<commit_before>const express = require('express');
const services = require('../../services');
const findConsumer = require('../utils/findConsumer');

module.exports = function () {
  const router = express.Router();

  router.get('/', function (req, res, next) {
    Promise.all([
      services.user.findAll(),
      services.application.findAll()
    ]).then(([{ users }, { apps }]) =>
      Promise.all(users.concat(apps).map(consumer => services.credential.getCredentials(consumer.id)))
    ).then(credentials => res.json({ credentials: credentials.reduce((acc, element) => acc.concat(element), []) }))
      .catch(err => res.status(500).send(err.message));
  });

  router.post('/', function (req, res, next) {
    findConsumer(req.body.consumerId)
      .then(consumer => {
        if (!consumer) {
          return res.status(422).send(`No consumer found with id: ${req.body.consumerId}`);
        }

        return services.credential
          .insertCredential(consumer.id, req.body.type, req.body.credential)
          .then((data) => res.json(data));
      })
      .catch(next);
  });

  router.get('/:type/:id', function (req, res, next) {
    const { id, type } = req.params;
    services.credential.getCredential(id, type)
      .then(cred => res.json(cred))
      .catch(next);
  });

  router.put('/:type/:id/status', function (req, res, next) {
    const { id, type } = req.params;
    const status = req.body.status;

    services.credential.getCredential(id, type)
      .then(cred => {
        if (!cred) {
          return res.status(404).send(`No credential found with id: ${id}`);
        } else {
          if (cred.isActive === status) {
            return res.json({ status: cred.isActive ? 'Active' : 'Inactive' });
          }
        }
        if (status === true) {
          return services.credential
            .activateCredential(id, type)
            .then(status => res.json({ status: 'Activated' }));
        } else {
          return services.credential
            .deactivateCredential(id, type)
            .then(status => res.json({ status: 'Deactivated' }));
        }
      }).catch(next);
  });

  router.put('/:type/:id/scopes/:scope', function (req, res, next) {
    const { id, type, scope } = req.params;

    services.credential
      .addScopesToCredential(id, type, [scope])
      .then(success => res.status(204).send())
      .catch(next);
  });

  router.delete('/:type/:id/scopes/:scope', function (req, res, next) {
    const { id, type, scope } = req.params;
    services.credential.removeScopesFromCredential(id, type, [scope])
      .then(success => res.status(204).send())
      .catch(next);
  });

  router.put('/:type/:id/scopes', function (req, res, next) {
    // set entire scopes array for cred
    const { id, type } = req.params;
    services.credential.setScopesForCredential(id, type, req.body.scopes)
      .then(success => res.status(204).send())
      .catch(next);
  });

  router.get('/:consumerId', function (req, res, next) {
    findConsumer(req.params.consumerId)
      .then((consumer) => {
        if (!consumer) {
          return res.status(404).json(new Error('Consumer Not Found: id:' + req.body.consumerId));
        }

        return services.credential
          .getCredentials(consumer.id)
          .then(credentials => res.json({ credentials }));
      }).catch(next);
  });

  return router;
};
<commit_msg>Return such property from the Admin API<commit_after>const express = require('express');
const services = require('../../services');
const findConsumer = require('../utils/findConsumer');

module.exports = function () {
  const router = express.Router();

  router.get('/', function (req, res, next) {
    Promise.all([
      services.user.findAll(),
      services.application.findAll()
    ]).then(([{ users }, { apps }]) =>
      Promise.all(
        users.concat(apps)
          .map(consumer => services.credential.getCredentials(consumer.id).then(credentials =>
            credentials.map(c => Object.assign({ consumerId: consumer.id }, c)))
          )
      )
    ).then(credentials => res.json({ credentials: credentials.reduce((acc, element) => acc.concat(element), []) }))
      .catch(err => res.status(500).send(err.message));
  });

  router.post('/', function (req, res, next) {
    findConsumer(req.body.consumerId)
      .then(consumer => {
        if (!consumer) {
          return res.status(422).send(`No consumer found with id: ${req.body.consumerId}`);
        }

        return services.credential
          .insertCredential(consumer.id, req.body.type, req.body.credential)
          .then((data) => res.json(data));
      })
      .catch(next);
  });

  router.get('/:type/:id', function (req, res, next) {
    const { id, type } = req.params;
    services.credential.getCredential(id, type)
      .then(cred => res.json(cred))
      .catch(next);
  });

  router.put('/:type/:id/status', function (req, res, next) {
    const { id, type } = req.params;
    const status = req.body.status;

    services.credential.getCredential(id, type)
      .then(cred => {
        if (!cred) {
          return res.status(404).send(`No credential found with id: ${id}`);
        } else {
          if (cred.isActive === status) {
            return res.json({ status: cred.isActive ? 'Active' : 'Inactive' });
          }
        }
        if (status === true) {
          return services.credential
            .activateCredential(id, type)
            .then(status => res.json({ status: 'Activated' }));
        } else {
          return services.credential
            .deactivateCredential(id, type)
            .then(status => res.json({ status: 'Deactivated' }));
        }
      }).catch(next);
  });

  router.put('/:type/:id/scopes/:scope', function (req, res, next) {
    const { id, type, scope } = req.params;

    services.credential
      .addScopesToCredential(id, type, [scope])
      .then(success => res.status(204).send())
      .catch(next);
  });

  router.delete('/:type/:id/scopes/:scope', function (req, res, next) {
    const { id, type, scope } = req.params;
    services.credential.removeScopesFromCredential(id, type, [scope])
      .then(success => res.status(204).send())
      .catch(next);
  });

  router.put('/:type/:id/scopes', function (req, res, next) {
    // set entire scopes array for cred
    const { id, type } = req.params;
    services.credential.setScopesForCredential(id, type, req.body.scopes)
      .then(success => res.status(204).send())
      .catch(next);
  });

  router.get('/:consumerId', function (req, res, next) {
    findConsumer(req.params.consumerId)
      .then((consumer) => {
        if (!consumer) {
          return res.status(404).json(new Error('Consumer Not Found: id:' + req.body.consumerId));
        }

        return services.credential
          .getCredentials(consumer.id)
          .then(credentials => res.json({ credentials }));
      }).catch(next);
  });

  return router;
};
<|endoftext|>


<commit_before>var gulp = require('gulp'),
  gulpLoadPlugins = require('gulp-load-plugins'),
  karma = require('karma').server;
var plugins = gulpLoadPlugins();

gulp.task('test', ['env:test', 'karma:unit', 'mochaTest']);

gulp.task('karma:unit', function (done) {
  karma.start({
    configFile: __dirname + '/../karma.conf.js',
    singleRun: true
  }, done);
});

gulp.task('env:test', function () {
  process.env.NODE_ENV = 'test';
});

gulp.task('loadTestSchema', function () {
  require('../server.js');
//  require('../node_modules/meanio/lib/util').preload('../packages/**/server', 'model');
});

gulp.task('mochaTest', ['loadTestSchema'], function () {
  return gulp.src('../packages/**/server/tests/**/*.js', {read: false})
    .pipe(plugins.mocha({
      reporter: 'spec'
    }));
});
<commit_msg>loading util in gulp test -  based on @lovebug357 PR<commit_after>var gulp = require('gulp'),
  gulpLoadPlugins = require('gulp-load-plugins'),
  karma = require('karma').server;
var plugins = gulpLoadPlugins();

gulp.task('test', ['env:test', 'karma:unit', 'mochaTest']);

gulp.task('karma:unit', function (done) {
  karma.start({
    configFile: __dirname + '/../karma.conf.js',
    singleRun: true
  }, done);
});

gulp.task('env:test', function () {
  process.env.NODE_ENV = 'test';
});

gulp.task('loadTestSchema', function () {
  require('../server.js');
  require('../node_modules/meanio/lib/core_modules/module/util').preload('../packages/**/server', 'model');
});

