<commit_before>// Requires
var async  = require('async'),
	fs     = require('fs'),
	path   = require('path'),
	minify = require('node-json-minify'),
	Server = require('./server');

// Constructor
function Deployer (stage, logger) {

	this.logger = logger;

	// load up the configuration for this deployment
	if (fs.existsSync('reploy.json')) {
		var contents = fs.readFileSync('reploy.json', { encoding: 'utf8' });
		this.deployment  = JSON.parse(minify(contents));
	} else {
		this.logger.error('reploy.json file not found!');
		process.exit(1);
	}

	if (!(stage in this.deployment)) {
		this.logger.error(stage + ' does not exist in reploy.json file!');
		process.exit(1);
	}

	this.config = {
		path: this._load('path', stage),
		repo: this._load('repository'),
		branch: this._load('branch', stage),
		keepReleases: this._load('keepReleases'),
		newReleasePath: '',
		releasePath: path.join(this._load('path', stage), 'releases'),
		currentPath: path.join(this._load('path', stage), 'current'),
		sharedPath: path.join(this._load('path', stage), 'shared'),
		repoPath: path.join(this._load('path', stage), 'repo'),
		deployLog: path.join(this._load('path', stage), 'deployments.log'),
		newRelease: '',
		newRevision: '',
		linkedFiles: this._load('linkedFiles'),
		linkedDirs: this._load('linkedDirs'),
		revisionExists: false,
		repoExists: false
	};

	// initialize a server for ssh connection
	this.server = new Server({
		host: this._load('host', stage),
		username: this._load('username', stage),
		agent: process.env.SSH_AUTH_SOCK,
		agentFwd: true
	}, logger);

};

// Load in a deployment setting
Deployer.prototype._load = function (key, stage) {

	if (stage) {
		return this.deployment[stage][key];
	} else {
		return this.deployment[key];
	}

};

// Make the actual deployment
Deployer.prototype.deploy = function () {

	var that = this;

	this.server.open(function (err) {
		if (err) {
			that.logger.error('Could not connect to ' + that.server.host + '! ' + err);

		} else {
			that.logger.log('Connected to ' + that.server.host);

			async.series([
				that._preDeploy.bind(that),
				that._fetchNewReleasePath.bind(that),
				that._deployRepo.bind(that),
				that._deployRelease.bind(that),
				that._setNewRevision.bind(that),
				that._symlinkDirs.bind(that),
				that._symlinkFiles.bind(that),
				that._symlinkCurrent.bind(that),
				that._cleanup.bind(that),
				that._writeRevisionLog.bind(that),

			], function (err) {
				if (err) {
					that.server.close(function () {
						that.logger.error('Deployment failed with: ' + err);
					});
				} else {
					that.server.close(function () {
						that.logger.success('Deployment complete!');
					});
				}
			});
		}
	});

};

// Set up everything before deploying a new release
Deployer.prototype._preDeploy = function (cb) {

	var that = this;

	this.server
		// make sure we can access git
		.queue(['git',
				'ls-remote',
				'--heads',
				this.config.repo
			])
		// make sure the needed directories are there
		.queue(['mkdir',
				'-p',
				this.config.releasePath,
				this.config.sharedPath
			]);

	// make sure that symlinked directories exist
	if (this.config.linkedDirs.length > 0) {
		var dirs = [];
		this.config.linkedDirs.forEach(function (dir) {
			dirs.push(path.join(that.config.sharedPath, dir));
		});

		this.server.queue(['mkdir', '-p', dirs.join(' ')]);
	}

	// make sure the directories of files to be symlinked exist
	if (this.config.linkedFiles.length > 0) {
		var dirs = [];
		this.config.linkedFiles.forEach(function (file) {
			dirs.push(path.dirname(path.join(that.config.sharedPath, file)));
		});

		this.server.queue(['mkdir', '-p', dirs.join(' ')]);
	}

	this.server
		.execQueue(function (err) {
			if (err) cb(err);
			else {
				async.series([
					// check that each of the symlinked files exist on the server
					// TODO make this a warning until user created tasks
					// are in there.
					function (callback) {
						if (that.config.linkedFiles.length > 0) {
							var files = that.config.linkedFiles.slice();

							async.whilst(
								function () { return files.length > 0 },

								function (callback) {
									var file = files.shift();

									that.server.check('file', path.join(that.config.sharedPath, file), function (response, err) {
										if (err) callback(err);
										else {
											if (response == "1") callback();
											else {
                                                //callback(path.join(that.config.sharedPath, file) + ' does not exist!');
                                            // if it doesn't exist, just create the file
                                                that.server
                                                    .queue(['touch', path.join(that.config.sharedPath, file)])
                                                    .execQueue(function (err) {
                                                        if (err) callback(err);
                                                        else callback();
                                                    });
                                            }
										}
									});
								},

								function (err) {
									if (err) callback(err);
									else callback();
								});

						} else {
							callback();
						}
					},

					// check if there's already a release deployed
					function (callback) {
						that.server.check('file', path.join(that.config.currentPath, 'REVISION'), function (response, err) {
							if (err) callback(err);
							else {
								if (response == "1")
									that.config.revisionExists = true;

								callback();
							}
						});
					},

					// check if the repo mirror has already been cloned
					function (callback) {
						that.server.check('file', path.join(that.config.repoPath, 'HEAD'), function (response, err) {
							if (err) callback(err);
							else {
								if (response == "1")
									that.config.repoExists = true;

								callback();
							}
						});
					}
				], function (err) {
					if (err) cb(err);
					else {
						that.logger.log('Check stage complete');
						cb();
					}
				});
			}
		});

};

// Fetch the new release path
Deployer.prototype._fetchNewReleasePath = function (cb) {

	this.server.capture('date +%Y%m%d%H%M%S', function (timestamp, err) {
		if (err) cb(err);
		else {
			this.config.newRelease = timestamp;
			this.config.newReleasePath = path.join(this.config.releasePath, this.config.newRelease);
			this.logger.verbose('New Release Path: ' + this.config.newReleasePath);
			cb();
		}
	}.bind(this));

};

// Clone, if needed, and update the repo on the server
Deployer.prototype._deployRepo = function (cb) {

	var that = this;

	// if the repo isn't already there, go ahead and clone it
	if (! this.config.repoExists)
		this.server.queue(['git', 'clone', '--mirror', '-q', this.config.repo, this.config.repoPath])

	this.server
		.queue(['git',
				'remote',
				'update'
			], this.config.repoPath)
		.execQueue(function (err) {

			if (err) cb(err);
			else {
				that.logger.log('Repo updated');
				cb();
			}
		});

};

// Create and clone the new release
Deployer.prototype._deployRelease = function (cb) {

	var that = this;

	this.server
		.queue(['mkdir',
				'-p',
				this.config.newReleasePath
			])
		.queue(['git',
				'archive',
				this.config.branch,
				'| tar',
				'-x -f - -C',
				this.config.newReleasePath
			], this.config.repoPath)
		.execQueue(function (err) {
			if (err) cb(err);
			else {
				that.logger.log('New release created');
				cb();
			}
		});

};

// Get the current git revision
Deployer.prototype._setNewRevision = function (cb) {

	var that = this;

	async.series([
			// fetch the new revision number
			function (callback) {
				that.server
					.capture(['git',
							'rev-parse',
							'--short',
							that.config.branch
						], that.config.repoPath,
						function (revision, err) {
							if (err) callback(err);
							else {
								that.config.newRevision = revision;
								callback();
							}
						});
			},

			// write the new revision number to the file
			function (callback) {
				that.server
					.queue(['echo',
							'\"'+that.config.newRevision+'\"',
							'>>',
							'REVISION'
						], that.config.newReleasePath)
					.execQueue(function (err) {
						if (err) callback(err);
						else callback();
					});
			}

		], function (err) {
			if (err) cb(err);
			else cb();
		});

};

// Set up the directory symlinks
Deployer.prototype._symlinkDirs = function (cb) {

	var that = this;

	if (this.config.linkedDirs.length > 0) {

		var dirs = this.config.linkedDirs.slice();

		async.whilst(
			function () { return dirs.length > 0; },

			function (callback) {
				var dir    = dirs.shift();
				var target = path.join(that.config.sharedPath, dir);
				var link   = path.join(that.config.newReleasePath, dir);

				// first make sure the parent directory exists
				// TODO may not need this since we created the dirs in _preDeploy
				that.server.queue(['mkdir', '-p', path.dirname(link)]);
				// then create the link
				that.server.queue(['ln', '-s', target, link]);

				callback();
			},

			function (err) {
				if (err) cb(err);
				else {
					that.server.execQueue(function (err) {
						if (err) cb(err);
						else {
							that.logger.log('Symlinked directories');
							cb();
						}
					});
				}
			});

	} else cb();

};

// Set up the file symlinks
Deployer.prototype._symlinkFiles = function (cb) {

	var that = this;

	if (this.config.linkedFiles.length > 0) {

		var files = this.config.linkedFiles.slice();

		async.whilst(
			function () { return files.length > 0; },

			function (callback) {
				var file   = files.shift();
				var target = path.join(that.config.sharedPath, file);
				var link   = path.join(that.config.newReleasePath, file);

				// first make sure the parent directory exists
				// TODO may not need this since we created the dirs in _preDeploy
				that.server.queue(['mkdir', '-p', path.dirname(link)]);
				// then create the link
				that.server.queue(['ln', '-s', target, link]);

				callback();
			},

			function (err) {
				if (err) cb(err);
				else {
					that.server.execQueue(function (err) {
						if (err) cb(err);
						else {
							that.logger.log('Symlinked files');
							cb();
						}
					});
				}
			});

	} else cb();

};

// Symlink the current dir to the new release
Deployer.prototype._symlinkCurrent = function (cb) {

	var that = this;

	// remove the current link if there is one
	if (this.config.revisionExists)
		this.server.queue('rm ' + this.config.currentPath);

	this.server
		.queue(['ln',
				'-s',
				this.config.newReleasePath,
				this.config.currentPath
			])
		.execQueue(function (err) {
			if (err) cb(err);
			else {
				that.logger.log('New release published');
				cb();
			}
		});

};

// Cleanup any old releases
Deployer.prototype._cleanup = function (cb) {

	var that = this;

	this.server.capture('ls -1tr ' + this.config.releasePath, function (list, err) {
		if (err) cb(err);
		else {
			var releases = list.split('\n'),
				count    = releases.length,
				keep     = that.config.keepReleases,
				toRemove = [];

			if (count > keep) {
				that.logger.log('Keeping ' + keep + ' of ' + count + ' deployed releases');

				for (var i = 0; i < (count - keep); i++) {
					var p = path.join(that.config.releasePath, releases[i]);
					toRemove.push(p);
				}

				toRemove.forEach(function (p) {
					that.server.queue('rm -rf ' + p);
				});

				that.server.execQueue(function (err) {
					if (err) cb(err);
					else cb();
				});

			} else {
				cb();
			}
		}
	});

};