gulp.task('mochaTest', ['loadTestSchema'], function () {
  return gulp.src('../packages/**/server/tests/**/*.js', {read: false})
    .pipe(plugins.mocha({
      reporter: 'spec'
    }));
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var karma = require('karma').server;

/**
* Run test once and exit
*/
gulp.task('test', function (done) {
  karma.start({
    basePath: '',
    frameworks: ['jasmine', 'source-map-support'],
    files: [
      'node_modules/babel/node_modules/babel-core/browser-polyfill.js',
      'node_modules/angular/angular.js',
      'node_modules/angular-new-router/dist/router.es5.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'node_modules/angular-animate/angular-animate.js',
      'node_modules/angular-local-storage/dist/angular-local-storage.js',
      'node_modules/ramda/dist/ramda.js',
      'app/app.js',
      'app/config_local.js',
      'app/services/*/*.js',
      'app/utilities/*.js',
      'app/components/*/*.js',
      'app/scribe/*.js',
      'app/scribe/*/*.js'
    ],
    preprocessors: {
      'app/**/*.js': ['babel']
    },
    'babelPreprocessor': {
      options: {
        sourceMap: 'inline'
      },
      filename: function(file) {
        return file.originalPath.replace(/\.js$/, '.es5.js');
      },
      sourceFileName: function(file) {
        return file.originalPath;
      }
    },
    exclude: [
      // 'app/**/components/**/*.test.js'
    ],
    port: 8080,
    autoWatch: true,
    // browsers: ['PhantomJS'],
    browsers: ['Chrome'],
    singleRun: false
  }, function () {
    done ();
  });
});
<commit_msg>Fix tests<commit_after>var gulp = require('gulp');
var Server = require('karma').Server;

/**
* Run test once and exit
*/
gulp.task('test', function (done) {
  var config = {
    basePath: '',
    frameworks: ['jasmine', 'source-map-support'],
    files: [
      'node_modules/babel/node_modules/babel-core/browser-polyfill.js',
      'node_modules/angular/angular.js',
      'node_modules/angular-new-router/dist/router.es5.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'node_modules/angular-animate/angular-animate.js',
      'node_modules/angular-local-storage/dist/angular-local-storage.js',
      'node_modules/angular-tooltips/dist/angular-tooltips.min.js',
      'node_modules/ramda/dist/ramda.js',
      'app/app.js',
      'app/config_local.js',
      'app/services/*/*.js',
      'app/utilities/*.js',
      'app/components/*/*.js',
      'app/scribe/*.js',
      'app/scribe/*/*.js'
    ],
    preprocessors: {
      'app/**/*.js': ['babel']
    },
    'babelPreprocessor': {
      options: {
        sourceMap: 'inline'
      },
      filename: function(file) {
        return file.originalPath.replace(/\.js$/, '.es5.js');
      },
      sourceFileName: function(file) {
        return file.originalPath;
      }
    },
    exclude: [
      // 'app/**/components/**/*.test.js'
    ],
    port: 8080,
    autoWatch: true,
    browsers: ['PhantomJS'],
    // browsers: ['Chrome'],
    singleRun: false
  };
  var server = new Server(config, done);
  server.start();
});
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-manager
 *
 * iotagent-manager is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-manager is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-manager.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::daniel.moranjimenez@telefonica.com
 */

'use strict';

var errors = require('../errors'),
    configurationData = require('./configurationData');

function isInvalidParameter(param) {
    var value = parseInt(param);

    return isNaN(value) || value < 1;
}

function validateListParameters(req, res, next) {
    if (req.query.limit && isInvalidParameter(req.query.limit)) {
        next(new errors.WrongParameterValue(req.query.limit));
    } else if (req.query.offset && isInvalidParameter(req.query.offset)) {
        next(new errors.WrongParameterValue(req.query.offset));
    } else {
        next();
    }
}

function handleListRequest(req, res, next) {
    configurationData.list(
        req.headers['fiware-service'],
        req.headers['fiware-servicepath'],
        req.query.limit,
        req.query.offset,
        function(error, configurations) {
            if (error) {
                next(error);
            } else {
                res.status(200).json(configurations);
            }
        });
}

function loadContextRoutes(router) {
    router.get('/iot/services', [
        validateListParameters,
        handleListRequest
    ]);
}

exports.loadContextRoutes = loadContextRoutes;
<commit_msg>add req.query.protocol to hadleListRequest<commit_after>/*
 * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of iotagent-manager
 *
 * iotagent-manager is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * iotagent-manager is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with iotagent-manager.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::daniel.moranjimenez@telefonica.com
 */

'use strict';

var errors = require('../errors'),
    configurationData = require('./configurationData');

function isInvalidParameter(param) {
    var value = parseInt(param);

    return isNaN(value) || value < 1;
}

function validateListParameters(req, res, next) {
    if (req.query.limit && isInvalidParameter(req.query.limit)) {
        next(new errors.WrongParameterValue(req.query.limit));
    } else if (req.query.offset && isInvalidParameter(req.query.offset)) {
        next(new errors.WrongParameterValue(req.query.offset));
    } else {
        next();
    }
}

function handleListRequest(req, res, next) {
    configurationData.list(
        req.headers['fiware-service'],
        req.headers['fiware-servicepath'],
        req.query.protocol,
        req.query.limit,
        req.query.offset,
        function(error, configurations) {
            if (error) {
                next(error);
            } else {
                res.status(200).json(configurations);
            }
        });
}

function loadContextRoutes(router) {
    router.get('/iot/services', [
        validateListParameters,
        handleListRequest
    ]);
}

exports.loadContextRoutes = loadContextRoutes;
<|endoftext|>


<commit_before>var databaseAccessor = function(){
    var obj = {};

    obj.setDbName = function(name){
	obj.dbName = name;
    }
    obj.setKeyName = function(name){
	obj.keyName = name;
    }
    obj.setValueName = function(name){
	obj.valueName = name;
    }
    obj.setUser = function(user){
	obj.user = user;
    };
    obj.get = function(key){
	return new Promise(function(resolve,reject){
	    ddb.getItem(dbName,key, null, {}, function(err,res,cap){
		if(err !== null){
		    reject(err);
		}else{
		    resolve(res[valueName]);
		}
	    });
	});
    };
    obj.set = function(key,value){
	return new Promise(function(resolve,reject){
	    var obj = {};
	    obj[valueName]={};
	    obj[valueName].value = value;
	    ddb.updateItem(dbName,key, null, obj, {}, function(err,det,cap){
		if(err !== null){
		    reject(err);
		}else{
		    resolve(null);
		}
	    });
	});
    };
    obj.deleteEntry = function(key){};

    return obj;
};
module.exports = databaseAccessor;
<commit_msg>Fixed build errors<commit_after>var databaseAccessor = function(){
    var obj = {};

    obj.setDbName = function(name){
	obj.dbName = name;
    };
    obj.setKeyName = function(name){
	obj.keyName = name;
    };
    obj.setValueName = function(name){
	obj.valueName = name;
    };
    obj.setUser = function(user){
	obj.user = user;
    };
    obj.get = function(key){
	return new Promise(function(resolve,reject){
	    ddb.getItem(dbName,key, null, {}, function(err,res,cap){
		if(err !== null){
		    reject(err);
		}else{
		    resolve(res[valueName]);
		}
	    });
	});
    };
    obj.set = function(key,value){
	return new Promise(function(resolve,reject){
	    var obj = {};
	    obj[valueName]={};
	    obj[valueName].value = value;
	    ddb.updateItem(dbName,key, null, obj, {}, function(err,det,cap){
		if(err !== null){
		    reject(err);
		}else{
		    resolve(null);
		}
	    });
	});
    };
    obj.deleteEntry = function(key){};

    return obj;
};
module.exports = databaseAccessor;
<|endoftext|>


<commit_before>/*
 Copyright 2013 Daniel Wirtz <dcode@dcode.io>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/**
 * node-harmonize (c) 2013 Daniel Wirtz <dcode@dcode.io>
 * Released under the Apache License, Version 2.0
 * see: https://github.com/dcodeIO/node-harmonize for details
 */
var child_process = require("child_process");
var isIojs        = require("is-iojs");
var tty           = require('tty');

module.exports = function() {
    if (typeof Proxy == 'undefined') { // We take direct proxies as our marker
        var v = process.versions.node.split(".");

        if (!isIojs && v[0] == 0 && v[1] < 8) {
            throw("harmonize requires at least node v0.8");
        }

        // harmony flag is unnecessary in io and beginning with node v0.12
        if(isIojs || (!isIojs && v[0] == 0 && v[1] > 12)) {
            return;
        }

        var node = child_process.spawn(process.argv[0], ['--harmony', '--harmony-proxies'].concat(process.argv.slice(1)), { pty: tty.isatty(0) });
        node.stdout.pipe(process.stdout);
        node.stderr.pipe(process.stderr);
        node.on("close", function(code) {
            process.exit(code);
        });

        // Interrupt process flow in the parent
        process.once("uncaughtException", function(e) {});
        throw("harmony");
    }
};

// Usage: require("harmonize")();
<commit_msg>actually fix color output<commit_after>/*
 Copyright 2013 Daniel Wirtz <dcode@dcode.io>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/**
 * node-harmonize (c) 2013 Daniel Wirtz <dcode@dcode.io>
 * Released under the Apache License, Version 2.0
 * see: https://github.com/dcodeIO/node-harmonize for details
 */
var child_process = require("child_process");
var isIojs        = require("is-iojs");

module.exports = function() {
    if (typeof Proxy == 'undefined') { // We take direct proxies as our marker
        var v = process.versions.node.split(".");

        if (!isIojs && v[0] == 0 && v[1] < 8) {
            throw("harmonize requires at least node v0.8");
        }

        // harmony flag is unnecessary in io and beginning with node v0.12
        if(isIojs || (!isIojs && v[0] == 0 && v[1] > 12)) {
            return;
        }

        var node = child_process.spawn(process.argv[0], ['--harmony', '--harmony-proxies'].concat(process.argv.slice(1)), { stdio: 'inherit' });
        node.on("close", function(code) {
            process.exit(code);
        });

        // Interrupt process flow in the parent
        process.once("uncaughtException", function(e) {});
        throw("harmony");
    }
};

// Usage: require("harmonize")();
<|endoftext|>


<commit_before>"use strict";

const Channel = require("./Channel");
const Collection = require("../util/Collection");
const Member = require("./Member");
const Message = require("./Message");
const Permission = require("./Permission");
const Permissions = require("../Constants").Permissions;
const PermissionOverwrite = require("./PermissionOverwrite");

/**
* Represents a guild channel
* @extends Channel
* @prop {String} mention A string that mentions the channel
* @prop {Guild} guild The guild that owns the channel
* @prop {Collection<Message>} messages Collection of Messages in this channel
* @prop {String} lastMessageID The ID of the last message in this channel
* @prop {Number} lastPinTimestamp The timestamp of the last pinned message
* @prop {Collection<PermissionOverwrite>} permissionOverwrites Collection of PermissionOverwrites in this channel
* @prop {String} type The type of the channel, either 0 or 2
* @prop {String} name The name of the channel
* @prop {Number} position The position of the channel
* @prop {String?} topic The topic of the channel (text channels only)
* @prop {Number?} bitrate The bitrate of the channel (voice channels only)
* @prop {Number?} userLimit The max number of users that can join the channel (voice channels only)
* @prop {Collection<Member>?} voiceMembers Collection of Members in this channel (voice channels only)
*/
class GuildChannel extends Channel {
    constructor(data, guild) {
        super(data);
        this.guild = guild;
        if(this.type === 2) {
            this.voiceMembers = new Collection(Member);
        } else {
            this.messages = new Collection(Message, guild.shard.client.options.messageLimit);
            this.lastMessageID = data.last_message_id || null;
            this.lastPinTimestamp = data.last_pin_timestamp ? Date.parse(data.last_pin_timestamp) : null;
        }
        this.update(data);
    }

    update(data) {
        this.name = data.name !== undefined ? data.name : this.name;
        this.topic = data.topic !== undefined ? data.topic : this.topic;
        this.position = data.position !== undefined ? data.position : this.position;
        this.bitrate = data.bitrate !== undefined ? data.bitrate : this.bitrate;
        this.userLimit = data.user_limit !== undefined ? data.user_limit : this.userLimit;
        if(data.permission_overwrites) {
            this.permissionOverwrites = new Collection(PermissionOverwrite);
            data.permission_overwrites.forEach((overwrite) => {
                this.permissionOverwrites.add(overwrite);
            });
        }
    }

    /**
    * Get the channel-specific permissions of a member
    * @arg {String} memberID The ID of the member
    * @returns {Permission}
    */
    permissionsOf(memberID) {
        var member = this.guild.members.get(memberID);
        var permission = member.permission.allow;
        if(permission & Permissions.administrator) {
            return new Permission(Permissions.all);
        }
        var deny = 0;
        var allow = 0;
        for(var overwrite of this.permissionOverwrites) {
            if(overwrite[1].type === "role" && ~member.roles.indexOf(overwrite[1].id)) {
                deny |= overwrite[1].deny;
                allow |= overwrite[1].allow;
            }
        }
        permission = (permission & ~deny) | allow;
        var memberOverwrite = this.permissionOverwrites.get(memberID);
        if(memberOverwrite) {
            permission = (permission & ~memberOverwrite.deny) | memberOverwrite.allow;
        }
        return new Permission(permission);
    }

    get mention() {
        return `<#${this.id}>`;
    }

    /**
    * Edit the channel's properties
    * @arg {Object} options The properties to edit
    * @arg {String} [options.name] The name of the channel
    * @arg {String} [options.topic] The topic of the channel (guild text channels only)
    * @arg {Number} [options.bitrate] The bitrate of the channel (guild voice channels only)
    * @arg {Number} [options.userLimit] The channel user limit (guild voice channels only)
    * @returns {Promise<GuildChannel>}
    */
    edit(options) {
        return this.guild.shard.client.editChannel.call(this.guild.shard.client, this.id, options);
    }

    /**
    * Edit the channel's position. Note that channel position numbers are lowest on top and highest at the bottom.
    * @arg {Number} position The new position of the channel
    * @returns {Promise}
    */
    editPosition(position) {
        return this.guild.shard.client.editChannelPosition.call(this.guild.shard.client, this.id, position);
    }

    /**
    * Delete the channel
    * @returns {Promise}
    */
    delete() {
        return this.guild.shard.client.deleteChannel.call(this.guild.shard.client, this.id);
    }

    /**
    * Create a channel permission overwrite
    * @arg {String} overwriteID The ID of the overwritten user or role
    * @arg {Number} allow The permissions number for allowed permissions
    * @arg {Number} deny The permissions number for denied permissions
    * @arg {String} type The object type of the overwrite, either "member" or "role"
    * @returns {Promise<PermissionOverwrite>}
    */
    editPermission(overwriteID, allow, deny, type) {
        return this.guild.shard.client.editChannelPermission.call(this.guild.shard.client, this.id, overwriteID, allow, deny, type);
    }

    /**
    * Delete a channel permission overwrite
    * @arg {String} overwriteID The ID of the overwritten user or role
    * @returns {Promise}
    */
    deletePermission(overwriteID) {
        return this.guild.shard.client.deleteChannelPermission.call(this.guild.shard.client, this.id, overwriteID);
    }

    /**
    * Get all invites in the channel
    * @returns {Promise<Invite[]>}
    */
    getInvites() {
        return this.guild.shard.client.getChannelInvites.call(this.guild.shard.client, this.id);
    }

    /**
    * Create an invite for the channel
    * @arg {Object} [options] Invite generation options
    * @arg {Number} [options.maxAge] How long the invite should last in seconds
    * @arg {Number} [options.maxUses] How many uses the invite should last for
    * @arg {Boolean} [options.temporary] Whether the invite is temporary or not
    * @returns {Promise<Invite>}
    */
    createInvite(options) {
        return this.guild.shard.client.createChannelInvite.call(this.guild.shard.client, this.id, options);
    }

    /**
    * Get all the webhooks in the channel
    * @returns {Promise<Object[]>} Resolves with an array of webhook objects
    */
    getWebhooks() {
        return this.guild.shard.client.getChannelWebhooks.call(this.guild.shard.client, this.id);
    }

    /**
    * Create a channel webhook
    * @arg {Object} options Webhook options
    * @arg {String} options.name The default name
    * @arg {String} options.avatar The default avatar as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
    * @returns {Promise<Object>} Resolves with a webhook object
    */
    createWebhook(options) {
        return this.guild.shard.client.createChannelWebhook.call(this.guild.shard.client, this.id, options);
    }
}

module.exports = GuildChannel;
<commit_msg>Fix permissionOf calculations<commit_after>"use strict";

const Channel = require("./Channel");
const Collection = require("../util/Collection");
const Member = require("./Member");
const Message = require("./Message");
const Permission = require("./Permission");
const Permissions = require("../Constants").Permissions;
const PermissionOverwrite = require("./PermissionOverwrite");

/**
* Represents a guild channel
* @extends Channel
* @prop {String} mention A string that mentions the channel
* @prop {Guild} guild The guild that owns the channel
* @prop {Collection<Message>} messages Collection of Messages in this channel
* @prop {String} lastMessageID The ID of the last message in this channel
* @prop {Number} lastPinTimestamp The timestamp of the last pinned message
* @prop {Collection<PermissionOverwrite>} permissionOverwrites Collection of PermissionOverwrites in this channel
* @prop {String} type The type of the channel, either 0 or 2
* @prop {String} name The name of the channel
* @prop {Number} position The position of the channel
* @prop {String?} topic The topic of the channel (text channels only)
* @prop {Number?} bitrate The bitrate of the channel (voice channels only)
* @prop {Number?} userLimit The max number of users that can join the channel (voice channels only)
* @prop {Collection<Member>?} voiceMembers Collection of Members in this channel (voice channels only)
*/
class GuildChannel extends Channel {
    constructor(data, guild) {
        super(data);
        this.guild = guild;
        if(this.type === 2) {
            this.voiceMembers = new Collection(Member);
        } else {
            this.messages = new Collection(Message, guild.shard.client.options.messageLimit);
            this.lastMessageID = data.last_message_id || null;
            this.lastPinTimestamp = data.last_pin_timestamp ? Date.parse(data.last_pin_timestamp) : null;
        }
        this.update(data);
    }

    update(data) {
        this.name = data.name !== undefined ? data.name : this.name;
        this.topic = data.topic !== undefined ? data.topic : this.topic;
        this.position = data.position !== undefined ? data.position : this.position;
        this.bitrate = data.bitrate !== undefined ? data.bitrate : this.bitrate;
        this.userLimit = data.user_limit !== undefined ? data.user_limit : this.userLimit;
        if(data.permission_overwrites) {
            this.permissionOverwrites = new Collection(PermissionOverwrite);
            data.permission_overwrites.forEach((overwrite) => {
                this.permissionOverwrites.add(overwrite);
            });
        }
    }

    /**
    * Get the channel-specific permissions of a member
    * @arg {String} memberID The ID of the member
    * @returns {Permission}
    */
    permissionsOf(memberID) {
        var member = this.guild.members.get(memberID);
        var permission = member.permission.allow;
        if(permission & Permissions.administrator) {
            return new Permission(Permissions.all);
        }
        var deny = 0;
        var allow = 0;
        for(var overwrite of this.permissionOverwrites) {
            if(overwrite[1].type === "role" && (overwrite[1].id === this.guild.id || ~member.roles.indexOf(overwrite[1].id))) {
                deny |= overwrite[1].deny;
                allow |= overwrite[1].allow;
            }
        }
        permission = (permission & ~deny) | allow;
        var memberOverwrite = this.permissionOverwrites.get(memberID);
        if(memberOverwrite) {
            permission = (permission & ~memberOverwrite.deny) | memberOverwrite.allow;
        }
        return new Permission(permission);
    }

    get mention() {
        return `<#${this.id}>`;
    }

    /**
    * Edit the channel's properties
    * @arg {Object} options The properties to edit
    * @arg {String} [options.name] The name of the channel
    * @arg {String} [options.topic] The topic of the channel (guild text channels only)
    * @arg {Number} [options.bitrate] The bitrate of the channel (guild voice channels only)
    * @arg {Number} [options.userLimit] The channel user limit (guild voice channels only)
    * @returns {Promise<GuildChannel>}
    */
    edit(options) {
        return this.guild.shard.client.editChannel.call(this.guild.shard.client, this.id, options);
    }

    /**
    * Edit the channel's position. Note that channel position numbers are lowest on top and highest at the bottom.
    * @arg {Number} position The new position of the channel
    * @returns {Promise}
    */
    editPosition(position) {
        return this.guild.shard.client.editChannelPosition.call(this.guild.shard.client, this.id, position);
    }

    /**
    * Delete the channel
    * @returns {Promise}
    */
    delete() {
        return this.guild.shard.client.deleteChannel.call(this.guild.shard.client, this.id);
    }

    /**
    * Create a channel permission overwrite
    * @arg {String} overwriteID The ID of the overwritten user or role
    * @arg {Number} allow The permissions number for allowed permissions
    * @arg {Number} deny The permissions number for denied permissions
    * @arg {String} type The object type of the overwrite, either "member" or "role"
    * @returns {Promise<PermissionOverwrite>}
    */
    editPermission(overwriteID, allow, deny, type) {
        return this.guild.shard.client.editChannelPermission.call(this.guild.shard.client, this.id, overwriteID, allow, deny, type);
    }

    /**
    * Delete a channel permission overwrite
    * @arg {String} overwriteID The ID of the overwritten user or role
    * @returns {Promise}
    */
    deletePermission(overwriteID) {
        return this.guild.shard.client.deleteChannelPermission.call(this.guild.shard.client, this.id, overwriteID);
    }

    /**
    * Get all invites in the channel
    * @returns {Promise<Invite[]>}
    */
    getInvites() {
        return this.guild.shard.client.getChannelInvites.call(this.guild.shard.client, this.id);
    }

    /**
    * Create an invite for the channel
    * @arg {Object} [options] Invite generation options
    * @arg {Number} [options.maxAge] How long the invite should last in seconds
    * @arg {Number} [options.maxUses] How many uses the invite should last for
    * @arg {Boolean} [options.temporary] Whether the invite is temporary or not
    * @returns {Promise<Invite>}
    */
    createInvite(options) {
        return this.guild.shard.client.createChannelInvite.call(this.guild.shard.client, this.id, options);
    }

    /**
    * Get all the webhooks in the channel
    * @returns {Promise<Object[]>} Resolves with an array of webhook objects
    */
    getWebhooks() {
        return this.guild.shard.client.getChannelWebhooks.call(this.guild.shard.client, this.id);
    }

    /**
    * Create a channel webhook
    * @arg {Object} options Webhook options
    * @arg {String} options.name The default name
    * @arg {String} options.avatar The default avatar as a base64 data URI. Note: base64 strings alone are not base64 data URI strings
    * @returns {Promise<Object>} Resolves with a webhook object
    */
    createWebhook(options) {
        return this.guild.shard.client.createChannelWebhook.call(this.guild.shard.client, this.id, options);
    }
}

module.exports = GuildChannel;
<|endoftext|>


<commit_before>var exports = module.exports;

var task = require('../models/task');

exports.listTasks = function(req, res) {
    var id = req.query.id || "";

    var context = {
        siteTitle: "Taskit List Page",
        testMessage: "Test message woooo"
    };

    var template = __dirname + '/../views/list';
    res.render(template, context);

    // Just responding with a string, without any template:
    // res.status(200).send('Hello World');
}<commit_msg>Updated tasks<commit_after>var exports = module.exports;

var task = require('../models/task');

exports.listTasks = function(req, res) {
    var id = req.query.id || "";

    var context = {
        siteTitle: "Taskit List Page",
        testMessage: "Test message woooo"
    };

    var template = __dirname + '/../views/list';
    res.render(template, context);

    // Just responding with a string, without any template:
    // res.status(200).send('Hello World');
}

exports.showTask = function(req, res) {
    var id = req.query.id || "";

    if( id != "" ) {
        task.
    }
}<|endoftext|>


<commit_before>import {FileReader} from '../fileReader/FileReader.js';
import {Tokenizer} from './Tokenizer.js';
describe('tokenizer module', function() {
  let assert = require('assert');
  it('should be able to instantiate and pass the file reader', function() {
    let tokenizer = new Tokenizer(new FileReader);
    assert(true);
  });
  it('should have the name attribute', function() {
    let tokenizer = new Tokenizer(new FileReader);
    assert.equal('Tokenizer', tokenizer.name);
  });
  it('should fail if not passed an instance of FileReader to constructor', function() {
    assert.throws(function() {
      let failToken = new Tokenizer();
    }, Error);
  });
  it('should tokenize the function', function(done) {
    let tokenizer = new Tokenizer(new FileReader);
    let fileName = '/../../samples/simpleContent.js';
    let tokens = tokenizer.getTokens(__dirname + fileName);
    tokens
        .then(function(tokens) {
          assert.equal(10, tokens.length);
          assert.equal('function', tokens[1].value);
          done();
        })
        .catch(function(reason) {
          assert(false);
          done();
        });
  });
  it('should yield a token by value', function(done) {
    let tokenizer = new Tokenizer(new FileReader);
    let fileName = __dirname + '/../../samples/commonJSSample1.js';
    tokenizer.yieldTokens(fileName, 'require')
        .then(function(tokensArray) {
          assert.deepEqual([{
            'type': 'Identifier',
            'value': 'require'
          }], tokensArray);
          done();
        })
        .catch(function(reason) {
          console.log(reason);
          assert(false);
          done();
        });
  });
  it('should yield a token with offset', function(done) {
    let tokenizer = new Tokenizer(new FileReader);
    let fileName = __dirname + '/../../samples/commonJSSample1.js';
    tokenizer.yieldTokens(fileName, 'require', 2)
        .then(function(tokensArray) {
          assert.deepEqual([{
            'type': 'String',
            'value': '\'file\''
          }], tokensArray);
          done();
        })
        .catch(function(reason) {
          console.log(reason);
          assert(false);
          done();
        });
  });
  it('should yield all the tokens by value', function(done) {
    let tokenizer = new Tokenizer(new FileReader);
    let fileName = __dirname + '/../../samples/commonJSSample2.js';
    tokenizer.yieldTokens(fileName, 'require', 2)
        .then(function(tokensArray) {
          assert.equal(3, tokensArray.length);
          done();
        })
        .catch(function(reason) {
          console.log(reason);
          assert(false);
          done();
        });
  });
});
<commit_msg>Rewritten the test to use the fat arrow instead of the usual function declaration for consistency<commit_after>import {FileReader} from '../fileReader/FileReader.js';
import {Tokenizer} from './Tokenizer.js';
describe('tokenizer module', () => {
  let assert = require('assert');
  it('should be able to instantiate and pass the file reader', () => {
    let tokenizer = new Tokenizer(new FileReader);
    assert(true);
  });
  it('should have the name attribute', () => {
    let tokenizer = new Tokenizer(new FileReader);
    assert.equal('Tokenizer', tokenizer.name);
  });
  it('should fail if not passed an instance of FileReader to constructor', () => {
    assert.throws(() => {
      let failToken = new Tokenizer();
    }, Error);
  });
  it('should tokenize the function', (done) => {
    let tokenizer = new Tokenizer(new FileReader);
    let fileName = '/../../samples/simpleContent.js';
    let tokens = tokenizer.getTokens(__dirname + fileName);
    tokens
        .then((tokens) => {
          assert.equal(10, tokens.length);
          assert.equal('function', tokens[1].value);
          done();
        })
        .catch((reason) => {
          assert(false);
          done();
        });
  });
  it('should yield a token by value', (done) => {
    let tokenizer = new Tokenizer(new FileReader);
    let fileName = __dirname + '/../../samples/commonJSSample1.js';
    tokenizer.yieldTokens(fileName, 'require')
        .then((tokensArray) => {
          assert.deepEqual([{
            'type': 'Identifier',
            'value': 'require'
          }], tokensArray);
          done();
        })
        .catch((reason) => {
          console.log(reason);
          assert(false);
          done();
        });
  });
  it('should yield a token with offset', (done) => {
    let tokenizer = new Tokenizer(new FileReader);
    let fileName = __dirname + '/../../samples/commonJSSample1.js';
    tokenizer.yieldTokens(fileName, 'require', 2)
        .then((tokensArray) => {
          assert.deepEqual([{
            'type': 'String',
            'value': '\'file\''
          }], tokensArray);
          done();
        })
        .catch((reason) => {
          console.log(reason);
          assert(false);
          done();
        });
  });
  it('should yield all the tokens by value', (done) => {
    let tokenizer = new Tokenizer(new FileReader);
    let fileName = __dirname + '/../../samples/commonJSSample2.js';
    tokenizer.yieldTokens(fileName, 'require', 2)
        .then((tokensArray) => {
          assert.equal(3, tokensArray.length);
          done();
        })
        .catch((reason) => {
          console.log(reason);
          assert(false);
          done();
        });
  });
});
<|endoftext|>


<commit_before>var builder = require('node-xmpp'), ltx = require('ltx')

exports.parse = function(item, entity) {
    if (!entity == {}) return
    entity.body = item.getChild('body').getText()
}

exports.build = function(data, p) {
    if (p.payload) return
    p.payload = new builder.Element('body').t(data)
}
<commit_msg>Fix issue with plain message parsing<commit_after>var builder = require('node-xmpp')

exports.parse = function(item, entity) {
    if (0 != Object.keys(entity).length) return;
    entity.body = item.getChild('body').getText()
}

exports.build = function(data, p) {
    if (p.payload) return
    p.payload = new builder.Element('body').t(data)
}
<|endoftext|>


<commit_before>"use strict";

var Document = require("substance-document");

var PublicationInfo = function(node, doc) {
  Document.Node.call(this, node, doc);
};

PublicationInfo.type = {
  "id": "publication_info",
  "parent": "content",
  "properties": {
    "received_on": "string",
    "accepted_on": "string",
    "published_on": "string",
    "journal": "string",
    "provider": "string",
    "article_type": "string",
    "keywords": ["array", "string"],
    "research_organisms": ["array", "string"],
    "subjects": ["array", "string"],
    "links": ["array", "objects"],
    "doi": "string",
    "supplements": ["array", "object"], // deprecated
    "related_article": "string",
    "article_info": "paragraph"
  }
};

PublicationInfo.description = {
  "name": "PublicationInfo",
  "description": "PublicationInfo Node",
  "remarks": [
    "Summarizes the article's meta information. Meant to be customized by publishers"
  ],
  "properties": {
    "received_on": "Submission received",
    "accepted_on": "Paper accepted on",
    "published_on": "Paper published on",
    "journal": "The Journal",
    "provider": "Who is hosting this article",
    "article_type": "Research Article vs. Insight, vs. Correction etc.",
    "keywords": "Article's keywords",
    "research_organisms": "Research Organisms",
    "subjects": "Article Subjects",
    "doi": "Article DOI",
    "related_article": "DOI of related article if there is any"
  }
};

PublicationInfo.example = {
  "id": "publication_info",
  "received_on": "2012-06-20",
  "accepted_on": "2012-09-05",
  "published_on": "2012-11-13",
  "journal": "eLife",
  "provider": "eLife",
  "article_type": "Research Article",
  "keywords": [
    "innate immunity",
    "histones",
    "lipid droplet",
    "anti-bacterial"
  ],
  "research_organisms": [
    "B. subtilis",
    "D. melanogaster",
    "E. coli",
    "Mouse"
  ],
  "subjects": [
    "Immunology",
    "Microbiology and infectious disease"
  ],
  "doi": "http://dx.doi.org/10.7554/eLife.00003"
};

PublicationInfo.Prototype = function() {

  this.getArticleInfo = function() {
    return this.document.get("articleinfo");
  };

};

PublicationInfo.Prototype.prototype = Document.Node.prototype;
PublicationInfo.prototype = new PublicationInfo.Prototype();
PublicationInfo.prototype.constructor = PublicationInfo;

Document.Node.defineProperties(PublicationInfo);

module.exports = PublicationInfo;
<commit_msg>Fix regression.<commit_after>"use strict";

var Document = require("substance-document");

var PublicationInfo = function(node, doc) {
  Document.Node.call(this, node, doc);
};

PublicationInfo.type = {
  "id": "publication_info",
  "parent": "content",
  "properties": {
    "received_on": "string",
    "accepted_on": "string",
    "revised_on": "string",
    "published_on": "string",
    "journal": "string",
    "provider": "string",
    "article_type": "string",
    "keywords": ["array", "string"],
    "research_organisms": ["array", "string"],
    "subjects": ["array", "string"],
    "links": ["array", "objects"],
    "doi": "string",
    "related_article": "string",
    "article_info": "paragraph"
  }
};

PublicationInfo.description = {
  "name": "PublicationInfo",
  "description": "PublicationInfo Node",
  "remarks": [
    "Summarizes the article's meta information. Meant to be customized by publishers"
  ],
  "properties": {
    "received_on": "Submission received",
    "accepted_on": "Paper accepted on",
    "published_on": "Paper published on",
    "journal": "The Journal",
    "provider": "Who is hosting this article",
    "article_type": "Research Article vs. Insight, vs. Correction etc.",
    "keywords": "Article's keywords",
    "research_organisms": "Research Organisms",
    "subjects": "Article Subjects",
    "doi": "Article DOI",
    "related_article": "DOI of related article if there is any"
  }
};

PublicationInfo.example = {
  "id": "publication_info",
  "received_on": "2012-06-20",
  "accepted_on": "2012-09-05",
  "published_on": "2012-11-13",
  "journal": "eLife",
  "provider": "eLife",
  "article_type": "Research Article",
  "keywords": [
    "innate immunity",
    "histones",
    "lipid droplet",
    "anti-bacterial"
  ],
  "research_organisms": [
    "B. subtilis",
    "D. melanogaster",
    "E. coli",
    "Mouse"
  ],
  "subjects": [
    "Immunology",
    "Microbiology and infectious disease"
  ],
  "doi": "http://dx.doi.org/10.7554/eLife.00003"
};

PublicationInfo.Prototype = function() {

  this.getArticleInfo = function() {
    return this.document.get("articleinfo");
  };

};

PublicationInfo.Prototype.prototype = Document.Node.prototype;
PublicationInfo.prototype = new PublicationInfo.Prototype();
PublicationInfo.prototype.constructor = PublicationInfo;

Document.Node.defineProperties(PublicationInfo);

module.exports = PublicationInfo;
<|endoftext|>


<commit_before>/*
 * file.js: Transport for outputting to a local log file
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 *
 */

var events = require('events'),
    fs = require('fs'),
    path = require('path'),
    util = require('util'),
    colors = require('colors'),
    common = require('../common'),
    Transport = require('./transport').Transport,
    Stream = require('stream').Stream;

//
// ### function File (options)
// #### @options {Object} Options for this instance.
// Constructor function for the File transport object responsible
// for persisting log messages and metadata to one or more files.
//
var File = exports.File = function (options) {
  Transport.call(this, options);

  //
  // Helper function which throws an `Error` in the event
  // that any of the rest of the arguments is present in `options`.
  //
  function throwIf (target /*, illegal... */) {
    Array.prototype.slice.call(arguments, 1).forEach(function (name) {
      if (options[name]) {
        throw new Error('Cannot set ' + name + ' and ' + target + 'together');
      }
    });
  }

  if (options.filename || options.dirname) {
    throwIf('filename or dirname', 'stream');
    this._basename = this.filename = path.basename(options.filename) || 'winston.log';
    this.dirname   = options.dirname || path.dirname(options.filename);
    this.options   = options.options || { flags: 'a' };
  }
  else if (options.stream) {
    throwIf('stream', 'filename', 'maxsize');
    this._stream = options.stream;
  }
  else {
    throw new Error('Cannot log to file without filename or stream.');
  }

  this.json      = options.json !== false;
  this.colorize  = options.colorize  || false;
  this.maxsize   = options.maxsize   || null;
  this.maxFiles  = options.maxFiles  || null;
  this.timestamp = options.timestamp != null ? options.timestamp : true;

  //
  // Internal state variables representing the number
  // of files this instance has created and the current
  // size (in bytes) of the current logfile.
  //
  this._size     = 0;
  this._created  = 0;
  this._buffer   = [];
  this._draining = false;
};

//
// Inherit from `winston.Transport`.
//
util.inherits(File, Transport);

//
// Expose the name of this Transport on the prototype
//
File.prototype.name = 'file';

//
// ### function log (level, msg, [meta], callback)
// #### @level {string} Level at which to log the message.
// #### @msg {string} Message to log
// #### @meta {Object} **Optional** Additional metadata to attach
// #### @callback {function} Continuation to respond to when complete.
// Core logging method exposed to Winston. Metadata is optional.
//
File.prototype.log = function (level, msg, meta, callback) {
  if (this.silent) {
    return callback(null, true);
  }

  var self = this, output = common.log({
    level:     level,
    message:   msg,
    meta:      meta,
    json:      this.json,
    colorize:  this.colorize,
    timestamp: this.timestamp
  }) + '\n';

  this._size += output.length;

  if (!this.filename) {
    //
    // If there is no `filename` on this instance then it was configured
    // with a raw `WriteableStream` instance and we should not perform any
    // size restrictions.
    //
    this._stream.write(output);
    self._lazyDrain();
  }
  else {
    this.open(function (err) {
      if (err) {
        //
        // If there was an error enqueue the message
        //
        return self._buffer.push(output);
      }

      self._stream.write(output);
      self._lazyDrain();
    });
  }

  callback(null, true);
};

//
// ### function query (options)
// #### @options {Object} Set stream options
// #### @callback {function} Callback
// Query the transport.
//

File.prototype.query = function (options, callback) {
  var file = path.join(this.dirname, this.filename)
      options = this.normalizeQuery(options),
      buff = '',
      results = [],
      row = 0;

  var stream = fs.createReadStream(file, {
    encoding: 'utf8'
  });

  stream.on('error', function(err) {
    stream.destroy();
    if (!callback) return;
    return err.code !== 'ENOENT'
      ? callback(err)
      : callback(null, results);
  });

  stream.on('data', function(data) {
    var data = (buff + data).split(/\n+/),
        l = data.length - 1,
        i = 0;

    for (; i < l; i++) {
      if (!options.start || row >= options.start) {
        add(data[i]);
      }
      row++;
    }

    buff = data[l];
  });

  stream.on('close', function() {
    if (buff) add(buff, true);
    if (options.order === 'desc') {
      results = results.reverse();
    }
    if (callback) callback(null, results);
  });

  function add(buff, attempt) {
    try {
      var log = JSON.parse(buff);
      if (check(log)) push(log);
    } catch (e) {
      if (!attempt) {
        stream.emit('error', e);
      }
    }
  }

  function push(log) {
    if (options.rows && results.length >= options.rows) {
      return stream.destroy();
    }

    if (options.fields) {
      var obj = {};
      options.fields.forEach(function(key) {
        obj[key] = log[key];
      });
      log = obj;
    }

    results.push(log);
  }

  function check(log) {
    if (!log) return;

    if (typeof log !== 'object') return;

    var time = new Date(log.timestamp);
    if (time < options.from || time > options.until) {
      return;
    }

    return true;
  }
};

//
// ### function _tail (file, callback)
// #### @file {String} Name of file to tail
// #### @callback {function} Callback to execute on every line.
// `tail -f` a file.
//

File.prototype._tail = function tail(options, callback) {
  var stream = fs.createReadStream(options.file, { encoding: 'utf8' }),
      buff = '',
      destroy,
      row = 0;

  destroy = stream.destroy.bind(stream);
  stream.destroy = function() {};

  if (options.start === -1) {
    delete options.start;
  }

  if (options.start == null) {
    stream.once('end', bind);
  } else {
    bind();
  }

  function bind() {
    stream.on('data', function(data) {
      var data = (buff + data).split(/\n+/),
          l = data.length - 1,
          i = 0;

      for (; i < l; i++) {
        if (options.start == null || row > options.start) {
          stream.emit('line', data[i]);
        }
        row++;
      }

      buff = data[l];
    });

    stream.on('line', function(data) {
      if (callback) callback(data);
    });

    stream.on('error', function(err) {
      destroy();
    });

    stream.on('end', function() {
      if (buff) {
        line(buff);
        buff = '';
      }

      resume();
    });

    resume();
  }

  function resume() {
    setTimeout(function() {
      stream.resume();
    }, 1000);
  }

  return destroy;
};

//
// ### function stream (options)
// #### @options {Object} Set stream options
// Returns a log stream.
//

File.prototype.stream = function(options) {
  var file = path.join(this.dirname, this.filename),
      options = options || {},
      stream = new Stream;

  var tail = {
    file: file,
    start: options.start
  };

  stream.destroy = this._tail(tail, function(line) {
    try {
      stream.emit('data', line);
      line = JSON.parse(line);
      stream.emit('log', line);
    } catch (e) {
      stream.emit('error', e);
    }
  });

  return stream;
};

//
// ### function open (callback)
// #### @callback {function} Continuation to respond to when complete
// Checks to see if a new file needs to be created based on the `maxsize`
// (if any) and the current size of the file used.
//
File.prototype.open = function (callback) {
  if (this.opening) {
    //
    // If we are already attempting to open the next
    // available file then respond with a value indicating
    // that the message should be buffered.
    //
    return callback(true);
  }
  else if (!this._stream || (this.maxsize && this._size >= this.maxsize)) {
    //
    // If we dont have a stream or have exceeded our size, then create
    // the next stream and respond with a value indicating that
    // the message should be buffered.
    //
    callback(true);
    return this._createStream();
  }

  //
  // Otherwise we have a valid (and ready) stream.
  //
  callback();
};

//
// ### function close ()
// Closes the stream associated with this instance.
//
File.prototype.close = function () {
  var self = this;

  if (this._stream) {
    this._stream.end();
    this._stream.destroySoon();

    this._stream.once('drain', function () {
      self.emit('flush');
      self.emit('closed');
    });
  }
};

//
// ### function flush ()
// Flushes any buffered messages to the current `stream`
// used by this instance.
//
File.prototype.flush = function () {
  var self = this;

  //
  // Iterate over the `_buffer` of enqueued messaged
  // and then write them to the newly created stream.
  //
  this._buffer.forEach(function (str) {
    process.nextTick(function () {
      self._stream.write(str);
      self._size += str.length;
    });
  });

  //
  // Quickly truncate the `_buffer` once the write operations
  // have been started
  //
  self._buffer.length = 0;

  //
  // When the stream has drained we have flushed
  // our buffer.
  //
  self._stream.once('drain', function () {
    self.emit('flush');
    self.emit('logged');
  });
};

//
// ### @private function _createStream ()
// Attempts to open the next appropriate file for this instance
// based on the common state (such as `maxsize` and `_basename`).
//
File.prototype._createStream = function () {
  var self = this;
  this.opening = true;

  (function checkFile (target) {
    var fullname = path.join(self.dirname, target);

    //
    // Creates the `WriteStream` and then flushes any
    // buffered messages.
    //
    function createAndFlush (size) {
      if (self._stream) {
        self._stream.end();
        self._stream.destroySoon();
      }

      self._size = size;
      self.filename = target;
      self._stream = fs.createWriteStream(fullname, self.options);

      //
      // When the current stream has finished flushing
      // then we can be sure we have finished opening
      // and thus can emit the `open` event.
      //
      self.once('flush', function () {
        self.opening = false;
        self.emit('open', fullname);
      });

      //
      // Remark: It is possible that in the time it has taken to find the
      // next logfile to be written more data than `maxsize` has been buffered,
      // but for sensible limits (10s - 100s of MB) this seems unlikely in less
      // than one second.
      //
      self.flush();
    }

    fs.stat(fullname, function (err, stats) {
      if (err) {
        if (err.code !== 'ENOENT') {
          return self.emit('error', err);
        }

        return createAndFlush(0);
      }

      if (!stats || (self.maxsize && stats.size >= self.maxsize)) {
        //
        // If `stats.size` is greater than the `maxsize` for
        // this instance then try again
        //
        return checkFile(self._getFile(true));
      }

      createAndFlush(stats.size);
    });
  })(this._getFile());
};

//
// ### @private function _getFile ()
// Gets the next filename to use for this instance
// in the case that log filesizes are being capped.
//
File.prototype._getFile = function (inc) {
  var self = this,
      ext = path.extname(this._basename),
      basename = path.basename(this._basename, ext),
      remaining;

  if (inc) {
    //
    // Increment the number of files created or
    // checked by this instance.
    //
    // Check for maxFiles option and delete file
    if (this.maxFiles && (this._created >= (this.maxFiles - 1))) {
      remaining = this._created - (this.maxFiles - 1);
      if (remaining === 0) {
        fs.unlinkSync(path.join(this.dirname, basename + ext));
      }
      else {
        fs.unlinkSync(path.join(this.dirname, basename + remaining + ext));
      }
    }

    this._created += 1;
  }

  return this._created
    ? basename + this._created + ext
    : basename + ext;
};

//
// ### @private function _lazyDrain ()
// Lazily attempts to emit the `logged` event when `this.stream` has
// drained. This is really just a simple mutex that only works because
// Node.js is single-threaded.
//
File.prototype._lazyDrain = function () {
  var self = this;

  if (!this._draining && this._stream) {
    this._draining = true;

    this._stream.once('drain', function () {
      this._draining = false;
      self.emit('logged');
    });
  }
};
<commit_msg>[fix] fix non-existent function call in File transport.<commit_after>/*
 * file.js: Transport for outputting to a local log file
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 *
 */

var events = require('events'),
    fs = require('fs'),
    path = require('path'),
    util = require('util'),
    colors = require('colors'),
    common = require('../common'),
    Transport = require('./transport').Transport,
    Stream = require('stream').Stream;

//
// ### function File (options)
// #### @options {Object} Options for this instance.
// Constructor function for the File transport object responsible
// for persisting log messages and metadata to one or more files.
//
var File = exports.File = function (options) {
  Transport.call(this, options);

  //
  // Helper function which throws an `Error` in the event
  // that any of the rest of the arguments is present in `options`.
  //
  function throwIf (target /*, illegal... */) {
    Array.prototype.slice.call(arguments, 1).forEach(function (name) {
      if (options[name]) {
        throw new Error('Cannot set ' + name + ' and ' + target + 'together');
      }
    });
  }

  if (options.filename || options.dirname) {
    throwIf('filename or dirname', 'stream');
    this._basename = this.filename = path.basename(options.filename) || 'winston.log';
    this.dirname   = options.dirname || path.dirname(options.filename);
    this.options   = options.options || { flags: 'a' };
  }
  else if (options.stream) {
    throwIf('stream', 'filename', 'maxsize');
    this._stream = options.stream;
  }
  else {
    throw new Error('Cannot log to file without filename or stream.');
  }

  this.json      = options.json !== false;
  this.colorize  = options.colorize  || false;
  this.maxsize   = options.maxsize   || null;
  this.maxFiles  = options.maxFiles  || null;
  this.timestamp = options.timestamp != null ? options.timestamp : true;

  //
  // Internal state variables representing the number
  // of files this instance has created and the current
  // size (in bytes) of the current logfile.
  //
  this._size     = 0;
  this._created  = 0;
  this._buffer   = [];
  this._draining = false;
};

//
// Inherit from `winston.Transport`.
//
util.inherits(File, Transport);

//
// Expose the name of this Transport on the prototype
//
File.prototype.name = 'file';

//
// ### function log (level, msg, [meta], callback)
// #### @level {string} Level at which to log the message.
// #### @msg {string} Message to log
// #### @meta {Object} **Optional** Additional metadata to attach
// #### @callback {function} Continuation to respond to when complete.
// Core logging method exposed to Winston. Metadata is optional.
//
File.prototype.log = function (level, msg, meta, callback) {
  if (this.silent) {
    return callback(null, true);
  }

  var self = this, output = common.log({
    level:     level,
    message:   msg,
    meta:      meta,
    json:      this.json,
    colorize:  this.colorize,
    timestamp: this.timestamp
  }) + '\n';

  this._size += output.length;

  if (!this.filename) {
    //
    // If there is no `filename` on this instance then it was configured
    // with a raw `WriteableStream` instance and we should not perform any
    // size restrictions.
    //
    this._stream.write(output);
    self._lazyDrain();
  }
  else {
    this.open(function (err) {
      if (err) {
        //
        // If there was an error enqueue the message
        //
        return self._buffer.push(output);
      }

      self._stream.write(output);
      self._lazyDrain();
    });
  }

  callback(null, true);
};

//
// ### function query (options)
// #### @options {Object} Set stream options
// #### @callback {function} Callback
// Query the transport.
//

File.prototype.query = function (options, callback) {
  var file = path.join(this.dirname, this.filename)
      options = this.normalizeQuery(options),
      buff = '',
      results = [],
      row = 0;

  var stream = fs.createReadStream(file, {
    encoding: 'utf8'
  });

  stream.on('error', function(err) {
    stream.destroy();
    if (!callback) return;
    return err.code !== 'ENOENT'
      ? callback(err)
      : callback(null, results);
  });

  stream.on('data', function(data) {
    var data = (buff + data).split(/\n+/),
        l = data.length - 1,
        i = 0;

    for (; i < l; i++) {
      if (!options.start || row >= options.start) {
        add(data[i]);
      }
      row++;
    }

    buff = data[l];
  });

  stream.on('close', function() {
    if (buff) add(buff, true);
    if (options.order === 'desc') {
      results = results.reverse();
    }
    if (callback) callback(null, results);
  });

  function add(buff, attempt) {
    try {
      var log = JSON.parse(buff);
      if (check(log)) push(log);
    } catch (e) {
      if (!attempt) {
        stream.emit('error', e);
      }
    }
  }

  function push(log) {
    if (options.rows && results.length >= options.rows) {
      return stream.destroy();
    }

    if (options.fields) {
      var obj = {};
      options.fields.forEach(function(key) {
        obj[key] = log[key];
      });
      log = obj;
    }

    results.push(log);
  }

  function check(log) {
    if (!log) return;

    if (typeof log !== 'object') return;

    var time = new Date(log.timestamp);
    if (time < options.from || time > options.until) {
      return;
    }

    return true;
  }
};

//
// ### function _tail (file, callback)
// #### @file {String} Name of file to tail
// #### @callback {function} Callback to execute on every line.
// `tail -f` a file.
//

File.prototype._tail = function tail(options, callback) {
  var stream = fs.createReadStream(options.file, { encoding: 'utf8' }),
      buff = '',
      destroy,
      row = 0;

  destroy = stream.destroy.bind(stream);
  stream.destroy = function() {};

  if (options.start === -1) {
    delete options.start;
  }

  if (options.start == null) {
    stream.once('end', bind);
  } else {
    bind();
  }

  function bind() {
    stream.on('data', function(data) {
      var data = (buff + data).split(/\n+/),
          l = data.length - 1,
          i = 0;

      for (; i < l; i++) {
        if (options.start == null || row > options.start) {
          stream.emit('line', data[i]);
        }
        row++;
      }

      buff = data[l];
    });

    stream.on('line', function(data) {
      if (callback) callback(data);
    });

    stream.on('error', function(err) {
      destroy();
    });

    stream.on('end', function() {
      if (buff) {
        stream.emit('line', buff);
        buff = '';
      }

      resume();
    });

    resume();
  }

  function resume() {
    setTimeout(function() {
      stream.resume();
    }, 1000);
  }

  return destroy;
};

//
// ### function stream (options)
// #### @options {Object} Set stream options
// Returns a log stream.
//

File.prototype.stream = function(options) {
  var file = path.join(this.dirname, this.filename),
      options = options || {},
      stream = new Stream;

  var tail = {
    file: file,
    start: options.start
  };

  stream.destroy = this._tail(tail, function(line) {
    try {
      stream.emit('data', line);
      line = JSON.parse(line);
      stream.emit('log', line);
    } catch (e) {
      stream.emit('error', e);
    }
  });

  return stream;
};

//
// ### function open (callback)
// #### @callback {function} Continuation to respond to when complete
// Checks to see if a new file needs to be created based on the `maxsize`
// (if any) and the current size of the file used.
//
File.prototype.open = function (callback) {
  if (this.opening) {
    //
    // If we are already attempting to open the next
    // available file then respond with a value indicating
    // that the message should be buffered.
    //
    return callback(true);
  }
  else if (!this._stream || (this.maxsize && this._size >= this.maxsize)) {
    //
    // If we dont have a stream or have exceeded our size, then create
    // the next stream and respond with a value indicating that
    // the message should be buffered.
    //
    callback(true);
    return this._createStream();
  }

  //
  // Otherwise we have a valid (and ready) stream.
  //
  callback();
};

//
// ### function close ()
// Closes the stream associated with this instance.
//
File.prototype.close = function () {
  var self = this;

  if (this._stream) {
    this._stream.end();
    this._stream.destroySoon();

    this._stream.once('drain', function () {
      self.emit('flush');
      self.emit('closed');
    });
  }
};

//
// ### function flush ()
// Flushes any buffered messages to the current `stream`
// used by this instance.
//
File.prototype.flush = function () {
  var self = this;

  //
  // Iterate over the `_buffer` of enqueued messaged
  // and then write them to the newly created stream.
  //
  this._buffer.forEach(function (str) {
    process.nextTick(function () {
      self._stream.write(str);
      self._size += str.length;
    });
  });

  //
  // Quickly truncate the `_buffer` once the write operations
  // have been started
  //
  self._buffer.length = 0;

  //
  // When the stream has drained we have flushed
  // our buffer.
  //
  self._stream.once('drain', function () {
    self.emit('flush');
    self.emit('logged');
  });
};

//
// ### @private function _createStream ()
// Attempts to open the next appropriate file for this instance
// based on the common state (such as `maxsize` and `_basename`).
//
File.prototype._createStream = function () {
  var self = this;
  this.opening = true;

  (function checkFile (target) {
    var fullname = path.join(self.dirname, target);

    //
    // Creates the `WriteStream` and then flushes any
    // buffered messages.
    //
    function createAndFlush (size) {
      if (self._stream) {
        self._stream.end();
        self._stream.destroySoon();
      }

      self._size = size;
      self.filename = target;
      self._stream = fs.createWriteStream(fullname, self.options);

      //
      // When the current stream has finished flushing
      // then we can be sure we have finished opening
      // and thus can emit the `open` event.
      //
      self.once('flush', function () {
        self.opening = false;
        self.emit('open', fullname);
      });

      //
      // Remark: It is possible that in the time it has taken to find the
      // next logfile to be written more data than `maxsize` has been buffered,
      // but for sensible limits (10s - 100s of MB) this seems unlikely in less
      // than one second.
      //
      self.flush();
    }

    fs.stat(fullname, function (err, stats) {
      if (err) {
        if (err.code !== 'ENOENT') {
          return self.emit('error', err);
        }

        return createAndFlush(0);
      }

      if (!stats || (self.maxsize && stats.size >= self.maxsize)) {
        //
        // If `stats.size` is greater than the `maxsize` for
        // this instance then try again
        //
        return checkFile(self._getFile(true));
      }

      createAndFlush(stats.size);
    });
  })(this._getFile());
};

//
// ### @private function _getFile ()
// Gets the next filename to use for this instance
// in the case that log filesizes are being capped.
//
File.prototype._getFile = function (inc) {
  var self = this,
      ext = path.extname(this._basename),
      basename = path.basename(this._basename, ext),
      remaining;

  if (inc) {
    //
    // Increment the number of files created or
    // checked by this instance.
    //
    // Check for maxFiles option and delete file
    if (this.maxFiles && (this._created >= (this.maxFiles - 1))) {
      remaining = this._created - (this.maxFiles - 1);
      if (remaining === 0) {
        fs.unlinkSync(path.join(this.dirname, basename + ext));
      }
      else {
        fs.unlinkSync(path.join(this.dirname, basename + remaining + ext));
      }
    }

    this._created += 1;
  }

  return this._created
    ? basename + this._created + ext
    : basename + ext;
};

//
// ### @private function _lazyDrain ()
// Lazily attempts to emit the `logged` event when `this.stream` has
// drained. This is really just a simple mutex that only works because
// Node.js is single-threaded.
//
File.prototype._lazyDrain = function () {
  var self = this;

  if (!this._draining && this._stream) {
    this._draining = true;

    this._stream.once('drain', function () {
      this._draining = false;
      self.emit('logged');
    });
  }
};
<|endoftext|>


<commit_before>// TODO: the build process implicitly will wrap this in a define() call
// with a closure of its own; do you need this extra closure?

var LocalFileSystem = require('cordova/plugin/LocalFileSystem');

(function (win, doc) {

var docDomain = null;
try {
    docDomain = doc.domain;
} catch (err) {
    //console.log("caught exception trying to access document.domain");
}

if (!docDomain || docDomain.length === 0) {

    var aliasXHR = win.XMLHttpRequest;

    win.XMLHttpRequest = function () { };
    win.XMLHttpRequest.noConflict = aliasXHR;
    win.XMLHttpRequest.UNSENT = 0;
    win.XMLHttpRequest.OPENED = 1;
    win.XMLHttpRequest.HEADERS_RECEIVED = 2;
    win.XMLHttpRequest.LOADING = 3;
    win.XMLHttpRequest.DONE = 4;

    win.XMLHttpRequest.prototype = {
        UNSENT: 0,
        OPENED: 1,
        HEADERS_RECEIVED: 2,
        LOADING: 3,
        DONE: 4,

        isAsync: false,
        onreadystatechange: null,
        readyState: 0,
        _url: "",
        timeout: 0,
        withCredentials: false,
        _requestHeaders: null,
        open: function (reqType, uri, isAsync, user, password) {

            if (uri && uri.indexOf("http") === 0) {
                if (!this.wrappedXHR) {
                    this.wrappedXHR = new aliasXHR();
                    var self = this;

                    // timeout
                    if (this.timeout > 0) {
                        this.wrappedXHR.timeout = this.timeout;
                    }
                    Object.defineProperty(this, "timeout", {
                        set: function (val) {
                            this.wrappedXHR.timeout = val;
                        },
                        get: function () {
                            return this.wrappedXHR.timeout;
                        }
                    });

                    if (this.withCredentials) {
                        this.wrappedXHR.withCredentials = this.withCredentials;
                    }
                    Object.defineProperty(this, "withCredentials", {
                        set: function (val) {
                            this.wrappedXHR.withCredentials = val;
                        },
                        get: function () {
                            return this.wrappedXHR.withCredentials;
                        }
                    });

                    Object.defineProperty(this, "status", { get: function () {
                        return this.wrappedXHR.status;
                    }
                    });
                    Object.defineProperty(this, "responseText", { get: function () {
                        return this.wrappedXHR.responseText;
                    }
                    });
                    Object.defineProperty(this, "statusText", { get: function () {
                        return this.wrappedXHR.statusText;
                    }
                    });

                    Object.defineProperty(this, "responseXML", { get: function () {
                        return this.wrappedXHR.responseXML;
                    }
                    });

                    this.getResponseHeader = function (header) {
                        return this.wrappedXHR.getResponseHeader(header);
                    };
                    this.getAllResponseHeaders = function () {
                        return this.wrappedXHR.getAllResponseHeaders();
                    };

                    this.wrappedXHR.onreadystatechange = function () {
                        self.changeReadyState(self.wrappedXHR.readyState);
                    };
                }
                return this.wrappedXHR.open(reqType, uri, isAsync, user, password);
            }
            else {
                console.log("url is " + uri);
                // x-wmapp1://app/www/page2.html
                // need to work some magic on the actual url/filepath
                var newUrl = uri;
                if (newUrl.indexOf(":/") > -1) {
                    newUrl = newUrl.split(":/")[1];
                }
                // prefix relative urls to our physical root
                if(newUrl.indexOf("app/www/") < 0)
                {
                    newUrl = "app/www/" + newUrl;
                }

                if (newUrl.lastIndexOf("/") === newUrl.length - 1) {
                    newUrl += "index.html"; // default page is index.html, when call is to a dir/ ( why not ...? )
                }
                this._url = newUrl;
            }
        },
        statusText: "",
        changeReadyState: function (newState) {
            this.readyState = newState;
            if (this.onreadystatechange) {
                this.onreadystatechange();
            }
        },
        setRequestHeader: function (header, value) {
            if (this.wrappedXHR) {
                this.wrappedXHR.setRequestHeader(header, value);
            }
        },
        getResponseHeader: function (header) {
            return this.wrappedXHR ? this.wrappedXHR.getResponseHeader(header) : "";
        },
        getAllResponseHeaders: function () {
            return this.wrappedXHR ? this.wrappedXHR.getAllResponseHeaders() : "";
        },
        responseText: "",
        responseXML: "",
        onResult: function (res) {
            this.status = 200;
            console.log("onResult XHR :: " + res);
            console.log("typeof = " + typeof res);
            if(typeof res == "object")
            {   // callback result handler may have already parsed this from a string-> a JSON object,
                // if so, we need to restore it's stringyness, as handlers are expecting string data.
                // especially if used with jQ -> $.getJSON
                console.log("re-stringing the guitar");
                res = JSON.stringify(res);
            }
            this.responseText = res;
            this.responseXML = res;
            this.changeReadyState(this.DONE);
        },
        onError: function (err) {
            this.status = 404;
            this.changeReadyState(this.DONE);
        },

        abort: function () {
            if (this.wrappedXHR) {
                return this.wrappedXHR.abort();
            }
        },

        send: function (data) {
            if (this.wrappedXHR) {
                return this.wrappedXHR.send(data);
            }
            else {
                this.changeReadyState(this.OPENED);

                var alias = this;

                var fail = function fail(evt) {
                    alias.onError(evt.code);
                };

                var gotFile = function gotFile(file) {
                    var reader = new FileReader();
                    reader.onloadend = function (evt) {
                        alias.onResult.apply(alias,[evt.target.result]);
                    };
                    reader.readAsText(file);
                };

                var gotEntry = function gotEntry(entry) {
                    entry.file(gotFile, fail);
                };

                var gotFS = function gotFS(fs) {
                    fs.root.getFile(alias._url, null, gotEntry, fail);
                };

                window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);

            }
        },
        status: 404
    };
} // if doc domain

// end closure wrap
})(window, document);

module.exports = null;<commit_msg>removed leftover console.logs<commit_after>// TODO: the build process implicitly will wrap this in a define() call
// with a closure of its own; do you need this extra closure?

var LocalFileSystem = require('cordova/plugin/LocalFileSystem');

(function (win, doc) {

var docDomain = null;
try {
    docDomain = doc.domain;
} catch (err) {
    //console.log("caught exception trying to access document.domain");
}

if (!docDomain || docDomain.length === 0) {

    var aliasXHR = win.XMLHttpRequest;

    win.XMLHttpRequest = function () { };
    win.XMLHttpRequest.noConflict = aliasXHR;
    win.XMLHttpRequest.UNSENT = 0;
    win.XMLHttpRequest.OPENED = 1;
    win.XMLHttpRequest.HEADERS_RECEIVED = 2;
    win.XMLHttpRequest.LOADING = 3;
    win.XMLHttpRequest.DONE = 4;

    win.XMLHttpRequest.prototype = {
        UNSENT: 0,
        OPENED: 1,
        HEADERS_RECEIVED: 2,
        LOADING: 3,
        DONE: 4,

        isAsync: false,
        onreadystatechange: null,
        readyState: 0,
        _url: "",
        timeout: 0,
        withCredentials: false,
        _requestHeaders: null,
        open: function (reqType, uri, isAsync, user, password) {

            if (uri && uri.indexOf("http") === 0) {
                if (!this.wrappedXHR) {
                    this.wrappedXHR = new aliasXHR();
                    var self = this;

                    // timeout
                    if (this.timeout > 0) {
                        this.wrappedXHR.timeout = this.timeout;
                    }
                    Object.defineProperty(this, "timeout", {
                        set: function (val) {
                            this.wrappedXHR.timeout = val;
                        },
                        get: function () {
                            return this.wrappedXHR.timeout;
                        }
                    });

                    if (this.withCredentials) {
                        this.wrappedXHR.withCredentials = this.withCredentials;
                    }
                    Object.defineProperty(this, "withCredentials", {
                        set: function (val) {
                            this.wrappedXHR.withCredentials = val;
                        },
                        get: function () {
                            return this.wrappedXHR.withCredentials;
                        }
                    });

                    Object.defineProperty(this, "status", { get: function () {
                        return this.wrappedXHR.status;
                    }
                    });
                    Object.defineProperty(this, "responseText", { get: function () {
                        return this.wrappedXHR.responseText;
                    }
                    });
                    Object.defineProperty(this, "statusText", { get: function () {
                        return this.wrappedXHR.statusText;
                    }
                    });

                    Object.defineProperty(this, "responseXML", { get: function () {
                        return this.wrappedXHR.responseXML;
                    }
                    });

                    this.getResponseHeader = function (header) {
                        return this.wrappedXHR.getResponseHeader(header);
                    };
                    this.getAllResponseHeaders = function () {
                        return this.wrappedXHR.getAllResponseHeaders();
                    };

                    this.wrappedXHR.onreadystatechange = function () {
                        self.changeReadyState(self.wrappedXHR.readyState);
                    };
                }
                return this.wrappedXHR.open(reqType, uri, isAsync, user, password);
            }
            else {
                // x-wmapp1://app/www/page2.html
                // need to work some magic on the actual url/filepath
                var newUrl = uri;
                if (newUrl.indexOf(":/") > -1) {
                    newUrl = newUrl.split(":/")[1];
                }
                // prefix relative urls to our physical root
                if(newUrl.indexOf("app/www/") < 0)
                {
                    newUrl = "app/www/" + newUrl;
                }

                if (newUrl.lastIndexOf("/") === newUrl.length - 1) {
                    newUrl += "index.html"; // default page is index.html, when call is to a dir/ ( why not ...? )
                }
                this._url = newUrl;
            }
        },
        statusText: "",
        changeReadyState: function (newState) {
            this.readyState = newState;
            if (this.onreadystatechange) {
                this.onreadystatechange();
            }
        },
        setRequestHeader: function (header, value) {
            if (this.wrappedXHR) {
                this.wrappedXHR.setRequestHeader(header, value);
            }
        },
        getResponseHeader: function (header) {
            return this.wrappedXHR ? this.wrappedXHR.getResponseHeader(header) : "";
        },
        getAllResponseHeaders: function () {
            return this.wrappedXHR ? this.wrappedXHR.getAllResponseHeaders() : "";
        },
        responseText: "",
        responseXML: "",
        onResult: function (res) {
            this.status = 200;
            if(typeof res == "object")
            {   // callback result handler may have already parsed this from a string-> a JSON object,
                // if so, we need to restore it's stringyness, as handlers are expecting string data.
                // especially if used with jQ -> $.getJSON
                res = JSON.stringify(res);
            }
            this.responseText = res;
            this.responseXML = res;
            this.changeReadyState(this.DONE);
        },
        onError: function (err) {
            this.status = 404;
            this.changeReadyState(this.DONE);
        },

        abort: function () {
            if (this.wrappedXHR) {
                return this.wrappedXHR.abort();
            }
        },

        send: function (data) {
            if (this.wrappedXHR) {
                return this.wrappedXHR.send(data);
            }
            else {
                this.changeReadyState(this.OPENED);

                var alias = this;

                var fail = function fail(evt) {
                    alias.onError(evt.code);
                };

                var gotFile = function gotFile(file) {
                    var reader = new FileReader();
                    reader.onloadend = function (evt) {
                        alias.onResult.apply(alias,[evt.target.result]);
                    };
                    reader.readAsText(file);
                };

                var gotEntry = function gotEntry(entry) {
                    entry.file(gotFile, fail);
                };

                var gotFS = function gotFS(fs) {
                    fs.root.getFile(alias._url, null, gotEntry, fail);
                };

                window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);

            }
        },
        status: 404
    };
} // if doc domain

// end closure wrap
})(window, document);

module.exports = null;<|endoftext|>