// Write out the deployment log
Deployer.prototype._writeRevisionLog = function (cb) {

	var log = 'Branch ';
		log += this.config.branch;
		log += ' (at ';
		log += this.config.newRevision;
		log += ') deployed as release ';
		log += this.config.newRelease;
		log += ' by ';
		log += process.env.USER;

	this.server
		.queue(['echo',
				'\"'+log+'\"',
				'>>',
				this.config.deployLog
			])
		.execQueue(function (err) {
			if (err) cb(err);
			else cb();
		});

};

module.exports = Deployer;<commit_msg>fixes some valid git output returning an error<commit_after>// Requires
var async  = require('async'),
	fs     = require('fs'),
	path   = require('path'),
	minify = require('node-json-minify'),
	Server = require('./server');

// Constructor
function Deployer (stage, logger) {

	this.logger = logger;

	// load up the configuration for this deployment
	if (fs.existsSync('reploy.json')) {
		var contents = fs.readFileSync('reploy.json', { encoding: 'utf8' });
		this.deployment  = JSON.parse(minify(contents));
	} else {
		this.logger.error('reploy.json file not found!');
		process.exit(1);
	}

	if (!(stage in this.deployment)) {
		this.logger.error(stage + ' does not exist in reploy.json file!');
		process.exit(1);
	}

	this.config = {
		path: this._load('path', stage),
		repo: this._load('repository'),
		branch: this._load('branch', stage),
		keepReleases: this._load('keepReleases'),
		newReleasePath: '',
		releasePath: path.join(this._load('path', stage), 'releases'),
		currentPath: path.join(this._load('path', stage), 'current'),
		sharedPath: path.join(this._load('path', stage), 'shared'),
		repoPath: path.join(this._load('path', stage), 'repo'),
		deployLog: path.join(this._load('path', stage), 'deployments.log'),
		newRelease: '',
		newRevision: '',
		linkedFiles: this._load('linkedFiles'),
		linkedDirs: this._load('linkedDirs'),
		revisionExists: false,
		repoExists: false
	};

	// initialize a server for ssh connection
	this.server = new Server({
		host: this._load('host', stage),
		username: this._load('username', stage),
		agent: process.env.SSH_AUTH_SOCK,
		agentFwd: true
	}, logger);

};

// Load in a deployment setting
Deployer.prototype._load = function (key, stage) {

	if (stage) {
		return this.deployment[stage][key];
	} else {
		return this.deployment[key];
	}

};

// Make the actual deployment
Deployer.prototype.deploy = function () {

	var that = this;

	this.server.open(function (err) {
		if (err) {
			that.logger.error('Could not connect to ' + that.server.host + '! ' + err);

		} else {
			that.logger.log('Connected to ' + that.server.host);

			async.series([
				that._preDeploy.bind(that),
				that._fetchNewReleasePath.bind(that),
				that._deployRepo.bind(that),
				that._deployRelease.bind(that),
				that._setNewRevision.bind(that),
				that._symlinkDirs.bind(that),
				that._symlinkFiles.bind(that),
				that._symlinkCurrent.bind(that),
				that._cleanup.bind(that),
				that._writeRevisionLog.bind(that),

			], function (err) {
				if (err) {
					that.server.close(function () {
						that.logger.error('Deployment failed with: ' + err);
					});
				} else {
					that.server.close(function () {
						that.logger.success('Deployment complete!');
					});
				}
			});
		}
	});

};

// Set up everything before deploying a new release
Deployer.prototype._preDeploy = function (cb) {

	var that = this;

	this.server
		// make sure we can access git
		.queue(['git',
				'ls-remote',
				'--heads',
				this.config.repo
			])
		// make sure the needed directories are there
		.queue(['mkdir',
				'-p',
				this.config.releasePath,
				this.config.sharedPath
			]);

	// make sure that symlinked directories exist
	if (this.config.linkedDirs.length > 0) {
		var dirs = [];
		this.config.linkedDirs.forEach(function (dir) {
			dirs.push(path.join(that.config.sharedPath, dir));
		});

		this.server.queue(['mkdir', '-p', dirs.join(' ')]);
	}

	// make sure the directories of files to be symlinked exist
	if (this.config.linkedFiles.length > 0) {
		var dirs = [];
		this.config.linkedFiles.forEach(function (file) {
			dirs.push(path.dirname(path.join(that.config.sharedPath, file)));
		});

		this.server.queue(['mkdir', '-p', dirs.join(' ')]);
	}

	this.server
		.execQueue(function (err) {
			if (err) cb(err);
			else {
				async.series([
					// check that each of the symlinked files exist on the server
					// TODO make this a warning until user created tasks
					// are in there.
					function (callback) {
						if (that.config.linkedFiles.length > 0) {
							var files = that.config.linkedFiles.slice();

							async.whilst(
								function () { return files.length > 0 },

								function (callback) {
									var file = files.shift();

									that.server.check('file', path.join(that.config.sharedPath, file), function (response, err) {
										if (err) callback(err);
										else {
											if (response == "1") callback();
											else {
                                                //callback(path.join(that.config.sharedPath, file) + ' does not exist!');
                                            // if it doesn't exist, just create the file
                                                that.server
                                                    .queue(['touch', path.join(that.config.sharedPath, file)])
                                                    .execQueue(function (err) {
                                                        if (err) callback(err);
                                                        else callback();
                                                    });
                                            }
										}
									});
								},

								function (err) {
									if (err) callback(err);
									else callback();
								});

						} else {
							callback();
						}
					},

					// check if there's already a release deployed
					function (callback) {
						that.server.check('file', path.join(that.config.currentPath, 'REVISION'), function (response, err) {
							if (err) callback(err);
							else {
								if (response == "1")
									that.config.revisionExists = true;

								callback();
							}
						});
					},

					// check if the repo mirror has already been cloned
					function (callback) {
						that.server.check('file', path.join(that.config.repoPath, 'HEAD'), function (response, err) {
							if (err) callback(err);
							else {
								if (response == "1")
									that.config.repoExists = true;

								callback();
							}
						});
					}
				], function (err) {
					if (err) cb(err);
					else {
						that.logger.log('Check stage complete');
						cb();
					}
				});
			}
		});

};

// Fetch the new release path
Deployer.prototype._fetchNewReleasePath = function (cb) {

	this.server.capture('date +%Y%m%d%H%M%S', function (timestamp, err) {
		if (err) cb(err);
		else {
			this.config.newRelease = timestamp;
			this.config.newReleasePath = path.join(this.config.releasePath, this.config.newRelease);
			this.logger.verbose('New Release Path: ' + this.config.newReleasePath);
			cb();
		}
	}.bind(this));

};

// Clone, if needed, and update the repo on the server
Deployer.prototype._deployRepo = function (cb) {

	var that = this;

	// if the repo isn't already there, go ahead and clone it
	if (! this.config.repoExists)
		this.server.queue(['git', 'clone', '--mirror', '-q', this.config.repo, this.config.repoPath])

	this.server
		.queue(['git',
				'remote',
				'update',
                '&>/dev/null'
			], this.config.repoPath)
		.execQueue(function (err) {

			if (err) cb(err);
			else {
				that.logger.log('Repo updated');
				cb();
			}
		});

};

// Create and clone the new release
Deployer.prototype._deployRelease = function (cb) {

	var that = this;

	this.server
		.queue(['mkdir',
				'-p',
				this.config.newReleasePath
			])
		.queue(['git',
				'archive',
				this.config.branch,
				'| tar',
				'-x -f - -C',
				this.config.newReleasePath
			], this.config.repoPath)
		.execQueue(function (err) {
			if (err) cb(err);
			else {
				that.logger.log('New release created');
				cb();
			}
		});

};

// Get the current git revision
Deployer.prototype._setNewRevision = function (cb) {

	var that = this;

	async.series([
			// fetch the new revision number
			function (callback) {
				that.server
					.capture(['git',
							'rev-parse',
							'--short',
							that.config.branch
						], that.config.repoPath,
						function (revision, err) {
							if (err) callback(err);
							else {
								that.config.newRevision = revision;
								callback();
							}
						});
			},

			// write the new revision number to the file
			function (callback) {
				that.server
					.queue(['echo',
							'\"'+that.config.newRevision+'\"',
							'>>',
							'REVISION'
						], that.config.newReleasePath)
					.execQueue(function (err) {
						if (err) callback(err);
						else callback();
					});
			}

		], function (err) {
			if (err) cb(err);
			else cb();
		});

};

// Set up the directory symlinks
Deployer.prototype._symlinkDirs = function (cb) {

	var that = this;

	if (this.config.linkedDirs.length > 0) {

		var dirs = this.config.linkedDirs.slice();

		async.whilst(
			function () { return dirs.length > 0; },

			function (callback) {
				var dir    = dirs.shift();
				var target = path.join(that.config.sharedPath, dir);
				var link   = path.join(that.config.newReleasePath, dir);

				// first make sure the parent directory exists
				// TODO may not need this since we created the dirs in _preDeploy
				that.server.queue(['mkdir', '-p', path.dirname(link)]);
				// then create the link
				that.server.queue(['ln', '-s', target, link]);

				callback();
			},

			function (err) {
				if (err) cb(err);
				else {
					that.server.execQueue(function (err) {
						if (err) cb(err);
						else {
							that.logger.log('Symlinked directories');
							cb();
						}
					});
				}
			});

	} else cb();

};

// Set up the file symlinks
Deployer.prototype._symlinkFiles = function (cb) {

	var that = this;

	if (this.config.linkedFiles.length > 0) {

		var files = this.config.linkedFiles.slice();

		async.whilst(
			function () { return files.length > 0; },

			function (callback) {
				var file   = files.shift();
				var target = path.join(that.config.sharedPath, file);
				var link   = path.join(that.config.newReleasePath, file);

				// first make sure the parent directory exists
				// TODO may not need this since we created the dirs in _preDeploy
				that.server.queue(['mkdir', '-p', path.dirname(link)]);
				// then create the link
				that.server.queue(['ln', '-s', target, link]);

				callback();
			},

			function (err) {
				if (err) cb(err);
				else {
					that.server.execQueue(function (err) {
						if (err) cb(err);
						else {
							that.logger.log('Symlinked files');
							cb();
						}
					});
				}
			});

	} else cb();

};

// Symlink the current dir to the new release
Deployer.prototype._symlinkCurrent = function (cb) {

	var that = this;

	// remove the current link if there is one
	if (this.config.revisionExists)
		this.server.queue('rm ' + this.config.currentPath);

	this.server
		.queue(['ln',
				'-s',
				this.config.newReleasePath,
				this.config.currentPath
			])
		.execQueue(function (err) {
			if (err) cb(err);
			else {
				that.logger.log('New release published');
				cb();
			}
		});

};

// Cleanup any old releases
Deployer.prototype._cleanup = function (cb) {

	var that = this;

	this.server.capture('ls -1tr ' + this.config.releasePath, function (list, err) {
		if (err) cb(err);
		else {
			var releases = list.split('\n'),
				count    = releases.length,
				keep     = that.config.keepReleases,
				toRemove = [];

			if (count > keep) {
				that.logger.log('Keeping ' + keep + ' of ' + count + ' deployed releases');

				for (var i = 0; i < (count - keep); i++) {
					var p = path.join(that.config.releasePath, releases[i]);
					toRemove.push(p);
				}

				toRemove.forEach(function (p) {
					that.server.queue('rm -rf ' + p);
				});

				that.server.execQueue(function (err) {
					if (err) cb(err);
					else cb();
				});

			} else {
				cb();
			}
		}
	});

};

// Write out the deployment log
Deployer.prototype._writeRevisionLog = function (cb) {

	var log = 'Branch ';
		log += this.config.branch;
		log += ' (at ';
		log += this.config.newRevision;
		log += ') deployed as release ';
		log += this.config.newRelease;
		log += ' by ';
		log += process.env.USER;

	this.server
		.queue(['echo',
				'\"'+log+'\"',
				'>>',
				this.config.deployLog
			])
		.execQueue(function (err) {
			if (err) cb(err);
			else cb();
		});

};

module.exports = Deployer;<|endoftext|>


<commit_before>// 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.

import {findModule} from '../../../modules'

export function addReactPlugins(plugins) {
  let {jsx, react} = process.env

  // Transform JSX into “React.createElement()” calls.
  if (jsx)
    plugins.push(findModule('@babel/plugin-transform-react-jsx'))

  // Add display name attribute to React classes created by calling
  // “React.createClass()” or “createReactClass()”.
  plugins.push(findModule('@babel/plugin-transform-react-display-name'))

  let {production} = process.env
  if (production)
    return

  // Add “__self” property to JSX elements which React will use to generate
  // runtime warnings.
  plugins.push(findModule('@babel/plugin-transform-react-jsx-self'))

  // Add “__source” property to JSX elements containing the file and line number
  // used to enhance error messages.
  plugins.push(findModule('@babel/plugin-transform-react-jsx-source'))
}

export default addReactPlugins
<commit_msg>Fix react plugins not being disabled<commit_after>// 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.

import {findModule} from '../../../modules'

export function addReactPlugins(plugins) {
  let {jsx, react} = process.env

  if (!react)
    return

  // Transform JSX into “React.createElement()” calls.
  if (jsx)
    plugins.push(findModule('@babel/plugin-transform-react-jsx'))

  // Add display name attribute to React classes created by calling
  // “React.createClass()” or “createReactClass()”.
  plugins.push(findModule('@babel/plugin-transform-react-display-name'))

  let {production} = process.env
  if (production)
    return

  // Add “__self” property to JSX elements which React will use to generate
  // runtime warnings.
  plugins.push(findModule('@babel/plugin-transform-react-jsx-self'))

  // Add “__source” property to JSX elements containing the file and line number
  // used to enhance error messages.
  plugins.push(findModule('@babel/plugin-transform-react-jsx-source'))
}

export default addReactPlugins
<|endoftext|>


<commit_before>'use strict';

var pathFn = require('path');
var fs = require('hexo-fs');
var chalk = require('chalk');
var swig = require('swig');
var moment = require('moment');
var spawn = require('hexo-util/lib/spawn');
var parseConfig = require('./parse_config');

var swigHelpers = {
  now: function(format) {
    return moment().format(format);
  }
};

module.exports = function(args) {
  var baseDir = this.base_dir;
  var deployDir = pathFn.join(baseDir, '.deploy_git');
  var publicDir = this.public_dir;
  var log = this.log;
  var message = commitMessage(args);
  var verbose = !args.silent;

  if (!args.repo && !args.repository) {
    var help = '';

    help += 'You have to configure the deployment settings in _config.yml first!\n\n';
    help += 'Example:\n';
    help += '  deploy:\n';
    help += '    type: git\n';
    help += '    repo: <repository url>\n';
    help += '    branch: [branch]\n';
    help += '    message: [message]\n\n';
    help += 'For more help, you can check the docs: ' + chalk.underline('http://hexo.io/docs/deployment.html');

    console.log(help);
    return;
  }

  function git() {
    var len = arguments.length;
    var args = new Array(len);

    for (var i = 0; i < len; i++) {
      args[i] = arguments[i];
    }

    return spawn('git', args, {
      cwd: deployDir,
      verbose: verbose
    });
  }

  function setup() {
    var userName = args.name || args.user || args.userName || '';
    var userEmail = args.email || args.userEmail || '';

    // Create a placeholder for the first commit
    return fs.writeFile(pathFn.join(deployDir, 'placeholder'), '').then(function() {
      return git('init');
    }).then(function() {
      return userName && git('config', 'user.name', userName);
    }).then(function() {
      return userEmail && git('config', 'user.email', userEmail);
    }).then(function() {
      return git('add', '-A');
    }).then(function() {
      return git('commit', '-m', 'First commit');
    });
  }

  function push(repo) {
    return git('add', '-A').then(function() {
      return git('commit', '-m', message).catch(function() {
        // Do nothing. It's OK if nothing to commit.
      });
    }).then(function() {
      return git('push', '-u', repo.url, 'HEAD:' + repo.branch, '--force');
    });
  }

  return fs.exists(deployDir).then(function(exist) {
    if (exist) return;

    log.info('Setting up Git deployment...');
    return setup();
  }).then(function() {
    log.info('Clearing .deploy_git folder...');
    return fs.emptyDir(deployDir);
  }).then(function() {
    log.info('Copying files from public folder...');
    return fs.copyDir(publicDir, deployDir);
  }).then(function() {
    return parseConfig(args);
  }).each(function(repo) {
    return push(repo);
  });
};

function commitMessage(args) {
  var message = args.m || args.msg || args.message || 'Site updated: {{ now(\'YYYY-MM-DD HH:mm:ss\') }}';
  return swig.compile(message)(swigHelpers);
}
<commit_msg>Add extend_dirs<commit_after>'use strict';

var pathFn = require('path');
var fs = require('hexo-fs');
var chalk = require('chalk');
var swig = require('swig');
var moment = require('moment');
var Promise = require('bluebird');
var spawn = require('hexo-util/lib/spawn');
var parseConfig = require('./parse_config');

var swigHelpers = {
  now: function(format) {
    return moment().format(format);
  }
};

module.exports = function(args) {
  var baseDir = this.base_dir;
  var deployDir = pathFn.join(baseDir, '.deploy_git');
  var publicDir = this.public_dir;
  var extendDirs = args.extend_dirs;
  var log = this.log;
  var message = commitMessage(args);
  var verbose = !args.silent;

  if (!args.repo && !args.repository) {
    var help = '';

    help += 'You have to configure the deployment settings in _config.yml first!\n\n';
    help += 'Example:\n';
    help += '  deploy:\n';
    help += '    type: git\n';
    help += '    repo: <repository url>\n';
    help += '    branch: [branch]\n';
    help += '    message: [message]\n\n';
    help += 'For more help, you can check the docs: ' + chalk.underline('http://hexo.io/docs/deployment.html');

    console.log(help);
    return;
  }

  function git() {
    var len = arguments.length;
    var args = new Array(len);

    for (var i = 0; i < len; i++) {
      args[i] = arguments[i];
    }

    return spawn('git', args, {
      cwd: deployDir,
      verbose: verbose
    });
  }

  function setup() {
    var userName = args.name || args.user || args.userName || '';
    var userEmail = args.email || args.userEmail || '';

    // Create a placeholder for the first commit
    return fs.writeFile(pathFn.join(deployDir, 'placeholder'), '').then(function() {
      return git('init');
    }).then(function() {
      return userName && git('config', 'user.name', userName);
    }).then(function() {
      return userEmail && git('config', 'user.email', userEmail);
    }).then(function() {
      return git('add', '-A');
    }).then(function() {
      return git('commit', '-m', 'First commit');
    });
  }

  function push(repo) {
    return git('add', '-A').then(function() {
      return git('commit', '-m', message).catch(function() {
        // Do nothing. It's OK if nothing to commit.
      });
    }).then(function() {
      return git('push', '-u', repo.url, 'HEAD:' + repo.branch, '--force');
    });
  }

  return fs.exists(deployDir).then(function(exist) {
    if (exist) return;

    log.info('Setting up Git deployment...');
    return setup();
  }).then(function() {
    log.info('Clearing .deploy_git folder...');
    return fs.emptyDir(deployDir);
  }).then(function() {
    log.info('Copying files from public folder...');
    return fs.copyDir(publicDir, deployDir);
  }).then(function() {
    log.info('Copying files from extend dirs...');

    if (!extendDirs) {
      return;
    }

    if (typeof extendDirs === 'string') {
      extendDirs = [extendDirs];
    }

    var mapFn = function(dir) {
      var extendPath = pathFn.join(baseDir, dir);
      var extendDist = pathFn.join(deployDir, dir);

      return fs.copyDir(extendPath, extendDist);
    };

    return Promise.map(extendDirs, mapFn, {
      concurrency: 2
    });
  }).then(function() {
    return parseConfig(args);
  }).each(function(repo) {
    return push(repo);
  });
};

function commitMessage(args) {
  var message = args.m || args.msg || args.message || 'Site updated: {{ now(\'YYYY-MM-DD HH:mm:ss\') }}';
  return swig.compile(message)(swigHelpers);
}
<|endoftext|>


<commit_before>var RSVP = require("rsvp"),
    _ = require("lodash");

module.exports = function(){
  var handlers = {};

  var createRequest = function(collection, opt, httpMethod){
    var createUrl = function(path, query) {
      var queryStr = '';
      _.each(Object.keys(query), function(key) {
        if (queryStr !== '') queryStr += '&';
        queryStr += key + '=' + query[key];
      });

      return path + '?' + queryStr;
    };
    var path = '/' + ((opt.params && opt.params.id) ? collection + '/' + opt.params.id : collection);

    return _.extend(opt, {
      direct: true,
      method: httpMethod,
      headers: _.extend({
        "content-type": "application/json"
      }, opt.headers),
      get: function(h){ return this.headers[h]; },
      set: function(key,val){ this.headers[key] = val},
      fortune: {requestMetadata: {direct: true}},
      query: opt.query || {},
      params: opt.params || {},
      zipkinTraceId: opt.zipkinTraceId,
      path: path,
      url = path + '?' + createUrl(),
    });
  };

  var createResponse = function(){
    var deferred = RSVP.defer(),
        res = {
          headers: {},
          set: function(key,val){ this.headers[key] = val; },
          get: function(h){ return this.headers[h]},
          setHeader: function(key,val){this.set(key,val);},
          status: function(){return this;}, //it's not used anywhere
          send: function(body){
            deferred.resolve(_.extend({
              body: body && JSON.parse(body)
            }, res));
          },
          promise: deferred.promise
        };

    return res;
  };

  var asSingleOrCollection = function(method, collection, options, httpMethod){
    var req, res,
        methodName = (options.params || {}).id ? method : (method + "All");

    handlers[collection][methodName](req = createRequest(collection, options, httpMethod), res = createResponse());

    return res.promise;
  };

  return {
    _createRequest: createRequest,
    _createResponse: createResponse,
    methods: {
      create: function(collection, options){
        var req, res;

        options.body = _.cloneDeep(options.body);

        handlers[collection].create(req = createRequest(collection, options, "POST"),res = createResponse());

        return res.promise;
      },
      get: function(collection,options){
        return asSingleOrCollection("get", collection, options || {}, "GET");
      },
      destroy: function(collection,options){
        return asSingleOrCollection("destroy", collection, options || {}, "DELETE");
      },
      replace: function(collection, options){
        var req,res;

        options.body = _.cloneDeep(options.body);

        handlers[collection].replace(req = createRequest(collection, options, "PUT"), res = createResponse());
        return res.promise;
      },
      update: function(collection, options){
        var req, res;

        options.body = _.cloneDeep(options.body);

        handlers[collection].update(req = createRequest(collection, options, "PATCH"), res = createResponse());

        return res.promise;
      },
      callAction: function(collection, method, options){
        var req, res;

        options.body = _.cloneDeep(options.body);
        handlers[collection].callAction(req = createRequest(collection, options, method), res = createResponse());

        return res.promise;
      },
      callGenericAction: function(collection, method, options){
        var req, res;

        options.body = _.cloneDeep(options.body);
        handlers[collection].callGenericAction(req = createRequest(collection, options, method), res = createResponse());

        return res.promise;
      }
    },
    registerResource: function(collection, callbacks){
      var handlerNames = [ "create", "update", "replace", "destroy", "destroyAll", "get", "getAll", "callAction", "callGenericAction"];
      if(!_.isEqual(_.keys(callbacks), handlerNames)){
        throw new Error("Wrong route handler names");
      }
      handlers[collection] = callbacks;
    }
  };
};
<commit_msg>SUP-3478: fix createUrl<commit_after>var RSVP = require("rsvp"),
    _ = require("lodash");

module.exports = function(){
  var handlers = {};

  var createRequest = function(collection, opt, httpMethod){
    var createUrl = function(path, query) {
      var queryStr = '';
      if(query !=== undefined) {
        _.each(Object.keys(query), function(key) {
          if (queryStr !== '') queryStr += '&';
          queryStr += key + '=' + query[key];
        });
      }
      return path + '?' + queryStr;
    };
    var path = '/' + ((opt.params && opt.params.id) ? collection + '/' + opt.params.id : collection);

    return _.extend(opt, {
      direct: true,
      method: httpMethod,
      headers: _.extend({
        "content-type": "application/json"
      }, opt.headers),
      get: function(h){ return this.headers[h]; },
      set: function(key,val){ this.headers[key] = val},
      fortune: {requestMetadata: {direct: true}},
      query: opt.query || {},
      params: opt.params || {},
      zipkinTraceId: opt.zipkinTraceId,
      path: path,
      url = createUrl(path, opt.query),
    });
  };

  var createResponse = function(){
    var deferred = RSVP.defer(),
        res = {
          headers: {},
          set: function(key,val){ this.headers[key] = val; },
          get: function(h){ return this.headers[h]},
          setHeader: function(key,val){this.set(key,val);},
          status: function(){return this;}, //it's not used anywhere
          send: function(body){
            deferred.resolve(_.extend({
              body: body && JSON.parse(body)
            }, res));
          },
          promise: deferred.promise
        };

    return res;
  };

  var asSingleOrCollection = function(method, collection, options, httpMethod){
    var req, res,
        methodName = (options.params || {}).id ? method : (method + "All");

    handlers[collection][methodName](req = createRequest(collection, options, httpMethod), res = createResponse());

    return res.promise;
  };

  return {
    _createRequest: createRequest,
    _createResponse: createResponse,
    methods: {
      create: function(collection, options){
        var req, res;

        options.body = _.cloneDeep(options.body);

        handlers[collection].create(req = createRequest(collection, options, "POST"),res = createResponse());

        return res.promise;
      },
      get: function(collection,options){
        return asSingleOrCollection("get", collection, options || {}, "GET");
      },
      destroy: function(collection,options){
        return asSingleOrCollection("destroy", collection, options || {}, "DELETE");
      },
      replace: function(collection, options){
        var req,res;

        options.body = _.cloneDeep(options.body);

        handlers[collection].replace(req = createRequest(collection, options, "PUT"), res = createResponse());
        return res.promise;
      },
      update: function(collection, options){
        var req, res;

        options.body = _.cloneDeep(options.body);

        handlers[collection].update(req = createRequest(collection, options, "PATCH"), res = createResponse());

        return res.promise;
      },
      callAction: function(collection, method, options){
        var req, res;

        options.body = _.cloneDeep(options.body);
        handlers[collection].callAction(req = createRequest(collection, options, method), res = createResponse());

        return res.promise;
      },
      callGenericAction: function(collection, method, options){
        var req, res;

        options.body = _.cloneDeep(options.body);
        handlers[collection].callGenericAction(req = createRequest(collection, options, method), res = createResponse());

        return res.promise;
      }
    },
    registerResource: function(collection, callbacks){
      var handlerNames = [ "create", "update", "replace", "destroy", "destroyAll", "get", "getAll", "callAction", "callGenericAction"];
      if(!_.isEqual(_.keys(callbacks), handlerNames)){
        throw new Error("Wrong route handler names");
      }
      handlers[collection] = callbacks;
    }
  };
};
<|endoftext|>


<commit_before>var Sensor = require("../lib/sensor.js"),
  util = require("util");

var Devices = {
  GP2Y0A21YK: {
    // https://www.sparkfun.com/products/242
    cm: {
      get: function() {
        return +(12343.85 * Math.pow(this.raw, -1.15)).toFixed(2);
      }
    }
  },
  GP2D120XJ00F: {
    // https://www.sparkfun.com/products/8959
    cm: {
      get: function() {
        return +((2914 / (this.raw + 5)) - 1).toFixed(2);
      }
    }
  },
  GP2Y0A02YK0F: {
    // https://www.sparkfun.com/products/8958
    cm: {
      get: function() {
        return +(10650.08 * Math.pow(this.raw, -0.935) - 10).toFixed(2);
      }
    }
  }
};

// Otherwise known as...
Devices["2Y0A21"] = Devices.GP2Y0A21YK;
Devices["2D120X"] = Devices.GP2D120XJ00F;
Devices["2Y0A02"] = Devices.GP2Y0A02YK0F;

function Distance(opts) {

  if (!(this instanceof Distance)) {
    return new Distance(opts);
  }

  Sensor.call(this, opts);

  var device = Devices[opts.device];

  if (device) {
    if (!device.inches) {
      device.inches = {
        get: function() {
          return +(this.cm * 0.39).toFixed(2);
        }
      };
    }
  } else {
    device = {
      inches: {
        value: null
      },
      cm: {
        value: null
      }
    };
  }

  Object.defineProperties(this, device);
}

util.inherits(Distance, Sensor);

module.exports = Distance;

// http://www.acroname.com/robotics/info/articles/sharp/sharp.html
<commit_msg>Allow new device type to be passed as an object<commit_after>var Sensor = require("../lib/sensor.js"),
  util = require("util");

var Devices = {
  GP2Y0A21YK: {
    // https://www.sparkfun.com/products/242
    cm: {
      get: function() {
        return +(12343.85 * Math.pow(this.raw, -1.15)).toFixed(2);
      }
    }
  },
  GP2D120XJ00F: {
    // https://www.sparkfun.com/products/8959
    cm: {
      get: function() {
        return +((2914 / (this.raw + 5)) - 1).toFixed(2);
      }
    }
  },
  GP2Y0A02YK0F: {
    // https://www.sparkfun.com/products/8958
    cm: {
      get: function() {
        return +(10650.08 * Math.pow(this.raw, -0.935) - 10).toFixed(2);
      }
    }
  }
};

// Otherwise known as...
Devices["2Y0A21"] = Devices.GP2Y0A21YK;
Devices["2D120X"] = Devices.GP2D120XJ00F;
Devices["2Y0A02"] = Devices.GP2Y0A02YK0F;

function Distance(opts) {

  if (!(this instanceof Distance)) {
    return new Distance(opts);
  }

  Sensor.call(this, opts);

  var device;
  if (typeof opts.device === "string") {
    device = Devices[opts.device];
  } else {
    device = opts.device;
  }

  if (device) {
    if (!device.inches) {
      device.inches = {
        get: function() {
          return +(this.cm * 0.39).toFixed(2);
        }
      };
    }
  } else {
    device = {
      inches: {
        value: null
      },
      cm: {
        value: null
      }
    };
  }

  Object.defineProperties(this, device);
}

util.inherits(Distance, Sensor);

module.exports = Distance;

// http://www.acroname.com/robotics/info/articles/sharp/sharp.html
<|endoftext|>


<commit_before>"use strict";

const l = require('log').get('dom');

// RegExp for checking if string is HTML
const re_html = /^\s*<(\w+|!)[^>]*>/;

/**
 * DomUtil class contains collection of static methods for common
 * DOM functions.
 */
class DomUtil {

	/**
	 * @ignore
	 */
	constructor() {
		throw new Error('DomUtil should not be instantiated');
	}

	/**
	 * Check whether the given object is a DOM Element.
	 */
	static isElement(obj) {
		return !!(obj && obj.nodeType === 1);
	}

	/**
	 * Check whether the given object is a DOM Text Node.
	 */
	static isTextNode(obj) {
		return !!(obj && obj.nodeType === 3);
	}

	/**
	 * Check whether the given object is a DOM Document.
	 */
	static isDocument(obj) {
		return !!(obj && obj.nodeType === 9);
	}

	/**
	 * Check whether the given object is a DOM Document Fragment.
	 */
	static isDocumentFragment(obj) {
		return !!(obj && obj.nodeType === 11);
	}

	/**
	 * Check whether the given string is HTML.
	 */
	static isHTML(str) {
		return re_html.test(str);
	}

	/**
	 * Query given selector from element or from whole document.
	 */
	static query(selector, parent) {
		parent = parent || document;
		return parent.querySelector(selector);
	}

	/**
	 * Query given selector from element or from whole document.
	 */
	static queryAll(selector, parent) {
		parent = parent || document;
		return Array.from(parent.querySelectorAll(selector));
	}

	static ensureElement(selector, parent) {
		let element = selector;
		if (typeof element === 'string') {
			element = DomUtil.query(selector, parent);
		}

		if (!DomUtil.isElement(element)) {
			throw new Error("'element' must be DOM element");
		}
		return element;
	}

	/**
	 * Check whether the given element matches the selector.
	 */
	static matches(element, selector) {
		if (!selector || !DomUtil.isElement(element)) {
			return false;
		}
		return element.matches(selector);
	}

	/**
	 * Filter array of elements using given query selector.
	 */
	static filter(elements, selector) {
		// convert array-like objects to array and wrap anything else in array.
		elements = Array.from(elements);

		let result;
		if (typeof selector === 'undefined') {
			// return all elements if no selector is given
			result = elements;
		} else if (typeof selector === 'function') {
			// use given function as a callback for the Array filter
			result = elements.filter(selector);
		} else {
			result = elements.filter((e) => DomUtil.matches(e, selector));
		}
		return result;
	}

	/**
	 * Find a parent element that satisfies the query selector.
	 */
	static findParent(element, selector, until) {
		if (!DomUtil.isElement(element)) {
			return null;
		}

		while (element) {
			if (DomUtil.matches(element, selector)) {
				return element;
			} else if (until && DomUtil.matches(element, until)) {
				return false;
			}

			element = element.parentElement;
		}
		return false;
	}

	static updateElementValue(element, name, value) {
		if (typeof value === 'function') {
			value = value(element);
		}
		if (typeof value === 'object' && !Array.isArray(value)) {
			DomUtil.updateElement(element, name, value);
		}

		if (name === '_') {
			// l("update text: %o", value);
			element.textContent = value;
		} else
		if (name == '$') {
			// l("update html: %o", value);
			element.innerHTML = value;
		} else
		if (name == '#') {
			// l("update id: %o", value);
			element.id = value;
		} else
		if (name === '.') {
			// l("update class: %o", value);
			element.className = value;
		} else
		if (name.startsWith('.')) {
			let attr = name.slice(1);
			// l("update attr %s: %s", attr, value);
			element.setAttribute(attr, value);
		} else {
			console.warn("Unknown `updateElementValue` name: '" + name + "'");
		}
		return element;
	}

	static updateElement(element, selector, data) {
		if (element) {
			// l("update target: '%s' => %o", selector, data);
			let targets = element.querySelectorAll(selector);
			for (let name in data) {
				const value = data[name];
				for (let target of targets) {
					DomUtil.updateElementValue(target, name, value);
				}
			}
		} else {
			console.warn('Can not update null element');
		}
	}

	static updateElementAll(element, data) {
		for (let selector in data) {
			// l("update: '%s' => %o", selector, data[selector]);
			DomUtil.updateElement(element, selector, data[selector]);
		}
	}
}
module.exports = DomUtil;
<commit_msg>Remove exception if element is not DOM element<commit_after>"use strict";

const l = require('log').get('dom');

// RegExp for checking if string is HTML
const re_html = /^\s*<(\w+|!)[^>]*>/;

/**
 * DomUtil class contains collection of static methods for common
 * DOM functions.
 */
class DomUtil {

	/**
	 * @ignore
	 */
	constructor() {
		throw new Error('DomUtil should not be instantiated');
	}

	/**
	 * Check whether the given object is a DOM Element.
	 */
	static isElement(obj) {
		return !!(obj && obj.nodeType === 1);
	}

	/**
	 * Check whether the given object is a DOM Text Node.
	 */
	static isTextNode(obj) {
		return !!(obj && obj.nodeType === 3);
	}

	/**
	 * Check whether the given object is a DOM Document.
	 */
	static isDocument(obj) {
		return !!(obj && obj.nodeType === 9);
	}

	/**
	 * Check whether the given object is a DOM Document Fragment.
	 */
	static isDocumentFragment(obj) {
		return !!(obj && obj.nodeType === 11);
	}

	/**
	 * Check whether the given string is HTML.
	 */
	static isHTML(str) {
		return re_html.test(str);
	}

	/**
	 * Query given selector from element or from whole document.
	 */
	static query(selector, parent) {
		parent = parent || document;
		return parent.querySelector(selector);
	}

	/**
	 * Query given selector from element or from whole document.
	 */
	static queryAll(selector, parent) {
		parent = parent || document;
		return Array.from(parent.querySelectorAll(selector));
	}

	static ensureElement(selector, parent) {
		let element = selector;
		if (typeof element === 'string') {
			element = DomUtil.query(selector, parent);
		}
		return element;
	}

	/**
	 * Check whether the given element matches the selector.
	 */
	static matches(element, selector) {
		if (!selector || !DomUtil.isElement(element)) {
			return false;
		}
		return element.matches(selector);
	}

	/**
	 * Filter array of elements using given query selector.
	 */
	static filter(elements, selector) {
		// convert array-like objects to array and wrap anything else in array.
		elements = Array.from(elements);

		let result;
		if (typeof selector === 'undefined') {
			// return all elements if no selector is given
			result = elements;
		} else if (typeof selector === 'function') {
			// use given function as a callback for the Array filter
			result = elements.filter(selector);
		} else {
			result = elements.filter((e) => DomUtil.matches(e, selector));
		}
		return result;
	}

	/**
	 * Find a parent element that satisfies the query selector.
	 */
	static findParent(element, selector, until) {
		if (!DomUtil.isElement(element)) {
			return null;
		}

		while (element) {
			if (DomUtil.matches(element, selector)) {
				return element;
			} else if (until && DomUtil.matches(element, until)) {
				return false;
			}

			element = element.parentElement;
		}
		return false;
	}

	static updateElementValue(element, name, value) {
		if (typeof value === 'function') {
			value = value(element);
		}
		if (typeof value === 'object' && !Array.isArray(value)) {
			DomUtil.updateElement(element, name, value);
		}

		if (name === '_') {
			// l("update text: %o", value);
			element.textContent = value;
		} else
		if (name == '$') {
			// l("update html: %o", value);
			element.innerHTML = value;
		} else
		if (name == '#') {
			// l("update id: %o", value);
			element.id = value;
		} else
		if (name === '.') {
			// l("update class: %o", value);
			element.className = value;
		} else
		if (name.startsWith('.')) {
			let attr = name.slice(1);
			// l("update attr %s: %s", attr, value);
			element.setAttribute(attr, value);
		} else {
			console.warn("Unknown `updateElementValue` name: '" + name + "'");
		}
		return element;
	}

	static updateElement(element, selector, data) {
		if (element) {
			// l("update target: '%s' => %o", selector, data);
			let targets = element.querySelectorAll(selector);
			for (let name in data) {
				const value = data[name];
				for (let target of targets) {
					DomUtil.updateElementValue(target, name, value);
				}
			}
		} else {
			console.warn('Can not update null element');
		}
	}

	static updateElementAll(element, data) {
		for (let selector in data) {
			// l("update: '%s' => %o", selector, data[selector]);
			DomUtil.updateElement(element, selector, data[selector]);
		}
	}
}
module.exports = DomUtil;
<|endoftext|>


<commit_before>import 'uni-platform/runtime/index'

import {
  isFn
} from 'uni-shared'

import parseApp from 'uni-platform/runtime/wrapper/app-parser'

export default function createPlugin (vm) {
  const appOptions = parseApp(vm)
  if (isFn(appOptions.onShow) && __GLOBAL__.onAppShow) {
    __GLOBAL__.onAppShow((...args) => {
      appOptions.onShow.apply(vm, args)
    })
  }
  if (isFn(appOptions.onHide) && __GLOBAL__.onAppHide) {
    __GLOBAL__.onAppHide((...args) => {
      appOptions.onHide.apply(vm, args)
    })
  }
  if (isFn(appOptions.onLaunch)) {
    const args = __GLOBAL__.getLaunchOptionsSync && __GLOBAL__.getLaunchOptionsSync()
    appOptions.onLaunch.call(vm, args)
  }
  return vm
}
<commit_msg>chore: mp-plugin call_hook<commit_after>import 'uni-platform/runtime/index'

import {
  isFn
} from 'uni-shared'

import parseApp from 'uni-platform/runtime/wrapper/app-parser'

export default function createPlugin (vm) {
  const appOptions = parseApp(vm)
  if (isFn(appOptions.onShow) && __GLOBAL__.onAppShow) {
    __GLOBAL__.onAppShow((...args) => {
      vm.__call_hook('onShow', args)
    })
  }
  if (isFn(appOptions.onHide) && __GLOBAL__.onAppHide) {
    __GLOBAL__.onAppHide((...args) => {
      vm.__call_hook('onHide', args)
    })
  }
  if (isFn(appOptions.onLaunch)) {
    const args = __GLOBAL__.getLaunchOptionsSync && __GLOBAL__.getLaunchOptionsSync()
    vm.__call_hook('onLaunch', args)
  }
  return vm
}
<|endoftext|>


<commit_before>var debug = require('debug')('mvm:download'),
  path = require('./path'),
  fs = require('fs-extra'),
  request = require('request'),
  createCleanupCrew = require('./cleanup'),
  tildify = require('tildify'),
  ProgressBar = require('progress');

module.exports = function(pkg, fn){
  var dest = path.artifact(pkg),
    url = pkg.url,
    cleanup = createCleanupCrew('remove incomplete artifact', fs.unlinkSync.bind(null, dest));

  fs.mkdirs(path.artifacts(), function(err){
    if(err) return fn(err);

      fs.exists(dest, function(exists){
        if(exists){
          debug('already have artifact ' + dest);
          cleanup.clear();
          return fn();
        }

        debug('downloading %s to %s', url, tildify(dest));
        var out = fs.createWriteStream(dest)
          .on('error', fn)
          .on('finish', function(){
            cleanup.clear();
            fn(null, dest);
          }),
          req = request(url);
        req.on('response', function(res){
          var total = parseInt(res.headers['content-length'], 10);
          debug('total size %dMB', (total/1024/1024).toFixed(2));
          console.log();
          var bar = new ProgressBar('  Downloading MongoDB v' + pkg.version + ' [:bar] :percent :etasec', {
            complete: '=',
            incomplete: ' ',
            width: 40,
            total: total
          });

          res.on('data', function (chunk) {
            bar.tick(chunk.length);
          });

          res.on('end', function () {
            console.log('\n');
          });
        });
        req.pipe(out);
        req.on('error', fn);
      });
  });
};
<commit_msg>[[fixes #14] if dl response size 0, throw correct error<commit_after>var debug = require('debug')('mvm:download'),
  path = require('./path'),
  fs = require('fs-extra'),
  request = require('request'),
  createCleanupCrew = require('./cleanup'),
  tildify = require('tildify'),
  ProgressBar = require('progress');

module.exports = function(pkg, fn) {
  var dest = path.artifact(pkg),
    url = pkg.url,
    cleanup = createCleanupCrew('remove incomplete artifact', fs.unlinkSync.bind(null, dest));

  fs.mkdirs(path.artifacts(), function(err) {
    if (err) return fn(err);

    fs.exists(dest, function(exists) {
      if (exists) {
        debug('already have artifact ' + dest);
        cleanup.clear();
        return fn();
      }

      debug('downloading %s to %s', url, tildify(dest));
      var out = fs.createWriteStream(dest)
          .on('error', fn)
          .on('finish', function() {
            cleanup.clear();
            fn(null, dest);
          }),
        req = request(url);
      req.on('response', function(res) {
        var total = parseInt(res.headers['content-length'], 10);
        debug('total size %dMB', (total / 1024 / 1024).toFixed(2));

        if (!total) {
          return fn(new Error('No response.  Are you sure ' + pkg.version + ' is the right version?'));
        }

        console.log();
        var bar = new ProgressBar('  Downloading MongoDB v' + pkg.version + ' [:bar] :percent :etasec', {
          complete: '=',
          incomplete: ' ',
          width: 40,
          total: total
        });

        res.on('data', function(chunk) {
          bar.tick(chunk.length);
        });

        res.on('end', function() {
          console.log('\n');
        });
      });
      req.pipe(out);
      req.on('error', fn);
    });
  });
};
<|endoftext|>


<commit_before>/**
 * @constructor
 */

var registerGenericListener = function(target) {
	target.onListener('',
		function(name) {
			//log('registering generic event', name)
			var callback = function() {
				target.emit(name)
			}
			target.dom.addEventListener(name, callback)
		},
		function(name) {
			//fixme: implement removing callback
			//return remove callback from first callback?
		}
	)
}

exports.Element = function(context, dom) {
	_globals.core.EventEmitter.apply(this)
	this._context = context
	this.dom = dom
	this._fragment = []
	this._styles = {}

	registerGenericListener(this)
}

exports.Element.prototype = Object.create(_globals.core.EventEmitter.prototype)
exports.Element.prototype.constructor = exports.Element

exports.Element.prototype.addClass = function(cls) {
	this.dom.classList.add(cls)
}

exports.Element.prototype.setHtml = function(html) {
	var dom = this.dom
	this._fragment.forEach(function(node) { dom.removeChild(node) })
	this._fragment = []

	if (html === '')
		return

	var fragment = document.createDocumentFragment()
	var temp = document.createElement('div')

	temp.innerHTML = html
	while (temp.firstChild) {
		this._fragment.push(temp.firstChild)
		fragment.appendChild(temp.firstChild)
	}
	dom.appendChild(fragment)
}

exports.Element.prototype.width = function() {
	return this.dom.clientWidth
}

exports.Element.prototype.height = function() {
	return this.dom.clientHeight
}

exports.Element.prototype.fullWidth = function() {
	return this.dom.scrollWidth
}

exports.Element.prototype.fullHeight = function() {
	return this.dom.scrollHeight
}

exports.Element.prototype.style = function(name, style) {
	if (style !== undefined) {
		if (style !== '') //fixme: replace it with explicit 'undefined' syntax
			this._styles[name] = style
		else
			delete this._styles[name]
		this.updateStyle()
	} else if (name instanceof Object) { //style({ }) assignment
		for(var k in name) {
			var value = name[k]
			if (value !== '') //fixme: replace it with explicit 'undefined' syntax
				this._styles[k] = value
			else
				delete this._styles[k]
		}
		this.updateStyle()
	}
	else
		return this._styles[name]
}

exports.Element.prototype.setAttribute = function(name, value) {
	this.dom.setAttribute(name, value)
}

exports.Element.prototype.updateStyle = function() {
	var element = this.dom
	if (!element)
		return

	/** @const */
	var cssUnits = {
		'left': 'px',
		'top': 'px',
		'width': 'px',
		'height': 'px',

		'border-radius': 'px',
		'border-width': 'px',

		'margin-left': 'px',
		'margin-top': 'px',
		'margin-right': 'px',
		'margin-bottom': 'px'
	}

	var rules = []
	for(var name in this._styles) {
		var value = this._styles[name]
		var rule = []

		var prefixedName = this._context.getPrefixedName(name)
		rule.push(prefixedName !== false? prefixedName: name)
		if (Array.isArray(value))
			value = value.join(',')

		var unit = (typeof value === 'number')? cssUnits[name] || '': ''
		value += unit

		var prefixedValue = window.Modernizr.prefixedCSSValue(name, value)
		rule.push(prefixedValue !== false? prefixedValue: value)

		rules.push(rule.join(':'))
	}

	this.dom.setAttribute('style', rules.join(';'))
}

exports.Element.prototype.append = function(el) {
	this.dom.appendChild((el instanceof Node)? el: el.dom)
}

exports.Element.prototype.remove = function() {
	this.dom.remove()
}

exports.Window = function(context, dom) {
	_globals.core.EventEmitter.apply(this)
	this._context = context
	this.dom = dom

	registerGenericListener(this)
}

exports.Window.prototype = Object.create(_globals.core.EventEmitter.prototype)
exports.Window.prototype.constructor = exports.Window

exports.Window.prototype.width = function() {
	return this.dom.innerWidth
}

exports.Window.prototype.height = function() {
	return this.dom.innerHeight
}

exports.getElement = function(tag) {
	var tags = document.getElementsByTagName(tag)
	if (tags.length != 1)
		throw new Error('no tag ' + tag + '/multiple tags')
	return new exports.Element(this, tags[0])
}
<commit_msg>setHtml returns element children<commit_after>/**
 * @constructor
 */

var registerGenericListener = function(target) {
	target.onListener('',
		function(name) {
			//log('registering generic event', name)
			var callback = function() {
				target.emit(name)
			}
			target.dom.addEventListener(name, callback)
		},
		function(name) {
			//fixme: implement removing callback
			//return remove callback from first callback?
		}
	)
}

exports.Element = function(context, dom) {
	_globals.core.EventEmitter.apply(this)
	this._context = context
	this.dom = dom
	this._fragment = []
	this._styles = {}

	registerGenericListener(this)
}

exports.Element.prototype = Object.create(_globals.core.EventEmitter.prototype)
exports.Element.prototype.constructor = exports.Element

exports.Element.prototype.addClass = function(cls) {
	this.dom.classList.add(cls)
}

exports.Element.prototype.setHtml = function(html) {
	var dom = this.dom
	this._fragment.forEach(function(node) { dom.removeChild(node) })
	this._fragment = []

	if (html === '')
		return

	var fragment = document.createDocumentFragment()
	var temp = document.createElement('div')

	temp.innerHTML = html
	while (temp.firstChild) {
		this._fragment.push(temp.firstChild)
		fragment.appendChild(temp.firstChild)
	}
	dom.appendChild(fragment)
	return dom.children
}

exports.Element.prototype.width = function() {
	return this.dom.clientWidth
}

exports.Element.prototype.height = function() {
	return this.dom.clientHeight
}

exports.Element.prototype.fullWidth = function() {
	return this.dom.scrollWidth
}

exports.Element.prototype.fullHeight = function() {
	return this.dom.scrollHeight
}

exports.Element.prototype.style = function(name, style) {
	if (style !== undefined) {
		if (style !== '') //fixme: replace it with explicit 'undefined' syntax
			this._styles[name] = style
		else
			delete this._styles[name]
		this.updateStyle()
	} else if (name instanceof Object) { //style({ }) assignment
		for(var k in name) {
			var value = name[k]
			if (value !== '') //fixme: replace it with explicit 'undefined' syntax
				this._styles[k] = value
			else
				delete this._styles[k]
		}
		this.updateStyle()
	}
	else
		return this._styles[name]
}

exports.Element.prototype.setAttribute = function(name, value) {
	this.dom.setAttribute(name, value)
}

exports.Element.prototype.updateStyle = function() {
	var element = this.dom
	if (!element)
		return

	/** @const */
	var cssUnits = {
		'left': 'px',
		'top': 'px',
		'width': 'px',
		'height': 'px',

		'border-radius': 'px',
		'border-width': 'px',

		'margin-left': 'px',
		'margin-top': 'px',
		'margin-right': 'px',
		'margin-bottom': 'px'
	}

	var rules = []
	for(var name in this._styles) {
		var value = this._styles[name]
		var rule = []

		var prefixedName = this._context.getPrefixedName(name)
		rule.push(prefixedName !== false? prefixedName: name)
		if (Array.isArray(value))
			value = value.join(',')

		var unit = (typeof value === 'number')? cssUnits[name] || '': ''
		value += unit

		var prefixedValue = window.Modernizr.prefixedCSSValue(name, value)
		rule.push(prefixedValue !== false? prefixedValue: value)

		rules.push(rule.join(':'))
	}

	this.dom.setAttribute('style', rules.join(';'))
}

exports.Element.prototype.append = function(el) {
	this.dom.appendChild((el instanceof Node)? el: el.dom)
}

exports.Element.prototype.remove = function() {
	this.dom.remove()
}

exports.Window = function(context, dom) {
	_globals.core.EventEmitter.apply(this)
	this._context = context
	this.dom = dom

	registerGenericListener(this)
}

exports.Window.prototype = Object.create(_globals.core.EventEmitter.prototype)
exports.Window.prototype.constructor = exports.Window

exports.Window.prototype.width = function() {
	return this.dom.innerWidth
}

exports.Window.prototype.height = function() {
	return this.dom.innerHeight
}

exports.getElement = function(tag) {
	var tags = document.getElementsByTagName(tag)
	if (tags.length != 1)
		throw new Error('no tag ' + tag + '/multiple tags')
	return new exports.Element(this, tags[0])
}
<|endoftext|>


<commit_before>'use strict';
var U = require('./utils');

exports.attributeDefinitions = function attributeDefinitions(attrs) {
	attrs = attrs || Object.create(null);

	return Object.keys(attrs).map(function (key) {
		var type = attrs[key];
		if (!U.isString(type)) {
			throw new Error('DynamoDB Engine expects key value (type) to ' +
				'be a String.');
		}
		type = type.slice(0, 1).toUpperCase();
		if (['S', 'N', 'B'].indexOf(type) === -1) {
			throw new Error('DynamoDB Engine expects key value (type) to ' +
				'be "String", "Number", or "Boolean');
		}
		return {
			AttributeName: key,
			AttributeType: type
		};
	});
};

exports.keySchema = function keySchema(keys, attributes) {
	keys = keys || Object.create(null);
	var keySchema = [];

	if (!keys.hash && !keys.range) {
		throw new Error('DynamoDB Engine expects keys.hash and/or keys.range');
	}

	if (keys.hash) {
		if (!U.isString(keys.hash)) {
			throw new Error('DynamoDB Engine expects keys.hash to be a String.');
		}
		if (!U.find(attributes, 'AttributeName', keys.hash)) {
			throw new Error('DynamoDB requires attribute names in hash key also ' +
				'be defined in attributes');
		}
		keySchema.push({
			AttributeName: keys.hash,
			KeyType: 'HASH'
		});
	}

	if (keys.range) {
		if (!U.isString(keys.range)) {
			throw new Error('DynamoDB Engine expects keys.range to be a String.');
		}
		if (!U.find(attributes, 'AttributeName', keys.range)) {
			throw new Error('DynamoDB requires attribute names in range key also ' +
				'be defined in attributes');
		}
		keySchema.push({
			AttributeName: keys.range,
			KeyType: 'RANGE'
		});
	}

	return keySchema;
};

exports.valueDefinition = function valueDefinition(obj) {
	switch (typeof obj) {
		case 'string':
			return {S: obj};
		case 'number':
			return {N: obj};
		case 'boolean':
			return {B: obj};
		default:
			throw new Error('DynamoDB Engine epxects values to be ' +
				'String, Number, or Boolean');
	}
};

// record.id
// record.data
// options.idAttribute
exports.serializeRecord = function serializeRecord(attrs) {
	return Object.keys(attrs).reduce(function (rec, key) {
		var val = exports.typeCast(attrs[key]);
		if (val) {
			rec[key] = val;
		}
		return rec;
	}, {});
};

exports.typeCast = function typeCast(obj) {
	switch (typeof obj) {
		case 'string':
			if (obj.length === 0) {
				throw new TypeError('Cannot set empty string attributes on DynamoDB.');
			}
			return {S: obj};
		case 'number':
			if (isNaN(obj)) {
				throw new TypeError('Cannot set NaN as an attribute on DynamoDB.');
			}
			return {N: obj.toString()};
		case 'boolean':
			return {BOOL: obj};
		case 'function':
			throw new TypeError('Cannot set a function as an attribute on DynamoDB.');
		case 'undefined':
			break;
		default:
			if (!obj) {
				return {NULL: true};
			}
			return Array.isArray(obj) ?
				exports.typeCastArray(obj) :
				exports.typeCastObject(obj);
	}
};

exports.typeCastArray = function typeCastArray(obj) {
	if (!obj.length) {
		return {NULL: true};
	}

	var rv = {};
	var type = typeof obj[0];
	var key;

	// We only accept String Lists or Number Lists.
	if (type === 'string') {
		key = 'SS';
	} else if (type === 'number') {
		key = 'NS';
	} else {
		throw new TypeError('Only String or Number Lists (not ' + type +
												') may be defined in DynamoDB Engine.');
	}

	rv[key] = obj.map(function (val) {
		if (typeof val !== type) {
			throw new TypeError('All values in a String or Number List must be of ' +
													'the same type in DynamoDB Engine.');
		}
		return val;
	});

	return rv;
};

exports.typeCastObject = function typeCastObject(obj) {
	var keys = Object.keys(obj);
	var rv = {M: {}};
	if (!keys.length) {
		return rv;
	}

	rv.M = keys.reduce(function (M, key) {
		var type = typeof obj[key];
		var val = obj[key];
		switch (type) {
			case 'string':
				M[key] = {S: val};
				break;
			case 'number':
				M[key] = {N: val};
				break;
			case 'boolean':
				M[key] = {BOOL: val};
				break;
			default:
				throw new TypeError('Only String, Number or Boolean attributes ' +
														'(not ' + type + ') may be defined on Mixed ' +
														'Objects in DynamoDB Engine.');
		}
		return M;
	}, rv.M);

	return rv;
};

exports.deserializeData = function deserializeData(obj) {
	return Object.keys(obj).reduce(function (rv, key) {
		var val = obj[key];
		if (val.hasOwnProperty('S')) {
			rv[key] = val.S.toString();
		} else if (val.hasOwnProperty('N')) {
			rv[key] = val.N;
		} else if (val.SS || val.NS) {
			rv[key] = val.SS || val.NS;
		} else if (val.hasOwnProperty('BOOL')) {
			rv[key] = Boolean(val.BOOL);
		} else if (val.hasOwnProperty('M')) {
			rv[key] = exports.deserializeData(val.M);
		} else if (val.hasOwnProperty('NULL')) {
			rv[key] = null;
		}
		return rv;
	}, Object.create(null));
};

exports.isResourceNotFoundException = function (err) {
	return err && err.code === 'ResourceNotFoundException';
};

exports.isConditionalFailedException = function (err) {
	return (err && err.code === 'ConditionalCheckFailedException');
};

exports.isProvisionedThroughputExceededException = function (err) {
	return err && err.code === 'ProvisionedThroughputExceededException';
};

exports.isTableExistsException = function (err) {
	return (err &&
		err.code === 'ResourceInUseException' &&
		/already\sexists/.test(err.message));
};

exports.isNonExistentTableException = function (err) {
	return (err &&
		err.code === 'ResourceNotFoundException' &&
		/non-existent\stable/.test(err.message));
};
<commit_msg>Update DynamoDB Class.<commit_after>'use strict';
var U = require('lodash');
var Promise = require('bluebird');
var AWS = require('aws-sdk');
var errors = require('./errors');
var ThroughputExceededError = errors.get('ThroughputExceededError');
var NonExistentTableError = errors.get('NonExistentTableError');
var TableExistsError = errors.get('TableExistsError');
var ConditionFailedError = errors.get('ConditionFailedError');
var DynamoDBError = errors.get('DynamoDBError');
var NotFoundError = errors.get('NotFoundError');

function DynamoDB() {}

module.exports = DynamoDB;

U.extend(DynamoDB.prototype, {
	// spec.accessKeyId
	// spec.secretAccessKey
	// spec.region
	// spec.endpoint
	// spec.tablePrefix
	initialize: function (spec) {
		Object.defineProperties(this, {
			api: {
				enumerable: true,
				value: DynamoDB.createAWSDynamoDB(spec)
			},
			tablePrefix: {
				enumerable: true,
				value: spec.tablePrefix
			}
		});
		return this;
	},

	table: function (type) {
		return this.tablePrefix + '_' + type + '_entities';
	},

	relationTable: function () {
		return this.tablePrefix + '_relations';
	},

	createTable: function (params) {
		var api = this.api;
		return new Promise(function (resolve, reject) {
			var inFlight = false;

			var waitFor = {TableName: params.TableName};
			api.waitFor('tableExists', waitFor, function (err, res) {
				if (err) {
					return reject(new DynamoDBError(err));
				}
				if (inFlight) {
					resolve(res.Table);
				}
			});

			api.createTable(params, function (err) {
				inFlight = true;
				if (DynamoDB.isTableExistsException(err)) {
					reject(new TableExistsError(err.message));
				} else if (err) {
					reject(new DynamoDBError(err));
				}
			});
		});
	},

	getItem: function (params) {
		var api = this.api;
		return new Promise(function (resolve, reject) {
			api.getItem(params, function getItemCallback(err, res) {
				if (DynamoDB.isProvisionedThroughputExceededException(err)) {
					reject(new ThroughputExceededError(err.message));
				} else if (DynamoDB.isNonExistentTableException(err)) {
					reject(new NonExistentTableError(err.message));
				} else if (err) {
					reject(new DynamoDBError(err));
				} else if (res) {
					return resolve(res);
				}
				reject(new NotFoundError('Could not find entity'));
			});
		});
	},

	putItem: function (params) {
		var api = this.api;
		return new Promise(function (resolve, reject) {
			api.putItem(params, function putItemCallback(err) {
				if (DynamoDB.isProvisionedThroughputExceededException(err)) {
					reject(new ThroughputExceededError(err.message));
				} else if (DynamoDB.isNonExistentTableException(err)) {
					reject(new NonExistentTableError(err.message));
				} else if (DynamoDB.isConditionalFailedException(err)) {
					reject(new ConditionFailedError(err.message));
				} else if (err) {
					return reject(new DynamoDBError(err));
				}
				resolve(true);
			});
		});
	},

	deleteItem: function (params) {
		var api = this.api;
		return new Promise(function (resolve, reject) {
			api.deleteItem(params, function deleteItemCallback(err, res) {
				if (DynamoDB.isProvisionedThroughputExceededException(err)) {
					reject(new ThroughputExceededError(err.message));
				} else if (DynamoDB.isNonExistentTableException(err)) {
					reject(new NonExistentTableError(err.message));
				} else if (err) {
					reject(new DynamoDBError(err));
				} else if (res) {
					return resolve(res);
				}
				reject(new NotFoundError('Could not find entity'));
			});
		});
	},

	query: function (params) {
		var api = this.api;
		return new Promise(function (resolve, reject) {
			api.query(params, function getItemCallback(err, res) {
				if (DynamoDB.isProvisionedThroughputExceededException(err)) {
					reject(new ThroughputExceededError(err.message));
				} else if (DynamoDB.isNonExistentTableException(err)) {
					reject(new NonExistentTableError(err.message));
				} else if (err) {
					reject(new DynamoDBError(err));
				}
				resolve(res);
			});
		});
	}
});

// spec.accessKeyId
// spec.secretAccessKey
// spec.region
// spec.endpoint
// spec.tablePrefix
DynamoDB.create = function (spec) {
	var obj = new DynamoDB();
	return obj.initialize(spec);
};

// spec.accessKeyId
// spec.secretAccessKey
// spec.region
// spec.endpoint
DynamoDB.createAWSDynamoDB = function createAWSDynamoDB(options) {
	var awsOptions = {
		accessKeyId: options.accessKeyId,
		secretAccessKey: options.secretAccessKey,
		region: options.region,
		apiVersion: options.apiVersion || '2012-08-10'
	};
	if (options.endpoint) {
		awsOptions.endpoint = options.endpoint;
	}

	return new AWS.DynamoDB(awsOptions);
};

DynamoDB.serializeItem = function serializeItem(attrs) {
	return Object.keys(attrs).reduce(function (rec, key) {
		var val = DynamoDB.typeCast(attrs[key]);
		if (val) {
			rec[key] = val;
		}
		return rec;
	}, {});
};

DynamoDB.serializeRelation = function serializeRelation(args) {
	return DynamoDB.serializeItem({
		subject: args.subjectId,
		predicate: args.object.type,
		object: args.object
	});
};

DynamoDB.deserializeItem = function deserializeItem(obj) {
	return Object.keys(obj).reduce(function (rv, key) {
		var val = obj[key];
		if (val.hasOwnProperty('S')) {
			rv[key] = val.S.toString();
		} else if (val.hasOwnProperty('N')) {
			rv[key] = val.N;
		} else if (val.SS || val.NS) {
			rv[key] = val.SS || val.NS;
		} else if (val.hasOwnProperty('BOOL')) {
			rv[key] = Boolean(val.BOOL);
		} else if (val.hasOwnProperty('M')) {
			rv[key] = DynamoDB.deserializeItem(val.M);
		} else if (val.hasOwnProperty('NULL')) {
			rv[key] = null;
		}
		return rv;
	}, Object.create(null));
};

DynamoDB.typeCast = function typeCast(obj) {
	switch (typeof obj) {
		case 'string':
			if (obj.length === 0) {
				throw new TypeError('Cannot set empty string attributes on DynamoDB.');
			}
			return {S: obj};
		case 'number':
			if (isNaN(obj)) {
				throw new TypeError('Cannot set NaN as an attribute on DynamoDB.');
			}
			return {N: obj.toString()};
		case 'boolean':
			return {BOOL: obj};
		case 'function':
			throw new TypeError('Cannot set a function as an attribute on DynamoDB.');
		case 'undefined':
			break;
		default:
			if (!obj) {
				return {NULL: true};
			}
			return Array.isArray(obj) ?
				DynamoDB.typeCastArray(obj) :
				DynamoDB.typeCastObject(obj);
	}
};

DynamoDB.typeCastArray = function typeCastArray(obj) {
	if (!obj.length) {
		return {NULL: true};
	}

	var rv = {};
	var type = typeof obj[0];
	var key;

	if (type === 'string') {
		key = 'SS';
	} else if (type === 'number') {
		key = 'NS';
	} else {
		throw new TypeError('Only String or Number Lists (not ' + type +
												') may be defined in DynamoDB Engine.');
	}

	rv[key] = obj.map(function (val) {
		if (typeof val !== type) {
			throw new TypeError('All values in a String or Number List must be of ' +
													'the same type in DynamoDB Engine.');
		}
		return val;
	});

	return rv;
};

DynamoDB.typeCastObject = function typeCastObject(obj) {
	var keys = Object.keys(obj);
	var rv = {M: {}};
	if (!keys.length) {
		return rv;
	}

	rv.M = keys.reduce(function (M, key) {
		var type = typeof obj[key];
		var val = obj[key];
		switch (type) {
			case 'string':
				M[key] = {S: val};
				break;
			case 'number':
				M[key] = {N: val};
				break;
			case 'boolean':
				M[key] = {BOOL: val};
				break;
			default:
				throw new TypeError('Only String, Number or Boolean attributes (not ' +
					type + ') may be defined on Mixed Objects in DynamoDB Engine.');
		}
		return M;
	}, rv.M);

	return rv;
};

DynamoDB.serializeKey = function serializeKey(obj) {
	return Object.keys(obj).reduce(function (keys, key) {
		keys[key] = DynamoDB.typeCastKey(obj[key]);
		return keys;
	}, {});
};

DynamoDB.typeCastKey = function typeCastKey(obj) {
	var type = typeof obj;
	switch (type) {
		case 'string':
			return {S: obj};
		case 'number':
			return {N: obj};
		case 'boolean':
			return {B: obj};
		default:
			throw new TypeError('Only String, Number or Boolean attributes (not ' +
				type + ') may be defined on keys in DynamoDB Engine.');
	}
};

DynamoDB.deserializeKey = function deserializeKey(obj) {
	return Object.keys(obj).reduce(function (rv, key) {
		var val = obj[key];
		if (U.has(val, 'S')) {
			rv[key] = val.S.toString();
		} else if (U.has(val, 'N')) {
			rv[key] = val.N;
		} else if (U.has(val, 'B')) {
			rv[key] = Boolean(val.B);
		}
		return rv;
	}, Object.create(null));
};

DynamoDB.keySchema = function keySchema(keys, attrs) {
	keys = keys || Object.create(null);
	var keySchema = [];

	if (!keys.hash && !keys.range) {
		throw new Error('DynamoDB Engine expects keys.hash and/or keys.range');
	}

	if (keys.hash) {
		if (!U.isString(keys.hash)) {
			throw new Error('DynamoDB Engine expects keys.hash to be a String.');
		}
		if (!U.find(attrs, 'AttributeName', keys.hash)) {
			throw new Error('DynamoDB requires attribute names in hash key also ' +
				'be defined in attributes');
		}
		keySchema.push({
			AttributeName: keys.hash,
			KeyType: 'HASH'
		});
	}

	if (keys.range) {
		if (!U.isString(keys.range)) {
			throw new Error('DynamoDB Engine expects keys.range to be a String.');
		}
		if (!U.find(attrs, 'AttributeName', keys.range)) {
			throw new Error('DynamoDB requires attribute names in range key also ' +
				'be defined in attributes');
		}
		keySchema.push({
			AttributeName: keys.range,
			KeyType: 'RANGE'
		});
	}

	return keySchema;
};

DynamoDB.isResourceNotFoundException = function (err) {
	return err && err.code === 'ResourceNotFoundException';
};

DynamoDB.isConditionalFailedException = function (err) {
	return (err && err.code === 'ConditionalCheckFailedException');
};

DynamoDB.isProvisionedThroughputExceededException = function (err) {
	return err && err.code === 'ProvisionedThroughputExceededException';
};

DynamoDB.isTableExistsException = function (err) {
	return (err &&
		err.code === 'ResourceInUseException' &&
		/already\sexists/.test(err.message));
};

DynamoDB.isNonExistentTableException = function (err) {
	return (err &&
		err.code === 'ResourceNotFoundException' &&
		/non-existent\stable/.test(err.message));
};
<|endoftext|>


<commit_before>// @flow weak
/* eslint-env mocha */

import { assert } from 'chai';
import schedule from './schedule';
import { newId, easeCubicInOut } from './helpers';

const preset = {
  time: null,
  delay: 0,
  duration: 250,
  ease: easeCubicInOut,
};

describe('schedule', () => {
  it('should add a TRANSITION_SCHEDULES proprtty to node ', () => {
    const node = { rect: {} };

    schedule(node, 'rect', newId(), preset, []);
    assert.isObject(node.TRANSITION_SCHEDULES, 'should be true');
  });
});
<commit_msg>fix typo<commit_after>// @flow weak
/* eslint-env mocha */

import { assert } from 'chai';
import schedule from './schedule';
import { newId, easeCubicInOut } from './helpers';

const preset = {
  time: null,
  delay: 0,
  duration: 250,
  ease: easeCubicInOut,
};

describe('schedule', () => {
  it('should add a TRANSITION_SCHEDULES property to node ', () => {
    const node = { rect: {} };

    schedule(node, 'rect', newId(), preset, []);
    assert.isObject(node.TRANSITION_SCHEDULES, 'should be true');
  });
});
<|endoftext|>


<commit_before>
"use strict"

function isNameChar(ch) {
    if (ch >= 'a' && ch <= 'z')
        return true;
    if (ch >= 'A' && ch <= 'Z')
        return true;

    if (ch >= '0' && ch <= '9')
        return true;

    return false;
}

function isLetter(ch) {
    if (ch >= 'a' && ch <= 'z')
        return true;
    if (ch >= 'A' && ch <= 'Z')
        return true;

    return false;
}

function parseName(text, offset, name) {
    var token = {
        text: text,
        offset: offset
    };

    var length = 1;

    if (!isLetter(text[offset]))
        throw new Error("Invalid " + name + " name");

    while (isNameChar(text[offset + length]))
        length++;

    token.length = length;

    return token;
}

function findClose(text, offset) {
    var nextgt = text.indexOf('>', offset);

    if (nextgt < 0)
        throw new Error('Unclosed element');

    var nextlt = text.indexOf('<', offset);

    if (nextlt >= 0 && nextlt < nextgt)
        throw new Error('Invalid element');

    return nextgt;
}

function findOpen(text, offset) {
    var nextlt = text.indexOf('<', offset);
    var nextgt = text.indexOf('>', offset);

    if (nextgt >= 0 && nextgt < nextlt)
        throw new Error('Invalid element');

    return nextlt;
}

function Element(text, offset) {
    offset = offset || 0;

    offset = findOpen(text, offset);

    var tag = parseName(text, offset + 1, 'tag');

    var nextgt = findClose(text, tag.offset + tag.length);

    var nextclose = text.indexOf('</', nextgt + 1);
    var length = nextclose + 2 + tag.length + 1 - offset;

    this.tag = function () {
        return text.substring(tag.offset, tag.offset + tag.length);
    }

    this.xml = function () {
        return text.substring(offset, offset + length);
    }
}

function createElement(text, offset) {
    return new Element(text, offset);
}

module.exports = {
    element: createElement
}

<commit_msg>internal refactor detecting close tag<commit_after>
"use strict"

function isNameChar(ch) {
    if (ch >= 'a' && ch <= 'z')
        return true;
    if (ch >= 'A' && ch <= 'Z')
        return true;

    if (ch >= '0' && ch <= '9')
        return true;

    return false;
}

function isLetter(ch) {
    if (ch >= 'a' && ch <= 'z')
        return true;
    if (ch >= 'A' && ch <= 'Z')
        return true;

    return false;
}

function parseName(text, offset, name) {
    var token = {
        text: text,
        offset: offset
    };

    var length = 1;

    if (!isLetter(text[offset]))
        throw new Error("Invalid " + name + " name");

    while (isNameChar(text[offset + length]))
        length++;

    token.length = length;

    return token;
}

function findClose(text, offset) {
    var nextgt = text.indexOf('>', offset);

    if (nextgt < 0)
        throw new Error('Unclosed element');

    var nextlt = text.indexOf('<', offset);

    if (nextlt >= 0 && nextlt < nextgt)
        throw new Error('Invalid element');

    return nextgt;
}

function findOpen(text, offset) {
    var nextlt = text.indexOf('<', offset);
    var nextgt = text.indexOf('>', offset);

    if (nextgt >= 0 && nextgt < nextlt)
        throw new Error('Invalid element');

    return nextlt;
}

function Element(text, offset) {
    offset = offset || 0;
    offset = findOpen(text, offset);

    var tag = parseName(text, offset + 1, 'tag');

    var nextgt = findClose(text, tag.offset + tag.length);

    var nextlt = findOpen(text, nextgt + 1);
    var elements = [];

    while (nextlt >= 0) {
        if (text[nextlt + 1] == '/')
            break;

        var element = new Element(text, nextlt);

        nextlt = findOpen(text, element.offset() + element.length())
    }

    if (nextlt < 0)
        throw new Error('Unclosed element');

    var length = nextlt + 2 + tag.length + 1 - offset;

    this.tag = function () {
        return text.substring(tag.offset, tag.offset + tag.length);
    }

    this.xml = function () {
        return text.substring(offset, offset + length);
    }

    this.offset = function () { return offset; }

    this.length = function () { return length; }
}

function createElement(text, offset) {
    return new Element(text, offset);
}

module.exports = {
    element: createElement
}

<|endoftext|>