????JFIF??x?x????'
Server IP : 79.136.114.73 / Your IP : 18.224.32.173 Web Server : Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.29 OpenSSL/1.0.1f System : Linux b8009 3.13.0-170-generic #220-Ubuntu SMP Thu May 9 12:40:49 UTC 2019 x86_64 User : www-data ( 33) PHP Version : 5.5.9-1ubuntu4.29 Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority, MySQL : ON | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /var/www/www.astacus.se/wp-content/plugins/cornerstone/assets/dist-app/js/ |
Upload File : |
/* jshint ignore:start */ window.EmberENV = {"FEATURES":{}}; var runningTests = false; /* jshint ignore:end */ ;var loader, define, requireModule, require, requirejs; (function (global) { 'use strict'; var heimdall = global.heimdall; function dict() { var obj = Object.create(null); obj['__'] = undefined; delete obj['__']; return obj; } // Save off the original values of these globals, so we can restore them if someone asks us to var oldGlobals = { loader: loader, define: define, requireModule: requireModule, require: require, requirejs: requirejs }; requirejs = require = requireModule = function (id) { var pending = []; var mod = findModule(id, '(require)', pending); for (var i = pending.length - 1; i >= 0; i--) { pending[i].exports(); } return mod.module.exports; }; loader = { noConflict: function (aliases) { var oldName, newName; for (oldName in aliases) { if (aliases.hasOwnProperty(oldName)) { if (oldGlobals.hasOwnProperty(oldName)) { newName = aliases[oldName]; global[newName] = global[oldName]; global[oldName] = oldGlobals[oldName]; } } } } }; var registry = dict(); var seen = dict(); var uuid = 0; function unsupportedModule(length) { throw new Error('an unsupported module was defined, expected `define(id, deps, module)` instead got: `' + length + '` arguments to define`'); } var defaultDeps = ['require', 'exports', 'module']; function Module(id, deps, callback, alias) { this.uuid = uuid++; this.id = id; this.deps = !deps.length && callback.length ? defaultDeps : deps; this.module = { exports: {} }; this.callback = callback; this.hasExportsAsDep = false; this.isAlias = alias; this.reified = new Array(deps.length); /* Each module normally passes through these states, in order: new : initial state pending : this module is scheduled to be executed reifying : this module's dependencies are being executed reified : this module's dependencies finished executing successfully errored : this module's dependencies failed to execute finalized : this module executed successfully */ this.state = 'new'; } Module.prototype.makeDefaultExport = function () { var exports = this.module.exports; if (exports !== null && (typeof exports === 'object' || typeof exports === 'function') && exports['default'] === undefined && Object.isExtensible(exports)) { exports['default'] = exports; } }; Module.prototype.exports = function () { // if finalized, there is no work to do. If reifying, there is a // circular dependency so we must return our (partial) exports. if (this.state === 'finalized' || this.state === 'reifying') { return this.module.exports; } if (loader.wrapModules) { this.callback = loader.wrapModules(this.id, this.callback); } this.reify(); var result = this.callback.apply(this, this.reified); this.reified.length = 0; this.state = 'finalized'; if (!(this.hasExportsAsDep && result === undefined)) { this.module.exports = result; } this.makeDefaultExport(); return this.module.exports; }; Module.prototype.unsee = function () { this.state = 'new'; this.module = { exports: {} }; }; Module.prototype.reify = function () { if (this.state === 'reified') { return; } this.state = 'reifying'; try { this.reified = this._reify(); this.state = 'reified'; } finally { if (this.state === 'reifying') { this.state = 'errored'; } } }; Module.prototype._reify = function () { var reified = this.reified.slice(); for (var i = 0; i < reified.length; i++) { var mod = reified[i]; reified[i] = mod.exports ? mod.exports : mod.module.exports(); } return reified; }; Module.prototype.findDeps = function (pending) { if (this.state !== 'new') { return; } this.state = 'pending'; var deps = this.deps; for (var i = 0; i < deps.length; i++) { var dep = deps[i]; var entry = this.reified[i] = { exports: undefined, module: undefined }; if (dep === 'exports') { this.hasExportsAsDep = true; entry.exports = this.module.exports; } else if (dep === 'require') { entry.exports = this.makeRequire(); } else if (dep === 'module') { entry.exports = this.module; } else { entry.module = findModule(resolve(dep, this.id), this.id, pending); } } }; Module.prototype.makeRequire = function () { var id = this.id; var r = function (dep) { return require(resolve(dep, id)); }; r['default'] = r; r.moduleId = id; r.has = function (dep) { return has(resolve(dep, id)); }; return r; }; define = function (id, deps, callback) { var module = registry[id]; // If a module for this id has already been defined and is in any state // other than `new` (meaning it has been or is currently being required), // then we return early to avoid redefinition. if (module && module.state !== 'new') { return; } if (arguments.length < 2) { unsupportedModule(arguments.length); } if (!Array.isArray(deps)) { callback = deps; deps = []; } if (callback instanceof Alias) { registry[id] = new Module(callback.id, deps, callback, true); } else { registry[id] = new Module(id, deps, callback, false); } }; define.exports = function (name, defaultExport) { var module = registry[name]; // If a module for this name has already been defined and is in any state // other than `new` (meaning it has been or is currently being required), // then we return early to avoid redefinition. if (module && module.state !== 'new') { return; } module = new Module(name, [], noop, null); module.module.exports = defaultExport; module.state = 'finalized'; registry[name] = module; return module; }; function noop() {} // we don't support all of AMD // define.amd = {}; function Alias(id) { this.id = id; } define.alias = function (id, target) { if (arguments.length === 2) { return define(target, new Alias(id)); } return new Alias(id); }; function missingModule(id, referrer) { throw new Error('Could not find module `' + id + '` imported from `' + referrer + '`'); } function findModule(id, referrer, pending) { var mod = registry[id] || registry[id + '/index']; while (mod && mod.isAlias) { mod = registry[mod.id]; } if (!mod) { missingModule(id, referrer); } if (pending && mod.state !== 'pending' && mod.state !== 'finalized') { mod.findDeps(pending); pending.push(mod); } return mod; } function resolve(child, id) { if (child.charAt(0) !== '.') { return child; } var parts = child.split('/'); var nameParts = id.split('/'); var parentBase = nameParts.slice(0, -1); for (var i = 0, l = parts.length; i < l; i++) { var part = parts[i]; if (part === '..') { if (parentBase.length === 0) { throw new Error('Cannot access parent module of root'); } parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join('/'); } function has(id) { return !!(registry[id] || registry[id + '/index']); } requirejs.entries = requirejs._eak_seen = registry; requirejs.has = has; requirejs.unsee = function (id) { findModule(id, '(unsee)', false).unsee(); }; requirejs.clear = function () { requirejs.entries = requirejs._eak_seen = registry = dict(); seen = dict(); }; // This code primes the JS engine for good performance by warming the // JIT compiler for these functions. define('foo', function () {}); define('foo/bar', [], function () {}); define('foo/asdf', ['module', 'exports', 'require'], function (module, exports, require) { if (require.has('foo/bar')) { require('foo/bar'); } }); define('foo/baz', [], define.alias('foo')); define('foo/quz', define.alias('foo')); define.alias('foo', 'foo/qux'); define('foo/bar', ['foo', './quz', './baz', './asdf', './bar', '../foo'], function () {}); define('foo/main', ['foo/bar'], function () {}); define.exports('foo/exports', {}); require('foo/exports'); require('foo/main'); require.unsee('foo/bar'); requirejs.clear(); if (typeof exports === 'object' && typeof module === 'object' && module.exports) { module.exports = { require: require, define: define }; } })(this); ;;(function() { /*! * @overview Ember - JavaScript Application Framework * @copyright Copyright 2011-2016 Tilde Inc. and contributors * Portions Copyright 2006-2011 Strobe Inc. * Portions Copyright 2008-2011 Apple Inc. All rights reserved. * @license Licensed under MIT license * See https://raw.github.com/emberjs/ember.js/master/LICENSE * @version 2.8.0 */ var enifed, requireModule, require, Ember; var mainContext = this; (function() { var isNode = typeof window === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; if (!isNode) { Ember = this.Ember = this.Ember || {}; } if (typeof Ember === 'undefined') { Ember = {}; } if (typeof Ember.__loader === 'undefined') { var registry = {}; var seen = {}; enifed = function(name, deps, callback) { var value = { }; if (!callback) { value.deps = []; value.callback = deps; } else { value.deps = deps; value.callback = callback; } registry[name] = value; }; require = requireModule = function(name) { return internalRequire(name, null); }; // setup `require` module require['default'] = require; require.has = function registryHas(moduleName) { return !!registry[moduleName] || !!registry[moduleName + '/index']; }; function missingModule(name, referrerName) { if (referrerName) { throw new Error('Could not find module ' + name + ' required by: ' + referrerName); } else { throw new Error('Could not find module ' + name); } } function internalRequire(_name, referrerName) { var name = _name; var mod = registry[name]; if (!mod) { name = name + '/index'; mod = registry[name]; } var exports = seen[name]; if (exports !== undefined) { return exports; } exports = seen[name] = {}; if (!mod) { missingModule(_name, referrerName); } var deps = mod.deps; var callback = mod.callback; var reified = new Array(deps.length); for (var i = 0; i < deps.length; i++) { if (deps[i] === 'exports') { reified[i] = exports; } else if (deps[i] === 'require') { reified[i] = require; } else { reified[i] = internalRequire(deps[i], name); } } callback.apply(this, reified); return exports; } requireModule._eak_seen = registry; Ember.__loader = { define: enifed, require: require, registry: registry }; } else { enifed = Ember.__loader.define; require = requireModule = Ember.__loader.require; } })(); enifed('backburner', ['exports', 'backburner/utils', 'backburner/platform', 'backburner/binary-search', 'backburner/deferred-action-queues'], function (exports, _backburnerUtils, _backburnerPlatform, _backburnerBinarySearch, _backburnerDeferredActionQueues) { 'use strict'; exports.default = Backburner; function Backburner(queueNames, options) { this.queueNames = queueNames; this.options = options || {}; if (!this.options.defaultQueue) { this.options.defaultQueue = queueNames[0]; } this.instanceStack = []; this._debouncees = []; this._throttlers = []; this._eventCallbacks = { end: [], begin: [] }; var _this = this; this._boundClearItems = function () { clearItems(); }; this._timerTimeoutId = undefined; this._timers = []; this._platform = this.options._platform || _backburnerPlatform.default; this._boundRunExpiredTimers = function () { _this._runExpiredTimers(); }; } Backburner.prototype = { begin: function () { var options = this.options; var onBegin = options && options.onBegin; var previousInstance = this.currentInstance; if (previousInstance) { this.instanceStack.push(previousInstance); } this.currentInstance = new _backburnerDeferredActionQueues.default(this.queueNames, options); this._trigger('begin', this.currentInstance, previousInstance); if (onBegin) { onBegin(this.currentInstance, previousInstance); } }, end: function () { var options = this.options; var onEnd = options && options.onEnd; var currentInstance = this.currentInstance; var nextInstance = null; // Prevent double-finally bug in Safari 6.0.2 and iOS 6 // This bug appears to be resolved in Safari 6.0.5 and iOS 7 var finallyAlreadyCalled = false; try { currentInstance.flush(); } finally { if (!finallyAlreadyCalled) { finallyAlreadyCalled = true; this.currentInstance = null; if (this.instanceStack.length) { nextInstance = this.instanceStack.pop(); this.currentInstance = nextInstance; } this._trigger('end', currentInstance, nextInstance); if (onEnd) { onEnd(currentInstance, nextInstance); } } } }, /** Trigger an event. Supports up to two arguments. Designed around triggering transition events from one run loop instance to the next, which requires an argument for the first instance and then an argument for the next instance. @private @method _trigger @param {String} eventName @param {any} arg1 @param {any} arg2 */ _trigger: function (eventName, arg1, arg2) { var callbacks = this._eventCallbacks[eventName]; if (callbacks) { for (var i = 0; i < callbacks.length; i++) { callbacks[i](arg1, arg2); } } }, on: function (eventName, callback) { if (typeof callback !== 'function') { throw new TypeError('Callback must be a function'); } var callbacks = this._eventCallbacks[eventName]; if (callbacks) { callbacks.push(callback); } else { throw new TypeError('Cannot on() event "' + eventName + '" because it does not exist'); } }, off: function (eventName, callback) { if (eventName) { var callbacks = this._eventCallbacks[eventName]; var callbackFound = false; if (!callbacks) return; if (callback) { for (var i = 0; i < callbacks.length; i++) { if (callbacks[i] === callback) { callbackFound = true; callbacks.splice(i, 1); i--; } } } if (!callbackFound) { throw new TypeError('Cannot off() callback that does not exist'); } } else { throw new TypeError('Cannot off() event "' + eventName + '" because it does not exist'); } }, run: function () /* target, method, args */{ var length = arguments.length; var method, target, args; if (length === 1) { method = arguments[0]; target = null; } else { target = arguments[0]; method = arguments[1]; } if (_backburnerUtils.isString(method)) { method = target[method]; } if (length > 2) { args = new Array(length - 2); for (var i = 0, l = length - 2; i < l; i++) { args[i] = arguments[i + 2]; } } else { args = []; } var onError = getOnError(this.options); this.begin(); // guard against Safari 6's double-finally bug var didFinally = false; if (onError) { try { return method.apply(target, args); } catch (error) { onError(error); } finally { if (!didFinally) { didFinally = true; this.end(); } } } else { try { return method.apply(target, args); } finally { if (!didFinally) { didFinally = true; this.end(); } } } }, /* Join the passed method with an existing queue and execute immediately, if there isn't one use `Backburner#run`. The join method is like the run method except that it will schedule into an existing queue if one already exists. In either case, the join method will immediately execute the passed in function and return its result. @method join @param {Object} target @param {Function} method The method to be executed @param {any} args The method arguments @return method result */ join: function () /* target, method, args */{ if (!this.currentInstance) { return this.run.apply(this, arguments); } var length = arguments.length; var method, target; if (length === 1) { method = arguments[0]; target = null; } else { target = arguments[0]; method = arguments[1]; } if (_backburnerUtils.isString(method)) { method = target[method]; } if (length === 1) { return method(); } else if (length === 2) { return method.call(target); } else { var args = new Array(length - 2); for (var i = 0, l = length - 2; i < l; i++) { args[i] = arguments[i + 2]; } return method.apply(target, args); } }, /* Defer the passed function to run inside the specified queue. @method defer @param {String} queueName @param {Object} target @param {Function|String} method The method or method name to be executed @param {any} args The method arguments @return method result */ defer: function (queueName /* , target, method, args */) { var length = arguments.length; var method, target, args; if (length === 2) { method = arguments[1]; target = null; } else { target = arguments[1]; method = arguments[2]; } if (_backburnerUtils.isString(method)) { method = target[method]; } var stack = this.DEBUG ? new Error() : undefined; if (length > 3) { args = new Array(length - 3); for (var i = 3; i < length; i++) { args[i - 3] = arguments[i]; } } else { args = undefined; } if (!this.currentInstance) { createAutorun(this); } return this.currentInstance.schedule(queueName, target, method, args, false, stack); }, deferOnce: function (queueName /* , target, method, args */) { var length = arguments.length; var method, target, args; if (length === 2) { method = arguments[1]; target = null; } else { target = arguments[1]; method = arguments[2]; } if (_backburnerUtils.isString(method)) { method = target[method]; } var stack = this.DEBUG ? new Error() : undefined; if (length > 3) { args = new Array(length - 3); for (var i = 3; i < length; i++) { args[i - 3] = arguments[i]; } } else { args = undefined; } if (!this.currentInstance) { createAutorun(this); } return this.currentInstance.schedule(queueName, target, method, args, true, stack); }, setTimeout: function () { var l = arguments.length; var args = new Array(l); for (var x = 0; x < l; x++) { args[x] = arguments[x]; } var length = args.length, method, wait, target, methodOrTarget, methodOrWait, methodOrArgs; if (length === 0) { return; } else if (length === 1) { method = args.shift(); wait = 0; } else if (length === 2) { methodOrTarget = args[0]; methodOrWait = args[1]; if (_backburnerUtils.isFunction(methodOrWait) || _backburnerUtils.isFunction(methodOrTarget[methodOrWait])) { target = args.shift(); method = args.shift(); wait = 0; } else if (_backburnerUtils.isCoercableNumber(methodOrWait)) { method = args.shift(); wait = args.shift(); } else { method = args.shift(); wait = 0; } } else { var last = args[args.length - 1]; if (_backburnerUtils.isCoercableNumber(last)) { wait = args.pop(); } else { wait = 0; } methodOrTarget = args[0]; methodOrArgs = args[1]; if (_backburnerUtils.isFunction(methodOrArgs) || _backburnerUtils.isString(methodOrArgs) && methodOrTarget !== null && methodOrArgs in methodOrTarget) { target = args.shift(); method = args.shift(); } else { method = args.shift(); } } var executeAt = Date.now() + parseInt(wait !== wait ? 0 : wait, 10); if (_backburnerUtils.isString(method)) { method = target[method]; } var onError = getOnError(this.options); function fn() { if (onError) { try { method.apply(target, args); } catch (e) { onError(e); } } else { method.apply(target, args); } } return this._setTimeout(fn, executeAt); }, _setTimeout: function (fn, executeAt) { if (this._timers.length === 0) { this._timers.push(executeAt, fn); this._installTimerTimeout(); return fn; } // find position to insert var i = _backburnerBinarySearch.default(executeAt, this._timers); this._timers.splice(i, 0, executeAt, fn); // we should be the new earliest timer if i == 0 if (i === 0) { this._reinstallTimerTimeout(); } return fn; }, throttle: function (target, method /* , args, wait, [immediate] */) { var backburner = this; var args = new Array(arguments.length); for (var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } var immediate = args.pop(); var wait, throttler, index, timer; if (_backburnerUtils.isNumber(immediate) || _backburnerUtils.isString(immediate)) { wait = immediate; immediate = true; } else { wait = args.pop(); } wait = parseInt(wait, 10); index = findThrottler(target, method, this._throttlers); if (index > -1) { return this._throttlers[index]; } // throttled timer = this._platform.setTimeout(function () { if (!immediate) { backburner.run.apply(backburner, args); } var index = findThrottler(target, method, backburner._throttlers); if (index > -1) { backburner._throttlers.splice(index, 1); } }, wait); if (immediate) { this.run.apply(this, args); } throttler = [target, method, timer]; this._throttlers.push(throttler); return throttler; }, debounce: function (target, method /* , args, wait, [immediate] */) { var backburner = this; var args = new Array(arguments.length); for (var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } var immediate = args.pop(); var wait, index, debouncee, timer; if (_backburnerUtils.isNumber(immediate) || _backburnerUtils.isString(immediate)) { wait = immediate; immediate = false; } else { wait = args.pop(); } wait = parseInt(wait, 10); // Remove debouncee index = findDebouncee(target, method, this._debouncees); if (index > -1) { debouncee = this._debouncees[index]; this._debouncees.splice(index, 1); this._platform.clearTimeout(debouncee[2]); } timer = this._platform.setTimeout(function () { if (!immediate) { backburner.run.apply(backburner, args); } var index = findDebouncee(target, method, backburner._debouncees); if (index > -1) { backburner._debouncees.splice(index, 1); } }, wait); if (immediate && index === -1) { backburner.run.apply(backburner, args); } debouncee = [target, method, timer]; backburner._debouncees.push(debouncee); return debouncee; }, cancelTimers: function () { _backburnerUtils.each(this._throttlers, this._boundClearItems); this._throttlers = []; _backburnerUtils.each(this._debouncees, this._boundClearItems); this._debouncees = []; this._clearTimerTimeout(); this._timers = []; if (this._autorun) { this._platform.clearTimeout(this._autorun); this._autorun = null; } }, hasTimers: function () { return !!this._timers.length || !!this._debouncees.length || !!this._throttlers.length || this._autorun; }, cancel: function (timer) { var timerType = typeof timer; if (timer && timerType === 'object' && timer.queue && timer.method) { // we're cancelling a deferOnce return timer.queue.cancel(timer); } else if (timerType === 'function') { // we're cancelling a setTimeout for (var i = 0, l = this._timers.length; i < l; i += 2) { if (this._timers[i + 1] === timer) { this._timers.splice(i, 2); // remove the two elements if (i === 0) { this._reinstallTimerTimeout(); } return true; } } } else if (Object.prototype.toString.call(timer) === '[object Array]') { // we're cancelling a throttle or debounce return this._cancelItem(findThrottler, this._throttlers, timer) || this._cancelItem(findDebouncee, this._debouncees, timer); } else { return; // timer was null or not a timer } }, _cancelItem: function (findMethod, array, timer) { var item, index; if (timer.length < 3) { return false; } index = findMethod(timer[0], timer[1], array); if (index > -1) { item = array[index]; if (item[2] === timer[2]) { array.splice(index, 1); this._platform.clearTimeout(timer[2]); return true; } } return false; }, _runExpiredTimers: function () { this._timerTimeoutId = undefined; this.run(this, this._scheduleExpiredTimers); }, _scheduleExpiredTimers: function () { var n = Date.now(); var timers = this._timers; var i = 0; var l = timers.length; for (; i < l; i += 2) { var executeAt = timers[i]; var fn = timers[i + 1]; if (executeAt <= n) { this.schedule(this.options.defaultQueue, null, fn); } else { break; } } timers.splice(0, i); this._installTimerTimeout(); }, _reinstallTimerTimeout: function () { this._clearTimerTimeout(); this._installTimerTimeout(); }, _clearTimerTimeout: function () { if (!this._timerTimeoutId) { return; } this._platform.clearTimeout(this._timerTimeoutId); this._timerTimeoutId = undefined; }, _installTimerTimeout: function () { if (!this._timers.length) { return; } var minExpiresAt = this._timers[0]; var n = Date.now(); var wait = Math.max(0, minExpiresAt - n); this._timerTimeoutId = this._platform.setTimeout(this._boundRunExpiredTimers, wait); } }; Backburner.prototype.schedule = Backburner.prototype.defer; Backburner.prototype.scheduleOnce = Backburner.prototype.deferOnce; Backburner.prototype.later = Backburner.prototype.setTimeout; function getOnError(options) { return options.onError || options.onErrorTarget && options.onErrorTarget[options.onErrorMethod]; } function createAutorun(backburner) { backburner.begin(); backburner._autorun = backburner._platform.setTimeout(function () { backburner._autorun = null; backburner.end(); }); } function findDebouncee(target, method, debouncees) { return findItem(target, method, debouncees); } function findThrottler(target, method, throttlers) { return findItem(target, method, throttlers); } function findItem(target, method, collection) { var item; var index = -1; for (var i = 0, l = collection.length; i < l; i++) { item = collection[i]; if (item[0] === target && item[1] === method) { index = i; break; } } return index; } function clearItems(item) { this._platform.clearTimeout(item[2]); } }); enifed("backburner/binary-search", ["exports"], function (exports) { "use strict"; exports.default = binarySearch; function binarySearch(time, timers) { var start = 0; var end = timers.length - 2; var middle, l; while (start < end) { // since timers is an array of pairs 'l' will always // be an integer l = (end - start) / 2; // compensate for the index in case even number // of pairs inside timers middle = start + l - l % 2; if (time >= timers[middle]) { start = middle + 2; } else { end = middle; } } return time >= timers[start] ? start + 2 : start; } }); enifed('backburner/deferred-action-queues', ['exports', 'backburner/utils', 'backburner/queue'], function (exports, _backburnerUtils, _backburnerQueue) { 'use strict'; exports.default = DeferredActionQueues; function DeferredActionQueues(queueNames, options) { var queues = this.queues = {}; this.queueNames = queueNames = queueNames || []; this.options = options; _backburnerUtils.each(queueNames, function (queueName) { queues[queueName] = new _backburnerQueue.default(queueName, options[queueName], options); }); } function noSuchQueue(name) { throw new Error('You attempted to schedule an action in a queue (' + name + ') that doesn\'t exist'); } function noSuchMethod(name) { throw new Error('You attempted to schedule an action in a queue (' + name + ') for a method that doesn\'t exist'); } DeferredActionQueues.prototype = { schedule: function (name, target, method, args, onceFlag, stack) { var queues = this.queues; var queue = queues[name]; if (!queue) { noSuchQueue(name); } if (!method) { noSuchMethod(name); } if (onceFlag) { return queue.pushUnique(target, method, args, stack); } else { return queue.push(target, method, args, stack); } }, flush: function () { var queues = this.queues; var queueNames = this.queueNames; var queueName, queue; var queueNameIndex = 0; var numberOfQueues = queueNames.length; while (queueNameIndex < numberOfQueues) { queueName = queueNames[queueNameIndex]; queue = queues[queueName]; var numberOfQueueItems = queue._queue.length; if (numberOfQueueItems === 0) { queueNameIndex++; } else { queue.flush(false /* async */); queueNameIndex = 0; } } } }; }); enifed('backburner/platform', ['exports'], function (exports) { 'use strict'; var GlobalContext; /* global self */ if (typeof self === 'object') { GlobalContext = self; /* global global */ } else if (typeof global === 'object') { GlobalContext = global; /* global window */ } else if (typeof window === 'object') { GlobalContext = window; } else { throw new Error('no global: `self`, `global` nor `window` was found'); } exports.default = GlobalContext; }); enifed('backburner/queue', ['exports', 'backburner/utils'], function (exports, _backburnerUtils) { 'use strict'; exports.default = Queue; function Queue(name, options, globalOptions) { this.name = name; this.globalOptions = globalOptions || {}; this.options = options; this._queue = []; this.targetQueues = {}; this._queueBeingFlushed = undefined; } Queue.prototype = { push: function (target, method, args, stack) { var queue = this._queue; queue.push(target, method, args, stack); return { queue: this, target: target, method: method }; }, pushUniqueWithoutGuid: function (target, method, args, stack) { var queue = this._queue; for (var i = 0, l = queue.length; i < l; i += 4) { var currentTarget = queue[i]; var currentMethod = queue[i + 1]; if (currentTarget === target && currentMethod === method) { queue[i + 2] = args; // replace args queue[i + 3] = stack; // replace stack return; } } queue.push(target, method, args, stack); }, targetQueue: function (targetQueue, target, method, args, stack) { var queue = this._queue; for (var i = 0, l = targetQueue.length; i < l; i += 2) { var currentMethod = targetQueue[i]; var currentIndex = targetQueue[i + 1]; if (currentMethod === method) { queue[currentIndex + 2] = args; // replace args queue[currentIndex + 3] = stack; // replace stack return; } } targetQueue.push(method, queue.push(target, method, args, stack) - 4); }, pushUniqueWithGuid: function (guid, target, method, args, stack) { var hasLocalQueue = this.targetQueues[guid]; if (hasLocalQueue) { this.targetQueue(hasLocalQueue, target, method, args, stack); } else { this.targetQueues[guid] = [method, this._queue.push(target, method, args, stack) - 4]; } return { queue: this, target: target, method: method }; }, pushUnique: function (target, method, args, stack) { var KEY = this.globalOptions.GUID_KEY; if (target && KEY) { var guid = target[KEY]; if (guid) { return this.pushUniqueWithGuid(guid, target, method, args, stack); } } this.pushUniqueWithoutGuid(target, method, args, stack); return { queue: this, target: target, method: method }; }, invoke: function (target, method, args, _, _errorRecordedForStack) { if (args && args.length > 0) { method.apply(target, args); } else { method.call(target); } }, invokeWithOnError: function (target, method, args, onError, errorRecordedForStack) { try { if (args && args.length > 0) { method.apply(target, args); } else { method.call(target); } } catch (error) { onError(error, errorRecordedForStack); } }, flush: function (sync) { var queue = this._queue; var length = queue.length; if (length === 0) { return; } var globalOptions = this.globalOptions; var options = this.options; var before = options && options.before; var after = options && options.after; var onError = globalOptions.onError || globalOptions.onErrorTarget && globalOptions.onErrorTarget[globalOptions.onErrorMethod]; var target, method, args, errorRecordedForStack; var invoke = onError ? this.invokeWithOnError : this.invoke; this.targetQueues = Object.create(null); var queueItems = this._queueBeingFlushed = this._queue.slice(); this._queue = []; if (before) { before(); } for (var i = 0; i < length; i += 4) { target = queueItems[i]; method = queueItems[i + 1]; args = queueItems[i + 2]; errorRecordedForStack = queueItems[i + 3]; // Debugging assistance if (_backburnerUtils.isString(method)) { method = target[method]; } // method could have been nullified / canceled during flush if (method) { // // ** Attention intrepid developer ** // // To find out the stack of this task when it was scheduled onto // the run loop, add the following to your app.js: // // Ember.run.backburner.DEBUG = true; // NOTE: This slows your app, don't leave it on in production. // // Once that is in place, when you are at a breakpoint and navigate // here in the stack explorer, you can look at `errorRecordedForStack.stack`, // which will be the captured stack when this job was scheduled. // invoke(target, method, args, onError, errorRecordedForStack); } } if (after) { after(); } this._queueBeingFlushed = undefined; if (sync !== false && this._queue.length > 0) { // check if new items have been added this.flush(true); } }, cancel: function (actionToCancel) { var queue = this._queue, currentTarget, currentMethod, i, l; var target = actionToCancel.target; var method = actionToCancel.method; var GUID_KEY = this.globalOptions.GUID_KEY; if (GUID_KEY && this.targetQueues && target) { var targetQueue = this.targetQueues[target[GUID_KEY]]; if (targetQueue) { for (i = 0, l = targetQueue.length; i < l; i++) { if (targetQueue[i] === method) { targetQueue.splice(i, 1); } } } } for (i = 0, l = queue.length; i < l; i += 4) { currentTarget = queue[i]; currentMethod = queue[i + 1]; if (currentTarget === target && currentMethod === method) { queue.splice(i, 4); return true; } } // if not found in current queue // could be in the queue that is being flushed queue = this._queueBeingFlushed; if (!queue) { return; } for (i = 0, l = queue.length; i < l; i += 4) { currentTarget = queue[i]; currentMethod = queue[i + 1]; if (currentTarget === target && currentMethod === method) { // don't mess with array during flush // just nullify the method queue[i + 1] = null; return true; } } } }; }); enifed('backburner/utils', ['exports'], function (exports) { 'use strict'; exports.each = each; exports.isString = isString; exports.isFunction = isFunction; exports.isNumber = isNumber; exports.isCoercableNumber = isCoercableNumber; var NUMBER = /\d+/; function each(collection, callback) { for (var i = 0; i < collection.length; i++) { callback(collection[i]); } } function isString(suspect) { return typeof suspect === 'string'; } function isFunction(suspect) { return typeof suspect === 'function'; } function isNumber(suspect) { return typeof suspect === 'number'; } function isCoercableNumber(number) { return isNumber(number) || NUMBER.test(number); } }); enifed('container/container', ['exports', 'ember-environment', 'ember-metal/debug', 'ember-metal/dictionary', 'container/owner', 'ember-runtime/mixins/container_proxy', 'ember-metal/symbol'], function (exports, _emberEnvironment, _emberMetalDebug, _emberMetalDictionary, _containerOwner, _emberRuntimeMixinsContainer_proxy, _emberMetalSymbol) { 'use strict'; exports.default = Container; var CONTAINER_OVERRIDE = _emberMetalSymbol.default('CONTAINER_OVERRIDE'); /** A container used to instantiate and cache objects. Every `Container` must be associated with a `Registry`, which is referenced to determine the factory and options that should be used to instantiate objects. The public API for `Container` is still in flux and should not be considered stable. @private @class Container */ function Container(registry, options) { this.registry = registry; this.owner = options && options.owner ? options.owner : null; this.cache = _emberMetalDictionary.default(options && options.cache ? options.cache : null); this.factoryCache = _emberMetalDictionary.default(options && options.factoryCache ? options.factoryCache : null); this.validationCache = _emberMetalDictionary.default(options && options.validationCache ? options.validationCache : null); this._fakeContainerToInject = _emberRuntimeMixinsContainer_proxy.buildFakeContainerWithDeprecations(this); this[CONTAINER_OVERRIDE] = undefined; this.isDestroyed = false; } Container.prototype = { /** @private @property owner @type Object */ owner: null, /** @private @property registry @type Registry @since 1.11.0 */ registry: null, /** @private @property cache @type InheritingDict */ cache: null, /** @private @property factoryCache @type InheritingDict */ factoryCache: null, /** @private @property validationCache @type InheritingDict */ validationCache: null, /** Given a fullName return a corresponding instance. The default behaviour is for lookup to return a singleton instance. The singleton is scoped to the container, allowing multiple containers to all have their own locally scoped singletons. ```javascript let registry = new Registry(); let container = registry.container(); registry.register('api:twitter', Twitter); let twitter = container.lookup('api:twitter'); twitter instanceof Twitter; // => true // by default the container will return singletons let twitter2 = container.lookup('api:twitter'); twitter2 instanceof Twitter; // => true twitter === twitter2; //=> true ``` If singletons are not wanted, an optional flag can be provided at lookup. ```javascript let registry = new Registry(); let container = registry.container(); registry.register('api:twitter', Twitter); let twitter = container.lookup('api:twitter', { singleton: false }); let twitter2 = container.lookup('api:twitter', { singleton: false }); twitter === twitter2; //=> false ``` @private @method lookup @param {String} fullName @param {Object} [options] @param {String} [options.source] The fullname of the request source (used for local lookup) @return {any} */ lookup: function (fullName, options) { _emberMetalDebug.assert('fullName must be a proper full name', this.registry.validateFullName(fullName)); return lookup(this, this.registry.normalize(fullName), options); }, /** Given a fullName, return the corresponding factory. @private @method lookupFactory @param {String} fullName @param {Object} [options] @param {String} [options.source] The fullname of the request source (used for local lookup) @return {any} */ lookupFactory: function (fullName, options) { _emberMetalDebug.assert('fullName must be a proper full name', this.registry.validateFullName(fullName)); return factoryFor(this, this.registry.normalize(fullName), options); }, /** A depth first traversal, destroying the container, its descendant containers and all their managed objects. @private @method destroy */ destroy: function () { eachDestroyable(this, function (item) { if (item.destroy) { item.destroy(); } }); this.isDestroyed = true; }, /** Clear either the entire cache or just the cache for a particular key. @private @method reset @param {String} fullName optional key to reset; if missing, resets everything */ reset: function (fullName) { if (arguments.length > 0) { resetMember(this, this.registry.normalize(fullName)); } else { resetCache(this); } }, /** Returns an object that can be used to provide an owner to a manually created instance. @private @method ownerInjection @returns { Object } */ ownerInjection: function () { var _ref; return _ref = {}, _ref[_containerOwner.OWNER] = this.owner, _ref; } }; function isSingleton(container, fullName) { return container.registry.getOption(fullName, 'singleton') !== false; } function lookup(container, fullName) { var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; if (options.source) { fullName = container.registry.expandLocalLookup(fullName, options); // if expandLocalLookup returns falsey, we do not support local lookup if (!fullName) { return; } } if (container.cache[fullName] !== undefined && options.singleton !== false) { return container.cache[fullName]; } var value = instantiate(container, fullName); if (value === undefined) { return; } if (isSingleton(container, fullName) && options.singleton !== false) { container.cache[fullName] = value; } return value; } function markInjectionsAsDynamic(injections) { injections._dynamic = true; } function areInjectionsDynamic(injections) { return !!injections._dynamic; } function buildInjections() /* container, ...injections */{ var hash = {}; if (arguments.length > 1) { var container = arguments[0]; var injections = []; var injection = undefined; for (var i = 1; i < arguments.length; i++) { if (arguments[i]) { injections = injections.concat(arguments[i]); } } container.registry.validateInjections(injections); for (var i = 0; i < injections.length; i++) { injection = injections[i]; hash[injection.property] = lookup(container, injection.fullName); if (!isSingleton(container, injection.fullName)) { markInjectionsAsDynamic(hash); } } } return hash; } function factoryFor(container, fullName) { var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var registry = container.registry; if (options.source) { fullName = registry.expandLocalLookup(fullName, options); // if expandLocalLookup returns falsey, we do not support local lookup if (!fullName) { return; } } var cache = container.factoryCache; if (cache[fullName]) { return cache[fullName]; } var factory = registry.resolve(fullName); if (factory === undefined) { return; } var type = fullName.split(':')[0]; if (!factory || typeof factory.extend !== 'function' || !_emberEnvironment.ENV.MODEL_FACTORY_INJECTIONS && type === 'model') { if (factory && typeof factory._onLookup === 'function') { factory._onLookup(fullName); } // TODO: think about a 'safe' merge style extension // for now just fallback to create time injection cache[fullName] = factory; return factory; } else { var injections = injectionsFor(container, fullName); var factoryInjections = factoryInjectionsFor(container, fullName); var cacheable = !areInjectionsDynamic(injections) && !areInjectionsDynamic(factoryInjections); factoryInjections._toString = registry.makeToString(factory, fullName); var injectedFactory = factory.extend(injections); // TODO - remove all `container` injections when Ember reaches v3.0.0 injectDeprecatedContainer(injectedFactory.prototype, container); injectedFactory.reopenClass(factoryInjections); if (factory && typeof factory._onLookup === 'function') { factory._onLookup(fullName); } if (cacheable) { cache[fullName] = injectedFactory; } return injectedFactory; } } function injectionsFor(container, fullName) { var registry = container.registry; var splitName = fullName.split(':'); var type = splitName[0]; var injections = buildInjections(container, registry.getTypeInjections(type), registry.getInjections(fullName)); injections._debugContainerKey = fullName; _containerOwner.setOwner(injections, container.owner); return injections; } function factoryInjectionsFor(container, fullName) { var registry = container.registry; var splitName = fullName.split(':'); var type = splitName[0]; var factoryInjections = buildInjections(container, registry.getFactoryTypeInjections(type), registry.getFactoryInjections(fullName)); factoryInjections._debugContainerKey = fullName; return factoryInjections; } function instantiate(container, fullName) { var factory = factoryFor(container, fullName); var lazyInjections = undefined, validationCache = undefined; if (container.registry.getOption(fullName, 'instantiate') === false) { return factory; } if (factory) { if (typeof factory.create !== 'function') { throw new Error('Failed to create an instance of \'' + fullName + '\'. Most likely an improperly defined class or' + ' an invalid module export.'); } validationCache = container.validationCache; _emberMetalDebug.runInDebug(function () { // Ensure that all lazy injections are valid at instantiation time if (!validationCache[fullName] && typeof factory._lazyInjections === 'function') { lazyInjections = factory._lazyInjections(); lazyInjections = container.registry.normalizeInjectionsHash(lazyInjections); container.registry.validateInjections(lazyInjections); } }); validationCache[fullName] = true; var obj = undefined; if (typeof factory.extend === 'function') { // assume the factory was extendable and is already injected obj = factory.create(); } else { // assume the factory was extendable // to create time injections // TODO: support new'ing for instantiation and merge injections for pure JS Functions var injections = injectionsFor(container, fullName); // Ensure that a container is available to an object during instantiation. // TODO - remove when Ember reaches v3.0.0 // This "fake" container will be replaced after instantiation with a // property that raises deprecations every time it is accessed. injections.container = container._fakeContainerToInject; obj = factory.create(injections); // TODO - remove when Ember reaches v3.0.0 if (!Object.isFrozen(obj) && 'container' in obj) { injectDeprecatedContainer(obj, container); } } return obj; } } // TODO - remove when Ember reaches v3.0.0 function injectDeprecatedContainer(object, container) { Object.defineProperty(object, 'container', { configurable: true, enumerable: false, get: function () { _emberMetalDebug.deprecate('Using the injected `container` is deprecated. Please use the `getOwner` helper instead to access the owner of this object.', false, { id: 'ember-application.injected-container', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_injected-container-access' }); return this[CONTAINER_OVERRIDE] || container; }, set: function (value) { _emberMetalDebug.deprecate('Providing the `container` property to ' + this + ' is deprecated. Please use `Ember.setOwner` or `owner.ownerInjection()` instead to provide an owner to the instance being created.', false, { id: 'ember-application.injected-container', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_injected-container-access' }); this[CONTAINER_OVERRIDE] = value; return value; } }); } function eachDestroyable(container, callback) { var cache = container.cache; var keys = Object.keys(cache); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = cache[key]; if (container.registry.getOption(key, 'instantiate') !== false) { callback(value); } } } function resetCache(container) { eachDestroyable(container, function (value) { if (value.destroy) { value.destroy(); } }); container.cache.dict = _emberMetalDictionary.default(null); } function resetMember(container, fullName) { var member = container.cache[fullName]; delete container.factoryCache[fullName]; if (member) { delete container.cache[fullName]; if (member.destroy) { member.destroy(); } } } }); enifed('container/index', ['exports', 'container/registry', 'container/container', 'container/owner'], function (exports, _containerRegistry, _containerContainer, _containerOwner) { /* Public API for the container is still in flux. The public API, specified on the application namespace should be considered the stable API. // @module container @private */ 'use strict'; exports.Registry = _containerRegistry.default; exports.Container = _containerContainer.default; exports.getOwner = _containerOwner.getOwner; exports.setOwner = _containerOwner.setOwner; }); enifed('container/owner', ['exports', 'ember-metal/symbol'], function (exports, _emberMetalSymbol) { /** @module ember @submodule ember-runtime */ 'use strict'; exports.getOwner = getOwner; exports.setOwner = setOwner; var OWNER = _emberMetalSymbol.default('OWNER'); exports.OWNER = OWNER; /** Framework objects in an Ember application (components, services, routes, etc.) are created via a factory and dependency injection system. Each of these objects is the responsibility of an "owner", which handled its instantiation and manages its lifetime. `getOwner` fetches the owner object responsible for an instance. This can be used to lookup or resolve other class instances, or register new factories into the owner. For example, this component dynamically looks up a service based on the `audioType` passed as an attribute: ``` // app/components/play-audio.js import Ember from 'ember'; // Usage: // // {{play-audio audioType=model.audioType audioFile=model.file}} // export default Ember.Component.extend({ audioService: Ember.computed('audioType', function() { let owner = Ember.getOwner(this); return owner.lookup(`service:${this.get('audioType')}`); }), click() { let player = this.get('audioService'); player.play(this.get('audioFile')); } }); ``` @method getOwner @for Ember @param {Object} object An object with an owner. @return {Object} An owner object. @since 2.3.0 @public */ function getOwner(object) { return object[OWNER]; } /** `setOwner` forces a new owner on a given object instance. This is primarily useful in some testing cases. @method setOwner @for Ember @param {Object} object An object with an owner. @return {Object} An owner object. @since 2.3.0 @public */ function setOwner(object, owner) { object[OWNER] = owner; } }); enifed('container/registry', ['exports', 'ember-metal/debug', 'ember-metal/dictionary', 'ember-metal/empty_object', 'ember-metal/assign', 'container/container', 'ember-metal/utils'], function (exports, _emberMetalDebug, _emberMetalDictionary, _emberMetalEmpty_object, _emberMetalAssign, _containerContainer, _emberMetalUtils) { 'use strict'; exports.default = Registry; exports.privatize = privatize; var VALID_FULL_NAME_REGEXP = /^[^:]+:[^:]+$/; /** A registry used to store factory and option information keyed by type. A `Registry` stores the factory and option information needed by a `Container` to instantiate and cache objects. The API for `Registry` is still in flux and should not be considered stable. @private @class Registry @since 1.11.0 */ function Registry(options) { this.fallback = options && options.fallback ? options.fallback : null; if (options && options.resolver) { this.resolver = options.resolver; if (typeof this.resolver === 'function') { deprecateResolverFunction(this); } } this.registrations = _emberMetalDictionary.default(options && options.registrations ? options.registrations : null); this._typeInjections = _emberMetalDictionary.default(null); this._injections = _emberMetalDictionary.default(null); this._factoryTypeInjections = _emberMetalDictionary.default(null); this._factoryInjections = _emberMetalDictionary.default(null); this._localLookupCache = new _emberMetalEmpty_object.default(); this._normalizeCache = _emberMetalDictionary.default(null); this._resolveCache = _emberMetalDictionary.default(null); this._failCache = _emberMetalDictionary.default(null); this._options = _emberMetalDictionary.default(null); this._typeOptions = _emberMetalDictionary.default(null); } Registry.prototype = { /** A backup registry for resolving registrations when no matches can be found. @private @property fallback @type Registry */ fallback: null, /** An object that has a `resolve` method that resolves a name. @private @property resolver @type Resolver */ resolver: null, /** @private @property registrations @type InheritingDict */ registrations: null, /** @private @property _typeInjections @type InheritingDict */ _typeInjections: null, /** @private @property _injections @type InheritingDict */ _injections: null, /** @private @property _factoryTypeInjections @type InheritingDict */ _factoryTypeInjections: null, /** @private @property _factoryInjections @type InheritingDict */ _factoryInjections: null, /** @private @property _normalizeCache @type InheritingDict */ _normalizeCache: null, /** @private @property _resolveCache @type InheritingDict */ _resolveCache: null, /** @private @property _options @type InheritingDict */ _options: null, /** @private @property _typeOptions @type InheritingDict */ _typeOptions: null, /** Creates a container based on this registry. @private @method container @param {Object} options @return {Container} created container */ container: function (options) { return new _containerContainer.default(this, options); }, /** Registers a factory for later injection. Example: ```javascript let registry = new Registry(); registry.register('model:user', Person, {singleton: false }); registry.register('fruit:favorite', Orange); registry.register('communication:main', Email, {singleton: false}); ``` @private @method register @param {String} fullName @param {Function} factory @param {Object} options */ register: function (fullName, factory) { var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; _emberMetalDebug.assert('fullName must be a proper full name', this.validateFullName(fullName)); if (factory === undefined) { throw new TypeError('Attempting to register an unknown factory: \'' + fullName + '\''); } var normalizedName = this.normalize(fullName); if (this._resolveCache[normalizedName]) { throw new Error('Cannot re-register: \'' + fullName + '\', as it has already been resolved.'); } delete this._failCache[normalizedName]; this.registrations[normalizedName] = factory; this._options[normalizedName] = options; }, /** Unregister a fullName ```javascript let registry = new Registry(); registry.register('model:user', User); registry.resolve('model:user').create() instanceof User //=> true registry.unregister('model:user') registry.resolve('model:user') === undefined //=> true ``` @private @method unregister @param {String} fullName */ unregister: function (fullName) { _emberMetalDebug.assert('fullName must be a proper full name', this.validateFullName(fullName)); var normalizedName = this.normalize(fullName); this._localLookupCache = new _emberMetalEmpty_object.default(); delete this.registrations[normalizedName]; delete this._resolveCache[normalizedName]; delete this._failCache[normalizedName]; delete this._options[normalizedName]; }, /** Given a fullName return the corresponding factory. By default `resolve` will retrieve the factory from the registry. ```javascript let registry = new Registry(); registry.register('api:twitter', Twitter); registry.resolve('api:twitter') // => Twitter ``` Optionally the registry can be provided with a custom resolver. If provided, `resolve` will first provide the custom resolver the opportunity to resolve the fullName, otherwise it will fallback to the registry. ```javascript let registry = new Registry(); registry.resolver = function(fullName) { // lookup via the module system of choice }; // the twitter factory is added to the module system registry.resolve('api:twitter') // => Twitter ``` @private @method resolve @param {String} fullName @param {Object} [options] @param {String} [options.source] the fullname of the request source (used for local lookups) @return {Function} fullName's factory */ resolve: function (fullName, options) { _emberMetalDebug.assert('fullName must be a proper full name', this.validateFullName(fullName)); var factory = resolve(this, this.normalize(fullName), options); if (factory === undefined && this.fallback) { var _fallback; factory = (_fallback = this.fallback).resolve.apply(_fallback, arguments); } return factory; }, /** A hook that can be used to describe how the resolver will attempt to find the factory. For example, the default Ember `.describe` returns the full class name (including namespace) where Ember's resolver expects to find the `fullName`. @private @method describe @param {String} fullName @return {string} described fullName */ describe: function (fullName) { if (this.resolver && this.resolver.lookupDescription) { return this.resolver.lookupDescription(fullName); } else if (this.fallback) { return this.fallback.describe(fullName); } else { return fullName; } }, /** A hook to enable custom fullName normalization behaviour @private @method normalizeFullName @param {String} fullName @return {string} normalized fullName */ normalizeFullName: function (fullName) { if (this.resolver && this.resolver.normalize) { return this.resolver.normalize(fullName); } else if (this.fallback) { return this.fallback.normalizeFullName(fullName); } else { return fullName; } }, /** Normalize a fullName based on the application's conventions @private @method normalize @param {String} fullName @return {string} normalized fullName */ normalize: function (fullName) { return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this.normalizeFullName(fullName)); }, /** @method makeToString @private @param {any} factory @param {string} fullName @return {function} toString function */ makeToString: function (factory, fullName) { if (this.resolver && this.resolver.makeToString) { return this.resolver.makeToString(factory, fullName); } else if (this.fallback) { return this.fallback.makeToString(factory, fullName); } else { return factory.toString(); } }, /** Given a fullName check if the container is aware of its factory or singleton instance. @private @method has @param {String} fullName @param {Object} [options] @param {String} [options.source] the fullname of the request source (used for local lookups) @return {Boolean} */ has: function (fullName, options) { if (!this.isValidFullName(fullName)) { return false; } var source = options && options.source && this.normalize(options.source); return has(this, this.normalize(fullName), source); }, /** Allow registering options for all factories of a type. ```javascript let registry = new Registry(); let container = registry.container(); // if all of type `connection` must not be singletons registry.optionsForType('connection', { singleton: false }); registry.register('connection:twitter', TwitterConnection); registry.register('connection:facebook', FacebookConnection); let twitter = container.lookup('connection:twitter'); let twitter2 = container.lookup('connection:twitter'); twitter === twitter2; // => false let facebook = container.lookup('connection:facebook'); let facebook2 = container.lookup('connection:facebook'); facebook === facebook2; // => false ``` @private @method optionsForType @param {String} type @param {Object} options */ optionsForType: function (type, options) { this._typeOptions[type] = options; }, getOptionsForType: function (type) { var optionsForType = this._typeOptions[type]; if (optionsForType === undefined && this.fallback) { optionsForType = this.fallback.getOptionsForType(type); } return optionsForType; }, /** @private @method options @param {String} fullName @param {Object} options */ options: function (fullName) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var normalizedName = this.normalize(fullName); this._options[normalizedName] = options; }, getOptions: function (fullName) { var normalizedName = this.normalize(fullName); var options = this._options[normalizedName]; if (options === undefined && this.fallback) { options = this.fallback.getOptions(fullName); } return options; }, getOption: function (fullName, optionName) { var options = this._options[fullName]; if (options && options[optionName] !== undefined) { return options[optionName]; } var type = fullName.split(':')[0]; options = this._typeOptions[type]; if (options && options[optionName] !== undefined) { return options[optionName]; } else if (this.fallback) { return this.fallback.getOption(fullName, optionName); } }, /** Used only via `injection`. Provides a specialized form of injection, specifically enabling all objects of one type to be injected with a reference to another object. For example, provided each object of type `controller` needed a `router`. one would do the following: ```javascript let registry = new Registry(); let container = registry.container(); registry.register('router:main', Router); registry.register('controller:user', UserController); registry.register('controller:post', PostController); registry.typeInjection('controller', 'router', 'router:main'); let user = container.lookup('controller:user'); let post = container.lookup('controller:post'); user.router instanceof Router; //=> true post.router instanceof Router; //=> true // both controllers share the same router user.router === post.router; //=> true ``` @private @method typeInjection @param {String} type @param {String} property @param {String} fullName */ typeInjection: function (type, property, fullName) { _emberMetalDebug.assert('fullName must be a proper full name', this.validateFullName(fullName)); var fullNameType = fullName.split(':')[0]; if (fullNameType === type) { throw new Error('Cannot inject a \'' + fullName + '\' on other ' + type + '(s).'); } var injections = this._typeInjections[type] || (this._typeInjections[type] = []); injections.push({ property: property, fullName: fullName }); }, /** Defines injection rules. These rules are used to inject dependencies onto objects when they are instantiated. Two forms of injections are possible: * Injecting one fullName on another fullName * Injecting one fullName on a type Example: ```javascript let registry = new Registry(); let container = registry.container(); registry.register('source:main', Source); registry.register('model:user', User); registry.register('model:post', Post); // injecting one fullName on another fullName // eg. each user model gets a post model registry.injection('model:user', 'post', 'model:post'); // injecting one fullName on another type registry.injection('model', 'source', 'source:main'); let user = container.lookup('model:user'); let post = container.lookup('model:post'); user.source instanceof Source; //=> true post.source instanceof Source; //=> true user.post instanceof Post; //=> true // and both models share the same source user.source === post.source; //=> true ``` @private @method injection @param {String} factoryName @param {String} property @param {String} injectionName */ injection: function (fullName, property, injectionName) { this.validateFullName(injectionName); var normalizedInjectionName = this.normalize(injectionName); if (fullName.indexOf(':') === -1) { return this.typeInjection(fullName, property, normalizedInjectionName); } _emberMetalDebug.assert('fullName must be a proper full name', this.validateFullName(fullName)); var normalizedName = this.normalize(fullName); var injections = this._injections[normalizedName] || (this._injections[normalizedName] = []); injections.push({ property: property, fullName: normalizedInjectionName }); }, /** Used only via `factoryInjection`. Provides a specialized form of injection, specifically enabling all factory of one type to be injected with a reference to another object. For example, provided each factory of type `model` needed a `store`. one would do the following: ```javascript let registry = new Registry(); registry.register('store:main', SomeStore); registry.factoryTypeInjection('model', 'store', 'store:main'); let store = registry.lookup('store:main'); let UserFactory = registry.lookupFactory('model:user'); UserFactory.store instanceof SomeStore; //=> true ``` @private @method factoryTypeInjection @param {String} type @param {String} property @param {String} fullName */ factoryTypeInjection: function (type, property, fullName) { var injections = this._factoryTypeInjections[type] || (this._factoryTypeInjections[type] = []); injections.push({ property: property, fullName: this.normalize(fullName) }); }, /** Defines factory injection rules. Similar to regular injection rules, but are run against factories, via `Registry#lookupFactory`. These rules are used to inject objects onto factories when they are looked up. Two forms of injections are possible: * Injecting one fullName on another fullName * Injecting one fullName on a type Example: ```javascript let registry = new Registry(); let container = registry.container(); registry.register('store:main', Store); registry.register('store:secondary', OtherStore); registry.register('model:user', User); registry.register('model:post', Post); // injecting one fullName on another type registry.factoryInjection('model', 'store', 'store:main'); // injecting one fullName on another fullName registry.factoryInjection('model:post', 'secondaryStore', 'store:secondary'); let UserFactory = container.lookupFactory('model:user'); let PostFactory = container.lookupFactory('model:post'); let store = container.lookup('store:main'); UserFactory.store instanceof Store; //=> true UserFactory.secondaryStore instanceof OtherStore; //=> false PostFactory.store instanceof Store; //=> true PostFactory.secondaryStore instanceof OtherStore; //=> true // and both models share the same source instance UserFactory.store === PostFactory.store; //=> true ``` @private @method factoryInjection @param {String} factoryName @param {String} property @param {String} injectionName */ factoryInjection: function (fullName, property, injectionName) { var normalizedName = this.normalize(fullName); var normalizedInjectionName = this.normalize(injectionName); this.validateFullName(injectionName); if (fullName.indexOf(':') === -1) { return this.factoryTypeInjection(normalizedName, property, normalizedInjectionName); } var injections = this._factoryInjections[normalizedName] || (this._factoryInjections[normalizedName] = []); injections.push({ property: property, fullName: normalizedInjectionName }); }, /** @private @method knownForType @param {String} type the type to iterate over */ knownForType: function (type) { var fallbackKnown = undefined, resolverKnown = undefined; var localKnown = _emberMetalDictionary.default(null); var registeredNames = Object.keys(this.registrations); for (var index = 0; index < registeredNames.length; index++) { var fullName = registeredNames[index]; var itemType = fullName.split(':')[0]; if (itemType === type) { localKnown[fullName] = true; } } if (this.fallback) { fallbackKnown = this.fallback.knownForType(type); } if (this.resolver && this.resolver.knownForType) { resolverKnown = this.resolver.knownForType(type); } return _emberMetalAssign.default({}, fallbackKnown, localKnown, resolverKnown); }, validateFullName: function (fullName) { if (!this.isValidFullName(fullName)) { throw new TypeError('Invalid Fullname, expected: \'type:name\' got: ' + fullName); } return true; }, isValidFullName: function (fullName) { return !!VALID_FULL_NAME_REGEXP.test(fullName); }, validateInjections: function (injections) { if (!injections) { return; } var fullName = undefined; for (var i = 0; i < injections.length; i++) { fullName = injections[i].fullName; if (!this.has(fullName)) { throw new Error('Attempting to inject an unknown injection: \'' + fullName + '\''); } } }, normalizeInjectionsHash: function (hash) { var injections = []; for (var key in hash) { if (hash.hasOwnProperty(key)) { _emberMetalDebug.assert('Expected a proper full name, given \'' + hash[key] + '\'', this.validateFullName(hash[key])); injections.push({ property: key, fullName: hash[key] }); } } return injections; }, getInjections: function (fullName) { var injections = this._injections[fullName] || []; if (this.fallback) { injections = injections.concat(this.fallback.getInjections(fullName)); } return injections; }, getTypeInjections: function (type) { var injections = this._typeInjections[type] || []; if (this.fallback) { injections = injections.concat(this.fallback.getTypeInjections(type)); } return injections; }, getFactoryInjections: function (fullName) { var injections = this._factoryInjections[fullName] || []; if (this.fallback) { injections = injections.concat(this.fallback.getFactoryInjections(fullName)); } return injections; }, getFactoryTypeInjections: function (type) { var injections = this._factoryTypeInjections[type] || []; if (this.fallback) { injections = injections.concat(this.fallback.getFactoryTypeInjections(type)); } return injections; } }; function deprecateResolverFunction(registry) { _emberMetalDebug.deprecate('Passing a `resolver` function into a Registry is deprecated. Please pass in a Resolver object with a `resolve` method.', false, { id: 'ember-application.registry-resolver-as-function', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_registry-resolver-as-function' }); registry.resolver = { resolve: registry.resolver }; } /** Given a fullName and a source fullName returns the fully resolved fullName. Used to allow for local lookup. ```javascript let registry = new Registry(); // the twitter factory is added to the module system registry.expandLocalLookup('component:post-title', { source: 'template:post' }) // => component:post/post-title ``` @private @method expandLocalLookup @param {String} fullName @param {Object} [options] @param {String} [options.source] the fullname of the request source (used for local lookups) @return {String} fullName */ Registry.prototype.expandLocalLookup = function Registry_expandLocalLookup(fullName, options) { if (this.resolver && this.resolver.expandLocalLookup) { _emberMetalDebug.assert('fullName must be a proper full name', this.validateFullName(fullName)); _emberMetalDebug.assert('options.source must be provided to expandLocalLookup', options && options.source); _emberMetalDebug.assert('options.source must be a proper full name', this.validateFullName(options.source)); var normalizedFullName = this.normalize(fullName); var normalizedSource = this.normalize(options.source); return expandLocalLookup(this, normalizedFullName, normalizedSource); } else if (this.fallback) { return this.fallback.expandLocalLookup(fullName, options); } else { return null; } }; function expandLocalLookup(registry, normalizedName, normalizedSource) { var cache = registry._localLookupCache; var normalizedNameCache = cache[normalizedName]; if (!normalizedNameCache) { normalizedNameCache = cache[normalizedName] = new _emberMetalEmpty_object.default(); } var cached = normalizedNameCache[normalizedSource]; if (cached !== undefined) { return cached; } var expanded = registry.resolver.expandLocalLookup(normalizedName, normalizedSource); return normalizedNameCache[normalizedSource] = expanded; } function resolve(registry, normalizedName, options) { if (options && options.source) { // when `source` is provided expand normalizedName // and source into the full normalizedName normalizedName = registry.expandLocalLookup(normalizedName, options); // if expandLocalLookup returns falsey, we do not support local lookup if (!normalizedName) { return; } } var cached = registry._resolveCache[normalizedName]; if (cached !== undefined) { return cached; } if (registry._failCache[normalizedName]) { return; } var resolved = undefined; if (registry.resolver) { resolved = registry.resolver.resolve(normalizedName); } if (resolved === undefined) { resolved = registry.registrations[normalizedName]; } if (resolved === undefined) { registry._failCache[normalizedName] = true; } else { registry._resolveCache[normalizedName] = resolved; } return resolved; } function has(registry, fullName, source) { return registry.resolve(fullName, { source: source }) !== undefined; } var privateNames = _emberMetalDictionary.default(null); var privateSuffix = '' + Math.random() + Date.now(); function privatize(_ref) { var fullName = _ref[0]; var name = privateNames[fullName]; if (name) { return name; } var _fullName$split = fullName.split(':'); var type = _fullName$split[0]; var rawName = _fullName$split[1]; return privateNames[fullName] = _emberMetalUtils.intern(type + ':' + rawName + '-' + privateSuffix); } }); enifed('dag-map', ['exports', 'vertex', 'visit'], function (exports, _vertex, _visit) { 'use strict'; exports.default = DAG; /** * DAG stands for Directed acyclic graph. * * It is used to build a graph of dependencies checking that there isn't circular * dependencies. p.e Registering initializers with a certain precedence order. * * @class DAG * @constructor */ function DAG() { this.names = []; this.vertices = Object.create(null); } /** * Adds a vertex entry to the graph unless it is already added. * * @private * @method add * @param {String} name The name of the vertex to add */ DAG.prototype.add = function (name) { if (!name) { throw new Error("Can't add Vertex without name"); } if (this.vertices[name] !== undefined) { return this.vertices[name]; } var vertex = new _vertex.default(name); this.vertices[name] = vertex; this.names.push(name); return vertex; }; /** * Adds a vertex to the graph and sets its value. * * @private * @method map * @param {String} name The name of the vertex. * @param value The value to put in the vertex. */ DAG.prototype.map = function (name, value) { this.add(name).value = value; }; /** * Connects the vertices with the given names, adding them to the graph if * necessary, only if this does not produce is any circular dependency. * * @private * @method addEdge * @param {String} fromName The name the vertex where the edge starts. * @param {String} toName The name the vertex where the edge ends. */ DAG.prototype.addEdge = function (fromName, toName) { if (!fromName || !toName || fromName === toName) { return; } var from = this.add(fromName); var to = this.add(toName); if (to.incoming.hasOwnProperty(fromName)) { return; } function checkCycle(vertex, path) { if (vertex.name === toName) { throw new Error("cycle detected: " + toName + " <- " + path.join(" <- ")); } } _visit.default(from, checkCycle); from.hasOutgoing = true; to.incoming[fromName] = from; to.incomingNames.push(fromName); }; /** * Visits all the vertex of the graph calling the given function with each one, * ensuring that the vertices are visited respecting their precedence. * * @method topsort * @param {Function} fn The function to be invoked on each vertex. */ DAG.prototype.topsort = function (fn) { var visited = {}; var vertices = this.vertices; var names = this.names; var len = names.length; var i, vertex; for (i = 0; i < len; i++) { vertex = vertices[names[i]]; if (!vertex.hasOutgoing) { _visit.default(vertex, fn, visited); } } }; /** * Adds a vertex with the given name and value to the graph and joins it with the * vertices referenced in _before_ and _after_. If there isn't vertices with those * names, they are added too. * * If either _before_ or _after_ are falsy/empty, the added vertex will not have * an incoming/outgoing edge. * * @method addEdges * @param {String} name The name of the vertex to be added. * @param value The value of that vertex. * @param before An string or array of strings with the names of the vertices before * which this vertex must be visited. * @param after An string or array of strings with the names of the vertex after * which this vertex must be visited. * */ DAG.prototype.addEdges = function (name, value, before, after) { var i; this.map(name, value); if (before) { if (typeof before === 'string') { this.addEdge(name, before); } else { for (i = 0; i < before.length; i++) { this.addEdge(name, before[i]); } } } if (after) { if (typeof after === 'string') { this.addEdge(after, name); } else { for (i = 0; i < after.length; i++) { this.addEdge(after[i], name); } } } }; }); enifed('dag-map.umd', ['exports', 'dag-map/platform', 'dag-map'], function (exports, _dagMapPlatform, _dagMap) { 'use strict'; /* global define:true module:true window: true */ if (typeof define === 'function' && define.amd) { define(function () { return _dagMap.default; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = _dagMap.default; } else if (typeof _dagMapPlatform.default !== 'undefined') { _dagMapPlatform.default['DAG'] = _dagMap.default; } }); enifed('dag-map/platform', ['exports'], function (exports) { 'use strict'; var platform; /* global self */ if (typeof self === 'object') { platform = self; /* global global */ } else if (typeof global === 'object') { platform = global; } else { throw new Error('no global: `self` or `global` found'); } exports.default = platform; }); enifed("dom-helper", ["exports", "htmlbars-runtime/morph", "morph-attr", "dom-helper/build-html-dom", "dom-helper/classes", "dom-helper/prop"], function (exports, _htmlbarsRuntimeMorph, _morphAttr, _domHelperBuildHtmlDom, _domHelperClasses, _domHelperProp) { /*globals module, URL*/ "use strict"; var doc = typeof document === 'undefined' ? false : document; var deletesBlankTextNodes = doc && (function (document) { var element = document.createElement('div'); element.appendChild(document.createTextNode('')); var clonedElement = element.cloneNode(true); return clonedElement.childNodes.length === 0; })(doc); var ignoresCheckedAttribute = doc && (function (document) { var element = document.createElement('input'); element.setAttribute('checked', 'checked'); var clonedElement = element.cloneNode(false); return !clonedElement.checked; })(doc); var canRemoveSvgViewBoxAttribute = doc && (doc.createElementNS ? (function (document) { var element = document.createElementNS(_domHelperBuildHtmlDom.svgNamespace, 'svg'); element.setAttribute('viewBox', '0 0 100 100'); element.removeAttribute('viewBox'); return !element.getAttribute('viewBox'); })(doc) : true); var canClone = doc && (function (document) { var element = document.createElement('div'); element.appendChild(document.createTextNode(' ')); element.appendChild(document.createTextNode(' ')); var clonedElement = element.cloneNode(true); return clonedElement.childNodes[0].nodeValue === ' '; })(doc); // This is not the namespace of the element, but of // the elements inside that elements. function interiorNamespace(element) { if (element && element.namespaceURI === _domHelperBuildHtmlDom.svgNamespace && !_domHelperBuildHtmlDom.svgHTMLIntegrationPoints[element.tagName]) { return _domHelperBuildHtmlDom.svgNamespace; } else { return null; } } // The HTML spec allows for "omitted start tags". These tags are optional // when their intended child is the first thing in the parent tag. For // example, this is a tbody start tag: // // <table> // <tbody> // <tr> // // The tbody may be omitted, and the browser will accept and render: // // <table> // <tr> // // However, the omitted start tag will still be added to the DOM. Here // we test the string and context to see if the browser is about to // perform this cleanup. // // http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags // describes which tags are omittable. The spec for tbody and colgroup // explains this behavior: // // http://www.whatwg.org/specs/web-apps/current-work/multipage/tables.html#the-tbody-element // http://www.whatwg.org/specs/web-apps/current-work/multipage/tables.html#the-colgroup-element // var omittedStartTagChildTest = /<([\w:]+)/; function detectOmittedStartTag(string, contextualElement) { // Omitted start tags are only inside table tags. if (contextualElement.tagName === 'TABLE') { var omittedStartTagChildMatch = omittedStartTagChildTest.exec(string); if (omittedStartTagChildMatch) { var omittedStartTagChild = omittedStartTagChildMatch[1]; // It is already asserted that the contextual element is a table // and not the proper start tag. Just see if a tag was omitted. return omittedStartTagChild === 'tr' || omittedStartTagChild === 'col'; } } } function buildSVGDOM(html, dom) { var div = dom.document.createElement('div'); div.innerHTML = '<svg>' + html + '</svg>'; return div.firstChild.childNodes; } var guid = 1; function ElementMorph(element, dom, namespace) { this.element = element; this.dom = dom; this.namespace = namespace; this.guid = "element" + guid++; this._state = undefined; this.isDirty = true; } ElementMorph.prototype.getState = function () { if (!this._state) { this._state = {}; } return this._state; }; ElementMorph.prototype.setState = function (newState) { /*jshint -W093 */ return this._state = newState; }; // renderAndCleanup calls `clear` on all items in the morph map // just before calling `destroy` on the morph. // // As a future refactor this could be changed to set the property // back to its original/default value. ElementMorph.prototype.clear = function () {}; ElementMorph.prototype.destroy = function () { this.element = null; this.dom = null; }; /* * A class wrapping DOM functions to address environment compatibility, * namespaces, contextual elements for morph un-escaped content * insertion. * * When entering a template, a DOMHelper should be passed: * * template(context, { hooks: hooks, dom: new DOMHelper() }); * * TODO: support foreignObject as a passed contextual element. It has * a namespace (svg) that does not match its internal namespace * (xhtml). * * @class DOMHelper * @constructor * @param {HTMLDocument} _document The document DOM methods are proxied to */ function DOMHelper(_document) { this.document = _document || document; if (!this.document) { throw new Error("A document object must be passed to the DOMHelper, or available on the global scope"); } this.canClone = canClone; this.namespace = null; installEnvironmentSpecificMethods(this); } var prototype = DOMHelper.prototype; prototype.constructor = DOMHelper; prototype.getElementById = function (id, rootNode) { rootNode = rootNode || this.document; return rootNode.getElementById(id); }; prototype.insertBefore = function (element, childElement, referenceChild) { return element.insertBefore(childElement, referenceChild); }; prototype.appendChild = function (element, childElement) { return element.appendChild(childElement); }; var itemAt; // It appears that sometimes, in yet to be itentified scenarios PhantomJS 2.0 // crashes on childNodes.item(index), but works as expected with childNodes[index]; // // Although it would be nice to move to childNodes[index] in all scenarios, // this would require SimpleDOM to maintain the childNodes array. This would be // quite costly, in both dev time and runtime. // // So instead, we choose the best possible method and call it a day. // /*global navigator */ if (typeof navigator !== 'undefined' && navigator.userAgent.indexOf('PhantomJS')) { itemAt = function (nodes, index) { return nodes[index]; }; } else { itemAt = function (nodes, index) { return nodes.item(index); }; } prototype.childAt = function (element, indices) { var child = element; for (var i = 0; i < indices.length; i++) { child = itemAt(child.childNodes, indices[i]); } return child; }; // Note to a Fellow Implementor: // Ahh, accessing a child node at an index. Seems like it should be so simple, // doesn't it? Unfortunately, this particular method has caused us a surprising // amount of pain. As you'll note below, this method has been modified to walk // the linked list of child nodes rather than access the child by index // directly, even though there are two (2) APIs in the DOM that do this for us. // If you're thinking to yourself, "What an oversight! What an opportunity to // optimize this code!" then to you I say: stop! For I have a tale to tell. // // First, this code must be compatible with simple-dom for rendering on the // server where there is no real DOM. Previously, we accessed a child node // directly via `element.childNodes[index]`. While we *could* in theory do a // full-fidelity simulation of a live `childNodes` array, this is slow, // complicated and error-prone. // // "No problem," we thought, "we'll just use the similar // `childNodes.item(index)` API." Then, we could just implement our own `item` // method in simple-dom and walk the child node linked list there, allowing // us to retain the performance advantages of the (surely optimized) `item()` // API in the browser. // // Unfortunately, an enterprising soul named Samy Alzahrani discovered that in // IE8, accessing an item out-of-bounds via `item()` causes an exception where // other browsers return null. This necessitated a... check of // `childNodes.length`, bringing us back around to having to support a // full-fidelity `childNodes` array! // // Worst of all, Kris Selden investigated how browsers are actualy implemented // and discovered that they're all linked lists under the hood anyway. Accessing // `childNodes` requires them to allocate a new live collection backed by that // linked list, which is itself a rather expensive operation. Our assumed // optimization had backfired! That is the danger of magical thinking about // the performance of native implementations. // // And this, my friends, is why the following implementation just walks the // linked list, as surprised as that may make you. Please ensure you understand // the above before changing this and submitting a PR. // // Tom Dale, January 18th, 2015, Portland OR prototype.childAtIndex = function (element, index) { var node = element.firstChild; for (var idx = 0; node && idx < index; idx++) { node = node.nextSibling; } return node; }; prototype.appendText = function (element, text) { return element.appendChild(this.document.createTextNode(text)); }; prototype.setAttribute = function (element, name, value) { element.setAttribute(name, String(value)); }; prototype.getAttribute = function (element, name) { return element.getAttribute(name); }; prototype.setAttributeNS = function (element, namespace, name, value) { element.setAttributeNS(namespace, name, String(value)); }; prototype.getAttributeNS = function (element, namespace, name) { return element.getAttributeNS(namespace, name); }; if (canRemoveSvgViewBoxAttribute) { prototype.removeAttribute = function (element, name) { element.removeAttribute(name); }; } else { prototype.removeAttribute = function (element, name) { if (element.tagName === 'svg' && name === 'viewBox') { element.setAttribute(name, null); } else { element.removeAttribute(name); } }; } prototype.setPropertyStrict = function (element, name, value) { if (value === undefined) { value = null; } if (value === null && (name === 'value' || name === 'type' || name === 'src')) { value = ''; } element[name] = value; }; prototype.getPropertyStrict = function (element, name) { return element[name]; }; prototype.setProperty = function (element, name, value, namespace) { if (element.namespaceURI === _domHelperBuildHtmlDom.svgNamespace) { if (_domHelperProp.isAttrRemovalValue(value)) { element.removeAttribute(name); } else { if (namespace) { element.setAttributeNS(namespace, name, value); } else { element.setAttribute(name, value); } } } else { var _normalizeProperty = _domHelperProp.normalizeProperty(element, name); var normalized = _normalizeProperty.normalized; var type = _normalizeProperty.type; if (type === 'prop') { element[normalized] = value; } else { if (_domHelperProp.isAttrRemovalValue(value)) { element.removeAttribute(name); } else { if (namespace && element.setAttributeNS) { element.setAttributeNS(namespace, name, value); } else { element.setAttribute(name, value); } } } } }; if (doc && doc.createElementNS) { // Only opt into namespace detection if a contextualElement // is passed. prototype.createElement = function (tagName, contextualElement) { var namespace = this.namespace; if (contextualElement) { if (tagName === 'svg') { namespace = _domHelperBuildHtmlDom.svgNamespace; } else { namespace = interiorNamespace(contextualElement); } } if (namespace) { return this.document.createElementNS(namespace, tagName); } else { return this.document.createElement(tagName); } }; prototype.setAttributeNS = function (element, namespace, name, value) { element.setAttributeNS(namespace, name, String(value)); }; } else { prototype.createElement = function (tagName) { return this.document.createElement(tagName); }; prototype.setAttributeNS = function (element, namespace, name, value) { element.setAttribute(name, String(value)); }; } prototype.addClasses = _domHelperClasses.addClasses; prototype.removeClasses = _domHelperClasses.removeClasses; prototype.setNamespace = function (ns) { this.namespace = ns; }; prototype.detectNamespace = function (element) { this.namespace = interiorNamespace(element); }; prototype.createDocumentFragment = function () { return this.document.createDocumentFragment(); }; prototype.createTextNode = function (text) { return this.document.createTextNode(text); }; prototype.createComment = function (text) { return this.document.createComment(text); }; prototype.repairClonedNode = function (element, blankChildTextNodes, isChecked) { if (deletesBlankTextNodes && blankChildTextNodes.length > 0) { for (var i = 0, len = blankChildTextNodes.length; i < len; i++) { var textNode = this.document.createTextNode(''), offset = blankChildTextNodes[i], before = this.childAtIndex(element, offset); if (before) { element.insertBefore(textNode, before); } else { element.appendChild(textNode); } } } if (ignoresCheckedAttribute && isChecked) { element.setAttribute('checked', 'checked'); } }; prototype.cloneNode = function (element, deep) { var clone = element.cloneNode(!!deep); return clone; }; prototype.AttrMorphClass = _morphAttr.default; prototype.createAttrMorph = function (element, attrName, namespace) { return this.AttrMorphClass.create(element, attrName, this, namespace); }; prototype.ElementMorphClass = ElementMorph; prototype.createElementMorph = function (element, namespace) { return new this.ElementMorphClass(element, this, namespace); }; prototype.createUnsafeAttrMorph = function (element, attrName, namespace) { var morph = this.createAttrMorph(element, attrName, namespace); morph.escaped = false; return morph; }; prototype.MorphClass = _htmlbarsRuntimeMorph.default; prototype.createMorph = function (parent, start, end, contextualElement) { if (contextualElement && contextualElement.nodeType === 11) { throw new Error("Cannot pass a fragment as the contextual element to createMorph"); } if (!contextualElement && parent && parent.nodeType === 1) { contextualElement = parent; } var morph = new this.MorphClass(this, contextualElement); morph.firstNode = start; morph.lastNode = end; return morph; }; prototype.createFragmentMorph = function (contextualElement) { if (contextualElement && contextualElement.nodeType === 11) { throw new Error("Cannot pass a fragment as the contextual element to createMorph"); } var fragment = this.createDocumentFragment(); return _htmlbarsRuntimeMorph.default.create(this, contextualElement, fragment); }; prototype.replaceContentWithMorph = function (element) { var firstChild = element.firstChild; if (!firstChild) { var comment = this.createComment(''); this.appendChild(element, comment); return _htmlbarsRuntimeMorph.default.create(this, element, comment); } else { var morph = _htmlbarsRuntimeMorph.default.attach(this, element, firstChild, element.lastChild); morph.clear(); return morph; } }; prototype.createUnsafeMorph = function (parent, start, end, contextualElement) { var morph = this.createMorph(parent, start, end, contextualElement); morph.parseTextAsHTML = true; return morph; }; // This helper is just to keep the templates good looking, // passing integers instead of element references. prototype.createMorphAt = function (parent, startIndex, endIndex, contextualElement) { var single = startIndex === endIndex; var start = this.childAtIndex(parent, startIndex); var end = single ? start : this.childAtIndex(parent, endIndex); return this.createMorph(parent, start, end, contextualElement); }; prototype.createUnsafeMorphAt = function (parent, startIndex, endIndex, contextualElement) { var morph = this.createMorphAt(parent, startIndex, endIndex, contextualElement); morph.parseTextAsHTML = true; return morph; }; prototype.insertMorphBefore = function (element, referenceChild, contextualElement) { var insertion = this.document.createComment(''); element.insertBefore(insertion, referenceChild); return this.createMorph(element, insertion, insertion, contextualElement); }; prototype.appendMorph = function (element, contextualElement) { var insertion = this.document.createComment(''); element.appendChild(insertion); return this.createMorph(element, insertion, insertion, contextualElement); }; prototype.insertBoundary = function (fragment, index) { // this will always be null or firstChild var child = index === null ? null : this.childAtIndex(fragment, index); this.insertBefore(fragment, this.createTextNode(''), child); }; prototype.setMorphHTML = function (morph, html) { morph.setHTML(html); }; prototype.parseHTML = function (html, contextualElement) { var childNodes; if (interiorNamespace(contextualElement) === _domHelperBuildHtmlDom.svgNamespace) { childNodes = buildSVGDOM(html, this); } else { var nodes = _domHelperBuildHtmlDom.buildHTMLDOM(html, contextualElement, this); if (detectOmittedStartTag(html, contextualElement)) { var node = nodes[0]; while (node && node.nodeType !== 1) { node = node.nextSibling; } childNodes = node.childNodes; } else { childNodes = nodes; } } // Copy node list to a fragment. var fragment = this.document.createDocumentFragment(); if (childNodes && childNodes.length > 0) { var currentNode = childNodes[0]; // We prepend an <option> to <select> boxes to absorb any browser bugs // related to auto-select behavior. Skip past it. if (contextualElement.tagName === 'SELECT') { currentNode = currentNode.nextSibling; } while (currentNode) { var tempNode = currentNode; currentNode = currentNode.nextSibling; fragment.appendChild(tempNode); } } return fragment; }; var nodeURL; var parsingNode; function installEnvironmentSpecificMethods(domHelper) { var protocol = browserProtocolForURL.call(domHelper, 'foobar:baz'); // Test to see if our DOM implementation parses // and normalizes URLs. if (protocol === 'foobar:') { // Swap in the method that doesn't do this test now that // we know it works. domHelper.protocolForURL = browserProtocolForURL; } else if (typeof URL === 'object') { // URL globally provided, likely from FastBoot's sandbox nodeURL = URL; domHelper.protocolForURL = nodeProtocolForURL; } else if (typeof module === 'object' && typeof module.require === 'function') { // Otherwise, we need to fall back to our own URL parsing. // Global `require` is shadowed by Ember's loader so we have to use the fully // qualified `module.require`. nodeURL = module.require('url'); domHelper.protocolForURL = nodeProtocolForURL; } else { throw new Error("DOM Helper could not find valid URL parsing mechanism"); } // A SimpleDOM-specific extension that allows us to place HTML directly // into the DOM tree, for when the output target is always serialized HTML. if (domHelper.document.createRawHTMLSection) { domHelper.setMorphHTML = nodeSetMorphHTML; } } function nodeSetMorphHTML(morph, html) { var section = this.document.createRawHTMLSection(html); morph.setNode(section); } function browserProtocolForURL(url) { if (!parsingNode) { parsingNode = this.document.createElement('a'); } parsingNode.href = url; return parsingNode.protocol; } function nodeProtocolForURL(url) { var protocol = null; if (typeof url === 'string') { protocol = nodeURL.parse(url).protocol; } return protocol === null ? ':' : protocol; } exports.default = DOMHelper; }); enifed('dom-helper/build-html-dom', ['exports'], function (exports) { /* global XMLSerializer:false */ 'use strict'; var svgHTMLIntegrationPoints = { foreignObject: 1, desc: 1, title: 1 }; exports.svgHTMLIntegrationPoints = svgHTMLIntegrationPoints; var svgNamespace = 'http://www.w3.org/2000/svg'; exports.svgNamespace = svgNamespace; var doc = typeof document === 'undefined' ? false : document; // Safari does not like using innerHTML on SVG HTML integration // points (desc/title/foreignObject). var needsIntegrationPointFix = doc && (function (document) { if (document.createElementNS === undefined) { return; } // In FF title will not accept innerHTML. var testEl = document.createElementNS(svgNamespace, 'title'); testEl.innerHTML = "<div></div>"; return testEl.childNodes.length === 0 || testEl.childNodes[0].nodeType !== 1; })(doc); // Internet Explorer prior to 9 does not allow setting innerHTML if the first element // is a "zero-scope" element. This problem can be worked around by making // the first node an invisible text node. We, like Modernizr, use ­ var needsShy = doc && (function (document) { var testEl = document.createElement('div'); testEl.innerHTML = "<div></div>"; testEl.firstChild.innerHTML = "<script><\/script>"; return testEl.firstChild.innerHTML === ''; })(doc); // IE 8 (and likely earlier) likes to move whitespace preceeding // a script tag to appear after it. This means that we can // accidentally remove whitespace when updating a morph. var movesWhitespace = doc && (function (document) { var testEl = document.createElement('div'); testEl.innerHTML = "Test: <script type='text/x-placeholder'><\/script>Value"; return testEl.childNodes[0].nodeValue === 'Test:' && testEl.childNodes[2].nodeValue === ' Value'; })(doc); var tagNamesRequiringInnerHTMLFix = doc && (function (document) { var tagNamesRequiringInnerHTMLFix; // IE 9 and earlier don't allow us to set innerHTML on col, colgroup, frameset, // html, style, table, tbody, tfoot, thead, title, tr. Detect this and add // them to an initial list of corrected tags. // // Here we are only dealing with the ones which can have child nodes. // var tableNeedsInnerHTMLFix; var tableInnerHTMLTestElement = document.createElement('table'); try { tableInnerHTMLTestElement.innerHTML = '<tbody></tbody>'; } catch (e) {} finally { tableNeedsInnerHTMLFix = tableInnerHTMLTestElement.childNodes.length === 0; } if (tableNeedsInnerHTMLFix) { tagNamesRequiringInnerHTMLFix = { colgroup: ['table'], table: [], tbody: ['table'], tfoot: ['table'], thead: ['table'], tr: ['table', 'tbody'] }; } // IE 8 doesn't allow setting innerHTML on a select tag. Detect this and // add it to the list of corrected tags. // var selectInnerHTMLTestElement = document.createElement('select'); selectInnerHTMLTestElement.innerHTML = '<option></option>'; if (!selectInnerHTMLTestElement.childNodes[0]) { tagNamesRequiringInnerHTMLFix = tagNamesRequiringInnerHTMLFix || {}; tagNamesRequiringInnerHTMLFix.select = []; } return tagNamesRequiringInnerHTMLFix; })(doc); function scriptSafeInnerHTML(element, html) { // without a leading text node, IE will drop a leading script tag. html = '­' + html; element.innerHTML = html; var nodes = element.childNodes; // Look for ­ to remove it. var shyElement = nodes[0]; while (shyElement.nodeType === 1 && !shyElement.nodeName) { shyElement = shyElement.firstChild; } // At this point it's the actual unicode character. if (shyElement.nodeType === 3 && shyElement.nodeValue.charAt(0) === "\u00AD") { var newValue = shyElement.nodeValue.slice(1); if (newValue.length) { shyElement.nodeValue = shyElement.nodeValue.slice(1); } else { shyElement.parentNode.removeChild(shyElement); } } return nodes; } function buildDOMWithFix(html, contextualElement) { var tagName = contextualElement.tagName; // Firefox versions < 11 do not have support for element.outerHTML. var outerHTML = contextualElement.outerHTML || new XMLSerializer().serializeToString(contextualElement); if (!outerHTML) { throw "Can't set innerHTML on " + tagName + " in this browser"; } html = fixSelect(html, contextualElement); var wrappingTags = tagNamesRequiringInnerHTMLFix[tagName.toLowerCase()]; var startTag = outerHTML.match(new RegExp("<" + tagName + "([^>]*)>", 'i'))[0]; var endTag = '</' + tagName + '>'; var wrappedHTML = [startTag, html, endTag]; var i = wrappingTags.length; var wrappedDepth = 1 + i; while (i--) { wrappedHTML.unshift('<' + wrappingTags[i] + '>'); wrappedHTML.push('</' + wrappingTags[i] + '>'); } var wrapper = document.createElement('div'); scriptSafeInnerHTML(wrapper, wrappedHTML.join('')); var element = wrapper; while (wrappedDepth--) { element = element.firstChild; while (element && element.nodeType !== 1) { element = element.nextSibling; } } while (element && element.tagName !== tagName) { element = element.nextSibling; } return element ? element.childNodes : []; } var buildDOM; if (needsShy) { buildDOM = function buildDOM(html, contextualElement, dom) { html = fixSelect(html, contextualElement); contextualElement = dom.cloneNode(contextualElement, false); scriptSafeInnerHTML(contextualElement, html); return contextualElement.childNodes; }; } else { buildDOM = function buildDOM(html, contextualElement, dom) { html = fixSelect(html, contextualElement); contextualElement = dom.cloneNode(contextualElement, false); contextualElement.innerHTML = html; return contextualElement.childNodes; }; } function fixSelect(html, contextualElement) { if (contextualElement.tagName === 'SELECT') { html = "<option></option>" + html; } return html; } var buildIESafeDOM; if (tagNamesRequiringInnerHTMLFix || movesWhitespace) { buildIESafeDOM = function buildIESafeDOM(html, contextualElement, dom) { // Make a list of the leading text on script nodes. Include // script tags without any whitespace for easier processing later. var spacesBefore = []; var spacesAfter = []; if (typeof html === 'string') { html = html.replace(/(\s*)(<script)/g, function (match, spaces, tag) { spacesBefore.push(spaces); return tag; }); html = html.replace(/(<\/script>)(\s*)/g, function (match, tag, spaces) { spacesAfter.push(spaces); return tag; }); } // Fetch nodes var nodes; if (tagNamesRequiringInnerHTMLFix[contextualElement.tagName.toLowerCase()]) { // buildDOMWithFix uses string wrappers for problematic innerHTML. nodes = buildDOMWithFix(html, contextualElement); } else { nodes = buildDOM(html, contextualElement, dom); } // Build a list of script tags, the nodes themselves will be // mutated as we add test nodes. var i, j, node, nodeScriptNodes; var scriptNodes = []; for (i = 0; i < nodes.length; i++) { node = nodes[i]; if (node.nodeType !== 1) { continue; } if (node.tagName === 'SCRIPT') { scriptNodes.push(node); } else { nodeScriptNodes = node.getElementsByTagName('script'); for (j = 0; j < nodeScriptNodes.length; j++) { scriptNodes.push(nodeScriptNodes[j]); } } } // Walk the script tags and put back their leading text nodes. var scriptNode, textNode, spaceBefore, spaceAfter; for (i = 0; i < scriptNodes.length; i++) { scriptNode = scriptNodes[i]; spaceBefore = spacesBefore[i]; if (spaceBefore && spaceBefore.length > 0) { textNode = dom.document.createTextNode(spaceBefore); scriptNode.parentNode.insertBefore(textNode, scriptNode); } spaceAfter = spacesAfter[i]; if (spaceAfter && spaceAfter.length > 0) { textNode = dom.document.createTextNode(spaceAfter); scriptNode.parentNode.insertBefore(textNode, scriptNode.nextSibling); } } return nodes; }; } else { buildIESafeDOM = buildDOM; } var buildHTMLDOM; if (needsIntegrationPointFix) { exports.buildHTMLDOM = buildHTMLDOM = function buildHTMLDOM(html, contextualElement, dom) { if (svgHTMLIntegrationPoints[contextualElement.tagName]) { return buildIESafeDOM(html, document.createElement('div'), dom); } else { return buildIESafeDOM(html, contextualElement, dom); } }; } else { exports.buildHTMLDOM = buildHTMLDOM = buildIESafeDOM; } exports.buildHTMLDOM = buildHTMLDOM; }); enifed('dom-helper/classes', ['exports'], function (exports) { 'use strict'; var doc = typeof document === 'undefined' ? false : document; // PhantomJS has a broken classList. See https://github.com/ariya/phantomjs/issues/12782 var canClassList = doc && (function () { var d = document.createElement('div'); if (!d.classList) { return false; } d.classList.add('boo'); d.classList.add('boo', 'baz'); return d.className === 'boo baz'; })(); function buildClassList(element) { var classString = element.getAttribute('class') || ''; return classString !== '' && classString !== ' ' ? classString.split(' ') : []; } function intersect(containingArray, valuesArray) { var containingIndex = 0; var containingLength = containingArray.length; var valuesIndex = 0; var valuesLength = valuesArray.length; var intersection = new Array(valuesLength); // TODO: rewrite this loop in an optimal manner for (; containingIndex < containingLength; containingIndex++) { valuesIndex = 0; for (; valuesIndex < valuesLength; valuesIndex++) { if (valuesArray[valuesIndex] === containingArray[containingIndex]) { intersection[valuesIndex] = containingIndex; break; } } } return intersection; } function addClassesViaAttribute(element, classNames) { var existingClasses = buildClassList(element); var indexes = intersect(existingClasses, classNames); var didChange = false; for (var i = 0, l = classNames.length; i < l; i++) { if (indexes[i] === undefined) { didChange = true; existingClasses.push(classNames[i]); } } if (didChange) { element.setAttribute('class', existingClasses.length > 0 ? existingClasses.join(' ') : ''); } } function removeClassesViaAttribute(element, classNames) { var existingClasses = buildClassList(element); var indexes = intersect(classNames, existingClasses); var didChange = false; var newClasses = []; for (var i = 0, l = existingClasses.length; i < l; i++) { if (indexes[i] === undefined) { newClasses.push(existingClasses[i]); } else { didChange = true; } } if (didChange) { element.setAttribute('class', newClasses.length > 0 ? newClasses.join(' ') : ''); } } var addClasses, removeClasses; if (canClassList) { exports.addClasses = addClasses = function addClasses(element, classNames) { if (element.classList) { if (classNames.length === 1) { element.classList.add(classNames[0]); } else if (classNames.length === 2) { element.classList.add(classNames[0], classNames[1]); } else { element.classList.add.apply(element.classList, classNames); } } else { addClassesViaAttribute(element, classNames); } }; exports.removeClasses = removeClasses = function removeClasses(element, classNames) { if (element.classList) { if (classNames.length === 1) { element.classList.remove(classNames[0]); } else if (classNames.length === 2) { element.classList.remove(classNames[0], classNames[1]); } else { element.classList.remove.apply(element.classList, classNames); } } else { removeClassesViaAttribute(element, classNames); } }; } else { exports.addClasses = addClasses = addClassesViaAttribute; exports.removeClasses = removeClasses = removeClassesViaAttribute; } exports.addClasses = addClasses; exports.removeClasses = removeClasses; }); enifed('dom-helper/prop', ['exports'], function (exports) { 'use strict'; exports.isAttrRemovalValue = isAttrRemovalValue; exports.normalizeProperty = normalizeProperty; function isAttrRemovalValue(value) { return value === null || value === undefined; } /* * * @method normalizeProperty * @param element {HTMLElement} * @param slotName {String} * @returns {Object} { name, type } */ function normalizeProperty(element, slotName) { var type, normalized; if (slotName in element) { normalized = slotName; type = 'prop'; } else { var lower = slotName.toLowerCase(); if (lower in element) { type = 'prop'; normalized = lower; } else { type = 'attr'; normalized = slotName; } } if (type === 'prop' && (normalized.toLowerCase() === 'style' || preferAttr(element.tagName, normalized))) { type = 'attr'; } return { normalized: normalized, type: type }; } // properties that MUST be set as attributes, due to: // * browser bug // * strange spec outlier var ATTR_OVERRIDES = { // phantomjs < 2.0 lets you set it as a prop but won't reflect it // back to the attribute. button.getAttribute('type') === null BUTTON: { type: true, form: true }, INPUT: { // TODO: remove when IE8 is droped // Some versions of IE (IE8) throw an exception when setting // `input.list = 'somestring'`: // https://github.com/emberjs/ember.js/issues/10908 // https://github.com/emberjs/ember.js/issues/11364 list: true, // Some version of IE (like IE9) actually throw an exception // if you set input.type = 'something-unknown' type: true, form: true, // Chrome 46.0.2464.0: 'autocorrect' in document.createElement('input') === false // Safari 8.0.7: 'autocorrect' in document.createElement('input') === false // Mobile Safari (iOS 8.4 simulator): 'autocorrect' in document.createElement('input') === true autocorrect: true }, // element.form is actually a legitimate readOnly property, that is to be // mutated, but must be mutated by setAttribute... SELECT: { form: true }, OPTION: { form: true }, TEXTAREA: { form: true }, LABEL: { form: true }, FIELDSET: { form: true }, LEGEND: { form: true }, OBJECT: { form: true } }; function preferAttr(tagName, propName) { var tag = ATTR_OVERRIDES[tagName.toUpperCase()]; return tag && tag[propName.toLowerCase()] || false; } }); enifed('ember-application/index', ['exports', 'ember-metal/core', 'ember-metal/features', 'ember-runtime/system/lazy_load', 'ember-application/system/resolver', 'ember-application/system/application', 'ember-application/system/application-instance', 'ember-application/system/engine', 'ember-application/system/engine-instance', 'ember-application/initializers/dom-templates'], function (exports, _emberMetalCore, _emberMetalFeatures, _emberRuntimeSystemLazy_load, _emberApplicationSystemResolver, _emberApplicationSystemApplication, _emberApplicationSystemApplicationInstance, _emberApplicationSystemEngine, _emberApplicationSystemEngineInstance, _emberApplicationInitializersDomTemplates) { 'use strict'; _emberMetalCore.default.Application = _emberApplicationSystemApplication.default; _emberMetalCore.default.Resolver = _emberApplicationSystemResolver.Resolver; _emberMetalCore.default.DefaultResolver = _emberApplicationSystemResolver.default; if (true) { _emberMetalCore.default.Engine = _emberApplicationSystemEngine.default; // Expose `EngineInstance` and `ApplicationInstance` for easy overriding. // Reanalyze whether to continue exposing these after feature flag is removed. _emberMetalCore.default.EngineInstance = _emberApplicationSystemEngineInstance.default; _emberMetalCore.default.ApplicationInstance = _emberApplicationSystemApplicationInstance.default; } // add domTemplates initializer (only does something if `ember-template-compiler` // is loaded already) _emberRuntimeSystemLazy_load.runLoadHooks('Ember.Application', _emberApplicationSystemApplication.default); }); // reexports /** @module ember @submodule ember-application */ enifed('ember-application/initializers/dom-templates', ['exports', 'require', 'ember-environment', 'ember-application/system/application'], function (exports, _require, _emberEnvironment, _emberApplicationSystemApplication) { 'use strict'; var bootstrap = function () {}; _emberApplicationSystemApplication.default.initializer({ name: 'domTemplates', initialize: function () { var bootstrapModuleId = 'ember-template-compiler/system/bootstrap'; if (_emberEnvironment.environment.hasDOM && _require.has(bootstrapModuleId)) { bootstrap = _require.default(bootstrapModuleId).default; } bootstrap(); } }); }); enifed('ember-application/system/application-instance', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/run_loop', 'ember-metal/computed', 'ember-runtime/mixins/registry_proxy', 'ember-metal/assign', 'ember-environment', 'ember-runtime/ext/rsvp', 'ember-views/system/jquery', 'ember-application/system/engine-instance'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalRun_loop, _emberMetalComputed, _emberRuntimeMixinsRegistry_proxy, _emberMetalAssign, _emberEnvironment, _emberRuntimeExtRsvp, _emberViewsSystemJquery, _emberApplicationSystemEngineInstance) { /** @module ember @submodule ember-application */ 'use strict'; var BootOptions = undefined; /** The `ApplicationInstance` encapsulates all of the stateful aspects of a running `Application`. At a high-level, we break application boot into two distinct phases: * Definition time, where all of the classes, templates, and other dependencies are loaded (typically in the browser). * Run time, where we begin executing the application once everything has loaded. Definition time can be expensive and only needs to happen once since it is an idempotent operation. For example, between test runs and FastBoot requests, the application stays the same. It is only the state that we want to reset. That state is what the `ApplicationInstance` manages: it is responsible for creating the container that contains all application state, and disposing of it once the particular test run or FastBoot request has finished. @public @class Ember.ApplicationInstance @extends Ember.EngineInstance */ var ApplicationInstance = _emberApplicationSystemEngineInstance.default.extend({ /** The `Application` for which this is an instance. @property {Ember.Application} application @private */ application: null, /** The DOM events for which the event dispatcher should listen. By default, the application's `Ember.EventDispatcher` listens for a set of standard DOM events, such as `mousedown` and `keyup`, and delegates them to your application's `Ember.View` instances. @private @property {Object} customEvents */ customEvents: null, /** The root DOM element of the Application as an element or a [jQuery-compatible selector string](http://api.jquery.com/category/selectors/). @private @property {String|DOMElement} rootElement */ rootElement: null, init: function () { this._super.apply(this, arguments); // Register this instance in the per-instance registry. // // Why do we need to register the instance in the first place? // Because we need a good way for the root route (a.k.a ApplicationRoute) // to notify us when it has created the root-most view. That view is then // appended to the rootElement, in the case of apps, to the fixture harness // in tests, or rendered to a string in the case of FastBoot. this.register('-application-instance:main', this, { instantiate: false }); }, /** Overrides the base `EngineInstance._bootSync` method with concerns relevant to booting application (instead of engine) instances. This method should only contain synchronous boot concerns. Asynchronous boot concerns should eventually be moved to the `boot` method, which returns a promise. Until all boot code has been made asynchronous, we need to continue to expose this method for use *internally* in places where we need to boot an instance synchronously. @private */ _bootSync: function (options) { if (this._booted) { return this; } options = new BootOptions(options); this.setupRegistry(options); if (options.rootElement) { this.rootElement = options.rootElement; } else { this.rootElement = this.application.rootElement; } if (options.location) { var router = _emberMetalProperty_get.get(this, 'router'); _emberMetalProperty_set.set(router, 'location', options.location); } this.application.runInstanceInitializers(this); if (options.isInteractive) { this.setupEventDispatcher(); } this._booted = true; return this; }, setupRegistry: function (options) { this.constructor.setupRegistry(this.__registry__, options); }, router: _emberMetalComputed.computed(function () { return this.lookup('router:main'); }).readOnly(), /** This hook is called by the root-most Route (a.k.a. the ApplicationRoute) when it has finished creating the root View. By default, we simply take the view and append it to the `rootElement` specified on the Application. In cases like FastBoot and testing, we can override this hook and implement custom behavior, such as serializing to a string and sending over an HTTP socket rather than appending to DOM. @param view {Ember.View} the root-most view @private */ didCreateRootView: function (view) { view.appendTo(this.rootElement); }, /** Tells the router to start routing. The router will ask the location for the current URL of the page to determine the initial URL to start routing to. To start the app at a specific URL, call `handleURL` instead. @private */ startRouting: function () { var router = _emberMetalProperty_get.get(this, 'router'); router.startRouting(); this._didSetupRouter = true; }, /** @private Sets up the router, initializing the child router and configuring the location before routing begins. Because setup should only occur once, multiple calls to `setupRouter` beyond the first call have no effect. */ setupRouter: function () { if (this._didSetupRouter) { return; } this._didSetupRouter = true; var router = _emberMetalProperty_get.get(this, 'router'); router.setupRouter(); }, /** Directs the router to route to a particular URL. This is useful in tests, for example, to tell the app to start at a particular URL. @param url {String} the URL the router should route to @private */ handleURL: function (url) { var router = _emberMetalProperty_get.get(this, 'router'); this.setupRouter(); return router.handleURL(url); }, /** @private */ setupEventDispatcher: function () { var dispatcher = this.lookup('event_dispatcher:main'); var applicationCustomEvents = _emberMetalProperty_get.get(this.application, 'customEvents'); var instanceCustomEvents = _emberMetalProperty_get.get(this, 'customEvents'); var customEvents = _emberMetalAssign.default({}, applicationCustomEvents, instanceCustomEvents); dispatcher.setup(customEvents, this.rootElement); return dispatcher; }, /** Returns the current URL of the app instance. This is useful when your app does not update the browsers URL bar (i.e. it uses the `'none'` location adapter). @public @return {String} the current URL */ getURL: function () { var router = _emberMetalProperty_get.get(this, 'router'); return _emberMetalProperty_get.get(router, 'url'); }, // `instance.visit(url)` should eventually replace `instance.handleURL()`; // the test helpers can probably be switched to use this implementation too /** Navigate the instance to a particular URL. This is useful in tests, for example, or to tell the app to start at a particular URL. This method returns a promise that resolves with the app instance when the transition is complete, or rejects if the transion was aborted due to an error. @public @param url {String} the destination URL @return {Promise} */ visit: function (url) { var _this = this; this.setupRouter(); var router = _emberMetalProperty_get.get(this, 'router'); var handleResolve = function () { // Resolve only after rendering is complete return new _emberRuntimeExtRsvp.default.Promise(function (resolve) { // TODO: why is this necessary? Shouldn't 'actions' queue be enough? // Also, aren't proimses supposed to be async anyway? _emberMetalRun_loop.default.next(null, resolve, _this); }); }; var handleReject = function (error) { if (error.error) { throw error.error; } else if (error.name === 'TransitionAborted' && router.router.activeTransition) { return router.router.activeTransition.then(handleResolve, handleReject); } else if (error.name === 'TransitionAborted') { throw new Error(error.message); } else { throw error; } }; var location = _emberMetalProperty_get.get(router, 'location'); // Keeps the location adapter's internal URL in-sync location.setURL(url); // getURL returns the set url with the rootURL stripped off return router.handleURL(location.getURL()).then(handleResolve, handleReject); } }); ApplicationInstance.reopenClass({ /** @private @method setupRegistry @param {Registry} registry @param {BootOptions} options */ setupRegistry: function (registry) { var options = arguments.length <= 1 || arguments[1] === undefined ? new BootOptions() : arguments[1]; registry.register('-environment:main', options.toEnvironment(), { instantiate: false }); registry.register('service:-document', options.document, { instantiate: false }); this._super(registry, options); } }); /** A list of boot-time configuration options for customizing the behavior of an `Ember.ApplicationInstance`. This is an interface class that exists purely to document the available options; you do not need to construct it manually. Simply pass a regular JavaScript object containing the desired options into methods that require one of these options object: ```javascript MyApp.visit("/", { location: "none", rootElement: "#container" }); ``` Not all combinations of the supported options are valid. See the documentation on `Ember.Application#visit` for the supported configurations. Internal, experimental or otherwise unstable flags are marked as private. @class BootOptions @namespace Ember.ApplicationInstance @public */ BootOptions = function BootOptions() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; /** Provide a specific instance of jQuery. This is useful in conjunction with the `document` option, as it allows you to use a copy of `jQuery` that is appropriately bound to the foreign `document` (e.g. a jsdom). This is highly experimental and support very incomplete at the moment. @property jQuery @type Object @default auto-detected @private */ this.jQuery = _emberViewsSystemJquery.default; // This default is overridable below /** Interactive mode: whether we need to set up event delegation and invoke lifecycle callbacks on Components. @property isInteractive @type boolean @default auto-detected @private */ this.isInteractive = _emberEnvironment.environment.hasDOM; // This default is overridable below /** Run in a full browser environment. When this flag is set to `false`, it will disable most browser-specific and interactive features. Specifically: * It does not use `jQuery` to append the root view; the `rootElement` (either specified as a subsequent option or on the application itself) must already be an `Element` in the given `document` (as opposed to a string selector). * It does not set up an `EventDispatcher`. * It does not run any `Component` lifecycle hooks (such as `didInsertElement`). * It sets the `location` option to `"none"`. (If you would like to use the location adapter specified in the app's router instead, you can also specify `{ location: null }` to specifically opt-out.) @property isBrowser @type boolean @default auto-detected @public */ if (options.isBrowser !== undefined) { this.isBrowser = !!options.isBrowser; } else { this.isBrowser = _emberEnvironment.environment.hasDOM; } if (!this.isBrowser) { this.jQuery = null; this.isInteractive = false; this.location = 'none'; } /** Disable rendering completely. When this flag is set to `true`, it will disable the entire rendering pipeline. Essentially, this puts the app into "routing-only" mode. No templates will be rendered, and no Components will be created. @property shouldRender @type boolean @default true @public */ if (options.shouldRender !== undefined) { this.shouldRender = !!options.shouldRender; } else { this.shouldRender = true; } if (!this.shouldRender) { this.jQuery = null; this.isInteractive = false; } /** If present, render into the given `Document` object instead of the global `window.document` object. In practice, this is only useful in non-browser environment or in non-interactive mode, because Ember's `jQuery` dependency is implicitly bound to the current document, causing event delegation to not work properly when the app is rendered into a foreign document object (such as an iframe's `contentDocument`). In non-browser mode, this could be a "`Document`-like" object as Ember only interact with a small subset of the DOM API in non- interactive mode. While the exact requirements have not yet been formalized, the `SimpleDOM` library's implementation is known to work. @property document @type Document @default the global `document` object @public */ if (options.document) { this.document = options.document; } else { this.document = typeof document !== 'undefined' ? document : null; } /** If present, overrides the application's `rootElement` property on the instance. This is useful for testing environment, where you might want to append the root view to a fixture area. In non-browser mode, because Ember does not have access to jQuery, this options must be specified as a DOM `Element` object instead of a selector string. See the documentation on `Ember.Applications`'s `rootElement` for details. @property rootElement @type String|Element @default null @public */ if (options.rootElement) { this.rootElement = options.rootElement; } // Set these options last to give the user a chance to override the // defaults from the "combo" options like `isBrowser` (although in // practice, the resulting combination is probably invalid) /** If present, overrides the router's `location` property with this value. This is useful for environments where trying to modify the URL would be inappropriate. @property location @type string @default null @public */ if (options.location !== undefined) { this.location = options.location; } if (options.jQuery !== undefined) { this.jQuery = options.jQuery; } if (options.isInteractive !== undefined) { this.isInteractive = !!options.isInteractive; } }; BootOptions.prototype.toEnvironment = function () { var env = _emberMetalAssign.default({}, _emberEnvironment.environment); // For compatibility with existing code env.hasDOM = this.isBrowser; env.isInteractive = this.isInteractive; env.options = this; return env; }; Object.defineProperty(ApplicationInstance.prototype, 'container', { configurable: true, enumerable: false, get: function () { var instance = this; return { lookup: function () { _emberMetalDebug.deprecate('Using `ApplicationInstance.container.lookup` is deprecated. Please use `ApplicationInstance.lookup` instead.', false, { id: 'ember-application.app-instance-container', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-applicationinstance-container' }); return instance.lookup.apply(instance, arguments); } }; } }); Object.defineProperty(ApplicationInstance.prototype, 'registry', { configurable: true, enumerable: false, get: function () { return _emberRuntimeMixinsRegistry_proxy.buildFakeRegistryWithDeprecations(this, 'ApplicationInstance'); } }); exports.default = ApplicationInstance; }); enifed('ember-application/system/application', ['exports', 'ember-environment', 'ember-metal/debug', 'ember-metal/dictionary', 'ember-metal/libraries', 'ember-metal/testing', 'ember-metal/property_get', 'ember-runtime/system/namespace', 'ember-runtime/system/lazy_load', 'ember-metal/run_loop', 'ember-views/system/event_dispatcher', 'ember-views/system/jquery', 'ember-routing/system/route', 'ember-routing/system/router', 'ember-routing/location/hash_location', 'ember-routing/location/history_location', 'ember-routing/location/auto_location', 'ember-routing/location/none_location', 'ember-routing/system/cache', 'ember-application/system/application-instance', 'ember-runtime/mixins/registry_proxy', 'container/registry', 'ember-runtime/ext/rsvp', 'ember-application/system/engine', 'require'], function (exports, _emberEnvironment, _emberMetalDebug, _emberMetalDictionary, _emberMetalLibraries, _emberMetalTesting, _emberMetalProperty_get, _emberRuntimeSystemNamespace, _emberRuntimeSystemLazy_load, _emberMetalRun_loop, _emberViewsSystemEvent_dispatcher, _emberViewsSystemJquery, _emberRoutingSystemRoute, _emberRoutingSystemRouter, _emberRoutingLocationHash_location, _emberRoutingLocationHistory_location, _emberRoutingLocationAuto_location, _emberRoutingLocationNone_location, _emberRoutingSystemCache, _emberApplicationSystemApplicationInstance, _emberRuntimeMixinsRegistry_proxy, _containerRegistry, _emberRuntimeExtRsvp, _emberApplicationSystemEngine, _require) { /** @module ember @submodule ember-application */ 'use strict'; exports._resetLegacyAddonWarnings = _resetLegacyAddonWarnings; var _templateObject = _taggedTemplateLiteralLoose(['-bucket-cache:main'], ['-bucket-cache:main']); function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } var librariesRegistered = false; var warnedAboutLegacyViewAddon = false; var warnedAboutLegacyControllerAddon = false; // For testing function _resetLegacyAddonWarnings() { warnedAboutLegacyViewAddon = false; warnedAboutLegacyControllerAddon = false; } /** An instance of `Ember.Application` is the starting point for every Ember application. It helps to instantiate, initialize and coordinate the many objects that make up your app. Each Ember app has one and only one `Ember.Application` object. In fact, the very first thing you should do in your application is create the instance: ```javascript window.App = Ember.Application.create(); ``` Typically, the application object is the only global variable. All other classes in your app should be properties on the `Ember.Application` instance, which highlights its first role: a global namespace. For example, if you define a view class, it might look like this: ```javascript App.MyView = Ember.View.extend(); ``` By default, calling `Ember.Application.create()` will automatically initialize your application by calling the `Ember.Application.initialize()` method. If you need to delay initialization, you can call your app's `deferReadiness()` method. When you are ready for your app to be initialized, call its `advanceReadiness()` method. You can define a `ready` method on the `Ember.Application` instance, which will be run by Ember when the application is initialized. Because `Ember.Application` inherits from `Ember.Namespace`, any classes you create will have useful string representations when calling `toString()`. See the `Ember.Namespace` documentation for more information. While you can think of your `Ember.Application` as a container that holds the other classes in your application, there are several other responsibilities going on under-the-hood that you may want to understand. ### Event Delegation Ember uses a technique called _event delegation_. This allows the framework to set up a global, shared event listener instead of requiring each view to do it manually. For example, instead of each view registering its own `mousedown` listener on its associated element, Ember sets up a `mousedown` listener on the `body`. If a `mousedown` event occurs, Ember will look at the target of the event and start walking up the DOM node tree, finding corresponding views and invoking their `mouseDown` method as it goes. `Ember.Application` has a number of default events that it listens for, as well as a mapping from lowercase events to camel-cased view method names. For example, the `keypress` event causes the `keyPress` method on the view to be called, the `dblclick` event causes `doubleClick` to be called, and so on. If there is a bubbling browser event that Ember does not listen for by default, you can specify custom events and their corresponding view method names by setting the application's `customEvents` property: ```javascript let App = Ember.Application.create({ customEvents: { // add support for the paste event paste: 'paste' } }); ``` To prevent Ember from setting up a listener for a default event, specify the event name with a `null` value in the `customEvents` property: ```javascript let App = Ember.Application.create({ customEvents: { // prevent listeners for mouseenter/mouseleave events mouseenter: null, mouseleave: null } }); ``` By default, the application sets up these event listeners on the document body. However, in cases where you are embedding an Ember application inside an existing page, you may want it to set up the listeners on an element inside the body. For example, if only events inside a DOM element with the ID of `ember-app` should be delegated, set your application's `rootElement` property: ```javascript let App = Ember.Application.create({ rootElement: '#ember-app' }); ``` The `rootElement` can be either a DOM element or a jQuery-compatible selector string. Note that *views appended to the DOM outside the root element will not receive events.* If you specify a custom root element, make sure you only append views inside it! To learn more about the events Ember components use, see [components/handling-events](https://guides.emberjs.com/v2.6.0/components/handling-events/#toc_event-names). ### Initializers Libraries on top of Ember can add initializers, like so: ```javascript Ember.Application.initializer({ name: 'api-adapter', initialize: function(application) { application.register('api-adapter:main', ApiAdapter); } }); ``` Initializers provide an opportunity to access the internal registry, which organizes the different components of an Ember application. Additionally they provide a chance to access the instantiated application. Beyond being used for libraries, initializers are also a great way to organize dependency injection or setup in your own application. ### Routing In addition to creating your application's router, `Ember.Application` is also responsible for telling the router when to start routing. Transitions between routes can be logged with the `LOG_TRANSITIONS` flag, and more detailed intra-transition logging can be logged with the `LOG_TRANSITIONS_INTERNAL` flag: ```javascript let App = Ember.Application.create({ LOG_TRANSITIONS: true, // basic logging of successful transitions LOG_TRANSITIONS_INTERNAL: true // detailed logging of all routing steps }); ``` By default, the router will begin trying to translate the current URL into application state once the browser emits the `DOMContentReady` event. If you need to defer routing, you can call the application's `deferReadiness()` method. Once routing can begin, call the `advanceReadiness()` method. If there is any setup required before routing begins, you can implement a `ready()` method on your app that will be invoked immediately before routing begins. @class Application @namespace Ember @extends Ember.Engine @uses RegistryProxyMixin @public */ var Application = _emberApplicationSystemEngine.default.extend({ _suppressDeferredDeprecation: true, /** The root DOM element of the Application. This can be specified as an element or a [jQuery-compatible selector string](http://api.jquery.com/category/selectors/). This is the element that will be passed to the Application's, `eventDispatcher`, which sets up the listeners for event delegation. Every view in your application should be a child of the element you specify here. @property rootElement @type DOMElement @default 'body' @public */ rootElement: 'body', /** The `Ember.EventDispatcher` responsible for delegating events to this application's views. The event dispatcher is created by the application at initialization time and sets up event listeners on the DOM element described by the application's `rootElement` property. See the documentation for `Ember.EventDispatcher` for more information. @property eventDispatcher @type Ember.EventDispatcher @default null @public */ eventDispatcher: null, /** The DOM events for which the event dispatcher should listen. By default, the application's `Ember.EventDispatcher` listens for a set of standard DOM events, such as `mousedown` and `keyup`, and delegates them to your application's `Ember.View` instances. If you would like additional bubbling events to be delegated to your views, set your `Ember.Application`'s `customEvents` property to a hash containing the DOM event name as the key and the corresponding view method name as the value. Setting an event to a value of `null` will prevent a default event listener from being added for that event. To add new events to be listened to: ```javascript let App = Ember.Application.create({ customEvents: { // add support for the paste event paste: 'paste' } }); ``` To prevent default events from being listened to: ```javascript let App = Ember.Application.create({ customEvents: { // remove support for mouseenter / mouseleave events mouseenter: null, mouseleave: null } }); ``` @property customEvents @type Object @default null @public */ customEvents: null, /** Whether the application should automatically start routing and render templates to the `rootElement` on DOM ready. While default by true, other environments such as FastBoot or a testing harness can set this property to `false` and control the precise timing and behavior of the boot process. @property autoboot @type Boolean @default true @private */ autoboot: true, /** Whether the application should be configured for the legacy "globals mode". Under this mode, the Application object serves as a global namespace for all classes. ```javascript let App = Ember.Application.create({ ... }); App.Router.reopen({ location: 'none' }); App.Router.map({ ... }); App.MyComponent = Ember.Component.extend({ ... }); ``` This flag also exposes other internal APIs that assumes the existence of a special "default instance", like `App.__container__.lookup(...)`. This option is currently not configurable, its value is derived from the `autoboot` flag – disabling `autoboot` also implies opting-out of globals mode support, although they are ultimately orthogonal concerns. Some of the global modes features are already deprecated in 1.x. The existence of this flag is to untangle the globals mode code paths from the autoboot code paths, so that these legacy features can be reviewed for deprecation/removal separately. Forcing the (autoboot=true, _globalsMode=false) here and running the tests would reveal all the places where we are still relying on these legacy behavior internally (mostly just tests). @property _globalsMode @type Boolean @default true @private */ _globalsMode: true, init: function (options) { this._super.apply(this, arguments); if (!this.$) { this.$ = _emberViewsSystemJquery.default; } registerLibraries(); logLibraryVersions(); // Start off the number of deferrals at 1. This will be decremented by // the Application's own `boot` method. this._readinessDeferrals = 1; this._booted = false; this.autoboot = this._globalsMode = !!this.autoboot; if (this._globalsMode) { this._prepareForGlobalsMode(); } if (this.autoboot) { this.waitForDOMReady(); } }, /** Create an ApplicationInstance for this application. @private @method buildInstance @return {Ember.ApplicationInstance} the application instance */ buildInstance: function () { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; options.base = this; options.application = this; return _emberApplicationSystemApplicationInstance.default.create(options); }, /** Enable the legacy globals mode by allowing this application to act as a global namespace. See the docs on the `_globalsMode` property for details. Most of these features are already deprecated in 1.x, so we can stop using them internally and try to remove them. @private @method _prepareForGlobalsMode */ _prepareForGlobalsMode: function () { // Create subclass of Ember.Router for this Application instance. // This is to ensure that someone reopening `App.Router` does not // tamper with the default `Ember.Router`. this.Router = (this.Router || _emberRoutingSystemRouter.default).extend(); this._buildDeprecatedInstance(); }, /* Build the deprecated instance for legacy globals mode support. Called when creating and resetting the application. This is orthogonal to autoboot: the deprecated instance needs to be created at Application construction (not boot) time to expose App.__container__. If autoboot sees that this instance exists, it will continue booting it to avoid doing unncessary work (as opposed to building a new instance at boot time), but they are otherwise unrelated. @private @method _buildDeprecatedInstance */ _buildDeprecatedInstance: function () { // Build a default instance var instance = this.buildInstance(); // Legacy support for App.__container__ and other global methods // on App that rely on a single, default instance. this.__deprecatedInstance__ = instance; this.__container__ = instance.__container__; }, /** Automatically kick-off the boot process for the application once the DOM has become ready. The initialization itself is scheduled on the actions queue which ensures that code-loading finishes before booting. If you are asynchronously loading code, you should call `deferReadiness()` to defer booting, and then call `advanceReadiness()` once all of your code has finished loading. @private @method waitForDOMReady */ waitForDOMReady: function () { if (!this.$ || this.$.isReady) { _emberMetalRun_loop.default.schedule('actions', this, 'domReady'); } else { this.$().ready(_emberMetalRun_loop.default.bind(this, 'domReady')); } }, /** This is the autoboot flow: 1. Boot the app by calling `this.boot()` 2. Create an instance (or use the `__deprecatedInstance__` in globals mode) 3. Boot the instance by calling `instance.boot()` 4. Invoke the `App.ready()` callback 5. Kick-off routing on the instance Ideally, this is all we would need to do: ```javascript _autoBoot() { this.boot().then(() => { let instance = (this._globalsMode) ? this.__deprecatedInstance__ : this.buildInstance(); return instance.boot(); }).then((instance) => { App.ready(); instance.startRouting(); }); } ``` Unfortunately, we cannot actually write this because we need to participate in the "synchronous" boot process. While the code above would work fine on the initial boot (i.e. DOM ready), when `App.reset()` is called, we need to boot a new instance synchronously (see the documentation on `_bootSync()` for details). Because of this restriction, the actual logic of this method is located inside `didBecomeReady()`. @private @method domReady */ domReady: function () { if (this.isDestroyed) { return; } this._bootSync(); // Continues to `didBecomeReady` }, /** Use this to defer readiness until some condition is true. Example: ```javascript let App = Ember.Application.create(); App.deferReadiness(); // Ember.$ is a reference to the jQuery object/function Ember.$.getJSON('/auth-token', function(token) { App.token = token; App.advanceReadiness(); }); ``` This allows you to perform asynchronous setup logic and defer booting your application until the setup has finished. However, if the setup requires a loading UI, it might be better to use the router for this purpose. @method deferReadiness @public */ deferReadiness: function () { _emberMetalDebug.assert('You must call deferReadiness on an instance of Ember.Application', this instanceof Application); _emberMetalDebug.assert('You cannot defer readiness since the `ready()` hook has already been called.', this._readinessDeferrals > 0); this._readinessDeferrals++; }, /** Call `advanceReadiness` after any asynchronous setup logic has completed. Each call to `deferReadiness` must be matched by a call to `advanceReadiness` or the application will never become ready and routing will not begin. @method advanceReadiness @see {Ember.Application#deferReadiness} @public */ advanceReadiness: function () { _emberMetalDebug.assert('You must call advanceReadiness on an instance of Ember.Application', this instanceof Application); this._readinessDeferrals--; if (this._readinessDeferrals === 0) { _emberMetalRun_loop.default.once(this, this.didBecomeReady); } }, /** Initialize the application and return a promise that resolves with the `Ember.Application` object when the boot process is complete. Run any application initializers and run the application load hook. These hooks may choose to defer readiness. For example, an authentication hook might want to defer readiness until the auth token has been retrieved. By default, this method is called automatically on "DOM ready"; however, if autoboot is disabled, this is automatically called when the first application instance is created via `visit`. @private @method boot @return {Promise<Ember.Application,Error>} */ boot: function () { if (this._bootPromise) { return this._bootPromise; } try { this._bootSync(); } catch (_) { // Ignore th error: in the asynchronous boot path, the error is already reflected // in the promise rejection } return this._bootPromise; }, /** Unfortunately, a lot of existing code assumes the booting process is "synchronous". Specifically, a lot of tests assumes the last call to `app.advanceReadiness()` or `app.reset()` will result in the app being fully-booted when the current runloop completes. We would like new code (like the `visit` API) to stop making this assumption, so we created the asynchronous version above that returns a promise. But until we have migrated all the code, we would have to expose this method for use *internally* in places where we need to boot an app "synchronously". @private */ _bootSync: function () { if (this._booted) { return; } // Even though this returns synchronously, we still need to make sure the // boot promise exists for book-keeping purposes: if anything went wrong in // the boot process, we need to store the error as a rejection on the boot // promise so that a future caller of `boot()` can tell what failed. var defer = this._bootResolver = new _emberRuntimeExtRsvp.default.defer(); this._bootPromise = defer.promise; try { this.runInitializers(); _emberRuntimeSystemLazy_load.runLoadHooks('application', this); this.advanceReadiness(); // Continues to `didBecomeReady` } catch (error) { // For the asynchronous boot path defer.reject(error); // For the synchronous boot path throw error; } }, /** Reset the application. This is typically used only in tests. It cleans up the application in the following order: 1. Deactivate existing routes 2. Destroy all objects in the container 3. Create a new application container 4. Re-route to the existing url Typical Example: ```javascript let App; run(function() { App = Ember.Application.create(); }); module('acceptance test', { setup: function() { App.reset(); } }); test('first test', function() { // App is freshly reset }); test('second test', function() { // App is again freshly reset }); ``` Advanced Example: Occasionally you may want to prevent the app from initializing during setup. This could enable extra configuration, or enable asserting prior to the app becoming ready. ```javascript let App; run(function() { App = Ember.Application.create(); }); module('acceptance test', { setup: function() { run(function() { App.reset(); App.deferReadiness(); }); } }); test('first test', function() { ok(true, 'something before app is initialized'); run(function() { App.advanceReadiness(); }); ok(true, 'something after app is initialized'); }); ``` @method reset @public */ reset: function () { _emberMetalDebug.assert('Calling reset() on instances of `Ember.Application` is not\n supported when globals mode is disabled; call `visit()` to\n create new `Ember.ApplicationInstance`s and dispose them\n via their `destroy()` method instead.', this._globalsMode && this.autoboot); var instance = this.__deprecatedInstance__; this._readinessDeferrals = 1; this._bootPromise = null; this._bootResolver = null; this._booted = false; function handleReset() { _emberMetalRun_loop.default(instance, 'destroy'); this._buildDeprecatedInstance(); _emberMetalRun_loop.default.schedule('actions', this, '_bootSync'); } _emberMetalRun_loop.default.join(this, handleReset); }, /** @private @method didBecomeReady */ didBecomeReady: function () { try { // TODO: Is this still needed for _globalsMode = false? if (!_emberMetalTesting.isTesting()) { // Eagerly name all classes that are already loaded _emberRuntimeSystemNamespace.default.processAll(); _emberRuntimeSystemNamespace.setSearchDisabled(true); } // See documentation on `_autoboot()` for details if (this.autoboot) { var instance = undefined; if (this._globalsMode) { // If we already have the __deprecatedInstance__ lying around, boot it to // avoid unnecessary work instance = this.__deprecatedInstance__; } else { // Otherwise, build an instance and boot it. This is currently unreachable, // because we forced _globalsMode to === autoboot; but having this branch // allows us to locally toggle that flag for weeding out legacy globals mode // dependencies independently instance = this.buildInstance(); } instance._bootSync(); // TODO: App.ready() is not called when autoboot is disabled, is this correct? this.ready(); instance.startRouting(); } // For the asynchronous boot path this._bootResolver.resolve(this); // For the synchronous boot path this._booted = true; } catch (error) { // For the asynchronous boot path this._bootResolver.reject(error); // For the synchronous boot path throw error; } }, /** Called when the Application has become ready, immediately before routing begins. The call will be delayed until the DOM has become ready. @event ready @public */ ready: function () { return this; }, // This method must be moved to the application instance object willDestroy: function () { this._super.apply(this, arguments); _emberRuntimeSystemNamespace.setSearchDisabled(false); this._booted = false; this._bootPromise = null; this._bootResolver = null; if (_emberRuntimeSystemLazy_load._loaded.application === this) { _emberRuntimeSystemLazy_load._loaded.application = undefined; } if (this._globalsMode && this.__deprecatedInstance__) { this.__deprecatedInstance__.destroy(); } }, /** Boot a new instance of `Ember.ApplicationInstance` for the current application and navigate it to the given `url`. Returns a `Promise` that resolves with the instance when the initial routing and rendering is complete, or rejects with any error that occured during the boot process. When `autoboot` is disabled, calling `visit` would first cause the application to boot, which runs the application initializers. This method also takes a hash of boot-time configuration options for customizing the instance's behavior. See the documentation on `Ember.ApplicationInstance.BootOptions` for details. `Ember.ApplicationInstance.BootOptions` is an interface class that exists purely to document the available options; you do not need to construct it manually. Simply pass a regular JavaScript object containing of the desired options: ```javascript MyApp.visit("/", { location: "none", rootElement: "#container" }); ``` ### Supported Scenarios While the `BootOptions` class exposes a large number of knobs, not all combinations of them are valid; certain incompatible combinations might result in unexpected behavior. For example, booting the instance in the full browser environment while specifying a foriegn `document` object (e.g. `{ isBrowser: true, document: iframe.contentDocument }`) does not work correctly today, largely due to Ember's jQuery dependency. Currently, there are three officially supported scenarios/configurations. Usages outside of these scenarios are not guaranteed to work, but please feel free to file bug reports documenting your experience and any issues you encountered to help expand support. #### Browser Applications (Manual Boot) The setup is largely similar to how Ember works out-of-the-box. Normally, Ember will boot a default instance for your Application on "DOM ready". However, you can customize this behavior by disabling `autoboot`. For example, this allows you to render a miniture demo of your application into a specific area on your marketing website: ```javascript import MyApp from 'my-app'; $(function() { let App = MyApp.create({ autoboot: false }); let options = { // Override the router's location adapter to prevent it from updating // the URL in the address bar location: 'none', // Override the default `rootElement` on the app to render into a // specific `div` on the page rootElement: '#demo' }; // Start the app at the special demo URL App.visit('/demo', options); }); ```` Or perhaps you might want to boot two instances of your app on the same page for a split-screen multiplayer experience: ```javascript import MyApp from 'my-app'; $(function() { let App = MyApp.create({ autoboot: false }); let sessionId = MyApp.generateSessionID(); let player1 = App.visit(`/matches/join?name=Player+1&session=${sessionId}`, { rootElement: '#left', location: 'none' }); let player2 = App.visit(`/matches/join?name=Player+2&session=${sessionId}`, { rootElement: '#right', location: 'none' }); Promise.all([player1, player2]).then(() => { // Both apps have completed the initial render $('#loading').fadeOut(); }); }); ``` Do note that each app instance maintains their own registry/container, so they will run in complete isolation by default. #### Server-Side Rendering (also known as FastBoot) This setup allows you to run your Ember app in a server environment using Node.js and render its content into static HTML for SEO purposes. ```javascript const HTMLSerializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap); function renderURL(url) { let dom = new SimpleDOM.Document(); let rootElement = dom.body; let options = { isBrowser: false, document: dom, rootElement: rootElement }; return MyApp.visit(options).then(instance => { try { return HTMLSerializer.serialize(rootElement.firstChild); } finally { instance.destroy(); } }); } ``` In this scenario, because Ember does not have access to a global `document` object in the Node.js environment, you must provide one explicitly. In practice, in the non-browser environment, the stand-in `document` object only need to implement a limited subset of the full DOM API. The `SimpleDOM` library is known to work. Since there is no access to jQuery in the non-browser environment, you must also specify a DOM `Element` object in the same `document` for the `rootElement` option (as opposed to a selector string like `"body"`). See the documentation on the `isBrowser`, `document` and `rootElement` properties on `Ember.ApplicationInstance.BootOptions` for details. #### Server-Side Resource Discovery This setup allows you to run the routing layer of your Ember app in a server environment using Node.js and completely disable rendering. This allows you to simulate and discover the resources (i.e. AJAX requests) needed to fufill a given request and eagerly "push" these resources to the client. ```app/initializers/network-service.js import BrowserNetworkService from 'app/services/network/browser'; import NodeNetworkService from 'app/services/network/node'; // Inject a (hypothetical) service for abstracting all AJAX calls and use // the appropiate implementaion on the client/server. This also allows the // server to log all the AJAX calls made during a particular request and use // that for resource-discovery purpose. export function initialize(application) { if (window) { // browser application.register('service:network', BrowserNetworkService); } else { // node application.register('service:network', NodeNetworkService); } application.inject('route', 'network', 'service:network'); }; export default { name: 'network-service', initialize: initialize }; ``` ```app/routes/post.js import Ember from 'ember'; // An example of how the (hypothetical) service is used in routes. export default Ember.Route.extend({ model(params) { return this.network.fetch(`/api/posts/${params.post_id}.json`); }, afterModel(post) { if (post.isExternalContent) { return this.network.fetch(`/api/external/?url=${post.externalURL}`); } else { return post; } } }); ``` ```javascript // Finally, put all the pieces together function discoverResourcesFor(url) { return MyApp.visit(url, { isBrowser: false, shouldRender: false }).then(instance => { let networkService = instance.lookup('service:network'); return networkService.requests; // => { "/api/posts/123.json": "..." } }); } ``` @public @method visit @param url {String} The initial URL to navigate to @param options {Ember.ApplicationInstance.BootOptions} @return {Promise<Ember.ApplicationInstance, Error>} */ visit: function (url, options) { var _this = this; return this.boot().then(function () { return _this.buildInstance().boot(options).then(function (instance) { return instance.visit(url); }); }); } }); Object.defineProperty(Application.prototype, 'registry', { configurable: true, enumerable: false, get: function () { return _emberRuntimeMixinsRegistry_proxy.buildFakeRegistryWithDeprecations(this, 'Application'); } }); Application.reopenClass({ /** This creates a registry with the default Ember naming conventions. It also configures the registry: * registered views are created every time they are looked up (they are not singletons) * registered templates are not factories; the registered value is returned directly. * the router receives the application as its `namespace` property * all controllers receive the router as their `target` and `controllers` properties * all controllers receive the application as their `namespace` property * the application view receives the application controller as its `controller` property * the application view receives the application template as its `defaultTemplate` property @method buildRegistry @static @param {Ember.Application} namespace the application for which to build the registry @return {Ember.Registry} the built registry @private */ buildRegistry: function (application) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var registry = this._super.apply(this, arguments); commonSetupRegistry(registry); if (options[_emberApplicationSystemEngine.GLIMMER]) { var glimmerSetupRegistry = _require.default('ember-glimmer/setup-registry').setupApplicationRegistry; glimmerSetupRegistry(registry); } else { var htmlbarsSetupRegistry = _require.default('ember-htmlbars/setup-registry').setupApplicationRegistry; htmlbarsSetupRegistry(registry); } return registry; } }); function commonSetupRegistry(registry) { registry.register('-view-registry:main', { create: function () { return _emberMetalDictionary.default(null); } }); registry.register('route:basic', _emberRoutingSystemRoute.default); registry.register('event_dispatcher:main', _emberViewsSystemEvent_dispatcher.default); registry.injection('router:main', 'namespace', 'application:main'); registry.register('location:auto', _emberRoutingLocationAuto_location.default); registry.register('location:hash', _emberRoutingLocationHash_location.default); registry.register('location:history', _emberRoutingLocationHistory_location.default); registry.register('location:none', _emberRoutingLocationNone_location.default); registry.register(_containerRegistry.privatize(_templateObject), _emberRoutingSystemCache.default); } function registerLibraries() { if (!librariesRegistered) { librariesRegistered = true; if (_emberEnvironment.environment.hasDOM) { _emberMetalLibraries.default.registerCoreLibrary('jQuery', _emberViewsSystemJquery.default().jquery); } } } function logLibraryVersions() { if (_emberEnvironment.ENV.LOG_VERSION) { // we only need to see this once per Application#init _emberEnvironment.ENV.LOG_VERSION = false; var libs = _emberMetalLibraries.default._registry; var nameLengths = libs.map(function (item) { return _emberMetalProperty_get.get(item, 'name.length'); }); var maxNameLength = Math.max.apply(this, nameLengths); _emberMetalDebug.debug('-------------------------------'); for (var i = 0; i < libs.length; i++) { var lib = libs[i]; var spaces = new Array(maxNameLength - lib.name.length + 1).join(' '); _emberMetalDebug.debug([lib.name, spaces, ' : ', lib.version].join('')); } _emberMetalDebug.debug('-------------------------------'); } } exports.default = Application; }); enifed('ember-application/system/engine-instance', ['exports', 'ember-runtime/system/object', 'ember-metal/error', 'container/registry', 'ember-runtime/mixins/container_proxy', 'ember-runtime/mixins/registry_proxy', 'ember-application/system/engine-parent', 'ember-metal/debug', 'ember-metal/run_loop', 'ember-runtime/ext/rsvp', 'ember-metal/features'], function (exports, _emberRuntimeSystemObject, _emberMetalError, _containerRegistry, _emberRuntimeMixinsContainer_proxy, _emberRuntimeMixinsRegistry_proxy, _emberApplicationSystemEngineParent, _emberMetalDebug, _emberMetalRun_loop, _emberRuntimeExtRsvp, _emberMetalFeatures) { /** @module ember @submodule ember-application */ 'use strict'; var _templateObject = _taggedTemplateLiteralLoose(['-bucket-cache:main'], ['-bucket-cache:main']); function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } /** The `EngineInstance` encapsulates all of the stateful aspects of a running `Engine`. @public @class Ember.EngineInstance @extends Ember.Object @uses RegistryProxyMixin @uses ContainerProxyMixin @category ember-application-engines */ var EngineInstance = _emberRuntimeSystemObject.default.extend(_emberRuntimeMixinsRegistry_proxy.default, _emberRuntimeMixinsContainer_proxy.default, { /** The base `Engine` for which this is an instance. @property {Ember.Engine} engine @private */ base: null, init: function () { this._super.apply(this, arguments); var base = this.base; if (!base) { base = this.application; this.base = base; } // Create a per-instance registry that will use the application's registry // as a fallback for resolving registrations. var registry = this.__registry__ = new _containerRegistry.default({ fallback: base.__registry__ }); // Create a per-instance container from the instance's registry this.__container__ = registry.container({ owner: this }); this._booted = false; }, /** Initialize the `Ember.EngineInstance` and return a promise that resolves with the instance itself when the boot process is complete. The primary task here is to run any registered instance initializers. See the documentation on `BootOptions` for the options it takes. @private @method boot @param options {Object} @return {Promise<Ember.EngineInstance,Error>} */ boot: function (options) { var _this = this; if (this._bootPromise) { return this._bootPromise; } this._bootPromise = new _emberRuntimeExtRsvp.default.Promise(function (resolve) { return resolve(_this._bootSync(options)); }); return this._bootPromise; }, /** Unfortunately, a lot of existing code assumes booting an instance is synchronous – specifically, a lot of tests assume the last call to `app.advanceReadiness()` or `app.reset()` will result in a new instance being fully-booted when the current runloop completes. We would like new code (like the `visit` API) to stop making this assumption, so we created the asynchronous version above that returns a promise. But until we have migrated all the code, we would have to expose this method for use *internally* in places where we need to boot an instance synchronously. @private */ _bootSync: function (options) { if (this._booted) { return this; } _emberMetalDebug.assert('An engine instance\'s parent must be set via `setEngineParent(engine, parent)` prior to calling `engine.boot()`.', _emberApplicationSystemEngineParent.getEngineParent(this)); if (true) { this.cloneParentDependencies(); } this.setupRegistry(options); this.base.runInstanceInitializers(this); this._booted = true; return this; }, setupRegistry: function () { var options = arguments.length <= 0 || arguments[0] === undefined ? this.__container__.lookup('-environment:main') : arguments[0]; this.constructor.setupRegistry(this.__registry__, options); }, /** Unregister a factory. Overrides `RegistryProxy#unregister` in order to clear any cached instances of the unregistered factory. @public @method unregister @param {String} fullName */ unregister: function (fullName) { this.__container__.reset(fullName); this._super.apply(this, arguments); }, /** @private */ willDestroy: function () { this._super.apply(this, arguments); _emberMetalRun_loop.default(this.__container__, 'destroy'); } }); EngineInstance.reopenClass({ /** @private @method setupRegistry @param {Registry} registry @param {BootOptions} options */ setupRegistry: function (registry, options) { // when no options/environment is present, do nothing if (!options) { return; } registry.injection('view', '_environment', '-environment:main'); registry.injection('route', '_environment', '-environment:main'); if (options.isInteractive) { registry.injection('view', 'renderer', 'renderer:-dom'); registry.injection('component', 'renderer', 'renderer:-dom'); } else { registry.injection('view', 'renderer', 'renderer:-inert'); registry.injection('component', 'renderer', 'renderer:-inert'); } } }); if (true) { EngineInstance.reopen({ /** Build a new `Ember.EngineInstance` that's a child of this instance. Engines must be registered by name with their parent engine (or application). @private @method buildChildEngineInstance @param name {String} the registered name of the engine. @param options {Object} options provided to the engine instance. @return {Ember.EngineInstance,Error} */ buildChildEngineInstance: function (name) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var Engine = this.lookup('engine:' + name); if (!Engine) { throw new _emberMetalError.default('You attempted to mount the engine \'' + name + '\', but it is not registered with its parent.'); } var engineInstance = Engine.buildInstance(options); _emberApplicationSystemEngineParent.setEngineParent(engineInstance, this); return engineInstance; }, /** Clone dependencies shared between an engine instance and its parent. @private @method cloneParentDependencies */ cloneParentDependencies: function () { var _this2 = this; var parent = _emberApplicationSystemEngineParent.getEngineParent(this); var registrations = ['route:basic', 'event_dispatcher:main', 'service:-routing']; if (false) { registrations.push('service:-glimmer-environment'); } registrations.forEach(function (key) { return _this2.register(key, parent.resolveRegistration(key)); }); var env = parent.lookup('-environment:main'); this.register('-environment:main', env, { instantiate: false }); var singletons = ['router:main', _containerRegistry.privatize(_templateObject), '-view-registry:main', 'renderer:-' + (env.isInteractive ? 'dom' : 'inert')]; singletons.forEach(function (key) { return _this2.register(key, parent.lookup(key), { instantiate: false }); }); this.inject('view', '_environment', '-environment:main'); this.inject('route', '_environment', '-environment:main'); } }); } exports.default = EngineInstance; }); enifed('ember-application/system/engine-parent', ['exports', 'ember-metal/symbol'], function (exports, _emberMetalSymbol) { /** @module ember @submodule ember-application */ 'use strict'; exports.getEngineParent = getEngineParent; exports.setEngineParent = setEngineParent; var ENGINE_PARENT = _emberMetalSymbol.default('ENGINE_PARENT'); exports.ENGINE_PARENT = ENGINE_PARENT; /** `getEngineParent` retrieves an engine instance's parent instance. @method getEngineParent @param {EngineInstance} engine An engine instance. @return {EngineInstance} The parent engine instance. @for Ember @public */ function getEngineParent(engine) { return engine[ENGINE_PARENT]; } /** `setEngineParent` sets an engine instance's parent instance. @method setEngineParent @param {EngineInstance} engine An engine instance. @param {EngineInstance} parent The parent engine instance. @private */ function setEngineParent(engine, parent) { engine[ENGINE_PARENT] = parent; } }); enifed('ember-application/system/engine', ['exports', 'ember-runtime/system/namespace', 'container/registry', 'ember-runtime/mixins/registry_proxy', 'dag-map', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/debug', 'ember-metal/utils', 'ember-metal/empty_object', 'ember-application/system/resolver', 'ember-application/system/engine-instance', 'ember-metal/features', 'ember-metal/symbol', 'ember-runtime/controllers/controller', 'ember-routing/services/routing', 'ember-extension-support/container_debug_adapter', 'ember-views/component_lookup', 'require'], function (exports, _emberRuntimeSystemNamespace, _containerRegistry, _emberRuntimeMixinsRegistry_proxy, _dagMap, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalDebug, _emberMetalUtils, _emberMetalEmpty_object, _emberApplicationSystemResolver, _emberApplicationSystemEngineInstance, _emberMetalFeatures, _emberMetalSymbol, _emberRuntimeControllersController, _emberRoutingServicesRouting, _emberExtensionSupportContainer_debug_adapter, _emberViewsComponent_lookup, _require) { /** @module ember @submodule ember-application */ 'use strict'; var _templateObject = _taggedTemplateLiteralLoose(['-bucket-cache:main'], ['-bucket-cache:main']); function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } var GLIMMER = _emberMetalSymbol.default('GLIMMER'); exports.GLIMMER = GLIMMER; function props(obj) { var properties = []; for (var key in obj) { properties.push(key); } return properties; } /** The `Engine` class contains core functionality for both applications and engines. Each engine manages a registry that's used for dependency injection and exposed through `RegistryProxy`. Engines also manage initializers and instance initializers. Engines can spawn `EngineInstance` instances via `buildInstance()`. @class Engine @namespace Ember @extends Ember.Namespace @uses RegistryProxy @category ember-application-engines @public */ var Engine = _emberRuntimeSystemNamespace.default.extend(_emberRuntimeMixinsRegistry_proxy.default, { init: function () { this._super.apply(this, arguments); if (this[GLIMMER] === undefined) { this[GLIMMER] = false; } this.buildRegistry(); }, /** A private flag indicating whether an engine's initializers have run yet. @private @property _initializersRan */ _initializersRan: false, /** Ensure that initializers are run once, and only once, per engine. @private @method ensureInitializers */ ensureInitializers: function () { if (!this._initializersRan) { this.runInitializers(); this._initializersRan = true; } }, /** Create an EngineInstance for this engine. @private @method buildInstance @return {Ember.EngineInstance} the engine instance */ buildInstance: function () { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.ensureInitializers(); options.base = this; return _emberApplicationSystemEngineInstance.default.create(options); }, /** Build and configure the registry for the current engine. @private @method buildRegistry @return {Ember.Registry} the configured registry */ buildRegistry: function () { var _constructor$buildRegistry; var registry = this.__registry__ = this.constructor.buildRegistry(this, (_constructor$buildRegistry = {}, _constructor$buildRegistry[GLIMMER] = this[GLIMMER], _constructor$buildRegistry)); return registry; }, /** @private @method initializer */ initializer: function (options) { this.constructor.initializer(options); }, /** @private @method instanceInitializer */ instanceInitializer: function (options) { this.constructor.instanceInitializer(options); }, /** @private @method runInitializers */ runInitializers: function () { var _this = this; this._runInitializer('initializers', function (name, initializer) { _emberMetalDebug.assert('No application initializer named \'' + name + '\'', !!initializer); if (initializer.initialize.length === 2) { _emberMetalDebug.deprecate('The `initialize` method for Application initializer \'' + name + '\' should take only one argument - `App`, an instance of an `Application`.', false, { id: 'ember-application.app-initializer-initialize-arguments', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_initializer-arity' }); initializer.initialize(_this.__registry__, _this); } else { initializer.initialize(_this); } }); }, /** @private @since 1.12.0 @method runInstanceInitializers */ runInstanceInitializers: function (instance) { this._runInitializer('instanceInitializers', function (name, initializer) { _emberMetalDebug.assert('No instance initializer named \'' + name + '\'', !!initializer); initializer.initialize(instance); }); }, _runInitializer: function (bucketName, cb) { var initializersByName = _emberMetalProperty_get.get(this.constructor, bucketName); var initializers = props(initializersByName); var graph = new _dagMap.default(); var initializer = undefined; for (var i = 0; i < initializers.length; i++) { initializer = initializersByName[initializers[i]]; graph.addEdges(initializer.name, initializer, initializer.before, initializer.after); } graph.topsort(function (vertex) { return cb(vertex.name, vertex.value); }); } }); Engine.reopenClass({ initializers: new _emberMetalEmpty_object.default(), instanceInitializers: new _emberMetalEmpty_object.default(), /** The goal of initializers should be to register dependencies and injections. This phase runs once. Because these initializers may load code, they are allowed to defer application readiness and advance it. If you need to access the container or store you should use an InstanceInitializer that will be run after all initializers and therefore after all code is loaded and the app is ready. Initializer receives an object which has the following attributes: `name`, `before`, `after`, `initialize`. The only required attribute is `initialize`, all others are optional. * `name` allows you to specify under which name the initializer is registered. This must be a unique name, as trying to register two initializers with the same name will result in an error. ```javascript Ember.Application.initializer({ name: 'namedInitializer', initialize: function(application) { Ember.debug('Running namedInitializer!'); } }); ``` * `before` and `after` are used to ensure that this initializer is ran prior or after the one identified by the value. This value can be a single string or an array of strings, referencing the `name` of other initializers. An example of ordering initializers, we create an initializer named `first`: ```javascript Ember.Application.initializer({ name: 'first', initialize: function(application) { Ember.debug('First initializer!'); } }); // DEBUG: First initializer! ``` We add another initializer named `second`, specifying that it should run after the initializer named `first`: ```javascript Ember.Application.initializer({ name: 'second', after: 'first', initialize: function(application) { Ember.debug('Second initializer!'); } }); // DEBUG: First initializer! // DEBUG: Second initializer! ``` Afterwards we add a further initializer named `pre`, this time specifying that it should run before the initializer named `first`: ```javascript Ember.Application.initializer({ name: 'pre', before: 'first', initialize: function(application) { Ember.debug('Pre initializer!'); } }); // DEBUG: Pre initializer! // DEBUG: First initializer! // DEBUG: Second initializer! ``` Finally we add an initializer named `post`, specifying it should run after both the `first` and the `second` initializers: ```javascript Ember.Application.initializer({ name: 'post', after: ['first', 'second'], initialize: function(application) { Ember.debug('Post initializer!'); } }); // DEBUG: Pre initializer! // DEBUG: First initializer! // DEBUG: Second initializer! // DEBUG: Post initializer! ``` * `initialize` is a callback function that receives one argument, `application`, on which you can operate. Example of using `application` to register an adapter: ```javascript Ember.Application.initializer({ name: 'api-adapter', initialize: function(application) { application.register('api-adapter:main', ApiAdapter); } }); ``` @method initializer @param initializer {Object} @public */ initializer: buildInitializerMethod('initializers', 'initializer'), /** Instance initializers run after all initializers have run. Because instance initializers run after the app is fully set up. We have access to the store, container, and other items. However, these initializers run after code has loaded and are not allowed to defer readiness. Instance initializer receives an object which has the following attributes: `name`, `before`, `after`, `initialize`. The only required attribute is `initialize`, all others are optional. * `name` allows you to specify under which name the instanceInitializer is registered. This must be a unique name, as trying to register two instanceInitializer with the same name will result in an error. ```javascript Ember.Application.instanceInitializer({ name: 'namedinstanceInitializer', initialize: function(application) { Ember.debug('Running namedInitializer!'); } }); ``` * `before` and `after` are used to ensure that this initializer is ran prior or after the one identified by the value. This value can be a single string or an array of strings, referencing the `name` of other initializers. * See Ember.Application.initializer for discussion on the usage of before and after. Example instanceInitializer to preload data into the store. ```javascript Ember.Application.initializer({ name: 'preload-data', initialize: function(application) { var userConfig, userConfigEncoded, store; // We have a HTML escaped JSON representation of the user's basic // configuration generated server side and stored in the DOM of the main // index.html file. This allows the app to have access to a set of data // without making any additional remote calls. Good for basic data that is // needed for immediate rendering of the page. Keep in mind, this data, // like all local models and data can be manipulated by the user, so it // should not be relied upon for security or authorization. // // Grab the encoded data from the meta tag userConfigEncoded = Ember.$('head meta[name=app-user-config]').attr('content'); // Unescape the text, then parse the resulting JSON into a real object userConfig = JSON.parse(unescape(userConfigEncoded)); // Lookup the store store = application.lookup('service:store'); // Push the encoded JSON into the store store.pushPayload(userConfig); } }); ``` @method instanceInitializer @param instanceInitializer @public */ instanceInitializer: buildInitializerMethod('instanceInitializers', 'instance initializer'), /** This creates a registry with the default Ember naming conventions. It also configures the registry: * registered views are created every time they are looked up (they are not singletons) * registered templates are not factories; the registered value is returned directly. * the router receives the application as its `namespace` property * all controllers receive the router as their `target` and `controllers` properties * all controllers receive the application as their `namespace` property * the application view receives the application controller as its `controller` property * the application view receives the application template as its `defaultTemplate` property @method buildRegistry @static @param {Ember.Application} namespace the application for which to build the registry @return {Ember.Registry} the built registry @private */ buildRegistry: function (namespace) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var registry = new _containerRegistry.default({ resolver: resolverFor(namespace) }); registry.set = _emberMetalProperty_set.set; registry.register('application:main', namespace, { instantiate: false }); commonSetupRegistry(registry); if (options[GLIMMER]) { var glimmerSetupRegistry = _require.default('ember-glimmer/setup-registry').setupEngineRegistry; glimmerSetupRegistry(registry); } else { var htmlbarsSetupRegistry = _require.default('ember-htmlbars/setup-registry').setupEngineRegistry; htmlbarsSetupRegistry(registry); } return registry; }, /** Set this to provide an alternate class to `Ember.DefaultResolver` @deprecated Use 'Resolver' instead @property resolver @public */ resolver: null, /** Set this to provide an alternate class to `Ember.DefaultResolver` @property resolver @public */ Resolver: null }); /** This function defines the default lookup rules for container lookups: * templates are looked up on `Ember.TEMPLATES` * other names are looked up on the application after classifying the name. For example, `controller:post` looks up `App.PostController` by default. * if the default lookup fails, look for registered classes on the container This allows the application to register default injections in the container that could be overridden by the normal naming convention. @private @method resolverFor @param {Ember.Namespace} namespace the namespace to look for classes @return {*} the resolved value for a given lookup */ function resolverFor(namespace) { var ResolverClass = namespace.get('Resolver') || _emberApplicationSystemResolver.default; return ResolverClass.create({ namespace: namespace }); } function buildInitializerMethod(bucketName, humanName) { return function (initializer) { // If this is the first initializer being added to a subclass, we are going to reopen the class // to make sure we have a new `initializers` object, which extends from the parent class' using // prototypal inheritance. Without this, attempting to add initializers to the subclass would // pollute the parent class as well as other subclasses. if (this.superclass[bucketName] !== undefined && this.superclass[bucketName] === this[bucketName]) { var attrs = {}; attrs[bucketName] = Object.create(this[bucketName]); this.reopenClass(attrs); } _emberMetalDebug.assert('The ' + humanName + ' \'' + initializer.name + '\' has already been registered', !this[bucketName][initializer.name]); _emberMetalDebug.assert('An ' + humanName + ' cannot be registered without an initialize function', _emberMetalUtils.canInvoke(initializer, 'initialize')); _emberMetalDebug.assert('An ' + humanName + ' cannot be registered without a name property', initializer.name !== undefined); this[bucketName][initializer.name] = initializer; }; } function commonSetupRegistry(registry) { registry.optionsForType('component', { singleton: false }); registry.optionsForType('view', { singleton: false }); registry.injection('renderer', 'dom', 'service:-dom-helper'); registry.register('controller:basic', _emberRuntimeControllersController.default, { instantiate: false }); registry.injection('service:-dom-helper', 'document', 'service:-document'); registry.injection('view', '_viewRegistry', '-view-registry:main'); registry.injection('renderer', '_viewRegistry', '-view-registry:main'); registry.injection('event_dispatcher:main', '_viewRegistry', '-view-registry:main'); registry.injection('route', '_topLevelViewTemplate', 'template:-outlet'); registry.injection('view:-outlet', 'namespace', 'application:main'); registry.injection('controller', 'target', 'router:main'); registry.injection('controller', 'namespace', 'application:main'); registry.injection('router', '_bucketCache', _containerRegistry.privatize(_templateObject)); registry.injection('route', '_bucketCache', _containerRegistry.privatize(_templateObject)); registry.injection('controller', '_bucketCache', _containerRegistry.privatize(_templateObject)); registry.injection('route', 'router', 'router:main'); // Register the routing service... registry.register('service:-routing', _emberRoutingServicesRouting.default); // Then inject the app router into it registry.injection('service:-routing', 'router', 'router:main'); // DEBUGGING registry.register('resolver-for-debugging:main', registry.resolver, { instantiate: false }); registry.injection('container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main'); registry.injection('data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main'); // Custom resolver authors may want to register their own ContainerDebugAdapter with this key registry.register('container-debug-adapter:main', _emberExtensionSupportContainer_debug_adapter.default); registry.register('component-lookup:main', _emberViewsComponent_lookup.default); } exports.default = Engine; }); enifed('ember-application/system/resolver', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-runtime/system/string', 'ember-runtime/system/object', 'ember-runtime/system/namespace', 'ember-application/utils/validate-type', 'ember-metal/dictionary', 'ember-templates/template_registry'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberRuntimeSystemString, _emberRuntimeSystemObject, _emberRuntimeSystemNamespace, _emberApplicationUtilsValidateType, _emberMetalDictionary, _emberTemplatesTemplate_registry) { /** @module ember @submodule ember-application */ 'use strict'; var Resolver = _emberRuntimeSystemObject.default.extend({ /* This will be set to the Application instance when it is created. @property namespace */ namespace: null, normalize: null, // required resolve: null, // required parseName: null, // required lookupDescription: null, // required makeToString: null, // required resolveOther: null, // required _logLookup: null // required }); exports.Resolver = Resolver; /** The DefaultResolver defines the default lookup rules to resolve container lookups before consulting the container for registered items: * templates are looked up on `Ember.TEMPLATES` * other names are looked up on the application after converting the name. For example, `controller:post` looks up `App.PostController` by default. * there are some nuances (see examples below) ### How Resolving Works The container calls this object's `resolve` method with the `fullName` argument. It first parses the fullName into an object using `parseName`. Then it checks for the presence of a type-specific instance method of the form `resolve[Type]` and calls it if it exists. For example if it was resolving 'template:post', it would call the `resolveTemplate` method. Its last resort is to call the `resolveOther` method. The methods of this object are designed to be easy to override in a subclass. For example, you could enhance how a template is resolved like so: ```javascript App = Ember.Application.create({ Resolver: Ember.DefaultResolver.extend({ resolveTemplate: function(parsedName) { let resolvedTemplate = this._super(parsedName); if (resolvedTemplate) { return resolvedTemplate; } return Ember.TEMPLATES['not_found']; } }) }); ``` Some examples of how names are resolved: ``` 'template:post' //=> Ember.TEMPLATES['post'] 'template:posts/byline' //=> Ember.TEMPLATES['posts/byline'] 'template:posts.byline' //=> Ember.TEMPLATES['posts/byline'] 'template:blogPost' //=> Ember.TEMPLATES['blogPost'] // OR // Ember.TEMPLATES['blog_post'] 'controller:post' //=> App.PostController 'controller:posts.index' //=> App.PostsIndexController 'controller:blog/post' //=> Blog.PostController 'controller:basic' //=> Ember.Controller 'route:post' //=> App.PostRoute 'route:posts.index' //=> App.PostsIndexRoute 'route:blog/post' //=> Blog.PostRoute 'route:basic' //=> Ember.Route 'view:post' //=> App.PostView 'view:posts.index' //=> App.PostsIndexView 'view:blog/post' //=> Blog.PostView 'view:basic' //=> Ember.View 'foo:post' //=> App.PostFoo 'model:post' //=> App.Post ``` @class DefaultResolver @namespace Ember @extends Ember.Object @public */ exports.default = _emberRuntimeSystemObject.default.extend({ /** This will be set to the Application instance when it is created. @property namespace @public */ namespace: null, init: function () { this._parseNameCache = _emberMetalDictionary.default(null); }, normalize: function (fullName) { var _fullName$split = fullName.split(':', 2); var type = _fullName$split[0]; var name = _fullName$split[1]; _emberMetalDebug.assert('Tried to normalize a container name without a colon (:) in it. ' + 'You probably tried to lookup a name that did not contain a type, ' + 'a colon, and a name. A proper lookup name would be `view:post`.', fullName.split(':').length === 2); if (type !== 'template') { var result = name; if (result.indexOf('.') > -1) { result = result.replace(/\.(.)/g, function (m) { return m.charAt(1).toUpperCase(); }); } if (name.indexOf('_') > -1) { result = result.replace(/_(.)/g, function (m) { return m.charAt(1).toUpperCase(); }); } if (name.indexOf('-') > -1) { result = result.replace(/-(.)/g, function (m) { return m.charAt(1).toUpperCase(); }); } return type + ':' + result; } else { return fullName; } }, /** This method is called via the container's resolver method. It parses the provided `fullName` and then looks up and returns the appropriate template or class. @method resolve @param {String} fullName the lookup string @return {Object} the resolved factory @public */ resolve: function (fullName) { var parsedName = this.parseName(fullName); var resolveMethodName = parsedName.resolveMethodName; var resolved; if (this[resolveMethodName]) { resolved = this[resolveMethodName](parsedName); } resolved = resolved || this.resolveOther(parsedName); if (parsedName.root && parsedName.root.LOG_RESOLVER) { this._logLookup(resolved, parsedName); } if (resolved) { _emberApplicationUtilsValidateType.default(resolved, parsedName); } return resolved; }, /** Convert the string name of the form 'type:name' to a Javascript object with the parsed aspects of the name broken out. @param {String} fullName the lookup string @method parseName @protected */ parseName: function (fullName) { return this._parseNameCache[fullName] || (this._parseNameCache[fullName] = this._parseName(fullName)); }, _parseName: function (fullName) { var _fullName$split2 = fullName.split(':'); var type = _fullName$split2[0]; var fullNameWithoutType = _fullName$split2[1]; var name = fullNameWithoutType; var namespace = _emberMetalProperty_get.get(this, 'namespace'); var root = namespace; var lastSlashIndex = name.lastIndexOf('/'); var dirname = lastSlashIndex !== -1 ? name.slice(0, lastSlashIndex) : null; if (type !== 'template' && lastSlashIndex !== -1) { var parts = name.split('/'); name = parts[parts.length - 1]; var namespaceName = _emberRuntimeSystemString.capitalize(parts.slice(0, -1).join('.')); root = _emberRuntimeSystemNamespace.default.byName(namespaceName); _emberMetalDebug.assert('You are looking for a ' + name + ' ' + type + ' in the ' + namespaceName + ' namespace, but the namespace could not be found', root); } var resolveMethodName = fullNameWithoutType === 'main' ? 'Main' : _emberRuntimeSystemString.classify(type); if (!(name && type)) { throw new TypeError('Invalid fullName: `' + fullName + '`, must be of the form `type:name` '); } return { fullName: fullName, type: type, fullNameWithoutType: fullNameWithoutType, dirname: dirname, name: name, root: root, resolveMethodName: 'resolve' + resolveMethodName }; }, /** Returns a human-readable description for a fullName. Used by the Application namespace in assertions to describe the precise name of the class that Ember is looking for, rather than container keys. @param {String} fullName the lookup string @method lookupDescription @protected */ lookupDescription: function (fullName) { var parsedName = this.parseName(fullName); var description = undefined; if (parsedName.type === 'template') { return 'template at ' + parsedName.fullNameWithoutType.replace(/\./g, '/'); } description = parsedName.root + '.' + _emberRuntimeSystemString.classify(parsedName.name).replace(/\./g, ''); if (parsedName.type !== 'model') { description += _emberRuntimeSystemString.classify(parsedName.type); } return description; }, makeToString: function (factory, fullName) { return factory.toString(); }, /** Given a parseName object (output from `parseName`), apply the conventions expected by `Ember.Router` @param {Object} parsedName a parseName object with the parsed fullName lookup string @method useRouterNaming @protected */ useRouterNaming: function (parsedName) { parsedName.name = parsedName.name.replace(/\./g, '_'); if (parsedName.name === 'basic') { parsedName.name = ''; } }, /** Look up the template in Ember.TEMPLATES @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveTemplate @protected */ resolveTemplate: function (parsedName) { var templateName = parsedName.fullNameWithoutType.replace(/\./g, '/'); return _emberTemplatesTemplate_registry.get(templateName) || _emberTemplatesTemplate_registry.get(_emberRuntimeSystemString.decamelize(templateName)); }, /** Lookup the view using `resolveOther` @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveView @protected */ resolveView: function (parsedName) { this.useRouterNaming(parsedName); return this.resolveOther(parsedName); }, /** Lookup the controller using `resolveOther` @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveController @protected */ resolveController: function (parsedName) { this.useRouterNaming(parsedName); return this.resolveOther(parsedName); }, /** Lookup the route using `resolveOther` @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveRoute @protected */ resolveRoute: function (parsedName) { this.useRouterNaming(parsedName); return this.resolveOther(parsedName); }, /** Lookup the model on the Application namespace @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveModel @protected */ resolveModel: function (parsedName) { var className = _emberRuntimeSystemString.classify(parsedName.name); var factory = _emberMetalProperty_get.get(parsedName.root, className); return factory; }, /** Look up the specified object (from parsedName) on the appropriate namespace (usually on the Application) @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveHelper @protected */ resolveHelper: function (parsedName) { return this.resolveOther(parsedName); }, /** Look up the specified object (from parsedName) on the appropriate namespace (usually on the Application) @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveOther @protected */ resolveOther: function (parsedName) { var className = _emberRuntimeSystemString.classify(parsedName.name) + _emberRuntimeSystemString.classify(parsedName.type); var factory = _emberMetalProperty_get.get(parsedName.root, className); return factory; }, resolveMain: function (parsedName) { var className = _emberRuntimeSystemString.classify(parsedName.type); return _emberMetalProperty_get.get(parsedName.root, className); }, /** @method _logLookup @param {Boolean} found @param {Object} parsedName @private */ _logLookup: function (found, parsedName) { var symbol = undefined, padding = undefined; if (found) { symbol = '[✓]'; } else { symbol = '[ ]'; } if (parsedName.fullName.length > 60) { padding = '.'; } else { padding = new Array(60 - parsedName.fullName.length).join('.'); } _emberMetalDebug.info(symbol, parsedName.fullName, padding, this.lookupDescription(parsedName.fullName)); }, /** Used to iterate all items of a given type. @method knownForType @param {String} type the type to search for @private */ knownForType: function (type) { var namespace = _emberMetalProperty_get.get(this, 'namespace'); var suffix = _emberRuntimeSystemString.classify(type); var typeRegexp = new RegExp(suffix + '$'); var known = _emberMetalDictionary.default(null); var knownKeys = Object.keys(namespace); for (var index = 0; index < knownKeys.length; index++) { var _name = knownKeys[index]; if (typeRegexp.test(_name)) { var containerName = this.translateToContainerFullname(type, _name); known[containerName] = true; } } return known; }, /** Converts provided name from the backing namespace into a container lookup name. Examples: App.FooBarHelper -> helper:foo-bar App.THelper -> helper:t @method translateToContainerFullname @param {String} type @param {String} name @private */ translateToContainerFullname: function (type, name) { var suffix = _emberRuntimeSystemString.classify(type); var namePrefix = name.slice(0, suffix.length * -1); var dasherizedName = _emberRuntimeSystemString.dasherize(namePrefix); return type + ':' + dasherizedName; } }); }); enifed('ember-application/utils/validate-type', ['exports', 'ember-metal/debug'], function (exports, _emberMetalDebug) { /** @module ember @submodule ember-application */ 'use strict'; exports.default = validateType; var VALIDATED_TYPES = { route: ['assert', 'isRouteFactory', 'Ember.Route'], component: ['deprecate', 'isComponentFactory', 'Ember.Component'], view: ['deprecate', 'isViewFactory', 'Ember.View'], service: ['deprecate', 'isServiceFactory', 'Ember.Service'] }; function validateType(resolvedType, parsedName) { var validationAttributes = VALIDATED_TYPES[parsedName.type]; if (!validationAttributes) { return; } var action = validationAttributes[0]; var factoryFlag = validationAttributes[1]; var expectedType = validationAttributes[2]; if (action === 'deprecate') { _emberMetalDebug.deprecate('In Ember 2.0 ' + parsedName.type + ' factories must have an `' + factoryFlag + '` ' + ('property set to true. You registered ' + resolvedType + ' as a ' + parsedName.type + ' ') + ('factory. Either add the `' + factoryFlag + '` property to this factory or ') + ('extend from ' + expectedType + '.'), !!resolvedType[factoryFlag], { id: 'ember-application.validate-type', until: '3.0.0' }); } else { _emberMetalDebug.assert('Expected ' + parsedName.fullName + ' to resolve to an ' + expectedType + ' but ' + ('instead it was ' + resolvedType + '.'), !!resolvedType[factoryFlag]); } } }); enifed('ember-console/index', ['exports', 'ember-environment'], function (exports, _emberEnvironment) { 'use strict'; function K() {} function consoleMethod(name) { var consoleObj = undefined; if (_emberEnvironment.context.imports.console) { consoleObj = _emberEnvironment.context.imports.console; } else if (typeof console !== 'undefined') { consoleObj = console; } var method = typeof consoleObj === 'object' ? consoleObj[name] : null; if (typeof method !== 'function') { return; } if (typeof method.bind === 'function') { return method.bind(consoleObj); } return function () { method.apply(consoleObj, arguments); }; } function assertPolyfill(test, message) { if (!test) { try { // attempt to preserve the stack throw new Error('assertion failed: ' + message); } catch (error) { setTimeout(function () { throw error; }, 0); } } } /** Inside Ember-Metal, simply uses the methods from `imports.console`. Override this to provide more robust logging functionality. @class Logger @namespace Ember @public */ exports.default = { /** Logs the arguments to the console. You can pass as many arguments as you want and they will be joined together with a space. ```javascript var foo = 1; Ember.Logger.log('log value of foo:', foo); // "log value of foo: 1" will be printed to the console ``` @method log @for Ember.Logger @param {*} arguments @public */ log: consoleMethod('log') || K, /** Prints the arguments to the console with a warning icon. You can pass as many arguments as you want and they will be joined together with a space. ```javascript Ember.Logger.warn('Something happened!'); // "Something happened!" will be printed to the console with a warning icon. ``` @method warn @for Ember.Logger @param {*} arguments @public */ warn: consoleMethod('warn') || K, /** Prints the arguments to the console with an error icon, red text and a stack trace. You can pass as many arguments as you want and they will be joined together with a space. ```javascript Ember.Logger.error('Danger! Danger!'); // "Danger! Danger!" will be printed to the console in red text. ``` @method error @for Ember.Logger @param {*} arguments @public */ error: consoleMethod('error') || K, /** Logs the arguments to the console. You can pass as many arguments as you want and they will be joined together with a space. ```javascript var foo = 1; Ember.Logger.info('log value of foo:', foo); // "log value of foo: 1" will be printed to the console ``` @method info @for Ember.Logger @param {*} arguments @public */ info: consoleMethod('info') || K, /** Logs the arguments to the console in blue text. You can pass as many arguments as you want and they will be joined together with a space. ```javascript var foo = 1; Ember.Logger.debug('log value of foo:', foo); // "log value of foo: 1" will be printed to the console ``` @method debug @for Ember.Logger @param {*} arguments @public */ debug: consoleMethod('debug') || consoleMethod('info') || K, /** If the value passed into `Ember.Logger.assert` is not truthy it will throw an error with a stack trace. ```javascript Ember.Logger.assert(true); // undefined Ember.Logger.assert(true === false); // Throws an Assertion failed error. Ember.Logger.assert(true === false, 'Something invalid'); // Throws an Assertion failed error with message. ``` @method assert @for Ember.Logger @param {Boolean} bool Value to test @param {String} message Assertion message on failed @public */ assert: consoleMethod('assert') || assertPolyfill }; }); enifed('ember-debug/deprecate', ['exports', 'ember-metal/error', 'ember-console', 'ember-environment', 'ember-debug/handlers'], function (exports, _emberMetalError, _emberConsole, _emberEnvironment, _emberDebugHandlers) { /*global __fail__*/ 'use strict'; var _slice = Array.prototype.slice; exports.registerHandler = registerHandler; exports.default = deprecate; function registerHandler(handler) { _emberDebugHandlers.registerHandler('deprecate', handler); } function formatMessage(_message, options) { var message = _message; if (options && options.id) { message = message + (' [deprecation id: ' + options.id + ']'); } if (options && options.url) { message += ' See ' + options.url + ' for more details.'; } return message; } registerHandler(function logDeprecationToConsole(message, options) { var updatedMessage = formatMessage(message, options); _emberConsole.default.warn('DEPRECATION: ' + updatedMessage); }); var captureErrorForStack = undefined; if (new Error().stack) { captureErrorForStack = function () { return new Error(); }; } else { captureErrorForStack = function () { try { __fail__.fail(); } catch (e) { return e; } }; } registerHandler(function logDeprecationStackTrace(message, options, next) { if (_emberEnvironment.ENV.LOG_STACKTRACE_ON_DEPRECATION) { var stackStr = ''; var error = captureErrorForStack(); var stack = undefined; if (error.stack) { if (error['arguments']) { // Chrome stack = error.stack.replace(/^\s+at\s+/gm, '').replace(/^([^\(]+?)([\n$])/gm, '{anonymous}($1)$2').replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}($1)').split('\n'); stack.shift(); } else { // Firefox stack = error.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^\(/gm, '{anonymous}(').split('\n'); } stackStr = '\n ' + stack.slice(2).join('\n '); } var updatedMessage = formatMessage(message, options); _emberConsole.default.warn('DEPRECATION: ' + updatedMessage + stackStr); } else { next.apply(undefined, arguments); } }); registerHandler(function raiseOnDeprecation(message, options, next) { if (_emberEnvironment.ENV.RAISE_ON_DEPRECATION) { var updatedMessage = formatMessage(message); throw new _emberMetalError.default(updatedMessage); } else { next.apply(undefined, arguments); } }); var missingOptionsDeprecation = 'When calling `Ember.deprecate` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include `id` and `until` properties.'; exports.missingOptionsDeprecation = missingOptionsDeprecation; var missingOptionsIdDeprecation = 'When calling `Ember.deprecate` you must provide `id` in options.'; exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation; var missingOptionsUntilDeprecation = 'When calling `Ember.deprecate` you must provide `until` in options.'; exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation; /** @module ember @submodule ember-debug */ /** Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only). * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. @method deprecate @param {String} message A description of the deprecation. @param {Boolean} test A boolean. If falsy, the deprecation will be displayed. @param {Object} options @param {String} options.id A unique id for this deprecation. The id can be used by Ember debugging tools to change the behavior (raise, log or silence) for that specific deprecation. The id should be namespaced by dots, e.g. "view.helper.select". @param {string} options.until The version of Ember when this deprecation warning will be removed. @param {String} [options.url] An optional url to the transition guide on the emberjs.com website. @for Ember @public */ function deprecate(message, test, options) { if (!options || !options.id && !options.until) { deprecate(missingOptionsDeprecation, false, { id: 'ember-debug.deprecate-options-missing', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } if (options && !options.id) { deprecate(missingOptionsIdDeprecation, false, { id: 'ember-debug.deprecate-id-missing', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } if (options && !options.until) { deprecate(missingOptionsUntilDeprecation, options && options.until, { id: 'ember-debug.deprecate-until-missing', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } _emberDebugHandlers.invoke.apply(undefined, ['deprecate'].concat(_slice.call(arguments))); } }); enifed("ember-debug/handlers", ["exports"], function (exports) { "use strict"; exports.registerHandler = registerHandler; exports.invoke = invoke; var HANDLERS = {}; exports.HANDLERS = HANDLERS; function registerHandler(type, callback) { var nextHandler = HANDLERS[type] || function () {}; HANDLERS[type] = function (message, options) { callback(message, options, nextHandler); }; } function invoke(type, message, test, options) { if (test) { return; } var handlerForType = HANDLERS[type]; if (!handlerForType) { return; } if (handlerForType) { handlerForType(message, options); } } }); enifed('ember-debug/index', ['exports', 'ember-metal/core', 'ember-environment', 'ember-metal/testing', 'ember-metal/debug', 'ember-metal/features', 'ember-metal/error', 'ember-console', 'ember-debug/deprecate', 'ember-debug/warn'], function (exports, _emberMetalCore, _emberEnvironment, _emberMetalTesting, _emberMetalDebug, _emberMetalFeatures, _emberMetalError, _emberConsole, _emberDebugDeprecate, _emberDebugWarn) { 'use strict'; exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags; /** @module ember @submodule ember-debug */ /** @class Ember @public */ /** Define an assertion that will throw an exception if the condition is not met. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. ```javascript // Test for truthiness Ember.assert('Must pass a valid object', obj); // Fail unconditionally Ember.assert('This code path should never be run'); ``` @method assert @param {String} desc A description of the assertion. This will become the text of the Error thrown if the assertion fails. @param {Boolean} test Must be truthy for the assertion to pass. If falsy, an exception will be thrown. @public */ _emberMetalDebug.setDebugFunction('assert', function assert(desc, test) { if (!test) { throw new _emberMetalError.default('Assertion Failed: ' + desc); } }); /** Display a debug notice. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. ```javascript Ember.debug('I\'m a debug notice!'); ``` @method debug @param {String} message A debug message to display. @public */ _emberMetalDebug.setDebugFunction('debug', function debug(message) { _emberConsole.default.debug('DEBUG: ' + message); }); /** Display an info notice. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. @method info @private */ _emberMetalDebug.setDebugFunction('info', function info() { _emberConsole.default.info.apply(undefined, arguments); }); /** Alias an old, deprecated method with its new counterpart. Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only) when the assigned method is called. * In a production build, this method is defined as an empty function (NOP). ```javascript Ember.oldMethod = Ember.deprecateFunc('Please use the new, updated method', Ember.newMethod); ``` @method deprecateFunc @param {String} message A description of the deprecation. @param {Object} [options] The options object for Ember.deprecate. @param {Function} func The new function called to replace its deprecated counterpart. @return {Function} A new function that wraps the original function with a deprecation warning @private */ _emberMetalDebug.setDebugFunction('deprecateFunc', function deprecateFunc() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length === 3) { var _ret = (function () { var message = args[0]; var options = args[1]; var func = args[2]; return { v: function () { _emberMetalDebug.deprecate(message, false, options); return func.apply(this, arguments); } }; })(); if (typeof _ret === 'object') return _ret.v; } else { var _ret2 = (function () { var message = args[0]; var func = args[1]; return { v: function () { _emberMetalDebug.deprecate(message); return func.apply(this, arguments); } }; })(); if (typeof _ret2 === 'object') return _ret2.v; } }); /** Run a function meant for debugging. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. ```javascript Ember.runInDebug(() => { Ember.Component.reopen({ didInsertElement() { console.log("I'm happy"); } }); }); ``` @method runInDebug @param {Function} func The function to be executed. @since 1.5.0 @public */ _emberMetalDebug.setDebugFunction('runInDebug', function runInDebug(func) { func(); }); _emberMetalDebug.setDebugFunction('debugSeal', function debugSeal(obj) { Object.seal(obj); }); _emberMetalDebug.setDebugFunction('deprecate', _emberDebugDeprecate.default); _emberMetalDebug.setDebugFunction('warn', _emberDebugWarn.default); /** Will call `Ember.warn()` if ENABLE_OPTIONAL_FEATURES or any specific FEATURES flag is truthy. This method is called automatically in debug canary builds. @private @method _warnIfUsingStrippedFeatureFlags @return {void} */ function _warnIfUsingStrippedFeatureFlags(FEATURES, knownFeatures, featuresWereStripped) { if (featuresWereStripped) { _emberMetalDebug.warn('Ember.ENV.ENABLE_OPTIONAL_FEATURES is only available in canary builds.', !_emberEnvironment.ENV.ENABLE_OPTIONAL_FEATURES, { id: 'ember-debug.feature-flag-with-features-stripped' }); var keys = Object.keys(FEATURES || {}); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key === 'isEnabled' || !(key in knownFeatures)) { continue; } _emberMetalDebug.warn('FEATURE["' + key + '"] is set as enabled, but FEATURE flags are only available in canary builds.', !FEATURES[key], { id: 'ember-debug.feature-flag-with-features-stripped' }); } } } if (!_emberMetalTesting.isTesting()) { (function () { // Complain if they're using FEATURE flags in builds other than canary _emberMetalFeatures.FEATURES['features-stripped-test'] = true; var featuresWereStripped = true; if (false) { featuresWereStripped = false; } delete _emberMetalFeatures.FEATURES['features-stripped-test']; _warnIfUsingStrippedFeatureFlags(_emberEnvironment.ENV.FEATURES, _emberMetalFeatures.DEFAULT_FEATURES, featuresWereStripped); // Inform the developer about the Ember Inspector if not installed. var isFirefox = _emberEnvironment.environment.isFirefox; var isChrome = _emberEnvironment.environment.isChrome; if (typeof window !== 'undefined' && (isFirefox || isChrome) && window.addEventListener) { window.addEventListener('load', function () { if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset.emberExtension) { var downloadURL; if (isChrome) { downloadURL = 'https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi'; } else if (isFirefox) { downloadURL = 'https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/'; } _emberMetalDebug.debug('For more advanced debugging, install the Ember Inspector from ' + downloadURL); } }, false); } })(); } /** @public @class Ember.Debug */ _emberMetalCore.default.Debug = {}; /** Allows for runtime registration of handler functions that override the default deprecation behavior. Deprecations are invoked by calls to [Ember.deprecate](http://emberjs.com/api/classes/Ember.html#method_deprecate). The following example demonstrates its usage by registering a handler that throws an error if the message contains the word "should", otherwise defers to the default handler. ```javascript Ember.Debug.registerDeprecationHandler((message, options, next) => { if (message.indexOf('should') !== -1) { throw new Error(`Deprecation message with should: ${message}`); } else { // defer to whatever handler was registered before this one next(message, options); } } ``` The handler function takes the following arguments: <ul> <li> <code>message</code> - The message received from the deprecation call.</li> <li> <code>options</code> - An object passed in with the deprecation call containing additional information including:</li> <ul> <li> <code>id</code> - An id of the deprecation in the form of <code>package-name.specific-deprecation</code>.</li> <li> <code>until</code> - The Ember version number the feature and deprecation will be removed in.</li> </ul> <li> <code>next</code> - A function that calls into the previously registered handler.</li> </ul> @public @static @method registerDeprecationHandler @param handler {Function} A function to handle deprecation calls. @since 2.1.0 */ _emberMetalCore.default.Debug.registerDeprecationHandler = _emberDebugDeprecate.registerHandler; /** Allows for runtime registration of handler functions that override the default warning behavior. Warnings are invoked by calls made to [Ember.warn](http://emberjs.com/api/classes/Ember.html#method_warn). The following example demonstrates its usage by registering a handler that does nothing overriding Ember's default warning behavior. ```javascript // next is not called, so no warnings get the default behavior Ember.Debug.registerWarnHandler(() => {}); ``` The handler function takes the following arguments: <ul> <li> <code>message</code> - The message received from the warn call. </li> <li> <code>options</code> - An object passed in with the warn call containing additional information including:</li> <ul> <li> <code>id</code> - An id of the warning in the form of <code>package-name.specific-warning</code>.</li> </ul> <li> <code>next</code> - A function that calls into the previously registered handler.</li> </ul> @public @static @method registerWarnHandler @param handler {Function} A function to handle warnings. @since 2.1.0 */ _emberMetalCore.default.Debug.registerWarnHandler = _emberDebugWarn.registerHandler; /* We are transitioning away from `ember.js` to `ember.debug.js` to make it much clearer that it is only for local development purposes. This flag value is changed by the tooling (by a simple string replacement) so that if `ember.js` (which must be output for backwards compat reasons) is used a nice helpful warning message will be printed out. */ var runningNonEmberDebugJS = false; exports.runningNonEmberDebugJS = runningNonEmberDebugJS; if (runningNonEmberDebugJS) { _emberMetalDebug.warn('Please use `ember.debug.js` instead of `ember.js` for development and debugging.'); } }); // reexports enifed('ember-debug/warn', ['exports', 'ember-console', 'ember-metal/debug', 'ember-debug/handlers'], function (exports, _emberConsole, _emberMetalDebug, _emberDebugHandlers) { 'use strict'; var _slice = Array.prototype.slice; exports.registerHandler = registerHandler; exports.default = warn; function registerHandler(handler) { _emberDebugHandlers.registerHandler('warn', handler); } registerHandler(function logWarning(message, options) { _emberConsole.default.warn('WARNING: ' + message); if ('trace' in _emberConsole.default) { _emberConsole.default.trace(); } }); var missingOptionsDeprecation = 'When calling `Ember.warn` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include an `id` property.'; exports.missingOptionsDeprecation = missingOptionsDeprecation; var missingOptionsIdDeprecation = 'When calling `Ember.warn` you must provide `id` in options.'; exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation; /** @module ember @submodule ember-debug */ /** Display a warning with the provided message. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. @method warn @param {String} message A warning to display. @param {Boolean} test An optional boolean. If falsy, the warning will be displayed. @param {Object} options An object that can be used to pass a unique `id` for this warning. The `id` can be used by Ember debugging tools to change the behavior (raise, log, or silence) for that specific warning. The `id` should be namespaced by dots, e.g. "ember-debug.feature-flag-with-features-stripped" @for Ember @public */ function warn(message, test, options) { if (!options) { _emberMetalDebug.deprecate(missingOptionsDeprecation, false, { id: 'ember-debug.warn-options-missing', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } if (options && !options.id) { _emberMetalDebug.deprecate(missingOptionsIdDeprecation, false, { id: 'ember-debug.warn-id-missing', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } _emberDebugHandlers.invoke.apply(undefined, ['warn'].concat(_slice.call(arguments))); } }); enifed('ember-environment/global', ['exports'], function (exports) { /* globals global, window, self, mainContext */ // from lodash to catch fake globals 'use strict'; function checkGlobal(value) { return value && value.Object === Object ? value : undefined; } // element ids can ruin global miss checks function checkElementIdShadowing(value) { return value && value.nodeType === undefined ? value : undefined; } // export real global exports.default = checkGlobal(checkElementIdShadowing(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || mainContext || // set before strict mode in Ember loader/wrapper new Function('return this')(); // eval outside of strict mode }); enifed('ember-environment/index', ['exports', 'ember-environment/global', 'ember-environment/utils'], function (exports, _emberEnvironmentGlobal, _emberEnvironmentUtils) { /* globals module */ 'use strict'; /** The hash of environment variables used to control various configuration settings. To specify your own or override default settings, add the desired properties to a global hash named `EmberENV` (or `ENV` for backwards compatibility with earlier versions of Ember). The `EmberENV` hash must be created before loading Ember. @class EmberENV @type Object @public */ var ENV = typeof _emberEnvironmentGlobal.default.EmberENV === 'object' && _emberEnvironmentGlobal.default.EmberENV || typeof _emberEnvironmentGlobal.default.ENV === 'object' && _emberEnvironmentGlobal.default.ENV || {}; exports.ENV = ENV; // ENABLE_ALL_FEATURES was documented, but you can't actually enable non optional features. if (ENV.ENABLE_ALL_FEATURES) { ENV.ENABLE_OPTIONAL_FEATURES = true; } /** Determines whether Ember should add to `Array`, `Function`, and `String` native object prototypes, a few extra methods in order to provide a more friendly API. We generally recommend leaving this option set to true however, if you need to turn it off, you can add the configuration property `EXTEND_PROTOTYPES` to `EmberENV` and set it to `false`. Note, when disabled (the default configuration for Ember Addons), you will instead have to access all methods and functions from the Ember namespace. @property EXTEND_PROTOTYPES @type Boolean @default true @for EmberENV @public */ ENV.EXTEND_PROTOTYPES = _emberEnvironmentUtils.normalizeExtendPrototypes(ENV.EXTEND_PROTOTYPES); /** The `LOG_STACKTRACE_ON_DEPRECATION` property, when true, tells Ember to log a full stack trace during deprecation warnings. @property LOG_STACKTRACE_ON_DEPRECATION @type Boolean @default true @for EmberENV @public */ ENV.LOG_STACKTRACE_ON_DEPRECATION = _emberEnvironmentUtils.defaultTrue(ENV.LOG_STACKTRACE_ON_DEPRECATION); /** The `LOG_VERSION` property, when true, tells Ember to log versions of all dependent libraries in use. @property LOG_VERSION @type Boolean @default true @for EmberENV @public */ ENV.LOG_VERSION = _emberEnvironmentUtils.defaultTrue(ENV.LOG_VERSION); // default false ENV.MODEL_FACTORY_INJECTIONS = _emberEnvironmentUtils.defaultFalse(ENV.MODEL_FACTORY_INJECTIONS); /** Debug parameter you can turn on. This will log all bindings that fire to the console. This should be disabled in production code. Note that you can also enable this from the console or temporarily. @property LOG_BINDINGS @for EmberENV @type Boolean @default false @public */ ENV.LOG_BINDINGS = _emberEnvironmentUtils.defaultFalse(ENV.LOG_BINDINGS); ENV.RAISE_ON_DEPRECATION = _emberEnvironmentUtils.defaultFalse(ENV.RAISE_ON_DEPRECATION); // check if window exists and actually is the global var hasDOM = typeof window !== 'undefined' && window === _emberEnvironmentGlobal.default && window.document && window.document.createElement && !ENV.disableBrowserEnvironment; // is this a public thing? // legacy imports/exports/lookup stuff (should we keep this??) var originalContext = _emberEnvironmentGlobal.default.Ember || {}; var context = { // import jQuery imports: originalContext.imports || _emberEnvironmentGlobal.default, // export Ember exports: originalContext.exports || _emberEnvironmentGlobal.default, // search for Namespaces lookup: originalContext.lookup || _emberEnvironmentGlobal.default }; exports.context = context; // TODO: cleanup single source of truth issues with this stuff var environment = hasDOM ? { hasDOM: true, isChrome: !!window.chrome && !window.opera, isFirefox: typeof InstallTrigger !== 'undefined', isPhantom: !!window.callPhantom, location: window.location, history: window.history, userAgent: window.navigator.userAgent, window: window } : { hasDOM: false, isChrome: false, isFirefox: false, isPhantom: false, location: null, history: null, userAgent: 'Lynx (textmode)', window: null }; exports.environment = environment; }); enifed("ember-environment/utils", ["exports"], function (exports) { "use strict"; exports.defaultTrue = defaultTrue; exports.defaultFalse = defaultFalse; exports.normalizeExtendPrototypes = normalizeExtendPrototypes; function defaultTrue(v) { return v === false ? false : true; } function defaultFalse(v) { return v === true ? true : false; } function normalizeExtendPrototypes(obj) { if (obj === false) { return { String: false, Array: false, Function: false }; } else if (!obj || obj === true) { return { String: true, Array: true, Function: true }; } else { return { String: defaultTrue(obj.String), Array: defaultTrue(obj.Array), Function: defaultTrue(obj.Function) }; } } }); enifed('ember-extension-support/container_debug_adapter', ['exports', 'ember-metal/core', 'ember-runtime/system/native_array', 'ember-runtime/utils', 'ember-runtime/system/string', 'ember-runtime/system/namespace', 'ember-runtime/system/object'], function (exports, _emberMetalCore, _emberRuntimeSystemNative_array, _emberRuntimeUtils, _emberRuntimeSystemString, _emberRuntimeSystemNamespace, _emberRuntimeSystemObject) { 'use strict'; /** @module ember @submodule ember-extension-support */ /** The `ContainerDebugAdapter` helps the container and resolver interface with tools that debug Ember such as the [Ember Extension](https://github.com/tildeio/ember-extension) for Chrome and Firefox. This class can be extended by a custom resolver implementer to override some of the methods with library-specific code. The methods likely to be overridden are: * `canCatalogEntriesByType` * `catalogEntriesByType` The adapter will need to be registered in the application's container as `container-debug-adapter:main`. Example: ```javascript Application.initializer({ name: "containerDebugAdapter", initialize(application) { application.register('container-debug-adapter:main', require('app/container-debug-adapter')); } }); ``` @class ContainerDebugAdapter @namespace Ember @extends Ember.Object @since 1.5.0 @public */ exports.default = _emberRuntimeSystemObject.default.extend({ /** The resolver instance of the application being debugged. This property will be injected on creation. @property resolver @default null @public */ resolver: null, /** Returns true if it is possible to catalog a list of available classes in the resolver for a given type. @method canCatalogEntriesByType @param {String} type The type. e.g. "model", "controller", "route". @return {boolean} whether a list is available for this type. @public */ canCatalogEntriesByType: function (type) { if (type === 'model' || type === 'template') { return false; } return true; }, /** Returns the available classes a given type. @method catalogEntriesByType @param {String} type The type. e.g. "model", "controller", "route". @return {Array} An array of strings. @public */ catalogEntriesByType: function (type) { var namespaces = _emberRuntimeSystemNative_array.A(_emberRuntimeSystemNamespace.default.NAMESPACES); var types = _emberRuntimeSystemNative_array.A(); var typeSuffixRegex = new RegExp(_emberRuntimeSystemString.classify(type) + '$'); namespaces.forEach(function (namespace) { if (namespace !== _emberMetalCore.default) { for (var key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } if (typeSuffixRegex.test(key)) { var klass = namespace[key]; if (_emberRuntimeUtils.typeOf(klass) === 'class') { types.push(_emberRuntimeSystemString.dasherize(key.replace(typeSuffixRegex, ''))); } } } } }); return types; } }); }); // Ember as namespace enifed('ember-extension-support/data_adapter', ['exports', 'ember-metal/property_get', 'ember-metal/run_loop', 'ember-runtime/system/string', 'ember-runtime/system/namespace', 'ember-runtime/system/object', 'ember-runtime/system/native_array', 'ember-application/system/application', 'container/owner', 'ember-runtime/mixins/array'], function (exports, _emberMetalProperty_get, _emberMetalRun_loop, _emberRuntimeSystemString, _emberRuntimeSystemNamespace, _emberRuntimeSystemObject, _emberRuntimeSystemNative_array, _emberApplicationSystemApplication, _containerOwner, _emberRuntimeMixinsArray) { 'use strict'; /** @module ember @submodule ember-extension-support */ /** The `DataAdapter` helps a data persistence library interface with tools that debug Ember such as the [Ember Extension](https://github.com/tildeio/ember-extension) for Chrome and Firefox. This class will be extended by a persistence library which will override some of the methods with library-specific code. The methods likely to be overridden are: * `getFilters` * `detect` * `columnsForType` * `getRecords` * `getRecordColumnValues` * `getRecordKeywords` * `getRecordFilterValues` * `getRecordColor` * `observeRecord` The adapter will need to be registered in the application's container as `dataAdapter:main`. Example: ```javascript Application.initializer({ name: "data-adapter", initialize: function(application) { application.register('data-adapter:main', DS.DataAdapter); } }); ``` @class DataAdapter @namespace Ember @extends EmberObject @public */ exports.default = _emberRuntimeSystemObject.default.extend({ init: function () { this._super.apply(this, arguments); this.releaseMethods = _emberRuntimeSystemNative_array.A(); }, /** The container-debug-adapter which is used to list all models. @property containerDebugAdapter @default undefined @since 1.5.0 @public **/ containerDebugAdapter: undefined, /** The number of attributes to send as columns. (Enough to make the record identifiable). @private @property attributeLimit @default 3 @since 1.3.0 */ attributeLimit: 3, /** Ember Data > v1.0.0-beta.18 requires string model names to be passed around instead of the actual factories. This is a stamp for the Ember Inspector to differentiate between the versions to be able to support older versions too. @public @property acceptsModelName */ acceptsModelName: true, /** Stores all methods that clear observers. These methods will be called on destruction. @private @property releaseMethods @since 1.3.0 */ releaseMethods: _emberRuntimeSystemNative_array.A(), /** Specifies how records can be filtered. Records returned will need to have a `filterValues` property with a key for every name in the returned array. @public @method getFilters @return {Array} List of objects defining filters. The object should have a `name` and `desc` property. */ getFilters: function () { return _emberRuntimeSystemNative_array.A(); }, /** Fetch the model types and observe them for changes. @public @method watchModelTypes @param {Function} typesAdded Callback to call to add types. Takes an array of objects containing wrapped types (returned from `wrapModelType`). @param {Function} typesUpdated Callback to call when a type has changed. Takes an array of objects containing wrapped types. @return {Function} Method to call to remove all observers */ watchModelTypes: function (typesAdded, typesUpdated) { var _this = this; var modelTypes = this.getModelTypes(); var releaseMethods = _emberRuntimeSystemNative_array.A(); var typesToSend = undefined; typesToSend = modelTypes.map(function (type) { var klass = type.klass; var wrapped = _this.wrapModelType(klass, type.name); releaseMethods.push(_this.observeModelType(type.name, typesUpdated)); return wrapped; }); typesAdded(typesToSend); var release = function () { releaseMethods.forEach(function (fn) { return fn(); }); _this.releaseMethods.removeObject(release); }; this.releaseMethods.pushObject(release); return release; }, _nameToClass: function (type) { if (typeof type === 'string') { type = _containerOwner.getOwner(this)._lookupFactory('model:' + type); } return type; }, /** Fetch the records of a given type and observe them for changes. @public @method watchRecords @param {String} modelName The model name. @param {Function} recordsAdded Callback to call to add records. Takes an array of objects containing wrapped records. The object should have the following properties: columnValues: {Object} The key and value of a table cell. object: {Object} The actual record object. @param {Function} recordsUpdated Callback to call when a record has changed. Takes an array of objects containing wrapped records. @param {Function} recordsRemoved Callback to call when a record has removed. Takes the following parameters: index: The array index where the records were removed. count: The number of records removed. @return {Function} Method to call to remove all observers. */ watchRecords: function (modelName, recordsAdded, recordsUpdated, recordsRemoved) { var _this2 = this; var releaseMethods = _emberRuntimeSystemNative_array.A(); var klass = this._nameToClass(modelName); var records = this.getRecords(klass, modelName); var release = undefined; function recordUpdated(updatedRecord) { recordsUpdated([updatedRecord]); } var recordsToSend = records.map(function (record) { releaseMethods.push(_this2.observeRecord(record, recordUpdated)); return _this2.wrapRecord(record); }); var contentDidChange = function (array, idx, removedCount, addedCount) { for (var i = idx; i < idx + addedCount; i++) { var record = _emberRuntimeMixinsArray.objectAt(array, i); var wrapped = _this2.wrapRecord(record); releaseMethods.push(_this2.observeRecord(record, recordUpdated)); recordsAdded([wrapped]); } if (removedCount) { recordsRemoved(idx, removedCount); } }; var observer = { didChange: contentDidChange, willChange: function () { return this; } }; _emberRuntimeMixinsArray.addArrayObserver(records, this, observer); release = function () { releaseMethods.forEach(function (fn) { return fn(); }); _emberRuntimeMixinsArray.removeArrayObserver(records, _this2, observer); _this2.releaseMethods.removeObject(release); }; recordsAdded(recordsToSend); this.releaseMethods.pushObject(release); return release; }, /** Clear all observers before destruction @private @method willDestroy */ willDestroy: function () { this._super.apply(this, arguments); this.releaseMethods.forEach(function (fn) { return fn(); }); }, /** Detect whether a class is a model. Test that against the model class of your persistence library. @private @method detect @param {Class} klass The class to test. @return boolean Whether the class is a model class or not. */ detect: function (klass) { return false; }, /** Get the columns for a given model type. @private @method columnsForType @param {Class} type The model type. @return {Array} An array of columns of the following format: name: {String} The name of the column. desc: {String} Humanized description (what would show in a table column name). */ columnsForType: function (type) { return _emberRuntimeSystemNative_array.A(); }, /** Adds observers to a model type class. @private @method observeModelType @param {String} modelName The model type name. @param {Function} typesUpdated Called when a type is modified. @return {Function} The function to call to remove observers. */ observeModelType: function (modelName, typesUpdated) { var _this3 = this; var klass = this._nameToClass(modelName); var records = this.getRecords(klass, modelName); function onChange() { typesUpdated([this.wrapModelType(klass, modelName)]); } var observer = { didChange: function () { _emberMetalRun_loop.default.scheduleOnce('actions', this, onChange); }, willChange: function () { return this; } }; _emberRuntimeMixinsArray.addArrayObserver(records, this, observer); var release = function () { return _emberRuntimeMixinsArray.removeArrayObserver(records, _this3, observer); }; return release; }, /** Wraps a given model type and observes changes to it. @private @method wrapModelType @param {Class} klass A model class. @param {String} modelName Name of the class. @return {Object} Contains the wrapped type and the function to remove observers Format: type: {Object} The wrapped type. The wrapped type has the following format: name: {String} The name of the type. count: {Integer} The number of records available. columns: {Columns} An array of columns to describe the record. object: {Class} The actual Model type class. release: {Function} The function to remove observers. */ wrapModelType: function (klass, name) { var records = this.getRecords(klass, name); var typeToSend = undefined; typeToSend = { name: name, count: _emberMetalProperty_get.get(records, 'length'), columns: this.columnsForType(klass), object: klass }; return typeToSend; }, /** Fetches all models defined in the application. @private @method getModelTypes @return {Array} Array of model types. */ getModelTypes: function () { var _this4 = this; var containerDebugAdapter = this.get('containerDebugAdapter'); var types = undefined; if (containerDebugAdapter.canCatalogEntriesByType('model')) { types = containerDebugAdapter.catalogEntriesByType('model'); } else { types = this._getObjectsOnNamespaces(); } // New adapters return strings instead of classes. types = _emberRuntimeSystemNative_array.A(types).map(function (name) { return { klass: _this4._nameToClass(name), name: name }; }); types = _emberRuntimeSystemNative_array.A(types).filter(function (type) { return _this4.detect(type.klass); }); return _emberRuntimeSystemNative_array.A(types); }, /** Loops over all namespaces and all objects attached to them. @private @method _getObjectsOnNamespaces @return {Array} Array of model type strings. */ _getObjectsOnNamespaces: function () { var _this5 = this; var namespaces = _emberRuntimeSystemNative_array.A(_emberRuntimeSystemNamespace.default.NAMESPACES); var types = _emberRuntimeSystemNative_array.A(); namespaces.forEach(function (namespace) { for (var key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } // Even though we will filter again in `getModelTypes`, // we should not call `lookupFactory` on non-models // (especially when `EmberENV.MODEL_FACTORY_INJECTIONS` is `true`) if (!_this5.detect(namespace[key])) { continue; } var _name = _emberRuntimeSystemString.dasherize(key); if (!(namespace instanceof _emberApplicationSystemApplication.default) && namespace.toString()) { _name = namespace + '/' + _name; } types.push(_name); } }); return types; }, /** Fetches all loaded records for a given type. @private @method getRecords @return {Array} An array of records. This array will be observed for changes, so it should update when new records are added/removed. */ getRecords: function (type) { return _emberRuntimeSystemNative_array.A(); }, /** Wraps a record and observers changes to it. @private @method wrapRecord @param {Object} record The record instance. @return {Object} The wrapped record. Format: columnValues: {Array} searchKeywords: {Array} */ wrapRecord: function (record) { var recordToSend = { object: record }; recordToSend.columnValues = this.getRecordColumnValues(record); recordToSend.searchKeywords = this.getRecordKeywords(record); recordToSend.filterValues = this.getRecordFilterValues(record); recordToSend.color = this.getRecordColor(record); return recordToSend; }, /** Gets the values for each column. @private @method getRecordColumnValues @return {Object} Keys should match column names defined by the model type. */ getRecordColumnValues: function (record) { return {}; }, /** Returns keywords to match when searching records. @private @method getRecordKeywords @return {Array} Relevant keywords for search. */ getRecordKeywords: function (record) { return _emberRuntimeSystemNative_array.A(); }, /** Returns the values of filters defined by `getFilters`. @private @method getRecordFilterValues @param {Object} record The record instance. @return {Object} The filter values. */ getRecordFilterValues: function (record) { return {}; }, /** Each record can have a color that represents its state. @private @method getRecordColor @param {Object} record The record instance @return {String} The records color. Possible options: black, red, blue, green. */ getRecordColor: function (record) { return null; }, /** Observes all relevant properties and re-sends the wrapped record when a change occurs. @private @method observerRecord @param {Object} record The record instance. @param {Function} recordUpdated The callback to call when a record is updated. @return {Function} The function to call to remove all observers. */ observeRecord: function (record, recordUpdated) { return function () {}; } }); }); enifed('ember-extension-support/index', ['exports', 'ember-metal/core', 'ember-extension-support/data_adapter', 'ember-extension-support/container_debug_adapter'], function (exports, _emberMetalCore, _emberExtensionSupportData_adapter, _emberExtensionSupportContainer_debug_adapter) { /** @module ember @submodule ember-extension-support */ 'use strict'; _emberMetalCore.default.DataAdapter = _emberExtensionSupportData_adapter.default; _emberMetalCore.default.ContainerDebugAdapter = _emberExtensionSupportContainer_debug_adapter.default; }); // reexports enifed('ember-htmlbars/component', ['exports', 'ember-metal/debug', 'ember-metal/mixin', 'ember-environment', 'ember-runtime/mixins/target_action_support', 'ember-views/mixins/action_support', 'ember-views/views/view', 'ember-metal/computed', 'container/owner', 'ember-metal/symbol'], function (exports, _emberMetalDebug, _emberMetalMixin, _emberEnvironment, _emberRuntimeMixinsTarget_action_support, _emberViewsMixinsAction_support, _emberViewsViewsView, _emberMetalComputed, _containerOwner, _emberMetalSymbol) { 'use strict'; var HAS_BLOCK = _emberMetalSymbol.default('HAS_BLOCK'); exports.HAS_BLOCK = HAS_BLOCK; /** @module ember @submodule ember-views */ /** An `Ember.Component` is a view that is completely isolated. Properties accessed in its templates go to the view object and actions are targeted at the view object. There is no access to the surrounding context or outer controller; all contextual information must be passed in. The easiest way to create an `Ember.Component` is via a template. If you name a template `components/my-foo`, you will be able to use `{{my-foo}}` in other templates, which will make an instance of the isolated component. ```handlebars {{app-profile person=currentUser}} ``` ```handlebars <!-- app-profile template --> <h1>{{person.title}}</h1> <img src={{person.avatar}}> <p class='signature'>{{person.signature}}</p> ``` You can use `yield` inside a template to include the **contents** of any block attached to the component. The block will be executed in the context of the surrounding context or outer controller: ```handlebars {{#app-profile person=currentUser}} <p>Admin mode</p> {{! Executed in the controller's context. }} {{/app-profile}} ``` ```handlebars <!-- app-profile template --> <h1>{{person.title}}</h1> {{! Executed in the component's context. }} {{yield}} {{! block contents }} ``` If you want to customize the component, in order to handle events or actions, you implement a subclass of `Ember.Component` named after the name of the component. Note that `Component` needs to be appended to the name of your subclass like `AppProfileComponent`. For example, you could implement the action `hello` for the `app-profile` component: ```javascript App.AppProfileComponent = Ember.Component.extend({ actions: { hello: function(name) { console.log("Hello", name); } } }); ``` And then use it in the component's template: ```handlebars <!-- app-profile template --> <h1>{{person.title}}</h1> {{yield}} <!-- block contents --> <button {{action 'hello' person.name}}> Say Hello to {{person.name}} </button> ``` Components must have a `-` in their name to avoid conflicts with built-in controls that wrap HTML elements. This is consistent with the same requirement in web components. @class Component @namespace Ember @extends Ember.View @uses Ember.ViewTargetActionSupport @public */ var Component = _emberViewsViewsView.default.extend(_emberRuntimeMixinsTarget_action_support.default, _emberViewsMixinsAction_support.default, { isComponent: true, instrumentName: 'component', instrumentDisplay: _emberMetalComputed.computed(function () { if (this._debugContainerKey) { return '{{' + this._debugContainerKey.split(':')[1] + '}}'; } }), init: function () { var _this = this; this._super.apply(this, arguments); // If a `defaultLayout` was specified move it to the `layout` prop. // `layout` is no longer a CP, so this just ensures that the `defaultLayout` // logic is supported with a deprecation if (this.defaultLayout && !this.layout) { _emberMetalDebug.deprecate('Specifying `defaultLayout` to ' + this + ' is deprecated. Please use `layout` instead.', false, { id: 'ember-views.component.defaultLayout', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-component-defaultlayout' }); this.layout = this.defaultLayout; } // If in a tagless component, assert that no event handlers are defined _emberMetalDebug.assert('You can not define a function that handles DOM events in the `' + this + '` tagless component since it doesn\'t have any DOM element.', this.tagName !== '' || !_emberEnvironment.environment.hasDOM || !(function () { var eventDispatcher = _containerOwner.getOwner(_this).lookup('event_dispatcher:main'); var events = eventDispatcher && eventDispatcher._finalEvents || {}; for (var key in events) { var methodName = events[key]; if (typeof _this[methodName] === 'function') { return true; // indicate that the assertion should be triggered } } })()); }, template: null, layoutName: null, layout: null, /** Normally, Ember's component model is "write-only". The component takes a bunch of attributes that it got passed in, and uses them to render its template. One nice thing about this model is that if you try to set a value to the same thing as last time, Ember (through HTMLBars) will avoid doing any work on the DOM. This is not just a performance optimization. If an attribute has not changed, it is important not to clobber the element's "hidden state". For example, if you set an input's `value` to the same value as before, it will clobber selection state and cursor position. In other words, setting an attribute is not **always** idempotent. This method provides a way to read an element's attribute and also update the last value Ember knows about at the same time. This makes setting an attribute idempotent. In particular, what this means is that if you get an `<input>` element's `value` attribute and then re-render the template with the same value, it will avoid clobbering the cursor and selection position. Since most attribute sets are idempotent in the browser, you typically can get away with reading attributes using jQuery, but the most reliable way to do so is through this method. @method readDOMAttr @param {String} name the name of the attribute @return String @public */ readDOMAttr: function (name) { var attr = this._renderNode.childNodes.filter(function (node) { return node.attrName === name; })[0]; if (!attr) { return null; } return attr.getContent(); }, /** Returns true when the component was invoked with a block template. Example (`hasBlock` will be `false`): ```hbs {{! templates/application.hbs }} {{foo-bar}} {{! templates/components/foo-bar.hbs }} {{#if hasBlock}} This will not be printed, because no block was provided {{/if}} ``` Example (`hasBlock` will be `true`): ```hbs {{! templates/application.hbs }} {{#foo-bar}} Hi! {{/foo-bar}} {{! templates/components/foo-bar.hbs }} {{#if hasBlock}} This will be printed because a block was provided {{yield}} {{/if}} ``` This helper accepts an argument with the name of the block we want to check the presence of. This is useful for checking for the presence of the optional inverse block in components. ```hbs {{! templates/application.hbs }} {{#foo-bar}} Hi! {{else}} What's up? {{/foo-bar}} {{! templates/components/foo-bar.hbs }} {{yield}} {{#if (hasBlock "inverse")}} {{yield to="inverse"}} {{else}} How are you? {{/if}} ``` @public @property hasBlock @param {String} [blockName="default"] The name of the block to check presence of. @returns Boolean @since 1.13.0 */ /** Returns true when the component was invoked with a block parameter supplied. Example (`hasBlockParams` will be `false`): ```hbs {{! templates/application.hbs }} {{#foo-bar}} No block parameter. {{/foo-bar}} {{! templates/components/foo-bar.hbs }} {{#if hasBlockParams}} This will not be printed, because no block was provided {{yield this}} {{/if}} ``` Example (`hasBlockParams` will be `true`): ```hbs {{! templates/application.hbs }} {{#foo-bar as |foo|}} Hi! {{/foo-bar}} {{! templates/components/foo-bar.hbs }} {{#if hasBlockParams}} This will be printed because a block was provided {{yield this}} {{/if}} ``` @public @property hasBlockParams @returns Boolean @since 1.13.0 */ /** Enables components to take a list of parameters as arguments. For example, a component that takes two parameters with the names `name` and `age`: ```javascript let MyComponent = Ember.Component.extend; MyComponent.reopenClass({ positionalParams: ['name', 'age'] }); ``` It can then be invoked like this: ```hbs {{my-component "John" 38}} ``` The parameters can be referred to just like named parameters: ```hbs Name: {{attrs.name}}, Age: {{attrs.age}}. ``` Using a string instead of an array allows for an arbitrary number of parameters: ```javascript let MyComponent = Ember.Component.extend; MyComponent.reopenClass({ positionalParams: 'names' }); ``` It can then be invoked like this: ```hbs {{my-component "John" "Michael" "Scott"}} ``` The parameters can then be referred to by enumerating over the list: ```hbs {{#each attrs.names as |name|}}{{name}}{{/each}} ``` @static @public @property positionalParams @since 1.13.0 */ /** Called when the attributes passed into the component have been updated. Called both during the initial render of a container and during a rerender. Can be used in place of an observer; code placed here will be executed every time any attribute updates. @method didReceiveAttrs @public @since 1.13.0 */ didReceiveAttrs: function () {}, /** Called when the attributes passed into the component have been updated. Called both during the initial render of a container and during a rerender. Can be used in place of an observer; code placed here will be executed every time any attribute updates. @event didReceiveAttrs @public @since 1.13.0 */ /** Called after a component has been rendered, both on initial render and in subsequent rerenders. @method didRender @public @since 1.13.0 */ didRender: function () {}, /** Called after a component has been rendered, both on initial render and in subsequent rerenders. @event didRender @public @since 1.13.0 */ /** Called before a component has been rendered, both on initial render and in subsequent rerenders. @method willRender @public @since 1.13.0 */ willRender: function () {}, /** Called before a component has been rendered, both on initial render and in subsequent rerenders. @event willRender @public @since 1.13.0 */ /** Called when the attributes passed into the component have been changed. Called only during a rerender, not during an initial render. @method didUpdateAttrs @public @since 1.13.0 */ didUpdateAttrs: function () {}, /** Called when the attributes passed into the component have been changed. Called only during a rerender, not during an initial render. @event didUpdateAttrs @public @since 1.13.0 */ /** Called when the component is about to update and rerender itself. Called only during a rerender, not during an initial render. @method willUpdate @public @since 1.13.0 */ willUpdate: function () {}, /** Called when the component is about to update and rerender itself. Called only during a rerender, not during an initial render. @event willUpdate @public @since 1.13.0 */ /** Called when the component has updated and rerendered itself. Called only during a rerender, not during an initial render. @method didUpdate @public @since 1.13.0 */ didUpdate: function () {} /** Called when the component has updated and rerendered itself. Called only during a rerender, not during an initial render. @event didUpdate @public @since 1.13.0 */ }); Component[_emberMetalMixin.NAME_KEY] = 'Ember.Component'; Component.reopenClass({ isComponentFactory: true, positionalParams: [] }); exports.default = Component; }); enifed('ember-htmlbars/components/checkbox', ['exports', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-htmlbars/component'], function (exports, _emberMetalProperty_get, _emberMetalProperty_set, _emberHtmlbarsComponent) { 'use strict'; /** @module ember @submodule ember-views */ /** The internal class used to create text inputs when the `{{input}}` helper is used with `type` of `checkbox`. See [Ember.Templates.helpers.input](/api/classes/Ember.Templates.helpers.html#method_input) for usage details. ## Direct manipulation of `checked` The `checked` attribute of an `Ember.Checkbox` object should always be set through the Ember object or by interacting with its rendered element representation via the mouse, keyboard, or touch. Updating the value of the checkbox via jQuery will result in the checked value of the object and its element losing synchronization. ## Layout and LayoutName properties Because HTML `input` elements are self closing `layout` and `layoutName` properties will not be applied. See [Ember.View](/api/classes/Ember.View.html)'s layout section for more information. @class Checkbox @namespace Ember @extends Ember.Component @public */ exports.default = _emberHtmlbarsComponent.default.extend({ instrumentDisplay: '{{input type="checkbox"}}', classNames: ['ember-checkbox'], tagName: 'input', attributeBindings: ['type', 'checked', 'indeterminate', 'disabled', 'tabindex', 'name', 'autofocus', 'required', 'form'], type: 'checkbox', checked: false, disabled: false, indeterminate: false, didInsertElement: function () { this._super.apply(this, arguments); _emberMetalProperty_get.get(this, 'element').indeterminate = !!_emberMetalProperty_get.get(this, 'indeterminate'); }, change: function () { _emberMetalProperty_set.set(this, 'checked', this.$().prop('checked')); } }); }); enifed('ember-htmlbars/components/link-to', ['exports', 'ember-console', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/computed', 'ember-runtime/computed/computed_macros', 'ember-views/system/utils', 'ember-runtime/inject', 'ember-runtime/system/service', 'ember-runtime/mixins/controller', 'ember-htmlbars/templates/link-to', 'ember-htmlbars/component', 'ember-metal/instrumentation'], function (exports, _emberConsole, _emberMetalDebug, _emberMetalProperty_get, _emberMetalComputed, _emberRuntimeComputedComputed_macros, _emberViewsSystemUtils, _emberRuntimeInject, _emberRuntimeSystemService, _emberRuntimeMixinsController, _emberHtmlbarsTemplatesLinkTo, _emberHtmlbarsComponent, _emberMetalInstrumentation) { /** @module ember @submodule ember-templates */ /** The `{{link-to}}` component renders a link to the supplied `routeName` passing an optionally supplied model to the route as its `model` context of the route. The block for `{{link-to}}` becomes the innerHTML of the rendered element: ```handlebars {{#link-to 'photoGallery'}} Great Hamster Photos {{/link-to}} ``` You can also use an inline form of `{{link-to}}` component by passing the link text as the first argument to the component: ```handlebars {{link-to 'Great Hamster Photos' 'photoGallery'}} ``` Both will result in: ```html <a href="/hamster-photos"> Great Hamster Photos </a> ``` ### Supplying a tagName By default `{{link-to}}` renders an `<a>` element. This can be overridden for a single use of `{{link-to}}` by supplying a `tagName` option: ```handlebars {{#link-to 'photoGallery' tagName="li"}} Great Hamster Photos {{/link-to}} ``` ```html <li> Great Hamster Photos </li> ``` To override this option for your entire application, see "Overriding Application-wide Defaults". ### Disabling the `link-to` component By default `{{link-to}}` is enabled. any passed value to the `disabled` component property will disable the `link-to` component. static use: the `disabled` option: ```handlebars {{#link-to 'photoGallery' disabled=true}} Great Hamster Photos {{/link-to}} ``` dynamic use: the `disabledWhen` option: ```handlebars {{#link-to 'photoGallery' disabledWhen=controller.someProperty}} Great Hamster Photos {{/link-to}} ``` any passed value to `disabled` will disable it except `undefined`. to ensure that only `true` disable the `link-to` component you can override the global behaviour of `Ember.LinkComponent`. ```javascript Ember.LinkComponent.reopen({ disabled: Ember.computed(function(key, value) { if (value !== undefined) { this.set('_isDisabled', value === true); } return value === true ? get(this, 'disabledClass') : false; }) }); ``` see "Overriding Application-wide Defaults" for more. ### Handling `href` `{{link-to}}` will use your application's Router to fill the element's `href` property with a url that matches the path to the supplied `routeName` for your router's configured `Location` scheme, which defaults to Ember.HashLocation. ### Handling current route `{{link-to}}` will apply a CSS class name of 'active' when the application's current route matches the supplied routeName. For example, if the application's current route is 'photoGallery.recent' the following use of `{{link-to}}`: ```handlebars {{#link-to 'photoGallery.recent'}} Great Hamster Photos {{/link-to}} ``` will result in ```html <a href="/hamster-photos/this-week" class="active"> Great Hamster Photos </a> ``` The CSS class name used for active classes can be customized for a single use of `{{link-to}}` by passing an `activeClass` option: ```handlebars {{#link-to 'photoGallery.recent' activeClass="current-url"}} Great Hamster Photos {{/link-to}} ``` ```html <a href="/hamster-photos/this-week" class="current-url"> Great Hamster Photos </a> ``` To override this option for your entire application, see "Overriding Application-wide Defaults". ### Keeping a link active for other routes If you need a link to be 'active' even when it doesn't match the current route, you can use the `current-when` argument. ```handlebars {{#link-to 'photoGallery' current-when='photos'}} Photo Gallery {{/link-to}} ``` This may be helpful for keeping links active for: * non-nested routes that are logically related * some secondary menu approaches * 'top navigation' with 'sub navigation' scenarios A link will be active if `current-when` is `true` or the current route is the route this link would transition to. To match multiple routes 'space-separate' the routes: ```handlebars {{#link-to 'gallery' current-when='photos drawings paintings'}} Art Gallery {{/link-to}} ``` ### Supplying a model An optional model argument can be used for routes whose paths contain dynamic segments. This argument will become the model context of the linked route: ```javascript Router.map(function() { this.route("photoGallery", {path: "hamster-photos/:photo_id"}); }); ``` ```handlebars {{#link-to 'photoGallery' aPhoto}} {{aPhoto.title}} {{/link-to}} ``` ```html <a href="/hamster-photos/42"> Tomster </a> ``` ### Supplying multiple models For deep-linking to route paths that contain multiple dynamic segments, multiple model arguments can be used. As the router transitions through the route path, each supplied model argument will become the context for the route with the dynamic segments: ```javascript Router.map(function() { this.route("photoGallery", { path: "hamster-photos/:photo_id" }, function() { this.route("comment", {path: "comments/:comment_id"}); }); }); ``` This argument will become the model context of the linked route: ```handlebars {{#link-to 'photoGallery.comment' aPhoto comment}} {{comment.body}} {{/link-to}} ``` ```html <a href="/hamster-photos/42/comments/718"> A+++ would snuggle again. </a> ``` ### Supplying an explicit dynamic segment value If you don't have a model object available to pass to `{{link-to}}`, an optional string or integer argument can be passed for routes whose paths contain dynamic segments. This argument will become the value of the dynamic segment: ```javascript Router.map(function() { this.route("photoGallery", { path: "hamster-photos/:photo_id" }); }); ``` ```handlebars {{#link-to 'photoGallery' aPhotoId}} {{aPhoto.title}} {{/link-to}} ``` ```html <a href="/hamster-photos/42"> Tomster </a> ``` When transitioning into the linked route, the `model` hook will be triggered with parameters including this passed identifier. ### Allowing Default Action By default the `{{link-to}}` component prevents the default browser action by calling `preventDefault()` as this sort of action bubbling is normally handled internally and we do not want to take the browser to a new URL (for example). If you need to override this behavior specify `preventDefault=false` in your template: ```handlebars {{#link-to 'photoGallery' aPhotoId preventDefault=false}} {{aPhotoId.title}} {{/link-to}} ``` ### Overriding attributes You can override any given property of the `Ember.LinkComponent` that is generated by the `{{link-to}}` component by passing key/value pairs, like so: ```handlebars {{#link-to aPhoto tagName='li' title='Following this link will change your life' classNames='pic sweet'}} Uh-mazing! {{/link-to}} ``` See [Ember.LinkComponent](/api/classes/Ember.LinkComponent.html) for a complete list of overrideable properties. Be sure to also check out inherited properties of `LinkComponent`. ### Overriding Application-wide Defaults ``{{link-to}}`` creates an instance of `Ember.LinkComponent` for rendering. To override options for your entire application, reopen `Ember.LinkComponent` and supply the desired values: ``` javascript Ember.LinkComponent.reopen({ activeClass: "is-active", tagName: 'li' }) ``` It is also possible to override the default event in this manner: ``` javascript Ember.LinkComponent.reopen({ eventName: 'customEventName' }); ``` @method link-to @for Ember.Templates.helpers @param {String} routeName @param {Object} [context]* @param [options] {Object} Handlebars key/value pairs of options, you can override any property of Ember.LinkComponent @return {String} HTML string @see {Ember.LinkComponent} @public */ /** @module ember @submodule ember-templates */ 'use strict'; /** `Ember.LinkComponent` renders an element whose `click` event triggers a transition of the application's instance of `Ember.Router` to a supplied route by name. `Ember.LinkComponent` components are invoked with {{#link-to}}. Properties of this class can be overridden with `reopen` to customize application-wide behavior. @class LinkComponent @namespace Ember @extends Ember.Component @see {Ember.Templates.helpers.link-to} @private **/ var LinkComponent = _emberHtmlbarsComponent.default.extend({ layout: _emberHtmlbarsTemplatesLinkTo.default, tagName: 'a', /** @deprecated Use current-when instead. @property currentWhen @private */ currentWhen: _emberRuntimeComputedComputed_macros.deprecatingAlias('current-when', { id: 'ember-routing-view.deprecated-current-when', until: '3.0.0' }), /** Used to determine when this `LinkComponent` is active. @property currentWhen @public */ 'current-when': null, /** Sets the `title` attribute of the `LinkComponent`'s HTML element. @property title @default null @public **/ title: null, /** Sets the `rel` attribute of the `LinkComponent`'s HTML element. @property rel @default null @public **/ rel: null, /** Sets the `tabindex` attribute of the `LinkComponent`'s HTML element. @property tabindex @default null @public **/ tabindex: null, /** Sets the `target` attribute of the `LinkComponent`'s HTML element. @since 1.8.0 @property target @default null @public **/ target: null, /** The CSS class to apply to `LinkComponent`'s element when its `active` property is `true`. @property activeClass @type String @default active @private **/ activeClass: 'active', /** The CSS class to apply to `LinkComponent`'s element when its `loading` property is `true`. @property loadingClass @type String @default loading @private **/ loadingClass: 'loading', /** The CSS class to apply to a `LinkComponent`'s element when its `disabled` property is `true`. @property disabledClass @type String @default disabled @private **/ disabledClass: 'disabled', _isDisabled: false, /** Determines whether the `LinkComponent` will trigger routing via the `replaceWith` routing strategy. @property replace @type Boolean @default false @public **/ replace: false, /** By default the `{{link-to}}` component will bind to the `href` and `title` attributes. It's discouraged that you override these defaults, however you can push onto the array if needed. @property attributeBindings @type Array | String @default ['title', 'rel', 'tabindex', 'target'] @public */ attributeBindings: ['href', 'title', 'rel', 'tabindex', 'target'], /** By default the `{{link-to}}` component will bind to the `active`, `loading`, and `disabled` classes. It is discouraged to override these directly. @property classNameBindings @type Array @default ['active', 'loading', 'disabled', 'ember-transitioning-in', 'ember-transitioning-out'] @public */ classNameBindings: ['active', 'loading', 'disabled', 'transitioningIn', 'transitioningOut'], /** By default the `{{link-to}}` component responds to the `click` event. You can override this globally by setting this property to your custom event name. This is particularly useful on mobile when one wants to avoid the 300ms click delay using some sort of custom `tap` event. @property eventName @type String @default click @private */ eventName: 'click', // this is doc'ed here so it shows up in the events // section of the API documentation, which is where // people will likely go looking for it. /** Triggers the `LinkComponent`'s routing behavior. If `eventName` is changed to a value other than `click` the routing behavior will trigger on that custom event instead. @event click @private */ /** An overridable method called when `LinkComponent` objects are instantiated. Example: ```javascript App.MyLinkComponent = Ember.LinkComponent.extend({ init: function() { this._super(...arguments); Ember.Logger.log('Event is ' + this.get('eventName')); } }); ``` NOTE: If you do override `init` for a framework class like `Ember.View`, be sure to call `this._super(...arguments)` in your `init` declaration! If you don't, Ember may not have an opportunity to do important setup work, and you'll see strange behavior in your application. @method init @private */ init: function () { this._super.apply(this, arguments); // Map desired event name to invoke function var eventName = _emberMetalProperty_get.get(this, 'eventName'); this.on(eventName, this, this._invoke); }, _routing: _emberRuntimeInject.default.service('-routing'), /** Accessed as a classname binding to apply the `LinkComponent`'s `disabledClass` CSS `class` to the element when the link is disabled. When `true` interactions with the element will not trigger route changes. @property disabled @private */ disabled: _emberMetalComputed.computed({ get: function (key, value) { return false; }, set: function (key, value) { if (value !== undefined) { this.set('_isDisabled', value); } return value ? _emberMetalProperty_get.get(this, 'disabledClass') : false; } }), _computeActive: function (routerState) { if (_emberMetalProperty_get.get(this, 'loading')) { return false; } var routing = _emberMetalProperty_get.get(this, '_routing'); var models = _emberMetalProperty_get.get(this, 'models'); var resolvedQueryParams = _emberMetalProperty_get.get(this, 'resolvedQueryParams'); var currentWhen = _emberMetalProperty_get.get(this, 'current-when'); var isCurrentWhenSpecified = !!currentWhen; currentWhen = currentWhen || _emberMetalProperty_get.get(this, 'qualifiedRouteName'); currentWhen = currentWhen.split(' '); for (var i = 0; i < currentWhen.length; i++) { if (routing.isActiveForRoute(models, resolvedQueryParams, currentWhen[i], routerState, isCurrentWhenSpecified)) { return _emberMetalProperty_get.get(this, 'activeClass'); } } return false; }, /** Accessed as a classname binding to apply the `LinkComponent`'s `activeClass` CSS `class` to the element when the link is active. A `LinkComponent` is considered active when its `currentWhen` property is `true` or the application's current route is the route the `LinkComponent` would trigger transitions into. The `currentWhen` property can match against multiple routes by separating route names using the ` ` (space) character. @property active @private */ active: _emberMetalComputed.computed('attrs.params', '_routing.currentState', function computeLinkToComponentActive() { var currentState = _emberMetalProperty_get.get(this, '_routing.currentState'); if (!currentState) { return false; } return this._computeActive(currentState); }), willBeActive: _emberMetalComputed.computed('_routing.targetState', function computeLinkToComponentWillBeActive() { var routing = _emberMetalProperty_get.get(this, '_routing'); var targetState = _emberMetalProperty_get.get(routing, 'targetState'); if (_emberMetalProperty_get.get(routing, 'currentState') === targetState) { return; } return !!this._computeActive(targetState); }), transitioningIn: _emberMetalComputed.computed('active', 'willBeActive', function computeLinkToComponentTransitioningIn() { var willBeActive = _emberMetalProperty_get.get(this, 'willBeActive'); if (typeof willBeActive === 'undefined') { return false; } return !_emberMetalProperty_get.get(this, 'active') && willBeActive && 'ember-transitioning-in'; }), transitioningOut: _emberMetalComputed.computed('active', 'willBeActive', function computeLinkToComponentTransitioningOut() { var willBeActive = _emberMetalProperty_get.get(this, 'willBeActive'); if (typeof willBeActive === 'undefined') { return false; } return _emberMetalProperty_get.get(this, 'active') && !willBeActive && 'ember-transitioning-out'; }), /** Event handler that invokes the link, activating the associated route. @method _invoke @param {Event} event @private */ _invoke: function (event) { if (!_emberViewsSystemUtils.isSimpleClick(event)) { return true; } var preventDefault = _emberMetalProperty_get.get(this, 'preventDefault'); var targetAttribute = _emberMetalProperty_get.get(this, 'target'); if (preventDefault !== false) { if (!targetAttribute || targetAttribute === '_self') { event.preventDefault(); } } if (_emberMetalProperty_get.get(this, 'bubbles') === false) { event.stopPropagation(); } if (_emberMetalProperty_get.get(this, '_isDisabled')) { return false; } if (_emberMetalProperty_get.get(this, 'loading')) { _emberConsole.default.warn('This link-to is in an inactive loading state because at least one of its parameters presently has a null/undefined value, or the provided route name is invalid.'); return false; } if (targetAttribute && targetAttribute !== '_self') { return false; } var qualifiedRouteName = _emberMetalProperty_get.get(this, 'qualifiedRouteName'); var models = _emberMetalProperty_get.get(this, 'models'); var queryParams = _emberMetalProperty_get.get(this, 'queryParams.values'); var shouldReplace = _emberMetalProperty_get.get(this, 'replace'); var payload = { queryParams: queryParams, routeName: qualifiedRouteName }; _emberMetalInstrumentation.flaggedInstrument('interaction.link-to', payload, this._generateTransition(payload, qualifiedRouteName, models, queryParams, shouldReplace)); }, _generateTransition: function (payload, qualifiedRouteName, models, queryParams, shouldReplace) { var routing = _emberMetalProperty_get.get(this, '_routing'); return function () { payload.transition = routing.transitionTo(qualifiedRouteName, models, queryParams, shouldReplace); }; }, queryParams: null, qualifiedRouteName: _emberMetalComputed.computed('targetRouteName', '_routing.currentState', function computeLinkToComponentQualifiedRouteName() { var params = _emberMetalProperty_get.get(this, 'params').slice(); var lastParam = params[params.length - 1]; if (lastParam && lastParam.isQueryParams) { params.pop(); } var onlyQueryParamsSupplied = this[_emberHtmlbarsComponent.HAS_BLOCK] ? params.length === 0 : params.length === 1; if (onlyQueryParamsSupplied) { return _emberMetalProperty_get.get(this, '_routing.currentRouteName'); } return _emberMetalProperty_get.get(this, 'targetRouteName'); }), resolvedQueryParams: _emberMetalComputed.computed('queryParams', function computeLinkToComponentResolvedQueryParams() { var resolvedQueryParams = {}; var queryParams = _emberMetalProperty_get.get(this, 'queryParams'); if (!queryParams) { return resolvedQueryParams; } var values = queryParams.values; for (var key in values) { if (!values.hasOwnProperty(key)) { continue; } resolvedQueryParams[key] = values[key]; } return resolvedQueryParams; }), /** Sets the element's `href` attribute to the url for the `LinkComponent`'s targeted route. If the `LinkComponent`'s `tagName` is changed to a value other than `a`, this property will be ignored. @property href @private */ href: _emberMetalComputed.computed('models', 'qualifiedRouteName', function computeLinkToComponentHref() { if (_emberMetalProperty_get.get(this, 'tagName') !== 'a') { return; } var qualifiedRouteName = _emberMetalProperty_get.get(this, 'qualifiedRouteName'); var models = _emberMetalProperty_get.get(this, 'models'); if (_emberMetalProperty_get.get(this, 'loading')) { return _emberMetalProperty_get.get(this, 'loadingHref'); } var routing = _emberMetalProperty_get.get(this, '_routing'); var queryParams = _emberMetalProperty_get.get(this, 'queryParams.values'); return routing.generateURL(qualifiedRouteName, models, queryParams); }), loading: _emberMetalComputed.computed('_modelsAreLoaded', 'qualifiedRouteName', function computeLinkToComponentLoading() { var qualifiedRouteName = _emberMetalProperty_get.get(this, 'qualifiedRouteName'); var modelsAreLoaded = _emberMetalProperty_get.get(this, '_modelsAreLoaded'); if (!modelsAreLoaded || qualifiedRouteName == null) { return _emberMetalProperty_get.get(this, 'loadingClass'); } }), _modelsAreLoaded: _emberMetalComputed.computed('models', function computeLinkToComponentModelsAreLoaded() { var models = _emberMetalProperty_get.get(this, 'models'); for (var i = 0; i < models.length; i++) { if (models[i] == null) { return false; } } return true; }), _getModels: function (params) { var modelCount = params.length - 1; var models = new Array(modelCount); for (var i = 0; i < modelCount; i++) { var value = params[i + 1]; while (_emberRuntimeMixinsController.default.detect(value)) { _emberMetalDebug.deprecate('Providing `{{link-to}}` with a param that is wrapped in a controller is deprecated. ' + (this.parentView ? 'Please update `' + this.parentView + '` to use `{{link-to "post" someController.model}}` instead.' : ''), false, { id: 'ember-routing-views.controller-wrapped-param', until: '3.0.0' }); value = value.get('model'); } models[i] = value; } return models; }, /** The default href value to use while a link-to is loading. Only applies when tagName is 'a' @property loadingHref @type String @default # @private */ loadingHref: '#', willRender: function () { var queryParams = undefined; var params = _emberMetalProperty_get.get(this, 'params'); if (params) { // Do not mutate params in place params = params.slice(); } _emberMetalDebug.assert('You must provide one or more parameters to the link-to component.', (function () { if (!params) { return false; } return params.length; })()); var disabledWhen = _emberMetalProperty_get.get(this, 'disabledWhen'); if (disabledWhen !== undefined) { this.set('disabled', disabledWhen); } // Process the positional arguments, in order. // 1. Inline link title comes first, if present. if (!this[_emberHtmlbarsComponent.HAS_BLOCK]) { this.set('linkTitle', params.shift()); } // 2. `targetRouteName` is now always at index 0. this.set('targetRouteName', params[0]); // 3. The last argument (if still remaining) is the `queryParams` object. var lastParam = params[params.length - 1]; if (lastParam && lastParam.isQueryParams) { queryParams = params.pop(); } else { queryParams = { values: {} }; } this.set('queryParams', queryParams); // 4. Any remaining indices (excepting `targetRouteName` at 0) are `models`. if (params.length > 1) { this.set('models', this._getModels(params)); } else { this.set('models', []); } } }); LinkComponent.toString = function () { return 'LinkComponent'; }; LinkComponent.reopenClass({ positionalParams: 'params' }); exports.default = LinkComponent; }); // creates inject.service enifed('ember-htmlbars/components/text_area', ['exports', 'ember-htmlbars/component', 'ember-views/mixins/text_support'], function (exports, _emberHtmlbarsComponent, _emberViewsMixinsText_support) { /** @module ember @submodule ember-views */ 'use strict'; /** The internal class used to create textarea element when the `{{textarea}}` helper is used. See [Ember.Templates.helpers.textarea](/api/classes/Ember.Templates.helpers.html#method_textarea) for usage details. ## Layout and LayoutName properties Because HTML `textarea` elements do not contain inner HTML the `layout` and `layoutName` properties will not be applied. See [Ember.View](/api/classes/Ember.View.html)'s layout section for more information. @class TextArea @namespace Ember @extends Ember.Component @uses Ember.TextSupport @public */ exports.default = _emberHtmlbarsComponent.default.extend(_emberViewsMixinsText_support.default, { instrumentDisplay: '{{textarea}}', classNames: ['ember-text-area'], tagName: 'textarea', attributeBindings: ['rows', 'cols', 'name', 'selectionEnd', 'selectionStart', 'wrap', 'lang', 'dir', 'value'], rows: null, cols: null }); }); enifed('ember-htmlbars/components/text_field', ['exports', 'ember-metal/computed', 'ember-environment', 'ember-htmlbars/component', 'ember-views/mixins/text_support', 'ember-metal/empty_object'], function (exports, _emberMetalComputed, _emberEnvironment, _emberHtmlbarsComponent, _emberViewsMixinsText_support, _emberMetalEmpty_object) { /** @module ember @submodule ember-views */ 'use strict'; var inputTypeTestElement = undefined; var inputTypes = new _emberMetalEmpty_object.default(); function canSetTypeOfInput(type) { if (type in inputTypes) { return inputTypes[type]; } // if running in outside of a browser always return the // original type if (!_emberEnvironment.environment.hasDOM) { inputTypes[type] = type; return type; } if (!inputTypeTestElement) { inputTypeTestElement = document.createElement('input'); } try { inputTypeTestElement.type = type; } catch (e) {} return inputTypes[type] = inputTypeTestElement.type === type; } /** The internal class used to create text inputs when the `{{input}}` helper is used with `type` of `text`. See [Ember.Templates.helpers.input](/api/classes/Ember.Templates.helpers.html#method_input) for usage details. ## Layout and LayoutName properties Because HTML `input` elements are self closing `layout` and `layoutName` properties will not be applied. See [Ember.View](/api/classes/Ember.View.html)'s layout section for more information. @class TextField @namespace Ember @extends Ember.Component @uses Ember.TextSupport @public */ exports.default = _emberHtmlbarsComponent.default.extend(_emberViewsMixinsText_support.default, { instrumentDisplay: '{{input type="text"}}', classNames: ['ember-text-field'], tagName: 'input', attributeBindings: ['accept', 'autocomplete', 'autosave', 'dir', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'height', 'inputmode', 'lang', 'list', 'max', 'min', 'multiple', 'name', 'pattern', 'size', 'step', 'type', 'value', 'width'], defaultLayout: null, /** The `value` attribute of the input element. As the user inputs text, this property is updated live. @property value @type String @default "" @public */ value: '', /** The `type` attribute of the input element. @property type @type String @default "text" @public */ type: _emberMetalComputed.computed({ get: function () { return 'text'; }, set: function (key, value) { var type = 'text'; if (canSetTypeOfInput(value)) { type = value; } return type; } }), /** The `size` of the text field in characters. @property size @type String @default null @public */ size: null, /** The `pattern` attribute of input element. @property pattern @type String @default null @public */ pattern: null, /** The `min` attribute of input element used with `type="number"` or `type="range"`. @property min @type String @default null @since 1.4.0 @public */ min: null, /** The `max` attribute of input element used with `type="number"` or `type="range"`. @property max @type String @default null @since 1.4.0 @public */ max: null }); }); enifed('ember-htmlbars/env', ['exports', 'ember-environment', 'htmlbars-runtime', 'ember-metal/assign', 'ember-metal/features', 'ember-htmlbars/hooks/subexpr', 'ember-htmlbars/hooks/concat', 'ember-htmlbars/hooks/link-render-node', 'ember-htmlbars/hooks/create-fresh-scope', 'ember-htmlbars/hooks/bind-shadow-scope', 'ember-htmlbars/hooks/bind-self', 'ember-htmlbars/hooks/bind-scope', 'ember-htmlbars/hooks/bind-local', 'ember-htmlbars/hooks/bind-block', 'ember-htmlbars/hooks/update-self', 'ember-htmlbars/hooks/get-root', 'ember-htmlbars/hooks/get-child', 'ember-htmlbars/hooks/get-block', 'ember-htmlbars/hooks/get-value', 'ember-htmlbars/hooks/get-cell-or-value', 'ember-htmlbars/hooks/cleanup-render-node', 'ember-htmlbars/hooks/destroy-render-node', 'ember-htmlbars/hooks/did-render-node', 'ember-htmlbars/hooks/will-cleanup-tree', 'ember-htmlbars/hooks/did-cleanup-tree', 'ember-htmlbars/hooks/classify', 'ember-htmlbars/hooks/component', 'ember-htmlbars/hooks/lookup-helper', 'ember-htmlbars/hooks/has-helper', 'ember-htmlbars/hooks/invoke-helper', 'ember-htmlbars/hooks/element', 'ember-htmlbars/helpers', 'ember-htmlbars/keywords', 'ember-htmlbars/system/dom-helper', 'ember-htmlbars/keywords/debugger', 'ember-htmlbars/keywords/with', 'ember-htmlbars/keywords/outlet', 'ember-htmlbars/keywords/unbound', 'ember-htmlbars/keywords/component', 'ember-htmlbars/keywords/element-component', 'ember-htmlbars/keywords/mount', 'ember-htmlbars/keywords/partial', 'ember-htmlbars/keywords/input', 'ember-htmlbars/keywords/textarea', 'ember-htmlbars/keywords/yield', 'ember-htmlbars/keywords/mut', 'ember-htmlbars/keywords/readonly', 'ember-htmlbars/keywords/get', 'ember-htmlbars/keywords/action', 'ember-htmlbars/keywords/render', 'ember-htmlbars/keywords/element-action'], function (exports, _emberEnvironment, _htmlbarsRuntime, _emberMetalAssign, _emberMetalFeatures, _emberHtmlbarsHooksSubexpr, _emberHtmlbarsHooksConcat, _emberHtmlbarsHooksLinkRenderNode, _emberHtmlbarsHooksCreateFreshScope, _emberHtmlbarsHooksBindShadowScope, _emberHtmlbarsHooksBindSelf, _emberHtmlbarsHooksBindScope, _emberHtmlbarsHooksBindLocal, _emberHtmlbarsHooksBindBlock, _emberHtmlbarsHooksUpdateSelf, _emberHtmlbarsHooksGetRoot, _emberHtmlbarsHooksGetChild, _emberHtmlbarsHooksGetBlock, _emberHtmlbarsHooksGetValue, _emberHtmlbarsHooksGetCellOrValue, _emberHtmlbarsHooksCleanupRenderNode, _emberHtmlbarsHooksDestroyRenderNode, _emberHtmlbarsHooksDidRenderNode, _emberHtmlbarsHooksWillCleanupTree, _emberHtmlbarsHooksDidCleanupTree, _emberHtmlbarsHooksClassify, _emberHtmlbarsHooksComponent, _emberHtmlbarsHooksLookupHelper, _emberHtmlbarsHooksHasHelper, _emberHtmlbarsHooksInvokeHelper, _emberHtmlbarsHooksElement, _emberHtmlbarsHelpers, _emberHtmlbarsKeywords, _emberHtmlbarsSystemDomHelper, _emberHtmlbarsKeywordsDebugger, _emberHtmlbarsKeywordsWith, _emberHtmlbarsKeywordsOutlet, _emberHtmlbarsKeywordsUnbound, _emberHtmlbarsKeywordsComponent, _emberHtmlbarsKeywordsElementComponent, _emberHtmlbarsKeywordsMount, _emberHtmlbarsKeywordsPartial, _emberHtmlbarsKeywordsInput, _emberHtmlbarsKeywordsTextarea, _emberHtmlbarsKeywordsYield, _emberHtmlbarsKeywordsMut, _emberHtmlbarsKeywordsReadonly, _emberHtmlbarsKeywordsGet, _emberHtmlbarsKeywordsAction, _emberHtmlbarsKeywordsRender, _emberHtmlbarsKeywordsElementAction) { 'use strict'; var emberHooks = _emberMetalAssign.default({}, _htmlbarsRuntime.hooks); emberHooks.keywords = _emberHtmlbarsKeywords.default; _emberMetalAssign.default(emberHooks, { linkRenderNode: _emberHtmlbarsHooksLinkRenderNode.default, createFreshScope: _emberHtmlbarsHooksCreateFreshScope.default, createChildScope: _emberHtmlbarsHooksCreateFreshScope.createChildScope, bindShadowScope: _emberHtmlbarsHooksBindShadowScope.default, bindSelf: _emberHtmlbarsHooksBindSelf.default, bindScope: _emberHtmlbarsHooksBindScope.default, bindLocal: _emberHtmlbarsHooksBindLocal.default, bindBlock: _emberHtmlbarsHooksBindBlock.default, updateSelf: _emberHtmlbarsHooksUpdateSelf.default, getBlock: _emberHtmlbarsHooksGetBlock.default, getRoot: _emberHtmlbarsHooksGetRoot.default, getChild: _emberHtmlbarsHooksGetChild.default, getValue: _emberHtmlbarsHooksGetValue.default, getCellOrValue: _emberHtmlbarsHooksGetCellOrValue.default, subexpr: _emberHtmlbarsHooksSubexpr.default, concat: _emberHtmlbarsHooksConcat.default, cleanupRenderNode: _emberHtmlbarsHooksCleanupRenderNode.default, destroyRenderNode: _emberHtmlbarsHooksDestroyRenderNode.default, willCleanupTree: _emberHtmlbarsHooksWillCleanupTree.default, didCleanupTree: _emberHtmlbarsHooksDidCleanupTree.default, didRenderNode: _emberHtmlbarsHooksDidRenderNode.default, classify: _emberHtmlbarsHooksClassify.default, component: _emberHtmlbarsHooksComponent.default, lookupHelper: _emberHtmlbarsHooksLookupHelper.default, hasHelper: _emberHtmlbarsHooksHasHelper.default, invokeHelper: _emberHtmlbarsHooksInvokeHelper.default, element: _emberHtmlbarsHooksElement.default }); _emberHtmlbarsKeywords.registerKeyword('debugger', _emberHtmlbarsKeywordsDebugger.default); _emberHtmlbarsKeywords.registerKeyword('with', _emberHtmlbarsKeywordsWith.default); _emberHtmlbarsKeywords.registerKeyword('outlet', _emberHtmlbarsKeywordsOutlet.default); _emberHtmlbarsKeywords.registerKeyword('unbound', _emberHtmlbarsKeywordsUnbound.default); _emberHtmlbarsKeywords.registerKeyword('component', _emberHtmlbarsKeywordsComponent.default); _emberHtmlbarsKeywords.registerKeyword('@element_component', _emberHtmlbarsKeywordsElementComponent.default); if (true) { _emberHtmlbarsKeywords.registerKeyword('mount', _emberHtmlbarsKeywordsMount.default); } _emberHtmlbarsKeywords.registerKeyword('partial', _emberHtmlbarsKeywordsPartial.default); _emberHtmlbarsKeywords.registerKeyword('input', _emberHtmlbarsKeywordsInput.default); _emberHtmlbarsKeywords.registerKeyword('textarea', _emberHtmlbarsKeywordsTextarea.default); _emberHtmlbarsKeywords.registerKeyword('yield', _emberHtmlbarsKeywordsYield.default); _emberHtmlbarsKeywords.registerKeyword('mut', _emberHtmlbarsKeywordsMut.default); _emberHtmlbarsKeywords.registerKeyword('@mut', _emberHtmlbarsKeywordsMut.privateMut); _emberHtmlbarsKeywords.registerKeyword('readonly', _emberHtmlbarsKeywordsReadonly.default); _emberHtmlbarsKeywords.registerKeyword('get', _emberHtmlbarsKeywordsGet.default); _emberHtmlbarsKeywords.registerKeyword('action', _emberHtmlbarsKeywordsAction.default); _emberHtmlbarsKeywords.registerKeyword('render', _emberHtmlbarsKeywordsRender.default); _emberHtmlbarsKeywords.registerKeyword('@element_action', _emberHtmlbarsKeywordsElementAction.default); exports.default = { hooks: emberHooks, helpers: _emberHtmlbarsHelpers.default, useFragmentCache: true }; var domHelper = _emberEnvironment.environment.hasDOM ? new _emberHtmlbarsSystemDomHelper.default() : null; exports.domHelper = domHelper; }); enifed('ember-htmlbars/helper', ['exports', 'ember-runtime/system/object'], function (exports, _emberRuntimeSystemObject) { /** @module ember @submodule ember-templates */ 'use strict'; exports.helper = helper; /** Ember Helpers are functions that can compute values, and are used in templates. For example, this code calls a helper named `format-currency`: ```handlebars <div>{{format-currency cents currency="$"}}</div> ``` Additionally, a helper can be called as a nested helper (sometimes called a subexpression). In this example, the computed value of a helper is passed to a component named `show-money`: ```handlebars {{show-money amount=(format-currency cents currency="$")}} ``` Helpers defined using a class must provide a `compute` function. For example: ```js export default Ember.Helper.extend({ compute(params, hash) { let cents = params[0]; let currency = hash.currency; return `${currency}${cents * 0.01}`; } }); ``` Each time the input to a helper changes, the `compute` function will be called again. As instances, these helpers also have access to the container and will accept injected dependencies. Additionally, class helpers can call `recompute` to force a new computation. If the output of your helper is only dependent on the current input, then you can use the `Helper.helper` function. See [Ember.Helper.helper](/api/classes/Ember.Helper.html#method_helper). In this form the example above becomes: ```js export default Ember.Helper.helper((params, hash) => { let cents = params[0]; let currency = hash.currency; return `${currency}${cents * 0.01}`; }); ``` @class Ember.Helper @public @since 1.13.0 */ var Helper = _emberRuntimeSystemObject.default.extend({ isHelperInstance: true, /** On a class-based helper, it may be useful to force a recomputation of that helpers value. This is akin to `rerender` on a component. For example, this component will rerender when the `currentUser` on a session service changes: ```js // app/helpers/current-user-email.js export default Ember.Helper.extend({ session: Ember.inject.service(), onNewUser: Ember.observer('session.currentUser', function() { this.recompute(); }), compute() { return this.get('session.currentUser.email'); } }); ``` @method recompute @public @since 1.13.0 */ recompute: function () { this._stream.notify(); } /** Override this function when writing a class-based helper. @method compute @param {Array} params The positional arguments to the helper @param {Object} hash The named arguments to the helper @public @since 1.13.0 */ }); Helper.reopenClass({ isHelperFactory: true }); /** In many cases, the ceremony of a full `Ember.Helper` class is not required. The `helper` method creates pure-function helpers without instances. For example: ```js // app/helpers/format-currency.js export function formatCurrency([cents], hash) { let currency = hash.currency; return `${currency}${cents * 0.01}`; }); export default Ember.Helper.helper(formatCurrency); // tests/myhelper.js import { formatCurrency } from ..../helpers/myhelper // add some tests ``` This form is more efficient at run time and results in smaller compiled js. It is also easier to test by using the following structure and importing the `formatCurrency` function into a test. @static @param {Function} helper The helper function @method helper @public @since 1.13.0 */ function helper(compute) { return { isHelperInstance: true, compute: compute }; } exports.default = Helper; }); enifed('ember-htmlbars/helpers', ['exports', 'ember-metal/empty_object'], function (exports, _emberMetalEmpty_object) { /** @module ember @submodule ember-htmlbars */ /** @private @property helpers */ 'use strict'; exports.registerHelper = registerHelper; var helpers = new _emberMetalEmpty_object.default(); /** @module ember @submodule ember-htmlbars */ /** @private @method _registerHelper @for Ember.HTMLBars @param {String} name @param {Object|Function} helperFunc The helper function to add. */ function registerHelper(name, helperFunc) { helpers[name] = helperFunc; } exports.default = helpers; }); enifed('ember-htmlbars/helpers/-html-safe', ['exports', 'htmlbars-util/safe-string'], function (exports, _htmlbarsUtilSafeString) { 'use strict'; exports.default = htmlSafeHelper; /** This private helper is used internally to handle `isVisible: false` for Ember.View and Ember.Component. @private */ function htmlSafeHelper(_ref) { var value = _ref[0]; return new _htmlbarsUtilSafeString.default(value); } }); enifed('ember-htmlbars/helpers/-join-classes', ['exports'], function (exports) { /* This private helper is used to join and compact a list of class names. @private */ 'use strict'; exports.default = joinClasses; function joinClasses(classNames) { var result = []; for (var i = 0; i < classNames.length; i++) { var className = classNames[i]; if (className) { result.push(className); } } return result.join(' '); } }); enifed('ember-htmlbars/helpers/-normalize-class', ['exports', 'ember-runtime/system/string', 'ember-metal/path_cache'], function (exports, _emberRuntimeSystemString, _emberMetalPath_cache) { 'use strict'; exports.default = normalizeClass; /* This private helper is used by ComponentNode to convert the classNameBindings microsyntax into a class name. When a component or view is created, we normalize class name bindings into a series of attribute nodes that use this helper. @private */ function normalizeClass(params, hash) { var propName = params[0]; var value = params[1]; var activeClass = hash.activeClass; var inactiveClass = hash.inactiveClass; // When using the colon syntax, evaluate the truthiness or falsiness // of the value to determine which className to return. if (activeClass || inactiveClass) { if (!!value) { return activeClass; } else { return inactiveClass; } // If value is a Boolean and true, return the dasherized property // name. } else if (value === true) { // Only apply to last segment in the path. if (propName && _emberMetalPath_cache.isPath(propName)) { var segments = propName.split('.'); propName = segments[segments.length - 1]; } return _emberRuntimeSystemString.dasherize(propName); // If the value is not false, undefined, or null, return the current // value of the property. } else if (value !== false && value != null) { return value; // Nothing to display. Return null so that the old class is removed // but no new class is added. } else { return null; } } }); enifed('ember-htmlbars/helpers/concat', ['exports'], function (exports) { /** @module ember @submodule ember-templates */ /** Concatenates input params together. Example: ```handlebars {{some-component name=(concat firstName " " lastName)}} {{! would pass name="<first name value> <last name value>" to the component}} ``` @public @method concat @for Ember.Templates.helpers @since 1.13.0 */ 'use strict'; exports.default = concat; function concat(params) { return params.join(''); } }); enifed('ember-htmlbars/helpers/each-in', ['exports', 'ember-htmlbars/streams/should_display'], function (exports, _emberHtmlbarsStreamsShould_display) { /** @module ember @submodule ember-templates */ 'use strict'; exports.default = eachInHelper; /** The `{{each-in}}` helper loops over properties on an object. It is unbound, in that new (or removed) properties added to the target object will not be rendered. For example, given a `user` object that looks like: ```javascript { "name": "Shelly Sails", "age": 42 } ``` This template would display all properties on the `user` object in a list: ```handlebars <ul> {{#each-in user as |key value|}} <li>{{key}}: {{value}}</li> {{/each-in}} </ul> ``` Outputting their name and age. @method each-in @for Ember.Templates.helpers @public @since 2.1.0 */ function eachInHelper(_ref, hash, blocks) { var object = _ref[0]; var objKeys = undefined, prop = undefined; objKeys = object ? Object.keys(object) : []; if (_emberHtmlbarsStreamsShould_display.default(objKeys)) { for (var i = 0; i < objKeys.length; i++) { prop = objKeys[i]; blocks.template.yieldItem(prop, [prop, object[prop]]); } } else if (blocks.inverse.yield) { blocks.inverse.yield(); } } }); enifed('ember-htmlbars/helpers/each', ['exports', 'ember-htmlbars/streams/should_display', 'ember-htmlbars/utils/decode-each-key'], function (exports, _emberHtmlbarsStreamsShould_display, _emberHtmlbarsUtilsDecodeEachKey) { /** @module ember @submodule ember-templates */ 'use strict'; exports.default = eachHelper; /** The `{{#each}}` helper loops over elements in a collection. It is an extension of the base Handlebars `{{#each}}` helper. The default behavior of `{{#each}}` is to yield its inner block once for every item in an array passing the item as the first block parameter. ```javascript var developers = [{ name: 'Yehuda' },{ name: 'Tom' }, { name: 'Paul' }]; ``` ```handlebars {{#each developers key="name" as |person|}} {{person.name}} {{! `this` is whatever it was outside the #each }} {{/each}} ``` The same rules apply to arrays of primitives. ```javascript var developerNames = ['Yehuda', 'Tom', 'Paul'] ``` ```handlebars {{#each developerNames key="@index" as |name|}} {{name}} {{/each}} ``` During iteration, the index of each item in the array is provided as a second block parameter. ```handlebars <ul> {{#each people as |person index|}} <li>Hello, {{person.name}}! You're number {{index}} in line</li> {{/each}} </ul> ``` ### Specifying Keys The `key` option is used to tell Ember how to determine if the array being iterated over with `{{#each}}` has changed between renders. By helping Ember detect that some elements in the array are the same, DOM elements can be re-used, significantly improving rendering speed. For example, here's the `{{#each}}` helper with its `key` set to `id`: ```handlebars {{#each model key="id" as |item|}} {{/each}} ``` When this `{{#each}}` re-renders, Ember will match up the previously rendered items (and reorder the generated DOM elements) based on each item's `id` property. By default the item's own reference is used. ### {{else}} condition `{{#each}}` can have a matching `{{else}}`. The contents of this block will render if the collection is empty. ```handlebars {{#each developers as |person|}} {{person.name}} {{else}} <p>Sorry, nobody is available for this task.</p> {{/each}} ``` @method each @for Ember.Templates.helpers @public */ function eachHelper(params, hash, blocks) { var list = params[0]; var keyPath = hash.key; if (_emberHtmlbarsStreamsShould_display.default(list)) { forEach(list, function (item, i) { var key = _emberHtmlbarsUtilsDecodeEachKey.default(item, keyPath, i); blocks.template.yieldItem(key, [item, i]); }); } else if (blocks.inverse.yield) { blocks.inverse.yield(); } } function forEach(iterable, cb) { return iterable.forEach ? iterable.forEach(cb) : Array.prototype.forEach.call(iterable, cb); } }); enifed("ember-htmlbars/helpers/hash", ["exports"], function (exports) { /** @module ember @submodule ember-templates */ /** Use the `{{hash}}` helper to create a hash to pass as an option to your components. This is specially useful for contextual components where you can just yield a hash: ```handlebars {{yield (hash name='Sarah' title=office )}} ``` Would result in an object such as: ```js { name: 'Sarah', title: this.get('office') } ``` Where the `title` is bound to updates of the `office` property. @method hash @for Ember.Templates.helpers @param {Object} options @return {Object} Hash @public */ "use strict"; exports.default = hashHelper; function hashHelper(params, hash, options) { return hash; } }); enifed('ember-htmlbars/helpers/if_unless', ['exports', 'ember-metal/debug', 'ember-htmlbars/streams/should_display'], function (exports, _emberMetalDebug, _emberHtmlbarsStreamsShould_display) { /** @module ember @submodule ember-templates */ 'use strict'; /** Use the `if` block helper to conditionally render a block depending on a property. If the property is "falsey", for example: `false`, `undefined`, `null`, `""`, `0`, `NaN` or an empty array, the block will not be rendered. ```handlebars {{! will not render if foo is falsey}} {{#if foo}} Welcome to the {{foo.bar}} {{/if}} ``` You can also specify a template to show if the property is falsey by using the `else` helper. ```handlebars {{! is it raining outside?}} {{#if isRaining}} Yes, grab an umbrella! {{else}} No, it's lovely outside! {{/if}} ``` You are also able to combine `else` and `if` helpers to create more complex conditional logic. ```handlebars {{#if isMorning}} Good morning {{else if isAfternoon}} Good afternoon {{else}} Good night {{/if}} ``` You can use `if` inline to conditionally render a single property or string. This helper acts like a ternary operator. If the first property is truthy, the second argument will be displayed, if not, the third argument will be displayed ```handlebars {{if useLongGreeting "Hello" "Hi"}} Dave ``` Finally, you can use the `if` helper inside another helper as a subexpression. ```handlebars {{some-component height=(if isBig "100" "10")}} ``` @method if @for Ember.Templates.helpers @public */ function ifHelper(params, hash, options) { _emberMetalDebug.assert('The block form of the `if` helper expects exactly one argument, e.g. ' + '`{{#if newMessages}} You have new messages. {{/if}}.`', !options.template.yield || params.length === 1); _emberMetalDebug.assert('The inline form of the `if` helper expects two or three arguments, e.g. ' + '`{{if trialExpired "Expired" expiryDate}}`.', !!options.template.yield || params.length === 2 || params.length === 3); return ifUnless(params, hash, options, _emberHtmlbarsStreamsShould_display.default(params[0])); } /** The `unless` helper is the inverse of the `if` helper. Its block will be rendered if the expression contains a falsey value. All forms of the `if` helper can also be used with `unless`. @method unless @for Ember.Templates.helpers @public */ function unlessHelper(params, hash, options) { _emberMetalDebug.assert('The block form of the `unless` helper expects exactly one argument, e.g. ' + '`{{#unless isFirstLogin}} Welcome back! {{/unless}}.`', !options.template.yield || params.length === 1); _emberMetalDebug.assert('The inline form of the `unless` helper expects two or three arguments, e.g. ' + '`{{if trialExpired "Expired" expiryDate}}`.', !!options.template.yield || params.length === 2 || params.length === 3); return ifUnless(params, hash, options, !_emberHtmlbarsStreamsShould_display.default(params[0])); } function ifUnless(params, hash, options, truthy) { if (truthy) { if (options.template.yield) { options.template.yield(); } else { return params[1]; } } else { if (options.inverse.yield) { options.inverse.yield(); } else { return params[2]; } } } exports.ifHelper = ifHelper; exports.unlessHelper = unlessHelper; }); enifed('ember-htmlbars/helpers/loc', ['exports', 'ember-htmlbars/helper', 'ember-runtime/system/string'], function (exports, _emberHtmlbarsHelper, _emberRuntimeSystemString) { 'use strict'; /** @module ember @submodule ember-templates */ /** Calls [Ember.String.loc](/api/classes/Ember.String.html#method_loc) with the provided string. This is a convenient way to localize text within a template. For example: ```javascript Ember.STRINGS = { '_welcome_': 'Bonjour' }; ``` ```handlebars <div class='message'> {{loc '_welcome_'}} </div> ``` ```html <div class='message'> Bonjour </div> ``` See [Ember.String.loc](/api/classes/Ember.String.html#method_loc) for how to set up localized string references. @method loc @for Ember.Templates.helpers @param {String} str The string to format. @see {Ember.String#loc} @public */ function locHelper(params) { return _emberRuntimeSystemString.loc.apply(null, params); } exports.default = _emberHtmlbarsHelper.helper(locHelper); }); enifed('ember-htmlbars/helpers/log', ['exports', 'ember-console'], function (exports, _emberConsole) { /** @module ember @submodule ember-templates */ 'use strict'; exports.default = logHelper; /** `log` allows you to output the value of variables in the current rendering context. `log` also accepts primitive types such as strings or numbers. ```handlebars {{log "myVariable:" myVariable }} ``` @method log @for Ember.Templates.helpers @param {*} values @public */ function logHelper(values) { _emberConsole.default.log.apply(null, values); } }); enifed('ember-htmlbars/helpers/query-params', ['exports', 'ember-metal/debug', 'ember-routing/system/query_params'], function (exports, _emberMetalDebug, _emberRoutingSystemQuery_params) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = queryParamsHelper; /** This is a helper to be used in conjunction with the link-to helper. It will supply url query parameters to the target route. Example ```handlebars {{#link-to 'posts' (query-params direction="asc")}}Sort{{/link-to}} ``` @method query-params @for Ember.Templates.helpers @param {Object} hash takes a hash of query parameters @return {Object} A `QueryParams` object for `{{link-to}}` @public */ function queryParamsHelper(params, hash) { _emberMetalDebug.assert('The `query-params` helper only accepts hash parameters, e.g. (query-params queryParamPropertyName=\'foo\') as opposed to just (query-params \'foo\')', params.length === 0); return _emberRoutingSystemQuery_params.default.create({ values: hash }); } }); enifed('ember-htmlbars/helpers/with', ['exports', 'ember-htmlbars/streams/should_display'], function (exports, _emberHtmlbarsStreamsShould_display) { /** @module ember @submodule ember-templates */ 'use strict'; exports.default = withHelper; /** Use the `{{with}}` helper when you want to alias a property to a new name. This is helpful for semantic clarity as it allows you to retain default scope or to reference a property from another `{{with}}` block. If the aliased property is "falsey", for example: `false`, `undefined` `null`, `""`, `0`, NaN or an empty array, the block will not be rendered. ```handlebars {{! Will only render if user.posts contains items}} {{#with user.posts as |blogPosts|}} <div class="notice"> There are {{blogPosts.length}} blog posts written by {{user.name}}. </div> {{#each blogPosts as |post|}} <li>{{post.title}}</li> {{/each}} {{/with}} ``` Without the `as` operator, it would be impossible to reference `user.name` in the example above. NOTE: The alias should not reuse a name from the bound property path. For example: `{{#with foo.bar as |foo|}}` is not supported because it attempts to alias using the first part of the property path, `foo`. Instead, use `{{#with foo.bar as |baz|}}`. @method with @for Ember.Templates.helpers @param {Object} options @return {String} HTML string @public */ function withHelper(params, hash, options) { if (_emberHtmlbarsStreamsShould_display.default(params[0])) { options.template.yield([params[0]]); } else if (options.inverse && options.inverse.yield) { options.inverse.yield([]); } } }); enifed('ember-htmlbars/hooks/bind-block', ['exports'], function (exports) { 'use strict'; exports.default = bindBlock; function bindBlock(env, scope, block) { var name = arguments.length <= 3 || arguments[3] === undefined ? 'default' : arguments[3]; scope.bindBlock(name, block); } }); enifed('ember-htmlbars/hooks/bind-local', ['exports', 'ember-htmlbars/streams/stream', 'ember-htmlbars/streams/proxy-stream'], function (exports, _emberHtmlbarsStreamsStream, _emberHtmlbarsStreamsProxyStream) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = bindLocal; function bindLocal(env, scope, key, value) { // TODO: What is the cause of these cases? if (scope.hasOwnLocal(key)) { var existing = scope.getLocal(key); if (existing !== value) { existing.setSource(value); } } else { var newValue = _emberHtmlbarsStreamsStream.wrap(value, _emberHtmlbarsStreamsProxyStream.default, key); scope.bindLocal(key, newValue); } } }); enifed("ember-htmlbars/hooks/bind-scope", ["exports"], function (exports) { "use strict"; exports.default = bindScope; function bindScope(env, scope) {} }); enifed('ember-htmlbars/hooks/bind-self', ['exports', 'ember-htmlbars/streams/proxy-stream'], function (exports, _emberHtmlbarsStreamsProxyStream) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = bindSelf; function bindSelf(env, scope, self) { var selfStream = newStream(self, ''); scope.bindSelf(selfStream); } function newStream(newValue, key) { return new _emberHtmlbarsStreamsProxyStream.default(newValue, key); } }); enifed('ember-htmlbars/hooks/bind-shadow-scope', ['exports', 'ember-htmlbars/streams/proxy-stream'], function (exports, _emberHtmlbarsStreamsProxyStream) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = bindShadowScope; function bindShadowScope(env, parentScope, shadowScope, options) { if (!options) { return; } var view = options.view; if (view && !view.isComponent) { shadowScope.bindLocal('view', newStream(view, 'view')); if (view.isView) { shadowScope.bindSelf(newStream(shadowScope.getLocal('view').getKey('context'), '')); } } shadowScope.bindView(view); if (view && options.attrs) { shadowScope.bindComponent(view); } if ('attrs' in options) { shadowScope.bindAttrs(options.attrs); } return shadowScope; } function newStream(newValue, key) { return new _emberHtmlbarsStreamsProxyStream.default(newValue, key); } }); enifed('ember-htmlbars/hooks/classify', ['exports', 'ember-htmlbars/utils/is-component'], function (exports, _emberHtmlbarsUtilsIsComponent) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = classify; function classify(env, scope, path) { if (_emberHtmlbarsUtilsIsComponent.default(env, scope, path)) { return 'component'; } return null; } }); enifed('ember-htmlbars/hooks/cleanup-render-node', ['exports'], function (exports) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = cleanupRenderNode; function cleanupRenderNode(renderNode) { var view = renderNode.emberView; if (view) { view.renderer.willDestroyElement(view); view.ownerView._destroyingSubtreeForView.push(function (env) { view._transitionTo('destroying'); // unregisters view // prevents rerender and scheduling view._renderNode = null; renderNode.emberView = null; view.renderer.didDestroyElement(view); if (view.parentView && view.parentView === env.view) { view.parentView.removeChild(view); } view.parentView = null; view._transitionTo('preRender'); }); } if (renderNode.cleanup) { renderNode.cleanup(); } } }); enifed('ember-htmlbars/hooks/component', ['exports', 'ember-metal/debug', 'ember-htmlbars/node-managers/component-node-manager', 'ember-views/utils/lookup-component', 'ember-metal/assign', 'ember-metal/empty_object', 'ember-htmlbars/system/lookup-helper', 'ember-htmlbars/utils/extract-positional-params', 'ember-htmlbars/keywords/closure-component'], function (exports, _emberMetalDebug, _emberHtmlbarsNodeManagersComponentNodeManager, _emberViewsUtilsLookupComponent, _emberMetalAssign, _emberMetalEmpty_object, _emberHtmlbarsSystemLookupHelper, _emberHtmlbarsUtilsExtractPositionalParams, _emberHtmlbarsKeywordsClosureComponent) { 'use strict'; exports.default = componentHook; function componentHook(renderNode, env, scope, _tagName, params, _attrs, templates, visitor) { var state = renderNode.getState(); var tagName = _tagName; var attrs = _attrs; if (_emberHtmlbarsSystemLookupHelper.CONTAINS_DOT_CACHE.get(tagName)) { var stream = env.hooks.get(env, scope, tagName); var componentCell = stream.value(); if (_emberHtmlbarsKeywordsClosureComponent.isComponentCell(componentCell)) { tagName = componentCell[_emberHtmlbarsKeywordsClosureComponent.COMPONENT_PATH]; /* * Processing positional params before merging into a hash must be done * here to avoid problems with rest positional parameters rendered using * the dot notation. * * Closure components (for the contextual component feature) do not * actually keep the positional params, but process them at each level. * Therefore, when rendering a closure component with the component * helper we process the parameters and attributes and then merge those * on top of the closure component attributes. * */ var newAttrs = _emberMetalAssign.default(new _emberMetalEmpty_object.default(), attrs); _emberHtmlbarsKeywordsClosureComponent.processPositionalParamsFromCell(componentCell, params, newAttrs); attrs = _emberHtmlbarsKeywordsClosureComponent.mergeInNewHash(componentCell[_emberHtmlbarsKeywordsClosureComponent.COMPONENT_HASH], newAttrs, componentCell[_emberHtmlbarsKeywordsClosureComponent.COMPONENT_POSITIONAL_PARAMS], params); params = []; } } // Determine if this is an initial render or a re-render. if (state.manager) { var sm = state.manager; _emberHtmlbarsUtilsExtractPositionalParams.default(renderNode, sm.component.constructor, params, attrs, false); state.manager.rerender(env, attrs, visitor); return; } var parentView = env.view; var moduleName = env.meta && env.meta.moduleName; var options = { source: moduleName && 'template:' + moduleName }; var _lookupComponent = _emberViewsUtilsLookupComponent.default(env.owner, tagName, options); var component = _lookupComponent.component; var layout = _lookupComponent.layout; _emberMetalDebug.assert('HTMLBars error: Could not find component named "' + tagName + '" (no component or template with that name was found)', !!(component || layout)); var manager = _emberHtmlbarsNodeManagersComponentNodeManager.default.create(renderNode, env, { tagName: tagName, params: params, attrs: attrs, parentView: parentView, templates: templates, component: component, layout: layout, parentScope: scope }); state.manager = manager; manager.render(env, visitor); } }); enifed('ember-htmlbars/hooks/concat', ['exports', 'ember-htmlbars/streams/concat'], function (exports, _emberHtmlbarsStreamsConcat) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = concat; function concat(env, parts) { return _emberHtmlbarsStreamsConcat.default(parts, ''); } }); enifed('ember-htmlbars/hooks/create-fresh-scope', ['exports', 'ember-htmlbars/streams/proxy-stream', 'ember-metal/empty_object'], function (exports, _emberHtmlbarsStreamsProxyStream, _emberMetalEmpty_object) { 'use strict'; exports.default = createFreshScope; exports.createChildScope = createChildScope; /* Ember's implementation of HTMLBars creates an enriched scope. * self: same as HTMLBars, this field represents the dynamic lookup of root keys that are not special keywords or block arguments. * blocks: same as HTMLBars, a bundle of named blocks the layout can yield to. * component: indicates that the scope is the layout of a component, which is used to trigger lifecycle hooks for the component when one of the streams in its layout fires. * attrs: a map of key-value attributes sent in by the invoker of a template, and available in the component's layout. * locals: a map of locals, produced by block params (`as |a b|`) * localPresent: a map of available locals to avoid expensive `hasOwnProperty` checks. The `self` field has two special meanings: * If `self` is a view (`isView`), the actual HTMLBars `self` becomes the view's `context`. This is legacy semantics; components always use the component itself as the `this`. * If `self` is a view, two special locals are created: `view` and `controller`. These locals are legacy semantics. **IMPORTANT**: There are two places in Ember where the ambient controller is looked up. Both of those places use the presence of `scope.locals.view` to indicate that the controller lookup should be dynamic off of the ambient view. If `scope.locals.view` does not exist, the code assumes that it is inside of a top-level template (without a view) and uses the `self` itself as the controller. This means that if you remove `scope.locals.view` (perhaps because we are finally ready to shed the view keyword), there may be unexpected consequences on controller semantics. If this happens to you, I hope you find this comment. - YK & TD In practice, this means that with the exceptions of top-level view-less templates and the legacy `controller=foo` semantics, the controller hierarchy is managed dynamically by looking at the current view's `controller`. */ function Scope(parent) { this._self = undefined; this._blocks = undefined; this._component = undefined; this._view = undefined; this._attrs = undefined; this._locals = undefined; this._localPresent = undefined; this.overrideController = undefined; this.parent = parent; } var proto = Scope.prototype; proto.getSelf = function () { return this._self || this.parent.getSelf(); }; proto.bindSelf = function (self) { this._self = self; }; proto.updateSelf = function (self, key) { var existing = this._self; if (existing) { existing.setSource(self); } else { this._self = new _emberHtmlbarsStreamsProxyStream.default(self, key); } }; proto.getBlock = function (name) { if (!this._blocks) { return this.parent.getBlock(name); } return this._blocks[name] || this.parent.getBlock(name); }; proto.hasBlock = function (name) { if (!this._blocks) { return this.parent.hasBlock(name); } return !!(this._blocks[name] || this.parent.hasBlock(name)); }; proto.bindBlock = function (name, block) { if (!this._blocks) { this._blocks = new _emberMetalEmpty_object.default(); } this._blocks[name] = block; }; proto.getComponent = function () { return this._component || this.parent.getComponent(); }; proto.bindComponent = function (component) { this._component = component; }; proto.getView = function () { return this._view || this.parent.getView(); }; proto.bindView = function (view) { this._view = view; }; proto.getAttrs = function () { return this._attrs || this.parent.getAttrs(); }; proto.bindAttrs = function (attrs) { this._attrs = attrs; }; proto.hasLocal = function (name) { if (!this._localPresent) { return this.parent.hasLocal(name); } return this._localPresent[name] || this.parent.hasLocal(name); }; proto.hasOwnLocal = function (name) { return this._localPresent && this._localPresent[name]; }; proto.getLocal = function (name) { if (!this._localPresent) { return this.parent.getLocal(name); } return this._localPresent[name] ? this._locals[name] : this.parent.getLocal(name); }; proto.bindLocal = function (name, value) { if (!this._localPresent) { this._localPresent = new _emberMetalEmpty_object.default(); this._locals = new _emberMetalEmpty_object.default(); } this._localPresent[name] = true; this._locals[name] = value; }; var EMPTY = { _self: undefined, _blocks: undefined, _component: undefined, _view: undefined, _attrs: undefined, _locals: undefined, _localPresent: undefined, overrideController: undefined, getSelf: function () { return null; }, bindSelf: function (self) { return null; }, updateSelf: function (self, key) { return null; }, getBlock: function (name) { return null; }, bindBlock: function (name, block) { return null; }, hasBlock: function (name) { return false; }, getComponent: function () { return null; }, bindComponent: function () { return null; }, getView: function () { return null; }, bindView: function (view) { return null; }, getAttrs: function () { return null; }, bindAttrs: function (attrs) { return null; }, hasLocal: function (name) { return false; }, hasOwnLocal: function (name) { return false; }, getLocal: function (name) { return null; }, bindLocal: function (name, value) { return null; } }; function createFreshScope() { return new Scope(EMPTY); } function createChildScope(parent) { return new Scope(parent); } }); enifed("ember-htmlbars/hooks/destroy-render-node", ["exports"], function (exports) { /** @module ember @submodule ember-htmlbars */ "use strict"; exports.default = destroyRenderNode; function destroyRenderNode(renderNode) { var view = renderNode.emberView; if (view) { view.ownerView._destroyingSubtreeForView.push(function () { view.destroy(); }); } var streamUnsubscribers = renderNode.streamUnsubscribers; if (streamUnsubscribers) { for (var i = 0; i < streamUnsubscribers.length; i++) { streamUnsubscribers[i](); } } renderNode.streamUnsubscribers = null; } }); enifed("ember-htmlbars/hooks/did-cleanup-tree", ["exports"], function (exports) { "use strict"; exports.default = didCleanupTree; function didCleanupTree(env) { // Once we have finsihed cleaning up the render node and sub-nodes, reset // state tracking which view those render nodes belonged to. var queue = env.view.ownerView._destroyingSubtreeForView; for (var i = 0; i < queue.length; i++) { queue[i](env); } env.view.ownerView._destroyingSubtreeForView = null; } }); enifed("ember-htmlbars/hooks/did-render-node", ["exports"], function (exports) { "use strict"; exports.default = didRenderNode; function didRenderNode(morph, env) { env.renderedNodes.add(morph); } }); enifed('ember-htmlbars/hooks/element', ['exports', 'ember-htmlbars/system/lookup-helper', 'htmlbars-runtime/hooks', 'ember-htmlbars/system/invoke-helper'], function (exports, _emberHtmlbarsSystemLookupHelper, _htmlbarsRuntimeHooks, _emberHtmlbarsSystemInvokeHelper) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = emberElement; function emberElement(morph, env, scope, path, params, hash, visitor) { if (_htmlbarsRuntimeHooks.handleRedirect(morph, env, scope, path, params, hash, null, null, visitor)) { return; } var result = undefined; var helper = _emberHtmlbarsSystemLookupHelper.findHelper(path, scope.getSelf(), env); if (helper) { var helperStream = _emberHtmlbarsSystemInvokeHelper.buildHelperStream(helper, params, hash, { element: morph.element }, env, scope, path); result = helperStream.value(); } else { result = env.hooks.get(env, scope, path); } env.hooks.getValue(result); } }); enifed("ember-htmlbars/hooks/get-block", ["exports"], function (exports) { "use strict"; exports.default = getBlock; function getBlock(scope, key) { return scope.getBlock(key); } }); enifed('ember-htmlbars/hooks/get-cell-or-value', ['exports', 'ember-htmlbars/streams/utils', 'ember-htmlbars/keywords/mut'], function (exports, _emberHtmlbarsStreamsUtils, _emberHtmlbarsKeywordsMut) { 'use strict'; exports.default = getCellOrValue; function getCellOrValue(ref) { if (ref && ref[_emberHtmlbarsKeywordsMut.MUTABLE_REFERENCE]) { // Reify the mutable reference into a mutable cell. return ref.cell(); } // Get the value out of the reference. return _emberHtmlbarsStreamsUtils.read(ref); } }); enifed('ember-htmlbars/hooks/get-child', ['exports', 'ember-htmlbars/streams/utils'], function (exports, _emberHtmlbarsStreamsUtils) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = getChild; function getChild(parent, key) { if (_emberHtmlbarsStreamsUtils.isStream(parent)) { return parent.getKey(key); } // This should only happen when we are looking at an `attrs` hash. // That might change if it is possible to pass object literals // through the templating system. return parent[key]; } }); enifed('ember-htmlbars/hooks/get-root', ['exports'], function (exports) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = getRoot; function getRoot(scope, key) { if (key === 'this') { return [scope.getSelf()]; } else if (key === 'hasBlock') { return [!!scope.hasBlock('default')]; } else if (key === 'hasBlockParams') { var block = scope.getBlock('default'); return [!!block && !!block.arity]; } else if (scope.hasLocal(key)) { return [scope.getLocal(key)]; } else { return [getKey(scope, key)]; } } function getKey(scope, key) { if (key === 'attrs') { var _attrs = scope.getAttrs(); if (_attrs) { return _attrs; } } var self = scope.getSelf() || scope.getLocal('view'); if (self) { return self.getKey(key); } var attrs = scope.getAttrs(); if (attrs && key in attrs) { // TODO: attrs // deprecate("You accessed the `" + key + "` attribute directly. Please use `attrs." + key + "` instead."); return attrs[key]; } } }); enifed('ember-htmlbars/hooks/get-value', ['exports', 'ember-htmlbars/streams/utils', 'ember-views/compat/attrs-proxy'], function (exports, _emberHtmlbarsStreamsUtils, _emberViewsCompatAttrsProxy) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = getValue; function getValue(ref) { var value = _emberHtmlbarsStreamsUtils.read(ref); if (value && value[_emberViewsCompatAttrsProxy.MUTABLE_CELL]) { return value.value; } return value; } }); enifed('ember-htmlbars/hooks/has-helper', ['exports', 'ember-htmlbars/system/lookup-helper'], function (exports, _emberHtmlbarsSystemLookupHelper) { 'use strict'; exports.default = hasHelperHook; function hasHelperHook(env, scope, helperName) { if (env.helpers[helperName]) { return true; } var owner = env.owner; if (_emberHtmlbarsSystemLookupHelper.validateLazyHelperName(helperName, owner, env.hooks.keywords)) { var registrationName = 'helper:' + helperName; if (owner.hasRegistration(registrationName)) { return true; } var options = {}; var moduleName = env.meta && env.meta.moduleName; if (moduleName) { options.source = 'template:' + moduleName; } if (owner.hasRegistration(registrationName, options)) { return true; } } return false; } }); enifed('ember-htmlbars/hooks/invoke-helper', ['exports', 'ember-htmlbars/system/invoke-helper', 'ember-htmlbars/utils/subscribe'], function (exports, _emberHtmlbarsSystemInvokeHelper, _emberHtmlbarsUtilsSubscribe) { 'use strict'; exports.default = invokeHelper; function invokeHelper(morph, env, scope, visitor, params, hash, helper, templates, context) { var helperStream = _emberHtmlbarsSystemInvokeHelper.buildHelperStream(helper, params, hash, templates, env, scope); // Ember.Helper helpers are pure values, thus linkable. if (helperStream.linkable) { if (morph) { // When processing an inline expression, the params and hash have already // been linked. Thus, HTMLBars will not link the returned helperStream. // We subscribe the morph to the helperStream here, and also subscribe // the helperStream to any params. var addedDependency = false; for (var i = 0; i < params.length; i++) { addedDependency = true; helperStream.addDependency(params[i]); } for (var key in hash) { addedDependency = true; helperStream.addDependency(hash[key]); } if (addedDependency) { _emberHtmlbarsUtilsSubscribe.default(morph, env, scope, helperStream); } } return { link: true, value: helperStream }; } // Built-in helpers are not linkable. They must run on every rerender. return { value: helperStream.value() }; } }); enifed('ember-htmlbars/hooks/link-render-node', ['exports', 'ember-htmlbars/utils/subscribe', 'ember-runtime/utils', 'ember-htmlbars/streams/utils', 'ember-htmlbars/system/lookup-helper', 'ember-htmlbars/keywords/closure-component'], function (exports, _emberHtmlbarsUtilsSubscribe, _emberRuntimeUtils, _emberHtmlbarsStreamsUtils, _emberHtmlbarsSystemLookupHelper, _emberHtmlbarsKeywordsClosureComponent) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = linkRenderNode; exports.linkParamsFor = linkParamsFor; function linkRenderNode(renderNode, env, scope, path, params, hash) { if (renderNode.streamUnsubscribers) { return true; } var keyword = env.hooks.keywords[path]; if (keyword && keyword.link) { keyword.link(renderNode.getState(), params, hash); } else if (path === 'unbound') { return true; } else { linkParamsFor(path, params); } // If there is a dot in the path, we need to subscribe to the arguments in the // closure component as well. if (_emberHtmlbarsSystemLookupHelper.CONTAINS_DOT_CACHE.get(path)) { var stream = env.hooks.get(env, scope, path); var componentCell = stream.value(); if (_emberHtmlbarsKeywordsClosureComponent.isComponentCell(componentCell)) { var closureAttrs = _emberHtmlbarsKeywordsClosureComponent.mergeInNewHash(componentCell[_emberHtmlbarsKeywordsClosureComponent.COMPONENT_HASH], hash); for (var key in closureAttrs) { _emberHtmlbarsUtilsSubscribe.default(renderNode, env, scope, closureAttrs[key]); } } } if (params && params.length) { for (var i = 0; i < params.length; i++) { _emberHtmlbarsUtilsSubscribe.default(renderNode, env, scope, params[i]); } } if (hash) { for (var key in hash) { _emberHtmlbarsUtilsSubscribe.default(renderNode, env, scope, hash[key]); } } // The params and hash can be reused. They don't need to be // recomputed on subsequent re-renders because they are // streams. return true; } function linkParamsFor(path, params) { switch (path) { case 'unless': case 'if': params[0] = shouldDisplay(params[0], toBool);break; case 'each': params[0] = eachParam(params[0]);break; case 'with': params[0] = shouldDisplay(params[0], identity);break; } } function eachParam(list) { var listChange = getKey(list, '[]'); var stream = _emberHtmlbarsStreamsUtils.chain(list, function () { _emberHtmlbarsStreamsUtils.read(listChange); return _emberHtmlbarsStreamsUtils.read(list); }, 'each'); stream.addDependency(listChange); return stream; } function shouldDisplay(predicate, coercer) { var length = getKey(predicate, 'length'); var isTruthy = getKey(predicate, 'isTruthy'); var stream = _emberHtmlbarsStreamsUtils.chain(predicate, function () { var predicateVal = _emberHtmlbarsStreamsUtils.read(predicate); var lengthVal = _emberHtmlbarsStreamsUtils.read(length); var isTruthyVal = _emberHtmlbarsStreamsUtils.read(isTruthy); if (_emberRuntimeUtils.isArray(predicateVal)) { return lengthVal > 0 ? coercer(predicateVal) : false; } if (typeof isTruthyVal === 'boolean') { return isTruthyVal ? coercer(predicateVal) : false; } return coercer(predicateVal); }, 'ShouldDisplay'); _emberHtmlbarsStreamsUtils.addDependency(stream, length); _emberHtmlbarsStreamsUtils.addDependency(stream, isTruthy); return stream; } function toBool(value) { return !!value; } function identity(value) { return value; } function getKey(obj, key) { if (_emberHtmlbarsStreamsUtils.isStream(obj)) { return obj.getKey(key); } else { return obj && obj[key]; } } }); enifed('ember-htmlbars/hooks/lookup-helper', ['exports', 'ember-htmlbars/system/lookup-helper'], function (exports, _emberHtmlbarsSystemLookupHelper) { 'use strict'; exports.default = lookupHelperHook; function lookupHelperHook(env, scope, helperName) { return _emberHtmlbarsSystemLookupHelper.default(helperName, scope.getSelf(), env); } }); enifed('ember-htmlbars/hooks/subexpr', ['exports', 'ember-htmlbars/system/lookup-helper', 'ember-htmlbars/system/invoke-helper', 'ember-htmlbars/streams/utils', 'ember-htmlbars/hooks/link-render-node'], function (exports, _emberHtmlbarsSystemLookupHelper, _emberHtmlbarsSystemInvokeHelper, _emberHtmlbarsStreamsUtils, _emberHtmlbarsHooksLinkRenderNode) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = subexpr; exports.labelForSubexpr = labelForSubexpr; function subexpr(env, scope, helperName, params, hash) { // TODO: Keywords and helper invocation should be integrated into // the subexpr hook upstream in HTMLBars. var keyword = env.hooks.keywords[helperName]; if (keyword) { return keyword(null, env, scope, params, hash, null, null); } _emberHtmlbarsHooksLinkRenderNode.linkParamsFor(helperName, params); var label = labelForSubexpr(params, hash, helperName); var helper = _emberHtmlbarsSystemLookupHelper.default(helperName, scope.getSelf(), env); var helperStream = _emberHtmlbarsSystemInvokeHelper.buildHelperStream(helper, params, hash, null, env, scope, label); for (var i = 0; i < params.length; i++) { helperStream.addDependency(params[i]); } for (var key in hash) { helperStream.addDependency(hash[key]); } return helperStream; } function labelForSubexpr(params, hash, helperName) { var paramsLabels = labelsForParams(params); var hashLabels = labelsForHash(hash); var label = '(' + helperName; if (paramsLabels) { label += ' ' + paramsLabels; } if (hashLabels) { label += ' ' + hashLabels; } return label + ')'; } function labelsForParams(params) { return _emberHtmlbarsStreamsUtils.labelsFor(params).join(' '); } function labelsForHash(hash) { var out = []; for (var prop in hash) { out.push(prop + '=' + _emberHtmlbarsStreamsUtils.labelFor(hash[prop])); } return out.join(' '); } }); enifed('ember-htmlbars/hooks/update-self', ['exports', 'ember-metal/debug', 'ember-metal/property_get'], function (exports, _emberMetalDebug, _emberMetalProperty_get) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = updateSelf; function updateSelf(env, scope, _self) { var self = _self; if (self && self.hasBoundController) { var _self2 = self; var controller = _self2.controller; self = self.self; scope.updateLocal('controller', controller || self); } _emberMetalDebug.assert('BUG: scope.attrs and self.isView should not both be true', !(scope.attrs && self.isView)); if (self && self.isView) { scope.updateLocal('view', self); scope.updateSelf(_emberMetalProperty_get.get(self, 'context'), ''); return; } scope.updateSelf(self); } }); enifed("ember-htmlbars/hooks/will-cleanup-tree", ["exports"], function (exports) { "use strict"; exports.default = willCleanupTree; function willCleanupTree(env) { var view = env.view; // When we go to clean up the render node and all of its children, we may // encounter views/components associated with those nodes along the way. In // those cases, we need to sever the link between the // existing view hierarchy and those views. // // However, we do *not* need to remove the child views of child views, since // severing the connection to their parent effectively severs them from the // view graph. // // For example, imagine the following view graph: // // A // / \ // B C // / \ // D E // // If we are cleaning up the node for view C, we need to remove that view // from A's child views. However, we do not need to remove D and E from C's // child views, since removing C transitively removes D and E as well. // // To accomplish this, we track the nearest view to this render node on the // owner view, the root-most view in the graph (A in the example above). If // we detect a view that is a direct child of that view, we remove it from // the `childViews` array. Other parent/child view relationships are // untouched. This view is then cleared once cleanup is complete in // `didCleanupTree`. view.ownerView._destroyingSubtreeForView = []; } }); enifed('ember-htmlbars/index', ['exports', 'ember-metal/core', 'ember-htmlbars/helpers', 'ember-htmlbars/helpers/if_unless', 'ember-htmlbars/helpers/with', 'ember-htmlbars/helpers/loc', 'ember-htmlbars/helpers/log', 'ember-htmlbars/helpers/each', 'ember-htmlbars/helpers/each-in', 'ember-htmlbars/helpers/-normalize-class', 'ember-htmlbars/helpers/concat', 'ember-htmlbars/helpers/-join-classes', 'ember-htmlbars/helpers/-html-safe', 'ember-htmlbars/helpers/hash', 'ember-htmlbars/helpers/query-params', 'ember-htmlbars/system/dom-helper', 'ember-htmlbars/system/template'], function (exports, _emberMetalCore, _emberHtmlbarsHelpers, _emberHtmlbarsHelpersIf_unless, _emberHtmlbarsHelpersWith, _emberHtmlbarsHelpersLoc, _emberHtmlbarsHelpersLog, _emberHtmlbarsHelpersEach, _emberHtmlbarsHelpersEachIn, _emberHtmlbarsHelpersNormalizeClass, _emberHtmlbarsHelpersConcat, _emberHtmlbarsHelpersJoinClasses, _emberHtmlbarsHelpersHtmlSafe, _emberHtmlbarsHelpersHash, _emberHtmlbarsHelpersQueryParams, _emberHtmlbarsSystemDomHelper, _emberHtmlbarsSystemTemplate) { /** Ember templates are executed by [HTMLBars](https://github.com/tildeio/htmlbars), an HTML-friendly version of [Handlebars](http://handlebarsjs.com/). Any valid Handlebars syntax is valid in an Ember template. ### Showing a property Templates manage the flow of an application's UI, and display state (through the DOM) to a user. For example, given a component with the property "name", that component's template can use the name in several ways: ```javascript // app/components/person.js export default Ember.Component.extend({ name: 'Jill' }); ``` ```handlebars {{! app/components/person.hbs }} {{name}} <div>{{name}}</div> <span data-name={{name}}></span> ``` Any time the "name" property on the component changes, the DOM will be updated. Properties can be chained as well: ```handlebars {{aUserModel.name}} <div>{{listOfUsers.firstObject.name}}</div> ``` ### Using Ember helpers When content is passed in mustaches `{{}}`, Ember will first try to find a helper or component with that name. For example, the `if` helper: ```handlebars {{if name "I have a name" "I have no name"}} <span data-has-name={{if name true}}></span> ``` The returned value is placed where the `{{}}` is called. The above style is called "inline". A second style of helper usage is called "block". For example: ```handlebars {{#if name}} I have a name {{else}} I have no name {{/if}} ``` The block form of helpers allows you to control how the UI is created based on the values of properties. A third form of helper is called "nested". For example here the concat helper will add " Doe" to a displayed name if the person has no last name: ```handlebars <span data-name={{concat firstName ( if lastName (concat " " lastName) "Doe" )}}></span> ``` Ember's built-in helpers are described under the [Ember.Templates.helpers](/api/classes/Ember.Templates.helpers.html) namespace. Documentation on creating custom helpers can be found under [Ember.Helper](/api/classes/Ember.Helper.html). ### Invoking a Component Ember components represent state to the UI of an application. Further reading on components can be found under [Ember.Component](/api/classes/Ember.Component.html). @module ember @submodule ember-templates @main ember-templates @public */ /** [HTMLBars](https://github.com/tildeio/htmlbars) is a [Handlebars](http://handlebarsjs.com/) compatible templating engine used by Ember.js. The classes and namespaces covered by this documentation attempt to focus on APIs for interacting with HTMLBars itself. For more general guidance on Ember.js templates and helpers, please see the [ember-templates](/api/modules/ember-templates.html) package. @module ember @submodule ember-htmlbars @main ember-htmlbars @public */ 'use strict'; exports.template = _emberHtmlbarsSystemTemplate.default; _emberHtmlbarsHelpers.registerHelper('if', _emberHtmlbarsHelpersIf_unless.ifHelper); _emberHtmlbarsHelpers.registerHelper('unless', _emberHtmlbarsHelpersIf_unless.unlessHelper); _emberHtmlbarsHelpers.registerHelper('with', _emberHtmlbarsHelpersWith.default); _emberHtmlbarsHelpers.registerHelper('loc', _emberHtmlbarsHelpersLoc.default); _emberHtmlbarsHelpers.registerHelper('log', _emberHtmlbarsHelpersLog.default); _emberHtmlbarsHelpers.registerHelper('each', _emberHtmlbarsHelpersEach.default); _emberHtmlbarsHelpers.registerHelper('each-in', _emberHtmlbarsHelpersEachIn.default); _emberHtmlbarsHelpers.registerHelper('-normalize-class', _emberHtmlbarsHelpersNormalizeClass.default); _emberHtmlbarsHelpers.registerHelper('concat', _emberHtmlbarsHelpersConcat.default); _emberHtmlbarsHelpers.registerHelper('-join-classes', _emberHtmlbarsHelpersJoinClasses.default); _emberHtmlbarsHelpers.registerHelper('-html-safe', _emberHtmlbarsHelpersHtmlSafe.default); _emberHtmlbarsHelpers.registerHelper('hash', _emberHtmlbarsHelpersHash.default); _emberHtmlbarsHelpers.registerHelper('query-params', _emberHtmlbarsHelpersQueryParams.default); _emberMetalCore.default.HTMLBars = { DOMHelper: _emberHtmlbarsSystemDomHelper.default }; }); // exposing Ember.HTMLBars enifed('ember-htmlbars/keywords', ['exports', 'htmlbars-runtime'], function (exports, _htmlbarsRuntime) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.registerKeyword = registerKeyword; /** @private @property helpers */ var keywords = Object.create(_htmlbarsRuntime.hooks.keywords); /** @module ember @submodule ember-htmlbars */ /** @private @method _registerHelper @for Ember.HTMLBars @param {String} name @param {Object|Function} keyword The keyword to add. */ function registerKeyword(name, keyword) { keywords[name] = keyword; } exports.default = keywords; }); enifed('ember-htmlbars/keywords/action', ['exports', 'htmlbars-runtime/hooks', 'ember-htmlbars/keywords/closure-action'], function (exports, _htmlbarsRuntimeHooks, _emberHtmlbarsKeywordsClosureAction) { /** @module ember @submodule ember-templates */ 'use strict'; /** The `{{action}}` helper provides a way to pass triggers for behavior (usually just a function) between components, and into components from controllers. ### Passing functions with the action helper There are three contexts an action helper can be used in. The first two contexts to discuss are attribute context, and Handlebars value context. ```handlebars {{! An example of attribute context }} <div onclick={{action "save"}}></div> {{! Examples of Handlebars value context }} {{input on-input=(action "save")}} {{yield (action "refreshData") andAnotherParam}} ``` In these contexts, the helper is called a "closure action" helper. Its behavior is simple: If passed a function name, read that function off the `actions` property of the current context. Once that function is read (or if a function was passed), create a closure over that function and any arguments. The resulting value of an action helper used this way is simply a function. For example, in the attribute context: ```handlebars {{! An example of attribute context }} <div onclick={{action "save"}}></div> ``` The resulting template render logic would be: ```js var div = document.createElement('div'); var actionFunction = (function(context){ return function() { return context.actions.save.apply(context, arguments); }; })(context); div.onclick = actionFunction; ``` Thus when the div is clicked, the action on that context is called. Because the `actionFunction` is just a function, closure actions can be passed between components and still execute in the correct context. Here is an example action handler on a component: ```js export default Ember.Component.extend({ actions: { save() { this.get('model').save(); } } }); ``` Actions are always looked up on the `actions` property of the current context. This avoids collisions in the naming of common actions, such as `destroy`. Two options can be passed to the `action` helper when it is used in this way. * `target=someProperty` will look to `someProperty` instead of the current context for the `actions` hash. This can be useful when targetting a service for actions. * `value="target.value"` will read the path `target.value` off the first argument to the action when it is called and rewrite the first argument to be that value. This is useful when attaching actions to event listeners. ### Invoking an action Closure actions curry both their scope and any arguments. When invoked, any additional arguments are added to the already curried list. Actions should be invoked using the [sendAction](/api/classes/Ember.Component.html#method_sendAction) method. The first argument to `sendAction` is the action to be called, and additional arguments are passed to the action function. This has interesting properties combined with currying of arguments. For example: ```js export default Ember.Component.extend({ actions: { // Usage {{input on-input=(action (action 'setName' model) value="target.value")}} setName(model, name) { model.set('name', name); } } }); ``` The first argument (`model`) was curried over, and the run-time argument (`event`) becomes a second argument. Action calls can be nested this way because each simply returns a function. Any function can be passed to the `{{action}}` helper, including other actions. Actions invoked with `sendAction` have the same currying behavior as demonstrated with `on-input` above. For example: ```js export default Ember.Component.extend({ actions: { setName(model, name) { model.set('name', name); } } }); ``` ```handlebars {{my-input submit=(action 'setName' model)}} ``` ```js // app/components/my-component.js export default Ember.Component.extend({ click() { // Note that model is not passed, it was curried in the template this.sendAction('submit', 'bob'); } }); ``` ### Attaching actions to DOM elements The third context of the `{{action}}` helper can be called "element space". For example: ```handlebars {{! An example of element space }} <div {{action "save"}}></div> ``` Used this way, the `{{action}}` helper provides a useful shortcut for registering an HTML element in a template for a single DOM event and forwarding that interaction to the template's context (controller or component). If the context of a template is a controller, actions used this way will bubble to routes when the controller does not implement the specified action. Once an action hits a route, it will bubble through the route hierarchy. ### Event Propagation `{{action}}` helpers called in element space can control event bubbling. Note that the closure style actions cannot. Events triggered through the action helper will automatically have `.preventDefault()` called on them. You do not need to do so in your event handlers. If you need to allow event propagation (to handle file inputs for example) you can supply the `preventDefault=false` option to the `{{action}}` helper: ```handlebars <div {{action "sayHello" preventDefault=false}}> <input type="file" /> <input type="checkbox" /> </div> ``` To disable bubbling, pass `bubbles=false` to the helper: ```handlebars <button {{action 'edit' post bubbles=false}}>Edit</button> ``` To disable bubbling with closure style actions you must create your own wrapper helper that makes use of `event.stopPropagation()`: ```handlebars <div onclick={{disable-bubbling (action "sayHello")}}>Hello</div> ``` ```js // app/helpers/disable-bubbling.js import Ember from 'ember'; export function disableBubbling([action]) { return function(event) { event.stopPropagation(); return action(event); }; } export default Ember.Helper.helper(disableBubbling); ``` If you need the default handler to trigger you should either register your own event handler, or use event methods on your view class. See ["Responding to Browser Events"](/api/classes/Ember.View.html#toc_responding-to-browser-events) in the documentation for Ember.View for more information. ### Specifying DOM event type `{{action}}` helpers called in element space can specify an event type. By default the `{{action}}` helper registers for DOM `click` events. You can supply an `on` option to the helper to specify a different DOM event name: ```handlebars <div {{action "anActionName" on="doubleClick"}}> click me </div> ``` See ["Event Names"](/api/classes/Ember.View.html#toc_event-names) for a list of acceptable DOM event names. ### Specifying whitelisted modifier keys `{{action}}` helpers called in element space can specify modifier keys. By default the `{{action}}` helper will ignore click events with pressed modifier keys. You can supply an `allowedKeys` option to specify which keys should not be ignored. ```handlebars <div {{action "anActionName" allowedKeys="alt"}}> click me </div> ``` This way the action will fire when clicking with the alt key pressed down. Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys. ```handlebars <div {{action "anActionName" allowedKeys="any"}}> click me with any key pressed </div> ``` ### Specifying a Target A `target` option can be provided to the helper to change which object will receive the method call. This option must be a path to an object, accessible in the current context: ```handlebars {{! app/templates/application.hbs }} <div {{action "anActionName" target=someService}}> click me </div> ``` ```javascript // app/controllers/application.js export default Ember.Controller.extend({ someService: Ember.inject.service() }); ``` @method action @for Ember.Templates.helpers @public */ exports.default = function (morph, env, scope, params, hash, template, inverse, visitor) { if (morph) { _htmlbarsRuntimeHooks.keyword('@element_action', morph, env, scope, params, hash, template, inverse, visitor); return true; } return _emberHtmlbarsKeywordsClosureAction.default(morph, env, scope, params, hash, template, inverse, visitor); }; }); enifed('ember-htmlbars/keywords/closure-action', ['exports', 'ember-htmlbars/streams/stream', 'ember-htmlbars/streams/utils', 'ember-metal/symbol', 'ember-metal/property_get', 'ember-htmlbars/hooks/subexpr', 'ember-metal/error', 'ember-metal/run_loop', 'ember-metal/instrumentation', 'ember-metal/is_none'], function (exports, _emberHtmlbarsStreamsStream, _emberHtmlbarsStreamsUtils, _emberMetalSymbol, _emberMetalProperty_get, _emberHtmlbarsHooksSubexpr, _emberMetalError, _emberMetalRun_loop, _emberMetalInstrumentation, _emberMetalIs_none) { 'use strict'; exports.default = closureAction; var INVOKE = _emberMetalSymbol.default('INVOKE'); exports.INVOKE = INVOKE; var ACTION = _emberMetalSymbol.default('ACTION'); exports.ACTION = ACTION; function closureAction(morph, env, scope, params, hash, template, inverse, visitor) { var _this = this; var s = new _emberHtmlbarsStreamsStream.Stream(function () { var rawAction = params[0]; var actionArguments = _emberHtmlbarsStreamsUtils.readArray(params.slice(1, params.length)); var target = undefined, action = undefined, valuePath = undefined; if (_emberMetalIs_none.default(rawAction)) { var label = _emberHtmlbarsHooksSubexpr.labelForSubexpr(params, hash, 'action'); throw new _emberMetalError.default('Action passed is null or undefined in ' + label + ' from ' + _emberHtmlbarsStreamsUtils.read(scope.getSelf()) + '.'); } else if (rawAction[INVOKE]) { // on-change={{action (mut name)}} target = rawAction; action = rawAction[INVOKE]; } else { // on-change={{action setName}} // element-space actions look to "controller" then target. Here we only // look to "target". target = _emberHtmlbarsStreamsUtils.read(scope.getSelf()); action = _emberHtmlbarsStreamsUtils.read(rawAction); var actionType = typeof action; if (actionType === 'string') { var actionName = action; action = null; // on-change={{action 'setName'}} if (hash.target) { // on-change={{action 'setName' target=alternativeComponent}} target = _emberHtmlbarsStreamsUtils.read(hash.target); } if (target.actions) { action = target.actions[actionName]; } if (!action) { throw new _emberMetalError.default('An action named \'' + actionName + '\' was not found in ' + target + '.'); } } else if (action && typeof action[INVOKE] === 'function') { target = action; action = action[INVOKE]; } else if (actionType !== 'function') { throw new _emberMetalError.default('An action could not be made for `' + rawAction.label + '` in ' + target + '. Please confirm that you are using either a quoted action name (i.e. `(action \'' + rawAction.label + '\')`) or a function available in ' + target + '.'); } } if (hash.value) { // <button on-keypress={{action (mut name) value="which"}} // on-keypress is not even an Ember feature yet valuePath = _emberHtmlbarsStreamsUtils.read(hash.value); } return createClosureAction(_this, target, action, valuePath, actionArguments); }, function () { return _emberHtmlbarsHooksSubexpr.labelForSubexpr(params, hash, 'action'); }); params.forEach(s.addDependency, s); Object.keys(hash).forEach(function (item) { return s.addDependency(item); }); return s; } function createClosureAction(stream, target, action, valuePath, actionArguments) { var closureAction = undefined; if (actionArguments.length > 0) { closureAction = function () { var args = actionArguments; for (var _len = arguments.length, passedArguments = Array(_len), _key = 0; _key < _len; _key++) { passedArguments[_key] = arguments[_key]; } if (passedArguments.length > 0) { args = actionArguments.concat(passedArguments); } if (valuePath && args.length > 0) { args[0] = _emberMetalProperty_get.get(args[0], valuePath); } var payload = { target: target, args: args, label: _emberHtmlbarsStreamsUtils.labelFor(stream) }; return _emberMetalInstrumentation.flaggedInstrument('interaction.ember-action', payload, function () { return _emberMetalRun_loop.default.join.apply(_emberMetalRun_loop.default, [target, action].concat(args)); }); }; } else { closureAction = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } if (valuePath && args.length > 0) { args[0] = _emberMetalProperty_get.get(args[0], valuePath); } var payload = { target: target, args: args, label: _emberHtmlbarsStreamsUtils.labelFor(stream) }; return _emberMetalInstrumentation.flaggedInstrument('interaction.ember-action', payload, function () { return _emberMetalRun_loop.default.join.apply(_emberMetalRun_loop.default, [target, action].concat(args)); }); }; } closureAction[ACTION] = true; return closureAction; } }); enifed('ember-htmlbars/keywords/closure-component', ['exports', 'ember-metal/debug', 'ember-metal/is_empty', 'ember-metal/is_none', 'ember-metal/symbol', 'ember-htmlbars/streams/stream', 'ember-metal/empty_object', 'ember-htmlbars/streams/utils', 'ember-htmlbars/hooks/subexpr', 'ember-metal/assign', 'ember-htmlbars/utils/extract-positional-params', 'ember-views/utils/lookup-component'], function (exports, _emberMetalDebug, _emberMetalIs_empty, _emberMetalIs_none, _emberMetalSymbol, _emberHtmlbarsStreamsStream, _emberMetalEmpty_object, _emberHtmlbarsStreamsUtils, _emberHtmlbarsHooksSubexpr, _emberMetalAssign, _emberHtmlbarsUtilsExtractPositionalParams, _emberViewsUtilsLookupComponent) { /** @module ember @submodule ember-templates */ 'use strict'; exports.default = closureComponent; exports.isComponentCell = isComponentCell; exports.processPositionalParamsFromCell = processPositionalParamsFromCell; exports.mergeInNewHash = mergeInNewHash; var COMPONENT_REFERENCE = _emberMetalSymbol.default('COMPONENT_REFERENCE'); exports.COMPONENT_REFERENCE = COMPONENT_REFERENCE; var COMPONENT_CELL = _emberMetalSymbol.default('COMPONENT_CELL'); exports.COMPONENT_CELL = COMPONENT_CELL; var COMPONENT_PATH = _emberMetalSymbol.default('COMPONENT_PATH'); exports.COMPONENT_PATH = COMPONENT_PATH; var COMPONENT_POSITIONAL_PARAMS = _emberMetalSymbol.default('COMPONENT_POSITIONAL_PARAMS'); exports.COMPONENT_POSITIONAL_PARAMS = COMPONENT_POSITIONAL_PARAMS; var COMPONENT_HASH = _emberMetalSymbol.default('COMPONENT_HASH'); exports.COMPONENT_HASH = COMPONENT_HASH; var ClosureComponentStream = _emberHtmlbarsStreamsStream.default.extend({ init: function (env, path, params, hash) { this._env = env; this._path = path; this._params = params; this._hash = hash; this.label = _emberHtmlbarsHooksSubexpr.labelForSubexpr([path].concat(params), hash, 'component'); this[COMPONENT_REFERENCE] = true; }, compute: function () { return createClosureComponentCell(this._env, this._path, this._params, this._hash, this.label); } }); function closureComponent(env, _ref3, hash) { var path = _ref3[0]; var params = _ref3.slice(1); var s = new ClosureComponentStream(env, path, params, hash); s.addDependency(path); // FIXME: If the stream invalidates on every params or hash change, then // the {{component helper will be forced to re-render the whole component // each time. Instead, these dependencies should not be required and the // element component keyword should add the params and hash as dependencies. params.forEach(function (item) { return s.addDependency(item); }); Object.keys(hash).forEach(function (key) { return s.addDependency(hash[key]); }); return s; } function createClosureComponentCell(env, originalComponentPath, params, hash, label) { var componentPath = _emberHtmlbarsStreamsUtils.read(originalComponentPath); _emberMetalDebug.assert('Component path cannot be null in ' + label, !_emberMetalIs_none.default(componentPath)); var newHash = _emberMetalAssign.default(new _emberMetalEmpty_object.default(), hash); if (isComponentCell(componentPath)) { return createNestedClosureComponentCell(componentPath, params, newHash); } else { _emberMetalDebug.assert('The component helper cannot be used without a valid component name. You used "' + componentPath + '" via ' + label, isValidComponentPath(env, componentPath)); return createNewClosureComponentCell(env, componentPath, params, newHash); } } function isValidComponentPath(env, path) { var result = _emberViewsUtilsLookupComponent.default(env.owner, path); return !!(result.component || result.layout); } function isComponentCell(component) { return component && component[COMPONENT_CELL]; } function createNestedClosureComponentCell(componentCell, params, hash) { var _ref; // This needs to be done in each nesting level to avoid raising assertions. processPositionalParamsFromCell(componentCell, params, hash); return _ref = {}, _ref[COMPONENT_PATH] = componentCell[COMPONENT_PATH], _ref[COMPONENT_HASH] = mergeInNewHash(componentCell[COMPONENT_HASH], hash, componentCell[COMPONENT_POSITIONAL_PARAMS], params), _ref[COMPONENT_POSITIONAL_PARAMS] = componentCell[COMPONENT_POSITIONAL_PARAMS], _ref[COMPONENT_CELL] = true, _ref; } function processPositionalParamsFromCell(componentCell, params, hash) { var positionalParams = componentCell[COMPONENT_POSITIONAL_PARAMS]; _emberHtmlbarsUtilsExtractPositionalParams.processPositionalParams(null, positionalParams, params, hash); } function createNewClosureComponentCell(env, componentPath, params, hash) { var _ref2; var positionalParams = getPositionalParams(env.owner, componentPath); // This needs to be done in each nesting level to avoid raising assertions. _emberHtmlbarsUtilsExtractPositionalParams.processPositionalParams(null, positionalParams, params, hash); return _ref2 = {}, _ref2[COMPONENT_PATH] = componentPath, _ref2[COMPONENT_HASH] = hash, _ref2[COMPONENT_POSITIONAL_PARAMS] = positionalParams, _ref2[COMPONENT_CELL] = true, _ref2; } /* Returns the positional parameters for component `componentPath`. If it has no positional parameters, it returns the empty array. */ function getPositionalParams(container, componentPath) { if (!componentPath) { return []; } var result = _emberViewsUtilsLookupComponent.default(container, componentPath); var component = result.component; if (component && component.positionalParams) { return component.positionalParams; } else { return []; } } /* * This function merges two hashes in a new one. * Furthermore this function deals with the issue expressed in #13742. * * ```hbs * {{component (component 'link-to' 'index')}} * ``` * * results in the following error * * > You must provide one or more parameters to the link-to component. * * This is so because a naive merging would not take into account that the * invocation (the external `{{component}}`) would result in the following * attributes (before merging with the ones in the contextual component): * * ```js * let attrs = { params: [] }; * ``` * * Given that the contextual component has the following attributes: * * ```js * let attrs = { params: ['index'] }; * ``` * * Merging them would result in: * * ```js * let attrs = { params: [] }; * ``` * * Therefore, if there are no positional parameters and `positionalParams` is * a string (rest positional parameters), we keep the parameters from the * `original` hash. * */ function mergeInNewHash(original, updates) { var positionalParams = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; var params = arguments.length <= 3 || arguments[3] === undefined ? [] : arguments[3]; var newHash = _emberMetalAssign.default({}, original, updates); if (_emberHtmlbarsUtilsExtractPositionalParams.isRestPositionalParams(positionalParams) && _emberMetalIs_empty.default(params)) { var propName = positionalParams; newHash[propName] = original[propName]; } return newHash; } }); enifed('ember-htmlbars/keywords/component', ['exports', 'htmlbars-runtime/hooks', 'ember-htmlbars/keywords/closure-component', 'ember-metal/empty_object', 'ember-metal/assign'], function (exports, _htmlbarsRuntimeHooks, _emberHtmlbarsKeywordsClosureComponent, _emberMetalEmpty_object, _emberMetalAssign) { /** @module ember @submodule ember-templates @public */ 'use strict'; /** The `{{component}}` helper lets you add instances of `Ember.Component` to a template. See [Ember.Component](/api/classes/Ember.Component.html) for additional information on how a `Component` functions. `{{component}}`'s primary use is for cases where you want to dynamically change which type of component is rendered as the state of your application changes. The provided block will be applied as the template for the component. Given an empty `<body>` the following template: ```handlebars {{! application.hbs }} {{component infographicComponentName}} ``` And the following application code: ```javascript export default Ember.Controller.extend({ infographicComponentName: computed('isMarketOpen', { get() { if (this.get('isMarketOpen')) { return 'live-updating-chart'; } else { return 'market-close-summary'; } } }) }); ``` The `live-updating-chart` component will be appended when `isMarketOpen` is `true`, and the `market-close-summary` component will be appended when `isMarketOpen` is `false`. If the value changes while the app is running, the component will be automatically swapped out accordingly. Note: You should not use this helper when you are consistently rendering the same component. In that case, use standard component syntax, for example: ```handlebars {{! application.hbs }} {{live-updating-chart}} ``` ## Nested Usage The `component` helper can be used to package a component path with initial attrs. The included attrs can then be merged during the final invocation. For example, given a `person-form` component with the following template: ```handlebars {{yield (hash nameInput=(component "my-input-component" value=model.name placeholder="First Name"))}} ``` The following snippet: ``` {{#person-form as |form|}} {{component form.nameInput placeholder="Username"}} {{/person-form}} ``` would output an input whose value is already bound to `model.name` and `placeholder` is "Username". @method component @since 1.11.0 @for Ember.Templates.helpers @public */ exports.default = function (morph, env, scope, params, hash, template, inverse, visitor) { if (!morph) { return _emberHtmlbarsKeywordsClosureComponent.default(env, params, hash); } var newHash = _emberMetalAssign.default(new _emberMetalEmpty_object.default(), hash); _htmlbarsRuntimeHooks.keyword('@element_component', morph, env, scope, params, newHash, template, inverse, visitor); return true; }; }); enifed('ember-htmlbars/keywords/debugger', ['exports', 'ember-metal/debug'], function (exports, _emberMetalDebug) { /*jshint debug:true*/ /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = debuggerKeyword; /** Execute the `debugger` statement in the current template's context. ```handlebars {{debugger}} ``` When using the debugger helper you will have access to a `get` function. This function retrieves values available in the context of the template. For example, if you're wondering why a value `{{foo}}` isn't rendering as expected within a template, you could place a `{{debugger}}` statement and, when the `debugger;` breakpoint is hit, you can attempt to retrieve this value: ``` > get('foo') ``` `get` is also aware of keywords. So in this situation ```handlebars {{#each items as |item|}} {{debugger}} {{/each}} ``` You'll be able to get values from the current item: ``` > get('item.name') ``` You can also access the context of the view to make sure it is the object that you expect: ``` > context ``` @method debugger @for Ember.Templates.helpers @public */ function debuggerKeyword(morph, env, scope) { /* jshint unused: false, debug: true */ var view = env.hooks.getValue(scope.getLocal('view')); var context = env.hooks.getValue(scope.getSelf()); function get(path) { return env.hooks.getValue(env.hooks.get(env, scope, path)); } _emberMetalDebug.info('Use `view`, `context`, and `get(<path>)` to debug this template.'); debugger; return true; } }); enifed('ember-htmlbars/keywords/element-action', ['exports', 'ember-metal/debug', 'ember-metal/utils', 'ember-htmlbars/streams/utils', 'ember-metal/run_loop', 'ember-views/system/utils', 'ember-views/system/action_manager', 'ember-metal/instrumentation'], function (exports, _emberMetalDebug, _emberMetalUtils, _emberHtmlbarsStreamsUtils, _emberMetalRun_loop, _emberViewsSystemUtils, _emberViewsSystemAction_manager, _emberMetalInstrumentation) { 'use strict'; exports.default = { setupState: function (state, env, scope, params, hash) { var getStream = env.hooks.get; var read = env.hooks.getValue; var actionName = read(params[0]); _emberMetalDebug.assert('You specified a quoteless path to the {{action}} helper ' + 'which did not resolve to an action name (a string). ' + 'Perhaps you meant to use a quoted actionName? (e.g. {{action \'save\'}}).', typeof actionName === 'string' || typeof actionName === 'function'); var actionArgs = []; for (var i = 1; i < params.length; i++) { actionArgs.push(_emberHtmlbarsStreamsUtils.readUnwrappedModel(params[i])); } var target = undefined; if (hash.target) { if (typeof hash.target === 'string') { target = read(getStream(env, scope, hash.target)); } else { target = read(hash.target); } } else { target = read(scope.getLocal('controller')) || read(scope.getSelf()); } return { actionName: actionName, actionArgs: actionArgs, target: target }; }, isStable: function (state, env, scope, params, hash) { return true; }, render: function (node, env, scope, params, hash, template, inverse, visitor) { var actionId = env.dom.getAttribute(node.element, 'data-ember-action') || _emberMetalUtils.uuid(); ActionHelper.registerAction({ actionId: actionId, node: node, eventName: hash.on || 'click', bubbles: hash.bubbles, preventDefault: hash.preventDefault, withKeyCode: hash.withKeyCode, allowedKeys: hash.allowedKeys }); node.cleanup = function () { return ActionHelper.unregisterAction(actionId); }; env.dom.setAttribute(node.element, 'data-ember-action', actionId); } }; var ActionHelper = {}; exports.ActionHelper = ActionHelper; // registeredActions is re-exported for compatibility with older plugins // that were using this undocumented API. ActionHelper.registeredActions = _emberViewsSystemAction_manager.default.registeredActions; ActionHelper.registerAction = function (_ref) { var actionId = _ref.actionId; var node = _ref.node; var eventName = _ref.eventName; var preventDefault = _ref.preventDefault; var bubbles = _ref.bubbles; var allowedKeys = _ref.allowedKeys; var actions = _emberViewsSystemAction_manager.default.registeredActions[actionId]; if (!actions) { actions = _emberViewsSystemAction_manager.default.registeredActions[actionId] = []; } actions.push({ eventName: eventName, handler: function (event) { if (!isAllowedEvent(event, _emberHtmlbarsStreamsUtils.read(allowedKeys))) { return true; } if (_emberHtmlbarsStreamsUtils.read(preventDefault) !== false) { event.preventDefault(); } if (_emberHtmlbarsStreamsUtils.read(bubbles) === false) { event.stopPropagation(); } var _node$getState = node.getState(); var target = _node$getState.target; var actionName = _node$getState.actionName; var actionArgs = _node$getState.actionArgs; _emberMetalRun_loop.default(function runRegisteredAction() { var payload = { target: target, args: actionArgs }; if (typeof actionName === 'function') { _emberMetalInstrumentation.flaggedInstrument('interaction.ember-action', payload, function () { actionName.apply(target, actionArgs); }); return; } payload.name = actionName; if (target.send) { _emberMetalInstrumentation.flaggedInstrument('interaction.ember-action', payload, function () { target.send.apply(target, [actionName].concat(actionArgs)); }); } else { _emberMetalDebug.assert('The action \'' + actionName + '\' did not exist on ' + target, typeof target[actionName] === 'function'); _emberMetalInstrumentation.flaggedInstrument('interaction.ember-action', payload, function () { target[actionName].apply(target, actionArgs); }); } }); } }); return actionId; }; ActionHelper.unregisterAction = function (actionId) { return delete _emberViewsSystemAction_manager.default.registeredActions[actionId]; }; var MODIFIERS = ['alt', 'shift', 'meta', 'ctrl']; var POINTER_EVENT_TYPE_REGEX = /^click|mouse|touch/; function isAllowedEvent(event, allowedKeys) { if (typeof allowedKeys === 'undefined') { if (POINTER_EVENT_TYPE_REGEX.test(event.type)) { return _emberViewsSystemUtils.isSimpleClick(event); } else { allowedKeys = ''; } } if (allowedKeys.indexOf('any') >= 0) { return true; } for (var i = 0; i < MODIFIERS.length; i++) { if (event[MODIFIERS[i] + 'Key'] && allowedKeys.indexOf(MODIFIERS[i]) === -1) { return false; } } return true; } }); enifed('ember-htmlbars/keywords/element-component', ['exports', 'ember-metal/assign', 'ember-htmlbars/keywords/closure-component', 'ember-views/utils/lookup-component', 'ember-htmlbars/utils/extract-positional-params'], function (exports, _emberMetalAssign, _emberHtmlbarsKeywordsClosureComponent, _emberViewsUtilsLookupComponent, _emberHtmlbarsUtilsExtractPositionalParams) { 'use strict'; exports.default = { setupState: function (lastState, env, scope, params, hash) { var componentPath = getComponentPath(params[0], env); return _emberMetalAssign.default({}, lastState, { componentPath: componentPath, isComponentHelper: true }); }, render: function (morph) { var state = morph.getState(); if (state.manager) { state.manager.destroy(); } // Force the component hook to treat this as a first-time render, // because normal components (`<foo-bar>`) cannot change at runtime, // but the `{{component}}` helper can. state.manager = null; render.apply(undefined, arguments); }, rerender: render }; function getComponentPath(param, env) { var path = env.hooks.getValue(param); if (_emberHtmlbarsKeywordsClosureComponent.isComponentCell(path)) { path = path[_emberHtmlbarsKeywordsClosureComponent.COMPONENT_PATH]; } return path; } function render(morph, env, scope, _ref, hash, template, inverse, visitor) { var path = _ref[0]; var params = _ref.slice(1); var isRerender = arguments.length <= 8 || arguments[8] === undefined ? false : arguments[8]; var _morph$getState = morph.getState(); var componentPath = _morph$getState.componentPath; // If the value passed to the {{component}} helper is undefined or null, // don't create a new ComponentNode. if (componentPath === undefined || componentPath === null) { return; } path = env.hooks.getValue(path); if (isRerender) { var result = _emberViewsUtilsLookupComponent.default(env.owner, componentPath); var component = result.component; _emberHtmlbarsUtilsExtractPositionalParams.default(null, component, params, hash); } if (_emberHtmlbarsKeywordsClosureComponent.isComponentCell(path)) { var closureComponent = env.hooks.getValue(path); // This needs to be done in each nesting level to avoid raising assertions _emberHtmlbarsKeywordsClosureComponent.processPositionalParamsFromCell(closureComponent, params, hash); hash = _emberHtmlbarsKeywordsClosureComponent.mergeInNewHash(closureComponent[_emberHtmlbarsKeywordsClosureComponent.COMPONENT_HASH], hash, closureComponent[_emberHtmlbarsKeywordsClosureComponent.COMPONENT_POSITIONAL_PARAMS], params); params = []; } var templates = { default: template, inverse: inverse }; env.hooks.component(morph, env, scope, componentPath, params, hash, templates, visitor); } }); enifed('ember-htmlbars/keywords/get', ['exports', 'ember-metal/debug', 'ember-htmlbars/streams/stream', 'ember-htmlbars/streams/utils', 'ember-htmlbars/utils/subscribe', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/observer'], function (exports, _emberMetalDebug, _emberHtmlbarsStreamsStream, _emberHtmlbarsStreamsUtils, _emberHtmlbarsUtilsSubscribe, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalObserver) { /** @module ember @submodule ember-templates */ 'use strict'; exports.default = getKeyword; function labelFor(source, key) { var sourceLabel = source.label ? source.label : ''; var keyLabel = key.label ? key.label : ''; return '(get ' + sourceLabel + ' ' + keyLabel + ')'; } var DynamicKeyStream = _emberHtmlbarsStreamsStream.default.extend({ init: function (source, keySource) { // Used to get the original path for debugging purposes. var label = labelFor(source, keySource); this.label = label; this.path = label; this.sourceDep = this.addMutableDependency(source); this.keyDep = this.addMutableDependency(keySource); this.observedObject = null; this.observedKey = null; }, key: function () { var key = this.keyDep.getValue(); if (typeof key === 'string') { return key; } }, compute: function () { var object = this.sourceDep.getValue(); var key = this.key(); if (object && key) { return _emberMetalProperty_get.get(object, key); } }, setValue: function (value) { var object = this.sourceDep.getValue(); var key = this.key(); if (object) { _emberMetalProperty_set.set(object, key, value); } }, _super$revalidate: _emberHtmlbarsStreamsStream.default.prototype.revalidate, revalidate: function (value) { this._super$revalidate(value); var object = this.sourceDep.getValue(); var key = this.key(); if (object !== this.observedObject || key !== this.observedKey) { this._clearObservedObject(); if (object && typeof object === 'object' && key) { _emberMetalObserver.addObserver(object, key, this, this.notify); this.observedObject = object; this.observedKey = key; } } }, _clearObservedObject: function () { if (this.observedObject) { _emberMetalObserver.removeObserver(this.observedObject, this.observedKey, this, this.notify); this.observedObject = null; this.observedKey = null; } } }); function buildStream(params) { var objRef = params[0]; var pathRef = params[1]; _emberMetalDebug.assert('The first argument to {{get}} must be a stream', _emberHtmlbarsStreamsUtils.isStream(objRef)); _emberMetalDebug.assert('{{get}} requires at least two arguments', params.length > 1); var stream = buildDynamicKeyStream(objRef, pathRef); return stream; } function buildDynamicKeyStream(source, keySource) { if (!_emberHtmlbarsStreamsUtils.isStream(keySource)) { return source.get(keySource); } else { return new DynamicKeyStream(source, keySource); } } /** Dynamically look up a property on an object. The second argument to `{{get}}` should have a string value, although it can be bound. For example, these two usages are equivilent: ```handlebars {{person.height}} {{get person "height"}} ``` If there were several facts about a person, the `{{get}}` helper can dynamically pick one: ```handlebars {{get person factName}} ``` For a more complex example, this template would allow the user to switch between showing the user's height and weight with a click: ```handlebars {{get person factName}} <button {{action (mut factName) "height"}}>Show height</button> <button {{action (mut factName) "weight"}}>Show weight</button> ``` The `{{get}}` helper can also respect mutable values itself. For example: ```handlebars {{input value=(mut (get person factName)) type="text"}} <button {{action (mut factName) "height"}}>Show height</button> <button {{action (mut factName) "weight"}}>Show weight</button> ``` Would allow the user to swap what fact is being displayed, and also edit that fact via a two-way mutable binding. @public @method get @for Ember.Templates.helpers @since 2.1.0 */ function getKeyword(morph, env, scope, params, hash, template, inverse, visitor) { if (morph === null) { return buildStream(params); } else { var stream = undefined; if (morph.linkedResult) { stream = morph.linkedResult; } else { stream = buildStream(params); _emberHtmlbarsUtilsSubscribe.default(morph, env, scope, stream); env.hooks.linkRenderNode(morph, env, scope, null, params, hash); morph.linkedResult = stream; } env.hooks.range(morph, env, scope, null, stream, visitor); } return true; } }); enifed('ember-htmlbars/keywords/input', ['exports', 'ember-metal/debug', 'ember-metal/assign'], function (exports, _emberMetalDebug, _emberMetalAssign) { /** @module ember @submodule ember-templates */ 'use strict'; /** The `{{input}}` helper lets you create an HTML `<input />` component. It causes an `Ember.TextField` component to be rendered. For more info, see the [Ember.TextField](/api/classes/Ember.TextField.html) docs and the [templates guide](http://emberjs.com/guides/templates/input-helpers/). ```handlebars {{input value="987"}} ``` renders as: ```HTML <input type="text" value="987" /> ``` ### Text field If no `type` option is specified, a default of type 'text' is used. Many of the standard HTML attributes may be passed to this helper. <table> <tr><td>`readonly`</td><td>`required`</td><td>`autofocus`</td></tr> <tr><td>`value`</td><td>`placeholder`</td><td>`disabled`</td></tr> <tr><td>`size`</td><td>`tabindex`</td><td>`maxlength`</td></tr> <tr><td>`name`</td><td>`min`</td><td>`max`</td></tr> <tr><td>`pattern`</td><td>`accept`</td><td>`autocomplete`</td></tr> <tr><td>`autosave`</td><td>`formaction`</td><td>`formenctype`</td></tr> <tr><td>`formmethod`</td><td>`formnovalidate`</td><td>`formtarget`</td></tr> <tr><td>`height`</td><td>`inputmode`</td><td>`multiple`</td></tr> <tr><td>`step`</td><td>`width`</td><td>`form`</td></tr> <tr><td>`selectionDirection`</td><td>`spellcheck`</td><td> </td></tr> </table> When set to a quoted string, these values will be directly applied to the HTML element. When left unquoted, these values will be bound to a property on the template's current rendering context (most typically a controller instance). A very common use of this helper is to bind the `value` of an input to an Object's attribute: ```handlebars Search: {{input value=searchWord}} ``` In this example, the inital value in the `<input />` will be set to the value of `searchWord`. If the user changes the text, the value of `searchWord` will also be updated. ### Actions The helper can send multiple actions based on user events. The action property defines the action which is sent when the user presses the return key. ```handlebars {{input action="submit"}} ``` The helper allows some user events to send actions. * `enter` * `insert-newline` * `escape-press` * `focus-in` * `focus-out` * `key-press` * `key-up` For example, if you desire an action to be sent when the input is blurred, you only need to setup the action name to the event name property. ```handlebars {{input focus-out="alertMessage"}} ``` See more about [Text Support Actions](/api/classes/Ember.TextField.html) ### Extending `Ember.TextField` Internally, `{{input type="text"}}` creates an instance of `Ember.TextField`, passing arguments from the helper to `Ember.TextField`'s `create` method. You can extend the capabilities of text inputs in your applications by reopening this class. For example, if you are building a Bootstrap project where `data-*` attributes are used, you can add one to the `TextField`'s `attributeBindings` property: ```javascript Ember.TextField.reopen({ attributeBindings: ['data-error'] }); ``` Keep in mind when writing `Ember.TextField` subclasses that `Ember.TextField` itself extends `Ember.Component`. Expect isolated component semantics, not legacy 1.x view semantics (like `controller` being present). See more about [Ember components](/api/classes/Ember.Component.html) ### Checkbox Checkboxes are special forms of the `{{input}}` helper. To create a `<checkbox />`: ```handlebars Emberize Everything: {{input type="checkbox" name="isEmberized" checked=isEmberized}} ``` This will bind checked state of this checkbox to the value of `isEmberized` -- if either one changes, it will be reflected in the other. The following HTML attributes can be set via the helper: * `checked` * `disabled` * `tabindex` * `indeterminate` * `name` * `autofocus` * `form` ### Extending `Ember.Checkbox` Internally, `{{input type="checkbox"}}` creates an instance of `Ember.Checkbox`, passing arguments from the helper to `Ember.Checkbox`'s `create` method. You can extend the capablilties of checkbox inputs in your applications by reopening this class. For example, if you wanted to add a css class to all checkboxes in your application: ```javascript Ember.Checkbox.reopen({ classNames: ['my-app-checkbox'] }); ``` @method input @for Ember.Templates.helpers @param {Hash} options @public */ exports.default = { setupState: function (lastState, env, scope, params, hash) { var type = env.hooks.getValue(hash.type); var componentName = componentNameMap[type] || defaultComponentName; _emberMetalDebug.assert('{{input type=\'checkbox\'}} does not support setting `value=someBooleanValue`; ' + 'you must use `checked=someBooleanValue` instead.', !(type === 'checkbox' && hash.hasOwnProperty('value'))); return _emberMetalAssign.default({}, lastState, { componentName: componentName }); }, render: function (morph, env, scope, params, hash, template, inverse, visitor) { env.hooks.component(morph, env, scope, morph.getState().componentName, params, hash, { default: template, inverse: inverse }, visitor); }, rerender: function () { this.render.apply(this, arguments); } }; var defaultComponentName = '-text-field'; var componentNameMap = { 'checkbox': '-checkbox' }; }); enifed('ember-htmlbars/keywords/mount', ['exports', 'ember-htmlbars/node-managers/view-node-manager', 'ember-htmlbars/system/render-env', 'ember-metal/debug', 'container/owner', 'ember-htmlbars/keywords/outlet', 'ember-htmlbars/keywords/render'], function (exports, _emberHtmlbarsNodeManagersViewNodeManager, _emberHtmlbarsSystemRenderEnv, _emberMetalDebug, _containerOwner, _emberHtmlbarsKeywordsOutlet, _emberHtmlbarsKeywordsRender) { /** @module ember @submodule ember-templates */ 'use strict'; /** The `{{mount}}` helper lets you embed a routeless engine in a template. Mounting an engine will cause an instance to be booted and its `application` template to be rendered. For example, the following template mounts the `ember-chat` engine: ```handlebars {{! application.hbs }} {{mount "ember-chat"}} ``` Currently, the engine name is the only argument that can be passed to `{{mount}}`. @method mount @for Ember.Templates.helpers @category ember-application-engines @public */ exports.default = { setupState: function (prevState, env, scope, params /*, hash */) { var name = params[0]; _emberMetalDebug.assert('The first argument of {{mount}} must be an engine name, e.g. {{mount "chat-engine"}}.', params.length === 1); _emberMetalDebug.assert('The first argument of {{mount}} must be quoted, e.g. {{mount "chat-engine"}}.', typeof name === 'string'); _emberMetalDebug.assert('You used `{{mount \'' + name + '\'}}`, but the engine \'' + name + '\' can not be found.', env.owner.hasRegistration('engine:' + name)); var engineInstance = env.owner.buildChildEngineInstance(name); engineInstance.boot(); var state = { parentView: env.view, manager: prevState.manager, controller: lookupEngineController(engineInstance), childOutletState: _emberHtmlbarsKeywordsRender.childOutletState(name, env) }; _containerOwner.setOwner(state, engineInstance); return state; }, childEnv: function (state, env) { return buildEnvForEngine(_containerOwner.getOwner(state), env); }, isStable: function (lastState, nextState) { return isStable(lastState.childOutletState, nextState.childOutletState); }, isEmpty: function () /* state */{ return false; }, render: function (node, env, scope, params, hash, template, inverse, visitor) { var state = node.getState(); var engineInstance = _containerOwner.getOwner(state); var engineController = lookupEngineController(engineInstance); var engineTemplate = lookupEngineTemplate(engineInstance); var options = { layout: null, self: engineController }; var engineEnv = buildEnvForEngine(engineInstance, env); var nodeManager = _emberHtmlbarsNodeManagersViewNodeManager.default.create(node, engineEnv, hash, options, state.parentView, null, null, engineTemplate); state.manager = nodeManager; nodeManager.render(engineEnv, hash, visitor); } }; function isStable(a, b) { if (!a && !b) { return true; } if (!a || !b) { return false; } for (var outletName in a) { if (!_emberHtmlbarsKeywordsOutlet.isOutletStable(a[outletName], b[outletName])) { return false; } } return true; } function lookupEngineController(engineInstance) { return engineInstance.lookup('controller:application'); } function lookupEngineView(engineInstance, ownerView) { var engineView = engineInstance.lookup('view:toplevel'); if (engineView.ownerView !== ownerView) { engineView.ownerView = ownerView; } return engineView; } function lookupEngineTemplate(engineInstance) { var engineTemplate = engineInstance.lookup('template:application'); if (engineTemplate && engineTemplate.raw) { engineTemplate = engineTemplate.raw; } return engineTemplate; } function buildEnvForEngine(engineInstance, parentEnv) { var engineView = lookupEngineView(engineInstance, parentEnv.view.ownerView); var engineTemplate = lookupEngineTemplate(engineInstance); var engineEnv = _emberHtmlbarsSystemRenderEnv.default.build(engineView, engineTemplate.meta); return engineEnv; } }); enifed('ember-htmlbars/keywords/mut', ['exports', 'ember-metal/debug', 'ember-metal/symbol', 'ember-htmlbars/streams/proxy-stream', 'ember-htmlbars/streams/stream', 'ember-htmlbars/streams/utils', 'ember-views/compat/attrs-proxy', 'ember-htmlbars/keywords/closure-action'], function (exports, _emberMetalDebug, _emberMetalSymbol, _emberHtmlbarsStreamsProxyStream, _emberHtmlbarsStreamsStream, _emberHtmlbarsStreamsUtils, _emberViewsCompatAttrsProxy, _emberHtmlbarsKeywordsClosureAction) { /** @module ember @submodule ember-templates */ 'use strict'; var _ProxyStream$extend; exports.default = mut; exports.privateMut = privateMut; var MUTABLE_REFERENCE = _emberMetalSymbol.default('MUTABLE_REFERENCE'); exports.MUTABLE_REFERENCE = MUTABLE_REFERENCE; var MutStream = _emberHtmlbarsStreamsProxyStream.default.extend((_ProxyStream$extend = { init: function (stream) { this.label = '(mut ' + stream.label + ')'; this.path = stream.path; this.sourceDep = this.addMutableDependency(stream); this[MUTABLE_REFERENCE] = true; }, cell: function () { var source = this; var value = source.value(); if (value && value[_emberHtmlbarsKeywordsClosureAction.ACTION]) { return value; } var val = { value: value, update: function (val) { source.setValue(val); } }; val[_emberViewsCompatAttrsProxy.MUTABLE_CELL] = true; return val; } }, _ProxyStream$extend[_emberHtmlbarsKeywordsClosureAction.INVOKE] = function (val) { this.setValue(val); }, _ProxyStream$extend)); /** The `mut` helper lets you __clearly specify__ that a child `Component` can update the (mutable) value passed to it, which will __change the value of the parent component__. This is very helpful for passing mutable values to a `Component` of any size, but critical to understanding the logic of a large/complex `Component`. To specify that a parameter is mutable, when invoking the child `Component`: ```handlebars {{my-child childClickCount=(mut totalClicks)}} ``` The child `Component` can then modify the parent's value as needed: ```javascript // my-child.js export default Component.extend({ click() { this.get('childClickCount').update(this.get('childClickCount').value + 1); } }); ``` Additionally, the `mut` helper can be combined with the `action` helper to mutate a value. For example: ```handlebars {{my-child childClickCount=totalClicks click-count-change=(action (mut totalClicks))}} ``` The child `Component` would invoke the action with the new click value: ```javascript // my-child.js export default Component.extend({ click() { this.get('clickCountChange')(this.get('childClickCount') + 1); } }); ``` The `mut` helper changes the `totalClicks` value to what was provided as the action argument. See a [2.0 blog post](http://emberjs.com/blog/2015/05/10/run-up-to-two-oh.html#toc_the-code-mut-code-helper) for additional information on using `{{mut}}`. @method mut @param {Object} [attr] the "two-way" attribute that can be modified. @for Ember.Templates.helpers @public */ function mut(morph, env, scope, originalParams, hash, template, inverse) { // If `morph` is `null` the keyword is being invoked as a subexpression. if (morph === null) { var valueStream = originalParams[0]; return mutParam(env.hooks.getValue, valueStream); } return true; } function privateMut(morph, env, scope, originalParams, hash, template, inverse) { // If `morph` is `null` the keyword is being invoked as a subexpression. if (morph === null) { var valueStream = originalParams[0]; return mutParam(env.hooks.getValue, valueStream, true); } return true; } var LiteralStream = _emberHtmlbarsStreamsStream.default.extend({ init: function (literal) { this.literal = literal; this.label = '(literal ' + literal + ')'; }, compute: function () { return this.literal; }, setValue: function (val) { this.literal = val; this.notify(); } }); function mutParam(read, stream, internal) { if (internal) { if (!_emberHtmlbarsStreamsUtils.isStream(stream)) { var literal = stream; stream = new LiteralStream(literal); } } else { _emberMetalDebug.assert('You can only pass a path to mut', _emberHtmlbarsStreamsUtils.isStream(stream)); } if (stream[MUTABLE_REFERENCE]) { return stream; } return new MutStream(stream); } }); enifed('ember-htmlbars/keywords/outlet', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-htmlbars/node-managers/view-node-manager', 'ember-htmlbars/templates/top-level-view', 'ember-metal/features', 'ember/version'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberHtmlbarsNodeManagersViewNodeManager, _emberHtmlbarsTemplatesTopLevelView, _emberMetalFeatures, _emberVersion) { /** @module ember @submodule ember-templates */ 'use strict'; exports.isOutletStable = isOutletStable; if (!false) { _emberHtmlbarsTemplatesTopLevelView.default.meta.revision = 'Ember@' + _emberVersion.default; } /** The `{{outlet}}` helper lets you specify where a child route will render in your template. An important use of the `{{outlet}}` helper is in your application's `application.hbs` file: ```handlebars {{! app/templates/application.hbs }} <!-- header content goes here, and will always display --> {{my-header}} <div class="my-dynamic-content"> <!-- this content will change based on the current route, which depends on the current URL --> {{outlet}} </div> <!-- footer content goes here, and will always display --> {{my-footer}} ``` See [templates guide](http://emberjs.com/guides/templates/the-application-template/) for additional information on using `{{outlet}}` in `application.hbs`. You may also specify a name for the `{{outlet}}`, which is useful when using more than one `{{outlet}}` in a template: ```handlebars {{outlet "menu"}} {{outlet "sidebar"}} {{outlet "main"}} ``` Your routes can then render into a specific one of these `outlet`s by specifying the `outlet` attribute in your `renderTemplate` function: ```javascript // app/routes/menu.js export default Ember.Route.extend({ renderTemplate() { this.render({ outlet: 'menu' }); } }); ``` See the [routing guide](http://emberjs.com/guides/routing/rendering-a-template/) for more information on how your `route` interacts with the `{{outlet}}` helper. Note: Your content __will not render__ if there isn't an `{{outlet}}` for it. @method outlet @param {String} [name] @for Ember.Templates.helpers @public */ exports.default = { willRender: function (renderNode, env) { env.view.ownerView._outlets.push(renderNode); }, setupState: function (state, env, scope, params, hash) { var outletState = env.outletState; var read = env.hooks.getValue; var outletName = read(params[0]) || 'main'; var selectedOutletState = outletState[outletName]; return { outletState: selectedOutletState, hasParentOutlet: env.hasParentOutlet, manager: state.manager }; }, childEnv: function (state, env) { var outletState = state.outletState; var toRender = outletState && outletState.render; var meta = toRender && toRender.template && toRender.template.meta; var childEnv = env.childWithOutletState(outletState && outletState.outlets, true, meta); if (true) { var owner = outletState && outletState.render && outletState.render.owner; if (owner && owner !== childEnv.owner) { childEnv.originalOwner = childEnv.owner; childEnv.owner = owner; } } return childEnv; }, isStable: function (lastState, nextState) { return isOutletStable(lastState.outletState, nextState.outletState); }, isEmpty: function (state) { return isOutletEmpty(state.outletState); }, render: function (renderNode, env, scope, params, hash, _template, inverse, visitor) { var state = renderNode.getState(); var owner = env.owner; var parentView = env.view; var outletState = state.outletState; var toRender = outletState.render; var namespace = owner.lookup('application:main'); var LOG_VIEW_LOOKUPS = _emberMetalProperty_get.get(namespace, 'LOG_VIEW_LOOKUPS'); var ViewClass = outletState.render.ViewClass; if (true) { owner = env.originalOwner || owner; } if (!state.hasParentOutlet && !ViewClass) { ViewClass = owner._lookupFactory('view:toplevel'); } var attrs = {}; var options = { component: ViewClass, self: toRender.controller, createOptions: { controller: toRender.controller } }; var template = _template || toRender.template && toRender.template.raw; if (LOG_VIEW_LOOKUPS && ViewClass) { _emberMetalDebug.info('Rendering ' + toRender.name + ' with ' + ViewClass, { fullName: 'view:' + toRender.name }); } if (state.manager) { state.manager.destroy(); state.manager = null; } if (true) { // detect if we are crossing into an engine if (env.originalOwner) { // when this outlet represents an engine we must ensure that a `ViewClass` is present // even if the engine does not contain a `view:application`. We need a `ViewClass` to // ensure that an `ownerView` is set on the `env` created just above options.component = options.component || owner._lookupFactory('view:toplevel'); } } var nodeManager = _emberHtmlbarsNodeManagersViewNodeManager.default.create(renderNode, env, attrs, options, parentView, null, null, template); state.manager = nodeManager; nodeManager.render(env, hash, visitor); } }; function isOutletEmpty(outletState) { return !outletState || !outletState.render.ViewClass && !outletState.render.template; } function isOutletStable(a, b) { if (!a && !b) { return true; } if (!a || !b) { return false; } a = a.render; b = b.render; for (var key in a) { if (a.hasOwnProperty(key)) { // Name is only here for logging & debugging. If two different // names result in otherwise identical states, they're still // identical. if (a[key] !== b[key] && key !== 'name') { return false; } } } return true; } }); enifed('ember-htmlbars/keywords/partial', ['exports', 'ember-views/system/lookup_partial', 'htmlbars-runtime'], function (exports, _emberViewsSystemLookup_partial, _htmlbarsRuntime) { /** @module ember @submodule ember-templates */ 'use strict'; /** The `partial` helper renders another template without changing the template context: ```handlebars {{foo}} {{partial "nav"}} ``` The above example template will render a template named "-nav", which has the same context as the parent template it's rendered into, so if the "-nav" template also referenced `{{foo}}`, it would print the same thing as the `{{foo}}` in the above example. If a "-nav" template isn't found, the `partial` helper will fall back to a template named "nav". ### Bound template names The parameter supplied to `partial` can also be a path to a property containing a template name, e.g.: ```handlebars {{partial someTemplateName}} ``` The above example will look up the value of `someTemplateName` on the template context (e.g. a controller) and use that value as the name of the template to render. If the resolved value is falsy, nothing will be rendered. If `someTemplateName` changes, the partial will be re-rendered using the new template name. @method partial @for Ember.Templates.helpers @param {String} partialName The name of the template to render minus the leading underscore. @public */ exports.default = { setupState: function (state, env, scope, params, hash) { return { partialName: env.hooks.getValue(params[0]) }; }, render: function (renderNode, env, scope, params, hash, template, inverse, visitor) { var state = renderNode.getState(); if (!state.partialName) { return true; } var found = _emberViewsSystemLookup_partial.default(env, state.partialName); if (!found) { return true; } _htmlbarsRuntime.internal.hostBlock(renderNode, env, scope, found.raw, null, null, visitor, function (options) { options.templates.template.yield(); }); } }; }); enifed('ember-htmlbars/keywords/readonly', ['exports', 'ember-htmlbars/keywords/mut'], function (exports, _emberHtmlbarsKeywordsMut) { /** @module ember @submodule ember-templates */ 'use strict'; exports.default = readonly; function readonly(morph, env, scope, originalParams, hash, template, inverse) { // If `morph` is `null` the keyword is being invoked as a subexpression. if (morph === null) { var stream = originalParams[0]; if (stream && stream[_emberHtmlbarsKeywordsMut.MUTABLE_REFERENCE]) { return stream.sourceDep.dependee; } return stream; } return true; } }); enifed('ember-htmlbars/keywords/render', ['exports', 'ember-metal/debug', 'ember-metal/empty_object', 'ember-metal/error', 'ember-htmlbars/streams/utils', 'ember-routing/system/generate_controller', 'ember-htmlbars/node-managers/view-node-manager'], function (exports, _emberMetalDebug, _emberMetalEmpty_object, _emberMetalError, _emberHtmlbarsStreamsUtils, _emberRoutingSystemGenerate_controller, _emberHtmlbarsNodeManagersViewNodeManager) { /** @module ember @submodule ember-templates */ 'use strict'; exports.childOutletState = childOutletState; /** Calling ``{{render}}`` from within a template will insert another template that matches the provided name. The inserted template will access its properties on its own controller (rather than the controller of the parent template). If a view class with the same name exists, the view class also will be used. Note: A given controller may only be used *once* in your app in this manner. A singleton instance of the controller will be created for you. Example: ```javascript App.NavigationController = Ember.Controller.extend({ who: "world" }); ``` ```handlebars <!-- navigation.hbs --> Hello, {{who}}. ``` ```handlebars <!-- application.hbs --> <h1>My great app</h1> {{render "navigation"}} ``` ```html <h1>My great app</h1> <div class='ember-view'> Hello, world. </div> ``` Optionally you may provide a second argument: a property path that will be bound to the `model` property of the controller. If a `model` property path is specified, then a new instance of the controller will be created and `{{render}}` can be used multiple times with the same name. For example if you had this `author` template. ```handlebars <div class="author"> Written by {{firstName}} {{lastName}}. Total Posts: {{postCount}} </div> ``` You could render it inside the `post` template using the `render` helper. ```handlebars <div class="post"> <h1>{{title}}</h1> <div>{{body}}</div> {{render "author" author}} </div> ``` @method render @for Ember.Templates.helpers @param {String} name @param {Object?} context @param {Hash} options @return {String} HTML string @public */ exports.default = { willRender: function (renderNode, env) { if (env.view.ownerView._outlets) { // We make sure we will get dirtied when outlet state changes. env.view.ownerView._outlets.push(renderNode); } }, setupState: function (prevState, env, scope, params, hash) { var name = params[0]; _emberMetalDebug.assert('The first argument of {{render}} must be quoted, e.g. {{render "sidebar"}}.', typeof name === 'string'); return { parentView: env.view, manager: prevState.manager, controller: prevState.controller, childOutletState: childOutletState(name, env) }; }, childEnv: function (state, env) { return env.childWithOutletState(state.childOutletState); }, isStable: function (lastState, nextState) { return isStable(lastState.childOutletState, nextState.childOutletState); }, isEmpty: function (state) { return false; }, render: function (node, env, scope, params, hash, template, inverse, visitor) { var state = node.getState(); var name = params[0]; var context = params[1]; var owner = env.owner; var router = owner.lookup('router:main'); _emberMetalDebug.assert('The second argument of {{render}} must be a path, e.g. {{render "post" post}}.', params.length < 2 || _emberHtmlbarsStreamsUtils.isStream(params[1])); if (params.length === 1) { // use the singleton controller _emberMetalDebug.assert('You can only use the {{render}} helper once without a model object as ' + 'its second argument, as in {{render "post" post}}.', !router || !router._lookupActiveComponentNode(name)); } else if (params.length !== 2) { throw new _emberMetalError.default('You must pass a templateName to render'); } var templateName = 'template:' + name; _emberMetalDebug.assert('You used `{{render \'' + name + '\'}}`, but \'' + name + '\' can not be ' + 'found as a template.', owner.hasRegistration(templateName) || !!template); if (!template) { template = owner.lookup(templateName); } // provide controller override var controllerName = undefined; var controllerFullName = undefined; if (hash.controller) { controllerName = hash.controller; controllerFullName = 'controller:' + controllerName; delete hash.controller; _emberMetalDebug.assert('The controller name you supplied \'' + controllerName + '\' ' + 'did not resolve to a controller.', owner.hasRegistration(controllerFullName)); } else { controllerName = name; controllerFullName = 'controller:' + controllerName; } var target = router; var controller = undefined; // choose name if (params.length > 1) { var factory = owner._lookupFactory(controllerFullName) || _emberRoutingSystemGenerate_controller.generateControllerFactory(owner, controllerName); controller = factory.create({ model: _emberHtmlbarsStreamsUtils.read(context), target: target }); node.addDestruction(controller); } else { controller = owner.lookup(controllerFullName) || _emberRoutingSystemGenerate_controller.default(owner, controllerName); controller.setProperties({ target: target }); } state.controller = controller; if (template && template.raw) { template = template.raw; } var options = { layout: null, self: controller }; var nodeManager = _emberHtmlbarsNodeManagersViewNodeManager.default.create(node, env, hash, options, state.parentView, null, null, template); state.manager = nodeManager; if (router && params.length === 1) { router._connectActiveComponentNode(name, nodeManager); } nodeManager.render(env, hash, visitor); }, rerender: function (node, env, scope, params, hash, template, inverse, visitor) { if (params.length > 1) { var model = _emberHtmlbarsStreamsUtils.read(params[1]); node.getState().controller.set('model', model); } } }; function childOutletState(name, env) { var topLevel = env.view.ownerView; if (!topLevel || !topLevel.outletState) { return; } var outletState = topLevel.outletState; if (!outletState.main) { return; } var selectedOutletState = outletState.main.outlets['__ember_orphans__']; if (!selectedOutletState) { return; } var matched = selectedOutletState.outlets[name]; if (matched) { var childState = new _emberMetalEmpty_object.default(); childState[matched.render.outlet] = matched; matched.wasUsed = true; return childState; } } function isStable(a, b) { if (!a && !b) { return true; } if (!a || !b) { return false; } for (var outletName in a) { if (!isStableOutlet(a[outletName], b[outletName])) { return false; } } return true; } function isStableOutlet(a, b) { if (!a && !b) { return true; } if (!a || !b) { return false; } a = a.render; b = b.render; for (var key in a) { if (a.hasOwnProperty(key)) { // name is only here for logging & debugging. If two different // names result in otherwise identical states, they're still // identical. if (a[key] !== b[key] && key !== 'name') { return false; } } } return true; } }); enifed('ember-htmlbars/keywords/textarea', ['exports'], function (exports) { /** @module ember @submodule ember-templates */ /** `{{textarea}}` inserts a new instance of `<textarea>` tag into the template. The attributes of `{{textarea}}` match those of the native HTML tags as closely as possible. The following HTML attributes can be set: * `value` * `name` * `rows` * `cols` * `placeholder` * `disabled` * `maxlength` * `tabindex` * `selectionEnd` * `selectionStart` * `selectionDirection` * `wrap` * `readonly` * `autofocus` * `form` * `spellcheck` * `required` When set to a quoted string, these value will be directly applied to the HTML element. When left unquoted, these values will be bound to a property on the template's current rendering context (most typically a controller instance). Unbound: ```handlebars {{textarea value="Lots of static text that ISN'T bound"}} ``` Would result in the following HTML: ```html <textarea class="ember-text-area"> Lots of static text that ISN'T bound </textarea> ``` Bound: In the following example, the `writtenWords` property on `App.ApplicationController` will be updated live as the user types 'Lots of text that IS bound' into the text area of their browser's window. ```javascript App.ApplicationController = Ember.Controller.extend({ writtenWords: "Lots of text that IS bound" }); ``` ```handlebars {{textarea value=writtenWords}} ``` Would result in the following HTML: ```html <textarea class="ember-text-area"> Lots of text that IS bound </textarea> ``` If you wanted a one way binding between the text area and a div tag somewhere else on your screen, you could use `Ember.computed.oneWay`: ```javascript App.ApplicationController = Ember.Controller.extend({ writtenWords: "Lots of text that IS bound", outputWrittenWords: Ember.computed.oneWay("writtenWords") }); ``` ```handlebars {{textarea value=writtenWords}} <div> {{outputWrittenWords}} </div> ``` Would result in the following HTML: ```html <textarea class="ember-text-area"> Lots of text that IS bound </textarea> <-- the following div will be updated in real time as you type --> <div> Lots of text that IS bound </div> ``` Finally, this example really shows the power and ease of Ember when two properties are bound to eachother via `Ember.computed.alias`. Type into either text area box and they'll both stay in sync. Note that `Ember.computed.alias` costs more in terms of performance, so only use it when your really binding in both directions: ```javascript App.ApplicationController = Ember.Controller.extend({ writtenWords: "Lots of text that IS bound", twoWayWrittenWords: Ember.computed.alias("writtenWords") }); ``` ```handlebars {{textarea value=writtenWords}} {{textarea value=twoWayWrittenWords}} ``` ```html <textarea id="ember1" class="ember-text-area"> Lots of text that IS bound </textarea> <-- both updated in real time --> <textarea id="ember2" class="ember-text-area"> Lots of text that IS bound </textarea> ``` ### Actions The helper can send multiple actions based on user events. The action property defines the action which is send when the user presses the return key. ```handlebars {{input action="submit"}} ``` The helper allows some user events to send actions. * `enter` * `insert-newline` * `escape-press` * `focus-in` * `focus-out` * `key-press` For example, if you desire an action to be sent when the input is blurred, you only need to setup the action name to the event name property. ```handlebars {{textarea focus-in="alertMessage"}} ``` See more about [Text Support Actions](/api/classes/Ember.TextArea.html) ### Extension Internally, `{{textarea}}` creates an instance of `Ember.TextArea`, passing arguments from the helper to `Ember.TextArea`'s `create` method. You can extend the capabilities of text areas in your application by reopening this class. For example, if you are building a Bootstrap project where `data-*` attributes are used, you can globally add support for a `data-*` attribute on all `{{textarea}}`s' in your app by reopening `Ember.TextArea` or `Ember.TextSupport` and adding it to the `attributeBindings` concatenated property: ```javascript Ember.TextArea.reopen({ attributeBindings: ['data-error'] }); ``` Keep in mind when writing `Ember.TextArea` subclasses that `Ember.TextArea` itself extends `Ember.Component`. Expect isolated component semantics, not legacy 1.x view semantics (like `controller` being present). See more about [Ember components](/api/classes/Ember.Component.html) @method textarea @for Ember.Templates.helpers @param {Hash} options @public */ 'use strict'; exports.default = textarea; function textarea(morph, env, scope, originalParams, hash, template, inverse, visitor) { env.hooks.component(morph, env, scope, '-text-area', originalParams, hash, { default: template, inverse: inverse }, visitor); return true; } }); enifed('ember-htmlbars/keywords/unbound', ['exports', 'ember-metal/debug', 'ember-htmlbars/streams/stream', 'ember-htmlbars/streams/utils'], function (exports, _emberMetalDebug, _emberHtmlbarsStreamsStream, _emberHtmlbarsStreamsUtils) { /** @module ember @submodule ember-templates */ 'use strict'; exports.default = unbound; /** The `{{unbound}}` helper disconnects the one-way binding of a property, essentially freezing its value at the moment of rendering. For example, in this example the display of the variable `name` will not change even if it is set with a new value: ```handlebars {{unbound name}} ``` Like any helper, the `unbound` helper can accept a nested helper expression. This allows for custom helpers to be rendered unbound: ```handlebars {{unbound (some-custom-helper)}} {{unbound (capitalize name)}} {{! You can use any helper, including unbound, in a nested expression }} {{capitalize (unbound name)}} ``` The `unbound` helper only accepts a single argument, and it return an unbound value. @method unbound @for Ember.Templates.helpers @public */ var VolatileStream = _emberHtmlbarsStreamsStream.default.extend({ init: function (source) { this.label = '(volatile ' + source.label + ')'; this.source = source; this.addDependency(source); }, value: function () { return _emberHtmlbarsStreamsUtils.read(this.source); }, notify: function () {} }); function unbound(morph, env, scope, params, hash, template, inverse, visitor) { _emberMetalDebug.assert('unbound helper cannot be called with multiple params or hash params', params.length === 1 && Object.keys(hash).length === 0); _emberMetalDebug.assert('unbound helper cannot be called as a block', !template); if (morph === null) { return new VolatileStream(params[0]); } var stream = undefined; if (morph.linkedResult) { stream = morph.linkedResult; } else { stream = new VolatileStream(params[0]); morph.linkedResult = stream; } env.hooks.range(morph, env, scope, null, stream, visitor); return true; } }); enifed('ember-htmlbars/keywords/with', ['exports', 'ember-metal/debug', 'htmlbars-runtime'], function (exports, _emberMetalDebug, _htmlbarsRuntime) { /** @module ember @submodule ember-templates */ 'use strict'; exports.default = { isStable: function () { return true; }, isEmpty: function (state) { return false; }, render: function (morph, env, scope, params, hash, template, inverse, visitor) { _emberMetalDebug.assert('{{#with foo}} must be called with a single argument or the use the ' + '{{#with foo as |bar|}} syntax', params.length === 1); _emberMetalDebug.assert('The {{#with}} helper must be called with a block', !!template); _htmlbarsRuntime.internal.continueBlock(morph, env, scope, 'with', params, hash, template, inverse, visitor); }, rerender: function (morph, env, scope, params, hash, template, inverse, visitor) { _htmlbarsRuntime.internal.continueBlock(morph, env, scope, 'with', params, hash, template, inverse, visitor); } }; }); enifed('ember-htmlbars/keywords/yield', ['exports'], function (exports) { 'use strict'; exports.default = yieldKeyword; function yieldKeyword(morph, env, scope, params, hash, template, inverse, visitor) { var to = env.hooks.getValue(hash.to) || 'default'; var block = scope.getBlock(to); if (block) { block.invoke(env, params, hash.self, morph, scope, visitor); } return true; } }); enifed('ember-htmlbars/make-bound-helper', ['exports', 'ember-metal/debug', 'ember-htmlbars/helper'], function (exports, _emberMetalDebug, _emberHtmlbarsHelper) { /** @module ember @submodule ember-templates */ 'use strict'; exports.default = makeBoundHelper; /** Create a bound helper. Accepts a function that receives the ordered and hash parameters from the template. If a bound property was provided in the template, it will be resolved to its value and any changes to the bound property cause the helper function to be re-run with the updated values. * `params` - An array of resolved ordered parameters. * `hash` - An object containing the hash parameters. For example: * With an unquoted ordered parameter: ```javascript {{x-capitalize foo}} ``` Assuming `foo` was set to `"bar"`, the bound helper would receive `["bar"]` as its first argument, and an empty hash as its second. * With a quoted ordered parameter: ```javascript {{x-capitalize "foo"}} ``` The bound helper would receive `["foo"]` as its first argument, and an empty hash as its second. * With an unquoted hash parameter: ```javascript {{x-repeat "foo" count=repeatCount}} ``` Assuming that `repeatCount` resolved to 2, the bound helper would receive `["foo"]` as its first argument, and { count: 2 } as its second. @private @method makeBoundHelper @for Ember.HTMLBars @param {Function} fn @since 1.10.0 */ function makeBoundHelper(fn) { _emberMetalDebug.deprecate('Using `Ember.HTMLBars.makeBoundHelper` is deprecated. Please refactor to use `Ember.Helper` or `Ember.Helper.helper`.', false, { id: 'ember-htmlbars.make-bound-helper', until: '3.0.0' }); return _emberHtmlbarsHelper.helper(fn); } }); enifed('ember-htmlbars/morphs/attr-morph', ['exports', 'ember-metal/debug', 'dom-helper', 'ember-metal/is_none', 'ember-views/system/utils'], function (exports, _emberMetalDebug, _domHelper, _emberMetalIs_none, _emberViewsSystemUtils) { 'use strict'; var HTMLBarsAttrMorph = _domHelper.default.prototype.AttrMorphClass; var proto = HTMLBarsAttrMorph.prototype; proto.didInit = function () { this.streamUnsubscribers = null; _emberMetalDebug.debugSeal(this); }; function deprecateEscapedStyle(morph, value) { _emberMetalDebug.warn(_emberViewsSystemUtils.STYLE_WARNING, (function (name, value, escaped) { // SafeString if (_emberMetalIs_none.default(value) || value && value.toHTML) { return true; } if (name !== 'style') { return true; } return !escaped; })(morph.attrName, value, morph.escaped), { id: 'ember-htmlbars.style-xss-warning' }); } proto.willSetContent = function (value) { deprecateEscapedStyle(this, value); }; exports.default = HTMLBarsAttrMorph; }); enifed('ember-htmlbars/morphs/morph', ['exports', 'dom-helper', 'ember-metal/debug'], function (exports, _domHelper, _emberMetalDebug) { 'use strict'; exports.default = EmberMorph; var HTMLBarsMorph = _domHelper.default.prototype.MorphClass; var guid = 1; function EmberMorph(DOMHelper, contextualElement) { this.HTMLBarsMorph$constructor(DOMHelper, contextualElement); this.emberView = null; this.emberToDestroy = null; this.streamUnsubscribers = null; this.guid = guid++; // A component can become dirty either because one of its // attributes changed, or because it was re-rendered. If any part // of the component's template changes through observation, it has // re-rendered from the perpsective of the programming model. This // flag is set to true whenever a component becomes dirty because // one of its attributes changed, which also triggers the attribute // update flag (didUpdateAttrs). this.shouldReceiveAttrs = false; _emberMetalDebug.debugSeal(this); } var proto = EmberMorph.prototype = Object.create(HTMLBarsMorph.prototype); proto.HTMLBarsMorph$constructor = HTMLBarsMorph; proto.HTMLBarsMorph$clear = HTMLBarsMorph.prototype.clear; proto.addDestruction = function (toDestroy) { // called from Router.prototype._connectActiveComponentNode for {{render}} this.emberToDestroy = this.emberToDestroy || []; this.emberToDestroy.push(toDestroy); }; proto.cleanup = function () { var toDestroy = this.emberToDestroy; if (toDestroy) { for (var i = 0; i < toDestroy.length; i++) { toDestroy[i].destroy(); } this.emberToDestroy = null; } }; proto.didRender = function (env, scope) { env.renderedNodes.add(this); }; }); enifed('ember-htmlbars/node-managers/component-node-manager', ['exports', 'ember-metal/debug', 'ember-htmlbars/system/build-component-template', 'ember-htmlbars/hooks/get-cell-or-value', 'ember-metal/property_get', 'ember-views/compat/attrs-proxy', 'ember-htmlbars/system/instrumentation-support', 'ember-htmlbars/component', 'ember-htmlbars/utils/extract-positional-params', 'container/owner', 'ember-htmlbars/hooks/get-value'], function (exports, _emberMetalDebug, _emberHtmlbarsSystemBuildComponentTemplate, _emberHtmlbarsHooksGetCellOrValue, _emberMetalProperty_get, _emberViewsCompatAttrsProxy, _emberHtmlbarsSystemInstrumentationSupport, _emberHtmlbarsComponent, _emberHtmlbarsUtilsExtractPositionalParams, _containerOwner, _emberHtmlbarsHooksGetValue) { 'use strict'; exports.default = ComponentNodeManager; exports.createComponent = createComponent; exports.takeLegacySnapshot = takeLegacySnapshot; function ComponentNodeManager(component, scope, renderNode, attrs, block, expectElement) { this.component = component; this.scope = scope; this.renderNode = renderNode; this.attrs = attrs; this.block = block; this.expectElement = expectElement; } ComponentNodeManager.create = function ComponentNodeManager_create(renderNode, env, options) { var _createOptions; var tagName = options.tagName; var params = options.params; var _options$attrs = options.attrs; var attrs = _options$attrs === undefined ? {} : _options$attrs; var parentView = options.parentView; var parentScope = options.parentScope; var component = options.component; var layout = options.layout; var templates = options.templates; component = component || _emberHtmlbarsComponent.default; var createOptions = (_createOptions = { parentView: parentView }, _createOptions[_emberHtmlbarsComponent.HAS_BLOCK] = !!templates.default, _createOptions); configureTagName(attrs, tagName, component, createOptions); // Map passed attributes (e.g. <my-component id="foo">) to component // properties ({ id: "foo" }). configureCreateOptions(attrs, createOptions); // This allows the component to target actions sent via `sendAction` correctly. createOptions._targetObject = _emberHtmlbarsHooksGetValue.default(parentScope.getSelf()); _emberHtmlbarsUtilsExtractPositionalParams.default(renderNode, component, params, attrs); // Instantiate the component component = createComponent(component, createOptions, renderNode, env, attrs); var layoutName = _emberMetalProperty_get.get(component, 'layoutName'); // If the component specifies its layout via the `layout` property // instead of using the template looked up in the container, get it // now that we have the component instance. if (!layout) { layout = _emberMetalProperty_get.get(component, 'layout'); } if (!layout && layoutName) { var owner = _containerOwner.getOwner(component); layout = owner.lookup('template:' + layoutName); } var results = _emberHtmlbarsSystemBuildComponentTemplate.default({ layout: layout, component: component }, attrs, { templates: templates, scope: parentScope }); return new ComponentNodeManager(component, parentScope, renderNode, attrs, results.block, results.createdElement); }; function configureTagName(attrs, tagName, component, createOptions) { if (attrs.tagName) { createOptions.tagName = _emberHtmlbarsHooksGetValue.default(attrs.tagName); } } function configureCreateOptions(attrs, createOptions) { // Some attrs are special and need to be set as properties on the component // instance. Make sure we use getValue() to get them from `attrs` since // they are still streams. if (attrs.id) { createOptions.elementId = _emberHtmlbarsHooksGetValue.default(attrs.id); } } ComponentNodeManager.prototype.render = function ComponentNodeManager_render(_env, visitor) { var component = this.component; return _emberHtmlbarsSystemInstrumentationSupport.instrument(component, function ComponentNodeManager_render_instrument() { var meta = this.block && this.block.template.meta; var env = _env.childWithView(component, meta); env.renderer.componentWillRender(component); env.renderedViews.push(component.elementId); if (this.block) { this.block.invoke(env, [], undefined, this.renderNode, this.scope, visitor); } var element = undefined; if (this.expectElement) { element = this.renderNode.firstNode; } // In environments like FastBoot, disable any hooks that would cause the component // to access the DOM directly. if (env.destinedForDOM) { env.renderer.didCreateElement(component, element); env.renderer.willInsertElement(component, element); env.lifecycleHooks.push({ type: 'didInsertElement', view: component }); } }, this); }; ComponentNodeManager.prototype.rerender = function ComponentNodeManager_rerender(_env, attrs, visitor) { var component = this.component; return _emberHtmlbarsSystemInstrumentationSupport.instrument(component, function ComponentNodeManager_rerender_instrument() { var meta = this.block && this.block.template.meta; var env = _env.childWithView(component, meta); var snapshot = takeSnapshot(attrs); if (component._renderNode.shouldReceiveAttrs) { if (component._propagateAttrsToThis) { component._propagateAttrsToThis(takeLegacySnapshot(attrs)); } env.renderer.componentUpdateAttrs(component, snapshot); component._renderNode.shouldReceiveAttrs = false; } // Notify component that it has become dirty and is about to change. env.renderer.componentWillUpdate(component, snapshot); env.renderer.componentWillRender(component); env.renderedViews.push(component.elementId); if (this.block) { this.block.invoke(env, [], undefined, this.renderNode, this.scope, visitor); } env.lifecycleHooks.push({ type: 'didUpdate', view: component }); return env; }, this); }; ComponentNodeManager.prototype.destroy = function ComponentNodeManager_destroy() { // Clear component's render node. Normally this gets cleared // during view destruction, but in this case we're re-assigning the // node to a different view and it will get cleaned up automatically. this.component.destroy(); }; function createComponent(_component, props, renderNode, env) { var attrs = arguments.length <= 4 || arguments[4] === undefined ? {} : arguments[4]; _emberMetalDebug.assert('controller= is no longer supported', !('controller' in attrs)); snapshotAndUpdateTarget(attrs, props); _containerOwner.setOwner(props, env.owner); props.renderer = props.parentView ? props.parentView.renderer : env.owner.lookup('renderer:-dom'); var component = _component.create(props); if (props.parentView) { props.parentView.appendChild(component); } component._renderNode = renderNode; renderNode.emberView = component; renderNode.buildChildEnv = buildChildEnv; return component; } function takeSnapshot(attrs) { var hash = {}; for (var prop in attrs) { hash[prop] = _emberHtmlbarsHooksGetCellOrValue.default(attrs[prop]); } return hash; } function takeLegacySnapshot(attrs) { var hash = {}; for (var prop in attrs) { hash[prop] = _emberHtmlbarsHooksGetValue.default(attrs[prop]); } return hash; } function snapshotAndUpdateTarget(rawAttrs, target) { var attrs = {}; for (var prop in rawAttrs) { var value = _emberHtmlbarsHooksGetCellOrValue.default(rawAttrs[prop]); attrs[prop] = value; // when `attrs` is an actual value being set in the // attrs hash (`{{foo-bar attrs="blah"}}`) we cannot // set `"blah"` to the root of the target because // that would replace all attrs with `attrs.attrs` if (prop === 'attrs') { _emberMetalDebug.warn('Invoking a component with a hash attribute named `attrs` is not supported. Please refactor usage of ' + target + ' to avoid passing `attrs` as a hash parameter.', false, { id: 'ember-htmlbars.component-unsupported-attrs' }); continue; } if (value && value[_emberViewsCompatAttrsProxy.MUTABLE_CELL]) { value = value.value; } target[prop] = value; } return target.attrs = attrs; } function buildChildEnv(state, env) { return env.childWithView(this.emberView); } }); // In theory this should come through the env, but it should // be safe to import this until we make the hook system public // and it gets actively used in addons or other downstream // libraries. enifed('ember-htmlbars/node-managers/view-node-manager', ['exports', 'ember-metal/assign', 'ember-metal/debug', 'ember-htmlbars/system/build-component-template', 'ember-metal/property_get', 'ember-metal/set_properties', 'ember-views/compat/attrs-proxy', 'ember-htmlbars/hooks/get-cell-or-value', 'ember-htmlbars/system/instrumentation-support', 'ember-htmlbars/node-managers/component-node-manager', 'container/owner', 'ember-htmlbars/hooks/get-value'], function (exports, _emberMetalAssign, _emberMetalDebug, _emberHtmlbarsSystemBuildComponentTemplate, _emberMetalProperty_get, _emberMetalSet_properties, _emberViewsCompatAttrsProxy, _emberHtmlbarsHooksGetCellOrValue, _emberHtmlbarsSystemInstrumentationSupport, _emberHtmlbarsNodeManagersComponentNodeManager, _containerOwner, _emberHtmlbarsHooksGetValue) { 'use strict'; exports.default = ViewNodeManager; exports.createOrUpdateComponent = createOrUpdateComponent; function ViewNodeManager(component, scope, renderNode, block, expectElement) { this.component = component; this.scope = scope; this.renderNode = renderNode; this.block = block; this.expectElement = expectElement; } ViewNodeManager.create = function ViewNodeManager_create(renderNode, env, attrs, found, parentView, path, contentScope, contentTemplate) { _emberMetalDebug.assert('HTMLBars error: Could not find component named "' + path + '" (no component or template with that name was found)', !!(function () { if (path) { return found.component || found.layout; } else { return found.component || found.layout || contentTemplate; } })()); var component = undefined; var componentInfo = { layout: found.layout }; if (found.component) { var options = { parentView: parentView }; if (attrs && attrs.id) { options.elementId = _emberHtmlbarsHooksGetValue.default(attrs.id); } if (attrs && attrs.tagName) { options.tagName = _emberHtmlbarsHooksGetValue.default(attrs.tagName); } component = componentInfo.component = createOrUpdateComponent(found.component, options, found.createOptions, renderNode, env, attrs); var layout = _emberMetalProperty_get.get(component, 'layout'); if (layout) { componentInfo.layout = layout; } else { componentInfo.layout = getTemplate(component) || componentInfo.layout; } renderNode.emberView = component; } _emberMetalDebug.assert('BUG: ViewNodeManager.create can take a scope or a self, but not both', !(contentScope && found.self)); var results = _emberHtmlbarsSystemBuildComponentTemplate.default(componentInfo, attrs, { templates: { default: contentTemplate }, scope: contentScope, self: found.self }); return new ViewNodeManager(component, contentScope, renderNode, results.block, results.createdElement); }; ViewNodeManager.prototype.render = function ViewNodeManager_render(env, attrs, visitor) { var component = this.component; return _emberHtmlbarsSystemInstrumentationSupport.instrument(component, function ViewNodeManager_render_instrument() { var newEnv = env; if (component) { newEnv = env.childWithView(component); } else { var meta = this.block && this.block.template.meta; newEnv = env.childWithMeta(meta); } if (component) { env.renderer.willRender(component); env.renderedViews.push(component.elementId); } if (this.block) { this.block.invoke(newEnv, [], undefined, this.renderNode, this.scope, visitor); } if (component) { var element = this.expectElement && this.renderNode.firstNode; // In environments like FastBoot, disable any hooks that would cause the component // to access the DOM directly. if (env.destinedForDOM) { env.renderer.didCreateElement(component, element); env.renderer.willInsertElement(component, element); env.lifecycleHooks.push({ type: 'didInsertElement', view: component }); } } }, this); }; ViewNodeManager.prototype.rerender = function ViewNodeManager_rerender(env, attrs, visitor) { var component = this.component; return _emberHtmlbarsSystemInstrumentationSupport.instrument(component, function ViewNodeManager_rerender_instrument() { var newEnv = env; if (component) { newEnv = env.childWithView(component); var snapshot = takeSnapshot(attrs); // Notify component that it has become dirty and is about to change. env.renderer.willUpdate(component, snapshot); if (component._renderNode.shouldReceiveAttrs) { if (component._propagateAttrsToThis) { component._propagateAttrsToThis(_emberHtmlbarsNodeManagersComponentNodeManager.takeLegacySnapshot(attrs)); } env.renderer.componentUpdateAttrs(component, snapshot); component._renderNode.shouldReceiveAttrs = false; } env.renderer.willRender(component); env.renderedViews.push(component.elementId); } else { var meta = this.block && this.block.template.meta; newEnv = env.childWithMeta(meta); } if (this.block) { this.block.invoke(newEnv, [], undefined, this.renderNode, this.scope, visitor); } return newEnv; }, this); }; ViewNodeManager.prototype.destroy = function ViewNodeManager_destroy() { if (this.component) { this.component.destroy(); this.component = null; } }; function getTemplate(componentOrView) { if (!componentOrView.isComponent) { return _emberMetalProperty_get.get(componentOrView, 'template'); } return null; } function createOrUpdateComponent(component, options, createOptions, renderNode, env) { var attrs = arguments.length <= 5 || arguments[5] === undefined ? {} : arguments[5]; var snapshot = takeSnapshot(attrs); var props = _emberMetalAssign.default({}, options); if (!props.ownerView && options.parentView) { props.ownerView = options.parentView.ownerView; } props.attrs = snapshot; if (component.create) { if (createOptions) { _emberMetalAssign.default(props, createOptions); } mergeBindings(props, snapshot); var owner = env.owner; _containerOwner.setOwner(props, owner); props.renderer = options.parentView ? options.parentView.renderer : owner && owner.lookup('renderer:-dom'); component = component.create(props); } else { env.renderer.componentUpdateAttrs(component, snapshot); _emberMetalSet_properties.default(component, props); if (component._propagateAttrsToThis) { component._propagateAttrsToThis(_emberHtmlbarsNodeManagersComponentNodeManager.takeLegacySnapshot(attrs)); } } if (options.parentView) { options.parentView.appendChild(component); } component._renderNode = renderNode; renderNode.emberView = component; return component; } function takeSnapshot(attrs) { var hash = {}; for (var prop in attrs) { hash[prop] = _emberHtmlbarsHooksGetCellOrValue.default(attrs[prop]); } return hash; } function mergeBindings(target, attrs) { for (var prop in attrs) { if (!attrs.hasOwnProperty(prop)) { continue; } // when `attrs` is an actual value being set in the // attrs hash (`{{foo-bar attrs="blah"}}`) we cannot // set `"blah"` to the root of the target because // that would replace all attrs with `attrs.attrs` if (prop === 'attrs') { _emberMetalDebug.warn('Invoking a component with a hash attribute named `attrs` is not supported. Please refactor usage of ' + target + ' to avoid passing `attrs` as a hash parameter.', false, { id: 'ember-htmlbars.view-unsupported-attrs' }); continue; } var value = attrs[prop]; if (value && value[_emberViewsCompatAttrsProxy.MUTABLE_CELL]) { target[prop] = value.value; } else { target[prop] = value; } } return target; } }); // In theory this should come through the env, but it should // be safe to import this until we make the hook system public // and it gets actively used in addons or other downstream // libraries. enifed('ember-htmlbars/renderer', ['exports', 'ember-metal/run_loop', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/assign', 'ember-metal/set_properties', 'ember-htmlbars/system/build-component-template', 'ember-environment', 'htmlbars-runtime', 'ember-htmlbars/system/render-view', 'ember-views/compat/fallback-view-registry', 'ember-metal/debug'], function (exports, _emberMetalRun_loop, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalAssign, _emberMetalSet_properties, _emberHtmlbarsSystemBuildComponentTemplate, _emberEnvironment, _htmlbarsRuntime, _emberHtmlbarsSystemRenderView, _emberViewsCompatFallbackViewRegistry, _emberMetalDebug) { 'use strict'; exports.Renderer = Renderer; exports.MorphSet = MorphSet; function Renderer(domHelper) { var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var destinedForDOM = _ref.destinedForDOM; var _viewRegistry = _ref._viewRegistry; this._dom = domHelper; // This flag indicates whether the resulting rendered element will be // inserted into the DOM. This should be set to `false` if the rendered // element is going to be serialized to HTML without being inserted into // the DOM (e.g., in FastBoot mode). By default, this flag is the same // as whether we are running in an environment with DOM, but may be // overridden. this._destinedForDOM = destinedForDOM === undefined ? _emberEnvironment.environment.hasDOM : destinedForDOM; this._viewRegistry = _viewRegistry || _emberViewsCompatFallbackViewRegistry.default; } Renderer.prototype.prerenderTopLevelView = function Renderer_prerenderTopLevelView(view, renderNode) { if (view._state === 'inDOM') { throw new Error('You cannot insert a View that has already been rendered'); } view.ownerView = renderNode.emberView = view; view._renderNode = renderNode; var layout = _emberMetalProperty_get.get(view, 'layout'); var template = _emberMetalProperty_get.get(view, 'template'); var componentInfo = { component: view, layout: layout }; var block = _emberHtmlbarsSystemBuildComponentTemplate.default(componentInfo, {}, { self: view, templates: template ? { default: template.raw } : undefined }).block; _emberHtmlbarsSystemRenderView.renderHTMLBarsBlock(view, block, renderNode); view.lastResult = renderNode.lastResult; this.clearRenderedViews(view._env); }; Renderer.prototype.renderTopLevelView = function Renderer_renderTopLevelView(view, renderNode) { // Check to see if insertion has been canceled. if (view._willInsert) { view._willInsert = false; this.prerenderTopLevelView(view, renderNode); this.dispatchLifecycleHooks(view._env); } }; Renderer.prototype.revalidateTopLevelView = function Renderer_revalidateTopLevelView(view) { // This guard prevents revalidation on an already-destroyed view. if (view._renderNode && view._renderNode.lastResult) { view._renderNode.lastResult.revalidate(view._env); this.dispatchLifecycleHooks(view._env); this.clearRenderedViews(view._env); } }; Renderer.prototype.dispatchLifecycleHooks = function Renderer_dispatchLifecycleHooks(env) { var ownerView = env.view; var lifecycleHooks = env.lifecycleHooks; var i = undefined, hook = undefined; for (i = 0; i < lifecycleHooks.length; i++) { hook = lifecycleHooks[i]; ownerView._dispatching = hook.type; switch (hook.type) { case 'didInsertElement': this.didInsertElement(hook.view);break; case 'didUpdate': this.didUpdate(hook.view);break; } this.didRender(hook.view); } ownerView._dispatching = null; env.lifecycleHooks.length = 0; }; Renderer.prototype.ensureViewNotRendering = function Renderer_ensureViewNotRendering(view) { var env = view.ownerView._env; if (env && env.renderedViews.indexOf(view.elementId) !== -1) { throw new Error('Something you did caused a view to re-render after it rendered but before it was inserted into the DOM.'); } }; function MorphSet() { this.morphs = []; } MorphSet.prototype.add = function (morph) { this.morphs.push(morph); morph.seen = true; }; MorphSet.prototype.has = function (morph) { return morph.seen; }; MorphSet.prototype.clear = function () { var morphs = this.morphs; for (var i = 0; i < morphs.length; i++) { morphs[i].seen = false; } this.morphs = []; }; Renderer.prototype.clearRenderedViews = function Renderer_clearRenderedViews(env) { env.renderedNodes.clear(); env.renderedViews.length = 0; }; // This entry point is called from top-level `view.appendTo`. Renderer.prototype.appendTo = function Renderer_appendTo(view, target) { var morph = this._dom.appendMorph(target); morph.ownerNode = morph; view._willInsert = true; _emberMetalRun_loop.default.schedule('render', this, this.renderTopLevelView, view, morph); }; Renderer.prototype.replaceIn = function Renderer_replaceIn(view, target) { var morph = this._dom.replaceContentWithMorph(target); morph.ownerNode = morph; view._willInsert = true; _emberMetalRun_loop.default.scheduleOnce('render', this, this.renderTopLevelView, view, morph); }; Renderer.prototype.didCreateElement = function (view, element) { if (element) { view.element = element; } if (view._transitionTo) { view._transitionTo('hasElement'); } }; // hasElement Renderer.prototype.willInsertElement = function (view) { if (view.trigger) { view.trigger('willInsertElement'); } }; // Will place into DOM. Renderer.prototype.componentInitAttrs = function (component, attrs) { component.trigger('didInitAttrs', { attrs: attrs }); component.trigger('didReceiveAttrs', { newAttrs: attrs }); }; // Set attrs the first time. Renderer.prototype.didInsertElement = function (view) { if (view._transitionTo) { view._transitionTo('inDOM'); } if (view.trigger) { view.trigger('didInsertElement'); } }; // inDOM // Placed into DOM. Renderer.prototype.didUpdate = function (view) { if (view.trigger) { view.trigger('didUpdate'); } }; Renderer.prototype.didRender = function (view) { if (view.trigger) { view.trigger('didRender'); } }; Renderer.prototype.componentUpdateAttrs = function (component, newAttrs) { var oldAttrs = null; if (component.attrs) { oldAttrs = _emberMetalAssign.default({}, component.attrs); _emberMetalSet_properties.default(component.attrs, newAttrs); } else { _emberMetalProperty_set.set(component, 'attrs', newAttrs); } component.trigger('didUpdateAttrs', { oldAttrs: oldAttrs, newAttrs: newAttrs }); component.trigger('didReceiveAttrs', { oldAttrs: oldAttrs, newAttrs: newAttrs }); }; Renderer.prototype.willUpdate = function (view, attrs) { if (view._willUpdate) { view._willUpdate(attrs); } }; Renderer.prototype.componentWillUpdate = function (component) { component.trigger('willUpdate'); }; Renderer.prototype.willRender = function (view) { if (view._willRender) { view._willRender(); } }; Renderer.prototype.componentWillRender = function (component) { component.trigger('willRender'); }; Renderer.prototype.rerender = function (view) { var renderNode = view._renderNode; renderNode.isDirty = true; _htmlbarsRuntime.internal.visitChildren(renderNode.childNodes, function (node) { if (node.getState().manager) { node.shouldReceiveAttrs = true; } node.isDirty = true; }); renderNode.ownerNode.emberView.scheduleRevalidate(renderNode, view.toString(), 'rerendering'); }; Renderer.prototype.remove = function (view) { var lastResult = view.lastResult; if (lastResult) { // toplevel only. view.lastResult = null; lastResult.destroy(); } else { view.destroy(); } }; Renderer.prototype.willDestroyElement = function (view) { if (view.trigger) { view.trigger('willDestroyElement'); view.trigger('willClearRender'); } }; Renderer.prototype.didDestroyElement = function (view) { view.element = null; if (view.trigger) { view.trigger('didDestroyElement'); } }; Renderer.prototype._register = function Renderer_register(view) { _emberMetalDebug.assert('Attempted to register a view with an id already in use: ' + view.elementId, !this._viewRegistry[this.elementId]); this._viewRegistry[view.elementId] = view; }; Renderer.prototype._unregister = function Renderer_unregister(view) { delete this._viewRegistry[this.elementId]; }; var InertRenderer = { create: function (_ref2) { var dom = _ref2.dom; var _viewRegistry = _ref2._viewRegistry; return new Renderer(dom, { destinedForDOM: false, _viewRegistry: _viewRegistry }); } }; exports.InertRenderer = InertRenderer; var InteractiveRenderer = { create: function (_ref3) { var dom = _ref3.dom; var _viewRegistry = _ref3._viewRegistry; return new Renderer(dom, { destinedForDOM: true, _viewRegistry: _viewRegistry }); } }; exports.InteractiveRenderer = InteractiveRenderer; }); enifed('ember-htmlbars/setup-registry', ['exports', 'container/registry', 'ember-htmlbars/renderer', 'ember-htmlbars/system/dom-helper', 'ember-htmlbars/templates/top-level-view', 'ember-htmlbars/views/outlet', 'ember-views/views/view', 'ember-htmlbars/component', 'ember-htmlbars/components/text_field', 'ember-htmlbars/components/text_area', 'ember-htmlbars/components/checkbox', 'ember-htmlbars/components/link-to', 'ember-views/mixins/template_support'], function (exports, _containerRegistry, _emberHtmlbarsRenderer, _emberHtmlbarsSystemDomHelper, _emberHtmlbarsTemplatesTopLevelView, _emberHtmlbarsViewsOutlet, _emberViewsViewsView, _emberHtmlbarsComponent, _emberHtmlbarsComponentsText_field, _emberHtmlbarsComponentsText_area, _emberHtmlbarsComponentsCheckbox, _emberHtmlbarsComponentsLinkTo, _emberViewsMixinsTemplate_support) { 'use strict'; exports.setupApplicationRegistry = setupApplicationRegistry; exports.setupEngineRegistry = setupEngineRegistry; var _templateObject = _taggedTemplateLiteralLoose(['component:-default'], ['component:-default']); function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } function setupApplicationRegistry(registry) { registry.register('renderer:-dom', _emberHtmlbarsRenderer.InteractiveRenderer); registry.register('renderer:-inert', _emberHtmlbarsRenderer.InertRenderer); registry.register('service:-dom-helper', { create: function (_ref) { var document = _ref.document; return new _emberHtmlbarsSystemDomHelper.default(document); } }); } function setupEngineRegistry(registry) { registry.optionsForType('template', { instantiate: false }); registry.register('view:-outlet', _emberHtmlbarsViewsOutlet.OutletView); registry.register('template:-outlet', _emberHtmlbarsTemplatesTopLevelView.default); registry.register('view:toplevel', _emberViewsViewsView.default.extend(_emberViewsMixinsTemplate_support.default)); registry.register('component:-text-field', _emberHtmlbarsComponentsText_field.default); registry.register('component:-text-area', _emberHtmlbarsComponentsText_area.default); registry.register('component:-checkbox', _emberHtmlbarsComponentsCheckbox.default); registry.register('component:link-to', _emberHtmlbarsComponentsLinkTo.default); registry.register(_containerRegistry.privatize(_templateObject), _emberHtmlbarsComponent.default); } }); enifed('ember-htmlbars/streams/built-in-helper', ['exports', 'ember-htmlbars/streams/stream', 'ember-htmlbars/streams/utils'], function (exports, _emberHtmlbarsStreamsStream, _emberHtmlbarsStreamsUtils) { 'use strict'; exports.default = _emberHtmlbarsStreamsStream.default.extend({ init: function (helper, params, hash, templates, env, scope, label) { this.helper = helper; this.params = params; this.templates = templates; this._env = env; this.scope = scope; this.hash = hash; this.label = label; }, compute: function () { return this.helper(_emberHtmlbarsStreamsUtils.getArrayValues(this.params), _emberHtmlbarsStreamsUtils.getHashValues(this.hash), this.templates, this._env, this.scope); } }); }); enifed('ember-htmlbars/streams/class_name_binding', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/utils', 'ember-htmlbars/streams/utils', 'ember-runtime/system/string'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalUtils, _emberHtmlbarsStreamsUtils, _emberRuntimeSystemString) { 'use strict'; exports.parsePropertyPath = parsePropertyPath; exports.classStringForValue = classStringForValue; exports.streamifyClassNameBinding = streamifyClassNameBinding; /** Parse a path and return an object which holds the parsed properties. For example a path like "content.isEnabled:enabled:disabled" will return the following object: ```javascript { path: "content.isEnabled", className: "enabled", falsyClassName: "disabled", classNames: ":enabled:disabled" } ``` @method parsePropertyPath @static @private */ function parsePropertyPath(path) { var split = path.split(':'); var propertyPath = split[0]; var classNames = ''; var className = undefined, falsyClassName = undefined; // check if the property is defined as prop:class or prop:trueClass:falseClass if (split.length > 1) { className = split[1]; if (split.length === 3) { falsyClassName = split[2]; } classNames = ':' + className; if (falsyClassName) { classNames += ':' + falsyClassName; } } return { path: propertyPath, classNames: classNames, className: className === '' ? undefined : className, falsyClassName: falsyClassName }; } /** Get the class name for a given value, based on the path, optional `className` and optional `falsyClassName`. - if a `className` or `falsyClassName` has been specified: - if the value is truthy and `className` has been specified, `className` is returned - if the value is falsy and `falsyClassName` has been specified, `falsyClassName` is returned - otherwise `null` is returned - if the value is `true`, the dasherized last part of the supplied path is returned - if the value is not `false`, `undefined` or `null`, the `value` is returned - if none of the above rules apply, `null` is returned @method classStringForValue @param path @param val @param className @param falsyClassName @static @private */ function classStringForValue(path, val, className, falsyClassName) { if (_emberMetalUtils.isArray(val)) { val = _emberMetalProperty_get.get(val, 'length') !== 0; } // When using the colon syntax, evaluate the truthiness or falsiness // of the value to determine which className to return if (className || falsyClassName) { if (className && !!val) { return className; } else if (falsyClassName && !val) { return falsyClassName; } else { return null; } // If value is a Boolean and true, return the dasherized property // name. } else if (val === true) { // Normalize property path to be suitable for use // as a class name. For exaple, content.foo.barBaz // becomes bar-baz. var parts = path.split('.'); return _emberRuntimeSystemString.dasherize(parts[parts.length - 1]); // If the value is not false, undefined, or null, return the current // value of the property. } else if (val !== false && val != null) { return val; // Nothing to display. Return null so that the old class is removed // but no new class is added. } else { return null; } } function streamifyClassNameBinding(view, classNameBinding, prefix) { prefix = prefix || ''; _emberMetalDebug.assert('classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. [\'foo\', \':bar\']', classNameBinding.indexOf(' ') === -1); var parsedPath = parsePropertyPath(classNameBinding); if (parsedPath.path === '') { return classStringForValue(parsedPath.path, true, parsedPath.className, parsedPath.falsyClassName); } else { var _ret = (function () { var pathValue = view.getStream(prefix + parsedPath.path); return { v: _emberHtmlbarsStreamsUtils.chain(pathValue, function () { return classStringForValue(parsedPath.path, _emberHtmlbarsStreamsUtils.read(pathValue), parsedPath.className, parsedPath.falsyClassName); }) }; })(); if (typeof _ret === 'object') return _ret.v; } } }); enifed('ember-htmlbars/streams/concat', ['exports', 'ember-htmlbars/streams/stream', 'ember-htmlbars/streams/utils'], function (exports, _emberHtmlbarsStreamsStream, _emberHtmlbarsStreamsUtils) { 'use strict'; exports.default = concat; var ConcatStream = _emberHtmlbarsStreamsStream.default.extend({ init: function (array, separator) { this.array = array; this.separator = separator; // Used by angle bracket components to detect an attribute was provided // as a string literal. this.isConcat = true; }, label: function () { var labels = _emberHtmlbarsStreamsUtils.labelsFor(this.array); return 'concat([' + labels.join(', ') + ']; separator=' + _emberHtmlbarsStreamsUtils.inspect(this.separator) + ')'; }, compute: function () { return concat(_emberHtmlbarsStreamsUtils.readArray(this.array), this.separator); } }); /* Join an array, with any streams replaced by their current values. @private @for Ember.stream @function concat @param {Array} array An array containing zero or more stream objects and zero or more non-stream objects. @param {String} separator String to be used to join array elements. @return {String} String with array elements concatenated and joined by the provided separator, and any stream array members having been replaced by the current value of the stream. */ function concat(array, separator) { // TODO: Create subclass ConcatStream < Stream. Defer // subscribing to streams until the value() is called. var hasStream = _emberHtmlbarsStreamsUtils.scanArray(array); if (hasStream) { var stream = new ConcatStream(array, separator); for (var i = 0; i < array.length; i++) { _emberHtmlbarsStreamsUtils.addDependency(stream, array[i]); } return stream; } else { return array.join(separator); } } }); enifed('ember-htmlbars/streams/dependency', ['exports', 'ember-metal/debug', 'ember-metal/assign', 'ember-htmlbars/streams/utils'], function (exports, _emberMetalDebug, _emberMetalAssign, _emberHtmlbarsStreamsUtils) { 'use strict'; exports.default = Dependency; /** @module ember-metal */ /** @private @class Dependency @namespace Ember.streams @constructor */ function Dependency(depender, dependee) { _emberMetalDebug.assert('Dependency error: Depender must be a stream', _emberHtmlbarsStreamsUtils.isStream(depender)); this.next = null; this.prev = null; this.depender = depender; this.dependee = dependee; this.unsubscription = null; } _emberMetalAssign.default(Dependency.prototype, { subscribe: function () { _emberMetalDebug.assert('Dependency error: Dependency tried to subscribe while already subscribed', !this.unsubscription); this.unsubscription = _emberHtmlbarsStreamsUtils.subscribe(this.dependee, this.depender.notify, this.depender); }, unsubscribe: function () { if (this.unsubscription) { this.unsubscription(); this.unsubscription = null; } }, replace: function (dependee) { if (this.dependee !== dependee) { this.dependee = dependee; if (this.unsubscription) { this.unsubscribe(); this.subscribe(); } return true; } return false; }, getValue: function () { return _emberHtmlbarsStreamsUtils.read(this.dependee); }, setValue: function (value) { return _emberHtmlbarsStreamsUtils.setValue(this.dependee, value); } // destroy() { // var next = this.next; // var prev = this.prev; // if (prev) { // prev.next = next; // } else { // this.depender.dependencyHead = next; // } // if (next) { // next.prev = prev; // } else { // this.depender.dependencyTail = prev; // } // this.unsubscribe(); // } }); }); enifed('ember-htmlbars/streams/helper-factory', ['exports', 'ember-htmlbars/streams/stream', 'ember-htmlbars/streams/utils'], function (exports, _emberHtmlbarsStreamsStream, _emberHtmlbarsStreamsUtils) { 'use strict'; exports.default = _emberHtmlbarsStreamsStream.default.extend({ init: function (helperFactory, params, hash, label) { this.helperFactory = helperFactory; this.params = params; this.hash = hash; this.linkable = true; this.helper = null; this.label = label; }, compute: function () { if (!this.helper) { this.helper = this.helperFactory.create({ _stream: this }); } return this.helper.compute(_emberHtmlbarsStreamsUtils.getArrayValues(this.params), _emberHtmlbarsStreamsUtils.getHashValues(this.hash)); }, deactivate: function () { this.super$deactivate(); if (this.helper) { this.helper.destroy(); this.helper = null; } }, super$deactivate: _emberHtmlbarsStreamsStream.default.prototype.deactivate }); }); enifed('ember-htmlbars/streams/helper-instance', ['exports', 'ember-htmlbars/streams/stream', 'ember-htmlbars/streams/utils'], function (exports, _emberHtmlbarsStreamsStream, _emberHtmlbarsStreamsUtils) { 'use strict'; exports.default = _emberHtmlbarsStreamsStream.default.extend({ init: function (helper, params, hash, label) { this.helper = helper; this.params = params; this.hash = hash; this.linkable = true; this.label = label; }, compute: function () { return this.helper.compute(_emberHtmlbarsStreamsUtils.getArrayValues(this.params), _emberHtmlbarsStreamsUtils.getHashValues(this.hash)); } }); }); enifed('ember-htmlbars/streams/key-stream', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/observer', 'ember-htmlbars/streams/stream', 'ember-htmlbars/streams/utils'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalObserver, _emberHtmlbarsStreamsStream, _emberHtmlbarsStreamsUtils) { 'use strict'; function labelFor(source, key) { return source.label ? source.label + '.' + key : key; } exports.default = _emberHtmlbarsStreamsStream.default.extend({ init: function (source, key) { _emberMetalDebug.assert('KeyStream error: source must be a stream', _emberHtmlbarsStreamsUtils.isStream(source)); // TODO: This isn't necessary. _emberMetalDebug.assert('KeyStream error: key must be a non-empty string', typeof key === 'string' && key.length > 0); _emberMetalDebug.assert('KeyStream error: key must not have a \'.\'', key.indexOf('.') === -1); var label = labelFor(source, key); this.path = label; this.observedObject = null; this.key = key; this.sourceDep = this.addMutableDependency(source); this.label = label; }, compute: function () { var object = this.sourceDep.getValue(); var type = typeof object; if (!object || type === 'boolean') { return; } if (type === 'object') { return _emberMetalProperty_get.get(object, this.key); } return object[this.key]; }, setValue: function (value) { var object = this.sourceDep.getValue(); if (object) { _emberMetalProperty_set.set(object, this.key, value); } }, setSource: function (source) { this.sourceDep.replace(source); this.notify(); }, _super$revalidate: _emberHtmlbarsStreamsStream.default.prototype.revalidate, revalidate: function (value) { this._super$revalidate(value); var object = this.sourceDep.getValue(); if (object !== this.observedObject) { this._clearObservedObject(); if (object && typeof object === 'object') { _emberMetalObserver.addObserver(object, this.key, this, this.notify); this.observedObject = object; } } }, _super$deactivate: _emberHtmlbarsStreamsStream.default.prototype.deactivate, _clearObservedObject: function () { if (this.observedObject) { _emberMetalObserver.removeObserver(this.observedObject, this.key, this, this.notify); this.observedObject = null; } }, deactivate: function () { this._super$deactivate(); this._clearObservedObject(); } }); }); enifed('ember-htmlbars/streams/proxy-stream', ['exports', 'ember-runtime/system/object', 'ember-htmlbars/streams/stream'], function (exports, _emberRuntimeSystemObject, _emberHtmlbarsStreamsStream) { 'use strict'; var ProxyStream = _emberHtmlbarsStreamsStream.default.extend({ init: function (source, label) { this.label = label; this.sourceDep = this.addMutableDependency(source); }, compute: function () { return this.sourceDep.getValue(); }, setValue: function (value) { this.sourceDep.setValue(value); }, setSource: function (source) { var didChange = this.sourceDep.replace(source); if (didChange || !(source instanceof _emberRuntimeSystemObject.default)) { // If the source changed, we must notify. If the source is not // an Ember.Object, we must also notify, because it could have // interior mutability that is otherwise not being observed. this.notify(); } } }); ProxyStream.extend = _emberHtmlbarsStreamsStream.default.extend; exports.default = ProxyStream; }); enifed('ember-htmlbars/streams/should_display', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-runtime/utils', 'ember-htmlbars/streams/stream', 'ember-htmlbars/streams/utils'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberRuntimeUtils, _emberHtmlbarsStreamsStream, _emberHtmlbarsStreamsUtils) { 'use strict'; exports.default = shouldDisplay; var ShouldDisplayStream = _emberHtmlbarsStreamsStream.default.extend({ init: function (predicate) { _emberMetalDebug.assert('ShouldDisplayStream error: predicate must be a stream', _emberHtmlbarsStreamsUtils.isStream(predicate)); var isTruthy = predicate.get('isTruthy'); this.init(); this.predicate = predicate; this.isTruthy = isTruthy; this.lengthDep = null; this.addDependency(predicate); this.addDependency(isTruthy); }, compute: function () { var truthy = _emberHtmlbarsStreamsUtils.read(this.isTruthy); if (typeof truthy === 'boolean') { return truthy; } if (this.lengthDep) { return this.lengthDep.getValue() !== 0; } else { return !!_emberHtmlbarsStreamsUtils.read(this.predicate); } }, revalidate: function () { if (_emberRuntimeUtils.isArray(_emberHtmlbarsStreamsUtils.read(this.predicate))) { if (!this.lengthDep) { this.lengthDep = this.addMutableDependency(this.predicate.get('length')); } } else { if (this.lengthDep) { this.lengthDep.destroy(); this.lengthDep = null; } } } }); function shouldDisplay(predicate) { if (_emberHtmlbarsStreamsUtils.isStream(predicate)) { return new ShouldDisplayStream(predicate); } var type = typeof predicate; if (type === 'boolean') { return predicate; } if (type && type === 'object' && predicate !== null) { var isTruthy = _emberMetalProperty_get.get(predicate, 'isTruthy'); if (typeof isTruthy === 'boolean') { return isTruthy; } } if (_emberRuntimeUtils.isArray(predicate)) { return _emberMetalProperty_get.get(predicate, 'length') !== 0; } else { return !!predicate; } } }); enifed('ember-htmlbars/streams/stream', ['exports', 'ember-metal/assign', 'ember-metal/debug', 'ember-metal/path_cache', 'ember-metal/observer', 'ember-htmlbars/streams/utils', 'ember-metal/empty_object', 'ember-htmlbars/streams/subscriber', 'ember-htmlbars/streams/dependency', 'ember-metal/utils', 'require', 'ember-metal/symbol'], function (exports, _emberMetalAssign, _emberMetalDebug, _emberMetalPath_cache, _emberMetalObserver, _emberHtmlbarsStreamsUtils, _emberMetalEmpty_object, _emberHtmlbarsStreamsSubscriber, _emberHtmlbarsStreamsDependency, _emberMetalUtils, _require, _emberMetalSymbol) { 'use strict'; exports.default = BasicStream; exports.wrap = wrap; var IS_STREAM = _emberMetalSymbol.default('IS_STREAM'); exports.IS_STREAM = IS_STREAM; /** @module ember-metal */ /** @private @class Stream @namespace Ember.stream @constructor */ function BasicStream(label) { this._init(label); } // lazy var KeyStream = undefined; var ProxyMixin = undefined; BasicStream.prototype = { _init: function (label) { this[IS_STREAM] = true; this.label = makeLabel(label); this.isActive = false; this.isDirty = true; this.isDestroyed = false; this.cache = undefined; this.children = undefined; this.subscriberHead = null; this.subscriberTail = null; this.dependencyHead = null; this.dependencyTail = null; this.observedProxy = null; this.__ember_meta__ = null; this[_emberMetalUtils.GUID_KEY] = null; }, _makeChildStream: function (key) { KeyStream = KeyStream || _require.default('ember-htmlbars/streams/key-stream').default; return new KeyStream(this, key); }, removeChild: function (key) { delete this.children[key]; }, getKey: function (key) { if (this.children === undefined) { this.children = new _emberMetalEmpty_object.default(); } var keyStream = this.children[key]; if (keyStream === undefined) { keyStream = this._makeChildStream(key); this.children[key] = keyStream; } return keyStream; }, get: function (path) { var firstKey = _emberMetalPath_cache.getFirstKey(path); var tailPath = _emberMetalPath_cache.getTailPath(path); if (this.children === undefined) { this.children = new _emberMetalEmpty_object.default(); } var keyStream = this.children[firstKey]; if (keyStream === undefined) { keyStream = this._makeChildStream(firstKey, path); this.children[firstKey] = keyStream; } if (tailPath === undefined) { return keyStream; } else { return keyStream.get(tailPath); } }, value: function () { // TODO: Ensure value is never called on a destroyed stream // so that we can uncomment this assertion. // // assert("Stream error: value was called after the stream was destroyed", !this.isDestroyed); // TODO: Remove this block. This will require ensuring we are // not treating streams as "volatile" anywhere. if (!this.isActive) { this.isDirty = true; } var willRevalidate = false; if (!this.isActive && this.subscriberHead) { this.activate(); willRevalidate = true; } if (this.isDirty) { if (this.isActive) { willRevalidate = true; } this.cache = this.compute(); this.isDirty = false; } if (willRevalidate) { this.revalidate(this.cache); } return this.cache; }, addMutableDependency: function (object) { var dependency = new _emberHtmlbarsStreamsDependency.default(this, object); if (this.isActive) { dependency.subscribe(); } if (this.dependencyHead === null) { this.dependencyHead = this.dependencyTail = dependency; } else { var tail = this.dependencyTail; tail.next = dependency; dependency.prev = tail; this.dependencyTail = dependency; } return dependency; }, addDependency: function (object) { if (_emberHtmlbarsStreamsUtils.isStream(object)) { this.addMutableDependency(object); } }, subscribeDependencies: function () { var dependency = this.dependencyHead; while (dependency) { var next = dependency.next; dependency.subscribe(); dependency = next; } }, unsubscribeDependencies: function () { var dependency = this.dependencyHead; while (dependency) { var next = dependency.next; dependency.unsubscribe(); dependency = next; } }, maybeDeactivate: function () { if (!this.subscriberHead && this.isActive) { this.isActive = false; this.unsubscribeDependencies(); this.deactivate(); } }, activate: function () { this.isActive = true; this.subscribeDependencies(); }, revalidate: function (value) { if (value !== this.observedProxy) { this._clearObservedProxy(); ProxyMixin = ProxyMixin || _require.default('ember-runtime/mixins/-proxy').default; if (ProxyMixin.detect(value)) { _emberMetalObserver.addObserver(value, 'content', this, this.notify); this.observedProxy = value; } } }, _clearObservedProxy: function () { if (this.observedProxy) { _emberMetalObserver.removeObserver(this.observedProxy, 'content', this, this.notify); this.observedProxy = null; } }, deactivate: function () { this._clearObservedProxy(); }, compute: function () { throw new Error('Stream error: compute not implemented'); }, setValue: function () { throw new Error('Stream error: setValue not implemented'); }, notify: function () { this.notifyExcept(); }, notifyExcept: function (callbackToSkip, contextToSkip) { if (!this.isDirty) { this.isDirty = true; this.notifySubscribers(callbackToSkip, contextToSkip); } }, subscribe: function (callback, context) { _emberMetalDebug.assert('You tried to subscribe to a stream but the callback provided was not a function.', typeof callback === 'function'); var subscriber = new _emberHtmlbarsStreamsSubscriber.default(callback, context, this); if (this.subscriberHead === null) { this.subscriberHead = this.subscriberTail = subscriber; } else { var tail = this.subscriberTail; tail.next = subscriber; subscriber.prev = tail; this.subscriberTail = subscriber; } var stream = this; return function (prune) { subscriber.removeFrom(stream); if (prune) { stream.prune(); } }; }, prune: function () { if (this.subscriberHead === null) { this.destroy(true); } }, unsubscribe: function (callback, context) { var subscriber = this.subscriberHead; while (subscriber) { var next = subscriber.next; if (subscriber.callback === callback && subscriber.context === context) { subscriber.removeFrom(this); } subscriber = next; } }, notifySubscribers: function (callbackToSkip, contextToSkip) { var subscriber = this.subscriberHead; while (subscriber) { var next = subscriber.next; var callback = subscriber.callback; var context = subscriber.context; subscriber = next; if (callback === callbackToSkip && context === contextToSkip) { continue; } if (context === undefined) { callback(this); } else { callback.call(context, this); } } }, destroy: function (prune) { if (!this.isDestroyed) { this.isDestroyed = true; this.subscriberHead = this.subscriberTail = null; this.maybeDeactivate(); var dependencies = this.dependencies; if (dependencies) { for (var i = 0; i < dependencies.length; i++) { dependencies[i](prune); } } return true; } } }; BasicStream.extend = function (object) { var Child = function () { this._init(); this.init.apply(this, arguments); _emberMetalDebug.debugSeal(this); }; Child.prototype = Object.create(this.prototype); _emberMetalAssign.default(Child.prototype, object); Child.extend = BasicStream.extend; return Child; }; var Stream = BasicStream.extend({ init: function (fn, label) { this._compute = fn; this.label = label; }, compute: function () { return this._compute(); } }); exports.Stream = Stream; function wrap(value, Kind, param) { if (_emberHtmlbarsStreamsUtils.isStream(value)) { return value; } else { return new Kind(value, param); } } function makeLabel(label) { if (label === undefined) { return '(no label)'; } else { return label; } } }); enifed('ember-htmlbars/streams/subscriber', ['exports', 'ember-metal/assign'], function (exports, _emberMetalAssign) { 'use strict'; exports.default = Subscriber; /** @module ember-metal */ /** @private @class Subscriber @namespace Ember.streams @constructor */ function Subscriber(callback, context) { this.next = null; this.prev = null; this.callback = callback; this.context = context; } _emberMetalAssign.default(Subscriber.prototype, { removeFrom: function (stream) { var next = this.next; var prev = this.prev; if (prev) { prev.next = next; } else { stream.subscriberHead = next; } if (next) { next.prev = prev; } else { stream.subscriberTail = prev; } stream.maybeDeactivate(); } }); }); enifed('ember-htmlbars/streams/utils', ['exports', 'ember-htmlbars/hooks/get-value', 'ember-metal/debug', 'ember-htmlbars/streams/stream', 'ember-metal/property_get', 'ember-runtime/mixins/controller'], function (exports, _emberHtmlbarsHooksGetValue, _emberMetalDebug, _emberHtmlbarsStreamsStream, _emberMetalProperty_get, _emberRuntimeMixinsController) { 'use strict'; exports.getArrayValues = getArrayValues; exports.getHashValues = getHashValues; exports.isStream = isStream; exports.subscribe = subscribe; exports.unsubscribe = unsubscribe; exports.read = read; exports.readArray = readArray; exports.readHash = readHash; exports.scanArray = scanArray; exports.scanHash = scanHash; exports.labelsFor = labelsFor; exports.labelsForObject = labelsForObject; exports.labelFor = labelFor; exports.or = or; exports.addDependency = addDependency; exports.zip = zip; exports.zipHash = zipHash; exports.chain = chain; exports.setValue = setValue; exports.readViewFactory = readViewFactory; exports.readUnwrappedModel = readUnwrappedModel; // We don't want to leak mutable cells into helpers, which // are pure functions that can only work with values. function getArrayValues(params) { var out = new Array(params.length); for (var i = 0; i < params.length; i++) { out[i] = _emberHtmlbarsHooksGetValue.default(params[i]); } return out; } function getHashValues(hash) { var out = {}; for (var prop in hash) { out[prop] = _emberHtmlbarsHooksGetValue.default(hash[prop]); } return out; } /* Check whether an object is a stream or not. @private @for Ember.stream @function isStream @param {Object|Stream} object Object to check whether it is a stream. @return {Boolean} `true` if the object is a stream, `false` otherwise. */ function isStream(object) { return object && object[_emberHtmlbarsStreamsStream.IS_STREAM]; } /* A method of subscribing to a stream which is safe for use with a non-stream object. If a non-stream object is passed, the function does nothing. @public @for Ember.stream @function subscribe @param {Object|Stream} object Object or stream to potentially subscribe to. @param {Function} callback Function to run when stream value changes. @param {Object} [context] the callback will be executed with this context if it is provided. */ function subscribe(object, callback, context) { if (object && object[_emberHtmlbarsStreamsStream.IS_STREAM]) { return object.subscribe(callback, context); } } /* A method of unsubscribing from a stream which is safe for use with a non-stream object. If a non-stream object is passed, the function does nothing. @private @for Ember.stream @function unsubscribe @param {Object|Stream} object Object or stream to potentially unsubscribe from. @param {Function} callback Function originally passed to `subscribe()`. @param {Object} [context] Object originally passed to `subscribe()`. */ function unsubscribe(object, callback, context) { if (object && object[_emberHtmlbarsStreamsStream.IS_STREAM]) { object.unsubscribe(callback, context); } } /* Retrieve the value of a stream, or in the case where a non-stream object is passed, return the object itself. @private @for Ember.stream @function read @param {Object|Stream} object Object to return the value of. @return The stream's current value, or the non-stream object itself. */ function read(object) { if (object && object[_emberHtmlbarsStreamsStream.IS_STREAM]) { return object.value(); } else { return object; } } /* Map an array, replacing any streams with their values. @private @for Ember.stream @function readArray @param {Array} array The array to read values from @return {Array} A new array of the same length with the values of non-stream objects mapped from their original positions untouched, and the values of stream objects retaining their original position and replaced with the stream's current value. */ function readArray(array) { var ret = new Array(array.length); for (var i = 0; i < array.length; i++) { ret[i] = read(array[i]); } return ret; } /* Map a hash, replacing any stream property values with the current value of that stream. @private @for Ember.stream @function readHash @param {Object} object The hash to read keys and values from. @return {Object} A new object with the same keys as the passed object. The property values in the new object are the original values in the case of non-stream objects, and the streams' current values in the case of stream objects. */ function readHash(object) { var ret = {}; for (var key in object) { ret[key] = read(object[key]); } return ret; } /* Check whether an array contains any stream values. @private @for Ember.stream @function scanArray @param {Array} array Array given to a handlebars helper. @return {Boolean} `true` if the array contains a stream/bound value, `false` otherwise. */ function scanArray(array) { var containsStream = false; for (var i = 0; i < array.length; i++) { if (isStream(array[i])) { containsStream = true; break; } } return containsStream; } /* Check whether a hash has any stream property values. @private @for Ember.stream @function scanHash @param {Object} hash "hash" argument given to a handlebars helper. @return {Boolean} `true` if the object contains a stream/bound value, `false` otherwise. */ function scanHash(hash) { var containsStream = false; for (var prop in hash) { if (isStream(hash[prop])) { containsStream = true; break; } } return containsStream; } function labelsFor(streams) { var labels = []; for (var i = 0; i < streams.length; i++) { var stream = streams[i]; labels.push(labelFor(stream)); } return labels; } function labelsForObject(streams) { var labels = []; for (var prop in streams) { labels.push(prop + ': ' + inspect(streams[prop])); } return labels.length ? '{ ' + labels.join(', ') + ' }' : '{}'; } function labelFor(maybeStream) { if (isStream(maybeStream)) { var stream = maybeStream; return typeof stream.label === 'function' ? stream.label() : stream.label; } else { return inspect(maybeStream); } } function inspect(value) { switch (typeof value) { case 'string': return '"' + value + '"'; case 'object': return '{ ... }'; case 'function': return 'function() { ... }'; default: return String(value); } } function or(first, second) { var stream = new _emberHtmlbarsStreamsStream.Stream(function () { return first.value() || second.value(); }, function () { return labelFor(first) + ' || ' + labelFor(second); }); stream.addDependency(first); stream.addDependency(second); return stream; } function addDependency(stream, dependency) { _emberMetalDebug.assert('Cannot add a stream as a dependency to a non-stream', isStream(stream) || !isStream(dependency)); if (isStream(stream)) { stream.addDependency(dependency); } } function zip(streams, callback, label) { _emberMetalDebug.assert('Must call zip with a label', !!label); var stream = new _emberHtmlbarsStreamsStream.Stream(function () { var array = readArray(streams); return callback ? callback(array) : array; }, function () { return label + '(' + labelsFor(streams) + ')'; }); for (var i = 0; i < streams.length; i++) { stream.addDependency(streams[i]); } return stream; } function zipHash(object, callback, label) { _emberMetalDebug.assert('Must call zipHash with a label', !!label); var stream = new _emberHtmlbarsStreamsStream.Stream(function () { var hash = readHash(object); return callback ? callback(hash) : hash; }, function () { return label + '(' + labelsForObject(object) + ')'; }); for (var prop in object) { stream.addDependency(object[prop]); } return stream; } /** Generate a new stream by providing a source stream and a function that can be used to transform the stream's value. In the case of a non-stream object, returns the result of the function. The value to transform would typically be available to the function you pass to `chain()` via scope. For example: ```javascript let source = ...; // stream returning a number // or a numeric (non-stream) object let result = chain(source, function() { let currentValue = read(source); return currentValue + 1; }); ``` In the example, result is a stream if source is a stream, or a number of source was numeric. @private @for Ember.stream @function chain @param {Object|Stream} value A stream or non-stream object. @param {Function} fn Function to be run when the stream value changes, or to be run once in the case of a non-stream object. @return {Object|Stream} In the case of a stream `value` parameter, a new stream that will be updated with the return value of the provided function `fn`. In the case of a non-stream object, the return value of the provided function `fn`. */ function chain(value, fn, label) { _emberMetalDebug.assert('Must call chain with a label', !!label); if (isStream(value)) { var stream = new _emberHtmlbarsStreamsStream.Stream(fn, function () { return label + '(' + labelFor(value) + ')'; }); stream.addDependency(value); return stream; } else { return fn(); } } function setValue(object, value) { if (object && object[_emberHtmlbarsStreamsStream.IS_STREAM]) { object.setValue(value); } } function readViewFactory(object, owner) { var value = read(object); var viewClass = undefined; if (typeof value === 'string') { _emberMetalDebug.assert('View requires an owner to resolve views not passed in through the context', !!owner); viewClass = owner._lookupFactory('view:' + value); } else { viewClass = value; } _emberMetalDebug.assert(value + ' must be a subclass or an instance of Ember.View, not ' + viewClass, (function (viewClass) { return viewClass && (viewClass.isViewFactory || viewClass.isView || viewClass.isComponentFactory || viewClass.isComponent); })(viewClass)); return viewClass; } function readUnwrappedModel(object) { if (isStream(object)) { var result = object.value(); // If the path is exactly `controller` then we don't unwrap it. if (object.label !== 'controller') { while (_emberRuntimeMixinsController.default.detect(result)) { result = _emberMetalProperty_get.get(result, 'model'); } } return result; } else { return object; } } }); enifed('ember-htmlbars/system/build-component-template', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'htmlbars-runtime', 'htmlbars-util/template-utils', 'ember-htmlbars/hooks/get-value', 'ember-htmlbars/streams/utils'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _htmlbarsRuntime, _htmlbarsUtilTemplateUtils, _emberHtmlbarsHooksGetValue, _emberHtmlbarsStreamsUtils) { 'use strict'; exports.default = buildComponentTemplate; exports.buildHTMLTemplate = buildHTMLTemplate; function buildComponentTemplate(_ref, attrs, content) { var component = _ref.component; var tagName = _ref.tagName; var layout = _ref.layout; var outerAttrs = _ref.outerAttrs; if (component === undefined) { component = null; } var blockToRender = undefined, meta = undefined; if (layout && layout.raw) { var yieldTo = createContentBlocks(content.templates, content.scope, content.self, component); blockToRender = createLayoutBlock(layout.raw, yieldTo, content.self, component, attrs); meta = layout.raw.meta; } else if (content.templates && content.templates.default) { blockToRender = createContentBlock(content.templates.default, content.scope, content.self, component); meta = content.templates.default.meta; } if (component) { tagName = tagName || tagNameFor(component); // If this is not a tagless component, we need to create the wrapping // element. We use `manualElement` to create a template that represents // the wrapping element and yields to the previous block. if (tagName !== '') { var attributes = normalizeComponentAttributes(component, attrs); var elementTemplate = _htmlbarsRuntime.internal.manualElement(tagName, attributes); elementTemplate.meta = meta; blockToRender = createElementBlock(elementTemplate, blockToRender, component); } _emberMetalDebug.assert('You cannot use `classNameBindings` on a tag-less component: ' + component.toString(), (function () { var _component = component; var classNameBindings = _component.classNameBindings; return tagName !== '' || !classNameBindings || classNameBindings.length === 0; })()); _emberMetalDebug.assert('You cannot use `elementId` on a tag-less component: ' + component.toString(), (function () { var _component2 = component; var elementId = _component2.elementId; return tagName !== '' || attrs.id === elementId || !elementId && elementId !== ''; })()); _emberMetalDebug.assert('You cannot use `attributeBindings` on a tag-less component: ' + component.toString(), (function () { var _component3 = component; var attributeBindings = _component3.attributeBindings; return tagName !== '' || !attributeBindings || attributeBindings.length === 0; })()); } // tagName is one of: // * `undefined` if no component is present // * the falsy value "" if set explicitly on the component // * an actual tagName set explicitly on the component return { createdElement: !!tagName, block: blockToRender }; } function buildHTMLTemplate(tagName, _attrs, content) { var attrs = {}; for (var prop in _attrs) { var val = _attrs[prop]; if (typeof val === 'string') { attrs[prop] = val; } else { attrs[prop] = _htmlbarsUtilTemplateUtils.buildStatement('value', val); } } var childTemplate = content.templates.default; var elementTemplate = _htmlbarsRuntime.internal.manualElement(tagName, attrs, childTemplate.isEmpty); if (childTemplate.isEmpty) { return blockFor(elementTemplate, { scope: content.scope }); } else { var blockToRender = blockFor(content.templates.default, content); return blockFor(elementTemplate, { yieldTo: blockToRender, scope: content.scope }); } } function blockFor(template, options) { _emberMetalDebug.assert('BUG: Must pass a template to blockFor', !!template); return _htmlbarsRuntime.internal.blockFor(_htmlbarsRuntime.render, template, options); } function createContentBlock(template, scope, self, component) { _emberMetalDebug.assert('BUG: buildComponentTemplate can take a scope or a self, but not both', !(scope && self)); return blockFor(template, { scope: scope, self: self, options: { view: component } }); } function createContentBlocks(templates, scope, self, component) { if (!templates) { return; } var output = {}; for (var _name in templates) { if (templates.hasOwnProperty(_name)) { var template = templates[_name]; if (template) { output[_name] = createContentBlock(templates[_name], scope, self, component); } } } return output; } function createLayoutBlock(template, yieldTo, self, component, attrs) { return blockFor(template, { yieldTo: yieldTo, // If we have an old-style Controller with a template it will be // passed as our `self` argument, and it should be the context for // the template. Otherwise, we must have a real Component and it // should be its own template context. self: self || component, options: { view: component, attrs: attrs } }); } function createElementBlock(template, yieldTo, component) { return blockFor(template, { yieldTo: yieldTo, self: component, options: { view: component } }); } function tagNameFor(view) { var tagName = view.tagName; if (tagName === null || tagName === undefined) { tagName = 'div'; } return tagName; } // Takes a component and builds a normalized set of attribute // bindings consumable by HTMLBars' `attribute` hook. function normalizeComponentAttributes(component, attrs) { var normalized = {}; var attributeBindings = component.attributeBindings; if (attrs.id && _emberHtmlbarsHooksGetValue.default(attrs.id)) { // Do not allow binding to the `id` normalized.id = _emberHtmlbarsHooksGetValue.default(attrs.id); component.elementId = normalized.id; } else { normalized.id = component.elementId; } if (attributeBindings) { for (var i = 0; i < attributeBindings.length; i++) { var attr = attributeBindings[i]; var colonIndex = attr.indexOf(':'); var attrName = undefined, expression = undefined; if (colonIndex !== -1) { var attrProperty = attr.substring(0, colonIndex); attrName = attr.substring(colonIndex + 1); expression = _htmlbarsUtilTemplateUtils.buildStatement('get', attrProperty); } else if (attrs[attr]) { // TODO: For compatibility with 1.x, we probably need to `set` // the component's attribute here if it is a CP, but we also // probably want to suspend observers and allow the // willUpdateAttrs logic to trigger observers at the correct time. attrName = attr; expression = _htmlbarsUtilTemplateUtils.buildStatement('value', attrs[attr]); } else { attrName = attr; expression = _htmlbarsUtilTemplateUtils.buildStatement('get', attr); } _emberMetalDebug.assert('You cannot use class as an attributeBinding, use classNameBindings instead.', attrName !== 'class'); normalized[attrName] = expression; } } normalized.role = normalized.role || _htmlbarsUtilTemplateUtils.buildStatement('get', 'ariaRole'); if (attrs.tagName) { component.tagName = attrs.tagName; } var normalizedClass = normalizeClass(component, attrs); if (normalizedClass) { normalized.class = normalizedClass; } if (_emberMetalProperty_get.get(component, 'isVisible') === false) { var hiddenStyle = _htmlbarsUtilTemplateUtils.buildStatement('subexpr', '-html-safe', ['display: none;'], []); var existingStyle = normalized.style; if (existingStyle) { normalized.style = _htmlbarsUtilTemplateUtils.buildStatement('subexpr', 'concat', [existingStyle, ' ', hiddenStyle], []); } else { normalized.style = hiddenStyle; } } return normalized; } function normalizeClass(component, attrs) { var normalizedClass = []; var classNames = _emberMetalProperty_get.get(component, 'classNames'); var classNameBindings = _emberMetalProperty_get.get(component, 'classNameBindings'); if (attrs.class) { if (_emberHtmlbarsStreamsUtils.isStream(attrs.class)) { normalizedClass.push(_htmlbarsUtilTemplateUtils.buildStatement('subexpr', '-normalize-class', [_htmlbarsUtilTemplateUtils.buildStatement('value', attrs.class.path), _htmlbarsUtilTemplateUtils.buildStatement('value', attrs.class)], [])); } else { normalizedClass.push(attrs.class); } } if (attrs.classBinding) { normalizeClasses(attrs.classBinding.split(' '), normalizedClass); } if (classNames) { for (var i = 0; i < classNames.length; i++) { normalizedClass.push(classNames[i]); } } if (classNameBindings) { normalizeClasses(classNameBindings, normalizedClass); } if (normalizeClass.length) { return _htmlbarsUtilTemplateUtils.buildStatement('subexpr', '-join-classes', normalizedClass, []); } } function normalizeClasses(classes, output, streamBasePath) { for (var i = 0; i < classes.length; i++) { var className = classes[i]; _emberMetalDebug.assert('classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. [\'foo\', \':bar\']', className.indexOf(' ') === -1); var _className$split = className.split(':'); var propName = _className$split[0]; var activeClass = _className$split[1]; var inactiveClass = _className$split[2]; // Legacy :class microsyntax for static class names if (propName === '') { output.push(activeClass); continue; } output.push(_htmlbarsUtilTemplateUtils.buildStatement('subexpr', '-normalize-class', [ // params _htmlbarsUtilTemplateUtils.buildStatement('value', propName), _htmlbarsUtilTemplateUtils.buildStatement('get', propName)], [ // hash 'activeClass', activeClass, 'inactiveClass', inactiveClass])); } } }); enifed('ember-htmlbars/system/dom-helper', ['exports', 'dom-helper', 'ember-htmlbars/morphs/morph', 'ember-htmlbars/morphs/attr-morph'], function (exports, _domHelper, _emberHtmlbarsMorphsMorph, _emberHtmlbarsMorphsAttrMorph) { 'use strict'; exports.default = EmberDOMHelper; function EmberDOMHelper(_document) { _domHelper.default.call(this, _document); } var proto = EmberDOMHelper.prototype = Object.create(_domHelper.default.prototype); proto.MorphClass = _emberHtmlbarsMorphsMorph.default; proto.AttrMorphClass = _emberHtmlbarsMorphsAttrMorph.default; }); enifed('ember-htmlbars/system/instrumentation-support', ['exports', 'ember-metal/instrumentation'], function (exports, _emberMetalInstrumentation) { 'use strict'; exports.instrument = instrument; /** Provides instrumentation for node managers. Wrap your node manager's render and re-render methods with this function. @param {Object} component Component or View instance (optional). @param {Function} callback The function to instrument. @param {Object} context The context to call the function with. @return {Object} Return value from the invoked callback. @private */ function instrument(component, callback, context) { var instrumentName = undefined, val = undefined, details = undefined, end = undefined; // Only instrument if there's at least one subscriber. if (_emberMetalInstrumentation.subscribers.length) { if (component) { instrumentName = component.instrumentName; } else { instrumentName = 'node'; } details = {}; if (component) { component.instrumentDetails(details); } end = _emberMetalInstrumentation._instrumentStart('render.' + instrumentName, function viewInstrumentDetails() { return details; }); val = callback.call(context); if (end) { end(); } return val; } else { return callback.call(context); } } }); enifed('ember-htmlbars/system/invoke-helper', ['exports', 'ember-metal/debug', 'ember-htmlbars/streams/helper-instance', 'ember-htmlbars/streams/helper-factory', 'ember-htmlbars/streams/built-in-helper'], function (exports, _emberMetalDebug, _emberHtmlbarsStreamsHelperInstance, _emberHtmlbarsStreamsHelperFactory, _emberHtmlbarsStreamsBuiltInHelper) { 'use strict'; exports.buildHelperStream = buildHelperStream; function buildHelperStream(helper, params, hash, templates, env, scope, label) { var isAnyKindOfHelper = helper.isHelperInstance || helper.isHelperFactory; _emberMetalDebug.assert('Helpers may not be used in the block form, for example {{#my-helper}}{{/my-helper}}. Please use a component, or alternatively use the helper in combination with a built-in Ember helper, for example {{#if (my-helper)}}{{/if}}.', !(isAnyKindOfHelper && templates && templates.template && templates.template.meta)); _emberMetalDebug.assert('Helpers may not be used in the element form, for example <div {{my-helper}}>.', !(isAnyKindOfHelper && templates && templates.element)); if (helper.isHelperFactory) { return new _emberHtmlbarsStreamsHelperFactory.default(helper, params, hash, label); } else if (helper.isHelperInstance) { return new _emberHtmlbarsStreamsHelperInstance.default(helper, params, hash, label); } else { templates = templates || { template: {}, inverse: {} }; return new _emberHtmlbarsStreamsBuiltInHelper.default(helper, params, hash, templates, env, scope, label); } } }); enifed('ember-htmlbars/system/lookup-helper', ['exports', 'ember-metal/debug', 'ember-metal/cache'], function (exports, _emberMetalDebug, _emberMetalCache) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.validateLazyHelperName = validateLazyHelperName; exports.findHelper = findHelper; exports.default = lookupHelper; var CONTAINS_DASH_CACHE = new _emberMetalCache.default(1000, function (key) { return key.indexOf('-') !== -1; }); exports.CONTAINS_DASH_CACHE = CONTAINS_DASH_CACHE; var CONTAINS_DOT_CACHE = new _emberMetalCache.default(1000, function (key) { return key.indexOf('.') !== -1; }); exports.CONTAINS_DOT_CACHE = CONTAINS_DOT_CACHE; function validateLazyHelperName(helperName, container, keywords) { return container && !(helperName in keywords); } /** Used to lookup/resolve handlebars helpers. The lookup order is: * Look for a registered helper * If a dash exists in the name: * Look for a helper registed in the container. * Use Ember.ComponentLookup to find an Ember.Component that resolves to the given name. @private @method resolveHelper @param {String} name The name of the helper to lookup. @return {Helper} */ function _findHelper(name, view, env, options) { var helper = env.helpers[name]; if (!helper) { var owner = env.owner; if (validateLazyHelperName(name, owner, env.hooks.keywords)) { var helperName = 'helper:' + name; // See https://github.com/emberjs/ember.js/issues/13071 // See https://bugs.chromium.org/p/v8/issues/detail?id=4839 var registered = owner.hasRegistration(helperName, options); if (registered) { helper = owner._lookupFactory(helperName, options); _emberMetalDebug.assert('Expected to find an Ember.Helper with the name ' + helperName + ', but found an object of type ' + typeof helper + ' instead.', helper.isHelperFactory || helper.isHelperInstance); } } } return helper; } function findHelper(name, view, env) { var options = {}; var moduleName = env.meta && env.meta.moduleName; if (moduleName) { options.source = 'template:' + moduleName; } var localHelper = _findHelper(name, view, env, options); // Local match found, use it. if (localHelper) { return localHelper; } // Fall back to global. return _findHelper(name, view, env); } function lookupHelper(name, view, env) { var helper = findHelper(name, view, env); _emberMetalDebug.assert('A helper named "' + name + '" could not be found', !!helper); return helper; } }); enifed('ember-htmlbars/system/render-env', ['exports', 'ember-htmlbars/env', 'ember-htmlbars/renderer', 'container/owner'], function (exports, _emberHtmlbarsEnv, _emberHtmlbarsRenderer, _containerOwner) { 'use strict'; exports.default = RenderEnv; function RenderEnv(options) { this.lifecycleHooks = options.lifecycleHooks || []; this.renderedViews = options.renderedViews || []; this.renderedNodes = options.renderedNodes || new _emberHtmlbarsRenderer.MorphSet(); this.hasParentOutlet = options.hasParentOutlet || false; this.view = options.view; this.outletState = options.outletState; this.owner = options.owner; this.renderer = options.renderer; this.dom = options.dom; this.meta = options.meta; this.hooks = _emberHtmlbarsEnv.default.hooks; this.helpers = _emberHtmlbarsEnv.default.helpers; this.useFragmentCache = _emberHtmlbarsEnv.default.useFragmentCache; this.destinedForDOM = this.renderer._destinedForDOM; } RenderEnv.build = function (view, meta) { return new RenderEnv({ view: view, outletState: view.outletState, owner: _containerOwner.getOwner(view), renderer: view.renderer, dom: view.renderer._dom, meta: meta }); }; RenderEnv.prototype.childWithMeta = function (meta) { return new RenderEnv({ view: this.view, outletState: this.outletState, owner: this.owner, renderer: this.renderer, dom: this.dom, lifecycleHooks: this.lifecycleHooks, renderedViews: this.renderedViews, renderedNodes: this.renderedNodes, hasParentOutlet: this.hasParentOutlet, meta: meta }); }; RenderEnv.prototype.childWithView = function (view) { var meta = arguments.length <= 1 || arguments[1] === undefined ? this.meta : arguments[1]; return new RenderEnv({ view: view, outletState: this.outletState, owner: this.owner, renderer: this.renderer, dom: this.dom, lifecycleHooks: this.lifecycleHooks, renderedViews: this.renderedViews, renderedNodes: this.renderedNodes, hasParentOutlet: this.hasParentOutlet, meta: meta }); }; RenderEnv.prototype.childWithOutletState = function (outletState) { var hasParentOutlet = arguments.length <= 1 || arguments[1] === undefined ? this.hasParentOutlet : arguments[1]; var meta = arguments.length <= 2 || arguments[2] === undefined ? this.meta : arguments[2]; return new RenderEnv({ view: this.view, outletState: outletState, owner: this.owner, renderer: this.renderer, dom: this.dom, lifecycleHooks: this.lifecycleHooks, renderedViews: this.renderedViews, renderedNodes: this.renderedNodes, hasParentOutlet: hasParentOutlet, meta: meta }); }; }); enifed('ember-htmlbars/system/render-view', ['exports', 'ember-htmlbars/node-managers/view-node-manager', 'ember-htmlbars/system/render-env'], function (exports, _emberHtmlbarsNodeManagersViewNodeManager, _emberHtmlbarsSystemRenderEnv) { 'use strict'; exports.renderHTMLBarsBlock = renderHTMLBarsBlock; // This function only gets called once per render of a "root view" (`appendTo`). Otherwise, // HTMLBars propagates the existing env and renders templates for a given render node. function renderHTMLBarsBlock(view, block, renderNode) { var meta = block && block.template && block.template.meta; var env = _emberHtmlbarsSystemRenderEnv.default.build(view, meta); view._env = env; _emberHtmlbarsNodeManagersViewNodeManager.createOrUpdateComponent(view, {}, null, renderNode, env); var nodeManager = new _emberHtmlbarsNodeManagersViewNodeManager.default(view, null, renderNode, block, view.tagName !== ''); nodeManager.render(env, {}); } }); enifed('ember-htmlbars/system/template', ['exports', 'htmlbars-runtime/hooks'], function (exports, _htmlbarsRuntimeHooks) { 'use strict'; exports.default = template; function template(templateSpec) { if (!templateSpec.render) { templateSpec = _htmlbarsRuntimeHooks.wrap(templateSpec); } templateSpec.isTop = true; templateSpec.isMethod = false; return templateSpec; } }); enifed("ember-htmlbars/templates/component", ["exports", "ember-htmlbars"], function (exports, _emberHtmlbars) { "use strict"; exports.default = _emberHtmlbars.template((function () { return { meta: {}, isEmpty: false, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "yield", ["loc", [null, [1, 0], [1, 9]]], 0, 0, 0, 0]], locals: [], templates: [] }; })()); }); enifed("ember-htmlbars/templates/empty", ["exports", "ember-htmlbars"], function (exports, _emberHtmlbars) { "use strict"; exports.default = _emberHtmlbars.template((function () { return { meta: {}, isEmpty: true, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); return el0; }, buildRenderNodes: function buildRenderNodes() { return []; }, statements: [], locals: [], templates: [] }; })()); }); enifed("ember-htmlbars/templates/link-to", ["exports", "ember-htmlbars"], function (exports, _emberHtmlbars) { "use strict"; exports.default = _emberHtmlbars.template((function () { var child0 = (function () { return { meta: {}, isEmpty: false, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "linkTitle", ["loc", [null, [1, 17], [1, 30]]], 0, 0, 0, 0]], locals: [], templates: [] }; })(); var child1 = (function () { return { meta: {}, isEmpty: false, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "yield", ["loc", [null, [1, 38], [1, 47]]], 0, 0, 0, 0]], locals: [], templates: [] }; })(); return { meta: {}, isEmpty: false, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "if", [["get", "linkTitle", ["loc", [null, [1, 6], [1, 15]]], 0, 0, 0, 0]], [], 0, 1, ["loc", [null, [1, 0], [1, 54]]]]], locals: [], templates: [child0, child1] }; })()); }); enifed("ember-htmlbars/templates/top-level-view", ["exports", "ember-htmlbars"], function (exports, _emberHtmlbars) { "use strict"; exports.default = _emberHtmlbars.template((function () { return { meta: {}, isEmpty: false, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "outlet", ["loc", [null, [1, 0], [1, 10]]], 0, 0, 0, 0]], locals: [], templates: [] }; })()); }); enifed('ember-htmlbars/utils/decode-each-key', ['exports', 'ember-metal/property_get', 'ember-metal/utils'], function (exports, _emberMetalProperty_get, _emberMetalUtils) { 'use strict'; exports.default = decodeEachKey; function identity(item) { var key = undefined; var type = typeof item; if (type === 'string' || type === 'number') { key = item; } else { key = _emberMetalUtils.guidFor(item); } return key; } function decodeEachKey(item, keyPath, index) { var key = undefined; switch (keyPath) { case '@index': key = index; break; case '@identity': key = identity(item); break; default: if (keyPath) { key = _emberMetalProperty_get.get(item, keyPath); } else { key = identity(item); } } if (typeof key === 'number') { key = String(key); } return key; } }); enifed('ember-htmlbars/utils/extract-positional-params', ['exports', 'ember-metal/debug', 'ember-htmlbars/streams/stream', 'ember-htmlbars/streams/utils'], function (exports, _emberMetalDebug, _emberHtmlbarsStreamsStream, _emberHtmlbarsStreamsUtils) { 'use strict'; exports.default = extractPositionalParams; exports.isRestPositionalParams = isRestPositionalParams; exports.processPositionalParams = processPositionalParams; function extractPositionalParams(renderNode, component, params, attrs) { var raiseAssertions = arguments.length <= 4 || arguments[4] === undefined ? true : arguments[4]; var positionalParams = component.positionalParams; if (positionalParams) { processPositionalParams(renderNode, positionalParams, params, attrs, raiseAssertions); } } function isRestPositionalParams(positionalParams) { return typeof positionalParams === 'string'; } function processPositionalParams(renderNode, positionalParams, params, attrs) { var raiseAssertions = arguments.length <= 4 || arguments[4] === undefined ? true : arguments[4]; var isRest = isRestPositionalParams(positionalParams); if (isRest) { processRestPositionalParameters(renderNode, positionalParams, params, attrs, raiseAssertions); } else { processNamedPositionalParameters(renderNode, positionalParams, params, attrs, raiseAssertions); } } function processNamedPositionalParameters(renderNode, positionalParams, params, attrs, raiseAssertions) { var limit = Math.min(params.length, positionalParams.length); for (var i = 0; i < limit; i++) { var param = params[i]; _emberMetalDebug.assert('You cannot specify both a positional param (at position ' + i + ') and the hash argument `' + positionalParams[i] + '`.', !(positionalParams[i] in attrs && raiseAssertions)); attrs[positionalParams[i]] = param; } } function processRestPositionalParameters(renderNode, positionalParamsName, params, attrs, raiseAssertions) { var nameInAttrs = (positionalParamsName in attrs); // when no params are used, do not override the specified `attrs.stringParamName` value if (params.length === 0 && nameInAttrs) { return; } // If there is already an attribute for that variable, do nothing _emberMetalDebug.assert('You cannot specify positional parameters and the hash argument `' + positionalParamsName + '`.', !(nameInAttrs && raiseAssertions)); var paramsStream = new _emberHtmlbarsStreamsStream.Stream(function () { return _emberHtmlbarsStreamsUtils.readArray(params.slice(0)); }, 'params'); attrs[positionalParamsName] = paramsStream; for (var i = 0; i < params.length; i++) { var param = params[i]; paramsStream.addDependency(param); } } }); enifed('ember-htmlbars/utils/is-component', ['exports', 'ember-htmlbars/system/lookup-helper', 'ember-htmlbars/keywords/closure-component', 'ember-htmlbars/streams/utils'], function (exports, _emberHtmlbarsSystemLookupHelper, _emberHtmlbarsKeywordsClosureComponent, _emberHtmlbarsStreamsUtils) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.default = isComponent; function hasComponentOrTemplate(owner, path, options) { return owner.hasRegistration('component:' + path, options) || owner.hasRegistration('template:components/' + path, options); } /* Given a path name, returns whether or not a component with that name was found in the container. */ function isComponent(env, scope, path) { var owner = env.owner; if (!owner) { return false; } if (typeof path === 'string') { if (_emberHtmlbarsSystemLookupHelper.CONTAINS_DOT_CACHE.get(path)) { var stream = env.hooks.get(env, scope, path); if (_emberHtmlbarsStreamsUtils.isStream(stream)) { var cell = stream.value(); if (_emberHtmlbarsKeywordsClosureComponent.isComponentCell(cell)) { return true; } } } if (!_emberHtmlbarsSystemLookupHelper.CONTAINS_DASH_CACHE.get(path)) { return false; } if (hasComponentOrTemplate(owner, path)) { return true; // global component found } else { var moduleName = env.meta && env.meta.moduleName; if (!moduleName) { // Without a source moduleName, we can not perform local lookups. return false; } var options = { source: 'template:' + moduleName }; return hasComponentOrTemplate(owner, path, options); } } } }); enifed('ember-htmlbars/utils/new-stream', ['exports', 'ember-htmlbars/streams/proxy-stream', 'ember-htmlbars/utils/subscribe'], function (exports, _emberHtmlbarsStreamsProxyStream, _emberHtmlbarsUtilsSubscribe) { 'use strict'; exports.default = newStream; function newStream(scope, key, newValue, renderNode, isSelf) { var stream = new _emberHtmlbarsStreamsProxyStream.default(newValue, isSelf ? '' : key); if (renderNode) { _emberHtmlbarsUtilsSubscribe.default(renderNode, scope, stream); } scope[key] = stream; } }); enifed("ember-htmlbars/utils/normalize-self", ["exports"], function (exports) { "use strict"; exports.default = normalizeSelf; function normalizeSelf(self) { if (self === undefined) { return null; } else { return self; } } }); enifed('ember-htmlbars/utils/string', ['exports', 'ember-metal/features', 'ember-metal/debug'], function (exports, _emberMetalFeatures, _emberMetalDebug) { /** @module ember @submodule ember-glimmer */ 'use strict'; exports.getSafeString = getSafeString; exports.escapeExpression = escapeExpression; exports.htmlSafe = htmlSafe; exports.isHTMLSafe = isHTMLSafe; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var SafeString = (function () { function SafeString(string) { _classCallCheck(this, SafeString); this.string = string; } SafeString.prototype.toString = function toString() { return '' + this.string; }; SafeString.prototype.toHTML = function toHTML() { return this.toString(); }; return SafeString; })(); exports.SafeString = SafeString; function getSafeString() { _emberMetalDebug.deprecate('Ember.Handlebars.SafeString is deprecated in favor of Ember.String.htmlSafe', !true, { id: 'ember-htmlbars.ember-handlebars-safestring', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_use-ember-string-htmlsafe-over-ember-handlebars-safestring' }); return SafeString; } var escape = { '&': '&', '<': '<', '>': '>', '"': '"', // jscs:disable "'": ''', // jscs:enable '`': '`', '=': '=' }; var possible = /[&<>"'`=]/; var badChars = /[&<>"'`=]/g; function escapeChar(chr) { return escape[chr]; } function escapeExpression(string) { if (typeof string !== 'string') { // don't escape SafeStrings, since they're already safe if (string && string.toHTML) { return string.toHTML(); } else if (string == null) { return ''; } else if (!string) { return string + ''; } // Force a string conversion as this will be done by the append regardless and // the regex test will do this transparently behind the scenes, causing issues if // an object's to string has escaped characters in it. string = '' + string; } if (!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); } /** Mark a string as safe for unescaped output with Ember templates. If you return HTML from a helper, use this function to ensure Ember's rendering layer does not escape the HTML. ```javascript Ember.String.htmlSafe('<div>someString</div>') ``` @method htmlSafe @for Ember.String @static @return {Handlebars.SafeString} A string that will not be HTML escaped by Handlebars. @public */ function htmlSafe(str) { if (str === null || str === undefined) { str = ''; } else if (typeof str !== 'string') { str = '' + str; } return new SafeString(str); } /** Detects if a string was decorated using `Ember.String.htmlSafe`. ```javascript var plainString = 'plain string', safeString = Ember.String.htmlSafe('<div>someValue</div>'); Ember.String.isHTMLSafe(plainString); // false Ember.String.isHTMLSafe(safeString); // true ``` @method isHTMLSafe @for Ember.String @static @return {Boolean} `true` if the string was decorated with `htmlSafe`, `false` otherwise. @public */ function isHTMLSafe(str) { return str && typeof str.toHTML === 'function'; } }); enifed('ember-htmlbars/utils/subscribe', ['exports', 'ember-htmlbars/streams/utils'], function (exports, _emberHtmlbarsStreamsUtils) { 'use strict'; exports.default = subscribe; function subscribe(node, env, scope, stream) { if (!_emberHtmlbarsStreamsUtils.isStream(stream)) { return; } var component = scope.getComponent(); var unsubscribers = node.streamUnsubscribers = node.streamUnsubscribers || []; unsubscribers.push(stream.subscribe(function () { node.isDirty = true; // Whenever a render node directly inside a component becomes // dirty, we want to invoke the willRenderElement and // didRenderElement lifecycle hooks. From the perspective of the // programming model, whenever anything in the DOM changes, a // "re-render" has occured. if (component && component._renderNode) { component._renderNode.isDirty = true; } if (node.getState().manager) { node.shouldReceiveAttrs = true; } // When the toplevelView (aka ownerView) is being torn // down (generally in tests), `ownerNode.emberView` will be // set to `null` (to prevent further work while tearing down) // so we need to guard against that case here var ownerView = node.ownerNode.emberView; if (ownerView) { ownerView.scheduleRevalidate(node, _emberHtmlbarsStreamsUtils.labelFor(stream)); } })); } }); enifed('ember-htmlbars/utils/update-scope', ['exports', 'ember-htmlbars/streams/proxy-stream', 'ember-htmlbars/utils/subscribe'], function (exports, _emberHtmlbarsStreamsProxyStream, _emberHtmlbarsUtilsSubscribe) { 'use strict'; exports.default = updateScope; function updateScope(scope, key, newValue, renderNode, isSelf) { var existing = scope[key]; if (existing) { existing.setSource(newValue); } else { var stream = new _emberHtmlbarsStreamsProxyStream.default(newValue, isSelf ? null : key); if (renderNode) { _emberHtmlbarsUtilsSubscribe.default(renderNode, scope, stream); } scope[key] = stream; } } }); enifed('ember-htmlbars/views/outlet', ['exports', 'ember-views/views/view', 'ember-htmlbars/templates/top-level-view', 'ember-views/mixins/template_support'], function (exports, _emberViewsViewsView, _emberHtmlbarsTemplatesTopLevelView, _emberViewsMixinsTemplate_support) { /** @module ember @submodule ember-templates */ 'use strict'; var CoreOutletView = _emberViewsViewsView.default.extend(_emberViewsMixinsTemplate_support.default, { defaultTemplate: _emberHtmlbarsTemplatesTopLevelView.default, init: function () { this._super(); this._outlets = []; }, setOutletState: function (state) { this.outletState = { main: state }; if (this._env) { this._env.outletState = this.outletState; } if (this.lastResult) { this.dirtyOutlets(); this._outlets = []; this.scheduleRevalidate(null, null); } }, dirtyOutlets: function () { // Dirty any render nodes that correspond to outlets for (var i = 0; i < this._outlets.length; i++) { this._outlets[i].isDirty = true; } } }); exports.CoreOutletView = CoreOutletView; var OutletView = CoreOutletView.extend({ tagName: '' }); exports.OutletView = OutletView; }); enifed('ember-metal/alias', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/error', 'ember-metal/properties', 'ember-metal/computed', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/dependent_keys'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalError, _emberMetalProperties, _emberMetalComputed, _emberMetalUtils, _emberMetalMeta, _emberMetalDependent_keys) { 'use strict'; exports.default = alias; exports.AliasedProperty = AliasedProperty; function alias(altKey) { return new AliasedProperty(altKey); } function AliasedProperty(altKey) { this.isDescriptor = true; this.altKey = altKey; this._dependentKeys = [altKey]; } AliasedProperty.prototype = Object.create(_emberMetalProperties.Descriptor.prototype); AliasedProperty.prototype.get = function AliasedProperty_get(obj, keyName) { return _emberMetalProperty_get.get(obj, this.altKey); }; AliasedProperty.prototype.set = function AliasedProperty_set(obj, keyName, value) { return _emberMetalProperty_set.set(obj, this.altKey, value); }; AliasedProperty.prototype.willWatch = function (obj, keyName) { _emberMetalDependent_keys.addDependentKeys(this, obj, keyName, _emberMetalMeta.meta(obj)); }; AliasedProperty.prototype.didUnwatch = function (obj, keyName) { _emberMetalDependent_keys.removeDependentKeys(this, obj, keyName, _emberMetalMeta.meta(obj)); }; AliasedProperty.prototype.setup = function (obj, keyName) { _emberMetalDebug.assert('Setting alias \'' + keyName + '\' on self', this.altKey !== keyName); var m = _emberMetalMeta.meta(obj); if (m.peekWatching(keyName)) { _emberMetalDependent_keys.addDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.teardown = function (obj, keyName) { var m = _emberMetalMeta.meta(obj); if (m.peekWatching(keyName)) { _emberMetalDependent_keys.removeDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.readOnly = function () { this.set = AliasedProperty_readOnlySet; return this; }; function AliasedProperty_readOnlySet(obj, keyName, value) { throw new _emberMetalError.default('Cannot set read-only property \'' + keyName + '\' on object: ' + _emberMetalUtils.inspect(obj)); } AliasedProperty.prototype.oneWay = function () { this.set = AliasedProperty_oneWaySet; return this; }; function AliasedProperty_oneWaySet(obj, keyName, value) { _emberMetalProperties.defineProperty(obj, keyName, null); return _emberMetalProperty_set.set(obj, keyName, value); } // Backwards compatibility with Ember Data. AliasedProperty.prototype._meta = undefined; AliasedProperty.prototype.meta = _emberMetalComputed.ComputedProperty.prototype.meta; }); enifed("ember-metal/assign", ["exports"], function (exports) { /** Copy properties from a source object to a target object. ```javascript var a = { first: 'Yehuda' }; var b = { last: 'Katz' }; var c = { company: 'Tilde Inc.' }; Ember.assign(a, b, c); // a === { first: 'Yehuda', last: 'Katz', company: 'Tilde Inc.' }, b === { last: 'Katz' }, c === { company: 'Tilde Inc.' } ``` @method assign @for Ember @param {Object} original The object to assign into @param {Object} ...args The objects to copy properties from @return {Object} @public */ "use strict"; exports.default = assign; function assign(original) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } for (var i = 0; i < args.length; i++) { var arg = args[i]; if (!arg) { continue; } var updates = Object.keys(arg); for (var _i = 0; _i < updates.length; _i++) { var prop = updates[_i]; original[prop] = arg[prop]; } } return original; } }); enifed('ember-metal/binding', ['exports', 'ember-console', 'ember-environment', 'ember-metal/run_loop', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/utils', 'ember-metal/events', 'ember-metal/observer', 'ember-metal/path_cache'], function (exports, _emberConsole, _emberEnvironment, _emberMetalRun_loop, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalUtils, _emberMetalEvents, _emberMetalObserver, _emberMetalPath_cache) { 'use strict'; exports.bind = bind; /** @module ember @submodule ember-metal */ // .......................................................... // BINDING // function Binding(toPath, fromPath) { // Configuration this._from = fromPath; this._to = toPath; this._oneWay = undefined; // State this._direction = undefined; this._readyToSync = undefined; this._fromObj = undefined; this._fromPath = undefined; this._toObj = undefined; } /** @class Binding @namespace Ember @deprecated See http://emberjs.com/deprecations/v2.x#toc_ember-binding @public */ Binding.prototype = { /** This copies the Binding so it can be connected to another object. @method copy @return {Ember.Binding} `this` @public */ copy: function () { var copy = new Binding(this._to, this._from); if (this._oneWay) { copy._oneWay = true; } return copy; }, // .......................................................... // CONFIG // /** This will set `from` property path to the specified value. It will not attempt to resolve this property path to an actual object until you connect the binding. The binding will search for the property path starting at the root object you pass when you `connect()` the binding. It follows the same rules as `get()` - see that method for more information. @method from @param {String} path The property path to connect to. @return {Ember.Binding} `this` @public */ from: function (path) { this._from = path; return this; }, /** This will set the `to` property path to the specified value. It will not attempt to resolve this property path to an actual object until you connect the binding. The binding will search for the property path starting at the root object you pass when you `connect()` the binding. It follows the same rules as `get()` - see that method for more information. @method to @param {String|Tuple} path A property path or tuple. @return {Ember.Binding} `this` @public */ to: function (path) { this._to = path; return this; }, /** Configures the binding as one way. A one-way binding will relay changes on the `from` side to the `to` side, but not the other way around. This means that if you change the `to` side directly, the `from` side may have a different value. @method oneWay @return {Ember.Binding} `this` @public */ oneWay: function () { this._oneWay = true; return this; }, /** @method toString @return {String} string representation of binding @public */ toString: function () { var oneWay = this._oneWay ? '[oneWay]' : ''; return 'Ember.Binding<' + _emberMetalUtils.guidFor(this) + '>(' + this._from + ' -> ' + this._to + ')' + oneWay; }, // .......................................................... // CONNECT AND SYNC // /** Attempts to connect this binding instance so that it can receive and relay changes. This method will raise an exception if you have not set the from/to properties yet. @method connect @param {Object} obj The root object for this binding. @return {Ember.Binding} `this` @public */ connect: function (obj) { _emberMetalDebug.assert('Must pass a valid object to Ember.Binding.connect()', !!obj); var fromObj = undefined, fromPath = undefined, possibleGlobal = undefined; // If the binding's "from" path could be interpreted as a global, verify // whether the path refers to a global or not by consulting `Ember.lookup`. if (_emberMetalPath_cache.isGlobalPath(this._from)) { var _name = _emberMetalPath_cache.getFirstKey(this._from); possibleGlobal = _emberEnvironment.context.lookup[_name]; if (possibleGlobal) { fromObj = possibleGlobal; fromPath = _emberMetalPath_cache.getTailPath(this._from); } } if (fromObj === undefined) { fromObj = obj; fromPath = this._from; } _emberMetalProperty_set.trySet(obj, this._to, _emberMetalProperty_get.get(fromObj, fromPath)); // Add an observer on the object to be notified when the binding should be updated. _emberMetalObserver.addObserver(fromObj, fromPath, this, 'fromDidChange'); // If the binding is a two-way binding, also set up an observer on the target. if (!this._oneWay) { _emberMetalObserver.addObserver(obj, this._to, this, 'toDidChange'); } _emberMetalEvents.addListener(obj, 'willDestroy', this, 'disconnect'); fireDeprecations(obj, this._to, this._from, possibleGlobal, this._oneWay, !possibleGlobal && !this._oneWay); this._readyToSync = true; this._fromObj = fromObj; this._fromPath = fromPath; this._toObj = obj; return this; }, /** Disconnects the binding instance. Changes will no longer be relayed. You will not usually need to call this method. @method disconnect @return {Ember.Binding} `this` @public */ disconnect: function () { _emberMetalDebug.assert('Must pass a valid object to Ember.Binding.disconnect()', !!this._toObj); // Remove an observer on the object so we're no longer notified of // changes that should update bindings. _emberMetalObserver.removeObserver(this._fromObj, this._fromPath, this, 'fromDidChange'); // If the binding is two-way, remove the observer from the target as well. if (!this._oneWay) { _emberMetalObserver.removeObserver(this._toObj, this._to, this, 'toDidChange'); } this._readyToSync = false; // Disable scheduled syncs... return this; }, // .......................................................... // PRIVATE // /* Called when the from side changes. */ fromDidChange: function (target) { this._scheduleSync('fwd'); }, /* Called when the to side changes. */ toDidChange: function (target) { this._scheduleSync('back'); }, _scheduleSync: function (dir) { var existingDir = this._direction; // If we haven't scheduled the binding yet, schedule it. if (existingDir === undefined) { _emberMetalRun_loop.default.schedule('sync', this, '_sync'); this._direction = dir; } // If both a 'back' and 'fwd' sync have been scheduled on the same object, // default to a 'fwd' sync so that it remains deterministic. if (existingDir === 'back' && dir === 'fwd') { this._direction = 'fwd'; } }, _sync: function () { var log = _emberEnvironment.ENV.LOG_BINDINGS; var toObj = this._toObj; // Don't synchronize destroyed objects or disconnected bindings. if (toObj.isDestroyed || !this._readyToSync) { return; } // Get the direction of the binding for the object we are // synchronizing from. var direction = this._direction; var fromObj = this._fromObj; var fromPath = this._fromPath; this._direction = undefined; // If we're synchronizing from the remote object... if (direction === 'fwd') { var fromValue = _emberMetalProperty_get.get(fromObj, fromPath); if (log) { _emberConsole.default.log(' ', this.toString(), '->', fromValue, fromObj); } if (this._oneWay) { _emberMetalProperty_set.trySet(toObj, this._to, fromValue); } else { _emberMetalObserver._suspendObserver(toObj, this._to, this, 'toDidChange', function () { _emberMetalProperty_set.trySet(toObj, this._to, fromValue); }); } // If we're synchronizing *to* the remote object. } else if (direction === 'back') { var toValue = _emberMetalProperty_get.get(toObj, this._to); if (log) { _emberConsole.default.log(' ', this.toString(), '<-', toValue, toObj); } _emberMetalObserver._suspendObserver(fromObj, fromPath, this, 'fromDidChange', function () { _emberMetalProperty_set.trySet(fromObj, fromPath, toValue); }); } } }; function fireDeprecations(obj, toPath, fromPath, deprecateGlobal, deprecateOneWay, deprecateAlias) { var deprecateGlobalMessage = '`Ember.Binding` is deprecated. Since you' + ' are binding to a global consider using a service instead.'; var deprecateOneWayMessage = '`Ember.Binding` is deprecated. Since you' + ' are using a `oneWay` binding consider using a `readOnly` computed' + ' property instead.'; var deprecateAliasMessage = '`Ember.Binding` is deprecated. Consider' + ' using an `alias` computed property instead.'; var objectInfo = 'The `' + toPath + '` property of `' + obj + '` is an `Ember.Binding` connected to `' + fromPath + '`, but '; _emberMetalDebug.deprecate(objectInfo + deprecateGlobalMessage, !deprecateGlobal, { id: 'ember-metal.binding', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_ember-binding' }); _emberMetalDebug.deprecate(objectInfo + deprecateOneWayMessage, !deprecateOneWay, { id: 'ember-metal.binding', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_ember-binding' }); _emberMetalDebug.deprecate(objectInfo + deprecateAliasMessage, !deprecateAlias, { id: 'ember-metal.binding', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_ember-binding' }); } function mixinProperties(to, from) { for (var key in from) { if (from.hasOwnProperty(key)) { to[key] = from[key]; } } } mixinProperties(Binding, { /* See `Ember.Binding.from`. @method from @static */ from: function (from) { var C = this; return new C(undefined, from); }, /* See `Ember.Binding.to`. @method to @static */ to: function (to) { var C = this; return new C(to, undefined); } }); /** An `Ember.Binding` connects the properties of two objects so that whenever the value of one property changes, the other property will be changed also. ## Automatic Creation of Bindings with `/^*Binding/`-named Properties. You do not usually create Binding objects directly but instead describe bindings in your class or object definition using automatic binding detection. Properties ending in a `Binding` suffix will be converted to `Ember.Binding` instances. The value of this property should be a string representing a path to another object or a custom binding instance created using Binding helpers (see "One Way Bindings"): ``` valueBinding: "MyApp.someController.title" ``` This will create a binding from `MyApp.someController.title` to the `value` property of your object instance automatically. Now the two values will be kept in sync. ## One Way Bindings One especially useful binding customization you can use is the `oneWay()` helper. This helper tells Ember that you are only interested in receiving changes on the object you are binding from. For example, if you are binding to a preference and you want to be notified if the preference has changed, but your object will not be changing the preference itself, you could do: ``` bigTitlesBinding: Ember.Binding.oneWay("MyApp.preferencesController.bigTitles") ``` This way if the value of `MyApp.preferencesController.bigTitles` changes the `bigTitles` property of your object will change also. However, if you change the value of your `bigTitles` property, it will not update the `preferencesController`. One way bindings are almost twice as fast to setup and twice as fast to execute because the binding only has to worry about changes to one side. You should consider using one way bindings anytime you have an object that may be created frequently and you do not intend to change a property; only to monitor it for changes (such as in the example above). ## Adding Bindings Manually All of the examples above show you how to configure a custom binding, but the result of these customizations will be a binding template, not a fully active Binding instance. The binding will actually become active only when you instantiate the object the binding belongs to. It is useful, however, to understand what actually happens when the binding is activated. For a binding to function it must have at least a `from` property and a `to` property. The `from` property path points to the object/key that you want to bind from while the `to` path points to the object/key you want to bind to. When you define a custom binding, you are usually describing the property you want to bind from (such as `MyApp.someController.value` in the examples above). When your object is created, it will automatically assign the value you want to bind `to` based on the name of your binding key. In the examples above, during init, Ember objects will effectively call something like this on your binding: ```javascript binding = Ember.Binding.from("valueBinding").to("value"); ``` This creates a new binding instance based on the template you provide, and sets the to path to the `value` property of the new object. Now that the binding is fully configured with a `from` and a `to`, it simply needs to be connected to become active. This is done through the `connect()` method: ```javascript binding.connect(this); ``` Note that when you connect a binding you pass the object you want it to be connected to. This object will be used as the root for both the from and to side of the binding when inspecting relative paths. This allows the binding to be automatically inherited by subclassed objects as well. This also allows you to bind between objects using the paths you declare in `from` and `to`: ```javascript // Example 1 binding = Ember.Binding.from("App.someObject.value").to("value"); binding.connect(this); // Example 2 binding = Ember.Binding.from("parentView.value").to("App.someObject.value"); binding.connect(this); ``` Now that the binding is connected, it will observe both the from and to side and relay changes. If you ever needed to do so (you almost never will, but it is useful to understand this anyway), you could manually create an active binding by using the `Ember.bind()` helper method. (This is the same method used by to setup your bindings on objects): ```javascript Ember.bind(MyApp.anotherObject, "value", "MyApp.someController.value"); ``` Both of these code fragments have the same effect as doing the most friendly form of binding creation like so: ```javascript MyApp.anotherObject = Ember.Object.create({ valueBinding: "MyApp.someController.value", // OTHER CODE FOR THIS OBJECT... }); ``` Ember's built in binding creation method makes it easy to automatically create bindings for you. You should always use the highest-level APIs available, even if you understand how it works underneath. @class Binding @namespace Ember @since Ember 0.9 @public */ // Ember.Binding = Binding; ES6TODO: where to put this? /** Global helper method to create a new binding. Just pass the root object along with a `to` and `from` path to create and connect the binding. @method bind @for Ember @param {Object} obj The root object of the transform. @param {String} to The path to the 'to' side of the binding. Must be relative to obj. @param {String} from The path to the 'from' side of the binding. Must be relative to obj or a global path. @return {Ember.Binding} binding instance @public */ function bind(obj, to, from) { return new Binding(to, from).connect(obj); } exports.Binding = Binding; }); enifed('ember-metal/cache', ['exports', 'ember-metal/empty_object'], function (exports, _emberMetalEmpty_object) { 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Cache = (function () { function Cache(limit, func, key, store) { _classCallCheck(this, Cache); this.size = 0; this.misses = 0; this.hits = 0; this.limit = limit; this.func = func; this.key = key; this.store = store || new DefaultStore(); } Cache.prototype.get = function get(obj) { var key = this.key === undefined ? obj : this.key(obj); var value = this.store.get(key); if (value === undefined) { this.misses++; value = this._set(key, this.func(obj)); } else if (value === UNDEFINED) { this.hits++; value = undefined; } else { this.hits++; // nothing to translate } return value; }; Cache.prototype.set = function set(obj, value) { var key = this.key === undefined ? obj : this.key(obj); return this._set(key, value); }; Cache.prototype._set = function _set(key, value) { if (this.limit > this.size) { this.size++; if (value === undefined) { this.store.set(key, UNDEFINED); } else { this.store.set(key, value); } } return value; }; Cache.prototype.purge = function purge() { this.store.clear(); this.size = 0; this.hits = 0; this.misses = 0; }; return Cache; })(); exports.default = Cache; function UNDEFINED() {} var DefaultStore = (function () { function DefaultStore() { _classCallCheck(this, DefaultStore); this.data = new _emberMetalEmpty_object.default(); } DefaultStore.prototype.get = function get(key) { return this.data[key]; }; DefaultStore.prototype.set = function set(key, value) { this.data[key] = value; }; DefaultStore.prototype.clear = function clear() { this.data = new _emberMetalEmpty_object.default(); }; return DefaultStore; })(); }); enifed('ember-metal/chains', ['exports', 'ember-metal/property_get', 'ember-metal/meta', 'ember-metal/watch_key', 'ember-metal/empty_object', 'ember-metal/watch_path'], function (exports, _emberMetalProperty_get, _emberMetalMeta, _emberMetalWatch_key, _emberMetalEmpty_object, _emberMetalWatch_path) { 'use strict'; exports.finishChains = finishChains; var FIRST_KEY = /^([^\.]+)/; function firstKey(path) { return path.match(FIRST_KEY)[0]; } function isObject(obj) { return obj && typeof obj === 'object'; } function isVolatile(obj) { return !(isObject(obj) && obj.isDescriptor && obj._volatile === false); } function ChainWatchers() { // chain nodes that reference a key in this obj by key // we only create ChainWatchers when we are going to add them // so create this upfront this.chains = new _emberMetalEmpty_object.default(); } ChainWatchers.prototype = { add: function (key, node) { var nodes = this.chains[key]; if (nodes === undefined) { this.chains[key] = [node]; } else { nodes.push(node); } }, remove: function (key, node) { var nodes = this.chains[key]; if (nodes) { for (var i = 0; i < nodes.length; i++) { if (nodes[i] === node) { nodes.splice(i, 1); break; } } } }, has: function (key, node) { var nodes = this.chains[key]; if (nodes) { for (var i = 0; i < nodes.length; i++) { if (nodes[i] === node) { return true; } } } return false; }, revalidateAll: function () { for (var key in this.chains) { this.notify(key, true, undefined); } }, revalidate: function (key) { this.notify(key, true, undefined); }, // key: the string key that is part of a path changed // revalidate: boolean; the chains that are watching this value should revalidate // callback: function that will be called with the object and path that // will be/are invalidated by this key change, depending on // whether the revalidate flag is passed notify: function (key, revalidate, callback) { var nodes = this.chains[key]; if (nodes === undefined || nodes.length === 0) { return; } var affected = undefined; if (callback) { affected = []; } for (var i = 0; i < nodes.length; i++) { nodes[i].notify(revalidate, affected); } if (callback === undefined) { return; } // we gather callbacks so we don't notify them during revalidation for (var i = 0; i < affected.length; i += 2) { var obj = affected[i]; var path = affected[i + 1]; callback(obj, path); } } }; function makeChainWatcher() { return new ChainWatchers(); } function addChainWatcher(obj, keyName, node) { if (!isObject(obj)) { return; } var m = _emberMetalMeta.meta(obj); m.writableChainWatchers(makeChainWatcher).add(keyName, node); _emberMetalWatch_key.watchKey(obj, keyName, m); } function removeChainWatcher(obj, keyName, node) { if (!isObject(obj)) { return; } var m = _emberMetalMeta.peekMeta(obj); if (!m || !m.readableChainWatchers()) { return; } // make meta writable m = _emberMetalMeta.meta(obj); m.readableChainWatchers().remove(keyName, node); _emberMetalWatch_key.unwatchKey(obj, keyName, m); } // A ChainNode watches a single key on an object. If you provide a starting // value for the key then the node won't actually watch it. For a root node // pass null for parent and key and object for value. function ChainNode(parent, key, value) { this._parent = parent; this._key = key; // _watching is true when calling get(this._parent, this._key) will // return the value of this node. // // It is false for the root of a chain (because we have no parent) // and for global paths (because the parent node is the object with // the observer on it) this._watching = value === undefined; this._chains = undefined; this._object = undefined; this.count = 0; this._value = value; this._paths = {}; if (this._watching) { this._object = parent.value(); if (this._object) { addChainWatcher(this._object, this._key, this); } } } function lazyGet(obj, key) { if (!obj) { return; } var meta = _emberMetalMeta.peekMeta(obj); // check if object meant only to be a prototype if (meta && meta.proto === obj) { return; } // Use `get` if the return value is an EachProxy or an uncacheable value. if (isVolatile(obj[key])) { return _emberMetalProperty_get.get(obj, key); // Otherwise attempt to get the cached value of the computed property } else { var cache = meta.readableCache(); if (cache && key in cache) { return cache[key]; } } } ChainNode.prototype = { value: function () { if (this._value === undefined && this._watching) { var obj = this._parent.value(); this._value = lazyGet(obj, this._key); } return this._value; }, destroy: function () { if (this._watching) { var obj = this._object; if (obj) { removeChainWatcher(obj, this._key, this); } this._watching = false; // so future calls do nothing } }, // copies a top level object only copy: function (obj) { var ret = new ChainNode(null, null, obj); var paths = this._paths; var path = undefined; for (path in paths) { // this check will also catch non-number vals. if (paths[path] <= 0) { continue; } ret.add(path); } return ret; }, // called on the root node of a chain to setup watchers on the specified // path. add: function (path) { var paths = this._paths; paths[path] = (paths[path] || 0) + 1; var key = firstKey(path); var tail = path.slice(key.length + 1); this.chain(key, tail); }, // called on the root node of a chain to teardown watcher on the specified // path remove: function (path) { var paths = this._paths; if (paths[path] > 0) { paths[path]--; } var key = firstKey(path); var tail = path.slice(key.length + 1); this.unchain(key, tail); }, chain: function (key, path) { var chains = this._chains; var node = undefined; if (chains === undefined) { chains = this._chains = new _emberMetalEmpty_object.default(); } else { node = chains[key]; } if (node === undefined) { node = chains[key] = new ChainNode(this, key, undefined); } node.count++; // count chains... // chain rest of path if there is one if (path) { key = firstKey(path); path = path.slice(key.length + 1); node.chain(key, path); } }, unchain: function (key, path) { var chains = this._chains; var node = chains[key]; // unchain rest of path first... if (path && path.length > 1) { var nextKey = firstKey(path); var nextPath = path.slice(nextKey.length + 1); node.unchain(nextKey, nextPath); } // delete node if needed. node.count--; if (node.count <= 0) { chains[node._key] = undefined; node.destroy(); } }, notify: function (revalidate, affected) { if (revalidate && this._watching) { var obj = this._parent.value(); if (obj !== this._object) { removeChainWatcher(this._object, this._key, this); this._object = obj; addChainWatcher(obj, this._key, this); } this._value = undefined; } // then notify chains... var chains = this._chains; var node = undefined; if (chains) { for (var key in chains) { node = chains[key]; if (node !== undefined) { node.notify(revalidate, affected); } } } if (affected && this._parent) { this._parent.populateAffected(this._key, 1, affected); } }, populateAffected: function (path, depth, affected) { if (this._key) { path = this._key + '.' + path; } if (this._parent) { this._parent.populateAffected(path, depth + 1, affected); } else { if (depth > 1) { affected.push(this.value(), path); } } } }; function finishChains(obj) { // We only create meta if we really have to var m = _emberMetalMeta.peekMeta(obj); if (m) { m = _emberMetalMeta.meta(obj); // finish any current chains node watchers that reference obj var chainWatchers = m.readableChainWatchers(); if (chainWatchers) { chainWatchers.revalidateAll(); } // ensure that if we have inherited any chains they have been // copied onto our own meta. if (m.readableChains()) { m.writableChains(_emberMetalWatch_path.makeChainNode); } } } exports.removeChainWatcher = removeChainWatcher; exports.ChainNode = ChainNode; }); enifed('ember-metal/computed', ['exports', 'ember-metal/debug', 'ember-metal/property_set', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/expand_properties', 'ember-metal/error', 'ember-metal/properties', 'ember-metal/property_events', 'ember-metal/dependent_keys'], function (exports, _emberMetalDebug, _emberMetalProperty_set, _emberMetalUtils, _emberMetalMeta, _emberMetalExpand_properties, _emberMetalError, _emberMetalProperties, _emberMetalProperty_events, _emberMetalDependent_keys) { 'use strict'; exports.default = computed; /** @module ember @submodule ember-metal */ function UNDEFINED() {} var DEEP_EACH_REGEX = /\.@each\.[^.]+\./; /** A computed property transforms an object literal with object's accessor function(s) into a property. By default the function backing the computed property will only be called once and the result will be cached. You can specify various properties that your computed property depends on. This will force the cached result to be recomputed if the dependencies are modified. In the following example we declare a computed property - `fullName` - by calling `.Ember.computed()` with property dependencies (`firstName` and `lastName`) as leading arguments and getter accessor function. The `fullName` getter function will be called once (regardless of how many times it is accessed) as long as its dependencies have not changed. Once `firstName` or `lastName` are updated any future calls (or anything bound) to `fullName` will incorporate the new values. ```javascript let Person = Ember.Object.extend({ // these will be supplied by `create` firstName: null, lastName: null, fullName: Ember.computed('firstName', 'lastName', function() { let firstName = this.get('firstName'), lastName = this.get('lastName'); return firstName + ' ' + lastName; }) }); let tom = Person.create({ firstName: 'Tom', lastName: 'Dale' }); tom.get('fullName') // 'Tom Dale' ``` You can also define what Ember should do when setting a computed property by providing additional function (`set`) in hash argument. If you try to set a computed property, it will try to invoke setter accessor function with the key and value you want to set it to as arguments. ```javascript let Person = Ember.Object.extend({ // these will be supplied by `create` firstName: null, lastName: null, fullName: Ember.computed('firstName', 'lastName', { get(key) { let firstName = this.get('firstName'), lastName = this.get('lastName'); return firstName + ' ' + lastName; }, set(key, value) { let [firstName, lastName] = value.split(' '); this.set('firstName', firstName); this.set('lastName', lastName); return value; } }) }); let person = Person.create(); person.set('fullName', 'Peter Wagenet'); person.get('firstName'); // 'Peter' person.get('lastName'); // 'Wagenet' ``` You can overwrite computed property with normal property (no longer computed), that won't change if dependencies change, if you set computed property and it won't have setter accessor function defined. You can also mark computed property as `.readOnly()` and block all attempts to set it. ```javascript let Person = Ember.Object.extend({ // these will be supplied by `create` firstName: null, lastName: null, fullName: Ember.computed('firstName', 'lastName', { get(key) { let firstName = this.get('firstName'); let lastName = this.get('lastName'); return firstName + ' ' + lastName; } }).readOnly() }); let person = Person.create(); person.set('fullName', 'Peter Wagenet'); // Uncaught Error: Cannot set read-only property "fullName" on object: <(...):emberXXX> ``` Additional resources: - [New CP syntax RFC](https://github.com/emberjs/rfcs/blob/master/text/0011-improved-cp-syntax.md) - [New computed syntax explained in "Ember 1.12 released" ](http://emberjs.com/blog/2015/05/13/ember-1-12-released.html#toc_new-computed-syntax) @class ComputedProperty @namespace Ember @public */ function ComputedProperty(config, opts) { this.isDescriptor = true; if (typeof config === 'function') { this._getter = config; } else { _emberMetalDebug.assert('Ember.computed expects a function or an object as last argument.', typeof config === 'object' && !Array.isArray(config)); _emberMetalDebug.assert('Config object passed to an Ember.computed can only contain `get` or `set` keys.', (function () { var keys = Object.keys(config); for (var i = 0; i < keys.length; i++) { if (keys[i] !== 'get' && keys[i] !== 'set') { return false; } } return true; })()); this._getter = config.get; this._setter = config.set; } _emberMetalDebug.assert('Computed properties must receive a getter or a setter, you passed none.', !!this._getter || !!this._setter); this._dependentKeys = undefined; this._suspended = undefined; this._meta = undefined; this._volatile = false; this._dependentKeys = opts && opts.dependentKeys; this._readOnly = false; } ComputedProperty.prototype = new _emberMetalProperties.Descriptor(); var ComputedPropertyPrototype = ComputedProperty.prototype; /** Call on a computed property to set it into non-cached mode. When in this mode the computed property will not automatically cache the return value. It also does not automatically fire any change events. You must manually notify any changes if you want to observe this property. Dependency keys have no effect on volatile properties as they are for cache invalidation and notification when cached value is invalidated. ```javascript let outsideService = Ember.Object.extend({ value: Ember.computed(function() { return OutsideService.getValue(); }).volatile() }).create(); ``` @method volatile @return {Ember.ComputedProperty} this @chainable @public */ ComputedPropertyPrototype.volatile = function () { this._volatile = true; return this; }; /** Call on a computed property to set it into read-only mode. When in this mode the computed property will throw an error when set. ```javascript let Person = Ember.Object.extend({ guid: Ember.computed(function() { return 'guid-guid-guid'; }).readOnly() }); let person = Person.create(); person.set('guid', 'new-guid'); // will throw an exception ``` @method readOnly @return {Ember.ComputedProperty} this @chainable @public */ ComputedPropertyPrototype.readOnly = function () { this._readOnly = true; _emberMetalDebug.assert('Computed properties that define a setter using the new syntax cannot be read-only', !(this._readOnly && this._setter && this._setter !== this._getter)); return this; }; /** Sets the dependent keys on this computed property. Pass any number of arguments containing key paths that this computed property depends on. ```javascript let President = Ember.Object.extend({ fullName: Ember.computed(function() { return this.get('firstName') + ' ' + this.get('lastName'); // Tell Ember that this computed property depends on firstName // and lastName }).property('firstName', 'lastName') }); let president = President.create({ firstName: 'Barack', lastName: 'Obama' }); president.get('fullName'); // 'Barack Obama' ``` @method property @param {String} path* zero or more property paths @return {Ember.ComputedProperty} this @chainable @public */ ComputedPropertyPrototype.property = function () { var args = []; function addArg(property) { _emberMetalDebug.warn('Dependent keys containing @each only work one level deep. ' + 'You cannot use nested forms like todos.@each.owner.name or todos.@each.owner.@each.name. ' + 'Please create an intermediary computed property.', DEEP_EACH_REGEX.test(property) === false, { id: 'ember-metal.computed-deep-each' }); args.push(property); } for (var i = 0; i < arguments.length; i++) { _emberMetalExpand_properties.default(arguments[i], addArg); } this._dependentKeys = args; return this; }; /** In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection. You can pass a hash of these values to a computed property like this: ``` person: Ember.computed(function() { let personId = this.get('personId'); return App.Person.create({ id: personId }); }).meta({ type: App.Person }) ``` The hash that you pass to the `meta()` function will be saved on the computed property descriptor under the `_meta` key. Ember runtime exposes a public API for retrieving these values from classes, via the `metaForProperty()` function. @method meta @param {Object} meta @chainable @public */ ComputedPropertyPrototype.meta = function (meta) { if (arguments.length === 0) { return this._meta || {}; } else { this._meta = meta; return this; } }; // invalidate cache when CP key changes ComputedPropertyPrototype.didChange = function (obj, keyName) { // _suspended is set via a CP.set to ensure we don't clear // the cached value set by the setter if (this._volatile || this._suspended === obj) { return; } // don't create objects just to invalidate var meta = _emberMetalMeta.peekMeta(obj); if (!meta || meta.source !== obj) { return; } var cache = meta.readableCache(); if (cache && cache[keyName] !== undefined) { cache[keyName] = undefined; _emberMetalDependent_keys.removeDependentKeys(this, obj, keyName, meta); } }; ComputedPropertyPrototype.get = function (obj, keyName) { if (this._volatile) { return this._getter.call(obj, keyName); } var meta = _emberMetalMeta.meta(obj); var cache = meta.writableCache(); var result = cache[keyName]; if (result === UNDEFINED) { return undefined; } else if (result !== undefined) { return result; } var ret = this._getter.call(obj, keyName); if (ret === undefined) { cache[keyName] = UNDEFINED; } else { cache[keyName] = ret; } var chainWatchers = meta.readableChainWatchers(); if (chainWatchers) { chainWatchers.revalidate(keyName); } _emberMetalDependent_keys.addDependentKeys(this, obj, keyName, meta); return ret; }; ComputedPropertyPrototype.set = function computedPropertySetEntry(obj, keyName, value) { if (this._readOnly) { this._throwReadOnlyError(obj, keyName); } if (!this._setter) { return this.clobberSet(obj, keyName, value); } if (this._volatile) { return this.volatileSet(obj, keyName, value); } return this.setWithSuspend(obj, keyName, value); }; ComputedPropertyPrototype._throwReadOnlyError = function computedPropertyThrowReadOnlyError(obj, keyName) { throw new _emberMetalError.default('Cannot set read-only property "' + keyName + '" on object: ' + _emberMetalUtils.inspect(obj)); }; ComputedPropertyPrototype.clobberSet = function computedPropertyClobberSet(obj, keyName, value) { var cachedValue = cacheFor(obj, keyName); _emberMetalProperties.defineProperty(obj, keyName, null, cachedValue); _emberMetalProperty_set.set(obj, keyName, value); return value; }; ComputedPropertyPrototype.volatileSet = function computedPropertyVolatileSet(obj, keyName, value) { return this._setter.call(obj, keyName, value); }; ComputedPropertyPrototype.setWithSuspend = function computedPropertySetWithSuspend(obj, keyName, value) { var oldSuspended = this._suspended; this._suspended = obj; try { return this._set(obj, keyName, value); } finally { this._suspended = oldSuspended; } }; ComputedPropertyPrototype._set = function computedPropertySet(obj, keyName, value) { // cache requires own meta var meta = _emberMetalMeta.meta(obj); // either there is a writable cache or we need one to update var cache = meta.writableCache(); var hadCachedValue = false; var cachedValue = undefined; if (cache[keyName] !== undefined) { if (cache[keyName] !== UNDEFINED) { cachedValue = cache[keyName]; } hadCachedValue = true; } var ret = this._setter.call(obj, keyName, value, cachedValue); // allows setter to return the same value that is cached already if (hadCachedValue && cachedValue === ret) { return ret; } _emberMetalProperty_events.propertyWillChange(obj, keyName); if (hadCachedValue) { cache[keyName] = undefined; } if (!hadCachedValue) { _emberMetalDependent_keys.addDependentKeys(this, obj, keyName, meta); } if (ret === undefined) { cache[keyName] = UNDEFINED; } else { cache[keyName] = ret; } _emberMetalProperty_events.propertyDidChange(obj, keyName); return ret; }; /* called before property is overridden */ ComputedPropertyPrototype.teardown = function (obj, keyName) { if (this._volatile) { return; } var meta = _emberMetalMeta.meta(obj); var cache = meta.readableCache(); if (cache && cache[keyName] !== undefined) { _emberMetalDependent_keys.removeDependentKeys(this, obj, keyName, meta); cache[keyName] = undefined; } }; /** This helper returns a new property descriptor that wraps the passed computed property function. You can use this helper to define properties with mixins or via `Ember.defineProperty()`. If you pass a function as an argument, it will be used as a getter. A computed property defined in this way might look like this: ```js let Person = Ember.Object.extend({ init() { this._super(...arguments); this.firstName = 'Betty'; this.lastName = 'Jones'; }, fullName: Ember.computed('firstName', 'lastName', function() { return `${this.get('firstName')} ${this.get('lastName')}`; }) }); let client = Person.create(); client.get('fullName'); // 'Betty Jones' client.set('lastName', 'Fuller'); client.get('fullName'); // 'Betty Fuller' ``` You can pass a hash with two functions, `get` and `set`, as an argument to provide both a getter and setter: ```js let Person = Ember.Object.extend({ init() { this._super(...arguments); this.firstName = 'Betty'; this.lastName = 'Jones'; }, fullName: Ember.computed('firstName', 'lastName', { get(key) { return `${this.get('firstName')} ${this.get('lastName')}`; }, set(key, value) { let [firstName, lastName] = value.split(/\s+/); this.setProperties({ firstName, lastName }); return value; } }); }) let client = Person.create(); client.get('firstName'); // 'Betty' client.set('fullName', 'Carroll Fuller'); client.get('firstName'); // 'Carroll' ``` The `set` function should accept two parameters, `key` and `value`. The value returned from `set` will be the new value of the property. _Note: This is the preferred way to define computed properties when writing third-party libraries that depend on or use Ember, since there is no guarantee that the user will have [prototype Extensions](http://emberjs.com/guides/configuring-ember/disabling-prototype-extensions/) enabled._ The alternative syntax, with prototype extensions, might look like: ```js fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); }.property('firstName', 'lastName') ``` @class computed @namespace Ember @constructor @static @param {String} [dependentKeys*] Optional dependent keys that trigger this computed property. @param {Function} func The computed property function. @return {Ember.ComputedProperty} property descriptor instance @public */ function computed(func) { var args = undefined; if (arguments.length > 1) { args = [].slice.call(arguments); func = args.pop(); } var cp = new ComputedProperty(func); if (args) { cp.property.apply(cp, args); } return cp; } /** Returns the cached value for a property, if one exists. This can be useful for peeking at the value of a computed property that is generated lazily, without accidentally causing it to be created. @method cacheFor @for Ember @param {Object} obj the object whose property you want to check @param {String} key the name of the property whose cached value you want to return @return {Object} the cached value @public */ function cacheFor(obj, key) { var meta = _emberMetalMeta.peekMeta(obj); var cache = meta && meta.source === obj && meta.readableCache(); var ret = cache && cache[key]; if (ret === UNDEFINED) { return undefined; } return ret; } cacheFor.set = function (cache, key, value) { if (value === undefined) { cache[key] = UNDEFINED; } else { cache[key] = value; } }; cacheFor.get = function (cache, key) { var ret = cache[key]; if (ret === UNDEFINED) { return undefined; } return ret; }; cacheFor.remove = function (cache, key) { cache[key] = undefined; }; exports.ComputedProperty = ComputedProperty; exports.computed = computed; exports.cacheFor = cacheFor; }); enifed('ember-metal/core', ['exports', 'ember-environment'], function (exports, _emberEnvironment) { 'use strict'; /** @module ember @submodule ember-metal */ /** This namespace contains all Ember methods and functions. Future versions of Ember may overwrite this namespace and therefore, you should avoid adding any new properties. At the heart of Ember is Ember-Runtime, a set of core functions that provide cross-platform compatibility and object property observing. Ember-Runtime is small and performance-focused so you can use it alongside other cross-platform libraries such as jQuery. For more details, see [Ember-Runtime](http://emberjs.com/api/modules/ember-runtime.html). @class Ember @static @public */ var Ember = typeof _emberEnvironment.context.imports.Ember === 'object' && _emberEnvironment.context.imports.Ember || {}; // Make sure these are set whether Ember was already defined or not Ember.isNamespace = true; Ember.toString = function () { return 'Ember'; }; // .......................................................... // BOOTSTRAP // exports.default = Ember; }); enifed("ember-metal/debug", ["exports"], function (exports) { "use strict"; exports.getDebugFunction = getDebugFunction; exports.setDebugFunction = setDebugFunction; exports.assert = assert; exports.info = info; exports.warn = warn; exports.debug = debug; exports.deprecate = deprecate; exports.deprecateFunc = deprecateFunc; exports.runInDebug = runInDebug; exports.debugSeal = debugSeal; var debugFunctions = { assert: function () {}, info: function () {}, warn: function () {}, debug: function () {}, deprecate: function () {}, deprecateFunc: function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return args[args.length - 1]; }, runInDebug: function () {}, debugSeal: function () {} }; exports.debugFunctions = debugFunctions; function getDebugFunction(name) { return debugFunctions[name]; } function setDebugFunction(name, fn) { debugFunctions[name] = fn; } function assert() { return debugFunctions.assert.apply(undefined, arguments); } function info() { return debugFunctions.info.apply(undefined, arguments); } function warn() { return debugFunctions.warn.apply(undefined, arguments); } function debug() { return debugFunctions.debug.apply(undefined, arguments); } function deprecate() { return debugFunctions.deprecate.apply(undefined, arguments); } function deprecateFunc() { return debugFunctions.deprecateFunc.apply(undefined, arguments); } function runInDebug() { return debugFunctions.runInDebug.apply(undefined, arguments); } function debugSeal() { return debugFunctions.debugSeal.apply(undefined, arguments); } }); enifed('ember-metal/dependent_keys', ['exports', 'ember-metal/watching'], function (exports, _emberMetalWatching) { 'no use strict'; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed exports.addDependentKeys = addDependentKeys; exports.removeDependentKeys = removeDependentKeys; /** @module ember @submodule ember-metal */ // .......................................................... // DEPENDENT KEYS // function addDependentKeys(desc, obj, keyName, meta) { // the descriptor has a list of dependent keys, so // add all of its dependent keys. var idx = undefined, depKey = undefined; var depKeys = desc._dependentKeys; if (!depKeys) { return; } for (idx = 0; idx < depKeys.length; idx++) { depKey = depKeys[idx]; // Increment the number of times depKey depends on keyName. meta.writeDeps(depKey, keyName, (meta.peekDeps(depKey, keyName) || 0) + 1); // Watch the depKey _emberMetalWatching.watch(obj, depKey, meta); } } function removeDependentKeys(desc, obj, keyName, meta) { // the descriptor has a list of dependent keys, so // remove all of its dependent keys. var depKeys = desc._dependentKeys; if (!depKeys) { return; } for (var idx = 0; idx < depKeys.length; idx++) { var depKey = depKeys[idx]; // Decrement the number of times depKey depends on keyName. meta.writeDeps(depKey, keyName, (meta.peekDeps(depKey, keyName) || 0) - 1); // Unwatch the depKey _emberMetalWatching.unwatch(obj, depKey, meta); } } }); enifed('ember-metal/deprecate_property', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set) { /** @module ember @submodule ember-metal */ 'use strict'; exports.deprecateProperty = deprecateProperty; /** Used internally to allow changing properties in a backwards compatible way, and print a helpful deprecation warning. @method deprecateProperty @param {Object} object The object to add the deprecated property to. @param {String} deprecatedKey The property to add (and print deprecation warnings upon accessing). @param {String} newKey The property that will be aliased. @private @since 1.7.0 */ function deprecateProperty(object, deprecatedKey, newKey, options) { function _deprecate() { _emberMetalDebug.deprecate('Usage of `' + deprecatedKey + '` is deprecated, use `' + newKey + '` instead.', false, options); } Object.defineProperty(object, deprecatedKey, { configurable: true, enumerable: false, set: function (value) { _deprecate(); _emberMetalProperty_set.set(this, newKey, value); }, get: function () { _deprecate(); return _emberMetalProperty_get.get(this, newKey); } }); } }); enifed('ember-metal/dictionary', ['exports', 'ember-metal/empty_object'], function (exports, _emberMetalEmpty_object) { 'use strict'; exports.default = makeDictionary; // the delete is meant to hint at runtimes that this object should remain in // dictionary mode. This is clearly a runtime specific hack, but currently it // appears worthwhile in some usecases. Please note, these deletes do increase // the cost of creation dramatically over a plain Object.create. And as this // only makes sense for long-lived dictionaries that aren't instantiated often. function makeDictionary(parent) { var dict = undefined; if (parent === null) { dict = new _emberMetalEmpty_object.default(); } else { dict = Object.create(parent); } dict['_dict'] = null; delete dict['_dict']; return dict; } }); enifed("ember-metal/empty_object", ["exports"], function (exports) { // This exists because `Object.create(null)` is absurdly slow compared // to `new EmptyObject()`. In either case, you want a null prototype // when you're treating the object instances as arbitrary dictionaries // and don't want your keys colliding with build-in methods on the // default object prototype. "use strict"; var proto = Object.create(null, { // without this, we will always still end up with (new // EmptyObject()).constructor === Object constructor: { value: undefined, enumerable: false, writable: true } }); function EmptyObject() {} EmptyObject.prototype = proto; exports.default = EmptyObject; }); enifed('ember-metal/error', ['exports'], function (exports) { 'use strict'; exports.default = EmberError; var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; /** A subclass of the JavaScript Error object for use in Ember. @class Error @namespace Ember @extends Error @constructor @public */ function EmberError() { var tmp = Error.apply(this, arguments); // Adds a `stack` property to the given error object that will yield the // stack trace at the time captureStackTrace was called. // When collecting the stack trace all frames above the topmost call // to this function, including that call, will be left out of the // stack trace. // This is useful because we can hide Ember implementation details // that are not very helpful for the user. if (Error.captureStackTrace) { Error.captureStackTrace(this, EmberError); } // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } } EmberError.prototype = Object.create(Error.prototype); }); enifed('ember-metal/error_handler', ['exports', 'ember-console', 'ember-metal/testing'], function (exports, _emberConsole, _emberMetalTesting) { 'use strict'; exports.getOnerror = getOnerror; exports.setOnerror = setOnerror; exports.dispatchError = dispatchError; exports.setDispatchOverride = setDispatchOverride; // To maintain stacktrace consistency across browsers var getStack = function (error) { var stack = error.stack; var message = error.message; if (stack.indexOf(message) === -1) { stack = message + '\n' + stack; } return stack; }; var onerror = undefined; // Ember.onerror getter function getOnerror() { return onerror; } // Ember.onerror setter function setOnerror(handler) { onerror = handler; } var dispatchOverride = undefined; // dispatch error function dispatchError(error) { if (dispatchOverride) { dispatchOverride(error); } else { defaultDispatch(error); } } // allows testing adapter to override dispatch function setDispatchOverride(handler) { dispatchOverride = handler; } function defaultDispatch(error) { if (_emberMetalTesting.isTesting()) { throw error; } if (onerror) { onerror(error); } else { _emberConsole.default.error(getStack(error)); } } }); enifed('ember-metal/events', ['exports', 'ember-metal/debug', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/meta_listeners'], function (exports, _emberMetalDebug, _emberMetalUtils, _emberMetalMeta, _emberMetalMeta_listeners) { 'no use strict'; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed /** @module ember @submodule ember-metal */ exports.accumulateListeners = accumulateListeners; exports.addListener = addListener; exports.removeListener = removeListener; exports.suspendListener = suspendListener; exports.suspendListeners = suspendListeners; exports.watchedEvents = watchedEvents; exports.sendEvent = sendEvent; exports.hasListeners = hasListeners; exports.listenersFor = listenersFor; exports.on = on; /* The event system uses a series of nested hashes to store listeners on an object. When a listener is registered, or when an event arrives, these hashes are consulted to determine which target and action pair to invoke. The hashes are stored in the object's meta hash, and look like this: // Object's meta hash { listeners: { // variable name: `listenerSet` "foo:changed": [ // variable name: `actions` target, method, flags ] } } */ function indexOf(array, target, method) { var index = -1; // hashes are added to the end of the event array // so it makes sense to start searching at the end // of the array and search in reverse for (var i = array.length - 3; i >= 0; i -= 3) { if (target === array[i] && method === array[i + 1]) { index = i; break; } } return index; } function accumulateListeners(obj, eventName, otherActions) { var meta = _emberMetalMeta.peekMeta(obj); if (!meta) { return; } var actions = meta.matchingListeners(eventName); var newActions = []; for (var i = actions.length - 3; i >= 0; i -= 3) { var target = actions[i]; var method = actions[i + 1]; var flags = actions[i + 2]; var actionIndex = indexOf(otherActions, target, method); if (actionIndex === -1) { otherActions.push(target, method, flags); newActions.push(target, method, flags); } } return newActions; } /** Add an event listener @method addListener @for Ember @param obj @param {String} eventName @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Boolean} once A flag whether a function should only be called once @public */ function addListener(obj, eventName, target, method, once) { _emberMetalDebug.assert('You must pass at least an object and event name to Ember.addListener', !!obj && !!eventName); _emberMetalDebug.deprecate('didInitAttrs called in ' + (obj && obj.toString && obj.toString()) + '.', eventName !== 'didInitAttrs', { id: 'ember-views.did-init-attrs', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_ember-component-didinitattrs' }); if (!method && 'function' === typeof target) { method = target; target = null; } var flags = 0; if (once) { flags |= _emberMetalMeta_listeners.ONCE; } _emberMetalMeta.meta(obj).addToListeners(eventName, target, method, flags); if ('function' === typeof obj.didAddListener) { obj.didAddListener(eventName, target, method); } } /** Remove an event listener Arguments should match those passed to `Ember.addListener`. @method removeListener @for Ember @param obj @param {String} eventName @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @public */ function removeListener(obj, eventName, target, method) { _emberMetalDebug.assert('You must pass at least an object and event name to Ember.removeListener', !!obj && !!eventName); if (!method && 'function' === typeof target) { method = target; target = null; } _emberMetalMeta.meta(obj).removeFromListeners(eventName, target, method, function () { if ('function' === typeof obj.didRemoveListener) { obj.didRemoveListener.apply(obj, arguments); } }); } /** Suspend listener during callback. This should only be used by the target of the event listener when it is taking an action that would cause the event, e.g. an object might suspend its property change listener while it is setting that property. @method suspendListener @for Ember @private @param obj @param {String} eventName @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Function} callback */ function suspendListener(obj, eventName, target, method, callback) { return suspendListeners(obj, [eventName], target, method, callback); } /** Suspends multiple listeners during a callback. @method suspendListeners @for Ember @private @param obj @param {Array} eventNames Array of event names @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Function} callback */ function suspendListeners(obj, eventNames, target, method, callback) { if (!method && 'function' === typeof target) { method = target; target = null; } return _emberMetalMeta.meta(obj).suspendListeners(eventNames, target, method, callback); } /** Return a list of currently watched events @private @method watchedEvents @for Ember @param obj */ function watchedEvents(obj) { return _emberMetalMeta.meta(obj).watchedEvents(); } /** Send an event. The execution of suspended listeners is skipped, and once listeners are removed. A listener without a target is executed on the passed object. If an array of actions is not passed, the actions stored on the passed object are invoked. @method sendEvent @for Ember @param obj @param {String} eventName @param {Array} params Optional parameters for each listener. @param {Array} actions Optional array of actions (listeners). @return true @public */ function sendEvent(obj, eventName, params, actions) { if (!actions) { var meta = _emberMetalMeta.peekMeta(obj); actions = meta && meta.matchingListeners(eventName); } if (!actions || actions.length === 0) { return; } for (var i = actions.length - 3; i >= 0; i -= 3) { // looping in reverse for once listeners var target = actions[i]; var method = actions[i + 1]; var flags = actions[i + 2]; if (!method) { continue; } if (flags & _emberMetalMeta_listeners.SUSPENDED) { continue; } if (flags & _emberMetalMeta_listeners.ONCE) { removeListener(obj, eventName, target, method); } if (!target) { target = obj; } if ('string' === typeof method) { if (params) { _emberMetalUtils.applyStr(target, method, params); } else { target[method](); } } else { if (params) { method.apply(target, params); } else { method.call(target); } } } return true; } /** @private @method hasListeners @for Ember @param obj @param {String} eventName */ function hasListeners(obj, eventName) { var meta = _emberMetalMeta.peekMeta(obj); if (!meta) { return false; } return meta.matchingListeners(eventName).length > 0; } /** @private @method listenersFor @for Ember @param obj @param {String} eventName */ function listenersFor(obj, eventName) { var ret = []; var meta = _emberMetalMeta.peekMeta(obj); var actions = meta && meta.matchingListeners(eventName); if (!actions) { return ret; } for (var i = 0; i < actions.length; i += 3) { var target = actions[i]; var method = actions[i + 1]; ret.push([target, method]); } return ret; } /** Define a property as a function that should be executed when a specified event or events are triggered. ``` javascript let Job = Ember.Object.extend({ logCompleted: Ember.on('completed', function() { console.log('Job completed!'); }) }); let job = Job.create(); Ember.sendEvent(job, 'completed'); // Logs 'Job completed!' ``` @method on @for Ember @param {String} eventNames* @param {Function} func @return func @public */ function on() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var func = args.pop(); var events = args; func.__ember_listens__ = events; return func; } }); enifed('ember-metal/expand_properties', ['exports', 'ember-metal/debug'], function (exports, _emberMetalDebug) { 'use strict'; exports.default = expandProperties; /** @module ember @submodule ember-metal */ var SPLIT_REGEX = /\{|\}/; var END_WITH_EACH_REGEX = /\.@each$/; /** Expands `pattern`, invoking `callback` for each expansion. The only pattern supported is brace-expansion, anything else will be passed once to `callback` directly. Example ```js function echo(arg){ console.log(arg); } Ember.expandProperties('foo.bar', echo); //=> 'foo.bar' Ember.expandProperties('{foo,bar}', echo); //=> 'foo', 'bar' Ember.expandProperties('foo.{bar,baz}', echo); //=> 'foo.bar', 'foo.baz' Ember.expandProperties('{foo,bar}.baz', echo); //=> 'foo.baz', 'bar.baz' Ember.expandProperties('foo.{bar,baz}.[]', echo) //=> 'foo.bar.[]', 'foo.baz.[]' Ember.expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs' Ember.expandProperties('{foo}.bar.{baz}') //=> 'foo.bar.baz' ``` @method expandProperties @for Ember @private @param {String} pattern The property pattern to expand. @param {Function} callback The callback to invoke. It is invoked once per expansion, and is passed the expansion. */ function expandProperties(pattern, callback) { _emberMetalDebug.assert('A computed property key must be a string', typeof pattern === 'string'); _emberMetalDebug.assert('Brace expanded properties cannot contain spaces, e.g. "user.{firstName, lastName}" should be "user.{firstName,lastName}"', pattern.indexOf(' ') === -1); var parts = pattern.split(SPLIT_REGEX); var properties = [parts]; for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (part.indexOf(',') >= 0) { properties = duplicateAndReplace(properties, part.split(','), i); } } for (var i = 0; i < properties.length; i++) { callback(properties[i].join('').replace(END_WITH_EACH_REGEX, '.[]')); } } function duplicateAndReplace(properties, currentParts, index) { var all = []; properties.forEach(function (property) { currentParts.forEach(function (part) { var current = property.slice(0); current[index] = part; all.push(current); }); }); return all; } }); enifed('ember-metal/features', ['exports', 'ember-environment', 'ember-metal/assign', 'ember/features'], function (exports, _emberEnvironment, _emberMetalAssign, _emberFeatures) { 'use strict'; exports.default = isEnabled; /** The hash of enabled Canary features. Add to this, any canary features before creating your application. Alternatively (and recommended), you can also define `EmberENV.FEATURES` if you need to enable features flagged at runtime. @class FEATURES @namespace Ember @static @since 1.1.0 @public */ var FEATURES = _emberMetalAssign.default(_emberFeatures.default, _emberEnvironment.ENV.FEATURES); exports.FEATURES = FEATURES; /** Determine whether the specified `feature` is enabled. Used by Ember's build tools to exclude experimental features from beta/stable builds. You can define the following configuration options: * `EmberENV.ENABLE_OPTIONAL_FEATURES` - enable any features that have not been explicitly enabled/disabled. @method isEnabled @param {String} feature The feature to check @return {Boolean} @for Ember.FEATURES @since 1.1.0 @public */ function isEnabled(feature) { var featureValue = FEATURES[feature]; if (featureValue === true || featureValue === false || featureValue === undefined) { return featureValue; } else if (_emberEnvironment.ENV.ENABLE_OPTIONAL_FEATURES) { return true; } else { return false; } } exports.DEFAULT_FEATURES = _emberFeatures.default; }); enifed('ember-metal/get_properties', ['exports', 'ember-metal/property_get'], function (exports, _emberMetalProperty_get) { 'use strict'; exports.default = getProperties; /** To get multiple properties at once, call `Ember.getProperties` with an object followed by a list of strings or an array: ```javascript Ember.getProperties(record, 'firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` is equivalent to: ```javascript Ember.getProperties(record, ['firstName', 'lastName', 'zipCode']); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` @method getProperties @for Ember @param {Object} obj @param {String...|Array} list of keys to get @return {Object} @public */ function getProperties(obj) { var ret = {}; var propertyNames = arguments; var i = 1; if (arguments.length === 2 && Array.isArray(arguments[1])) { i = 0; propertyNames = arguments[1]; } for (; i < propertyNames.length; i++) { ret[propertyNames[i]] = _emberMetalProperty_get.get(obj, propertyNames[i]); } return ret; } }); enifed('ember-metal/index', ['exports', 'require', 'ember-environment', 'ember/version', 'ember-metal/core', 'ember-metal/debug', 'ember-metal/features', 'ember-metal/assign', 'ember-metal/merge', 'ember-metal/instrumentation', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/error', 'ember-metal/cache', 'ember-console', 'ember-metal/property_get', 'ember-metal/events', 'ember-metal/observer_set', 'ember-metal/property_events', 'ember-metal/properties', 'ember-metal/property_set', 'ember-metal/weak_map', 'ember-metal/map', 'ember-metal/get_properties', 'ember-metal/set_properties', 'ember-metal/watch_key', 'ember-metal/chains', 'ember-metal/watch_path', 'ember-metal/watching', 'ember-metal/expand_properties', 'ember-metal/computed', 'ember-metal/alias', 'ember-metal/observer', 'ember-metal/mixin', 'ember-metal/binding', 'ember-metal/path_cache', 'ember-metal/testing', 'ember-metal/error_handler', 'ember-metal/run_loop', 'ember-metal/libraries', 'ember-metal/is_none', 'ember-metal/is_empty', 'ember-metal/is_blank', 'ember-metal/is_present', 'backburner'], function (exports, _require, _emberEnvironment, _emberVersion, _emberMetalCore, _emberMetalDebug, _emberMetalFeatures, _emberMetalAssign, _emberMetalMerge, _emberMetalInstrumentation, _emberMetalUtils, _emberMetalMeta, _emberMetalError, _emberMetalCache, _emberConsole, _emberMetalProperty_get, _emberMetalEvents, _emberMetalObserver_set, _emberMetalProperty_events, _emberMetalProperties, _emberMetalProperty_set, _emberMetalWeak_map, _emberMetalMap, _emberMetalGet_properties, _emberMetalSet_properties, _emberMetalWatch_key, _emberMetalChains, _emberMetalWatch_path, _emberMetalWatching, _emberMetalExpand_properties, _emberMetalComputed, _emberMetalAlias, _emberMetalObserver, _emberMetalMixin, _emberMetalBinding, _emberMetalPath_cache, _emberMetalTesting, _emberMetalError_handler, _emberMetalRun_loop, _emberMetalLibraries, _emberMetalIs_none, _emberMetalIs_empty, _emberMetalIs_blank, _emberMetalIs_present, _backburner) { /** @module ember @submodule ember-metal */ // BEGIN IMPORTS 'use strict'; _emberMetalComputed.computed.alias = _emberMetalAlias.default; // END IMPORTS // BEGIN EXPORTS var EmberInstrumentation = _emberMetalCore.default.Instrumentation = {}; EmberInstrumentation.instrument = _emberMetalInstrumentation.instrument; EmberInstrumentation.subscribe = _emberMetalInstrumentation.subscribe; EmberInstrumentation.unsubscribe = _emberMetalInstrumentation.unsubscribe; EmberInstrumentation.reset = _emberMetalInstrumentation.reset; _emberMetalCore.default.instrument = _emberMetalInstrumentation.instrument; _emberMetalCore.default.subscribe = _emberMetalInstrumentation.subscribe; _emberMetalCore.default._Cache = _emberMetalCache.default; _emberMetalCore.default.generateGuid = _emberMetalUtils.generateGuid; _emberMetalCore.default.GUID_KEY = _emberMetalUtils.GUID_KEY; _emberMetalCore.default.NAME_KEY = _emberMetalMixin.NAME_KEY; _emberMetalCore.default.platform = { defineProperty: true, hasPropertyAccessors: true }; _emberMetalCore.default.Error = _emberMetalError.default; _emberMetalCore.default.guidFor = _emberMetalUtils.guidFor; _emberMetalCore.default.META_DESC = _emberMetalMeta.META_DESC; _emberMetalCore.default.meta = _emberMetalMeta.meta; _emberMetalCore.default.inspect = _emberMetalUtils.inspect; _emberMetalCore.default.tryCatchFinally = _emberMetalUtils.deprecatedTryCatchFinally; _emberMetalCore.default.makeArray = _emberMetalUtils.makeArray; _emberMetalCore.default.canInvoke = _emberMetalUtils.canInvoke; _emberMetalCore.default.tryInvoke = _emberMetalUtils.tryInvoke; _emberMetalCore.default.wrap = _emberMetalUtils.wrap; _emberMetalCore.default.apply = _emberMetalUtils.apply; _emberMetalCore.default.applyStr = _emberMetalUtils.applyStr; _emberMetalCore.default.uuid = _emberMetalUtils.uuid; _emberMetalCore.default.Logger = _emberConsole.default; _emberMetalCore.default.get = _emberMetalProperty_get.get; _emberMetalCore.default.getWithDefault = _emberMetalProperty_get.getWithDefault; _emberMetalCore.default._getPath = _emberMetalProperty_get._getPath; _emberMetalCore.default.on = _emberMetalEvents.on; _emberMetalCore.default.addListener = _emberMetalEvents.addListener; _emberMetalCore.default.removeListener = _emberMetalEvents.removeListener; _emberMetalCore.default._suspendListener = _emberMetalEvents.suspendListener; _emberMetalCore.default._suspendListeners = _emberMetalEvents.suspendListeners; _emberMetalCore.default.sendEvent = _emberMetalEvents.sendEvent; _emberMetalCore.default.hasListeners = _emberMetalEvents.hasListeners; _emberMetalCore.default.watchedEvents = _emberMetalEvents.watchedEvents; _emberMetalCore.default.listenersFor = _emberMetalEvents.listenersFor; _emberMetalCore.default.accumulateListeners = _emberMetalEvents.accumulateListeners; _emberMetalCore.default._ObserverSet = _emberMetalObserver_set.default; _emberMetalCore.default.propertyWillChange = _emberMetalProperty_events.propertyWillChange; _emberMetalCore.default.propertyDidChange = _emberMetalProperty_events.propertyDidChange; _emberMetalCore.default.overrideChains = _emberMetalProperty_events.overrideChains; _emberMetalCore.default.beginPropertyChanges = _emberMetalProperty_events.beginPropertyChanges; _emberMetalCore.default.endPropertyChanges = _emberMetalProperty_events.endPropertyChanges; _emberMetalCore.default.changeProperties = _emberMetalProperty_events.changeProperties; _emberMetalCore.default.defineProperty = _emberMetalProperties.defineProperty; _emberMetalCore.default.set = _emberMetalProperty_set.set; _emberMetalCore.default.trySet = _emberMetalProperty_set.trySet; if (false) { _emberMetalCore.default.WeakMap = _emberMetalWeak_map.default; } _emberMetalCore.default.OrderedSet = _emberMetalMap.OrderedSet; _emberMetalCore.default.Map = _emberMetalMap.Map; _emberMetalCore.default.MapWithDefault = _emberMetalMap.MapWithDefault; _emberMetalCore.default.getProperties = _emberMetalGet_properties.default; _emberMetalCore.default.setProperties = _emberMetalSet_properties.default; _emberMetalCore.default.watchKey = _emberMetalWatch_key.watchKey; _emberMetalCore.default.unwatchKey = _emberMetalWatch_key.unwatchKey; _emberMetalCore.default.removeChainWatcher = _emberMetalChains.removeChainWatcher; _emberMetalCore.default._ChainNode = _emberMetalChains.ChainNode; _emberMetalCore.default.finishChains = _emberMetalChains.finishChains; _emberMetalCore.default.watchPath = _emberMetalWatch_path.watchPath; _emberMetalCore.default.unwatchPath = _emberMetalWatch_path.unwatchPath; _emberMetalCore.default.watch = _emberMetalWatching.watch; _emberMetalCore.default.isWatching = _emberMetalWatching.isWatching; _emberMetalCore.default.unwatch = _emberMetalWatching.unwatch; _emberMetalCore.default.rewatch = _emberMetalWatching.rewatch; _emberMetalCore.default.destroy = _emberMetalWatching.destroy; _emberMetalCore.default.expandProperties = _emberMetalExpand_properties.default; _emberMetalCore.default.ComputedProperty = _emberMetalComputed.ComputedProperty; _emberMetalCore.default.computed = _emberMetalComputed.computed; _emberMetalCore.default.cacheFor = _emberMetalComputed.cacheFor; _emberMetalCore.default.addObserver = _emberMetalObserver.addObserver; _emberMetalCore.default.observersFor = _emberMetalObserver.observersFor; _emberMetalCore.default.removeObserver = _emberMetalObserver.removeObserver; _emberMetalCore.default._suspendObserver = _emberMetalObserver._suspendObserver; _emberMetalCore.default._suspendObservers = _emberMetalObserver._suspendObservers; _emberMetalCore.default.required = _emberMetalMixin.required; _emberMetalCore.default.aliasMethod = _emberMetalMixin.aliasMethod; _emberMetalCore.default.observer = _emberMetalMixin.observer; _emberMetalCore.default.immediateObserver = _emberMetalMixin._immediateObserver; _emberMetalCore.default.mixin = _emberMetalMixin.mixin; _emberMetalCore.default.Mixin = _emberMetalMixin.Mixin; _emberMetalCore.default.bind = _emberMetalBinding.bind; _emberMetalCore.default.Binding = _emberMetalBinding.Binding; _emberMetalCore.default.isGlobalPath = _emberMetalPath_cache.isGlobalPath; _emberMetalCore.default.run = _emberMetalRun_loop.default; /** @class Backburner @for Ember @private */ _emberMetalCore.default.Backburner = function () { _emberMetalDebug.deprecate('Usage of Ember.Backburner is deprecated.', false, { id: 'ember-metal.ember-backburner', until: '2.8.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-backburner' }); function BackburnerAlias(args) { return _backburner.default.apply(this, args); } BackburnerAlias.prototype = _backburner.default.prototype; return new BackburnerAlias(arguments); }; _emberMetalCore.default._Backburner = _backburner.default; /** The semantic version @property VERSION @type String @public */ _emberMetalCore.default.VERSION = _emberVersion.default; _emberMetalCore.default.libraries = _emberMetalLibraries.default; _emberMetalLibraries.default.registerCoreLibrary('Ember', _emberMetalCore.default.VERSION); _emberMetalCore.default.isNone = _emberMetalIs_none.default; _emberMetalCore.default.isEmpty = _emberMetalIs_empty.default; _emberMetalCore.default.isBlank = _emberMetalIs_blank.default; _emberMetalCore.default.isPresent = _emberMetalIs_present.default; _emberMetalCore.default.assign = Object.assign || _emberMetalAssign.default; _emberMetalCore.default.merge = _emberMetalMerge.default; _emberMetalCore.default.FEATURES = _emberMetalFeatures.FEATURES; _emberMetalCore.default.FEATURES.isEnabled = _emberMetalFeatures.default; _emberMetalCore.default.EXTEND_PROTOTYPES = _emberEnvironment.ENV.EXTEND_PROTOTYPES; // BACKWARDS COMPAT ACCESSORS FOR ENV FLAGS Object.defineProperty(_emberMetalCore.default, 'LOG_STACKTRACE_ON_DEPRECATION', { get: function () { return _emberEnvironment.ENV.LOG_STACKTRACE_ON_DEPRECATION; }, set: function (value) { _emberEnvironment.ENV.LOG_STACKTRACE_ON_DEPRECATION = !!value; }, enumerable: false }); Object.defineProperty(_emberMetalCore.default, 'LOG_VERSION', { get: function () { return _emberEnvironment.ENV.LOG_VERSION; }, set: function (value) { _emberEnvironment.ENV.LOG_VERSION = !!value; }, enumerable: false }); Object.defineProperty(_emberMetalCore.default, 'MODEL_FACTORY_INJECTIONS', { get: function () { return _emberEnvironment.ENV.MODEL_FACTORY_INJECTIONS; }, set: function (value) { _emberEnvironment.ENV.MODEL_FACTORY_INJECTIONS = !!value; }, enumerable: false }); Object.defineProperty(_emberMetalCore.default, 'LOG_BINDINGS', { get: function () { return _emberEnvironment.ENV.LOG_BINDINGS; }, set: function (value) { _emberEnvironment.ENV.LOG_BINDINGS = !!value; }, enumerable: false }); Object.defineProperty(_emberMetalCore.default, 'ENV', { get: function () { return _emberEnvironment.ENV; }, enumerable: false }); /** The context that Ember searches for namespace instances on. @private */ Object.defineProperty(_emberMetalCore.default, 'lookup', { get: function () { return _emberEnvironment.context.lookup; }, set: function (value) { _emberEnvironment.context.lookup = value; }, enumerable: false }); Object.defineProperty(_emberMetalCore.default, 'testing', { get: _emberMetalTesting.isTesting, set: _emberMetalTesting.setTesting, enumerable: false }); /** A function may be assigned to `Ember.onerror` to be called when Ember internals encounter an error. This is useful for specialized error handling and reporting code. ```javascript Ember.onerror = function(error) { Em.$.ajax('/report-error', 'POST', { stack: error.stack, otherInformation: 'whatever app state you want to provide' }); }; ``` Internally, `Ember.onerror` is used as Backburner's error handler. @event onerror @for Ember @param {Exception} error the error object @public */ Object.defineProperty(_emberMetalCore.default, 'onerror', { get: _emberMetalError_handler.getOnerror, set: _emberMetalError_handler.setOnerror, enumerable: false }); /** An empty function useful for some operations. Always returns `this`. @method K @return {Object} @public */ _emberMetalCore.default.K = function K() { return this; }; // The debug functions are exported to globals with `require` to // prevent babel-plugin-filter-imports from removing them. var debugModule = _require.default('ember-metal/debug'); _emberMetalCore.default.assert = debugModule.assert; _emberMetalCore.default.warn = debugModule.warn; _emberMetalCore.default.debug = debugModule.debug; _emberMetalCore.default.deprecate = debugModule.deprecate; _emberMetalCore.default.deprecateFunc = debugModule.deprecateFunc; _emberMetalCore.default.runInDebug = debugModule.runInDebug; // END EXPORTS // do this for side-effects of updating Ember.assert, warn, etc when // ember-debug is present // This needs to be called before any deprecateFunc if (_require.has('ember-debug')) { _require.default('ember-debug'); } else { _emberMetalCore.default.Debug = {}; _emberMetalCore.default.Debug.registerDeprecationHandler = function () {}; _emberMetalCore.default.Debug.registerWarnHandler = function () {}; } _emberMetalCore.default.create = _emberMetalDebug.deprecateFunc('Ember.create is deprecated in favor of Object.create', { id: 'ember-metal.ember-create', until: '3.0.0' }, Object.create); _emberMetalCore.default.keys = _emberMetalDebug.deprecateFunc('Ember.keys is deprecated in favor of Object.keys', { id: 'ember-metal.ember.keys', until: '3.0.0' }, Object.keys); /* globals module */ if (typeof module === 'object' && module.exports) { module.exports = _emberMetalCore.default; } else { _emberEnvironment.context.exports.Ember = _emberEnvironment.context.exports.Em = _emberMetalCore.default; } exports.default = _emberMetalCore.default; }); // reexports enifed('ember-metal/injected_property', ['exports', 'ember-metal/debug', 'ember-metal/computed', 'ember-metal/alias', 'ember-metal/properties', 'container/owner'], function (exports, _emberMetalDebug, _emberMetalComputed, _emberMetalAlias, _emberMetalProperties, _containerOwner) { 'use strict'; exports.default = InjectedProperty; /** Read-only property that returns the result of a container lookup. @class InjectedProperty @namespace Ember @constructor @param {String} type The container type the property will lookup @param {String} name (optional) The name the property will lookup, defaults to the property's name @private */ function InjectedProperty(type, name) { this.type = type; this.name = name; this._super$Constructor(injectedPropertyGet); AliasedPropertyPrototype.oneWay.call(this); } function injectedPropertyGet(keyName) { var desc = this[keyName]; var owner = _containerOwner.getOwner(this) || this.container; // fallback to `container` for backwards compat _emberMetalDebug.assert('InjectedProperties should be defined with the Ember.inject computed property macros.', desc && desc.isDescriptor && desc.type); _emberMetalDebug.assert('Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container.', owner); return owner.lookup(desc.type + ':' + (desc.name || keyName)); } InjectedProperty.prototype = Object.create(_emberMetalProperties.Descriptor.prototype); var InjectedPropertyPrototype = InjectedProperty.prototype; var ComputedPropertyPrototype = _emberMetalComputed.ComputedProperty.prototype; var AliasedPropertyPrototype = _emberMetalAlias.AliasedProperty.prototype; InjectedPropertyPrototype._super$Constructor = _emberMetalComputed.ComputedProperty; InjectedPropertyPrototype.get = ComputedPropertyPrototype.get; InjectedPropertyPrototype.readOnly = ComputedPropertyPrototype.readOnly; InjectedPropertyPrototype.teardown = ComputedPropertyPrototype.teardown; }); enifed('ember-metal/instrumentation', ['exports', 'ember-environment', 'ember-metal/features'], function (exports, _emberEnvironment, _emberMetalFeatures) { 'use strict'; exports.instrument = instrument; exports._instrumentStart = _instrumentStart; exports.subscribe = subscribe; exports.unsubscribe = unsubscribe; exports.reset = reset; /** The purpose of the Ember Instrumentation module is to provide efficient, general-purpose instrumentation for Ember. Subscribe to a listener by using `Ember.subscribe`: ```javascript Ember.subscribe("render", { before(name, timestamp, payload) { }, after(name, timestamp, payload) { } }); ``` If you return a value from the `before` callback, that same value will be passed as a fourth parameter to the `after` callback. Instrument a block of code by using `Ember.instrument`: ```javascript Ember.instrument("render.handlebars", payload, function() { // rendering logic }, binding); ``` Event names passed to `Ember.instrument` are namespaced by periods, from more general to more specific. Subscribers can listen for events by whatever level of granularity they are interested in. In the above example, the event is `render.handlebars`, and the subscriber listened for all events beginning with `render`. It would receive callbacks for events named `render`, `render.handlebars`, `render.container`, or even `render.handlebars.layout`. @class Instrumentation @namespace Ember @static @private */ var subscribers = []; exports.subscribers = subscribers; var cache = {}; function populateListeners(name) { var listeners = []; var subscriber = undefined; for (var i = 0; i < subscribers.length; i++) { subscriber = subscribers[i]; if (subscriber.regex.test(name)) { listeners.push(subscriber.object); } } cache[name] = listeners; return listeners; } var time = (function () { var perf = 'undefined' !== typeof window ? window.performance || {} : {}; var fn = perf.now || perf.mozNow || perf.webkitNow || perf.msNow || perf.oNow; // fn.bind will be available in all the browsers that support the advanced window.performance... ;-) return fn ? fn.bind(perf) : function () { return +new Date(); }; })(); /** Notifies event's subscribers, calls `before` and `after` hooks. @method instrument @namespace Ember.Instrumentation @param {String} [name] Namespaced event name. @param {Object} _payload @param {Function} callback Function that you're instrumenting. @param {Object} binding Context that instrument function is called with. @private */ function instrument(name, _payload, callback, binding) { if (arguments.length <= 3 && typeof _payload === 'function') { binding = callback; callback = _payload; _payload = undefined; } if (subscribers.length === 0) { return callback.call(binding); } var payload = _payload || {}; var finalizer = _instrumentStart(name, function () { return payload; }); if (finalizer) { return withFinalizer(callback, finalizer, payload, binding); } else { return callback.call(binding); } } var flaggedInstrument = undefined; if (false) { exports.flaggedInstrument = flaggedInstrument = instrument; } else { exports.flaggedInstrument = flaggedInstrument = function (name, payload, callback) { return callback(); }; } exports.flaggedInstrument = flaggedInstrument; function withFinalizer(callback, finalizer, payload, binding) { var result = undefined; try { result = callback.call(binding); } catch (e) { payload.exception = e; result = payload; } finally { finalizer(); return result; } } // private for now function _instrumentStart(name, _payload) { var listeners = cache[name]; if (!listeners) { listeners = populateListeners(name); } if (listeners.length === 0) { return; } var payload = _payload(); var STRUCTURED_PROFILE = _emberEnvironment.ENV.STRUCTURED_PROFILE; var timeName = undefined; if (STRUCTURED_PROFILE) { timeName = name + ': ' + payload.object; console.time(timeName); } var beforeValues = new Array(listeners.length); var i = undefined, listener = undefined; var timestamp = time(); for (i = 0; i < listeners.length; i++) { listener = listeners[i]; beforeValues[i] = listener.before(name, timestamp, payload); } return function _instrumentEnd() { var i = undefined, listener = undefined; var timestamp = time(); for (i = 0; i < listeners.length; i++) { listener = listeners[i]; if (typeof listener.after === 'function') { listener.after(name, timestamp, payload, beforeValues[i]); } } if (STRUCTURED_PROFILE) { console.timeEnd(timeName); } }; } /** Subscribes to a particular event or instrumented block of code. @method subscribe @namespace Ember.Instrumentation @param {String} [pattern] Namespaced event name. @param {Object} [object] Before and After hooks. @return {Subscriber} @private */ function subscribe(pattern, object) { var paths = pattern.split('.'); var path = undefined; var regex = []; for (var i = 0; i < paths.length; i++) { path = paths[i]; if (path === '*') { regex.push('[^\\.]*'); } else { regex.push(path); } } regex = regex.join('\\.'); regex = regex + '(\\..*)?'; var subscriber = { pattern: pattern, regex: new RegExp('^' + regex + '$'), object: object }; subscribers.push(subscriber); cache = {}; return subscriber; } /** Unsubscribes from a particular event or instrumented block of code. @method unsubscribe @namespace Ember.Instrumentation @param {Object} [subscriber] @private */ function unsubscribe(subscriber) { var index = undefined; for (var i = 0; i < subscribers.length; i++) { if (subscribers[i] === subscriber) { index = i; } } subscribers.splice(index, 1); cache = {}; } /** Resets `Ember.Instrumentation` by flushing list of subscribers. @method reset @namespace Ember.Instrumentation @private */ function reset() { subscribers.length = 0; cache = {}; } }); enifed('ember-metal/is_blank', ['exports', 'ember-metal/is_empty'], function (exports, _emberMetalIs_empty) { 'use strict'; exports.default = isBlank; /** A value is blank if it is empty or a whitespace string. ```javascript Ember.isBlank(); // true Ember.isBlank(null); // true Ember.isBlank(undefined); // true Ember.isBlank(''); // true Ember.isBlank([]); // true Ember.isBlank('\n\t'); // true Ember.isBlank(' '); // true Ember.isBlank({}); // false Ember.isBlank('\n\t Hello'); // false Ember.isBlank('Hello world'); // false Ember.isBlank([1,2,3]); // false ``` @method isBlank @for Ember @param {Object} obj Value to test @return {Boolean} @since 1.5.0 @public */ function isBlank(obj) { return _emberMetalIs_empty.default(obj) || typeof obj === 'string' && obj.match(/\S/) === null; } }); enifed('ember-metal/is_empty', ['exports', 'ember-metal/property_get', 'ember-metal/is_none'], function (exports, _emberMetalProperty_get, _emberMetalIs_none) { 'use strict'; exports.default = isEmpty; /** Verifies that a value is `null` or an empty string, empty array, or empty function. Constrains the rules on `Ember.isNone` by returning true for empty string and empty arrays. ```javascript Ember.isEmpty(); // true Ember.isEmpty(null); // true Ember.isEmpty(undefined); // true Ember.isEmpty(''); // true Ember.isEmpty([]); // true Ember.isEmpty({}); // false Ember.isEmpty('Adam Hawkins'); // false Ember.isEmpty([0,1,2]); // false Ember.isEmpty('\n\t'); // false Ember.isEmpty(' '); // false ``` @method isEmpty @for Ember @param {Object} obj Value to test @return {Boolean} @public */ function isEmpty(obj) { var none = _emberMetalIs_none.default(obj); if (none) { return none; } if (typeof obj.size === 'number') { return !obj.size; } var objectType = typeof obj; if (objectType === 'object') { var size = _emberMetalProperty_get.get(obj, 'size'); if (typeof size === 'number') { return !size; } } if (typeof obj.length === 'number' && objectType !== 'function') { return !obj.length; } if (objectType === 'object') { var _length = _emberMetalProperty_get.get(obj, 'length'); if (typeof _length === 'number') { return !_length; } } return false; } }); enifed("ember-metal/is_none", ["exports"], function (exports) { /** Returns true if the passed value is null or undefined. This avoids errors from JSLint complaining about use of ==, which can be technically confusing. ```javascript Ember.isNone(); // true Ember.isNone(null); // true Ember.isNone(undefined); // true Ember.isNone(''); // false Ember.isNone([]); // false Ember.isNone(function() {}); // false ``` @method isNone @for Ember @param {Object} obj Value to test @return {Boolean} @public */ "use strict"; exports.default = isNone; function isNone(obj) { return obj === null || obj === undefined; } }); enifed('ember-metal/is_present', ['exports', 'ember-metal/is_blank'], function (exports, _emberMetalIs_blank) { 'use strict'; exports.default = isPresent; /** A value is present if it not `isBlank`. ```javascript Ember.isPresent(); // false Ember.isPresent(null); // false Ember.isPresent(undefined); // false Ember.isPresent(''); // false Ember.isPresent(' '); // false Ember.isPresent('\n\t'); // false Ember.isPresent([]); // false Ember.isPresent({ length: 0 }) // false Ember.isPresent(false); // true Ember.isPresent(true); // true Ember.isPresent('string'); // true Ember.isPresent(0); // true Ember.isPresent(function() {}) // true Ember.isPresent({}); // true Ember.isPresent(false); // true Ember.isPresent('\n\t Hello'); // true Ember.isPresent([1,2,3]); // true ``` @method isPresent @for Ember @param {Object} obj Value to test @return {Boolean} @since 1.8.0 @public */ function isPresent(obj) { return !_emberMetalIs_blank.default(obj); } }); enifed('ember-metal/libraries', ['exports', 'ember-metal/debug', 'ember-metal/features'], function (exports, _emberMetalDebug, _emberMetalFeatures) { 'use strict'; exports.Libraries = Libraries; /** Helper class that allows you to register your library with Ember. Singleton created at `Ember.libraries`. @class Libraries @constructor @private */ function Libraries() { this._registry = []; this._coreLibIndex = 0; } Libraries.prototype = { constructor: Libraries, _getLibraryByName: function (name) { var libs = this._registry; var count = libs.length; for (var i = 0; i < count; i++) { if (libs[i].name === name) { return libs[i]; } } }, register: function (name, version, isCoreLibrary) { var index = this._registry.length; if (!this._getLibraryByName(name)) { if (isCoreLibrary) { index = this._coreLibIndex++; } this._registry.splice(index, 0, { name: name, version: version }); } else { _emberMetalDebug.warn('Library "' + name + '" is already registered with Ember.', false, { id: 'ember-metal.libraries-register' }); } }, registerCoreLibrary: function (name, version) { this.register(name, version, true); }, deRegister: function (name) { var lib = this._getLibraryByName(name); var index = undefined; if (lib) { index = this._registry.indexOf(lib); this._registry.splice(index, 1); } } }; if (false) { Libraries.prototype.isRegistered = function (name) { return !!this._getLibraryByName(name); }; } exports.default = new Libraries(); }); enifed('ember-metal/map', ['exports', 'ember-metal/utils', 'ember-metal/empty_object'], function (exports, _emberMetalUtils, _emberMetalEmpty_object) { /** @module ember @submodule ember-metal */ /* JavaScript (before ES6) does not have a Map implementation. Objects, which are often used as dictionaries, may only have Strings as keys. Because Ember has a way to get a unique identifier for every object via `Ember.guidFor`, we can implement a performant Map with arbitrary keys. Because it is commonly used in low-level bookkeeping, Map is implemented as a pure JavaScript object for performance. This implementation follows the current iteration of the ES6 proposal for maps (http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets), with one exception: as we do not have the luxury of in-VM iteration, we implement a forEach method for iteration. Map is mocked out to look like an Ember object, so you can do `Ember.Map.create()` for symmetry with other Ember classes. */ 'use strict'; function missingFunction(fn) { throw new TypeError(Object.prototype.toString.call(fn) + ' is not a function'); } function missingNew(name) { throw new TypeError('Constructor ' + name + ' requires \'new\''); } function copyNull(obj) { var output = new _emberMetalEmpty_object.default(); for (var prop in obj) { // hasOwnPropery is not needed because obj is new EmptyObject(); output[prop] = obj[prop]; } return output; } function copyMap(original, newObject) { var keys = original._keys.copy(); var values = copyNull(original._values); newObject._keys = keys; newObject._values = values; newObject.size = original.size; return newObject; } /** This class is used internally by Ember and Ember Data. Please do not use it at this time. We plan to clean it up and add many tests soon. @class OrderedSet @namespace Ember @constructor @private */ function OrderedSet() { if (this instanceof OrderedSet) { this.clear(); this._silenceRemoveDeprecation = false; } else { missingNew('OrderedSet'); } } /** @method create @static @return {Ember.OrderedSet} @private */ OrderedSet.create = function () { var Constructor = this; return new Constructor(); }; OrderedSet.prototype = { constructor: OrderedSet, /** @method clear @private */ clear: function () { this.presenceSet = new _emberMetalEmpty_object.default(); this.list = []; this.size = 0; }, /** @method add @param obj @param guid (optional, and for internal use) @return {Ember.OrderedSet} @private */ add: function (obj, _guid) { var guid = _guid || _emberMetalUtils.guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] !== true) { presenceSet[guid] = true; this.size = list.push(obj); } return this; }, /** @since 1.8.0 @method delete @param obj @param _guid (optional and for internal use only) @return {Boolean} @private */ delete: function (obj, _guid) { var guid = _guid || _emberMetalUtils.guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] === true) { delete presenceSet[guid]; var index = list.indexOf(obj); if (index > -1) { list.splice(index, 1); } this.size = list.length; return true; } else { return false; } }, /** @method isEmpty @return {Boolean} @private */ isEmpty: function () { return this.size === 0; }, /** @method has @param obj @return {Boolean} @private */ has: function (obj) { if (this.size === 0) { return false; } var guid = _emberMetalUtils.guidFor(obj); var presenceSet = this.presenceSet; return presenceSet[guid] === true; }, /** @method forEach @param {Function} fn @param self @private */ forEach: function (fn /*, ...thisArg*/) { if (typeof fn !== 'function') { missingFunction(fn); } if (this.size === 0) { return; } var list = this.list; if (arguments.length === 2) { for (var i = 0; i < list.length; i++) { fn.call(arguments[1], list[i]); } } else { for (var i = 0; i < list.length; i++) { fn(list[i]); } } }, /** @method toArray @return {Array} @private */ toArray: function () { return this.list.slice(); }, /** @method copy @return {Ember.OrderedSet} @private */ copy: function () { var Constructor = this.constructor; var set = new Constructor(); set._silenceRemoveDeprecation = this._silenceRemoveDeprecation; set.presenceSet = copyNull(this.presenceSet); set.list = this.toArray(); set.size = this.size; return set; } }; /** A Map stores values indexed by keys. Unlike JavaScript's default Objects, the keys of a Map can be any JavaScript object. Internally, a Map has two data structures: 1. `keys`: an OrderedSet of all of the existing keys 2. `values`: a JavaScript Object indexed by the `Ember.guidFor(key)` When a key/value pair is added for the first time, we add the key to the `keys` OrderedSet, and create or replace an entry in `values`. When an entry is deleted, we delete its entry in `keys` and `values`. @class Map @namespace Ember @private @constructor */ function Map() { if (this instanceof Map) { this._keys = OrderedSet.create(); this._keys._silenceRemoveDeprecation = true; this._values = new _emberMetalEmpty_object.default(); this.size = 0; } else { missingNew('Map'); } } /** @method create @static @private */ Map.create = function () { var Constructor = this; return new Constructor(); }; Map.prototype = { constructor: Map, /** This property will change as the number of objects in the map changes. @since 1.8.0 @property size @type number @default 0 @private */ size: 0, /** Retrieve the value associated with a given key. @method get @param {*} key @return {*} the value associated with the key, or `undefined` @private */ get: function (key) { if (this.size === 0) { return; } var values = this._values; var guid = _emberMetalUtils.guidFor(key); return values[guid]; }, /** Adds a value to the map. If a value for the given key has already been provided, the new value will replace the old value. @method set @param {*} key @param {*} value @return {Ember.Map} @private */ set: function (key, value) { var keys = this._keys; var values = this._values; var guid = _emberMetalUtils.guidFor(key); // ensure we don't store -0 var k = key === -0 ? 0 : key; keys.add(k, guid); values[guid] = value; this.size = keys.size; return this; }, /** Removes a value from the map for an associated key. @since 1.8.0 @method delete @param {*} key @return {Boolean} true if an item was removed, false otherwise @private */ delete: function (key) { if (this.size === 0) { return false; } // don't use ES6 "delete" because it will be annoying // to use in browsers that are not ES6 friendly; var keys = this._keys; var values = this._values; var guid = _emberMetalUtils.guidFor(key); if (keys.delete(key, guid)) { delete values[guid]; this.size = keys.size; return true; } else { return false; } }, /** Check whether a key is present. @method has @param {*} key @return {Boolean} true if the item was present, false otherwise @private */ has: function (key) { return this._keys.has(key); }, /** Iterate over all the keys and values. Calls the function once for each key, passing in value, key, and the map being iterated over, in that order. The keys are guaranteed to be iterated over in insertion order. @method forEach @param {Function} callback @param {*} self if passed, the `this` value inside the callback. By default, `this` is the map. @private */ forEach: function (callback /*, ...thisArg*/) { if (typeof callback !== 'function') { missingFunction(callback); } if (this.size === 0) { return; } var map = this; var cb = undefined, thisArg = undefined; if (arguments.length === 2) { thisArg = arguments[1]; cb = function (key) { return callback.call(thisArg, map.get(key), key, map); }; } else { cb = function (key) { return callback(map.get(key), key, map); }; } this._keys.forEach(cb); }, /** @method clear @private */ clear: function () { this._keys.clear(); this._values = new _emberMetalEmpty_object.default(); this.size = 0; }, /** @method copy @return {Ember.Map} @private */ copy: function () { return copyMap(this, new Map()); } }; /** @class MapWithDefault @namespace Ember @extends Ember.Map @private @constructor @param [options] @param {*} [options.defaultValue] */ function MapWithDefault(options) { this._super$constructor(); this.defaultValue = options.defaultValue; } /** @method create @static @param [options] @param {*} [options.defaultValue] @return {Ember.MapWithDefault|Ember.Map} If options are passed, returns `Ember.MapWithDefault` otherwise returns `Ember.Map` @private */ MapWithDefault.create = function (options) { if (options) { return new MapWithDefault(options); } else { return new Map(); } }; MapWithDefault.prototype = Object.create(Map.prototype); MapWithDefault.prototype.constructor = MapWithDefault; MapWithDefault.prototype._super$constructor = Map; MapWithDefault.prototype._super$get = Map.prototype.get; /** Retrieve the value associated with a given key. @method get @param {*} key @return {*} the value associated with the key, or the default value @private */ MapWithDefault.prototype.get = function (key) { var hasValue = this.has(key); if (hasValue) { return this._super$get(key); } else { var defaultValue = this.defaultValue(key); this.set(key, defaultValue); return defaultValue; } }; /** @method copy @return {Ember.MapWithDefault} @private */ MapWithDefault.prototype.copy = function () { var Constructor = this.constructor; return copyMap(this, new Constructor({ defaultValue: this.defaultValue })); }; exports.default = Map; exports.OrderedSet = OrderedSet; exports.Map = Map; exports.MapWithDefault = MapWithDefault; }); enifed('ember-metal/merge', ['exports'], function (exports) { /** Merge the contents of two objects together into the first object. ```javascript Ember.merge({ first: 'Tom' }, { last: 'Dale' }); // { first: 'Tom', last: 'Dale' } var a = { first: 'Yehuda' }; var b = { last: 'Katz' }; Ember.merge(a, b); // a == { first: 'Yehuda', last: 'Katz' }, b == { last: 'Katz' } ``` @method merge @for Ember @param {Object} original The object to merge into @param {Object} updates The object to copy properties from @return {Object} @public */ 'use strict'; exports.default = merge; function merge(original, updates) { if (!updates || typeof updates !== 'object') { return original; } var props = Object.keys(updates); var prop = undefined; for (var i = 0; i < props.length; i++) { prop = props[i]; original[prop] = updates[prop]; } return original; } }); enifed('ember-metal/meta', ['exports', 'ember-metal/features', 'ember-metal/meta_listeners', 'ember-metal/empty_object', 'ember-metal/utils', 'ember-metal/symbol'], function (exports, _emberMetalFeatures, _emberMetalMeta_listeners, _emberMetalEmpty_object, _emberMetalUtils, _emberMetalSymbol) { 'no use strict'; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed exports.meta = meta; exports.peekMeta = peekMeta; exports.deleteMeta = deleteMeta; /** @module ember-metal */ /* This declares several meta-programmed members on the Meta class. Such meta! In general, the `readable` variants will give you an object (if it already exists) that you can read but should not modify. The `writable` variants will give you a mutable object, and they will create it if it didn't already exist. The following methods will get generated metaprogrammatically, and I'm including them here for greppability: writableCache, readableCache, writeWatching, peekWatching, clearWatching, writeMixins, peekMixins, clearMixins, writeBindings, peekBindings, clearBindings, writeValues, peekValues, clearValues, writeDeps, forEachInDeps writableChainWatchers, readableChainWatchers, writableChains, readableChains, writableTag, readableTag */ var members = { cache: ownMap, weak: ownMap, watching: inheritedMap, mixins: inheritedMap, bindings: inheritedMap, values: inheritedMap, deps: inheritedMapOfMaps, chainWatchers: ownCustomObject, chains: inheritedCustomObject, tag: ownCustomObject }; var memberNames = Object.keys(members); var META_FIELD = '__ember_meta__'; function Meta(obj, parentMeta) { this._cache = undefined; this._weak = undefined; this._watching = undefined; this._mixins = undefined; this._bindings = undefined; this._values = undefined; this._deps = undefined; this._chainWatchers = undefined; this._chains = undefined; this._tag = undefined; // used only internally this.source = obj; // when meta(obj).proto === obj, the object is intended to be only a // prototype and doesn't need to actually be observable itself this.proto = undefined; // The next meta in our inheritance chain. We (will) track this // explicitly instead of using prototypical inheritance because we // have detailed knowledge of how each property should really be // inherited, and we can optimize it much better than JS runtimes. this.parent = parentMeta; this._initializeListeners(); } Meta.prototype.isInitialized = function (obj) { return this.proto !== obj; }; for (var _name in _emberMetalMeta_listeners.protoMethods) { Meta.prototype[_name] = _emberMetalMeta_listeners.protoMethods[_name]; } memberNames.forEach(function (name) { return members[name](name, Meta); }); // Implements a member that is a lazily created, non-inheritable // POJO. function ownMap(name, Meta) { var key = memberProperty(name); var capitalized = capitalize(name); Meta.prototype['writable' + capitalized] = function () { return this._getOrCreateOwnMap(key); }; Meta.prototype['readable' + capitalized] = function () { return this[key]; }; } Meta.prototype._getOrCreateOwnMap = function (key) { var ret = this[key]; if (!ret) { ret = this[key] = new _emberMetalEmpty_object.default(); } return ret; }; // Implements a member that is a lazily created POJO with inheritable // values. function inheritedMap(name, Meta) { var key = memberProperty(name); var capitalized = capitalize(name); Meta.prototype['write' + capitalized] = function (subkey, value) { var map = this._getOrCreateOwnMap(key); map[subkey] = value; }; Meta.prototype['peek' + capitalized] = function (subkey) { return this._findInherited(key, subkey); }; Meta.prototype['forEach' + capitalized] = function (fn) { var pointer = this; var seen = new _emberMetalEmpty_object.default(); while (pointer !== undefined) { var map = pointer[key]; if (map) { for (var _key in map) { if (!seen[_key]) { seen[_key] = true; fn(_key, map[_key]); } } } pointer = pointer.parent; } }; Meta.prototype['clear' + capitalized] = function () { this[key] = undefined; }; Meta.prototype['deleteFrom' + capitalized] = function (subkey) { delete this._getOrCreateOwnMap(key)[subkey]; }; Meta.prototype['hasIn' + capitalized] = function (subkey) { return this._findInherited(key, subkey) !== undefined; }; } Meta.prototype._getInherited = function (key) { var pointer = this; while (pointer !== undefined) { if (pointer[key]) { return pointer[key]; } pointer = pointer.parent; } }; Meta.prototype._findInherited = function (key, subkey) { var pointer = this; while (pointer !== undefined) { var map = pointer[key]; if (map) { var value = map[subkey]; if (value !== undefined) { return value; } } pointer = pointer.parent; } }; var UNDEFINED = _emberMetalSymbol.default('undefined'); exports.UNDEFINED = UNDEFINED; // Implements a member that provides a lazily created map of maps, // with inheritance at both levels. function inheritedMapOfMaps(name, Meta) { var key = memberProperty(name); var capitalized = capitalize(name); Meta.prototype['write' + capitalized] = function (subkey, itemkey, value) { var outerMap = this._getOrCreateOwnMap(key); var innerMap = outerMap[subkey]; if (!innerMap) { innerMap = outerMap[subkey] = new _emberMetalEmpty_object.default(); } innerMap[itemkey] = value; }; Meta.prototype['peek' + capitalized] = function (subkey, itemkey) { var pointer = this; while (pointer !== undefined) { var map = pointer[key]; if (map) { var value = map[subkey]; if (value) { if (value[itemkey] !== undefined) { return value[itemkey]; } } } pointer = pointer.parent; } }; Meta.prototype['has' + capitalized] = function (subkey) { var pointer = this; while (pointer !== undefined) { if (pointer[key] && pointer[key][subkey]) { return true; } pointer = pointer.parent; } return false; }; Meta.prototype['forEachIn' + capitalized] = function (subkey, fn) { return this._forEachIn(key, subkey, fn); }; } Meta.prototype._forEachIn = function (key, subkey, fn) { var pointer = this; var seen = new _emberMetalEmpty_object.default(); var calls = []; while (pointer !== undefined) { var map = pointer[key]; if (map) { var innerMap = map[subkey]; if (innerMap) { for (var innerKey in innerMap) { if (!seen[innerKey]) { seen[innerKey] = true; calls.push([innerKey, innerMap[innerKey]]); } } } } pointer = pointer.parent; } for (var i = 0; i < calls.length; i++) { var _calls$i = calls[i]; var innerKey = _calls$i[0]; var value = _calls$i[1]; fn(innerKey, value); } }; // Implements a member that provides a non-heritable, lazily-created // object using the method you provide. function ownCustomObject(name, Meta) { var key = memberProperty(name); var capitalized = capitalize(name); Meta.prototype['writable' + capitalized] = function (create) { var ret = this[key]; if (!ret) { ret = this[key] = create(this.source); } return ret; }; Meta.prototype['readable' + capitalized] = function () { return this[key]; }; } // Implements a member that provides an inheritable, lazily-created // object using the method you provide. We will derived children from // their parents by calling your object's `copy()` method. function inheritedCustomObject(name, Meta) { var key = memberProperty(name); var capitalized = capitalize(name); Meta.prototype['writable' + capitalized] = function (create) { var ret = this[key]; if (!ret) { if (this.parent) { ret = this[key] = this.parent['writable' + capitalized](create).copy(this.source); } else { ret = this[key] = create(this.source); } } return ret; }; Meta.prototype['readable' + capitalized] = function () { return this._getInherited(key); }; } function memberProperty(name) { return '_' + name; } // there's a more general-purpose capitalize in ember-runtime, but we // don't want to make ember-metal depend on ember-runtime. function capitalize(name) { return name.replace(/^\w/, function (m) { return m.toUpperCase(); }); } var META_DESC = { writable: true, configurable: true, enumerable: false, value: null }; exports.META_DESC = META_DESC; var EMBER_META_PROPERTY = { name: META_FIELD, descriptor: META_DESC }; if (true) { Meta.prototype.readInheritedValue = function (key, subkey) { var internalKey = '_' + key; var pointer = this; while (pointer !== undefined) { var map = pointer[internalKey]; if (map) { var value = map[subkey]; if (value !== undefined || subkey in map) { return map[subkey]; } } pointer = pointer.parent; } return UNDEFINED; }; Meta.prototype.writeValue = function (obj, key, value) { var descriptor = _emberMetalUtils.lookupDescriptor(obj, key); var isMandatorySetter = descriptor && descriptor.set && descriptor.set.isMandatorySetter; if (isMandatorySetter) { this.writeValues(key, value); } else { obj[key] = value; } }; } // choose the one appropriate for given platform var setMeta = function (obj, meta) { // if `null` already, just set it to the new value // otherwise define property first if (obj[META_FIELD] !== null) { if (obj.__defineNonEnumerable) { obj.__defineNonEnumerable(EMBER_META_PROPERTY); } else { Object.defineProperty(obj, META_FIELD, META_DESC); } } obj[META_FIELD] = meta; }; /** Retrieves the meta hash for an object. If `writable` is true ensures the hash is writable for this object as well. The meta object contains information about computed property descriptors as well as any watched properties and other information. You generally will not access this information directly but instead work with higher level methods that manipulate this hash indirectly. @method meta @for Ember @private @param {Object} obj The object to retrieve meta for @param {Boolean} [writable=true] Pass `false` if you do not intend to modify the meta hash, allowing the method to avoid making an unnecessary copy. @return {Object} the meta hash for an object */ function meta(obj) { var maybeMeta = peekMeta(obj); var parent = undefined; // remove this code, in-favor of explicit parent if (maybeMeta) { if (maybeMeta.source === obj) { return maybeMeta; } parent = maybeMeta; } var newMeta = new Meta(obj, parent); setMeta(obj, newMeta); return newMeta; } function peekMeta(obj) { return obj[META_FIELD]; } function deleteMeta(obj) { if (typeof obj[META_FIELD] !== 'object') { return; } obj[META_FIELD] = null; } }); enifed('ember-metal/meta_listeners', ['exports'], function (exports) { /* When we render a rich template hierarchy, the set of events that *might* happen tends to be much larger than the set of events that actually happen. This implies that we should make listener creation & destruction cheap, even at the cost of making event dispatch more expensive. Thus we store a new listener with a single push and no new allocations, without even bothering to do deduplication -- we can save that for dispatch time, if an event actually happens. */ /* listener flags */ 'use strict'; var ONCE = 1; exports.ONCE = ONCE; var SUSPENDED = 2; exports.SUSPENDED = SUSPENDED; var protoMethods = { addToListeners: function (eventName, target, method, flags) { if (!this._listeners) { this._listeners = []; } this._listeners.push(eventName, target, method, flags); }, _finalizeListeners: function () { if (this._listenersFinalized) { return; } if (!this._listeners) { this._listeners = []; } var pointer = this.parent; while (pointer) { var listeners = pointer._listeners; if (listeners) { this._listeners = this._listeners.concat(listeners); } if (pointer._listenersFinalized) { break; } pointer = pointer.parent; } this._listenersFinalized = true; }, removeFromListeners: function (eventName, target, method, didRemove) { var pointer = this; while (pointer) { var listeners = pointer._listeners; if (listeners) { for (var index = listeners.length - 4; index >= 0; index -= 4) { if (listeners[index] === eventName && (!method || listeners[index + 1] === target && listeners[index + 2] === method)) { if (pointer === this) { // we are modifying our own list, so we edit directly if (typeof didRemove === 'function') { didRemove(eventName, target, listeners[index + 2]); } listeners.splice(index, 4); } else { // we are trying to remove an inherited listener, so we do // just-in-time copying to detach our own listeners from // our inheritance chain. this._finalizeListeners(); return this.removeFromListeners(eventName, target, method); } } } } if (pointer._listenersFinalized) { break; } pointer = pointer.parent; } }, matchingListeners: function (eventName) { var pointer = this; var result = []; while (pointer) { var listeners = pointer._listeners; if (listeners) { for (var index = 0; index < listeners.length - 3; index += 4) { if (listeners[index] === eventName) { pushUniqueListener(result, listeners, index); } } } if (pointer._listenersFinalized) { break; } pointer = pointer.parent; } var sus = this._suspendedListeners; if (sus) { for (var susIndex = 0; susIndex < sus.length - 2; susIndex += 3) { if (eventName === sus[susIndex]) { for (var resultIndex = 0; resultIndex < result.length - 2; resultIndex += 3) { if (result[resultIndex] === sus[susIndex + 1] && result[resultIndex + 1] === sus[susIndex + 2]) { result[resultIndex + 2] |= SUSPENDED; } } } } } return result; }, suspendListeners: function (eventNames, target, method, callback) { var sus = this._suspendedListeners; if (!sus) { sus = this._suspendedListeners = []; } for (var i = 0; i < eventNames.length; i++) { sus.push(eventNames[i], target, method); } try { return callback.call(target); } finally { if (sus.length === eventNames.length) { this._suspendedListeners = undefined; } else { for (var i = sus.length - 3; i >= 0; i -= 3) { if (sus[i + 1] === target && sus[i + 2] === method && eventNames.indexOf(sus[i]) !== -1) { sus.splice(i, 3); } } } } }, watchedEvents: function () { var pointer = this; var names = {}; while (pointer) { var listeners = pointer._listeners; if (listeners) { for (var index = 0; index < listeners.length - 3; index += 4) { names[listeners[index]] = true; } } if (pointer._listenersFinalized) { break; } pointer = pointer.parent; } return Object.keys(names); }, _initializeListeners: function () { this._listeners = undefined; this._listenersFinalized = undefined; this._suspendedListeners = undefined; } }; exports.protoMethods = protoMethods; function pushUniqueListener(destination, source, index) { var target = source[index + 1]; var method = source[index + 2]; for (var destinationIndex = 0; destinationIndex < destination.length - 2; destinationIndex += 3) { if (destination[destinationIndex] === target && destination[destinationIndex + 1] === method) { return; } } destination.push(target, method, source[index + 3]); } }); enifed('ember-metal/mixin', ['exports', 'ember-metal/error', 'ember-metal/debug', 'ember-metal/assign', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/expand_properties', 'ember-metal/properties', 'ember-metal/computed', 'ember-metal/binding', 'ember-metal/observer', 'ember-metal/events'], function (exports, _emberMetalError, _emberMetalDebug, _emberMetalAssign, _emberMetalUtils, _emberMetalMeta, _emberMetalExpand_properties, _emberMetalProperties, _emberMetalComputed, _emberMetalBinding, _emberMetalObserver, _emberMetalEvents) { 'no use strict'; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed /** @module ember @submodule ember-metal */ exports.detectBinding = detectBinding; exports.mixin = mixin; exports.default = Mixin; exports.hasUnprocessedMixins = hasUnprocessedMixins; exports.clearUnprocessedMixins = clearUnprocessedMixins; exports.required = required; exports.aliasMethod = aliasMethod; exports.observer = observer; exports._immediateObserver = _immediateObserver; exports._beforeObserver = _beforeObserver; function ROOT() {} ROOT.__hasSuper = false; var a_slice = [].slice; function isMethod(obj) { return 'function' === typeof obj && obj.isMethod !== false && obj !== Boolean && obj !== Object && obj !== Number && obj !== Array && obj !== Date && obj !== String; } var CONTINUE = {}; function mixinProperties(mixinsMeta, mixin) { var guid = undefined; if (mixin instanceof Mixin) { guid = _emberMetalUtils.guidFor(mixin); if (mixinsMeta.peekMixins(guid)) { return CONTINUE; } mixinsMeta.writeMixins(guid, mixin); return mixin.properties; } else { return mixin; // apply anonymous mixin properties } } function concatenatedMixinProperties(concatProp, props, values, base) { var concats = undefined; // reset before adding each new mixin to pickup concats from previous concats = values[concatProp] || base[concatProp]; if (props[concatProp]) { concats = concats ? concats.concat(props[concatProp]) : props[concatProp]; } return concats; } function giveDescriptorSuper(meta, key, property, values, descs, base) { var superProperty = undefined; // Computed properties override methods, and do not call super to them if (values[key] === undefined) { // Find the original descriptor in a parent mixin superProperty = descs[key]; } // If we didn't find the original descriptor in a parent mixin, find // it on the original object. if (!superProperty) { var possibleDesc = base[key]; var superDesc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; superProperty = superDesc; } if (superProperty === undefined || !(superProperty instanceof _emberMetalComputed.ComputedProperty)) { return property; } // Since multiple mixins may inherit from the same parent, we need // to clone the computed property so that other mixins do not receive // the wrapped version. property = Object.create(property); property._getter = _emberMetalUtils.wrap(property._getter, superProperty._getter); if (superProperty._setter) { if (property._setter) { property._setter = _emberMetalUtils.wrap(property._setter, superProperty._setter); } else { property._setter = superProperty._setter; } } return property; } function giveMethodSuper(obj, key, method, values, descs) { var superMethod = undefined; // Methods overwrite computed properties, and do not call super to them. if (descs[key] === undefined) { // Find the original method in a parent mixin superMethod = values[key]; } // If we didn't find the original value in a parent mixin, find it in // the original object superMethod = superMethod || obj[key]; // Only wrap the new method if the original method was a function if (superMethod === undefined || 'function' !== typeof superMethod) { return method; } return _emberMetalUtils.wrap(method, superMethod); } function applyConcatenatedProperties(obj, key, value, values) { var baseValue = values[key] || obj[key]; if (baseValue) { if ('function' === typeof baseValue.concat) { if (value === null || value === undefined) { return baseValue; } else { return baseValue.concat(value); } } else { return _emberMetalUtils.makeArray(baseValue).concat(value); } } else { return _emberMetalUtils.makeArray(value); } } function applyMergedProperties(obj, key, value, values) { var baseValue = values[key] || obj[key]; _emberMetalDebug.runInDebug(function () { if (Array.isArray(value)) { // use conditional to avoid stringifying every time _emberMetalDebug.assert('You passed in `' + JSON.stringify(value) + '` as the value for `' + key + '` but `' + key + '` cannot be an Array', false); } }); if (!baseValue) { return value; } var newBase = _emberMetalAssign.default({}, baseValue); var hasFunction = false; for (var prop in value) { if (!value.hasOwnProperty(prop)) { continue; } var propValue = value[prop]; if (isMethod(propValue)) { // TODO: support for Computed Properties, etc? hasFunction = true; newBase[prop] = giveMethodSuper(obj, prop, propValue, baseValue, {}); } else { newBase[prop] = propValue; } } if (hasFunction) { newBase._super = ROOT; } return newBase; } function addNormalizedProperty(base, key, value, meta, descs, values, concats, mergings) { if (value instanceof _emberMetalProperties.Descriptor) { if (value === REQUIRED && descs[key]) { return CONTINUE; } // Wrap descriptor function to implement // _super() if needed if (value._getter) { value = giveDescriptorSuper(meta, key, value, values, descs, base); } descs[key] = value; values[key] = undefined; } else { if (concats && concats.indexOf(key) >= 0 || key === 'concatenatedProperties' || key === 'mergedProperties') { value = applyConcatenatedProperties(base, key, value, values); } else if (mergings && mergings.indexOf(key) >= 0) { value = applyMergedProperties(base, key, value, values); } else if (isMethod(value)) { value = giveMethodSuper(base, key, value, values, descs); } descs[key] = undefined; values[key] = value; } } function mergeMixins(mixins, m, descs, values, base, keys) { var currentMixin = undefined, props = undefined, key = undefined, concats = undefined, mergings = undefined, meta = undefined; function removeKeys(keyName) { delete descs[keyName]; delete values[keyName]; } for (var i = 0; i < mixins.length; i++) { currentMixin = mixins[i]; _emberMetalDebug.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(currentMixin), typeof currentMixin === 'object' && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== '[object Array]'); props = mixinProperties(m, currentMixin); if (props === CONTINUE) { continue; } if (props) { meta = _emberMetalMeta.meta(base); if (base.willMergeMixin) { base.willMergeMixin(props); } concats = concatenatedMixinProperties('concatenatedProperties', props, values, base); mergings = concatenatedMixinProperties('mergedProperties', props, values, base); for (key in props) { if (!props.hasOwnProperty(key)) { continue; } keys.push(key); addNormalizedProperty(base, key, props[key], meta, descs, values, concats, mergings); } // manually copy toString() because some JS engines do not enumerate it if (props.hasOwnProperty('toString')) { base.toString = props.toString; } } else if (currentMixin.mixins) { mergeMixins(currentMixin.mixins, m, descs, values, base, keys); if (currentMixin._without) { currentMixin._without.forEach(removeKeys); } } } } function detectBinding(key) { var length = key.length; return length > 7 && key.charCodeAt(length - 7) === 66 && key.indexOf('inding', length - 6) !== -1; } // warm both paths of above function detectBinding('notbound'); detectBinding('fooBinding'); function connectBindings(obj, m) { // TODO Mixin.apply(instance) should disconnect binding if exists m.forEachBindings(function (key, binding) { if (binding) { var to = key.slice(0, -7); // strip Binding off end if (binding instanceof _emberMetalBinding.Binding) { binding = binding.copy(); // copy prototypes' instance binding.to(to); } else { // binding is string path binding = new _emberMetalBinding.Binding(to, binding); } binding.connect(obj); obj[key] = binding; } }); // mark as applied m.clearBindings(); } function finishPartial(obj, m) { connectBindings(obj, m || _emberMetalMeta.meta(obj)); return obj; } function followAlias(obj, desc, m, descs, values) { var altKey = desc.methodName; var value = undefined; var possibleDesc = undefined; if (descs[altKey] || values[altKey]) { value = values[altKey]; desc = descs[altKey]; } else if ((possibleDesc = obj[altKey]) && possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) { desc = possibleDesc; value = undefined; } else { desc = undefined; value = obj[altKey]; } return { desc: desc, value: value }; } function updateObserversAndListeners(obj, key, observerOrListener, pathsKey, updateMethod) { var paths = observerOrListener[pathsKey]; if (paths) { for (var i = 0; i < paths.length; i++) { updateMethod(obj, paths[i], null, key); } } } function replaceObserversAndListeners(obj, key, observerOrListener) { var prev = obj[key]; if ('function' === typeof prev) { updateObserversAndListeners(obj, key, prev, '__ember_observesBefore__', _emberMetalObserver._removeBeforeObserver); updateObserversAndListeners(obj, key, prev, '__ember_observes__', _emberMetalObserver.removeObserver); updateObserversAndListeners(obj, key, prev, '__ember_listens__', _emberMetalEvents.removeListener); } if ('function' === typeof observerOrListener) { updateObserversAndListeners(obj, key, observerOrListener, '__ember_observesBefore__', _emberMetalObserver._addBeforeObserver); updateObserversAndListeners(obj, key, observerOrListener, '__ember_observes__', _emberMetalObserver.addObserver); updateObserversAndListeners(obj, key, observerOrListener, '__ember_listens__', _emberMetalEvents.addListener); } } function applyMixin(obj, mixins, partial) { var descs = {}; var values = {}; var m = _emberMetalMeta.meta(obj); var keys = []; var key = undefined, value = undefined, desc = undefined; obj._super = ROOT; // Go through all mixins and hashes passed in, and: // // * Handle concatenated properties // * Handle merged properties // * Set up _super wrapping if necessary // * Set up computed property descriptors // * Copying `toString` in broken browsers mergeMixins(mixins, m, descs, values, obj, keys); for (var i = 0; i < keys.length; i++) { key = keys[i]; if (key === 'constructor' || !values.hasOwnProperty(key)) { continue; } desc = descs[key]; value = values[key]; if (desc === REQUIRED) { continue; } while (desc && desc instanceof Alias) { var followed = followAlias(obj, desc, m, descs, values); desc = followed.desc; value = followed.value; } if (desc === undefined && value === undefined) { continue; } replaceObserversAndListeners(obj, key, value); if (detectBinding(key)) { m.writeBindings(key, value); } _emberMetalProperties.defineProperty(obj, key, desc, value, m); } if (!partial) { // don't apply to prototype finishPartial(obj, m); } return obj; } /** @method mixin @for Ember @param obj @param mixins* @return obj @private */ function mixin(obj) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } applyMixin(obj, args, false); return obj; } var NAME_KEY = _emberMetalUtils.GUID_KEY + '_name'; exports.NAME_KEY = NAME_KEY; /** The `Ember.Mixin` class allows you to create mixins, whose properties can be added to other classes. For instance, ```javascript App.Editable = Ember.Mixin.create({ edit: function() { console.log('starting to edit'); this.set('isEditing', true); }, isEditing: false }); // Mix mixins into classes by passing them as the first arguments to // .extend. App.CommentView = Ember.View.extend(App.Editable, { template: Ember.Handlebars.compile('{{#if view.isEditing}}...{{else}}...{{/if}}') }); commentView = App.CommentView.create(); commentView.edit(); // outputs 'starting to edit' ``` Note that Mixins are created with `Ember.Mixin.create`, not `Ember.Mixin.extend`. Note that mixins extend a constructor's prototype so arrays and object literals defined as properties will be shared amongst objects that implement the mixin. If you want to define a property in a mixin that is not shared, you can define it either as a computed property or have it be created on initialization of the object. ```javascript //filters array will be shared amongst any object implementing mixin App.Filterable = Ember.Mixin.create({ filters: Ember.A() }); //filters will be a separate array for every object implementing the mixin App.Filterable = Ember.Mixin.create({ filters: Ember.computed(function() {return Ember.A();}) }); //filters will be created as a separate array during the object's initialization App.Filterable = Ember.Mixin.create({ init: function() { this._super(...arguments); this.set("filters", Ember.A()); } }); ``` @class Mixin @namespace Ember @public */ function Mixin(args, properties) { this.properties = properties; var length = args && args.length; if (length > 0) { var m = new Array(length); for (var i = 0; i < length; i++) { var x = args[i]; if (x instanceof Mixin) { m[i] = x; } else { m[i] = new Mixin(undefined, x); } } this.mixins = m; } else { this.mixins = undefined; } this.ownerConstructor = undefined; this._without = undefined; this[_emberMetalUtils.GUID_KEY] = null; this[NAME_KEY] = null; _emberMetalDebug.debugSeal(this); } Mixin._apply = applyMixin; Mixin.applyPartial = function (obj) { var args = a_slice.call(arguments, 1); return applyMixin(obj, args, true); }; Mixin.finishPartial = finishPartial; var unprocessedFlag = false; function hasUnprocessedMixins() { return unprocessedFlag; } function clearUnprocessedMixins() { unprocessedFlag = false; } /** @method create @static @param arguments* @public */ Mixin.create = function () { // ES6TODO: this relies on a global state? unprocessedFlag = true; var M = this; for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return new M(args, undefined); }; var MixinPrototype = Mixin.prototype; /** @method reopen @param arguments* @private */ MixinPrototype.reopen = function () { var currentMixin = undefined; if (this.properties) { currentMixin = new Mixin(undefined, this.properties); this.properties = undefined; this.mixins = [currentMixin]; } else if (!this.mixins) { this.mixins = []; } var mixins = this.mixins; var idx = undefined; for (idx = 0; idx < arguments.length; idx++) { currentMixin = arguments[idx]; _emberMetalDebug.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(currentMixin), typeof currentMixin === 'object' && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== '[object Array]'); if (currentMixin instanceof Mixin) { mixins.push(currentMixin); } else { mixins.push(new Mixin(undefined, currentMixin)); } } return this; }; /** @method apply @param obj @return applied object @private */ MixinPrototype.apply = function (obj) { return applyMixin(obj, [this], false); }; MixinPrototype.applyPartial = function (obj) { return applyMixin(obj, [this], true); }; MixinPrototype.toString = Object.toString; function _detect(curMixin, targetMixin, seen) { var guid = _emberMetalUtils.guidFor(curMixin); if (seen[guid]) { return false; } seen[guid] = true; if (curMixin === targetMixin) { return true; } var mixins = curMixin.mixins; var loc = mixins ? mixins.length : 0; while (--loc >= 0) { if (_detect(mixins[loc], targetMixin, seen)) { return true; } } return false; } /** @method detect @param obj @return {Boolean} @private */ MixinPrototype.detect = function (obj) { if (!obj) { return false; } if (obj instanceof Mixin) { return _detect(obj, this, {}); } var m = _emberMetalMeta.peekMeta(obj); if (!m) { return false; } return !!m.peekMixins(_emberMetalUtils.guidFor(this)); }; MixinPrototype.without = function () { var ret = new Mixin([this]); for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } ret._without = args; return ret; }; function _keys(ret, mixin, seen) { if (seen[_emberMetalUtils.guidFor(mixin)]) { return; } seen[_emberMetalUtils.guidFor(mixin)] = true; if (mixin.properties) { var props = Object.keys(mixin.properties); for (var i = 0; i < props.length; i++) { var key = props[i]; ret[key] = true; } } else if (mixin.mixins) { mixin.mixins.forEach(function (x) { return _keys(ret, x, seen); }); } } MixinPrototype.keys = function () { var keys = {}; var seen = {}; _keys(keys, this, seen); var ret = Object.keys(keys); return ret; }; _emberMetalDebug.debugSeal(MixinPrototype); // returns the mixins currently applied to the specified object // TODO: Make Ember.mixin Mixin.mixins = function (obj) { var m = _emberMetalMeta.peekMeta(obj); var ret = []; if (!m) { return ret; } m.forEachMixins(function (key, currentMixin) { // skip primitive mixins since these are always anonymous if (!currentMixin.properties) { ret.push(currentMixin); } }); return ret; }; var REQUIRED = new _emberMetalProperties.Descriptor(); REQUIRED.toString = function () { return '(Required Property)'; }; /** Denotes a required property for a mixin @method required @for Ember @private */ function required() { _emberMetalDebug.deprecate('Ember.required is deprecated as its behavior is inconsistent and unreliable.', false, { id: 'ember-metal.required', until: '3.0.0' }); return REQUIRED; } function Alias(methodName) { this.isDescriptor = true; this.methodName = methodName; } Alias.prototype = new _emberMetalProperties.Descriptor(); /** Makes a method available via an additional name. ```javascript App.Person = Ember.Object.extend({ name: function() { return 'Tomhuda Katzdale'; }, moniker: Ember.aliasMethod('name') }); let goodGuy = App.Person.create(); goodGuy.name(); // 'Tomhuda Katzdale' goodGuy.moniker(); // 'Tomhuda Katzdale' ``` @method aliasMethod @for Ember @param {String} methodName name of the method to alias @public */ function aliasMethod(methodName) { return new Alias(methodName); } // .......................................................... // OBSERVER HELPER // /** Specify a method that observes property changes. ```javascript Ember.Object.extend({ valueObserver: Ember.observer('value', function() { // Executes whenever the "value" property changes }) }); ``` Also available as `Function.prototype.observes` if prototype extensions are enabled. @method observer @for Ember @param {String} propertyNames* @param {Function} func @return func @public */ function observer() { for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } var func = args.slice(-1)[0]; var paths = undefined; var addWatchedProperty = function (path) { paths.push(path); }; var _paths = args.slice(0, -1); if (typeof func !== 'function') { // revert to old, soft-deprecated argument ordering _emberMetalDebug.deprecate('Passing the dependentKeys after the callback function in Ember.observer is deprecated. Ensure the callback function is the last argument.', false, { id: 'ember-metal.observer-argument-order', until: '3.0.0' }); func = args[0]; _paths = args.slice(1); } paths = []; for (var i = 0; i < _paths.length; ++i) { _emberMetalExpand_properties.default(_paths[i], addWatchedProperty); } if (typeof func !== 'function') { throw new _emberMetalError.default('Ember.observer called without a function'); } func.__ember_observes__ = paths; return func; } /** Specify a method that observes property changes. ```javascript Ember.Object.extend({ valueObserver: Ember.immediateObserver('value', function() { // Executes whenever the "value" property changes }) }); ``` In the future, `Ember.observer` may become asynchronous. In this event, `Ember.immediateObserver` will maintain the synchronous behavior. Also available as `Function.prototype.observesImmediately` if prototype extensions are enabled. @method _immediateObserver @for Ember @param {String} propertyNames* @param {Function} func @deprecated Use `Ember.observer` instead. @return func @private */ function _immediateObserver() { _emberMetalDebug.deprecate('Usage of `Ember.immediateObserver` is deprecated, use `Ember.observer` instead.', false, { id: 'ember-metal.immediate-observer', until: '3.0.0' }); for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; _emberMetalDebug.assert('Immediate observers must observe internal properties only, not properties on other objects.', typeof arg !== 'string' || arg.indexOf('.') === -1); } return observer.apply(this, arguments); } /** When observers fire, they are called with the arguments `obj`, `keyName`. Note, `@each.property` observer is called per each add or replace of an element and it's not called with a specific enumeration item. A `_beforeObserver` fires before a property changes. A `_beforeObserver` is an alternative form of `.observesBefore()`. ```javascript App.PersonView = Ember.View.extend({ friends: [{ name: 'Tom' }, { name: 'Stefan' }, { name: 'Kris' }], valueDidChange: Ember.observer('content.value', function(obj, keyName) { // only run if updating a value already in the DOM if (this.get('state') === 'inDOM') { let color = obj.get(keyName) > this.changingFrom ? 'green' : 'red'; // logic } }), friendsDidChange: Ember.observer('friends.@each.name', function(obj, keyName) { // some logic // obj.get(keyName) returns friends array }) }); ``` Also available as `Function.prototype.observesBefore` if prototype extensions are enabled. @method beforeObserver @for Ember @param {String} propertyNames* @param {Function} func @return func @deprecated @private */ function _beforeObserver() { for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } var func = args.slice(-1)[0]; var paths = undefined; var addWatchedProperty = function (path) { paths.push(path); }; var _paths = args.slice(0, -1); if (typeof func !== 'function') { // revert to old, soft-deprecated argument ordering func = args[0]; _paths = args.slice(1); } paths = []; for (var i = 0; i < _paths.length; ++i) { _emberMetalExpand_properties.default(_paths[i], addWatchedProperty); } if (typeof func !== 'function') { throw new _emberMetalError.default('Ember.beforeObserver called without a function'); } func.__ember_observesBefore__ = paths; return func; } exports.Mixin = Mixin; exports.required = required; exports.REQUIRED = REQUIRED; }); enifed('ember-metal/observer', ['exports', 'ember-metal/watching', 'ember-metal/events'], function (exports, _emberMetalWatching, _emberMetalEvents) { 'use strict'; exports.addObserver = addObserver; exports.observersFor = observersFor; exports.removeObserver = removeObserver; exports._addBeforeObserver = _addBeforeObserver; exports._suspendObserver = _suspendObserver; exports._suspendObservers = _suspendObservers; exports._removeBeforeObserver = _removeBeforeObserver; /** @module ember-metal */ var AFTER_OBSERVERS = ':change'; var BEFORE_OBSERVERS = ':before'; function changeEvent(keyName) { return keyName + AFTER_OBSERVERS; } function beforeEvent(keyName) { return keyName + BEFORE_OBSERVERS; } /** @method addObserver @for Ember @param obj @param {String} _path @param {Object|Function} target @param {Function|String} [method] @public */ function addObserver(obj, _path, target, method) { _emberMetalEvents.addListener(obj, changeEvent(_path), target, method); _emberMetalWatching.watch(obj, _path); return this; } function observersFor(obj, path) { return _emberMetalEvents.listenersFor(obj, changeEvent(path)); } /** @method removeObserver @for Ember @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @public */ function removeObserver(obj, path, target, method) { _emberMetalWatching.unwatch(obj, path); _emberMetalEvents.removeListener(obj, changeEvent(path), target, method); return this; } /** @method _addBeforeObserver @for Ember @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @deprecated @private */ function _addBeforeObserver(obj, path, target, method) { _emberMetalEvents.addListener(obj, beforeEvent(path), target, method); _emberMetalWatching.watch(obj, path); return this; } // Suspend observer during callback. // // This should only be used by the target of the observer // while it is setting the observed path. function _suspendObserver(obj, path, target, method, callback) { return _emberMetalEvents.suspendListener(obj, changeEvent(path), target, method, callback); } function _suspendObservers(obj, paths, target, method, callback) { var events = paths.map(changeEvent); return _emberMetalEvents.suspendListeners(obj, events, target, method, callback); } /** @method removeBeforeObserver @for Ember @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @deprecated @private */ function _removeBeforeObserver(obj, path, target, method) { _emberMetalWatching.unwatch(obj, path); _emberMetalEvents.removeListener(obj, beforeEvent(path), target, method); return this; } }); enifed('ember-metal/observer_set', ['exports', 'ember-metal/utils', 'ember-metal/events'], function (exports, _emberMetalUtils, _emberMetalEvents) { 'use strict'; exports.default = ObserverSet; /* this.observerSet = { [senderGuid]: { // variable name: `keySet` [keyName]: listIndex } }, this.observers = [ { sender: obj, keyName: keyName, eventName: eventName, listeners: [ [target, method, flags] ] }, ... ] */ function ObserverSet() { this.clear(); } ObserverSet.prototype.add = function (sender, keyName, eventName) { var observerSet = this.observerSet; var observers = this.observers; var senderGuid = _emberMetalUtils.guidFor(sender); var keySet = observerSet[senderGuid]; var index = undefined; if (!keySet) { observerSet[senderGuid] = keySet = {}; } index = keySet[keyName]; if (index === undefined) { index = observers.push({ sender: sender, keyName: keyName, eventName: eventName, listeners: [] }) - 1; keySet[keyName] = index; } return observers[index].listeners; }; ObserverSet.prototype.flush = function () { var observers = this.observers; var i = undefined, observer = undefined, sender = undefined; this.clear(); for (i = 0; i < observers.length; ++i) { observer = observers[i]; sender = observer.sender; if (sender.isDestroying || sender.isDestroyed) { continue; } _emberMetalEvents.sendEvent(sender, observer.eventName, [sender, observer.keyName], observer.listeners); } }; ObserverSet.prototype.clear = function () { this.observerSet = {}; this.observers = []; }; }); enifed('ember-metal/path_cache', ['exports', 'ember-metal/cache'], function (exports, _emberMetalCache) { 'use strict'; exports.isGlobal = isGlobal; exports.isGlobalPath = isGlobalPath; exports.hasThis = hasThis; exports.isPath = isPath; exports.getFirstKey = getFirstKey; exports.getTailPath = getTailPath; var IS_GLOBAL = /^[A-Z$]/; var IS_GLOBAL_PATH = /^[A-Z$].*[\.]/; var HAS_THIS = 'this.'; var isGlobalCache = new _emberMetalCache.default(1000, function (key) { return IS_GLOBAL.test(key); }); var isGlobalPathCache = new _emberMetalCache.default(1000, function (key) { return IS_GLOBAL_PATH.test(key); }); var hasThisCache = new _emberMetalCache.default(1000, function (key) { return key.lastIndexOf(HAS_THIS, 0) === 0; }); var firstDotIndexCache = new _emberMetalCache.default(1000, function (key) { return key.indexOf('.'); }); var firstKeyCache = new _emberMetalCache.default(1000, function (path) { var index = firstDotIndexCache.get(path); if (index === -1) { return path; } else { return path.slice(0, index); } }); var tailPathCache = new _emberMetalCache.default(1000, function (path) { var index = firstDotIndexCache.get(path); if (index !== -1) { return path.slice(index + 1); } }); var caches = { isGlobalCache: isGlobalCache, isGlobalPathCache: isGlobalPathCache, hasThisCache: hasThisCache, firstDotIndexCache: firstDotIndexCache, firstKeyCache: firstKeyCache, tailPathCache: tailPathCache }; exports.caches = caches; function isGlobal(path) { return isGlobalCache.get(path); } function isGlobalPath(path) { return isGlobalPathCache.get(path); } function hasThis(path) { return hasThisCache.get(path); } function isPath(path) { return firstDotIndexCache.get(path) !== -1; } function getFirstKey(path) { return firstKeyCache.get(path); } function getTailPath(path) { return tailPathCache.get(path); } }); enifed('ember-metal/properties', ['exports', 'ember-metal/debug', 'ember-metal/features', 'ember-metal/meta', 'ember-metal/property_events'], function (exports, _emberMetalDebug, _emberMetalFeatures, _emberMetalMeta, _emberMetalProperty_events) { /** @module ember-metal */ 'use strict'; exports.Descriptor = Descriptor; exports.MANDATORY_SETTER_FUNCTION = MANDATORY_SETTER_FUNCTION; exports.DEFAULT_GETTER_FUNCTION = DEFAULT_GETTER_FUNCTION; exports.INHERITING_GETTER_FUNCTION = INHERITING_GETTER_FUNCTION; exports.defineProperty = defineProperty; // .......................................................... // DESCRIPTOR // /** Objects of this type can implement an interface to respond to requests to get and set. The default implementation handles simple properties. @class Descriptor @private */ function Descriptor() { this.isDescriptor = true; } var REDEFINE_SUPPORTED = (function () { // https://github.com/spalger/kibana/commit/b7e35e6737df585585332857a4c397dc206e7ff9 var a = Object.create(Object.prototype, { prop: { configurable: true, value: 1 } }); Object.defineProperty(a, 'prop', { configurable: true, value: 2 }); return a.prop === 2; })(); // .......................................................... // DEFINING PROPERTIES API // function MANDATORY_SETTER_FUNCTION(name) { function SETTER_FUNCTION(value) { var m = _emberMetalMeta.peekMeta(this); if (!m.isInitialized(this)) { m.writeValues(name, value); } else { _emberMetalDebug.assert('You must use Ember.set() to set the `' + name + '` property (of ' + this + ') to `' + value + '`.', false); } } SETTER_FUNCTION.isMandatorySetter = true; return SETTER_FUNCTION; } function DEFAULT_GETTER_FUNCTION(name) { return function GETTER_FUNCTION() { var meta = _emberMetalMeta.peekMeta(this); return meta && meta.peekValues(name); }; } function INHERITING_GETTER_FUNCTION(name) { function IGETTER_FUNCTION() { var meta = _emberMetalMeta.peekMeta(this); var val = meta && meta.readInheritedValue('values', name); if (val === _emberMetalMeta.UNDEFINED) { var proto = Object.getPrototypeOf(this); return proto && proto[name]; } else { return val; } } IGETTER_FUNCTION.isInheritingGetter = true; return IGETTER_FUNCTION; } /** NOTE: This is a low-level method used by other parts of the API. You almost never want to call this method directly. Instead you should use `Ember.mixin()` to define new properties. Defines a property on an object. This method works much like the ES5 `Object.defineProperty()` method except that it can also accept computed properties and other special descriptors. Normally this method takes only three parameters. However if you pass an instance of `Descriptor` as the third param then you can pass an optional value as the fourth parameter. This is often more efficient than creating new descriptor hashes for each property. ## Examples ```javascript // ES5 compatible mode Ember.defineProperty(contact, 'firstName', { writable: true, configurable: false, enumerable: true, value: 'Charles' }); // define a simple property Ember.defineProperty(contact, 'lastName', undefined, 'Jolley'); // define a computed property Ember.defineProperty(contact, 'fullName', Ember.computed('firstName', 'lastName', function() { return this.firstName+' '+this.lastName; })); ``` @private @method defineProperty @for Ember @param {Object} obj the object to define this property on. This may be a prototype. @param {String} keyName the name of the property @param {Descriptor} [desc] an instance of `Descriptor` (typically a computed property) or an ES5 descriptor. You must provide this or `data` but not both. @param {*} [data] something other than a descriptor, that will become the explicit value of this property. */ function defineProperty(obj, keyName, desc, data, meta) { var possibleDesc = undefined, existingDesc = undefined, watching = undefined, value = undefined; if (!meta) { meta = _emberMetalMeta.meta(obj); } var watchEntry = meta.peekWatching(keyName); possibleDesc = obj[keyName]; existingDesc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; watching = watchEntry !== undefined && watchEntry > 0; if (existingDesc) { existingDesc.teardown(obj, keyName); } if (desc instanceof Descriptor) { value = desc; if (true) { if (watching) { Object.defineProperty(obj, keyName, { configurable: true, enumerable: true, writable: true, value: value }); } else { obj[keyName] = value; } } else { obj[keyName] = value; } if (desc.setup) { desc.setup(obj, keyName); } } else { if (desc == null) { value = data; if (true) { if (watching) { meta.writeValues(keyName, data); var defaultDescriptor = { configurable: true, enumerable: true, set: MANDATORY_SETTER_FUNCTION(keyName), get: DEFAULT_GETTER_FUNCTION(keyName) }; if (REDEFINE_SUPPORTED) { Object.defineProperty(obj, keyName, defaultDescriptor); } else { handleBrokenPhantomDefineProperty(obj, keyName, defaultDescriptor); } } else { obj[keyName] = data; } } else { obj[keyName] = data; } } else { value = desc; // fallback to ES5 Object.defineProperty(obj, keyName, desc); } } // if key is being watched, override chains that // were initialized with the prototype if (watching) { _emberMetalProperty_events.overrideChains(obj, keyName, meta); } // The `value` passed to the `didDefineProperty` hook is // either the descriptor or data, whichever was passed. if (obj.didDefineProperty) { obj.didDefineProperty(obj, keyName, value); } return this; } function handleBrokenPhantomDefineProperty(obj, keyName, desc) { // https://github.com/ariya/phantomjs/issues/11856 Object.defineProperty(obj, keyName, { configurable: true, writable: true, value: 'iCry' }); Object.defineProperty(obj, keyName, desc); } }); enifed('ember-metal/property_events', ['exports', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/events', 'ember-metal/tags', 'ember-metal/observer_set', 'ember-metal/symbol'], function (exports, _emberMetalUtils, _emberMetalMeta, _emberMetalEvents, _emberMetalTags, _emberMetalObserver_set, _emberMetalSymbol) { 'use strict'; var PROPERTY_DID_CHANGE = _emberMetalSymbol.default('PROPERTY_DID_CHANGE'); exports.PROPERTY_DID_CHANGE = PROPERTY_DID_CHANGE; var beforeObserverSet = new _emberMetalObserver_set.default(); var observerSet = new _emberMetalObserver_set.default(); var deferred = 0; // .......................................................... // PROPERTY CHANGES // /** This function is called just before an object property is about to change. It will notify any before observers and prepare caches among other things. Normally you will not need to call this method directly but if for some reason you can't directly watch a property you can invoke this method manually along with `Ember.propertyDidChange()` which you should call just after the property value changes. @method propertyWillChange @for Ember @param {Object} obj The object with the property that will change @param {String} keyName The property key (or path) that will change. @return {void} @private */ function propertyWillChange(obj, keyName) { var m = _emberMetalMeta.peekMeta(obj); if (m && !m.isInitialized(obj)) { return; } var watching = m && m.peekWatching(keyName) > 0; var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; if (desc && desc.willChange) { desc.willChange(obj, keyName); } if (watching) { dependentKeysWillChange(obj, keyName, m); chainsWillChange(obj, keyName, m); notifyBeforeObservers(obj, keyName); } } /** This function is called just after an object property has changed. It will notify any observers and clear caches among other things. Normally you will not need to call this method directly but if for some reason you can't directly watch a property you can invoke this method manually along with `Ember.propertyWillChange()` which you should call just before the property value changes. @method propertyDidChange @for Ember @param {Object} obj The object with the property that will change @param {String} keyName The property key (or path) that will change. @return {void} @private */ function propertyDidChange(obj, keyName) { var m = _emberMetalMeta.peekMeta(obj); if (m && !m.isInitialized(obj)) { return; } var watching = m && m.peekWatching(keyName) > 0; var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; // shouldn't this mean that we're watching this key? if (desc && desc.didChange) { desc.didChange(obj, keyName); } if (watching) { if (m.hasDeps(keyName)) { dependentKeysDidChange(obj, keyName, m); } chainsDidChange(obj, keyName, m, false); notifyObservers(obj, keyName); } if (obj[PROPERTY_DID_CHANGE]) { obj[PROPERTY_DID_CHANGE](keyName); } _emberMetalTags.markObjectAsDirty(m); } var WILL_SEEN = undefined, DID_SEEN = undefined; // called whenever a property is about to change to clear the cache of any dependent keys (and notify those properties of changes, etc...) function dependentKeysWillChange(obj, depKey, meta) { if (obj.isDestroying) { return; } if (meta && meta.hasDeps(depKey)) { var seen = WILL_SEEN; var _top = !seen; if (_top) { seen = WILL_SEEN = {}; } iterDeps(propertyWillChange, obj, depKey, seen, meta); if (_top) { WILL_SEEN = null; } } } // called whenever a property has just changed to update dependent keys function dependentKeysDidChange(obj, depKey, meta) { if (obj.isDestroying) { return; } if (meta && meta.hasDeps(depKey)) { var seen = DID_SEEN; var _top2 = !seen; if (_top2) { seen = DID_SEEN = {}; } iterDeps(propertyDidChange, obj, depKey, seen, meta); if (_top2) { DID_SEEN = null; } } } function iterDeps(method, obj, depKey, seen, meta) { var possibleDesc = undefined, desc = undefined; var guid = _emberMetalUtils.guidFor(obj); var current = seen[guid]; if (!current) { current = seen[guid] = {}; } if (current[depKey]) { return; } current[depKey] = true; meta.forEachInDeps(depKey, function (key, value) { if (!value) { return; } possibleDesc = obj[key]; desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; if (desc && desc._suspended === obj) { return; } method(obj, key); }); } function chainsWillChange(obj, keyName, m) { var c = m.readableChainWatchers(); if (c) { c.notify(keyName, false, propertyWillChange); } } function chainsDidChange(obj, keyName, m) { var c = m.readableChainWatchers(); if (c) { c.notify(keyName, true, propertyDidChange); } } function overrideChains(obj, keyName, m) { var c = m.readableChainWatchers(); if (c) { c.revalidate(keyName); } } /** @method beginPropertyChanges @chainable @private */ function beginPropertyChanges() { deferred++; } /** @method endPropertyChanges @private */ function endPropertyChanges() { deferred--; if (deferred <= 0) { beforeObserverSet.clear(); observerSet.flush(); } } /** Make a series of property changes together in an exception-safe way. ```javascript Ember.changeProperties(function() { obj1.set('foo', mayBlowUpWhenSet); obj2.set('bar', baz); }); ``` @method changeProperties @param {Function} callback @param [binding] @private */ function changeProperties(callback, binding) { beginPropertyChanges(); try { callback.call(binding); } finally { endPropertyChanges.call(binding); } } function notifyBeforeObservers(obj, keyName) { if (obj.isDestroying) { return; } var eventName = keyName + ':before'; var listeners = undefined, added = undefined; if (deferred) { listeners = beforeObserverSet.add(obj, keyName, eventName); added = _emberMetalEvents.accumulateListeners(obj, eventName, listeners); _emberMetalEvents.sendEvent(obj, eventName, [obj, keyName], added); } else { _emberMetalEvents.sendEvent(obj, eventName, [obj, keyName]); } } function notifyObservers(obj, keyName) { if (obj.isDestroying) { return; } var eventName = keyName + ':change'; var listeners = undefined; if (deferred) { listeners = observerSet.add(obj, keyName, eventName); _emberMetalEvents.accumulateListeners(obj, eventName, listeners); } else { _emberMetalEvents.sendEvent(obj, eventName, [obj, keyName]); } } exports.propertyWillChange = propertyWillChange; exports.propertyDidChange = propertyDidChange; exports.overrideChains = overrideChains; exports.beginPropertyChanges = beginPropertyChanges; exports.endPropertyChanges = endPropertyChanges; exports.changeProperties = changeProperties; }); enifed('ember-metal/property_get', ['exports', 'ember-metal/debug', 'ember-metal/path_cache'], function (exports, _emberMetalDebug, _emberMetalPath_cache) { /** @module ember-metal */ 'use strict'; exports.get = get; exports._getPath = _getPath; exports.getWithDefault = getWithDefault; var ALLOWABLE_TYPES = { object: true, function: true, string: true }; // .......................................................... // GET AND SET // // If we are on a platform that supports accessors we can use those. // Otherwise simulate accessors by looking up the property directly on the // object. /** Gets the value of a property on an object. If the property is computed, the function will be invoked. If the property is not defined but the object implements the `unknownProperty` method then that will be invoked. If you plan to run on IE8 and older browsers then you should use this method anytime you want to retrieve a property on an object that you don't know for sure is private. (Properties beginning with an underscore '_' are considered private.) On all newer browsers, you only need to use this method to retrieve properties if the property might not be defined on the object and you want to respect the `unknownProperty` handler. Otherwise you can ignore this method. Note that if the object itself is `undefined`, this method will throw an error. @method get @for Ember @param {Object} obj The object to retrieve from. @param {String} keyName The property key to retrieve @return {Object} the property value or `null`. @public */ function get(obj, keyName) { _emberMetalDebug.assert('Get must be called with two arguments; an object and a property key', arguments.length === 2); _emberMetalDebug.assert('Cannot call get with \'' + keyName + '\' on an undefined object.', obj !== undefined && obj !== null); _emberMetalDebug.assert('The key provided to get must be a string, you passed ' + keyName, typeof keyName === 'string'); _emberMetalDebug.assert('\'this\' in paths is not supported', !_emberMetalPath_cache.hasThis(keyName)); // Helpers that operate with 'this' within an #each if (keyName === '') { return obj; } var value = obj[keyName]; var desc = value !== null && typeof value === 'object' && value.isDescriptor ? value : undefined; var ret = undefined; if (desc === undefined && _emberMetalPath_cache.isPath(keyName)) { return _getPath(obj, keyName); } if (desc) { return desc.get(obj, keyName); } else { ret = value; if (ret === undefined && 'object' === typeof obj && !(keyName in obj) && 'function' === typeof obj.unknownProperty) { return obj.unknownProperty(keyName); } return ret; } } function _getPath(root, path) { var obj = root; var parts = path.split('.'); for (var i = 0; i < parts.length; i++) { if (!isGettable(obj)) { return undefined; } obj = get(obj, parts[i]); if (obj && obj.isDestroyed) { return undefined; } } return obj; } function isGettable(obj) { if (obj == null) { return false; } return ALLOWABLE_TYPES[typeof obj]; } /** Retrieves the value of a property from an Object, or a default value in the case that the property returns `undefined`. ```javascript Ember.getWithDefault(person, 'lastName', 'Doe'); ``` @method getWithDefault @for Ember @param {Object} obj The object to retrieve from. @param {String} keyName The name of the property to retrieve @param {Object} defaultValue The value to return if the property value is undefined @return {Object} The property value or the defaultValue. @public */ function getWithDefault(root, key, defaultValue) { var value = get(root, key); if (value === undefined) { return defaultValue; } return value; } exports.default = get; }); enifed('ember-metal/property_set', ['exports', 'ember-metal/debug', 'ember-metal/features', 'ember-metal/property_get', 'ember-metal/property_events', 'ember-metal/error', 'ember-metal/path_cache', 'ember-metal/meta', 'ember-metal/utils'], function (exports, _emberMetalDebug, _emberMetalFeatures, _emberMetalProperty_get, _emberMetalProperty_events, _emberMetalError, _emberMetalPath_cache, _emberMetalMeta, _emberMetalUtils) { 'use strict'; exports.set = set; exports.trySet = trySet; /** Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the property is not defined but the object implements the `setUnknownProperty` method then that will be invoked as well. @method set @for Ember @param {Object} obj The object to modify. @param {String} keyName The property key to set @param {Object} value The value to set @return {Object} the passed value. @public */ function set(obj, keyName, value, tolerant) { _emberMetalDebug.assert('Set must be called with three or four arguments; an object, a property key, a value and tolerant true/false', arguments.length === 3 || arguments.length === 4); _emberMetalDebug.assert('Cannot call set with \'' + keyName + '\' on an undefined object.', obj && typeof obj === 'object' || typeof obj === 'function'); _emberMetalDebug.assert('The key provided to set must be a string, you passed ' + keyName, typeof keyName === 'string'); _emberMetalDebug.assert('\'this\' in paths is not supported', !_emberMetalPath_cache.hasThis(keyName)); _emberMetalDebug.assert('calling set on destroyed object: ' + _emberMetalUtils.toString(obj) + '.' + keyName + ' = ' + _emberMetalUtils.toString(value), !obj.isDestroyed); if (_emberMetalPath_cache.isPath(keyName)) { return setPath(obj, keyName, value, tolerant); } var meta = _emberMetalMeta.peekMeta(obj); var possibleDesc = obj[keyName]; var desc = undefined, currentValue = undefined; if (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) { desc = possibleDesc; } else { currentValue = possibleDesc; } if (desc) { /* computed property */ desc.set(obj, keyName, value); } else if (obj.setUnknownProperty && currentValue === undefined && !(keyName in obj)) { /* unknown property */ _emberMetalDebug.assert('setUnknownProperty must be a function', typeof obj.setUnknownProperty === 'function'); obj.setUnknownProperty(keyName, value); } else if (currentValue === value) { /* no change */ return value; } else { _emberMetalProperty_events.propertyWillChange(obj, keyName); if (true) { setWithMandatorySetter(meta, obj, keyName, value); } else { obj[keyName] = value; } _emberMetalProperty_events.propertyDidChange(obj, keyName); } return value; } if (true) { var setWithMandatorySetter = function (meta, obj, keyName, value) { if (meta && meta.peekWatching(keyName) > 0) { makeEnumerable(obj, keyName); meta.writeValue(obj, keyName, value); } else { obj[keyName] = value; } }; var makeEnumerable = function (obj, key) { var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc && desc.set && desc.set.isMandatorySetter) { desc.enumerable = true; Object.defineProperty(obj, key, desc); } }; } function setPath(root, path, value, tolerant) { // get the last part of the path var keyName = path.slice(path.lastIndexOf('.') + 1); // get the first part of the part path = path === keyName ? keyName : path.slice(0, path.length - (keyName.length + 1)); // unless the path is this, look up the first part to // get the root if (path !== 'this') { root = _emberMetalProperty_get._getPath(root, path); } if (!keyName || keyName.length === 0) { throw new _emberMetalError.default('Property set failed: You passed an empty path'); } if (!root) { if (tolerant) { return; } else { throw new _emberMetalError.default('Property set failed: object in path "' + path + '" could not be found or was destroyed.'); } } return set(root, keyName, value); } /** Error-tolerant form of `Ember.set`. Will not blow up if any part of the chain is `undefined`, `null`, or destroyed. This is primarily used when syncing bindings, which may try to update after an object has been destroyed. @method trySet @for Ember @param {Object} root The object to modify. @param {String} path The property path to set @param {Object} value The value to set @public */ function trySet(root, path, value) { return set(root, path, value, true); } }); enifed("ember-metal/replace", ["exports"], function (exports) { "use strict"; exports.default = replace; var splice = Array.prototype.splice; function replace(array, idx, amt, objects) { var args = [].concat(objects); var ret = []; // https://code.google.com/p/chromium/issues/detail?id=56588 var size = 60000; var start = idx; var ends = amt; var count = undefined, chunk = undefined; while (args.length) { count = ends > size ? size : ends; if (count <= 0) { count = 0; } chunk = args.splice(0, size); chunk = [start, count].concat(chunk); start += size; ends -= count; ret = ret.concat(splice.apply(array, chunk)); } return ret; } }); enifed('ember-metal/run_loop', ['exports', 'ember-metal/debug', 'ember-metal/testing', 'ember-metal/error_handler', 'ember-metal/utils', 'ember-metal/property_events', 'backburner'], function (exports, _emberMetalDebug, _emberMetalTesting, _emberMetalError_handler, _emberMetalUtils, _emberMetalProperty_events, _backburner) { 'use strict'; exports.default = run; function onBegin(current) { run.currentRunLoop = current; } function onEnd(current, next) { run.currentRunLoop = next; } var onErrorTarget = { get onerror() { return _emberMetalError_handler.getOnerror(); }, set onerror(handler) { return _emberMetalError_handler.setOnerror(handler); } }; var backburner = new _backburner.default(['sync', 'actions', 'destroy'], { GUID_KEY: _emberMetalUtils.GUID_KEY, sync: { before: _emberMetalProperty_events.beginPropertyChanges, after: _emberMetalProperty_events.endPropertyChanges }, defaultQueue: 'actions', onBegin: onBegin, onEnd: onEnd, onErrorTarget: onErrorTarget, onErrorMethod: 'onerror' }); // .......................................................... // run - this is ideally the only public API the dev sees // /** Runs the passed target and method inside of a RunLoop, ensuring any deferred actions including bindings and views updates are flushed at the end. Normally you should not need to invoke this method yourself. However if you are implementing raw event handlers when interfacing with other libraries or plugins, you should probably wrap all of your code inside this call. ```javascript run(function() { // code to be executed within a RunLoop }); ``` @class run @namespace Ember @static @constructor @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Object} return value from invoking the passed function. @public */ function run() { return backburner.run.apply(backburner, arguments); } /** If no run-loop is present, it creates a new one. If a run loop is present it will queue itself to run on the existing run-loops action queue. Please note: This is not for normal usage, and should be used sparingly. If invoked when not within a run loop: ```javascript run.join(function() { // creates a new run-loop }); ``` Alternatively, if called within an existing run loop: ```javascript run(function() { // creates a new run-loop run.join(function() { // joins with the existing run-loop, and queues for invocation on // the existing run-loops action queue. }); }); ``` @method join @namespace Ember @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Object} Return value from invoking the passed function. Please note, when called within an existing loop, no return value is possible. @public */ run.join = function () { return backburner.join.apply(backburner, arguments); }; /** Allows you to specify which context to call the specified function in while adding the execution of that function to the Ember run loop. This ability makes this method a great way to asynchronously integrate third-party libraries into your Ember application. `run.bind` takes two main arguments, the desired context and the function to invoke in that context. Any additional arguments will be supplied as arguments to the function that is passed in. Let's use the creation of a TinyMCE component as an example. Currently, TinyMCE provides a setup configuration option we can use to do some processing after the TinyMCE instance is initialized but before it is actually rendered. We can use that setup option to do some additional setup for our component. The component itself could look something like the following: ```javascript App.RichTextEditorComponent = Ember.Component.extend({ initializeTinyMCE: Ember.on('didInsertElement', function() { tinymce.init({ selector: '#' + this.$().prop('id'), setup: Ember.run.bind(this, this.setupEditor) }); }), setupEditor: function(editor) { this.set('editor', editor); editor.on('change', function() { console.log('content changed!'); }); } }); ``` In this example, we use Ember.run.bind to bind the setupEditor method to the context of the App.RichTextEditorComponent and to have the invocation of that method be safely handled and executed by the Ember run loop. @method bind @namespace Ember @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Function} returns a new function that will always have a particular context @since 1.4.0 @public */ run.bind = function () { for (var _len = arguments.length, curried = Array(_len), _key = 0; _key < _len; _key++) { curried[_key] = arguments[_key]; } return function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return run.join.apply(run, curried.concat(args)); }; }; run.backburner = backburner; run.currentRunLoop = null; run.queues = backburner.queueNames; /** Begins a new RunLoop. Any deferred actions invoked after the begin will be buffered until you invoke a matching call to `run.end()`. This is a lower-level way to use a RunLoop instead of using `run()`. ```javascript run.begin(); // code to be executed within a RunLoop run.end(); ``` @method begin @return {void} @public */ run.begin = function () { backburner.begin(); }; /** Ends a RunLoop. This must be called sometime after you call `run.begin()` to flush any deferred actions. This is a lower-level way to use a RunLoop instead of using `run()`. ```javascript run.begin(); // code to be executed within a RunLoop run.end(); ``` @method end @return {void} @public */ run.end = function () { backburner.end(); }; /** Array of named queues. This array determines the order in which queues are flushed at the end of the RunLoop. You can define your own queues by simply adding the queue name to this array. Normally you should not need to inspect or modify this property. @property queues @type Array @default ['sync', 'actions', 'destroy'] @private */ /** Adds the passed target/method and any optional arguments to the named queue to be executed at the end of the RunLoop. If you have not already started a RunLoop when calling this method one will be started for you automatically. At the end of a RunLoop, any methods scheduled in this way will be invoked. Methods will be invoked in an order matching the named queues defined in the `run.queues` property. ```javascript run.schedule('sync', this, function() { // this will be executed in the first RunLoop queue, when bindings are synced console.log('scheduled on sync queue'); }); run.schedule('actions', this, function() { // this will be executed in the 'actions' queue, after bindings have synced. console.log('scheduled on actions queue'); }); // Note the functions will be run in order based on the run queues order. // Output would be: // scheduled on sync queue // scheduled on actions queue ``` @method schedule @param {String} queue The name of the queue to schedule against. Default queues are 'sync' and 'actions' @param {Object} [target] target object to use as the context when invoking a method. @param {String|Function} method The method to invoke. If you pass a string it will be resolved on the target object at the time the scheduled item is invoked allowing you to change the target function. @param {Object} [arguments*] Optional arguments to be passed to the queued method. @return {void} @public */ run.schedule = function () /* queue, target, method */{ _emberMetalDebug.assert('You have turned on testing mode, which disabled the run-loop\'s autorun. ' + 'You will need to wrap any code with asynchronous side-effects in a run', run.currentRunLoop || !_emberMetalTesting.isTesting()); backburner.schedule.apply(backburner, arguments); }; // Used by global test teardown run.hasScheduledTimers = function () { return backburner.hasTimers(); }; // Used by global test teardown run.cancelTimers = function () { backburner.cancelTimers(); }; /** Immediately flushes any events scheduled in the 'sync' queue. Bindings use this queue so this method is a useful way to immediately force all bindings in the application to sync. You should call this method anytime you need any changed state to propagate throughout the app immediately without repainting the UI (which happens in the later 'render' queue added by the `ember-views` package). ```javascript run.sync(); ``` @method sync @return {void} @private */ run.sync = function () { if (backburner.currentInstance) { backburner.currentInstance.queues.sync.flush(); } }; /** Invokes the passed target/method and optional arguments after a specified period of time. The last parameter of this method must always be a number of milliseconds. You should use this method whenever you need to run some action after a period of time instead of using `setTimeout()`. This method will ensure that items that expire during the same script execution cycle all execute together, which is often more efficient than using a real setTimeout. ```javascript run.later(myContext, function() { // code here will execute within a RunLoop in about 500ms with this == myContext }, 500); ``` @method later @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} wait Number of milliseconds to wait. @return {*} Timer information for use in cancelling, see `run.cancel`. @public */ run.later = function () /*target, method*/{ return backburner.later.apply(backburner, arguments); }; /** Schedule a function to run one time during the current RunLoop. This is equivalent to calling `scheduleOnce` with the "actions" queue. @method once @param {Object} [target] The target of the method to invoke. @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} Timer information for use in cancelling, see `run.cancel`. @public */ run.once = function () { _emberMetalDebug.assert('You have turned on testing mode, which disabled the run-loop\'s autorun. ' + 'You will need to wrap any code with asynchronous side-effects in a run', run.currentRunLoop || !_emberMetalTesting.isTesting()); for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } args.unshift('actions'); return backburner.scheduleOnce.apply(backburner, args); }; /** Schedules a function to run one time in a given queue of the current RunLoop. Calling this method with the same queue/target/method combination will have no effect (past the initial call). Note that although you can pass optional arguments these will not be considered when looking for duplicates. New arguments will replace previous calls. ```javascript function sayHi() { console.log('hi'); } run(function() { run.scheduleOnce('afterRender', myContext, sayHi); run.scheduleOnce('afterRender', myContext, sayHi); // sayHi will only be executed once, in the afterRender queue of the RunLoop }); ``` Also note that passing an anonymous function to `run.scheduleOnce` will not prevent additional calls with an identical anonymous function from scheduling the items multiple times, e.g.: ```javascript function scheduleIt() { run.scheduleOnce('actions', myContext, function() { console.log('Closure'); }); } scheduleIt(); scheduleIt(); // "Closure" will print twice, even though we're using `run.scheduleOnce`, // because the function we pass to it is anonymous and won't match the // previously scheduled operation. ``` Available queues, and their order, can be found at `run.queues` @method scheduleOnce @param {String} [queue] The name of the queue to schedule against. Default queues are 'sync' and 'actions'. @param {Object} [target] The target of the method to invoke. @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} Timer information for use in cancelling, see `run.cancel`. @public */ run.scheduleOnce = function () /*queue, target, method*/{ _emberMetalDebug.assert('You have turned on testing mode, which disabled the run-loop\'s autorun. ' + 'You will need to wrap any code with asynchronous side-effects in a run', run.currentRunLoop || !_emberMetalTesting.isTesting()); return backburner.scheduleOnce.apply(backburner, arguments); }; /** Schedules an item to run from within a separate run loop, after control has been returned to the system. This is equivalent to calling `run.later` with a wait time of 1ms. ```javascript run.next(myContext, function() { // code to be executed in the next run loop, // which will be scheduled after the current one }); ``` Multiple operations scheduled with `run.next` will coalesce into the same later run loop, along with any other operations scheduled by `run.later` that expire right around the same time that `run.next` operations will fire. Note that there are often alternatives to using `run.next`. For instance, if you'd like to schedule an operation to happen after all DOM element operations have completed within the current run loop, you can make use of the `afterRender` run loop queue (added by the `ember-views` package, along with the preceding `render` queue where all the DOM element operations happen). Example: ```javascript export default Ember.Component.extend({ didInsertElement() { this._super(...arguments); run.scheduleOnce('afterRender', this, 'processChildElements'); }, processChildElements() { // ... do something with component's child component // elements after they've finished rendering, which // can't be done within this component's // `didInsertElement` hook because that gets run // before the child elements have been added to the DOM. } }); ``` One benefit of the above approach compared to using `run.next` is that you will be able to perform DOM/CSS operations before unprocessed elements are rendered to the screen, which may prevent flickering or other artifacts caused by delaying processing until after rendering. The other major benefit to the above approach is that `run.next` introduces an element of non-determinism, which can make things much harder to test, due to its reliance on `setTimeout`; it's much harder to guarantee the order of scheduled operations when they are scheduled outside of the current run loop, i.e. with `run.next`. @method next @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} Timer information for use in cancelling, see `run.cancel`. @public */ run.next = function () { for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } args.push(1); return backburner.later.apply(backburner, args); }; /** Cancels a scheduled item. Must be a value returned by `run.later()`, `run.once()`, `run.scheduleOnce()`, `run.next()`, `run.debounce()`, or `run.throttle()`. ```javascript let runNext = run.next(myContext, function() { // will not be executed }); run.cancel(runNext); let runLater = run.later(myContext, function() { // will not be executed }, 500); run.cancel(runLater); let runScheduleOnce = run.scheduleOnce('afterRender', myContext, function() { // will not be executed }); run.cancel(runScheduleOnce); let runOnce = run.once(myContext, function() { // will not be executed }); run.cancel(runOnce); let throttle = run.throttle(myContext, function() { // will not be executed }, 1, false); run.cancel(throttle); let debounce = run.debounce(myContext, function() { // will not be executed }, 1); run.cancel(debounce); let debounceImmediate = run.debounce(myContext, function() { // will be executed since we passed in true (immediate) }, 100, true); // the 100ms delay until this method can be called again will be cancelled run.cancel(debounceImmediate); ``` @method cancel @param {Object} timer Timer object to cancel @return {Boolean} true if cancelled or false/undefined if it wasn't found @public */ run.cancel = function (timer) { return backburner.cancel(timer); }; /** Delay calling the target method until the debounce period has elapsed with no additional debounce calls. If `debounce` is called again before the specified time has elapsed, the timer is reset and the entire period must pass again before the target method is called. This method should be used when an event may be called multiple times but the action should only be called once when the event is done firing. A common example is for scroll events where you only want updates to happen once scrolling has ceased. ```javascript function whoRan() { console.log(this.name + ' ran.'); } let myContext = { name: 'debounce' }; run.debounce(myContext, whoRan, 150); // less than 150ms passes run.debounce(myContext, whoRan, 150); // 150ms passes // whoRan is invoked with context myContext // console logs 'debounce ran.' one time. ``` Immediate allows you to run the function immediately, but debounce other calls for this function until the wait time has elapsed. If `debounce` is called again before the specified time has elapsed, the timer is reset and the entire period must pass again before the method can be called again. ```javascript function whoRan() { console.log(this.name + ' ran.'); } let myContext = { name: 'debounce' }; run.debounce(myContext, whoRan, 150, true); // console logs 'debounce ran.' one time immediately. // 100ms passes run.debounce(myContext, whoRan, 150, true); // 150ms passes and nothing else is logged to the console and // the debouncee is no longer being watched run.debounce(myContext, whoRan, 150, true); // console logs 'debounce ran.' one time immediately. // 150ms passes and nothing else is logged to the console and // the debouncee is no longer being watched ``` @method debounce @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} wait Number of milliseconds to wait. @param {Boolean} immediate Trigger the function on the leading instead of the trailing edge of the wait interval. Defaults to false. @return {Array} Timer information for use in cancelling, see `run.cancel`. @public */ run.debounce = function () { return backburner.debounce.apply(backburner, arguments); }; /** Ensure that the target method is never called more frequently than the specified spacing period. The target method is called immediately. ```javascript function whoRan() { console.log(this.name + ' ran.'); } let myContext = { name: 'throttle' }; run.throttle(myContext, whoRan, 150); // whoRan is invoked with context myContext // console logs 'throttle ran.' // 50ms passes run.throttle(myContext, whoRan, 150); // 50ms passes run.throttle(myContext, whoRan, 150); // 150ms passes run.throttle(myContext, whoRan, 150); // whoRan is invoked with context myContext // console logs 'throttle ran.' ``` @method throttle @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} spacing Number of milliseconds to space out requests. @param {Boolean} immediate Trigger the function on the leading instead of the trailing edge of the wait interval. Defaults to true. @return {Array} Timer information for use in cancelling, see `run.cancel`. @public */ run.throttle = function () { return backburner.throttle.apply(backburner, arguments); }; /** Add a new named queue after the specified queue. The queue to add will only be added once. @method _addQueue @param {String} name the name of the queue to add. @param {String} after the name of the queue to add after. @private */ run._addQueue = function (name, after) { if (run.queues.indexOf(name) === -1) { run.queues.splice(run.queues.indexOf(after) + 1, 0, name); } }; }); enifed('ember-metal/set_properties', ['exports', 'ember-metal/property_events', 'ember-metal/property_set'], function (exports, _emberMetalProperty_events, _emberMetalProperty_set) { 'use strict'; exports.default = setProperties; /** Set a list of properties on an object. These properties are set inside a single `beginPropertyChanges` and `endPropertyChanges` batch, so observers will be buffered. ```javascript let anObject = Ember.Object.create(); anObject.setProperties({ firstName: 'Stanley', lastName: 'Stuart', age: 21 }); ``` @method setProperties @param obj @param {Object} properties @return properties @public */ function setProperties(obj, properties) { if (!properties || typeof properties !== 'object') { return properties; } _emberMetalProperty_events.changeProperties(function () { var props = Object.keys(properties); var propertyName = undefined; for (var i = 0; i < props.length; i++) { propertyName = props[i]; _emberMetalProperty_set.set(obj, propertyName, properties[propertyName]); } }); return properties; } }); enifed('ember-metal/symbol', ['exports', 'ember-metal/utils'], function (exports, _emberMetalUtils) { 'use strict'; exports.default = symbol; function symbol(debugName) { // TODO: Investigate using platform symbols, but we do not // want to require non-enumerability for this API, which // would introduce a large cost. return _emberMetalUtils.intern(debugName + ' [id=' + _emberMetalUtils.GUID_KEY + Math.floor(Math.random() * new Date()) + ']'); } }); enifed('ember-metal/tags', ['exports', 'ember-metal/meta', 'require'], function (exports, _emberMetalMeta, _require2) { 'use strict'; exports.setHasViews = setHasViews; exports.tagFor = tagFor; var hasGlimmer = _require2.has('glimmer-reference'); var CONSTANT_TAG = undefined, CURRENT_TAG = undefined, DirtyableTag = undefined, makeTag = undefined, run = undefined; var hasViews = function () { return false; }; function setHasViews(fn) { hasViews = fn; } var markObjectAsDirty = undefined; exports.markObjectAsDirty = markObjectAsDirty; function tagFor(object, _meta) { if (!hasGlimmer) { throw new Error('Cannot call tagFor without Glimmer'); } if (object && typeof object === 'object') { var meta = _meta || _emberMetalMeta.meta(object); return meta.writableTag(makeTag); } else { return CONSTANT_TAG; } } function K() {} function ensureRunloop() { if (!run) { run = _require2.default('ember-metal/run_loop').default; } if (hasViews() && !run.backburner.currentInstance) { run.schedule('actions', K); } } if (hasGlimmer) { var _require = _require2.default('glimmer-reference'); DirtyableTag = _require.DirtyableTag; CONSTANT_TAG = _require.CONSTANT_TAG; CURRENT_TAG = _require.CURRENT_TAG; makeTag = function () { return new DirtyableTag(); }; exports.markObjectAsDirty = markObjectAsDirty = function (meta) { ensureRunloop(); var tag = meta && meta.readableTag() || CURRENT_TAG; tag.dirty(); }; } else { exports.markObjectAsDirty = markObjectAsDirty = function () {}; } }); enifed("ember-metal/testing", ["exports"], function (exports) { "use strict"; exports.isTesting = isTesting; exports.setTesting = setTesting; var testing = false; function isTesting() { return testing; } function setTesting(value) { testing = !!value; } }); enifed('ember-metal/utils', ['exports'], function (exports) { 'no use strict'; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed /** @module ember-metal */ /** Previously we used `Ember.$.uuid`, however `$.uuid` has been removed from jQuery master. We'll just bootstrap our own uuid now. @private @return {Number} the uuid */ exports.uuid = uuid; exports.intern = intern; exports.generateGuid = generateGuid; exports.guidFor = guidFor; exports.wrap = wrap; exports.tryInvoke = tryInvoke; exports.makeArray = makeArray; exports.inspect = inspect; exports.applyStr = applyStr; exports.lookupDescriptor = lookupDescriptor; exports.toString = toString; var _uuid = 0; /** Generates a universally unique identifier. This method is used internally by Ember for assisting with the generation of GUID's and other unique identifiers. @public @return {Number} [description] */ function uuid() { return ++_uuid; } /** Prefix used for guids through out Ember. @private @property GUID_PREFIX @for Ember @type String @final */ var GUID_PREFIX = 'ember'; // Used for guid generation... var numberCache = []; var stringCache = {}; /** Strongly hint runtimes to intern the provided string. When do I need to use this function? For the most part, never. Pre-mature optimization is bad, and often the runtime does exactly what you need it to, and more often the trade-off isn't worth it. Why? Runtimes store strings in at least 2 different representations: Ropes and Symbols (interned strings). The Rope provides a memory efficient data-structure for strings created from concatenation or some other string manipulation like splitting. Unfortunately checking equality of different ropes can be quite costly as runtimes must resort to clever string comparison algorithms. These algorithms typically cost in proportion to the length of the string. Luckily, this is where the Symbols (interned strings) shine. As Symbols are unique by their string content, equality checks can be done by pointer comparison. How do I know if my string is a rope or symbol? Typically (warning general sweeping statement, but truthy in runtimes at present) static strings created as part of the JS source are interned. Strings often used for comparisons can be interned at runtime if some criteria are met. One of these criteria can be the size of the entire rope. For example, in chrome 38 a rope longer then 12 characters will not intern, nor will segments of that rope. Some numbers: http://jsperf.com/eval-vs-keys/8 Known Trick™ @private @return {String} interned version of the provided string */ function intern(str) { var obj = {}; obj[str] = 1; for (var key in obj) { if (key === str) { return key; } } return str; } /** A unique key used to assign guids and other private metadata to objects. If you inspect an object in your browser debugger you will often see these. They can be safely ignored. On browsers that support it, these properties are added with enumeration disabled so they won't show up when you iterate over your properties. @private @property GUID_KEY @for Ember @type String @final */ var GUID_KEY = intern('__ember' + +new Date()); var GUID_DESC = { writable: true, configurable: true, enumerable: false, value: null }; exports.GUID_DESC = GUID_DESC; var nullDescriptor = { configurable: true, writable: true, enumerable: false, value: null }; var GUID_KEY_PROPERTY = { name: GUID_KEY, descriptor: nullDescriptor }; exports.GUID_KEY_PROPERTY = GUID_KEY_PROPERTY; /** Generates a new guid, optionally saving the guid to the object that you pass in. You will rarely need to use this method. Instead you should call `Ember.guidFor(obj)`, which return an existing guid if available. @private @method generateGuid @for Ember @param {Object} [obj] Object the guid will be used for. If passed in, the guid will be saved on the object and reused whenever you pass the same object again. If no object is passed, just generate a new guid. @param {String} [prefix] Prefix to place in front of the guid. Useful when you want to separate the guid into separate namespaces. @return {String} the guid */ function generateGuid(obj, prefix) { if (!prefix) { prefix = GUID_PREFIX; } var ret = prefix + uuid(); if (obj) { if (obj[GUID_KEY] === null) { obj[GUID_KEY] = ret; } else { GUID_DESC.value = ret; if (obj.__defineNonEnumerable) { obj.__defineNonEnumerable(GUID_KEY_PROPERTY); } else { Object.defineProperty(obj, GUID_KEY, GUID_DESC); } } } return ret; } /** Returns a unique id for the object. If the object does not yet have a guid, one will be assigned to it. You can call this on any object, `Ember.Object`-based or not, but be aware that it will add a `_guid` property. You can also use this method on DOM Element objects. @public @method guidFor @for Ember @param {Object} obj any object, string, number, Element, or primitive @return {String} the unique guid for this instance. */ function guidFor(obj) { if (obj && obj[GUID_KEY]) { return obj[GUID_KEY]; } // special cases where we don't want to add a key to object if (obj === undefined) { return '(undefined)'; } if (obj === null) { return '(null)'; } var ret = undefined; var type = typeof obj; // Don't allow prototype changes to String etc. to change the guidFor switch (type) { case 'number': ret = numberCache[obj]; if (!ret) { ret = numberCache[obj] = 'nu' + obj; } return ret; case 'string': ret = stringCache[obj]; if (!ret) { ret = stringCache[obj] = 'st' + uuid(); } return ret; case 'boolean': return obj ? '(true)' : '(false)'; default: if (obj === Object) { return '(Object)'; } if (obj === Array) { return '(Array)'; } ret = GUID_PREFIX + uuid(); if (obj[GUID_KEY] === null) { obj[GUID_KEY] = ret; } else { GUID_DESC.value = ret; if (obj.__defineNonEnumerable) { obj.__defineNonEnumerable(GUID_KEY_PROPERTY); } else { Object.defineProperty(obj, GUID_KEY, GUID_DESC); } } return ret; } } var HAS_SUPER_PATTERN = /\.(_super|call\(this|apply\(this)/; var fnToString = Function.prototype.toString; var checkHasSuper = (function () { var sourceAvailable = fnToString.call(function () { return this; }).indexOf('return this') > -1; if (sourceAvailable) { return function checkHasSuper(func) { return HAS_SUPER_PATTERN.test(fnToString.call(func)); }; } return function checkHasSuper() { return true; }; })(); exports.checkHasSuper = checkHasSuper; function ROOT() {} ROOT.__hasSuper = false; function hasSuper(func) { if (func.__hasSuper === undefined) { func.__hasSuper = checkHasSuper(func); } return func.__hasSuper; } /** Wraps the passed function so that `this._super` will point to the superFunc when the function is invoked. This is the primitive we use to implement calls to super. @private @method wrap @for Ember @param {Function} func The function to call @param {Function} superFunc The super function. @return {Function} wrapped function. */ function wrap(func, superFunc) { if (!hasSuper(func)) { return func; } // ensure an unwrapped super that calls _super is wrapped with a terminal _super if (!superFunc.wrappedFunction && hasSuper(superFunc)) { return _wrap(func, _wrap(superFunc, ROOT)); } return _wrap(func, superFunc); } function _wrap(func, superFunc) { function superWrapper() { var orig = this._super; this._super = superFunc; var ret = func.apply(this, arguments); this._super = orig; return ret; } superWrapper.wrappedFunction = func; superWrapper.__ember_observes__ = func.__ember_observes__; superWrapper.__ember_observesBefore__ = func.__ember_observesBefore__; superWrapper.__ember_listens__ = func.__ember_listens__; return superWrapper; } /** Checks to see if the `methodName` exists on the `obj`. ```javascript let foo = { bar: function() { return 'bar'; }, baz: null }; Ember.canInvoke(foo, 'bar'); // true Ember.canInvoke(foo, 'baz'); // false Ember.canInvoke(foo, 'bat'); // false ``` @method canInvoke @for Ember @param {Object} obj The object to check for the method @param {String} methodName The method name to check for @return {Boolean} @private */ function canInvoke(obj, methodName) { return !!(obj && typeof obj[methodName] === 'function'); } /** Checks to see if the `methodName` exists on the `obj`, and if it does, invokes it with the arguments passed. ```javascript let d = new Date('03/15/2013'); Ember.tryInvoke(d, 'getTime'); // 1363320000000 Ember.tryInvoke(d, 'setFullYear', [2014]); // 1394856000000 Ember.tryInvoke(d, 'noSuchMethod', [2014]); // undefined ``` @method tryInvoke @for Ember @param {Object} obj The object to check for the method @param {String} methodName The method name to check for @param {Array} [args] The arguments to pass to the method @return {*} the return value of the invoked method or undefined if it cannot be invoked @public */ function tryInvoke(obj, methodName, args) { if (canInvoke(obj, methodName)) { return args ? applyStr(obj, methodName, args) : applyStr(obj, methodName); } } // ........................................ // TYPING & ARRAY MESSAGING // var objectToString = Object.prototype.toString; /** Forces the passed object to be part of an array. If the object is already an array, it will return the object. Otherwise, it will add the object to an array. If obj is `null` or `undefined`, it will return an empty array. ```javascript Ember.makeArray(); // [] Ember.makeArray(null); // [] Ember.makeArray(undefined); // [] Ember.makeArray('lindsay'); // ['lindsay'] Ember.makeArray([1, 2, 42]); // [1, 2, 42] let controller = Ember.ArrayProxy.create({ content: [] }); Ember.makeArray(controller) === controller; // true ``` @method makeArray @for Ember @param {Object} obj the object @return {Array} @private */ function makeArray(obj) { if (obj === null || obj === undefined) { return []; } return Array.isArray(obj) ? obj : [obj]; } /** Convenience method to inspect an object. This method will attempt to convert the object into a useful string description. It is a pretty simple implementation. If you want something more robust, use something like JSDump: https://github.com/NV/jsDump @method inspect @for Ember @param {Object} obj The object you want to inspect. @return {String} A description of the object @since 1.4.0 @private */ function inspect(obj) { if (obj === null) { return 'null'; } if (obj === undefined) { return 'undefined'; } if (Array.isArray(obj)) { return '[' + obj + ']'; } // for non objects var type = typeof obj; if (type !== 'object' && type !== 'symbol') { return '' + obj; } // overridden toString if (typeof obj.toString === 'function' && obj.toString !== objectToString) { return obj.toString(); } // Object.prototype.toString === {}.toString var v = undefined; var ret = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { v = obj[key]; if (v === 'toString') { continue; } // ignore useless items if (typeof v === 'function') { v = 'function() { ... }'; } if (v && typeof v.toString !== 'function') { ret.push(key + ': ' + objectToString.call(v)); } else { ret.push(key + ': ' + v); } } } return '{' + ret.join(', ') + '}'; } /** @param {Object} t target @param {String} m method @param {Array} a args @private */ function applyStr(t, m, a) { var l = a && a.length; if (!a || !l) { return t[m](); } switch (l) { case 1: return t[m](a[0]); case 2: return t[m](a[0], a[1]); case 3: return t[m](a[0], a[1], a[2]); case 4: return t[m](a[0], a[1], a[2], a[3]); case 5: return t[m](a[0], a[1], a[2], a[3], a[4]); default: return t[m].apply(t, a); } } function lookupDescriptor(obj, keyName) { var current = obj; while (current) { var descriptor = Object.getOwnPropertyDescriptor(current, keyName); if (descriptor) { return descriptor; } current = Object.getPrototypeOf(current); } return null; } // A `toString` util function that supports objects without a `toString` // method, e.g. an object created with `Object.create(null)`. function toString(obj) { if (obj && obj.toString) { return obj.toString(); } else { return objectToString.call(obj); } } exports.GUID_KEY = GUID_KEY; exports.makeArray = makeArray; exports.canInvoke = canInvoke; }); enifed('ember-metal/watch_key', ['exports', 'ember-metal/features', 'ember-metal/meta', 'ember-metal/properties', 'ember-metal/utils'], function (exports, _emberMetalFeatures, _emberMetalMeta, _emberMetalProperties, _emberMetalUtils) { 'use strict'; exports.watchKey = watchKey; exports.unwatchKey = unwatchKey; var handleMandatorySetter = undefined; function watchKey(obj, keyName, meta) { var m = meta || _emberMetalMeta.meta(obj); // activate watching first time if (!m.peekWatching(keyName)) { m.writeWatching(keyName, 1); var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; if (desc && desc.willWatch) { desc.willWatch(obj, keyName); } if ('function' === typeof obj.willWatchProperty) { obj.willWatchProperty(keyName); } if (true) { // NOTE: this is dropped for prod + minified builds handleMandatorySetter(m, obj, keyName); } } else { m.writeWatching(keyName, (m.peekWatching(keyName) || 0) + 1); } } if (true) { (function () { var hasOwnProperty = function (obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); }; var propertyIsEnumerable = function (obj, key) { return Object.prototype.propertyIsEnumerable.call(obj, key); }; // Future traveler, although this code looks scary. It merely exists in // development to aid in development asertions. Production builds of // ember strip this entire block out handleMandatorySetter = function handleMandatorySetter(m, obj, keyName) { var descriptor = _emberMetalUtils.lookupDescriptor(obj, keyName); var configurable = descriptor ? descriptor.configurable : true; var isWritable = descriptor ? descriptor.writable : true; var hasValue = descriptor ? 'value' in descriptor : true; var possibleDesc = descriptor && descriptor.value; var isDescriptor = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor; if (isDescriptor) { return; } // this x in Y deopts, so keeping it in this function is better; if (configurable && isWritable && hasValue && keyName in obj) { var desc = { configurable: true, set: _emberMetalProperties.MANDATORY_SETTER_FUNCTION(keyName), enumerable: propertyIsEnumerable(obj, keyName), get: undefined }; if (hasOwnProperty(obj, keyName)) { m.writeValues(keyName, obj[keyName]); desc.get = _emberMetalProperties.DEFAULT_GETTER_FUNCTION(keyName); } else { desc.get = _emberMetalProperties.INHERITING_GETTER_FUNCTION(keyName); } Object.defineProperty(obj, keyName, desc); } }; })(); } function unwatchKey(obj, keyName, meta) { var m = meta || _emberMetalMeta.meta(obj); var count = m.peekWatching(keyName); if (count === 1) { m.writeWatching(keyName, 0); var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; if (desc && desc.didUnwatch) { desc.didUnwatch(obj, keyName); } if ('function' === typeof obj.didUnwatchProperty) { obj.didUnwatchProperty(keyName); } if (true) { // It is true, the following code looks quite WAT. But have no fear, It // exists purely to improve development ergonomics and is removed from // ember.min.js and ember.prod.js builds. // // Some further context: Once a property is watched by ember, bypassing `set` // for mutation, will bypass observation. This code exists to assert when // that occurs, and attempt to provide more helpful feedback. The alternative // is tricky to debug partially observable properties. if (!desc && keyName in obj) { var maybeMandatoryDescriptor = _emberMetalUtils.lookupDescriptor(obj, keyName); if (maybeMandatoryDescriptor.set && maybeMandatoryDescriptor.set.isMandatorySetter) { if (maybeMandatoryDescriptor.get && maybeMandatoryDescriptor.get.isInheritingGetter) { var possibleValue = m.readInheritedValue('values', keyName); if (possibleValue === _emberMetalMeta.UNDEFINED) { delete obj[keyName]; return; } } Object.defineProperty(obj, keyName, { configurable: true, enumerable: Object.prototype.propertyIsEnumerable.call(obj, keyName), writable: true, value: m.peekValues(keyName) }); m.deleteFromValues(keyName); } } } } else if (count > 1) { m.writeWatching(keyName, count - 1); } } }); enifed('ember-metal/watch_path', ['exports', 'ember-metal/meta', 'ember-metal/chains'], function (exports, _emberMetalMeta, _emberMetalChains) { 'use strict'; exports.makeChainNode = makeChainNode; exports.watchPath = watchPath; exports.unwatchPath = unwatchPath; // get the chains for the current object. If the current object has // chains inherited from the proto they will be cloned and reconfigured for // the current object. function chainsFor(obj, meta) { return (meta || _emberMetalMeta.meta(obj)).writableChains(makeChainNode); } function makeChainNode(obj) { return new _emberMetalChains.ChainNode(null, null, obj); } function watchPath(obj, keyPath, meta) { var m = meta || _emberMetalMeta.meta(obj); var counter = m.peekWatching(keyPath) || 0; if (!counter) { // activate watching first time m.writeWatching(keyPath, 1); chainsFor(obj, m).add(keyPath); } else { m.writeWatching(keyPath, counter + 1); } } function unwatchPath(obj, keyPath, meta) { var m = meta || _emberMetalMeta.meta(obj); var counter = m.peekWatching(keyPath) || 0; if (counter === 1) { m.writeWatching(keyPath, 0); chainsFor(obj, m).remove(keyPath); } else if (counter > 1) { m.writeWatching(keyPath, counter - 1); } } }); enifed('ember-metal/watching', ['exports', 'ember-metal/chains', 'ember-metal/watch_key', 'ember-metal/watch_path', 'ember-metal/path_cache', 'ember-metal/meta'], function (exports, _emberMetalChains, _emberMetalWatch_key, _emberMetalWatch_path, _emberMetalPath_cache, _emberMetalMeta) { /** @module ember-metal */ 'use strict'; exports.isWatching = isWatching; exports.watcherCount = watcherCount; exports.unwatch = unwatch; exports.destroy = destroy; /** Starts watching a property on an object. Whenever the property changes, invokes `Ember.propertyWillChange` and `Ember.propertyDidChange`. This is the primitive used by observers and dependent keys; usually you will never call this method directly but instead use higher level methods like `Ember.addObserver()` @private @method watch @for Ember @param obj @param {String} _keyPath */ function watch(obj, _keyPath, m) { if (!_emberMetalPath_cache.isPath(_keyPath)) { _emberMetalWatch_key.watchKey(obj, _keyPath, m); } else { _emberMetalWatch_path.watchPath(obj, _keyPath, m); } } exports.watch = watch; function isWatching(obj, key) { var meta = _emberMetalMeta.peekMeta(obj); return (meta && meta.peekWatching(key)) > 0; } function watcherCount(obj, key) { var meta = _emberMetalMeta.peekMeta(obj); return meta && meta.peekWatching(key) || 0; } function unwatch(obj, _keyPath, m) { if (!_emberMetalPath_cache.isPath(_keyPath)) { _emberMetalWatch_key.unwatchKey(obj, _keyPath, m); } else { _emberMetalWatch_path.unwatchPath(obj, _keyPath, m); } } var NODE_STACK = []; /** Tears down the meta on an object so that it can be garbage collected. Multiple calls will have no effect. @method destroy @for Ember @param {Object} obj the object to destroy @return {void} @private */ function destroy(obj) { var meta = _emberMetalMeta.peekMeta(obj); var node = undefined, nodes = undefined, key = undefined, nodeObject = undefined; if (meta) { _emberMetalMeta.deleteMeta(obj); // remove chainWatchers to remove circular references that would prevent GC node = meta.readableChains(); if (node) { NODE_STACK.push(node); // process tree while (NODE_STACK.length > 0) { node = NODE_STACK.pop(); // push children nodes = node._chains; if (nodes) { for (key in nodes) { if (nodes[key] !== undefined) { NODE_STACK.push(nodes[key]); } } } // remove chainWatcher in node object if (node._watching) { nodeObject = node._object; if (nodeObject) { _emberMetalChains.removeChainWatcher(nodeObject, node._key, node); } } } } } } }); enifed('ember-metal/weak_map', ['exports', 'ember-metal/utils', 'ember-metal/meta'], function (exports, _emberMetalUtils, _emberMetalMeta) { 'use strict'; exports.default = WeakMap; var id = 0; function UNDEFINED() {} // Returns whether Type(value) is Object according to the terminology in the spec function isObject(value) { return typeof value === 'object' && value !== null || typeof value === 'function'; } /* * @class Ember.WeakMap * @public * @category ember-metal-weakmap * * A partial polyfill for [WeakMap](http://www.ecma-international.org/ecma-262/6.0/#sec-weakmap-objects). * * There is a small but important caveat. This implementation assumes that the * weak map will live longer (in the sense of garbage collection) than all of its * keys, otherwise it is possible to leak the values stored in the weak map. In * practice, most use cases satisfy this limitation which is why it is included * in ember-metal. */ function WeakMap(iterable) { if (!(this instanceof WeakMap)) { throw new TypeError('Constructor WeakMap requires \'new\''); } this._id = _emberMetalUtils.GUID_KEY + id++; if (iterable === null || iterable === undefined) { return; } else if (Array.isArray(iterable)) { for (var i = 0; i < iterable.length; i++) { var _iterable$i = iterable[i]; var key = _iterable$i[0]; var value = _iterable$i[1]; this.set(key, value); } } else { throw new TypeError('The weak map constructor polyfill only supports an array argument'); } } /* * @method get * @param key {Object | Function} * @return {Any} stored value */ WeakMap.prototype.get = function (obj) { if (!isObject(obj)) { return undefined; } var meta = _emberMetalMeta.peekMeta(obj); if (meta) { var map = meta.readableWeak(); if (map) { if (map[this._id] === UNDEFINED) { return undefined; } return map[this._id]; } } }; /* * @method set * @param key {Object | Function} * @param value {Any} * @return {WeakMap} the weak map */ WeakMap.prototype.set = function (obj, value) { if (!isObject(obj)) { throw new TypeError('Invalid value used as weak map key'); } if (value === undefined) { value = UNDEFINED; } _emberMetalMeta.meta(obj).writableWeak()[this._id] = value; return this; }; /* * @method has * @param key {Object | Function} * @return {boolean} if the key exists */ WeakMap.prototype.has = function (obj) { if (!isObject(obj)) { return false; } var meta = _emberMetalMeta.peekMeta(obj); if (meta) { var map = meta.readableWeak(); if (map) { return map[this._id] !== undefined; } } return false; }; /* * @method delete * @param key {Object | Function} * @return {boolean} if the key was deleted */ WeakMap.prototype.delete = function (obj) { if (this.has(obj)) { delete _emberMetalMeta.meta(obj).writableWeak()[this._id]; return true; } else { return false; } }; /* * @method toString * @return {String} */ WeakMap.prototype.toString = function () { return '[object WeakMap]'; }; }); enifed('ember-routing/ext/controller', ['exports', 'ember-metal/property_get', 'ember-runtime/mixins/controller'], function (exports, _emberMetalProperty_get, _emberRuntimeMixinsController) { 'use strict'; /** @module ember @submodule ember-routing */ _emberRuntimeMixinsController.default.reopen({ concatenatedProperties: ['queryParams'], /** Defines which query parameters the controller accepts. If you give the names `['category','page']` it will bind the values of these query parameters to the variables `this.category` and `this.page` @property queryParams @public */ queryParams: null, /** @property _qpDelegate @private */ _qpDelegate: null, // set by route /** @method _qpChanged @private */ _qpChanged: function (controller, _prop) { var prop = _prop.substr(0, _prop.length - 3); var delegate = controller._qpDelegate; var value = _emberMetalProperty_get.get(controller, prop); delegate(prop, value); }, /** Transition the application into another route. The route may be either a single route or route path: ```javascript aController.transitionToRoute('blogPosts'); aController.transitionToRoute('blogPosts.recentEntries'); ``` Optionally supply a model for the route in question. The model will be serialized into the URL using the `serialize` hook of the route: ```javascript aController.transitionToRoute('blogPost', aPost); ``` If a literal is passed (such as a number or a string), it will be treated as an identifier instead. In this case, the `model` hook of the route will be triggered: ```javascript aController.transitionToRoute('blogPost', 1); ``` Multiple models will be applied last to first recursively up the route tree. ```javascript App.Router.map(function() { this.route('blogPost', { path: ':blogPostId' }, function() { this.route('blogComment', { path: ':blogCommentId', resetNamespace: true }); }); }); aController.transitionToRoute('blogComment', aPost, aComment); aController.transitionToRoute('blogComment', 1, 13); ``` It is also possible to pass a URL (a string that starts with a `/`). This is intended for testing and debugging purposes and should rarely be used in production code. ```javascript aController.transitionToRoute('/'); aController.transitionToRoute('/blog/post/1/comment/13'); aController.transitionToRoute('/blog/posts?sort=title'); ``` An options hash with a `queryParams` property may be provided as the final argument to add query parameters to the destination URL. ```javascript aController.transitionToRoute('blogPost', 1, { queryParams: { showComments: 'true' } }); // if you just want to transition the query parameters without changing the route aController.transitionToRoute({ queryParams: { sort: 'date' } }); ``` See also [replaceRoute](/api/classes/Ember.ControllerMixin.html#method_replaceRoute). @param {String} name the name of the route or a URL @param {...Object} models the model(s) or identifier(s) to be used while transitioning to the route. @param {Object} [options] optional hash with a queryParams property containing a mapping of query parameters @for Ember.ControllerMixin @method transitionToRoute @public */ transitionToRoute: function () { // target may be either another controller or a router var target = _emberMetalProperty_get.get(this, 'target'); var method = target.transitionToRoute || target.transitionTo; return method.apply(target, arguments); }, /** Transition into another route while replacing the current URL, if possible. This will replace the current history entry instead of adding a new one. Beside that, it is identical to `transitionToRoute` in all other respects. ```javascript aController.replaceRoute('blogPosts'); aController.replaceRoute('blogPosts.recentEntries'); ``` Optionally supply a model for the route in question. The model will be serialized into the URL using the `serialize` hook of the route: ```javascript aController.replaceRoute('blogPost', aPost); ``` If a literal is passed (such as a number or a string), it will be treated as an identifier instead. In this case, the `model` hook of the route will be triggered: ```javascript aController.replaceRoute('blogPost', 1); ``` Multiple models will be applied last to first recursively up the route tree. ```javascript App.Router.map(function() { this.route('blogPost', { path: ':blogPostId' }, function() { this.route('blogComment', { path: ':blogCommentId', resetNamespace: true }); }); }); aController.replaceRoute('blogComment', aPost, aComment); aController.replaceRoute('blogComment', 1, 13); ``` It is also possible to pass a URL (a string that starts with a `/`). This is intended for testing and debugging purposes and should rarely be used in production code. ```javascript aController.replaceRoute('/'); aController.replaceRoute('/blog/post/1/comment/13'); ``` @param {String} name the name of the route or a URL @param {...Object} models the model(s) or identifier(s) to be used while transitioning to the route. @for Ember.ControllerMixin @method replaceRoute @private */ replaceRoute: function () { // target may be either another controller or a router var target = _emberMetalProperty_get.get(this, 'target'); var method = target.replaceRoute || target.replaceWith; return method.apply(target, arguments); } }); exports.default = _emberRuntimeMixinsController.default; }); enifed('ember-routing/ext/run_loop', ['exports', 'ember-metal/run_loop'], function (exports, _emberMetalRun_loop) { 'use strict'; /** @module ember @submodule ember-views */ // Add a new named queue after the 'actions' queue (where RSVP promises // resolve), which is used in router transitions to prevent unnecessary // loading state entry if all context promises resolve on the // 'actions' queue first. _emberMetalRun_loop.default._addQueue('routerTransitions', 'actions'); }); enifed('ember-routing/index', ['exports', 'ember-metal/core', 'ember-routing/ext/run_loop', 'ember-routing/ext/controller', 'ember-routing/location/api', 'ember-routing/location/none_location', 'ember-routing/location/hash_location', 'ember-routing/location/history_location', 'ember-routing/location/auto_location', 'ember-routing/system/generate_controller', 'ember-routing/system/controller_for', 'ember-routing/system/dsl', 'ember-routing/system/router', 'ember-routing/system/route'], function (exports, _emberMetalCore, _emberRoutingExtRun_loop, _emberRoutingExtController, _emberRoutingLocationApi, _emberRoutingLocationNone_location, _emberRoutingLocationHash_location, _emberRoutingLocationHistory_location, _emberRoutingLocationAuto_location, _emberRoutingSystemGenerate_controller, _emberRoutingSystemController_for, _emberRoutingSystemDsl, _emberRoutingSystemRouter, _emberRoutingSystemRoute) { /** @module ember @submodule ember-routing */ 'use strict'; _emberMetalCore.default.Location = _emberRoutingLocationApi.default; _emberMetalCore.default.AutoLocation = _emberRoutingLocationAuto_location.default; _emberMetalCore.default.HashLocation = _emberRoutingLocationHash_location.default; _emberMetalCore.default.HistoryLocation = _emberRoutingLocationHistory_location.default; _emberMetalCore.default.NoneLocation = _emberRoutingLocationNone_location.default; _emberMetalCore.default.controllerFor = _emberRoutingSystemController_for.default; _emberMetalCore.default.generateControllerFactory = _emberRoutingSystemGenerate_controller.generateControllerFactory; _emberMetalCore.default.generateController = _emberRoutingSystemGenerate_controller.default; _emberMetalCore.default.RouterDSL = _emberRoutingSystemDsl.default; _emberMetalCore.default.Router = _emberRoutingSystemRouter.default; _emberMetalCore.default.Route = _emberRoutingSystemRoute.default; exports.default = _emberMetalCore.default; }); // reexports // ES6TODO: Cleanup modules with side-effects below enifed('ember-routing/location/api', ['exports', 'ember-metal/debug', 'ember-environment', 'ember-routing/location/util'], function (exports, _emberMetalDebug, _emberEnvironment, _emberRoutingLocationUtil) { 'use strict'; /** @module ember @submodule ember-routing */ /** Ember.Location returns an instance of the correct implementation of the `location` API. ## Implementations You can pass an implementation name (`hash`, `history`, `none`) to force a particular implementation to be used in your application. ### HashLocation Using `HashLocation` results in URLs with a `#` (hash sign) separating the server side URL portion of the URL from the portion that is used by Ember. This relies upon the `hashchange` event existing in the browser. Example: ```javascript App.Router.map(function() { this.route('posts', function() { this.route('new'); }); }); App.Router.reopen({ location: 'hash' }); ``` This will result in a posts.new url of `/#/posts/new`. ### HistoryLocation Using `HistoryLocation` results in URLs that are indistinguishable from a standard URL. This relies upon the browser's `history` API. Example: ```javascript App.Router.map(function() { this.route('posts', function() { this.route('new'); }); }); App.Router.reopen({ location: 'history' }); ``` This will result in a posts.new url of `/posts/new`. Keep in mind that your server must serve the Ember app at all the routes you define. ### AutoLocation Using `AutoLocation`, the router will use the best Location class supported by the browser it is running in. Browsers that support the `history` API will use `HistoryLocation`, those that do not, but still support the `hashchange` event will use `HashLocation`, and in the rare case neither is supported will use `NoneLocation`. Example: ```javascript App.Router.map(function() { this.route('posts', function() { this.route('new'); }); }); App.Router.reopen({ location: 'auto' }); ``` This will result in a posts.new url of `/posts/new` for modern browsers that support the `history` api or `/#/posts/new` for older ones, like Internet Explorer 9 and below. When a user visits a link to your application, they will be automatically upgraded or downgraded to the appropriate `Location` class, with the URL transformed accordingly, if needed. Keep in mind that since some of your users will use `HistoryLocation`, your server must serve the Ember app at all the routes you define. ### NoneLocation Using `NoneLocation` causes Ember to not store the applications URL state in the actual URL. This is generally used for testing purposes, and is one of the changes made when calling `App.setupForTesting()`. ## Location API Each location implementation must provide the following methods: * implementation: returns the string name used to reference the implementation. * getURL: returns the current URL. * setURL(path): sets the current URL. * replaceURL(path): replace the current URL (optional). * onUpdateURL(callback): triggers the callback when the URL changes. * formatURL(url): formats `url` to be placed into `href` attribute. * detect() (optional): instructs the location to do any feature detection necessary. If the location needs to redirect to a different URL, it can cancel routing by setting the `cancelRouterSetup` property on itself to `false`. Calling setURL or replaceURL will not trigger onUpdateURL callbacks. ## Custom implementation Ember scans `app/locations/*` for extending the Location API. Example: ```javascript import Ember from 'ember'; export default Ember.HistoryLocation.extend({ implementation: 'history-url-logging', pushState: function (path) { console.log(path); this._super.apply(this, arguments); } }); ``` @class Location @namespace Ember @static @private */ exports.default = { /** This is deprecated in favor of using the container to lookup the location implementation as desired. For example: ```javascript // Given a location registered as follows: container.register('location:history-test', HistoryTestLocation); // You could create a new instance via: container.lookup('location:history-test'); ``` @method create @param {Object} options @return {Object} an instance of an implementation of the `location` API @deprecated Use the container to lookup the location implementation that you need. @private */ create: function (options) { var implementation = options && options.implementation; _emberMetalDebug.assert('Ember.Location.create: you must specify a \'implementation\' option', !!implementation); var implementationClass = this.implementations[implementation]; _emberMetalDebug.assert('Ember.Location.create: ' + implementation + ' is not a valid implementation', !!implementationClass); return implementationClass.create.apply(implementationClass, arguments); }, implementations: {}, _location: _emberEnvironment.environment.location, /** Returns the current `location.hash` by parsing location.href since browsers inconsistently URL-decode `location.hash`. https://bugzilla.mozilla.org/show_bug.cgi?id=483304 @private @method getHash @since 1.4.0 */ _getHash: function () { return _emberRoutingLocationUtil.getHash(this.location); } }; }); enifed('ember-routing/location/auto_location', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/utils', 'container/owner', 'ember-runtime/system/object', 'ember-environment', 'ember-routing/location/util'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalUtils, _containerOwner, _emberRuntimeSystemObject, _emberEnvironment, _emberRoutingLocationUtil) { 'use strict'; exports.getHistoryPath = getHistoryPath; exports.getHashPath = getHashPath; /** @module ember @submodule ember-routing */ /** Ember.AutoLocation will select the best location option based off browser support with the priority order: history, hash, none. Clean pushState paths accessed by hashchange-only browsers will be redirected to the hash-equivalent and vice versa so future transitions are consistent. Keep in mind that since some of your users will use `HistoryLocation`, your server must serve the Ember app at all the routes you define. @class AutoLocation @namespace Ember @static @private */ exports.default = _emberRuntimeSystemObject.default.extend({ /** @private The browser's `location` object. This is typically equivalent to `window.location`, but may be overridden for testing. @property location @default environment.location */ location: _emberEnvironment.environment.location, /** @private The browser's `history` object. This is typically equivalent to `window.history`, but may be overridden for testing. @since 1.5.1 @property history @default environment.history */ history: _emberEnvironment.environment.history, /** @private The user agent's global variable. In browsers, this will be `window`. @since 1.11 @property global @default window */ global: _emberEnvironment.environment.window, /** @private The browser's `userAgent`. This is typically equivalent to `navigator.userAgent`, but may be overridden for testing. @since 1.5.1 @property userAgent @default environment.history */ userAgent: _emberEnvironment.environment.userAgent, /** @private This property is used by the router to know whether to cancel the routing setup process, which is needed while we redirect the browser. @since 1.5.1 @property cancelRouterSetup @default false */ cancelRouterSetup: false, /** @private Will be pre-pended to path upon state change. @since 1.5.1 @property rootURL @default '/' */ rootURL: '/', /** Called by the router to instruct the location to do any feature detection necessary. In the case of AutoLocation, we detect whether to use history or hash concrete implementations. @private */ detect: function () { var rootURL = this.rootURL; _emberMetalDebug.assert('rootURL must end with a trailing forward slash e.g. "/app/"', rootURL.charAt(rootURL.length - 1) === '/'); var implementation = detectImplementation({ location: this.location, history: this.history, userAgent: this.userAgent, rootURL: rootURL, documentMode: this.documentMode, global: this.global }); if (implementation === false) { _emberMetalProperty_set.set(this, 'cancelRouterSetup', true); implementation = 'none'; } var concrete = _containerOwner.getOwner(this).lookup('location:' + implementation); _emberMetalProperty_set.set(concrete, 'rootURL', rootURL); _emberMetalDebug.assert('Could not find location \'' + implementation + '\'.', !!concrete); _emberMetalProperty_set.set(this, 'concreteImplementation', concrete); }, initState: delegateToConcreteImplementation('initState'), getURL: delegateToConcreteImplementation('getURL'), setURL: delegateToConcreteImplementation('setURL'), replaceURL: delegateToConcreteImplementation('replaceURL'), onUpdateURL: delegateToConcreteImplementation('onUpdateURL'), formatURL: delegateToConcreteImplementation('formatURL'), willDestroy: function () { var concreteImplementation = _emberMetalProperty_get.get(this, 'concreteImplementation'); if (concreteImplementation) { concreteImplementation.destroy(); } } }); function delegateToConcreteImplementation(methodName) { return function () { var concreteImplementation = _emberMetalProperty_get.get(this, 'concreteImplementation'); _emberMetalDebug.assert('AutoLocation\'s detect() method should be called before calling any other hooks.', !!concreteImplementation); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _emberMetalUtils.tryInvoke(concreteImplementation, methodName, args); }; } /* Given the browser's `location`, `history` and `userAgent`, and a configured root URL, this function detects whether the browser supports the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History) and returns a string representing the Location object to use based on its determination. For example, if the page loads in an evergreen browser, this function would return the string "history", meaning the history API and thus HistoryLocation should be used. If the page is loaded in IE8, it will return the string "hash," indicating that the History API should be simulated by manipulating the hash portion of the location. */ function detectImplementation(options) { var location = options.location; var userAgent = options.userAgent; var history = options.history; var documentMode = options.documentMode; var global = options.global; var rootURL = options.rootURL; var implementation = 'none'; var cancelRouterSetup = false; var currentPath = _emberRoutingLocationUtil.getFullPath(location); if (_emberRoutingLocationUtil.supportsHistory(userAgent, history)) { var historyPath = getHistoryPath(rootURL, location); // If the browser supports history and we have a history path, we can use // the history location with no redirects. if (currentPath === historyPath) { return 'history'; } else { if (currentPath.substr(0, 2) === '/#') { history.replaceState({ path: historyPath }, null, historyPath); implementation = 'history'; } else { cancelRouterSetup = true; _emberRoutingLocationUtil.replacePath(location, historyPath); } } } else if (_emberRoutingLocationUtil.supportsHashChange(documentMode, global)) { var hashPath = getHashPath(rootURL, location); // Be sure we're using a hashed path, otherwise let's switch over it to so // we start off clean and consistent. We'll count an index path with no // hash as "good enough" as well. if (currentPath === hashPath || currentPath === '/' && hashPath === '/#/') { implementation = 'hash'; } else { // Our URL isn't in the expected hash-supported format, so we want to // cancel the router setup and replace the URL to start off clean cancelRouterSetup = true; _emberRoutingLocationUtil.replacePath(location, hashPath); } } if (cancelRouterSetup) { return false; } return implementation; } /** @private Returns the current path as it should appear for HistoryLocation supported browsers. This may very well differ from the real current path (e.g. if it starts off as a hashed URL) */ function getHistoryPath(rootURL, location) { var path = _emberRoutingLocationUtil.getPath(location); var hash = _emberRoutingLocationUtil.getHash(location); var query = _emberRoutingLocationUtil.getQuery(location); var rootURLIndex = path.indexOf(rootURL); var routeHash = undefined, hashParts = undefined; _emberMetalDebug.assert('Path ' + path + ' does not start with the provided rootURL ' + rootURL, rootURLIndex === 0); // By convention, Ember.js routes using HashLocation are required to start // with `#/`. Anything else should NOT be considered a route and should // be passed straight through, without transformation. if (hash.substr(0, 2) === '#/') { // There could be extra hash segments after the route hashParts = hash.substr(1).split('#'); // The first one is always the route url routeHash = hashParts.shift(); // If the path already has a trailing slash, remove the one // from the hashed route so we don't double up. if (path.slice(-1) === '/') { routeHash = routeHash.substr(1); } // This is the "expected" final order path = path + routeHash + query; if (hashParts.length) { path += '#' + hashParts.join('#'); } } else { path = path + query + hash; } return path; } /** @private Returns the current path as it should appear for HashLocation supported browsers. This may very well differ from the real current path. @method _getHashPath */ function getHashPath(rootURL, location) { var path = rootURL; var historyPath = getHistoryPath(rootURL, location); var routePath = historyPath.substr(rootURL.length); if (routePath !== '') { if (routePath.charAt(0) !== '/') { routePath = '/' + routePath; } path += '#' + routePath; } return path; } }); enifed('ember-routing/location/hash_location', ['exports', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/run_loop', 'ember-metal/utils', 'ember-runtime/system/object', 'ember-routing/location/api', 'ember-views/system/jquery'], function (exports, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalRun_loop, _emberMetalUtils, _emberRuntimeSystemObject, _emberRoutingLocationApi, _emberViewsSystemJquery) { 'use strict'; /** @module ember @submodule ember-routing */ /** `Ember.HashLocation` implements the location API using the browser's hash. At present, it relies on a `hashchange` event existing in the browser. @class HashLocation @namespace Ember @extends Ember.Object @private */ exports.default = _emberRuntimeSystemObject.default.extend({ implementation: 'hash', init: function () { _emberMetalProperty_set.set(this, 'location', _emberMetalProperty_get.get(this, '_location') || window.location); }, /** @private Returns normalized location.hash @since 1.5.1 @method getHash */ getHash: _emberRoutingLocationApi.default._getHash, /** Returns the normalized URL, constructed from `location.hash`. e.g. `#/foo` => `/foo` as well as `#/foo#bar` => `/foo#bar`. By convention, hashed paths must begin with a forward slash, otherwise they are not treated as a path so we can distinguish intent. @private @method getURL */ getURL: function () { var originalPath = this.getHash().substr(1); var outPath = originalPath; if (outPath.charAt(0) !== '/') { outPath = '/'; // Only add the # if the path isn't empty. // We do NOT want `/#` since the ampersand // is only included (conventionally) when // the location.hash has a value if (originalPath) { outPath += '#' + originalPath; } } return outPath; }, /** Set the `location.hash` and remembers what was set. This prevents `onUpdateURL` callbacks from triggering when the hash was set by `HashLocation`. @private @method setURL @param path {String} */ setURL: function (path) { _emberMetalProperty_get.get(this, 'location').hash = path; _emberMetalProperty_set.set(this, 'lastSetURL', path); }, /** Uses location.replace to update the url without a page reload or history modification. @private @method replaceURL @param path {String} */ replaceURL: function (path) { _emberMetalProperty_get.get(this, 'location').replace('#' + path); _emberMetalProperty_set.set(this, 'lastSetURL', path); }, /** Register a callback to be invoked when the hash changes. These callbacks will execute when the user presses the back or forward button, but not after `setURL` is invoked. @private @method onUpdateURL @param callback {Function} */ onUpdateURL: function (callback) { var _this = this; var guid = _emberMetalUtils.guidFor(this); _emberViewsSystemJquery.default(window).on('hashchange.ember-location-' + guid, function () { _emberMetalRun_loop.default(function () { var path = _this.getURL(); if (_emberMetalProperty_get.get(_this, 'lastSetURL') === path) { return; } _emberMetalProperty_set.set(_this, 'lastSetURL', null); callback(path); }); }); }, /** Given a URL, formats it to be placed into the page as part of an element's `href` attribute. This is used, for example, when using the {{action}} helper to generate a URL based on an event. @private @method formatURL @param url {String} */ formatURL: function (url) { return '#' + url; }, /** Cleans up the HashLocation event listener. @private @method willDestroy */ willDestroy: function () { var guid = _emberMetalUtils.guidFor(this); _emberViewsSystemJquery.default(window).off('hashchange.ember-location-' + guid); } }); }); enifed('ember-routing/location/history_location', ['exports', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/utils', 'ember-runtime/system/object', 'ember-routing/location/api', 'ember-views/system/jquery'], function (exports, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalUtils, _emberRuntimeSystemObject, _emberRoutingLocationApi, _emberViewsSystemJquery) { 'use strict'; /** @module ember @submodule ember-routing */ var popstateFired = false; /** Ember.HistoryLocation implements the location API using the browser's history.pushState API. @class HistoryLocation @namespace Ember @extends Ember.Object @private */ exports.default = _emberRuntimeSystemObject.default.extend({ implementation: 'history', init: function () { _emberMetalProperty_set.set(this, 'location', _emberMetalProperty_get.get(this, 'location') || window.location); _emberMetalProperty_set.set(this, 'baseURL', _emberViewsSystemJquery.default('base').attr('href') || ''); }, /** Used to set state on first call to setURL @private @method initState */ initState: function () { var history = _emberMetalProperty_get.get(this, 'history') || window.history; _emberMetalProperty_set.set(this, 'history', history); if (history && 'state' in history) { this.supportsHistory = true; } this.replaceState(this.formatURL(this.getURL())); }, /** Will be pre-pended to path upon state change @property rootURL @default '/' @private */ rootURL: '/', /** Returns the current `location.pathname` without `rootURL` or `baseURL` @private @method getURL @return url {String} */ getURL: function () { var location = _emberMetalProperty_get.get(this, 'location'); var path = location.pathname; var rootURL = _emberMetalProperty_get.get(this, 'rootURL'); var baseURL = _emberMetalProperty_get.get(this, 'baseURL'); // remove trailing slashes if they exists rootURL = rootURL.replace(/\/$/, ''); baseURL = baseURL.replace(/\/$/, ''); // remove baseURL and rootURL from start of path var url = path.replace(new RegExp('^' + baseURL + '(?=/|$)'), '').replace(new RegExp('^' + rootURL + '(?=/|$)'), ''); var search = location.search || ''; url += search; url += this.getHash(); return url; }, /** Uses `history.pushState` to update the url without a page reload. @private @method setURL @param path {String} */ setURL: function (path) { var state = this.getState(); path = this.formatURL(path); if (!state || state.path !== path) { this.pushState(path); } }, /** Uses `history.replaceState` to update the url without a page reload or history modification. @private @method replaceURL @param path {String} */ replaceURL: function (path) { var state = this.getState(); path = this.formatURL(path); if (!state || state.path !== path) { this.replaceState(path); } }, /** Get the current `history.state`. Checks for if a polyfill is required and if so fetches this._historyState. The state returned from getState may be null if an iframe has changed a window's history. @private @method getState @return state {Object} */ getState: function () { if (this.supportsHistory) { return _emberMetalProperty_get.get(this, 'history').state; } return this._historyState; }, /** Pushes a new state. @private @method pushState @param path {String} */ pushState: function (path) { var state = { path: path }; _emberMetalProperty_get.get(this, 'history').pushState(state, null, path); this._historyState = state; // used for webkit workaround this._previousURL = this.getURL(); }, /** Replaces the current state. @private @method replaceState @param path {String} */ replaceState: function (path) { var state = { path: path }; _emberMetalProperty_get.get(this, 'history').replaceState(state, null, path); this._historyState = state; // used for webkit workaround this._previousURL = this.getURL(); }, /** Register a callback to be invoked whenever the browser history changes, including using forward and back buttons. @private @method onUpdateURL @param callback {Function} */ onUpdateURL: function (callback) { var _this = this; var guid = _emberMetalUtils.guidFor(this); _emberViewsSystemJquery.default(window).on('popstate.ember-location-' + guid, function (e) { // Ignore initial page load popstate event in Chrome if (!popstateFired) { popstateFired = true; if (_this.getURL() === _this._previousURL) { return; } } callback(_this.getURL()); }); }, /** Used when using `{{action}}` helper. The url is always appended to the rootURL. @private @method formatURL @param url {String} @return formatted url {String} */ formatURL: function (url) { var rootURL = _emberMetalProperty_get.get(this, 'rootURL'); var baseURL = _emberMetalProperty_get.get(this, 'baseURL'); if (url !== '') { // remove trailing slashes if they exists rootURL = rootURL.replace(/\/$/, ''); baseURL = baseURL.replace(/\/$/, ''); } else if (baseURL.match(/^\//) && rootURL.match(/^\//)) { // if baseURL and rootURL both start with a slash // ... remove trailing slash from baseURL if it exists baseURL = baseURL.replace(/\/$/, ''); } return baseURL + rootURL + url; }, /** Cleans up the HistoryLocation event listener. @private @method willDestroy */ willDestroy: function () { var guid = _emberMetalUtils.guidFor(this); _emberViewsSystemJquery.default(window).off('popstate.ember-location-' + guid); }, /** @private Returns normalized location.hash @method getHash */ getHash: _emberRoutingLocationApi.default._getHash }); }); enifed('ember-routing/location/none_location', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-runtime/system/object'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set, _emberRuntimeSystemObject) { 'use strict'; /** @module ember @submodule ember-routing */ /** Ember.NoneLocation does not interact with the browser. It is useful for testing, or when you need to manage state with your Router, but temporarily don't want it to muck with the URL (for example when you embed your application in a larger page). @class NoneLocation @namespace Ember @extends Ember.Object @private */ exports.default = _emberRuntimeSystemObject.default.extend({ implementation: 'none', path: '', detect: function () { var rootURL = this.rootURL; _emberMetalDebug.assert('rootURL must end with a trailing forward slash e.g. "/app/"', rootURL.charAt(rootURL.length - 1) === '/'); }, /** Will be pre-pended to path. @private @property rootURL @default '/' */ rootURL: '/', /** Returns the current path without `rootURL`. @private @method getURL @return {String} path */ getURL: function () { var path = _emberMetalProperty_get.get(this, 'path'); var rootURL = _emberMetalProperty_get.get(this, 'rootURL'); // remove trailing slashes if they exists rootURL = rootURL.replace(/\/$/, ''); // remove rootURL from url return path.replace(new RegExp('^' + rootURL + '(?=/|$)'), ''); }, /** Set the path and remembers what was set. Using this method to change the path will not invoke the `updateURL` callback. @private @method setURL @param path {String} */ setURL: function (path) { _emberMetalProperty_set.set(this, 'path', path); }, /** Register a callback to be invoked when the path changes. These callbacks will execute when the user presses the back or forward button, but not after `setURL` is invoked. @private @method onUpdateURL @param callback {Function} */ onUpdateURL: function (callback) { this.updateCallback = callback; }, /** Sets the path and calls the `updateURL` callback. @private @method handleURL @param callback {Function} */ handleURL: function (url) { _emberMetalProperty_set.set(this, 'path', url); this.updateCallback(url); }, /** Given a URL, formats it to be placed into the page as part of an element's `href` attribute. This is used, for example, when using the {{action}} helper to generate a URL based on an event. @private @method formatURL @param url {String} @return {String} url */ formatURL: function (url) { var rootURL = _emberMetalProperty_get.get(this, 'rootURL'); if (url !== '') { // remove trailing slashes if they exists rootURL = rootURL.replace(/\/$/, ''); } return rootURL + url; } }); }); enifed('ember-routing/location/util', ['exports'], function (exports) { /** @private Returns the current `location.pathname`, normalized for IE inconsistencies. */ 'use strict'; exports.getPath = getPath; exports.getQuery = getQuery; exports.getHash = getHash; exports.getFullPath = getFullPath; exports.getOrigin = getOrigin; exports.supportsHashChange = supportsHashChange; exports.supportsHistory = supportsHistory; exports.replacePath = replacePath; function getPath(location) { var pathname = location.pathname; // Various versions of IE/Opera don't always return a leading slash if (pathname.charAt(0) !== '/') { pathname = '/' + pathname; } return pathname; } /** @private Returns the current `location.search`. */ function getQuery(location) { return location.search; } /** @private Returns the current `location.hash` by parsing location.href since browsers inconsistently URL-decode `location.hash`. Should be passed the browser's `location` object as the first argument. https://bugzilla.mozilla.org/show_bug.cgi?id=483304 */ function getHash(location) { var href = location.href; var hashIndex = href.indexOf('#'); if (hashIndex === -1) { return ''; } else { return href.substr(hashIndex); } } function getFullPath(location) { return getPath(location) + getQuery(location) + getHash(location); } function getOrigin(location) { var origin = location.origin; // Older browsers, especially IE, don't have origin if (!origin) { origin = location.protocol + '//' + location.hostname; if (location.port) { origin += ':' + location.port; } } return origin; } /* `documentMode` only exist in Internet Explorer, and it's tested because IE8 running in IE7 compatibility mode claims to support `onhashchange` but actually does not. `global` is an object that may have an `onhashchange` property. @private @function supportsHashChange */ function supportsHashChange(documentMode, global) { return 'onhashchange' in global && (documentMode === undefined || documentMode > 7); } /* `userAgent` is a user agent string. We use user agent testing here, because the stock Android browser is known to have buggy versions of the History API, in some Android versions. @private @function supportsHistory */ function supportsHistory(userAgent, history) { // Boosted from Modernizr: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js // The stock browser on Android 2.2 & 2.3, and 4.0.x returns positive on history support // Unfortunately support is really buggy and there is no clean way to detect // these bugs, so we fall back to a user agent sniff :( // We only want Android 2 and 4.0, stock browser, and not Chrome which identifies // itself as 'Mobile Safari' as well, nor Windows Phone. if ((userAgent.indexOf('Android 2.') !== -1 || userAgent.indexOf('Android 4.0') !== -1) && userAgent.indexOf('Mobile Safari') !== -1 && userAgent.indexOf('Chrome') === -1 && userAgent.indexOf('Windows Phone') === -1) { return false; } return !!(history && 'pushState' in history); } /** Replaces the current location, making sure we explicitly include the origin to prevent redirecting to a different origin. @private */ function replacePath(location, path) { location.replace(getOrigin(location) + path); } }); enifed('ember-routing/services/routing', ['exports', 'ember-runtime/system/service', 'ember-metal/property_get', 'ember-runtime/computed/computed_macros', 'ember-routing/utils', 'ember-metal/assign'], function (exports, _emberRuntimeSystemService, _emberMetalProperty_get, _emberRuntimeComputedComputed_macros, _emberRoutingUtils, _emberMetalAssign) { /** @module ember @submodule ember-routing */ 'use strict'; /** The Routing service is used by LinkComponent, and provides facilities for the component/view layer to interact with the router. While still private, this service can eventually be opened up, and provides the set of API needed for components to control routing without interacting with router internals. @private @class RoutingService */ exports.default = _emberRuntimeSystemService.default.extend({ router: null, targetState: _emberRuntimeComputedComputed_macros.readOnly('router.targetState'), currentState: _emberRuntimeComputedComputed_macros.readOnly('router.currentState'), currentRouteName: _emberRuntimeComputedComputed_macros.readOnly('router.currentRouteName'), currentPath: _emberRuntimeComputedComputed_macros.readOnly('router.currentPath'), availableRoutes: function () { return Object.keys(_emberMetalProperty_get.get(this, 'router').router.recognizer.names); }, hasRoute: function (routeName) { return _emberMetalProperty_get.get(this, 'router').hasRoute(routeName); }, transitionTo: function (routeName, models, queryParams, shouldReplace) { var router = _emberMetalProperty_get.get(this, 'router'); var transition = router._doTransition(routeName, models, queryParams); if (shouldReplace) { transition.method('replace'); } return transition; }, normalizeQueryParams: function (routeName, models, queryParams) { var router = _emberMetalProperty_get.get(this, 'router'); router._prepareQueryParams(routeName, models, queryParams); }, generateURL: function (routeName, models, queryParams) { var router = _emberMetalProperty_get.get(this, 'router'); if (!router.router) { return; } var visibleQueryParams = {}; _emberMetalAssign.default(visibleQueryParams, queryParams); this.normalizeQueryParams(routeName, models, visibleQueryParams); var args = _emberRoutingUtils.routeArgs(routeName, models, visibleQueryParams); return router.generate.apply(router, args); }, isActiveForRoute: function (contexts, queryParams, routeName, routerState, isCurrentWhenSpecified) { var router = _emberMetalProperty_get.get(this, 'router'); var handlers = router.router.recognizer.handlersFor(routeName); var leafName = handlers[handlers.length - 1].handler; var maximumContexts = numberOfContextsAcceptedByHandler(routeName, handlers); // NOTE: any ugliness in the calculation of activeness is largely // due to the fact that we support automatic normalizing of // `resource` -> `resource.index`, even though there might be // dynamic segments / query params defined on `resource.index` // which complicates (and makes somewhat ambiguous) the calculation // of activeness for links that link to `resource` instead of // directly to `resource.index`. // if we don't have enough contexts revert back to full route name // this is because the leaf route will use one of the contexts if (contexts.length > maximumContexts) { routeName = leafName; } return routerState.isActiveIntent(routeName, contexts, queryParams, !isCurrentWhenSpecified); } }); function numberOfContextsAcceptedByHandler(handler, handlerInfos) { var req = 0; for (var i = 0; i < handlerInfos.length; i++) { req = req + handlerInfos[i].names.length; if (handlerInfos[i].handler === handler) { break; } } return req; } }); enifed('ember-routing/system/cache', ['exports', 'ember-runtime/system/object'], function (exports, _emberRuntimeSystemObject) { 'use strict'; exports.default = _emberRuntimeSystemObject.default.extend({ init: function () { this.cache = {}; }, has: function (bucketKey) { return bucketKey in this.cache; }, stash: function (bucketKey, key, value) { var bucket = this.cache[bucketKey]; if (!bucket) { bucket = this.cache[bucketKey] = {}; } bucket[key] = value; }, lookup: function (bucketKey, prop, defaultValue) { var cache = this.cache; if (!(bucketKey in cache)) { return defaultValue; } var bucket = cache[bucketKey]; if (prop in bucket) { return bucket[prop]; } else { return defaultValue; } } }); }); enifed("ember-routing/system/controller_for", ["exports"], function (exports) { /** @module ember @submodule ember-routing */ /** Finds a controller instance. @for Ember @method controllerFor @private */ "use strict"; exports.default = controllerFor; function controllerFor(container, controllerName, lookupOptions) { return container.lookup("controller:" + controllerName, lookupOptions); } }); enifed('ember-routing/system/dsl', ['exports', 'ember-metal/debug', 'ember-metal/assign', 'ember-metal/features'], function (exports, _emberMetalDebug, _emberMetalAssign, _emberMetalFeatures) { 'use strict'; /** @module ember @submodule ember-routing */ function DSL(name, options) { this.parent = name; this.enableLoadingSubstates = options && options.enableLoadingSubstates; this.matches = []; this.explicitIndex = undefined; this.options = options; } exports.default = DSL; DSL.prototype = { route: function (name, options, callback) { var dummyErrorRoute = '/_unused_dummy_error_path_route_' + name + '/:error'; if (arguments.length === 2 && typeof options === 'function') { callback = options; options = {}; } if (arguments.length === 1) { options = {}; } _emberMetalDebug.assert('\'' + name + '\' cannot be used as a route name.', (function () { if (options.overrideNameAssertion === true) { return true; } return ['array', 'basic', 'object', 'application'].indexOf(name) === -1; })()); if (this.enableLoadingSubstates) { createRoute(this, name + '_loading', { resetNamespace: options.resetNamespace }); createRoute(this, name + '_error', { resetNamespace: options.resetNamespace, path: dummyErrorRoute }); } if (callback) { var fullName = getFullName(this, name, options.resetNamespace); var dsl = new DSL(fullName, this.options); createRoute(dsl, 'loading'); createRoute(dsl, 'error', { path: dummyErrorRoute }); callback.call(dsl); createRoute(this, name, options, dsl.generate()); } else { createRoute(this, name, options); } }, push: function (url, name, callback, serialize) { var parts = name.split('.'); if (true) { if (this.options.engineInfo) { var localFullName = name.slice(this.options.engineInfo.fullName.length + 1); var routeInfo = _emberMetalAssign.default({ localFullName: localFullName }, this.options.engineInfo); if (serialize) { routeInfo.serializeMethod = serialize; } this.options.addRouteForEngine(name, routeInfo); } else if (serialize) { throw new Error('Defining a route serializer on route \'' + name + '\' outside an Engine is not allowed.'); } } if (url === '' || url === '/' || parts[parts.length - 1] === 'index') { this.explicitIndex = true; } this.matches.push([url, name, callback]); }, resource: function (name, options, callback) { if (arguments.length === 2 && typeof options === 'function') { callback = options; options = {}; } if (arguments.length === 1) { options = {}; } options.resetNamespace = true; _emberMetalDebug.deprecate('this.resource() is deprecated. Use this.route(\'name\', { resetNamespace: true }, function () {}) instead.', false, { id: 'ember-routing.router-resource', until: '3.0.0' }); this.route(name, options, callback); }, generate: function () { var dslMatches = this.matches; if (!this.explicitIndex) { this.route('index', { path: '/' }); } return function (match) { for (var i = 0; i < dslMatches.length; i++) { var dslMatch = dslMatches[i]; match(dslMatch[0]).to(dslMatch[1], dslMatch[2]); } }; } }; function canNest(dsl) { return dsl.parent && dsl.parent !== 'application'; } function getFullName(dsl, name, resetNamespace) { if (canNest(dsl) && resetNamespace !== true) { return dsl.parent + '.' + name; } else { return name; } } function createRoute(dsl, name, options, callback) { options = options || {}; var fullName = getFullName(dsl, name, options.resetNamespace); if (typeof options.path !== 'string') { options.path = '/' + name; } dsl.push(options.path, fullName, callback, options.serialize); } DSL.map = function (callback) { var dsl = new DSL(); callback.call(dsl); return dsl; }; if (true) { (function () { var uuid = 0; DSL.prototype.mount = function (_name, _options) { var options = _options || {}; var engineRouteMap = this.options.resolveRouteMap(_name); var name = _name; if (options.as) { name = options.as; } var fullName = getFullName(this, name, options.resetNamespace); var engineInfo = { name: _name, instanceId: uuid++, mountPoint: fullName, fullName: fullName }; var path = options.path; if (typeof path !== 'string') { path = '/' + name; } var callback = undefined; if (engineRouteMap) { var shouldResetEngineInfo = false; var oldEngineInfo = this.options.engineInfo; if (oldEngineInfo) { shouldResetEngineInfo = true; this.options.engineInfo = engineInfo; } var optionsForChild = _emberMetalAssign.default({ engineInfo: engineInfo }, this.options); var childDSL = new DSL(fullName, optionsForChild); engineRouteMap.call(childDSL); callback = childDSL.generate(); if (shouldResetEngineInfo) { this.options.engineInfo = oldEngineInfo; } } if (this.enableLoadingSubstates) { var dummyErrorRoute = '/_unused_dummy_error_path_route_' + name + '/:error'; createRoute(this, name + '_loading', { resetNamespace: options.resetNamespace }); createRoute(this, name + '_error', { resetNamespace: options.resetNamespace, path: dummyErrorRoute }); } var localFullName = 'application'; var routeInfo = _emberMetalAssign.default({ localFullName: localFullName }, engineInfo); this.options.addRouteForEngine(fullName, routeInfo); this.push(path, fullName, callback); }; })(); } }); enifed('ember-routing/system/generate_controller', ['exports', 'ember-metal/debug', 'ember-metal/property_get'], function (exports, _emberMetalDebug, _emberMetalProperty_get) { 'use strict'; exports.generateControllerFactory = generateControllerFactory; exports.default = generateController; /** @module ember @submodule ember-routing */ /** Generates a controller factory @for Ember @method generateControllerFactory @private */ function generateControllerFactory(owner, controllerName, context) { var Factory = owner._lookupFactory('controller:basic').extend({ isGenerated: true, toString: function () { return '(generated ' + controllerName + ' controller)'; } }); var fullName = 'controller:' + controllerName; owner.register(fullName, Factory); return Factory; } /** Generates and instantiates a controller. The type of the generated controller factory is derived from the context. If the context is an array an array controller is generated, if an object, an object controller otherwise, a basic controller is generated. @for Ember @method generateController @private @since 1.3.0 */ function generateController(owner, controllerName, context) { generateControllerFactory(owner, controllerName, context); var fullName = 'controller:' + controllerName; var instance = owner.lookup(fullName); if (_emberMetalProperty_get.get(instance, 'namespace.LOG_ACTIVE_GENERATION')) { _emberMetalDebug.info('generated -> ' + fullName, { fullName: fullName }); } return instance; } }); enifed('ember-routing/system/query_params', ['exports', 'ember-runtime/system/object'], function (exports, _emberRuntimeSystemObject) { 'use strict'; exports.default = _emberRuntimeSystemObject.default.extend({ isQueryParams: true, values: null }); }); enifed('ember-routing/system/route', ['exports', 'ember-metal/debug', 'ember-metal/testing', 'ember-metal/features', 'ember-metal/error', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/get_properties', 'ember-metal/is_none', 'ember-metal/computed', 'ember-metal/assign', 'ember-runtime/utils', 'ember-metal/run_loop', 'ember-runtime/copy', 'ember-runtime/system/string', 'ember-runtime/system/object', 'ember-runtime/system/native_array', 'ember-runtime/mixins/evented', 'ember-runtime/mixins/action_handler', 'ember-routing/system/generate_controller', 'ember-routing/utils', 'container/owner', 'ember-metal/is_empty', 'ember-metal/symbol'], function (exports, _emberMetalDebug, _emberMetalTesting, _emberMetalFeatures, _emberMetalError, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalGet_properties, _emberMetalIs_none, _emberMetalComputed, _emberMetalAssign, _emberRuntimeUtils, _emberMetalRun_loop, _emberRuntimeCopy, _emberRuntimeSystemString, _emberRuntimeSystemObject, _emberRuntimeSystemNative_array, _emberRuntimeMixinsEvented, _emberRuntimeMixinsAction_handler, _emberRoutingSystemGenerate_controller, _emberRoutingUtils, _containerOwner, _emberMetalIs_empty, _emberMetalSymbol) { 'use strict'; exports.defaultSerialize = defaultSerialize; exports.hasDefaultSerialize = hasDefaultSerialize; var slice = Array.prototype.slice; function K() { return this; } function defaultSerialize(model, params) { if (params.length < 1) { return; } if (!model) { return; } var name = params[0]; var object = {}; if (params.length === 1) { if (name in model) { object[name] = _emberMetalProperty_get.get(model, name); } else if (/_id$/.test(name)) { object[name] = _emberMetalProperty_get.get(model, 'id'); } } else { object = _emberMetalGet_properties.default(model, params); } return object; } var DEFAULT_SERIALIZE = _emberMetalSymbol.default('DEFAULT_SERIALIZE'); if (true) { defaultSerialize[DEFAULT_SERIALIZE] = true; } function hasDefaultSerialize(route) { return !!route.serialize[DEFAULT_SERIALIZE]; } /** @module ember @submodule ember-routing */ /** The `Ember.Route` class is used to define individual routes. Refer to the [routing guide](http://emberjs.com/guides/routing/) for documentation. @class Route @namespace Ember @extends Ember.Object @uses Ember.ActionHandler @uses Ember.Evented @public */ var Route = _emberRuntimeSystemObject.default.extend(_emberRuntimeMixinsAction_handler.default, _emberRuntimeMixinsEvented.default, { /** Configuration hash for this route's queryParams. The possible configuration options and their defaults are as follows (assuming a query param whose controller property is `page`): ```javascript queryParams: { page: { // By default, controller query param properties don't // cause a full transition when they are changed, but // rather only cause the URL to update. Setting // `refreshModel` to true will cause an "in-place" // transition to occur, whereby the model hooks for // this route (and any child routes) will re-fire, allowing // you to reload models (e.g., from the server) using the // updated query param values. refreshModel: false, // By default, changes to controller query param properties // cause the URL to update via `pushState`, which means an // item will be added to the browser's history, allowing // you to use the back button to restore the app to the // previous state before the query param property was changed. // Setting `replace` to true will use `replaceState` (or its // hash location equivalent), which causes no browser history // item to be added. This options name and default value are // the same as the `link-to` helper's `replace` option. replace: false, // By default, the query param URL key is the same name as // the controller property name. Use `as` to specify a // different URL key. as: 'page' } } ``` @property queryParams @for Ember.Route @type Object @public */ queryParams: {}, /** The name of the route, dot-delimited. For example, a route found at `app/routes/posts/post.js` or `app/posts/post/route.js` (with pods) will have a `routeName` of `posts.post`. @property routeName @for Ember.Route @type String @public */ /** @private @property _qp */ _qp: _emberMetalComputed.computed(function () { var _this = this; var controllerProto = undefined, combinedQueryParameterConfiguration = undefined; var controllerName = this.controllerName || this.routeName; var definedControllerClass = _containerOwner.getOwner(this)._lookupFactory('controller:' + controllerName); var queryParameterConfiguraton = _emberMetalProperty_get.get(this, 'queryParams'); var hasRouterDefinedQueryParams = !!Object.keys(queryParameterConfiguraton).length; if (definedControllerClass) { // the developer has authored a controller class in their application for this route // access the prototype, find its query params and normalize their object shape // them merge in the query params for the route. As a mergedProperty, Route#queryParams is always // at least `{}` controllerProto = definedControllerClass.proto(); var controllerDefinedQueryParameterConfiguration = _emberMetalProperty_get.get(controllerProto, 'queryParams'); var normalizedControllerQueryParameterConfiguration = _emberRoutingUtils.normalizeControllerQueryParams(controllerDefinedQueryParameterConfiguration); combinedQueryParameterConfiguration = mergeEachQueryParams(normalizedControllerQueryParameterConfiguration, queryParameterConfiguraton); if (false) { if (controllerDefinedQueryParameterConfiguration.length) { _emberMetalDebug.deprecate('Configuring query parameters on a controller is deprecated. Migrate the query parameters configuration from the \'' + controllerName + '\' controller to the \'' + this.routeName + '\' route: ' + combinedQueryParameterConfiguration, false, { id: 'ember-routing.controller-configured-query-params', until: '3.0.0' }); } } } else if (hasRouterDefinedQueryParams) { // the developer has not defined a controller but *has* supplied route query params. // Generate a class for them so we can later insert default values var generatedControllerClass = _emberRoutingSystemGenerate_controller.generateControllerFactory(_containerOwner.getOwner(this), controllerName); controllerProto = generatedControllerClass.proto(); combinedQueryParameterConfiguration = queryParameterConfiguraton; } var qps = []; var map = {}; var propertyNames = []; for (var propName in combinedQueryParameterConfiguration) { if (!combinedQueryParameterConfiguration.hasOwnProperty(propName)) { continue; } // to support the dubious feature of using unknownProperty // on queryParams configuration if (propName === 'unknownProperty' || propName === '_super') { // possible todo: issue deprecation warning? continue; } var desc = combinedQueryParameterConfiguration[propName]; if (false) { // apply default values to controllers // detect that default value defined on router config if (desc.hasOwnProperty('defaultValue')) { // detect that property was not defined on controller if (controllerProto[propName] === undefined) { controllerProto[propName] = desc.defaultValue; } else { deprecateQueryParamDefaultValuesSetOnController(controllerName, this.routeName, propName); } } } var scope = desc.scope || 'model'; var parts = undefined; if (scope === 'controller') { parts = []; } var urlKey = desc.as || this.serializeQueryParamKey(propName); var defaultValue = _emberMetalProperty_get.get(controllerProto, propName); if (Array.isArray(defaultValue)) { defaultValue = _emberRuntimeSystemNative_array.A(defaultValue.slice()); } var type = desc.type || _emberRuntimeUtils.typeOf(defaultValue); var defaultValueSerialized = this.serializeQueryParam(defaultValue, urlKey, type); var scopedPropertyName = controllerName + ':' + propName; var qp = { undecoratedDefaultValue: _emberMetalProperty_get.get(controllerProto, propName), defaultValue: defaultValue, serializedDefaultValue: defaultValueSerialized, serializedValue: defaultValueSerialized, type: type, urlKey: urlKey, prop: propName, scopedPropertyName: scopedPropertyName, ctrl: controllerName, route: this, parts: parts, // provided later when stashNames is called if 'model' scope values: null, // provided later when setup is called. no idea why. scope: scope, prefix: '' }; map[propName] = map[urlKey] = map[scopedPropertyName] = qp; qps.push(qp); propertyNames.push(propName); } return { qps: qps, map: map, propertyNames: propertyNames, states: { /* Called when a query parameter changes in the URL, this route cares about that query parameter, but the route is not currently in the active route hierarchy. */ inactive: function (prop, value) { var qp = map[prop]; _this._qpChanged(prop, value, qp); }, /* Called when a query parameter changes in the URL, this route cares about that query parameter, and the route is currently in the active route hierarchy. */ active: function (prop, value) { var qp = map[prop]; _this._qpChanged(prop, value, qp); return _this._activeQPChanged(map[prop], value); }, /* Called when a value of a query parameter this route handles changes in a controller and the route is currently in the active route hierarchy. */ allowOverrides: function (prop, value) { var qp = map[prop]; _this._qpChanged(prop, value, qp); return _this._updatingQPChanged(map[prop]); } } }; }), /** @private @property _names */ _names: null, /** @private @method _stashNames */ _stashNames: function (_handlerInfo, dynamicParent) { var handlerInfo = _handlerInfo; if (this._names) { return; } var names = this._names = handlerInfo._names; if (!names.length) { handlerInfo = dynamicParent; names = handlerInfo && handlerInfo._names || []; } var qps = _emberMetalProperty_get.get(this, '_qp.qps'); var namePaths = new Array(names.length); for (var a = 0; a < names.length; ++a) { namePaths[a] = handlerInfo.name + '.' + names[a]; } for (var i = 0; i < qps.length; ++i) { var qp = qps[i]; if (qp.scope === 'model') { qp.parts = namePaths; } qp.prefix = qp.ctrl; } }, /** @private @property _activeQPChanged */ _activeQPChanged: function (qp, value) { var router = this.router; router._activeQPChanged(qp.scopedPropertyName, value); }, /** @private @method _updatingQPChanged */ _updatingQPChanged: function (qp) { var router = this.router; router._updatingQPChanged(qp.urlKey); }, mergedProperties: ['queryParams'], /** Retrieves parameters, for current route using the state.params variable and getQueryParamsFor, using the supplied routeName. @method paramsFor @param {String} name @public */ paramsFor: function (name) { var route = _containerOwner.getOwner(this).lookup('route:' + name); if (!route) { return {}; } var transition = this.router.router.activeTransition; var state = transition ? transition.state : this.router.router.state; var params = {}; var fullName = name; if (true) { fullName = getEngineRouteName(_containerOwner.getOwner(this), name); } _emberMetalAssign.default(params, state.params[fullName]); _emberMetalAssign.default(params, getQueryParamsFor(route, state)); return params; }, /** Serializes the query parameter key @method serializeQueryParamKey @param {String} controllerPropertyName @private */ serializeQueryParamKey: function (controllerPropertyName) { return controllerPropertyName; }, /** Serializes value of the query parameter based on defaultValueType @method serializeQueryParam @param {Object} value @param {String} urlKey @param {String} defaultValueType @private */ serializeQueryParam: function (value, urlKey, defaultValueType) { // urlKey isn't used here, but anyone overriding // can use it to provide serialization specific // to a certain query param. if (defaultValueType === 'array') { return JSON.stringify(value); } return '' + value; }, /** Deserializes value of the query parameter based on defaultValueType @method deserializeQueryParam @param {Object} value @param {String} urlKey @param {String} defaultValueType @private */ deserializeQueryParam: function (value, urlKey, defaultValueType) { // urlKey isn't used here, but anyone overriding // can use it to provide deserialization specific // to a certain query param. // Use the defaultValueType of the default value (the initial value assigned to a // controller query param property), to intelligently deserialize and cast. if (defaultValueType === 'boolean') { return value === 'true' ? true : false; } else if (defaultValueType === 'number') { return Number(value).valueOf(); } else if (defaultValueType === 'array') { return _emberRuntimeSystemNative_array.A(JSON.parse(value)); } return value; }, /** @private @property _optionsForQueryParam */ _optionsForQueryParam: function (qp) { return _emberMetalProperty_get.get(this, 'queryParams.' + qp.urlKey) || _emberMetalProperty_get.get(this, 'queryParams.' + qp.prop) || {}; }, /** A hook you can use to reset controller values either when the model changes or the route is exiting. ```javascript App.ArticlesRoute = Ember.Route.extend({ // ... resetController: function(controller, isExiting, transition) { if (isExiting) { controller.set('page', 1); } } }); ``` @method resetController @param {Controller} controller instance @param {Boolean} isExiting @param {Object} transition @since 1.7.0 @public */ resetController: K, /** @private @method exit */ exit: function () { this.deactivate(); this.trigger('deactivate'); this.teardownViews(); }, /** @private @method _reset @since 1.7.0 */ _reset: function (isExiting, transition) { var controller = this.controller; controller._qpDelegate = _emberMetalProperty_get.get(this, '_qp.states.inactive'); this.resetController(controller, isExiting, transition); }, /** @private @method enter */ enter: function () { this.connections = []; this.activate(); this.trigger('activate'); }, /** The name of the template to use by default when rendering this routes template. ```javascript let PostsList = Ember.Route.extend({ templateName: 'posts/list' }); App.PostsIndexRoute = PostsList.extend(); App.PostsArchivedRoute = PostsList.extend(); ``` @property templateName @type String @default null @since 1.4.0 @public */ templateName: null, /** The name of the controller to associate with this route. By default, Ember will lookup a route's controller that matches the name of the route (i.e. `App.PostController` for `App.PostRoute`). However, if you would like to define a specific controller to use, you can do so using this property. This is useful in many ways, as the controller specified will be: * passed to the `setupController` method. * used as the controller for the template being rendered by the route. * returned from a call to `controllerFor` for the route. @property controllerName @type String @default null @since 1.4.0 @public */ controllerName: null, /** The `willTransition` action is fired at the beginning of any attempted transition with a `Transition` object as the sole argument. This action can be used for aborting, redirecting, or decorating the transition from the currently active routes. A good example is preventing navigation when a form is half-filled out: ```javascript App.ContactFormRoute = Ember.Route.extend({ actions: { willTransition: function(transition) { if (this.controller.get('userHasEnteredData')) { this.controller.displayNavigationConfirm(); transition.abort(); } } } }); ``` You can also redirect elsewhere by calling `this.transitionTo('elsewhere')` from within `willTransition`. Note that `willTransition` will not be fired for the redirecting `transitionTo`, since `willTransition` doesn't fire when there is already a transition underway. If you want subsequent `willTransition` actions to fire for the redirecting transition, you must first explicitly call `transition.abort()`. To allow the `willTransition` event to continue bubbling to the parent route, use `return true;`. When the `willTransition` method has a return value of `true` then the parent route's `willTransition` method will be fired, enabling "bubbling" behavior for the event. @event willTransition @param {Transition} transition @public */ /** The `didTransition` action is fired after a transition has successfully been completed. This occurs after the normal model hooks (`beforeModel`, `model`, `afterModel`, `setupController`) have resolved. The `didTransition` action has no arguments, however, it can be useful for tracking page views or resetting state on the controller. ```javascript App.LoginRoute = Ember.Route.extend({ actions: { didTransition: function() { this.controller.get('errors.base').clear(); return true; // Bubble the didTransition event } } }); ``` @event didTransition @since 1.2.0 @public */ /** The `loading` action is fired on the route when a route's `model` hook returns a promise that is not already resolved. The current `Transition` object is the first parameter and the route that triggered the loading event is the second parameter. ```javascript App.ApplicationRoute = Ember.Route.extend({ actions: { loading: function(transition, route) { let controller = this.controllerFor('foo'); controller.set('currentlyLoading', true); transition.finally(function() { controller.set('currentlyLoading', false); }); } } }); ``` @event loading @param {Transition} transition @param {Ember.Route} route The route that triggered the loading event @since 1.2.0 @public */ /** When attempting to transition into a route, any of the hooks may return a promise that rejects, at which point an `error` action will be fired on the partially-entered routes, allowing for per-route error handling logic, or shared error handling logic defined on a parent route. Here is an example of an error handler that will be invoked for rejected promises from the various hooks on the route, as well as any unhandled errors from child routes: ```javascript App.AdminRoute = Ember.Route.extend({ beforeModel: function() { return Ember.RSVP.reject('bad things!'); }, actions: { error: function(error, transition) { // Assuming we got here due to the error in `beforeModel`, // we can expect that error === "bad things!", // but a promise model rejecting would also // call this hook, as would any errors encountered // in `afterModel`. // The `error` hook is also provided the failed // `transition`, which can be stored and later // `.retry()`d if desired. this.transitionTo('login'); } } }); ``` `error` actions that bubble up all the way to `ApplicationRoute` will fire a default error handler that logs the error. You can specify your own global default error handler by overriding the `error` handler on `ApplicationRoute`: ```javascript App.ApplicationRoute = Ember.Route.extend({ actions: { error: function(error, transition) { this.controllerFor('banner').displayError(error.message); } } }); ``` @event error @param {Error} error @param {Transition} transition @public */ /** This event is triggered when the router enters the route. It is not executed when the model for the route changes. ```javascript App.ApplicationRoute = Ember.Route.extend({ collectAnalytics: function(){ collectAnalytics(); }.on('activate') }); ``` @event activate @since 1.9.0 @public */ /** This event is triggered when the router completely exits this route. It is not executed when the model for the route changes. ```javascript App.IndexRoute = Ember.Route.extend({ trackPageLeaveAnalytics: function(){ trackPageLeaveAnalytics(); }.on('deactivate') }); ``` @event deactivate @since 1.9.0 @public */ /** The controller associated with this route. Example ```javascript App.FormRoute = Ember.Route.extend({ actions: { willTransition: function(transition) { if (this.controller.get('userHasEnteredData') && !confirm('Are you sure you want to abandon progress?')) { transition.abort(); } else { // Bubble the `willTransition` action so that // parent routes can decide whether or not to abort. return true; } } } }); ``` @property controller @type Ember.Controller @since 1.6.0 @public */ actions: { /** This action is called when one or more query params have changed. Bubbles. @method queryParamsDidChange @param changed {Object} Keys are names of query params that have changed. @param totalPresent {Object} Keys are names of query params that are currently set. @param removed {Object} Keys are names of query params that have been removed. @returns {boolean} @private */ queryParamsDidChange: function (changed, totalPresent, removed) { var qpMap = _emberMetalProperty_get.get(this, '_qp').map; var totalChanged = Object.keys(changed).concat(Object.keys(removed)); for (var i = 0; i < totalChanged.length; ++i) { var qp = qpMap[totalChanged[i]]; if (qp && _emberMetalProperty_get.get(this._optionsForQueryParam(qp), 'refreshModel') && this.router.currentState) { this.refresh(); } } return true; }, finalizeQueryParamChange: function (params, finalParams, transition) { if (this.routeName !== 'application') { return true; } // Transition object is absent for intermediate transitions. if (!transition) { return; } var handlerInfos = transition.state.handlerInfos; var router = this.router; var qpMeta = router._queryParamsFor(handlerInfos[handlerInfos.length - 1].name); var changes = router._qpUpdates; var replaceUrl = undefined; _emberRoutingUtils.stashParamNames(router, handlerInfos); for (var i = 0; i < qpMeta.qps.length; ++i) { var qp = qpMeta.qps[i]; var route = qp.route; var controller = route.controller; var presentKey = qp.urlKey in params && qp.urlKey; // Do a reverse lookup to see if the changed query // param URL key corresponds to a QP property on // this controller. var value = undefined, svalue = undefined; if (changes && qp.urlKey in changes) { // Value updated in/before setupController value = _emberMetalProperty_get.get(controller, qp.prop); svalue = route.serializeQueryParam(value, qp.urlKey, qp.type); } else { if (presentKey) { svalue = params[presentKey]; value = route.deserializeQueryParam(svalue, qp.urlKey, qp.type); } else { // No QP provided; use default value. svalue = qp.serializedDefaultValue; value = copyDefaultValue(qp.defaultValue); } } controller._qpDelegate = _emberMetalProperty_get.get(route, '_qp.states.inactive'); var thisQueryParamChanged = svalue !== qp.serializedValue; if (thisQueryParamChanged) { if (transition.queryParamsOnly && replaceUrl !== false) { var options = route._optionsForQueryParam(qp); var replaceConfigValue = _emberMetalProperty_get.get(options, 'replace'); if (replaceConfigValue) { replaceUrl = true; } else if (replaceConfigValue === false) { // Explicit pushState wins over any other replaceStates. replaceUrl = false; } } _emberMetalProperty_set.set(controller, qp.prop, value); } // Stash current serialized value of controller. qp.serializedValue = svalue; var thisQueryParamHasDefaultValue = qp.serializedDefaultValue === svalue; if (!thisQueryParamHasDefaultValue) { finalParams.push({ value: svalue, visible: true, key: presentKey || qp.urlKey }); } } if (replaceUrl) { transition.method('replace'); } qpMeta.qps.forEach(function (qp) { var routeQpMeta = _emberMetalProperty_get.get(qp.route, '_qp'); var finalizedController = qp.route.controller; finalizedController._qpDelegate = _emberMetalProperty_get.get(routeQpMeta, 'states.active'); }); router._qpUpdates = null; } }, /** This hook is executed when the router completely exits this route. It is not executed when the model for the route changes. @method deactivate @public */ deactivate: K, /** This hook is executed when the router enters the route. It is not executed when the model for the route changes. @method activate @public */ activate: K, /** Transition the application into another route. The route may be either a single route or route path: ```javascript this.transitionTo('blogPosts'); this.transitionTo('blogPosts.recentEntries'); ``` Optionally supply a model for the route in question. The model will be serialized into the URL using the `serialize` hook of the route: ```javascript this.transitionTo('blogPost', aPost); ``` If a literal is passed (such as a number or a string), it will be treated as an identifier instead. In this case, the `model` hook of the route will be triggered: ```javascript this.transitionTo('blogPost', 1); ``` Multiple models will be applied last to first recursively up the route tree. ```javascript App.Router.map(function() { this.route('blogPost', { path:':blogPostId' }, function() { this.route('blogComment', { path: ':blogCommentId', resetNamespace: true }); }); }); this.transitionTo('blogComment', aPost, aComment); this.transitionTo('blogComment', 1, 13); ``` It is also possible to pass a URL (a string that starts with a `/`). This is intended for testing and debugging purposes and should rarely be used in production code. ```javascript this.transitionTo('/'); this.transitionTo('/blog/post/1/comment/13'); this.transitionTo('/blog/posts?sort=title'); ``` An options hash with a `queryParams` property may be provided as the final argument to add query parameters to the destination URL. ```javascript this.transitionTo('blogPost', 1, { queryParams: { showComments: 'true' } }); // if you just want to transition the query parameters without changing the route this.transitionTo({ queryParams: { sort: 'date' } }); ``` See also [replaceWith](#method_replaceWith). Simple Transition Example ```javascript App.Router.map(function() { this.route('index'); this.route('secret'); this.route('fourOhFour', { path: '*:' }); }); App.IndexRoute = Ember.Route.extend({ actions: { moveToSecret: function(context) { if (authorized()) { this.transitionTo('secret', context); } else { this.transitionTo('fourOhFour'); } } } }); ``` Transition to a nested route ```javascript App.Router.map(function() { this.route('articles', { path: '/articles' }, function() { this.route('new'); }); }); App.IndexRoute = Ember.Route.extend({ actions: { transitionToNewArticle: function() { this.transitionTo('articles.new'); } } }); ``` Multiple Models Example ```javascript App.Router.map(function() { this.route('index'); this.route('breakfast', { path: ':breakfastId' }, function() { this.route('cereal', { path: ':cerealId', resetNamespace: true }); }); }); App.IndexRoute = Ember.Route.extend({ actions: { moveToChocolateCereal: function() { let cereal = { cerealId: 'ChocolateYumminess' }; let breakfast = { breakfastId: 'CerealAndMilk' }; this.transitionTo('cereal', breakfast, cereal); } } }); ``` Nested Route with Query String Example ```javascript App.Router.map(function() { this.route('fruits', function() { this.route('apples'); }); }); App.IndexRoute = Ember.Route.extend({ actions: { transitionToApples: function() { this.transitionTo('fruits.apples', { queryParams: { color: 'red' } }); } } }); ``` @method transitionTo @param {String} name the name of the route or a URL @param {...Object} models the model(s) or identifier(s) to be used while transitioning to the route. @param {Object} [options] optional hash with a queryParams property containing a mapping of query parameters @return {Transition} the transition object associated with this attempted transition @public */ transitionTo: function (name, context) { var router = this.router; return router.transitionTo.apply(router, arguments); }, /** Perform a synchronous transition into another route without attempting to resolve promises, update the URL, or abort any currently active asynchronous transitions (i.e. regular transitions caused by `transitionTo` or URL changes). This method is handy for performing intermediate transitions on the way to a final destination route, and is called internally by the default implementations of the `error` and `loading` handlers. @method intermediateTransitionTo @param {String} name the name of the route @param {...Object} models the model(s) to be used while transitioning to the route. @since 1.2.0 @public */ intermediateTransitionTo: function () { var router = this.router; router.intermediateTransitionTo.apply(router, arguments); }, /** Refresh the model on this route and any child routes, firing the `beforeModel`, `model`, and `afterModel` hooks in a similar fashion to how routes are entered when transitioning in from other route. The current route params (e.g. `article_id`) will be passed in to the respective model hooks, and if a different model is returned, `setupController` and associated route hooks will re-fire as well. An example usage of this method is re-querying the server for the latest information using the same parameters as when the route was first entered. Note that this will cause `model` hooks to fire even on routes that were provided a model object when the route was initially entered. @method refresh @return {Transition} the transition object associated with this attempted transition @since 1.4.0 @public */ refresh: function () { return this.router.router.refresh(this); }, /** Transition into another route while replacing the current URL, if possible. This will replace the current history entry instead of adding a new one. Beside that, it is identical to `transitionTo` in all other respects. See 'transitionTo' for additional information regarding multiple models. Example ```javascript App.Router.map(function() { this.route('index'); this.route('secret'); }); App.SecretRoute = Ember.Route.extend({ afterModel: function() { if (!authorized()){ this.replaceWith('index'); } } }); ``` @method replaceWith @param {String} name the name of the route or a URL @param {...Object} models the model(s) or identifier(s) to be used while transitioning to the route. @return {Transition} the transition object associated with this attempted transition @public */ replaceWith: function () { var router = this.router; return router.replaceWith.apply(router, arguments); }, /** Sends an action to the router, which will delegate it to the currently active route hierarchy per the bubbling rules explained under `actions`. Example ```javascript App.Router.map(function() { this.route('index'); }); App.ApplicationRoute = Ember.Route.extend({ actions: { track: function(arg) { console.log(arg, 'was clicked'); } } }); App.IndexRoute = Ember.Route.extend({ actions: { trackIfDebug: function(arg) { if (debug) { this.send('track', arg); } } } }); ``` @method send @param {String} name the name of the action to trigger @param {...*} args @public */ send: function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (this.router && this.router.router || !_emberMetalTesting.isTesting()) { var _router; (_router = this.router).send.apply(_router, args); } else { var _name2 = args[0]; args = slice.call(args, 1); var action = this.actions[_name2]; if (action) { return this.actions[_name2].apply(this, args); } } }, /** This hook is the entry point for router.js @private @method setup */ setup: function (context, transition) { var _this2 = this; var controller = undefined; var controllerName = this.controllerName || this.routeName; var definedController = this.controllerFor(controllerName, true); if (!definedController) { controller = this.generateController(controllerName, context); } else { controller = definedController; } // Assign the route's controller so that it can more easily be // referenced in action handlers. Side effects. Side effects everywhere. if (!this.controller) { var propNames = _emberMetalProperty_get.get(this, '_qp.propertyNames'); addQueryParamsObservers(controller, propNames); this.controller = controller; } var queryParams = _emberMetalProperty_get.get(this, '_qp'); var states = queryParams.states; if (transition) { (function () { // Update the model dep values used to calculate cache keys. _emberRoutingUtils.stashParamNames(_this2.router, transition.state.handlerInfos); var params = transition.params; var allParams = queryParams.propertyNames; var cache = _this2._bucketCache; allParams.forEach(function (prop) { var aQp = queryParams.map[prop]; aQp.values = params; var cacheKey = _emberRoutingUtils.calculateCacheKey(aQp.prefix, aQp.parts, aQp.values); if (cache) { var value = cache.lookup(cacheKey, prop, aQp.undecoratedDefaultValue); _emberMetalProperty_set.set(controller, prop, value); } }); })(); } controller._qpDelegate = states.allowOverrides; if (transition) { var qpValues = getQueryParamsFor(this, transition.state); controller.setProperties(qpValues); } this.setupController(controller, context, transition); if (!this._environment || this._environment.options.shouldRender) { this.renderTemplate(controller, context); } }, /* Called when a query parameter for this route changes, regardless of whether the route is currently part of the active route hierarchy. This will update the query parameter's value in the cache so if this route becomes active, the cache value has been updated. */ _qpChanged: function (prop, value, qp) { if (!qp) { return; } var cacheKey = _emberRoutingUtils.calculateCacheKey(qp.prefix || '', qp.parts, qp.values); // Update model-dep cache var cache = this._bucketCache; if (cache) { cache.stash(cacheKey, prop, value); } }, /** This hook is the first of the route entry validation hooks called when an attempt is made to transition into a route or one of its children. It is called before `model` and `afterModel`, and is appropriate for cases when: 1) A decision can be made to redirect elsewhere without needing to resolve the model first. 2) Any async operations need to occur first before the model is attempted to be resolved. This hook is provided the current `transition` attempt as a parameter, which can be used to `.abort()` the transition, save it for a later `.retry()`, or retrieve values set on it from a previous hook. You can also just call `this.transitionTo` to another route to implicitly abort the `transition`. You can return a promise from this hook to pause the transition until the promise resolves (or rejects). This could be useful, for instance, for retrieving async code from the server that is required to enter a route. ```javascript App.PostRoute = Ember.Route.extend({ beforeModel: function(transition) { if (!App.Post) { return Ember.$.getScript('/models/post.js'); } } }); ``` If `App.Post` doesn't exist in the above example, `beforeModel` will use jQuery's `getScript`, which returns a promise that resolves after the server has successfully retrieved and executed the code from the server. Note that if an error were to occur, it would be passed to the `error` hook on `Ember.Route`, but it's also possible to handle errors specific to `beforeModel` right from within the hook (to distinguish from the shared error handling behavior of the `error` hook): ```javascript App.PostRoute = Ember.Route.extend({ beforeModel: function(transition) { if (!App.Post) { let self = this; return Ember.$.getScript('post.js').then(null, function(e) { self.transitionTo('help'); // Note that the above transitionTo will implicitly // halt the transition. If you were to return // nothing from this promise reject handler, // according to promise semantics, that would // convert the reject into a resolve and the // transition would continue. To propagate the // error so that it'd be handled by the `error` // hook, you would have to return Ember.RSVP.reject(e); }); } } }); ``` @method beforeModel @param {Transition} transition @return {Promise} if the value returned from this hook is a promise, the transition will pause until the transition resolves. Otherwise, non-promise return values are not utilized in any way. @public */ beforeModel: K, /** This hook is called after this route's model has resolved. It follows identical async/promise semantics to `beforeModel` but is provided the route's resolved model in addition to the `transition`, and is therefore suited to performing logic that can only take place after the model has already resolved. ```javascript App.PostsRoute = Ember.Route.extend({ afterModel: function(posts, transition) { if (posts.get('length') === 1) { this.transitionTo('post.show', posts.get('firstObject')); } } }); ``` Refer to documentation for `beforeModel` for a description of transition-pausing semantics when a promise is returned from this hook. @method afterModel @param {Object} resolvedModel the value returned from `model`, or its resolved value if it was a promise @param {Transition} transition @return {Promise} if the value returned from this hook is a promise, the transition will pause until the transition resolves. Otherwise, non-promise return values are not utilized in any way. @public */ afterModel: K, /** A hook you can implement to optionally redirect to another route. If you call `this.transitionTo` from inside of this hook, this route will not be entered in favor of the other hook. `redirect` and `afterModel` behave very similarly and are called almost at the same time, but they have an important distinction in the case that, from one of these hooks, a redirect into a child route of this route occurs: redirects from `afterModel` essentially invalidate the current attempt to enter this route, and will result in this route's `beforeModel`, `model`, and `afterModel` hooks being fired again within the new, redirecting transition. Redirects that occur within the `redirect` hook, on the other hand, will _not_ cause these hooks to be fired again the second time around; in other words, by the time the `redirect` hook has been called, both the resolved model and attempted entry into this route are considered to be fully validated. @method redirect @param {Object} model the model for this route @param {Transition} transition the transition object associated with the current transition @public */ redirect: K, /** Called when the context is changed by router.js. @private @method contextDidChange */ contextDidChange: function () { this.currentModel = this.context; }, /** A hook you can implement to convert the URL into the model for this route. ```javascript App.Router.map(function() { this.route('post', { path: '/posts/:post_id' }); }); ``` The model for the `post` route is `store.findRecord('post', params.post_id)`. By default, if your route has a dynamic segment ending in `_id`: * The model class is determined from the segment (`post_id`'s class is `App.Post`) * The find method is called on the model class with the value of the dynamic segment. Note that for routes with dynamic segments, this hook is not always executed. If the route is entered through a transition (e.g. when using the `link-to` Handlebars helper or the `transitionTo` method of routes), and a model context is already provided this hook is not called. A model context does not include a primitive string or number, which does cause the model hook to be called. Routes without dynamic segments will always execute the model hook. ```javascript // no dynamic segment, model hook always called this.transitionTo('posts'); // model passed in, so model hook not called thePost = store.findRecord('post', 1); this.transitionTo('post', thePost); // integer passed in, model hook is called this.transitionTo('post', 1); // model id passed in, model hook is called // useful for forcing the hook to execute thePost = store.findRecord('post', 1); this.transitionTo('post', thePost.id); ``` This hook follows the asynchronous/promise semantics described in the documentation for `beforeModel`. In particular, if a promise returned from `model` fails, the error will be handled by the `error` hook on `Ember.Route`. Example ```javascript App.PostRoute = Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id); } }); ``` @method model @param {Object} params the parameters extracted from the URL @param {Transition} transition @return {Object|Promise} the model for this route. If a promise is returned, the transition will pause until the promise resolves, and the resolved value of the promise will be used as the model for this route. @public */ model: function (params, transition) { var match = undefined, name = undefined, sawParams = undefined, value = undefined; var queryParams = _emberMetalProperty_get.get(this, '_qp.map'); for (var prop in params) { if (prop === 'queryParams' || queryParams && prop in queryParams) { continue; } if (match = prop.match(/^(.*)_id$/)) { name = match[1]; value = params[prop]; } sawParams = true; } if (!name && sawParams) { return _emberRuntimeCopy.default(params); } else if (!name) { if (transition.resolveIndex < 1) { return; } var parentModel = transition.state.handlerInfos[transition.resolveIndex - 1].context; return parentModel; } return this.findModel(name, value); }, /** @private @method deserialize @param {Object} params the parameters extracted from the URL @param {Transition} transition @return {Object|Promise} the model for this route. Router.js hook. */ deserialize: function (params, transition) { return this.model(this.paramsFor(this.routeName), transition); }, /** @method findModel @param {String} type the model type @param {Object} value the value passed to find @private */ findModel: function () { var store = _emberMetalProperty_get.get(this, 'store'); return store.find.apply(store, arguments); }, /** Store property provides a hook for data persistence libraries to inject themselves. By default, this store property provides the exact same functionality previously in the model hook. Currently, the required interface is: `store.find(modelName, findArguments)` @method store @param {Object} store @private */ store: _emberMetalComputed.computed(function () { var owner = _containerOwner.getOwner(this); var routeName = this.routeName; var namespace = _emberMetalProperty_get.get(this, 'router.namespace'); return { find: function (name, value) { var modelClass = owner._lookupFactory('model:' + name); _emberMetalDebug.assert('You used the dynamic segment ' + name + '_id in your route ' + routeName + ', but ' + namespace + '.' + _emberRuntimeSystemString.classify(name) + ' did not exist and you did not override your route\'s `model` hook.', !!modelClass); if (!modelClass) { return; } _emberMetalDebug.assert(_emberRuntimeSystemString.classify(name) + ' has no method `find`.', typeof modelClass.find === 'function'); return modelClass.find(value); } }; }), /** A hook you can implement to convert the route's model into parameters for the URL. ```javascript App.Router.map(function() { this.route('post', { path: '/posts/:post_id' }); }); App.PostRoute = Ember.Route.extend({ model: function(params) { // the server returns `{ id: 12 }` return Ember.$.getJSON('/posts/' + params.post_id); }, serialize: function(model) { // this will make the URL `/posts/12` return { post_id: model.id }; } }); ``` The default `serialize` method will insert the model's `id` into the route's dynamic segment (in this case, `:post_id`) if the segment contains '_id'. If the route has multiple dynamic segments or does not contain '_id', `serialize` will return `Ember.getProperties(model, params)` This method is called when `transitionTo` is called with a context in order to populate the URL. @method serialize @param {Object} model the routes model @param {Array} params an Array of parameter names for the current route (in the example, `['post_id']`. @return {Object} the serialized parameters @public */ serialize: defaultSerialize, /** A hook you can use to setup the controller for the current route. This method is called with the controller for the current route and the model supplied by the `model` hook. By default, the `setupController` hook sets the `model` property of the controller to the `model`. If you implement the `setupController` hook in your Route, it will prevent this default behavior. If you want to preserve that behavior when implementing your `setupController` function, make sure to call `_super`: ```javascript App.PhotosRoute = Ember.Route.extend({ model: function() { return this.store.findAll('photo'); }, setupController: function(controller, model) { // Call _super for default behavior this._super(controller, model); // Implement your custom setup after this.controllerFor('application').set('showingPhotos', true); } }); ``` The provided controller will be one resolved based on the name of this route. If no explicit controller is defined, Ember will automatically create one. As an example, consider the router: ```javascript App.Router.map(function() { this.route('post', { path: '/posts/:post_id' }); }); ``` For the `post` route, a controller named `App.PostController` would be used if it is defined. If it is not defined, a basic `Ember.Controller` instance would be used. Example ```javascript App.PostRoute = Ember.Route.extend({ setupController: function(controller, model) { controller.set('model', model); } }); ``` @method setupController @param {Controller} controller instance @param {Object} model @public */ setupController: function (controller, context, transition) { if (controller && context !== undefined) { _emberMetalProperty_set.set(controller, 'model', context); } }, /** Returns the controller for a particular route or name. The controller instance must already have been created, either through entering the associated route or using `generateController`. ```javascript App.PostRoute = Ember.Route.extend({ setupController: function(controller, post) { this._super(controller, post); this.controllerFor('posts').set('currentPost', post); } }); ``` @method controllerFor @param {String} name the name of the route or controller @return {Ember.Controller} @public */ controllerFor: function (name, _skipAssert) { var owner = _containerOwner.getOwner(this); var route = owner.lookup('route:' + name); var controller = undefined; if (route && route.controllerName) { name = route.controllerName; } controller = owner.lookup('controller:' + name); // NOTE: We're specifically checking that skipAssert is true, because according // to the old API the second parameter was model. We do not want people who // passed a model to skip the assertion. _emberMetalDebug.assert('The controller named \'' + name + '\' could not be found. Make sure that this route exists and has already been entered at least once. If you are accessing a controller not associated with a route, make sure the controller class is explicitly defined.', controller || _skipAssert === true); return controller; }, /** Generates a controller for a route. Example ```javascript App.PostRoute = Ember.Route.extend({ setupController: function(controller, post) { this._super(controller, post); this.generateController('posts', post); } }); ``` @method generateController @param {String} name the name of the controller @param {Object} model the model to infer the type of the controller (optional) @private */ generateController: function (name, model) { var owner = _containerOwner.getOwner(this); model = model || this.modelFor(name); return _emberRoutingSystemGenerate_controller.default(owner, name, model); }, /** Returns the resolved model of a parent (or any ancestor) route in a route hierarchy. During a transition, all routes must resolve a model object, and if a route needs access to a parent route's model in order to resolve a model (or just reuse the model from a parent), it can call `this.modelFor(theNameOfParentRoute)` to retrieve it. If the ancestor route's model was a promise, its resolved result is returned. Example ```javascript App.Router.map(function() { this.route('post', { path: '/post/:post_id' }, function() { this.route('comments', { resetNamespace: true }); }); }); App.CommentsRoute = Ember.Route.extend({ afterModel: function() { this.set('post', this.modelFor('post')); } }); ``` @method modelFor @param {String} name the name of the route @return {Object} the model object @public */ modelFor: function (name) { var route = _containerOwner.getOwner(this).lookup('route:' + name); var transition = this.router ? this.router.router.activeTransition : null; // If we are mid-transition, we want to try and look up // resolved parent contexts on the current transitionEvent. if (transition) { var modelLookupName = route && route.routeName || name; if (transition.resolvedModels.hasOwnProperty(modelLookupName)) { return transition.resolvedModels[modelLookupName]; } } return route && route.currentModel; }, /** A hook you can use to render the template for the current route. This method is called with the controller for the current route and the model supplied by the `model` hook. By default, it renders the route's template, configured with the controller for the route. This method can be overridden to set up and render additional or alternative templates. ```javascript App.PostsRoute = Ember.Route.extend({ renderTemplate: function(controller, model) { let favController = this.controllerFor('favoritePost'); // Render the `favoritePost` template into // the outlet `posts`, and display the `favoritePost` // controller. this.render('favoritePost', { outlet: 'posts', controller: favController }); } }); ``` @method renderTemplate @param {Object} controller the route's controller @param {Object} model the route's model @public */ renderTemplate: function (controller, model) { this.render(); }, /** `render` is used to render a template into a region of another template (indicated by an `{{outlet}}`). `render` is used both during the entry phase of routing (via the `renderTemplate` hook) and later in response to user interaction. For example, given the following minimal router and templates: ```javascript Router.map(function() { this.route('photos'); }); ``` ```handlebars <!-- application.hbs --> <div class='something-in-the-app-hbs'> {{outlet "anOutletName"}} </div> ``` ```handlebars <!-- photos.hbs --> <h1>Photos</h1> ``` You can render `photos.hbs` into the `"anOutletName"` outlet of `application.hbs` by calling `render`: ```javascript // posts route Ember.Route.extend({ renderTemplate: function() { this.render('photos', { into: 'application', outlet: 'anOutletName' }) } }); ``` `render` additionally allows you to supply which `controller` and `model` objects should be loaded and associated with the rendered template. ```javascript // posts route Ember.Route.extend({ renderTemplate: function(controller, model){ this.render('posts', { // the template to render, referenced by name into: 'application', // the template to render into, referenced by name outlet: 'anOutletName', // the outlet inside `options.template` to render into. controller: 'someControllerName', // the controller to use for this template, referenced by name model: model // the model to set on `options.controller`. }) } }); ``` The string values provided for the template name, and controller will eventually pass through to the resolver for lookup. See Ember.Resolver for how these are mapped to JavaScript objects in your application. The template to render into needs to be related to either the current route or one of its ancestors. Not all options need to be passed to `render`. Default values will be used based on the name of the route specified in the router or the Route's `controllerName` and `templateName` properties. For example: ```javascript // router Router.map(function() { this.route('index'); this.route('post', { path: '/posts/:post_id' }); }); ``` ```javascript // post route PostRoute = App.Route.extend({ renderTemplate: function() { this.render(); // all defaults apply } }); ``` The name of the `PostRoute`, defined by the router, is `post`. The following equivalent default options will be applied when the Route calls `render`: ```javascript // this.render('post', { // the template name associated with 'post' Route into: 'application', // the parent route to 'post' Route outlet: 'main', // {{outlet}} and {{outlet 'main'}} are synonymous, controller: 'post', // the controller associated with the 'post' Route }) ``` By default the controller's `model` will be the route's model, so it does not need to be passed unless you wish to change which model is being used. @method render @param {String} name the name of the template to render @param {Object} [options] the options @param {String} [options.into] the template to render into, referenced by name. Defaults to the parent template @param {String} [options.outlet] the outlet inside `options.template` to render into. Defaults to 'main' @param {String|Object} [options.controller] the controller to use for this template, referenced by name or as a controller instance. Defaults to the Route's paired controller @param {Object} [options.model] the model object to set on `options.controller`. Defaults to the return value of the Route's model hook @public */ render: function (_name, options) { _emberMetalDebug.assert('The name in the given arguments is undefined', arguments.length > 0 ? !_emberMetalIs_none.default(arguments[0]) : true); var namePassed = typeof _name === 'string' && !!_name; var isDefaultRender = arguments.length === 0 || _emberMetalIs_empty.default(arguments[0]); var name = undefined; if (typeof _name === 'object' && !options) { name = this.routeName; options = _name; } else { name = _name; } var renderOptions = buildRenderOptions(this, namePassed, isDefaultRender, name, options); this.connections.push(renderOptions); _emberMetalRun_loop.default.once(this.router, '_setOutlets'); }, /** Disconnects a view that has been rendered into an outlet. You may pass any or all of the following options to `disconnectOutlet`: * `outlet`: the name of the outlet to clear (default: 'main') * `parentView`: the name of the view containing the outlet to clear (default: the view rendered by the parent route) Example: ```javascript App.ApplicationRoute = App.Route.extend({ actions: { showModal: function(evt) { this.render(evt.modalName, { outlet: 'modal', into: 'application' }); }, hideModal: function(evt) { this.disconnectOutlet({ outlet: 'modal', parentView: 'application' }); } } }); ``` Alternatively, you can pass the `outlet` name directly as a string. Example: ```javascript hideModal: function(evt) { this.disconnectOutlet('modal'); } ``` @method disconnectOutlet @param {Object|String} options the options hash or outlet name @public */ disconnectOutlet: function (options) { var outletName = undefined; var parentView = undefined; if (!options || typeof options === 'string') { outletName = options; } else { outletName = options.outlet; parentView = options.parentView; if (options && Object.keys(options).indexOf('outlet') !== -1 && typeof options.outlet === 'undefined') { throw new _emberMetalError.default('You passed undefined as the outlet name.'); } } parentView = parentView && parentView.replace(/\//g, '.'); outletName = outletName || 'main'; this._disconnectOutlet(outletName, parentView); for (var i = 0; i < this.router.router.currentHandlerInfos.length; i++) { // This non-local state munging is sadly necessary to maintain // backward compatibility with our existing semantics, which allow // any route to disconnectOutlet things originally rendered by any // other route. This should all get cut in 2.0. this.router.router.currentHandlerInfos[i].handler._disconnectOutlet(outletName, parentView); } }, _disconnectOutlet: function (outletName, parentView) { var parent = parentRoute(this); if (parent && parentView === parent.routeName) { parentView = undefined; } for (var i = 0; i < this.connections.length; i++) { var connection = this.connections[i]; if (connection.outlet === outletName && connection.into === parentView) { // This neuters the disconnected outlet such that it doesn't // render anything, but it leaves an entry in the outlet // hierarchy so that any existing other renders that target it // don't suddenly blow up. They will still stick themselves // into its outlets, which won't render anywhere. All of this // statefulness should get the machete in 2.0. this.connections[i] = { owner: connection.owner, into: connection.into, outlet: connection.outlet, name: connection.name, controller: undefined, template: undefined, ViewClass: undefined }; _emberMetalRun_loop.default.once(this.router, '_setOutlets'); } } }, willDestroy: function () { this.teardownViews(); }, /** @private @method teardownViews */ teardownViews: function () { if (this.connections && this.connections.length > 0) { this.connections = []; _emberMetalRun_loop.default.once(this.router, '_setOutlets'); } } }); _emberRuntimeMixinsAction_handler.deprecateUnderscoreActions(Route); Route.reopenClass({ isRouteFactory: true }); function parentRoute(route) { var handlerInfo = handlerInfoFor(route, route.router.router.state.handlerInfos, -1); return handlerInfo && handlerInfo.handler; } function handlerInfoFor(route, handlerInfos, _offset) { if (!handlerInfos) { return; } var offset = _offset || 0; var current = undefined; for (var i = 0; i < handlerInfos.length; i++) { current = handlerInfos[i].handler; if (current === route) { return handlerInfos[i + offset]; } } } function buildRenderOptions(route, namePassed, isDefaultRender, _name, options) { var into = options && options.into && options.into.replace(/\//g, '.'); var outlet = options && options.outlet || 'main'; var name = undefined, templateName = undefined; if (_name) { name = _name.replace(/\//g, '.'); templateName = name; } else { name = route.routeName; templateName = route.templateName || name; } var owner = _containerOwner.getOwner(route); var controller = options && options.controller; if (!controller) { if (namePassed) { controller = owner.lookup('controller:' + name) || route.controllerName || route.routeName; } else { controller = route.controllerName || owner.lookup('controller:' + name); } } if (typeof controller === 'string') { var controllerName = controller; controller = owner.lookup('controller:' + controllerName); if (!controller) { throw new _emberMetalError.default('You passed `controller: \'' + controllerName + '\'` into the `render` method, but no such controller could be found.'); } } if (options && Object.keys(options).indexOf('outlet') !== -1 && typeof options.outlet === 'undefined') { throw new _emberMetalError.default('You passed undefined as the outlet name.'); } if (options && options.model) { controller.set('model', options.model); } var template = owner.lookup('template:' + templateName); var parent = undefined; if (into && (parent = parentRoute(route)) && into === parentRoute(route).routeName) { into = undefined; } var renderOptions = { owner: owner, into: into, outlet: outlet, name: name, controller: controller, template: template || route._topLevelViewTemplate, ViewClass: undefined }; _emberMetalDebug.assert('Could not find "' + name + '" template, view, or component.', isDefaultRender || template); var LOG_VIEW_LOOKUPS = _emberMetalProperty_get.get(route.router, 'namespace.LOG_VIEW_LOOKUPS'); if (LOG_VIEW_LOOKUPS && !template) { _emberMetalDebug.info('Could not find "' + name + '" template. Nothing will be rendered', { fullName: 'template:' + name }); } return renderOptions; } function getFullQueryParams(router, state) { if (state.fullQueryParams) { return state.fullQueryParams; } state.fullQueryParams = {}; _emberMetalAssign.default(state.fullQueryParams, state.queryParams); var targetRouteName = state.handlerInfos[state.handlerInfos.length - 1].name; router._deserializeQueryParams(targetRouteName, state.fullQueryParams); return state.fullQueryParams; } function getQueryParamsFor(route, state) { state.queryParamsFor = state.queryParamsFor || {}; var name = route.routeName; if (true) { name = getEngineRouteName(_containerOwner.getOwner(route), name); } if (state.queryParamsFor[name]) { return state.queryParamsFor[name]; } var fullQueryParams = getFullQueryParams(route.router, state); var params = state.queryParamsFor[name] = {}; // Copy over all the query params for this route/controller into params hash. var qpMeta = _emberMetalProperty_get.get(route, '_qp'); var qps = qpMeta.qps; for (var i = 0; i < qps.length; ++i) { // Put deserialized qp on params hash. var qp = qps[i]; var qpValueWasPassedIn = (qp.prop in fullQueryParams); params[qp.prop] = qpValueWasPassedIn ? fullQueryParams[qp.prop] : copyDefaultValue(qp.defaultValue); } return params; } function copyDefaultValue(value) { if (Array.isArray(value)) { return _emberRuntimeSystemNative_array.A(value.slice()); } return value; } /* Merges all query parameters from a controller with those from a route, returning a new object and avoiding any mutations to the existing objects. */ function mergeEachQueryParams(controllerQP, routeQP) { var keysAlreadyMergedOrSkippable = undefined; var qps = {}; if (false) { keysAlreadyMergedOrSkippable = {}; } else { keysAlreadyMergedOrSkippable = { defaultValue: true, type: true, scope: true, as: true }; } // first loop over all controller qps, merging them with any matching route qps // into a new empty object to avoid mutating. for (var cqpName in controllerQP) { if (!controllerQP.hasOwnProperty(cqpName)) { continue; } var newControllerParameterConfiguration = {}; _emberMetalAssign.default(newControllerParameterConfiguration, controllerQP[cqpName]); _emberMetalAssign.default(newControllerParameterConfiguration, routeQP[cqpName]); qps[cqpName] = newControllerParameterConfiguration; // allows us to skip this QP when we check route QPs. keysAlreadyMergedOrSkippable[cqpName] = true; } // loop over all route qps, skipping those that were merged in the first pass // because they also appear in controller qps for (var rqpName in routeQP) { if (!routeQP.hasOwnProperty(rqpName) || keysAlreadyMergedOrSkippable[rqpName]) { continue; } var newRouteParameterConfiguration = {}; _emberMetalAssign.default(newRouteParameterConfiguration, routeQP[rqpName], controllerQP[rqpName]); qps[rqpName] = newRouteParameterConfiguration; } return qps; } function addQueryParamsObservers(controller, propNames) { propNames.forEach(function (prop) { controller.addObserver(prop + '.[]', controller, controller._qpChanged); }); } function deprecateQueryParamDefaultValuesSetOnController(controllerName, routeName, propName) { _emberMetalDebug.deprecate('Configuring query parameter default values on controllers is deprecated. Please move the value for the property \'' + propName + '\' from the \'' + controllerName + '\' controller to the \'' + routeName + '\' route in the format: {queryParams: ' + propName + ': {defaultValue: <default value> }}', false, { id: 'ember-routing.deprecate-query-param-default-values-set-on-controller', until: '3.0.0' }); } /* Returns an arguments array where the route name arg is prefixed based on the mount point @private */ function prefixRouteNameArg(route, args) { var routeName = args[0]; var owner = _containerOwner.getOwner(route); var prefix = owner.mountPoint; // only alter the routeName if it's actually referencing a route. if (owner.routable && typeof routeName === 'string') { if (resemblesURL(routeName)) { throw new _emberMetalError.default('Route#transitionTo cannot be used for URLs. Please use the route name instead.'); } else { routeName = prefix + '.' + routeName; args[0] = routeName; } } return args; } /* Check if a routeName resembles a url instead @private */ function resemblesURL(str) { return typeof str === 'string' && (str === '' || str.charAt(0) === '/'); } if (true) { Route.reopen({ replaceWith: function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return this._super.apply(this, prefixRouteNameArg(this, args)); }, transitionTo: function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return this._super.apply(this, prefixRouteNameArg(this, args)); }, modelFor: function (_routeName) { var routeName = undefined; var owner = _containerOwner.getOwner(this); if (owner.routable && this.router && this.router.router.activeTransition) { // only change the routeName when there is an active transition. // otherwise, we need the passed in route name. routeName = getEngineRouteName(owner, _routeName); } else { routeName = _routeName; } for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { args[_key4 - 1] = arguments[_key4]; } return this._super.apply(this, [routeName].concat(args)); } }); } function getEngineRouteName(engine, routeName) { if (engine.routable) { var prefix = engine.mountPoint; if (routeName === 'application') { return prefix; } else { return prefix + '.' + routeName; } } return routeName; } exports.default = Route; }); enifed('ember-routing/system/router', ['exports', 'ember-console', 'ember-metal/debug', 'ember-metal/error', 'ember-metal/features', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/properties', 'ember-metal/empty_object', 'ember-metal/computed', 'ember-metal/assign', 'ember-metal/run_loop', 'ember-runtime/system/object', 'ember-runtime/mixins/evented', 'ember-routing/system/route', 'ember-routing/system/dsl', 'ember-routing/location/api', 'ember-routing/utils', 'ember-metal/utils', 'ember-routing/system/router_state', 'container/owner', 'ember-metal/dictionary', 'router', 'router/transition'], function (exports, _emberConsole, _emberMetalDebug, _emberMetalError, _emberMetalFeatures, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalProperties, _emberMetalEmpty_object, _emberMetalComputed, _emberMetalAssign, _emberMetalRun_loop, _emberRuntimeSystemObject, _emberRuntimeMixinsEvented, _emberRoutingSystemRoute, _emberRoutingSystemDsl, _emberRoutingLocationApi, _emberRoutingUtils, _emberMetalUtils, _emberRoutingSystemRouter_state, _containerOwner, _emberMetalDictionary, _router4, _routerTransition) { 'use strict'; exports.triggerEvent = triggerEvent; function K() { return this; } var slice = Array.prototype.slice; /** The `Ember.Router` class manages the application state and URLs. Refer to the [routing guide](http://emberjs.com/guides/routing/) for documentation. @class Router @namespace Ember @extends Ember.Object @uses Ember.Evented @public */ var EmberRouter = _emberRuntimeSystemObject.default.extend(_emberRuntimeMixinsEvented.default, { /** The `location` property determines the type of URL's that your application will use. The following location types are currently available: * `history` - use the browser's history API to make the URLs look just like any standard URL * `hash` - use `#` to separate the server part of the URL from the Ember part: `/blog/#/posts/new` * `none` - do not store the Ember URL in the actual browser URL (mainly used for testing) * `auto` - use the best option based on browser capabilites: `history` if possible, then `hash` if possible, otherwise `none` Note: If using ember-cli, this value is defaulted to `auto` by the `locationType` setting of `/config/environment.js` @property location @default 'hash' @see {Ember.Location} @public */ location: 'hash', /** Represents the URL of the root of the application, often '/'. This prefix is assumed on all routes defined on this router. @property rootURL @default '/' @public */ rootURL: '/', _initRouterJs: function () { var router = this.router = new _router4.default(); router.triggerEvent = triggerEvent; router._triggerWillChangeContext = K; router._triggerWillLeave = K; var dslCallbacks = this.constructor.dslCallbacks || [K]; var dsl = this._buildDSL(); dsl.route('application', { path: '/', resetNamespace: true, overrideNameAssertion: true }, function () { for (var i = 0; i < dslCallbacks.length; i++) { dslCallbacks[i].call(this); } }); if (_emberMetalProperty_get.get(this, 'namespace.LOG_TRANSITIONS_INTERNAL')) { router.log = _emberConsole.default.debug; } router.map(dsl.generate()); }, _buildDSL: function () { var _this = this; var moduleBasedResolver = this._hasModuleBasedResolver(); var options = { enableLoadingSubstates: !!moduleBasedResolver }; if (true) { (function () { var owner = _containerOwner.getOwner(_this); var router = _this; options.enableLoadingSubstates = !!moduleBasedResolver; options.resolveRouteMap = function (name) { return owner._lookupFactory('route-map:' + name); }; options.addRouteForEngine = function (name, engineInfo) { if (!router._engineInfoByRoute[name]) { router._engineInfoByRoute[name] = engineInfo; } }; })(); } return new _emberRoutingSystemDsl.default(null, options); }, init: function () { this._super.apply(this, arguments); this._activeViews = {}; this._qpCache = new _emberMetalEmpty_object.default(); this._resetQueuedQueryParameterChanges(); this._handledErrors = _emberMetalDictionary.default(null); if (true) { this._engineInstances = new _emberMetalEmpty_object.default(); this._engineInfoByRoute = new _emberMetalEmpty_object.default(); } // avoid shaping issues with checks during `_setOutlets` this.isDestroyed = false; this.isDestroying = false; }, /* Resets all pending query paramter changes. Called after transitioning to a new route based on query parameter changes. */ _resetQueuedQueryParameterChanges: function () { this._queuedQPChanges = {}; }, /** Represents the current URL. @method url @return {String} The current URL. @private */ url: _emberMetalComputed.computed(function () { return _emberMetalProperty_get.get(this, 'location').getURL(); }), _hasModuleBasedResolver: function () { var owner = _containerOwner.getOwner(this); if (!owner) { return false; } var resolver = owner.application && owner.application.__registry__ && owner.application.__registry__.resolver; if (!resolver) { return false; } return !!resolver.moduleBasedResolver; }, /** Initializes the current router instance and sets up the change handling event listeners used by the instances `location` implementation. A property named `initialURL` will be used to determine the initial URL. If no value is found `/` will be used. @method startRouting @private */ startRouting: function () { var initialURL = _emberMetalProperty_get.get(this, 'initialURL'); if (this.setupRouter()) { if (typeof initialURL === 'undefined') { initialURL = _emberMetalProperty_get.get(this, 'location').getURL(); } var initialTransition = this.handleURL(initialURL); if (initialTransition && initialTransition.error) { throw initialTransition.error; } } }, setupRouter: function () { var _this2 = this; this._initRouterJs(); this._setupLocation(); var router = this.router; var location = _emberMetalProperty_get.get(this, 'location'); // Allow the Location class to cancel the router setup while it refreshes // the page if (_emberMetalProperty_get.get(location, 'cancelRouterSetup')) { return false; } this._setupRouter(router, location); location.onUpdateURL(function (url) { _this2.handleURL(url); }); return true; }, /** Handles updating the paths and notifying any listeners of the URL change. Triggers the router level `didTransition` hook. For example, to notify google analytics when the route changes, you could use this hook. (Note: requires also including GA scripts, etc.) ```javascript let Router = Ember.Router.extend({ location: config.locationType, didTransition: function() { this._super(...arguments); return ga('send', 'pageview', { 'page': this.get('url'), 'title': this.get('url') }); } }); ``` @method didTransition @public @since 1.2.0 */ didTransition: function (infos) { updatePaths(this); this._cancelSlowTransitionTimer(); this.notifyPropertyChange('url'); this.set('currentState', this.targetState); // Put this in the runloop so url will be accurate. Seems // less surprising than didTransition being out of sync. _emberMetalRun_loop.default.once(this, this.trigger, 'didTransition'); if (_emberMetalProperty_get.get(this, 'namespace').LOG_TRANSITIONS) { _emberConsole.default.log('Transitioned into \'' + EmberRouter._routePath(infos) + '\''); } }, _setOutlets: function () { // This is triggered async during Ember.Route#willDestroy. // If the router is also being destroyed we do not want to // to create another this._toplevelView (and leak the renderer) if (this.isDestroying || this.isDestroyed) { return; } var handlerInfos = this.router.currentHandlerInfos; var route = undefined; var defaultParentState = undefined; var liveRoutes = null; if (!handlerInfos) { return; } for (var i = 0; i < handlerInfos.length; i++) { route = handlerInfos[i].handler; var connections = route.connections; var ownState = undefined; for (var j = 0; j < connections.length; j++) { var appended = appendLiveRoute(liveRoutes, defaultParentState, connections[j]); liveRoutes = appended.liveRoutes; if (appended.ownState.render.name === route.routeName || appended.ownState.render.outlet === 'main') { ownState = appended.ownState; } } if (connections.length === 0) { ownState = representEmptyRoute(liveRoutes, defaultParentState, route); } defaultParentState = ownState; } if (!this._toplevelView) { var owner = _containerOwner.getOwner(this); var OutletView = owner._lookupFactory('view:-outlet'); this._toplevelView = OutletView.create(); this._toplevelView.setOutletState(liveRoutes); var instance = owner.lookup('-application-instance:main'); instance.didCreateRootView(this._toplevelView); } else { this._toplevelView.setOutletState(liveRoutes); } }, /** Handles notifying any listeners of an impending URL change. Triggers the router level `willTransition` hook. @method willTransition @public @since 1.11.0 */ willTransition: function (oldInfos, newInfos, transition) { _emberMetalRun_loop.default.once(this, this.trigger, 'willTransition', transition); if (_emberMetalProperty_get.get(this, 'namespace').LOG_TRANSITIONS) { _emberConsole.default.log('Preparing to transition from \'' + EmberRouter._routePath(oldInfos) + '\' to \'' + EmberRouter._routePath(newInfos) + '\''); } }, handleURL: function (url) { // Until we have an ember-idiomatic way of accessing #hashes, we need to // remove it because router.js doesn't know how to handle it. url = url.split(/#(.+)?/)[0]; return this._doURLTransition('handleURL', url); }, _doURLTransition: function (routerJsMethod, url) { var transition = this.router[routerJsMethod](url || '/'); didBeginTransition(transition, this); return transition; }, /** Transition the application into another route. The route may be either a single route or route path: See [Route.transitionTo](http://emberjs.com/api/classes/Ember.Route.html#method_transitionTo) for more info. @method transitionTo @param {String} name the name of the route or a URL @param {...Object} models the model(s) or identifier(s) to be used while transitioning to the route. @param {Object} [options] optional hash with a queryParams property containing a mapping of query parameters @return {Transition} the transition object associated with this attempted transition @public */ transitionTo: function () { var queryParams = undefined; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (resemblesURL(args[0])) { return this._doURLTransition('transitionTo', args[0]); } var possibleQueryParams = args[args.length - 1]; if (possibleQueryParams && possibleQueryParams.hasOwnProperty('queryParams')) { queryParams = args.pop().queryParams; } else { queryParams = {}; } var targetRouteName = args.shift(); return this._doTransition(targetRouteName, args, queryParams); }, intermediateTransitionTo: function () { var _router; (_router = this.router).intermediateTransitionTo.apply(_router, arguments); updatePaths(this); var infos = this.router.currentHandlerInfos; if (_emberMetalProperty_get.get(this, 'namespace').LOG_TRANSITIONS) { _emberConsole.default.log('Intermediate-transitioned into \'' + EmberRouter._routePath(infos) + '\''); } }, replaceWith: function () { return this.transitionTo.apply(this, arguments).method('replace'); }, generate: function () { var _router2; var url = (_router2 = this.router).generate.apply(_router2, arguments); return this.location.formatURL(url); }, /** Determines if the supplied route is currently active. @method isActive @param routeName @return {Boolean} @private */ isActive: function (routeName) { var router = this.router; return router.isActive.apply(router, arguments); }, /** An alternative form of `isActive` that doesn't require manual concatenation of the arguments into a single array. @method isActiveIntent @param routeName @param models @param queryParams @return {Boolean} @private @since 1.7.0 */ isActiveIntent: function (routeName, models, queryParams) { return this.currentState.isActiveIntent(routeName, models, queryParams); }, send: function (name, context) { var _router3; (_router3 = this.router).trigger.apply(_router3, arguments); }, /** Does this router instance have the given route. @method hasRoute @return {Boolean} @private */ hasRoute: function (route) { return this.router.hasRoute(route); }, /** Resets the state of the router by clearing the current route handlers and deactivating them. @private @method reset */ reset: function () { if (this.router) { this.router.reset(); } }, willDestroy: function () { if (true) { var instances = this._engineInstances; for (var _name in instances) { for (var id in instances[_name]) { _emberMetalRun_loop.default(instances[_name][id], 'destroy'); } } } if (this._toplevelView) { this._toplevelView.destroy(); this._toplevelView = null; } this._super.apply(this, arguments); this.reset(); }, _lookupActiveComponentNode: function (templateName) { return this._activeViews[templateName]; }, /* Called when an active route's query parameter has changed. These changes are batched into a runloop run and trigger a single transition. */ _activeQPChanged: function (queryParameterName, newValue) { this._queuedQPChanges[queryParameterName] = newValue; _emberMetalRun_loop.default.once(this, this._fireQueryParamTransition); }, _updatingQPChanged: function (queryParameterName) { if (!this._qpUpdates) { this._qpUpdates = {}; } this._qpUpdates[queryParameterName] = true; }, /* Triggers a transition to a route based on query parameter changes. This is called once per runloop, to batch changes. e.g. if these methods are called in succession: this._activeQPChanged('foo', '10'); // results in _queuedQPChanges = { foo: '10' } this._activeQPChanged('bar', false); // results in _queuedQPChanges = { foo: '10', bar: false } _queuedQPChanges will represent both of these changes and the transition using `transitionTo` will be triggered once. */ _fireQueryParamTransition: function () { this.transitionTo({ queryParams: this._queuedQPChanges }); this._resetQueuedQueryParameterChanges(); }, _connectActiveComponentNode: function (templateName, componentNode) { _emberMetalDebug.assert('cannot connect an activeView that already exists', !this._activeViews[templateName]); var _activeViews = this._activeViews; function disconnectActiveView() { delete _activeViews[templateName]; } this._activeViews[templateName] = componentNode; componentNode.renderNode.addDestruction({ destroy: disconnectActiveView }); }, _setupLocation: function () { var location = _emberMetalProperty_get.get(this, 'location'); var rootURL = _emberMetalProperty_get.get(this, 'rootURL'); var owner = _containerOwner.getOwner(this); if ('string' === typeof location && owner) { var resolvedLocation = owner.lookup('location:' + location); if ('undefined' !== typeof resolvedLocation) { location = _emberMetalProperty_set.set(this, 'location', resolvedLocation); } else { // Allow for deprecated registration of custom location API's var options = { implementation: location }; location = _emberMetalProperty_set.set(this, 'location', _emberRoutingLocationApi.default.create(options)); } } if (location !== null && typeof location === 'object') { if (rootURL) { _emberMetalProperty_set.set(location, 'rootURL', rootURL); } // Allow the location to do any feature detection, such as AutoLocation // detecting history support. This gives it a chance to set its // `cancelRouterSetup` property which aborts routing. if (typeof location.detect === 'function') { location.detect(); } // ensure that initState is called AFTER the rootURL is set on // the location instance if (typeof location.initState === 'function') { location.initState(); } } }, _getHandlerFunction: function () { var _this3 = this; var seen = new _emberMetalEmpty_object.default(); var owner = _containerOwner.getOwner(this); return function (name) { var routeName = name; var routeOwner = owner; var engineInfo = undefined; if (true) { engineInfo = _this3._engineInfoByRoute[routeName]; if (engineInfo) { var engineInstance = _this3._getEngineInstance(engineInfo); routeOwner = engineInstance; routeName = engineInfo.localFullName; } } var fullRouteName = 'route:' + routeName; var handler = routeOwner.lookup(fullRouteName); if (seen[name]) { return handler; } seen[name] = true; if (!handler) { var DefaultRoute = routeOwner._lookupFactory('route:basic'); routeOwner.register(fullRouteName, DefaultRoute.extend()); handler = routeOwner.lookup(fullRouteName); if (_emberMetalProperty_get.get(_this3, 'namespace.LOG_ACTIVE_GENERATION')) { _emberMetalDebug.info('generated -> ' + fullRouteName, { fullName: fullRouteName }); } } handler.routeName = routeName; if (engineInfo && !_emberRoutingSystemRoute.hasDefaultSerialize(handler)) { throw new Error('Defining a custom serialize method on an Engine route is not supported.'); } return handler; }; }, _getSerializerFunction: function () { var _this4 = this; return function (name) { var engineInfo = _this4._engineInfoByRoute[name]; // If this is not an Engine route, we fall back to the handler for serialization if (!engineInfo) { return; } return engineInfo.serializeMethod || _emberRoutingSystemRoute.defaultSerialize; }; }, _setupRouter: function (router, location) { var lastURL = undefined; var emberRouter = this; router.getHandler = this._getHandlerFunction(); if (true) { router.getSerializer = this._getSerializerFunction(); } var doUpdateURL = function () { location.setURL(lastURL); }; router.updateURL = function (path) { lastURL = path; _emberMetalRun_loop.default.once(doUpdateURL); }; if (location.replaceURL) { (function () { var doReplaceURL = function () { location.replaceURL(lastURL); }; router.replaceURL = function (path) { lastURL = path; _emberMetalRun_loop.default.once(doReplaceURL); }; })(); } router.didTransition = function (infos) { emberRouter.didTransition(infos); }; router.willTransition = function (oldInfos, newInfos, transition) { emberRouter.willTransition(oldInfos, newInfos, transition); }; }, _serializeQueryParams: function (targetRouteName, queryParams) { var groupedByUrlKey = {}; forEachQueryParam(this, targetRouteName, queryParams, function (key, value, qp) { var urlKey = qp.urlKey; if (!groupedByUrlKey[urlKey]) { groupedByUrlKey[urlKey] = []; } groupedByUrlKey[urlKey].push({ qp: qp, value: value }); delete queryParams[key]; }); for (var key in groupedByUrlKey) { var qps = groupedByUrlKey[key]; _emberMetalDebug.assert('You\'re not allowed to have more than one controller property map to the same query param key, but both `' + qps[0].qp.scopedPropertyName + '` and `' + (qps[1] ? qps[1].qp.scopedPropertyName : '') + '` map to `' + qps[0].qp.urlKey + '`. You can fix this by mapping one of the controller properties to a different query param key via the `as` config option, e.g. `' + qps[0].qp.prop + ': { as: \'other-' + qps[0].qp.prop + '\' }`', qps.length <= 1); var qp = qps[0].qp; queryParams[qp.urlKey] = qp.route.serializeQueryParam(qps[0].value, qp.urlKey, qp.type); } }, _deserializeQueryParams: function (targetRouteName, queryParams) { forEachQueryParam(this, targetRouteName, queryParams, function (key, value, qp) { delete queryParams[key]; queryParams[qp.prop] = qp.route.deserializeQueryParam(value, qp.urlKey, qp.type); }); }, _pruneDefaultQueryParamValues: function (targetRouteName, queryParams) { var qps = this._queryParamsFor(targetRouteName); for (var key in queryParams) { var qp = qps.map[key]; if (qp && qp.serializedDefaultValue === queryParams[key]) { delete queryParams[key]; } } }, _doTransition: function (_targetRouteName, models, _queryParams) { var targetRouteName = _targetRouteName || _emberRoutingUtils.getActiveTargetName(this.router); _emberMetalDebug.assert('The route ' + targetRouteName + ' was not found', targetRouteName && this.router.hasRoute(targetRouteName)); var queryParams = {}; this._processActiveTransitionQueryParams(targetRouteName, models, queryParams, _queryParams); _emberMetalAssign.default(queryParams, _queryParams); this._prepareQueryParams(targetRouteName, models, queryParams); var transitionArgs = _emberRoutingUtils.routeArgs(targetRouteName, models, queryParams); var transition = this.router.transitionTo.apply(this.router, transitionArgs); didBeginTransition(transition, this); return transition; }, _processActiveTransitionQueryParams: function (targetRouteName, models, queryParams, _queryParams) { // merge in any queryParams from the active transition which could include // queryParams from the url on initial load. if (!this.router.activeTransition) { return; } var unchangedQPs = {}; var qpUpdates = this._qpUpdates || {}; for (var key in this.router.activeTransition.queryParams) { if (!qpUpdates[key]) { unchangedQPs[key] = this.router.activeTransition.queryParams[key]; } } // We need to fully scope queryParams so that we can create one object // that represents both pased in queryParams and ones that aren't changed // from the active transition. this._fullyScopeQueryParams(targetRouteName, models, _queryParams); this._fullyScopeQueryParams(targetRouteName, models, unchangedQPs); _emberMetalAssign.default(queryParams, unchangedQPs); }, _prepareQueryParams: function (targetRouteName, models, queryParams) { this._hydrateUnsuppliedQueryParams(targetRouteName, models, queryParams); this._serializeQueryParams(targetRouteName, queryParams); this._pruneDefaultQueryParamValues(targetRouteName, queryParams); }, /** Returns a merged query params meta object for a given route. Useful for asking a route what its known query params are. @private */ _queryParamsFor: function (leafRouteName) { if (this._qpCache[leafRouteName]) { return this._qpCache[leafRouteName]; } var map = {}; var qps = []; this._qpCache[leafRouteName] = { map: map, qps: qps }; var routerjs = this.router; var recogHandlerInfos = routerjs.recognizer.handlersFor(leafRouteName); for (var i = 0; i < recogHandlerInfos.length; ++i) { var recogHandler = recogHandlerInfos[i]; var route = routerjs.getHandler(recogHandler.handler); var qpMeta = _emberMetalProperty_get.get(route, '_qp'); if (!qpMeta) { continue; } _emberMetalAssign.default(map, qpMeta.map); qps.push.apply(qps, qpMeta.qps); } return { qps: qps, map: map }; }, _fullyScopeQueryParams: function (leafRouteName, contexts, queryParams) { var state = calculatePostTransitionState(this, leafRouteName, contexts); var handlerInfos = state.handlerInfos; _emberRoutingUtils.stashParamNames(this, handlerInfos); for (var i = 0, len = handlerInfos.length; i < len; ++i) { var route = handlerInfos[i].handler; var qpMeta = _emberMetalProperty_get.get(route, '_qp'); for (var j = 0, qpLen = qpMeta.qps.length; j < qpLen; ++j) { var qp = qpMeta.qps[j]; var presentProp = qp.prop in queryParams && qp.prop || qp.scopedPropertyName in queryParams && qp.scopedPropertyName || qp.urlKey in queryParams && qp.urlKey; if (presentProp) { if (presentProp !== qp.scopedPropertyName) { queryParams[qp.scopedPropertyName] = queryParams[presentProp]; delete queryParams[presentProp]; } } } } }, _hydrateUnsuppliedQueryParams: function (leafRouteName, contexts, queryParams) { var state = calculatePostTransitionState(this, leafRouteName, contexts); var handlerInfos = state.handlerInfos; var appCache = this._bucketCache; _emberRoutingUtils.stashParamNames(this, handlerInfos); for (var i = 0; i < handlerInfos.length; ++i) { var route = handlerInfos[i].handler; var qpMeta = _emberMetalProperty_get.get(route, '_qp'); for (var j = 0, qpLen = qpMeta.qps.length; j < qpLen; ++j) { var qp = qpMeta.qps[j]; var presentProp = qp.prop in queryParams && qp.prop || qp.scopedPropertyName in queryParams && qp.scopedPropertyName || qp.urlKey in queryParams && qp.urlKey; if (presentProp) { if (presentProp !== qp.scopedPropertyName) { queryParams[qp.scopedPropertyName] = queryParams[presentProp]; delete queryParams[presentProp]; } } else { var cacheKey = _emberRoutingUtils.calculateCacheKey(qp.ctrl, qp.parts, state.params); queryParams[qp.scopedPropertyName] = appCache.lookup(cacheKey, qp.prop, qp.defaultValue); } } } }, _scheduleLoadingEvent: function (transition, originRoute) { this._cancelSlowTransitionTimer(); this._slowTransitionTimer = _emberMetalRun_loop.default.scheduleOnce('routerTransitions', this, '_handleSlowTransition', transition, originRoute); }, currentState: null, targetState: null, _handleSlowTransition: function (transition, originRoute) { if (!this.router.activeTransition) { // Don't fire an event if we've since moved on from // the transition that put us in a loading state. return; } this.set('targetState', _emberRoutingSystemRouter_state.default.create({ emberRouter: this, routerJs: this.router, routerJsState: this.router.activeTransition.state })); transition.trigger(true, 'loading', transition, originRoute); }, _cancelSlowTransitionTimer: function () { if (this._slowTransitionTimer) { _emberMetalRun_loop.default.cancel(this._slowTransitionTimer); } this._slowTransitionTimer = null; }, // These three helper functions are used to ensure errors aren't // re-raised if they're handled in a route's error action. _markErrorAsHandled: function (errorGuid) { this._handledErrors[errorGuid] = true; }, _isErrorHandled: function (errorGuid) { return this._handledErrors[errorGuid]; }, _clearHandledError: function (errorGuid) { delete this._handledErrors[errorGuid]; } }); /* Helper function for iterating root-ward, starting from (but not including) the provided `originRoute`. Returns true if the last callback fired requested to bubble upward. @private */ function forEachRouteAbove(originRoute, transition, callback) { var handlerInfos = transition.state.handlerInfos; var originRouteFound = false; var handlerInfo = undefined, route = undefined; for (var i = handlerInfos.length - 1; i >= 0; --i) { handlerInfo = handlerInfos[i]; route = handlerInfo.handler; if (!originRouteFound) { if (originRoute === route) { originRouteFound = true; } continue; } if (callback(route, handlerInfos[i + 1].handler) !== true) { return false; } } return true; } // These get invoked when an action bubbles above ApplicationRoute // and are not meant to be overridable. var defaultActionHandlers = { willResolveModel: function (transition, originRoute) { originRoute.router._scheduleLoadingEvent(transition, originRoute); }, error: function (error, transition, originRoute) { // Attempt to find an appropriate error substate to enter. var router = originRoute.router; var tryTopLevel = forEachRouteAbove(originRoute, transition, function (route, childRoute) { var childErrorRouteName = findChildRouteName(route, childRoute, 'error'); if (childErrorRouteName) { router.intermediateTransitionTo(childErrorRouteName, error); return; } return true; }); if (tryTopLevel) { // Check for top-level error state to enter. if (routeHasBeenDefined(originRoute.router, 'application_error')) { router.intermediateTransitionTo('application_error', error); return; } } logError(error, 'Error while processing route: ' + transition.targetName); }, loading: function (transition, originRoute) { // Attempt to find an appropriate loading substate to enter. var router = originRoute.router; var tryTopLevel = forEachRouteAbove(originRoute, transition, function (route, childRoute) { var childLoadingRouteName = findChildRouteName(route, childRoute, 'loading'); if (childLoadingRouteName) { router.intermediateTransitionTo(childLoadingRouteName); return; } // Don't bubble above pivot route. if (transition.pivotHandler !== route) { return true; } }); if (tryTopLevel) { // Check for top-level loading state to enter. if (routeHasBeenDefined(originRoute.router, 'application_loading')) { router.intermediateTransitionTo('application_loading'); return; } } } }; function logError(_error, initialMessage) { var errorArgs = []; var error = undefined; if (_error && typeof _error === 'object' && typeof _error.errorThrown === 'object') { error = _error.errorThrown; } else { error = _error; } if (initialMessage) { errorArgs.push(initialMessage); } if (error) { if (error.message) { errorArgs.push(error.message); } if (error.stack) { errorArgs.push(error.stack); } if (typeof error === 'string') { errorArgs.push(error); } } _emberConsole.default.error.apply(this, errorArgs); } function findChildRouteName(parentRoute, originatingChildRoute, name) { var router = parentRoute.router; var childName = undefined; var originatingChildRouteName = originatingChildRoute.routeName; if (true) { // The only time the originatingChildRoute's name should be 'application' // is if we're entering an engine if (originatingChildRouteName === 'application') { originatingChildRouteName = _containerOwner.getOwner(originatingChildRoute).mountPoint; } } // First, try a named loading state of the route, e.g. 'foo_loading' childName = originatingChildRouteName + '_' + name; if (routeHasBeenDefined(router, childName)) { return childName; } // Second, try general loading state of the parent, e.g. 'loading' var originatingChildRouteParts = originatingChildRouteName.split('.').slice(0, -1); var namespace = undefined; // If there is a namespace on the route, then we use that, otherwise we use // the parent route as the namespace. if (originatingChildRouteParts.length) { namespace = originatingChildRouteParts.join('.') + '.'; } else { namespace = parentRoute.routeName === 'application' ? '' : parentRoute.routeName + '.'; } childName = namespace + name; if (routeHasBeenDefined(router, childName)) { return childName; } } function routeHasBeenDefined(router, name) { var owner = _containerOwner.getOwner(router); return router.hasRoute(name) && (owner.hasRegistration('template:' + name) || owner.hasRegistration('route:' + name)); } function triggerEvent(handlerInfos, ignoreFailure, args) { var name = args.shift(); if (!handlerInfos) { if (ignoreFailure) { return; } throw new _emberMetalError.default('Can\'t trigger action \'' + name + '\' because your app hasn\'t finished transitioning into its first route. To trigger an action on destination routes during a transition, you can call `.send()` on the `Transition` object passed to the `model/beforeModel/afterModel` hooks.'); } var eventWasHandled = false; var handlerInfo = undefined, handler = undefined; for (var i = handlerInfos.length - 1; i >= 0; i--) { handlerInfo = handlerInfos[i]; handler = handlerInfo.handler; if (handler && handler.actions && handler.actions[name]) { if (handler.actions[name].apply(handler, args) === true) { eventWasHandled = true; } else { // Should only hit here if a non-bubbling error action is triggered on a route. if (name === 'error') { var errorId = _emberMetalUtils.guidFor(args[0]); handler.router._markErrorAsHandled(errorId); } return; } } } if (defaultActionHandlers[name]) { defaultActionHandlers[name].apply(null, args); return; } if (!eventWasHandled && !ignoreFailure) { throw new _emberMetalError.default('Nothing handled the action \'' + name + '\'. If you did handle the action, this error can be caused by returning true from an action handler in a controller, causing the action to bubble.'); } } function calculatePostTransitionState(emberRouter, leafRouteName, contexts) { var routerjs = emberRouter.router; var state = routerjs.applyIntent(leafRouteName, contexts); var handlerInfos = state.handlerInfos; var params = state.params; for (var i = 0; i < handlerInfos.length; ++i) { var handlerInfo = handlerInfos[i]; if (!handlerInfo.isResolved) { handlerInfo = handlerInfo.becomeResolved(null, handlerInfo.context); } params[handlerInfo.name] = handlerInfo.params; } return state; } function updatePaths(router) { var infos = router.router.currentHandlerInfos; if (infos.length === 0) { return; } var path = EmberRouter._routePath(infos); var currentRouteName = infos[infos.length - 1].name; _emberMetalProperty_set.set(router, 'currentPath', path); _emberMetalProperty_set.set(router, 'currentRouteName', currentRouteName); var appController = _containerOwner.getOwner(router).lookup('controller:application'); if (!appController) { // appController might not exist when top-level loading/error // substates have been entered since ApplicationRoute hasn't // actually been entered at that point. return; } if (!('currentPath' in appController)) { _emberMetalProperties.defineProperty(appController, 'currentPath'); } _emberMetalProperty_set.set(appController, 'currentPath', path); if (!('currentRouteName' in appController)) { _emberMetalProperties.defineProperty(appController, 'currentRouteName'); } _emberMetalProperty_set.set(appController, 'currentRouteName', currentRouteName); } EmberRouter.reopenClass({ router: null, /** The `Router.map` function allows you to define mappings from URLs to routes in your application. These mappings are defined within the supplied callback function using `this.route`. The first parameter is the name of the route which is used by default as the path name as well. The second parameter is the optional options hash. Available options are: * `path`: allows you to provide your own path as well as mark dynamic segments. * `resetNamespace`: false by default; when nesting routes, ember will combine the route names to form the fully-qualified route name, which is used with `{{link-to}}` or manually transitioning to routes. Setting `resetNamespace: true` will cause the route not to inherit from its parent route's names. This is handy for preventing extremely long route names. Keep in mind that the actual URL path behavior is still retained. The third parameter is a function, which can be used to nest routes. Nested routes, by default, will have the parent route tree's route name and path prepended to it's own. ```javascript App.Router.map(function(){ this.route('post', { path: '/post/:post_id' }, function() { this.route('edit'); this.route('comments', { resetNamespace: true }, function() { this.route('new'); }); }); }); ``` For more detailed documentation and examples please see [the guides](http://emberjs.com/guides/routing/defining-your-routes/). @method map @param callback @public */ map: function (callback) { if (!this.dslCallbacks) { this.dslCallbacks = []; this.reopenClass({ dslCallbacks: this.dslCallbacks }); } this.dslCallbacks.push(callback); return this; }, _routePath: function (handlerInfos) { var path = []; // We have to handle coalescing resource names that // are prefixed with their parent's names, e.g. // ['foo', 'foo.bar.baz'] => 'foo.bar.baz', not 'foo.foo.bar.baz' function intersectionMatches(a1, a2) { for (var i = 0; i < a1.length; ++i) { if (a1[i] !== a2[i]) { return false; } } return true; } var name = undefined, nameParts = undefined, oldNameParts = undefined; for (var i = 1; i < handlerInfos.length; i++) { name = handlerInfos[i].name; nameParts = name.split('.'); oldNameParts = slice.call(path); while (oldNameParts.length) { if (intersectionMatches(oldNameParts, nameParts)) { break; } oldNameParts.shift(); } path.push.apply(path, nameParts.slice(oldNameParts.length)); } return path.join('.'); } }); function didBeginTransition(transition, router) { var routerState = _emberRoutingSystemRouter_state.default.create({ emberRouter: router, routerJs: router.router, routerJsState: transition.state }); if (!router.currentState) { router.set('currentState', routerState); } router.set('targetState', routerState); transition.promise = transition.catch(function (error) { var errorId = _emberMetalUtils.guidFor(error); if (router._isErrorHandled(errorId)) { router._clearHandledError(errorId); } else { throw error; } }); } function resemblesURL(str) { return typeof str === 'string' && (str === '' || str.charAt(0) === '/'); } function forEachQueryParam(router, targetRouteName, queryParams, callback) { var qpCache = router._queryParamsFor(targetRouteName); for (var key in queryParams) { if (!queryParams.hasOwnProperty(key)) { continue; } var value = queryParams[key]; var qp = qpCache.map[key]; if (qp) { callback(key, value, qp); } } } function findLiveRoute(liveRoutes, name) { if (!liveRoutes) { return; } var stack = [liveRoutes]; while (stack.length > 0) { var test = stack.shift(); if (test.render.name === name) { return test; } var outlets = test.outlets; for (var outletName in outlets) { stack.push(outlets[outletName]); } } } function appendLiveRoute(liveRoutes, defaultParentState, renderOptions) { var target = undefined; var myState = { render: renderOptions, outlets: new _emberMetalEmpty_object.default(), wasUsed: false }; if (renderOptions.into) { target = findLiveRoute(liveRoutes, renderOptions.into); } else { target = defaultParentState; } if (target) { _emberMetalProperty_set.set(target.outlets, renderOptions.outlet, myState); } else { if (renderOptions.into) { // Megahax time. Post-3.0-breaking-changes, we will just assert // right here that the user tried to target a nonexistent // thing. But for now we still need to support the `render` // helper, and people are allowed to target templates rendered // by the render helper. So instead we defer doing anyting with // these orphan renders until afterRender. appendOrphan(liveRoutes, renderOptions.into, myState); } else { liveRoutes = myState; } } return { liveRoutes: liveRoutes, ownState: myState }; } function appendOrphan(liveRoutes, into, myState) { if (!liveRoutes.outlets.__ember_orphans__) { liveRoutes.outlets.__ember_orphans__ = { render: { name: '__ember_orphans__' }, outlets: new _emberMetalEmpty_object.default() }; } liveRoutes.outlets.__ember_orphans__.outlets[into] = myState; _emberMetalRun_loop.default.schedule('afterRender', function () { // `wasUsed` gets set by the render helper. _emberMetalDebug.assert('You attempted to render into \'' + into + '\' but it was not found', liveRoutes.outlets.__ember_orphans__.outlets[into].wasUsed); }); } function representEmptyRoute(liveRoutes, defaultParentState, route) { // the route didn't render anything var alreadyAppended = findLiveRoute(liveRoutes, route.routeName); if (alreadyAppended) { // But some other route has already rendered our default // template, so that becomes the default target for any // children we may have. return alreadyAppended; } else { // Create an entry to represent our default template name, // just so other routes can target it and inherit its place // in the outlet hierarchy. defaultParentState.outlets.main = { render: { name: route.routeName, outlet: 'main' }, outlets: {} }; return defaultParentState; } } if (true) { EmberRouter.reopen({ _getEngineInstance: function (_ref) { var name = _ref.name; var instanceId = _ref.instanceId; var mountPoint = _ref.mountPoint; var engineInstances = this._engineInstances; if (!engineInstances[name]) { engineInstances[name] = new _emberMetalEmpty_object.default(); } var engineInstance = engineInstances[name][instanceId]; if (!engineInstance) { var owner = _containerOwner.getOwner(this); _emberMetalDebug.assert('You attempted to mount the engine \'' + name + '\' in your router map, but the engine can not be found.', owner.hasRegistration('engine:' + name)); engineInstance = owner.buildChildEngineInstance(name, { routable: true, mountPoint: mountPoint }); engineInstance.boot(); engineInstances[name][instanceId] = engineInstance; } return engineInstance; } }); } exports.default = EmberRouter; }); /** @module ember @submodule ember-routing */ enifed('ember-routing/system/router_state', ['exports', 'ember-metal/is_empty', 'ember-runtime/system/object', 'ember-metal/assign'], function (exports, _emberMetalIs_empty, _emberRuntimeSystemObject, _emberMetalAssign) { 'use strict'; exports.default = _emberRuntimeSystemObject.default.extend({ emberRouter: null, routerJs: null, routerJsState: null, isActiveIntent: function (routeName, models, queryParams, queryParamsMustMatch) { var state = this.routerJsState; if (!this.routerJs.isActiveIntent(routeName, models, null, state)) { return false; } var emptyQueryParams = _emberMetalIs_empty.default(Object.keys(queryParams)); if (queryParamsMustMatch && !emptyQueryParams) { var visibleQueryParams = {}; _emberMetalAssign.default(visibleQueryParams, queryParams); this.emberRouter._prepareQueryParams(routeName, models, visibleQueryParams); return shallowEqual(visibleQueryParams, state.queryParams); } return true; } }); function shallowEqual(a, b) { var k = undefined; for (k in a) { if (a.hasOwnProperty(k) && a[k] !== b[k]) { return false; } } for (k in b) { if (b.hasOwnProperty(k) && a[k] !== b[k]) { return false; } } return true; } }); enifed('ember-routing/utils', ['exports', 'ember-metal/assign', 'ember-metal/property_get'], function (exports, _emberMetalAssign, _emberMetalProperty_get) { 'use strict'; exports.routeArgs = routeArgs; exports.getActiveTargetName = getActiveTargetName; exports.stashParamNames = stashParamNames; exports.calculateCacheKey = calculateCacheKey; exports.normalizeControllerQueryParams = normalizeControllerQueryParams; var ALL_PERIODS_REGEX = /\./g; function routeArgs(targetRouteName, models, queryParams) { var args = []; if (typeof targetRouteName === 'string') { args.push('' + targetRouteName); } args.push.apply(args, models); args.push({ queryParams: queryParams }); return args; } function getActiveTargetName(router) { var handlerInfos = router.activeTransition ? router.activeTransition.state.handlerInfos : router.state.handlerInfos; return handlerInfos[handlerInfos.length - 1].name; } function stashParamNames(router, handlerInfos) { if (handlerInfos._namesStashed) { return; } // This helper exists because router.js/route-recognizer.js awkwardly // keeps separate a handlerInfo's list of parameter names depending // on whether a URL transition or named transition is happening. // Hopefully we can remove this in the future. var targetRouteName = handlerInfos[handlerInfos.length - 1].name; var recogHandlers = router.router.recognizer.handlersFor(targetRouteName); var dynamicParent = null; for (var i = 0; i < handlerInfos.length; ++i) { var handlerInfo = handlerInfos[i]; var names = recogHandlers[i].names; if (names.length) { dynamicParent = handlerInfo; } handlerInfo._names = names; var route = handlerInfo.handler; route._stashNames(handlerInfo, dynamicParent); } handlerInfos._namesStashed = true; } function _calculateCacheValuePrefix(prefix, part) { // calculates the dot seperated sections from prefix that are also // at the start of part - which gives us the route name // given : prefix = site.article.comments, part = site.article.id // - returns: site.article (use get(values[site.article], 'id') to get the dynamic part - used below) // given : prefix = site.article, part = site.article.id // - returns: site.article. (use get(values[site.article], 'id') to get the dynamic part - used below) var prefixParts = prefix.split('.'); var currPrefix = ''; for (var i = 0; i < prefixParts.length; i++) { var currPart = prefixParts.slice(0, i + 1).join('.'); if (part.indexOf(currPart) !== 0) { break; } currPrefix = currPart; } return currPrefix; } /* Stolen from Controller */ function calculateCacheKey(prefix, _parts, values) { var parts = _parts || []; var suffixes = ''; for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var cacheValuePrefix = _calculateCacheValuePrefix(prefix, part); var value = undefined; if (values) { if (cacheValuePrefix && cacheValuePrefix in values) { var partRemovedPrefix = part.indexOf(cacheValuePrefix) === 0 ? part.substr(cacheValuePrefix.length + 1) : part; value = _emberMetalProperty_get.get(values[cacheValuePrefix], partRemovedPrefix); } else { value = _emberMetalProperty_get.get(values, part); } } suffixes += '::' + part + ':' + value; } return prefix + suffixes.replace(ALL_PERIODS_REGEX, '-'); } /* Controller-defined query parameters can come in three shapes: Array queryParams: ['foo', 'bar'] Array of simple objects where value is an alias queryParams: [ { 'foo': 'rename_foo_to_this' }, { 'bar': 'call_bar_this_instead' } ] Array of fully defined objects queryParams: [ { 'foo': { as: 'rename_foo_to_this' }, } { 'bar': { as: 'call_bar_this_instead', scope: 'controller' } } ] This helper normalizes all three possible styles into the 'Array of fully defined objects' style. */ function normalizeControllerQueryParams(queryParams) { if (queryParams._qpMap) { return queryParams._qpMap; } var qpMap = queryParams._qpMap = {}; for (var i = 0; i < queryParams.length; ++i) { accumulateQueryParamDescriptors(queryParams[i], qpMap); } return qpMap; } function accumulateQueryParamDescriptors(_desc, accum) { var desc = _desc; var tmp = undefined; if (typeof desc === 'string') { tmp = {}; tmp[desc] = { as: null }; desc = tmp; } for (var key in desc) { if (!desc.hasOwnProperty(key)) { return; } var singleDesc = desc[key]; if (typeof singleDesc === 'string') { singleDesc = { as: singleDesc }; } tmp = accum[key] || { as: null, scope: 'model' }; _emberMetalAssign.default(tmp, singleDesc); accum[key] = tmp; } } }); enifed('ember-runtime/compare', ['exports', 'ember-runtime/utils', 'ember-runtime/mixins/comparable'], function (exports, _emberRuntimeUtils, _emberRuntimeMixinsComparable) { 'use strict'; exports.default = compare; var TYPE_ORDER = { 'undefined': 0, 'null': 1, 'boolean': 2, 'number': 3, 'string': 4, 'array': 5, 'object': 6, 'instance': 7, 'function': 8, 'class': 9, 'date': 10 }; // // the spaceship operator // // `. ___ // __,' __`. _..----....____ // __...--.'``;. ,. ;``--..__ .' ,-._ _.-' // _..-''-------' `' `' `' O ``-''._ (,;') _,' // ,'________________ \`-._`-',' // `._ ```````````------...___ '-.._'-: // ```--.._ ,. ````--...__\-. // `.--. `-` "INFINITY IS LESS ____ | |` // `. `. THAN BEYOND" ,'`````. ; ;` // `._`. __________ `. \'__/` // `-:._____/______/___/____`. \ ` // | `._ `. \ // `._________`-. `. `.___ // SSt `------'` function spaceship(a, b) { var diff = a - b; return (diff > 0) - (diff < 0); } /** Compares two javascript values and returns: - -1 if the first is smaller than the second, - 0 if both are equal, - 1 if the first is greater than the second. ```javascript Ember.compare('hello', 'hello'); // 0 Ember.compare('abc', 'dfg'); // -1 Ember.compare(2, 1); // 1 ``` If the types of the two objects are different precedence occurs in the following order, with types earlier in the list considered `<` types later in the list: - undefined - null - boolean - number - string - array - object - instance - function - class - date ```javascript Ember.compare('hello', 50); // 1 Ember.compare(50, 'hello'); // -1 ``` @method compare @for Ember @param {Object} v First value to compare @param {Object} w Second value to compare @return {Number} -1 if v < w, 0 if v = w and 1 if v > w. @public */ function compare(v, w) { if (v === w) { return 0; } var type1 = _emberRuntimeUtils.typeOf(v); var type2 = _emberRuntimeUtils.typeOf(w); if (_emberRuntimeMixinsComparable.default) { if (type1 === 'instance' && _emberRuntimeMixinsComparable.default.detect(v) && v.constructor.compare) { return v.constructor.compare(v, w); } if (type2 === 'instance' && _emberRuntimeMixinsComparable.default.detect(w) && w.constructor.compare) { return w.constructor.compare(w, v) * -1; } } var res = spaceship(TYPE_ORDER[type1], TYPE_ORDER[type2]); if (res !== 0) { return res; } // types are equal - so we have to check values now switch (type1) { case 'boolean': case 'number': return spaceship(v, w); case 'string': return spaceship(v.localeCompare(w), 0); case 'array': var vLen = v.length; var wLen = w.length; var len = Math.min(vLen, wLen); for (var i = 0; i < len; i++) { var r = compare(v[i], w[i]); if (r !== 0) { return r; } } // all elements are equal now // shorter array should be ordered first return spaceship(vLen, wLen); case 'instance': if (_emberRuntimeMixinsComparable.default && _emberRuntimeMixinsComparable.default.detect(v)) { return v.compare(v, w); } return 0; case 'date': return spaceship(v.getTime(), w.getTime()); default: return 0; } } }); enifed('ember-runtime/computed/computed_macros', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/computed', 'ember-metal/is_empty', 'ember-metal/is_none', 'ember-metal/alias', 'ember-metal/expand_properties'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalComputed, _emberMetalIs_empty, _emberMetalIs_none, _emberMetalAlias, _emberMetalExpand_properties) { 'use strict'; exports.empty = empty; exports.notEmpty = notEmpty; exports.none = none; exports.not = not; exports.bool = bool; exports.match = match; exports.equal = equal; exports.gt = gt; exports.gte = gte; exports.lt = lt; exports.lte = lte; exports.oneWay = oneWay; exports.readOnly = readOnly; exports.deprecatingAlias = deprecatingAlias; /** @module ember @submodule ember-metal */ function expandPropertiesToArray(predicateName, properties) { var expandedProperties = []; function extractProperty(entry) { expandedProperties.push(entry); } for (var i = 0; i < properties.length; i++) { var property = properties[i]; _emberMetalDebug.assert('Dependent keys passed to Ember.computed.' + predicateName + '() can\'t have spaces.', property.indexOf(' ') < 0); _emberMetalExpand_properties.default(property, extractProperty); } return expandedProperties; } function generateComputedWithPredicate(name, predicate) { return function () { for (var _len = arguments.length, properties = Array(_len), _key = 0; _key < _len; _key++) { properties[_key] = arguments[_key]; } var expandedProperties = expandPropertiesToArray(name, properties); var computedFunc = _emberMetalComputed.computed(function () { var lastIdx = expandedProperties.length - 1; for (var i = 0; i < lastIdx; i++) { var value = _emberMetalProperty_get.get(this, expandedProperties[i]); if (!predicate(value)) { return value; } } return _emberMetalProperty_get.get(this, expandedProperties[lastIdx]); }); return computedFunc.property.apply(computedFunc, expandedProperties); }; } /** A computed property that returns true if the value of the dependent property is null, an empty string, empty array, or empty function. Example ```javascript let ToDoList = Ember.Object.extend({ isDone: Ember.computed.empty('todos') }); let todoList = ToDoList.create({ todos: ['Unit Test', 'Documentation', 'Release'] }); todoList.get('isDone'); // false todoList.get('todos').clear(); todoList.get('isDone'); // true ``` @since 1.6.0 @method empty @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which negate the original value for property @public */ function empty(dependentKey) { return _emberMetalComputed.computed(dependentKey + '.length', function () { return _emberMetalIs_empty.default(_emberMetalProperty_get.get(this, dependentKey)); }); } /** A computed property that returns true if the value of the dependent property is NOT null, an empty string, empty array, or empty function. Example ```javascript let Hamster = Ember.Object.extend({ hasStuff: Ember.computed.notEmpty('backpack') }); let hamster = Hamster.create({ backpack: ['Food', 'Sleeping Bag', 'Tent'] }); hamster.get('hasStuff'); // true hamster.get('backpack').clear(); // [] hamster.get('hasStuff'); // false ``` @method notEmpty @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which returns true if original value for property is not empty. @public */ function notEmpty(dependentKey) { return _emberMetalComputed.computed(dependentKey + '.length', function () { return !_emberMetalIs_empty.default(_emberMetalProperty_get.get(this, dependentKey)); }); } /** A computed property that returns true if the value of the dependent property is null or undefined. This avoids errors from JSLint complaining about use of ==, which can be technically confusing. Example ```javascript let Hamster = Ember.Object.extend({ isHungry: Ember.computed.none('food') }); let hamster = Hamster.create(); hamster.get('isHungry'); // true hamster.set('food', 'Banana'); hamster.get('isHungry'); // false hamster.set('food', null); hamster.get('isHungry'); // true ``` @method none @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which returns true if original value for property is null or undefined. @public */ function none(dependentKey) { return _emberMetalComputed.computed(dependentKey, function () { return _emberMetalIs_none.default(_emberMetalProperty_get.get(this, dependentKey)); }); } /** A computed property that returns the inverse boolean value of the original value for the dependent property. Example ```javascript let User = Ember.Object.extend({ isAnonymous: Ember.computed.not('loggedIn') }); let user = User.create({loggedIn: false}); user.get('isAnonymous'); // true user.set('loggedIn', true); user.get('isAnonymous'); // false ``` @method not @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which returns inverse of the original value for property @public */ function not(dependentKey) { return _emberMetalComputed.computed(dependentKey, function () { return !_emberMetalProperty_get.get(this, dependentKey); }); } /** A computed property that converts the provided dependent property into a boolean value. ```javascript let Hamster = Ember.Object.extend({ hasBananas: Ember.computed.bool('numBananas') }); let hamster = Hamster.create(); hamster.get('hasBananas'); // false hamster.set('numBananas', 0); hamster.get('hasBananas'); // false hamster.set('numBananas', 1); hamster.get('hasBananas'); // true hamster.set('numBananas', null); hamster.get('hasBananas'); // false ``` @method bool @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which converts to boolean the original value for property @public */ function bool(dependentKey) { return _emberMetalComputed.computed(dependentKey, function () { return !!_emberMetalProperty_get.get(this, dependentKey); }); } /** A computed property which matches the original value for the dependent property against a given RegExp, returning `true` if the value matches the RegExp and `false` if it does not. Example ```javascript let User = Ember.Object.extend({ hasValidEmail: Ember.computed.match('email', /^.+@.+\..+$/) }); let user = User.create({loggedIn: false}); user.get('hasValidEmail'); // false user.set('email', ''); user.get('hasValidEmail'); // false user.set('email', 'ember_hamster@example.com'); user.get('hasValidEmail'); // true ``` @method match @for Ember.computed @param {String} dependentKey @param {RegExp} regexp @return {Ember.ComputedProperty} computed property which match the original value for property against a given RegExp @public */ function match(dependentKey, regexp) { return _emberMetalComputed.computed(dependentKey, function () { var value = _emberMetalProperty_get.get(this, dependentKey); return typeof value === 'string' ? regexp.test(value) : false; }); } /** A computed property that returns true if the provided dependent property is equal to the given value. Example ```javascript let Hamster = Ember.Object.extend({ napTime: Ember.computed.equal('state', 'sleepy') }); let hamster = Hamster.create(); hamster.get('napTime'); // false hamster.set('state', 'sleepy'); hamster.get('napTime'); // true hamster.set('state', 'hungry'); hamster.get('napTime'); // false ``` @method equal @for Ember.computed @param {String} dependentKey @param {String|Number|Object} value @return {Ember.ComputedProperty} computed property which returns true if the original value for property is equal to the given value. @public */ function equal(dependentKey, value) { return _emberMetalComputed.computed(dependentKey, function () { return _emberMetalProperty_get.get(this, dependentKey) === value; }); } /** A computed property that returns true if the provided dependent property is greater than the provided value. Example ```javascript let Hamster = Ember.Object.extend({ hasTooManyBananas: Ember.computed.gt('numBananas', 10) }); let hamster = Hamster.create(); hamster.get('hasTooManyBananas'); // false hamster.set('numBananas', 3); hamster.get('hasTooManyBananas'); // false hamster.set('numBananas', 11); hamster.get('hasTooManyBananas'); // true ``` @method gt @for Ember.computed @param {String} dependentKey @param {Number} value @return {Ember.ComputedProperty} computed property which returns true if the original value for property is greater than given value. @public */ function gt(dependentKey, value) { return _emberMetalComputed.computed(dependentKey, function () { return _emberMetalProperty_get.get(this, dependentKey) > value; }); } /** A computed property that returns true if the provided dependent property is greater than or equal to the provided value. Example ```javascript let Hamster = Ember.Object.extend({ hasTooManyBananas: Ember.computed.gte('numBananas', 10) }); let hamster = Hamster.create(); hamster.get('hasTooManyBananas'); // false hamster.set('numBananas', 3); hamster.get('hasTooManyBananas'); // false hamster.set('numBananas', 10); hamster.get('hasTooManyBananas'); // true ``` @method gte @for Ember.computed @param {String} dependentKey @param {Number} value @return {Ember.ComputedProperty} computed property which returns true if the original value for property is greater or equal then given value. @public */ function gte(dependentKey, value) { return _emberMetalComputed.computed(dependentKey, function () { return _emberMetalProperty_get.get(this, dependentKey) >= value; }); } /** A computed property that returns true if the provided dependent property is less than the provided value. Example ```javascript let Hamster = Ember.Object.extend({ needsMoreBananas: Ember.computed.lt('numBananas', 3) }); let hamster = Hamster.create(); hamster.get('needsMoreBananas'); // true hamster.set('numBananas', 3); hamster.get('needsMoreBananas'); // false hamster.set('numBananas', 2); hamster.get('needsMoreBananas'); // true ``` @method lt @for Ember.computed @param {String} dependentKey @param {Number} value @return {Ember.ComputedProperty} computed property which returns true if the original value for property is less then given value. @public */ function lt(dependentKey, value) { return _emberMetalComputed.computed(dependentKey, function () { return _emberMetalProperty_get.get(this, dependentKey) < value; }); } /** A computed property that returns true if the provided dependent property is less than or equal to the provided value. Example ```javascript let Hamster = Ember.Object.extend({ needsMoreBananas: Ember.computed.lte('numBananas', 3) }); let hamster = Hamster.create(); hamster.get('needsMoreBananas'); // true hamster.set('numBananas', 5); hamster.get('needsMoreBananas'); // false hamster.set('numBananas', 3); hamster.get('needsMoreBananas'); // true ``` @method lte @for Ember.computed @param {String} dependentKey @param {Number} value @return {Ember.ComputedProperty} computed property which returns true if the original value for property is less or equal than given value. @public */ function lte(dependentKey, value) { return _emberMetalComputed.computed(dependentKey, function () { return _emberMetalProperty_get.get(this, dependentKey) <= value; }); } /** A computed property that performs a logical `and` on the original values for the provided dependent properties. You may pass in more than two properties and even use property brace expansion. The computed property will return the first falsy value or last truthy value just like JavaScript's `&&` operator. Example ```javascript let Hamster = Ember.Object.extend({ readyForCamp: Ember.computed.and('hasTent', 'hasBackpack'), readyForHike: Ember.computed.and('hasWalkingStick', 'hasBackpack') }); let tomster = Hamster.create(); tomster.get('readyForCamp'); // false tomster.set('hasTent', true); tomster.get('readyForCamp'); // false tomster.set('hasBackpack', true); tomster.get('readyForCamp'); // true tomster.set('hasBackpack', 'Yes'); tomster.get('readyForCamp'); // 'Yes' tomster.set('hasWalkingStick', null); tomster.get('readyForHike'); // null ``` @method and @for Ember.computed @param {String} dependentKey* @return {Ember.ComputedProperty} computed property which performs a logical `and` on the values of all the original values for properties. @public */ var and = generateComputedWithPredicate('and', function (value) { return value; }); exports.and = and; /** A computed property which performs a logical `or` on the original values for the provided dependent properties. You may pass in more than two properties and even use property brace expansion. The computed property will return the first truthy value or last falsy value just like JavaScript's `||` operator. Example ```javascript let Hamster = Ember.Object.extend({ readyForRain: Ember.computed.or('hasJacket', 'hasUmbrella'), readyForBeach: Ember.computed.or('{hasSunscreen,hasUmbrella}') }); let tomster = Hamster.create(); tomster.get('readyForRain'); // undefined tomster.set('hasUmbrella', true); tomster.get('readyForRain'); // true tomster.set('hasJacket', 'Yes'); tomster.get('readyForRain'); // 'Yes' tomster.set('hasSunscreen', 'Check'); tomster.get('readyForBeach'); // 'Check' ``` @method or @for Ember.computed @param {String} dependentKey* @return {Ember.ComputedProperty} computed property which performs a logical `or` on the values of all the original values for properties. @public */ var or = generateComputedWithPredicate('or', function (value) { return !value; }); exports.or = or; /** Creates a new property that is an alias for another property on an object. Calls to `get` or `set` this property behave as though they were called on the original property. ```javascript let Person = Ember.Object.extend({ name: 'Alex Matchneer', nomen: Ember.computed.alias('name') }); let alex = Person.create(); alex.get('nomen'); // 'Alex Matchneer' alex.get('name'); // 'Alex Matchneer' alex.set('nomen', '@machty'); alex.get('name'); // '@machty' ``` @method alias @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which creates an alias to the original value for property. @public */ /** Where `computed.alias` aliases `get` and `set`, and allows for bidirectional data flow, `computed.oneWay` only provides an aliased `get`. The `set` will not mutate the upstream property, rather causes the current property to become the value set. This causes the downstream property to permanently diverge from the upstream property. Example ```javascript let User = Ember.Object.extend({ firstName: null, lastName: null, nickName: Ember.computed.oneWay('firstName') }); let teddy = User.create({ firstName: 'Teddy', lastName: 'Zeenny' }); teddy.get('nickName'); // 'Teddy' teddy.set('nickName', 'TeddyBear'); // 'TeddyBear' teddy.get('firstName'); // 'Teddy' ``` @method oneWay @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which creates a one way computed property to the original value for property. @public */ function oneWay(dependentKey) { return _emberMetalAlias.default(dependentKey).oneWay(); } /** This is a more semantically meaningful alias of `computed.oneWay`, whose name is somewhat ambiguous as to which direction the data flows. @method reads @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which creates a one way computed property to the original value for property. @public */ /** Where `computed.oneWay` provides oneWay bindings, `computed.readOnly` provides a readOnly one way binding. Very often when using `computed.oneWay` one does not also want changes to propagate back up, as they will replace the value. This prevents the reverse flow, and also throws an exception when it occurs. Example ```javascript let User = Ember.Object.extend({ firstName: null, lastName: null, nickName: Ember.computed.readOnly('firstName') }); let teddy = User.create({ firstName: 'Teddy', lastName: 'Zeenny' }); teddy.get('nickName'); // 'Teddy' teddy.set('nickName', 'TeddyBear'); // throws Exception // throw new Ember.Error('Cannot Set: nickName on: <User:ember27288>' );` teddy.get('firstName'); // 'Teddy' ``` @method readOnly @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computed property which creates a one way computed property to the original value for property. @since 1.5.0 @public */ function readOnly(dependentKey) { return _emberMetalAlias.default(dependentKey).readOnly(); } /** Creates a new property that is an alias for another property on an object. Calls to `get` or `set` this property behave as though they were called on the original property, but also print a deprecation warning. ```javascript let Hamster = Ember.Object.extend({ bananaCount: Ember.computed.deprecatingAlias('cavendishCount', { id: 'hamster.deprecate-banana', until: '3.0.0' }) }); let hamster = Hamster.create(); hamster.set('bananaCount', 5); // Prints a deprecation warning. hamster.get('cavendishCount'); // 5 ``` @method deprecatingAlias @for Ember.computed @param {String} dependentKey @param {Object} options Options for `Ember.deprecate`. @return {Ember.ComputedProperty} computed property which creates an alias with a deprecation to the original value for property. @since 1.7.0 @public */ function deprecatingAlias(dependentKey, options) { return _emberMetalComputed.computed(dependentKey, { get: function (key) { _emberMetalDebug.deprecate('Usage of `' + key + '` is deprecated, use `' + dependentKey + '` instead.', false, options); return _emberMetalProperty_get.get(this, dependentKey); }, set: function (key, value) { _emberMetalDebug.deprecate('Usage of `' + key + '` is deprecated, use `' + dependentKey + '` instead.', false, options); _emberMetalProperty_set.set(this, dependentKey, value); return value; } }); } }); enifed('ember-runtime/computed/reduce_computed_macros', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/error', 'ember-metal/computed', 'ember-metal/observer', 'ember-runtime/compare', 'ember-runtime/utils', 'ember-runtime/system/native_array', 'ember-metal/is_none', 'ember-metal/get_properties', 'ember-metal/empty_object', 'ember-metal/utils', 'ember-metal/weak_map'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalError, _emberMetalComputed, _emberMetalObserver, _emberRuntimeCompare, _emberRuntimeUtils, _emberRuntimeSystemNative_array, _emberMetalIs_none, _emberMetalGet_properties, _emberMetalEmpty_object, _emberMetalUtils, _emberMetalWeak_map) { /** @module ember @submodule ember-runtime */ 'use strict'; exports.sum = sum; exports.max = max; exports.min = min; exports.map = map; exports.mapBy = mapBy; exports.filter = filter; exports.filterBy = filterBy; exports.uniq = uniq; exports.uniqBy = uniqBy; exports.intersect = intersect; exports.setDiff = setDiff; exports.collect = collect; exports.sort = sort; function reduceMacro(dependentKey, callback, initialValue) { return _emberMetalComputed.computed(dependentKey + '.[]', function () { var _this = this; var arr = _emberMetalProperty_get.get(this, dependentKey); if (arr === null || typeof arr !== 'object') { return initialValue; } return arr.reduce(function (previousValue, currentValue, index, array) { return callback.call(_this, previousValue, currentValue, index, array); }, initialValue); }).readOnly(); } function arrayMacro(dependentKey, callback) { // This is a bit ugly var propertyName = undefined; if (/@each/.test(dependentKey)) { propertyName = dependentKey.replace(/\.@each.*$/, ''); } else { propertyName = dependentKey; dependentKey += '.[]'; } return _emberMetalComputed.computed(dependentKey, function () { var value = _emberMetalProperty_get.get(this, propertyName); if (_emberRuntimeUtils.isArray(value)) { return _emberRuntimeSystemNative_array.A(callback.call(this, value)); } else { return _emberRuntimeSystemNative_array.A(); } }).readOnly(); } function multiArrayMacro(dependentKeys, callback) { var args = dependentKeys.map(function (key) { return key + '.[]'; }); args.push(function () { return _emberRuntimeSystemNative_array.A(callback.call(this, dependentKeys)); }); return _emberMetalComputed.computed.apply(this, args).readOnly(); } /** A computed property that returns the sum of the values in the dependent array. @method sum @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computes the sum of all values in the dependentKey's array @since 1.4.0 @public */ function sum(dependentKey) { return reduceMacro(dependentKey, function (sum, item) { return sum + item; }, 0); } /** A computed property that calculates the maximum value in the dependent array. This will return `-Infinity` when the dependent array is empty. ```javascript let Person = Ember.Object.extend({ childAges: Ember.computed.mapBy('children', 'age'), maxChildAge: Ember.computed.max('childAges') }); let lordByron = Person.create({ children: [] }); lordByron.get('maxChildAge'); // -Infinity lordByron.get('children').pushObject({ name: 'Augusta Ada Byron', age: 7 }); lordByron.get('maxChildAge'); // 7 lordByron.get('children').pushObjects([{ name: 'Allegra Byron', age: 5 }, { name: 'Elizabeth Medora Leigh', age: 8 }]); lordByron.get('maxChildAge'); // 8 ``` If the types of the arguments are not numbers, they will be converted to numbers and the type of the return value will always be `Number`. For example, the max of a list of Date objects will be the highest timestamp as a `Number`. This behavior is consistent with `Math.max`. @method max @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computes the largest value in the dependentKey's array @public */ function max(dependentKey) { return reduceMacro(dependentKey, function (max, item) { return Math.max(max, item); }, -Infinity); } /** A computed property that calculates the minimum value in the dependent array. This will return `Infinity` when the dependent array is empty. ```javascript let Person = Ember.Object.extend({ childAges: Ember.computed.mapBy('children', 'age'), minChildAge: Ember.computed.min('childAges') }); let lordByron = Person.create({ children: [] }); lordByron.get('minChildAge'); // Infinity lordByron.get('children').pushObject({ name: 'Augusta Ada Byron', age: 7 }); lordByron.get('minChildAge'); // 7 lordByron.get('children').pushObjects([{ name: 'Allegra Byron', age: 5 }, { name: 'Elizabeth Medora Leigh', age: 8 }]); lordByron.get('minChildAge'); // 5 ``` If the types of the arguments are not numbers, they will be converted to numbers and the type of the return value will always be `Number`. For example, the min of a list of Date objects will be the lowest timestamp as a `Number`. This behavior is consistent with `Math.min`. @method min @for Ember.computed @param {String} dependentKey @return {Ember.ComputedProperty} computes the smallest value in the dependentKey's array @public */ function min(dependentKey) { return reduceMacro(dependentKey, function (min, item) { return Math.min(min, item); }, Infinity); } /** Returns an array mapped via the callback The callback method you provide should have the following signature. `item` is the current item in the iteration. `index` is the integer index of the current item in the iteration. ```javascript function(item, index); ``` Example ```javascript let Hamster = Ember.Object.extend({ excitingChores: Ember.computed.map('chores', function(chore, index) { return chore.toUpperCase() + '!'; }) }); let hamster = Hamster.create({ chores: ['clean', 'write more unit tests'] }); hamster.get('excitingChores'); // ['CLEAN!', 'WRITE MORE UNIT TESTS!'] ``` @method map @for Ember.computed @param {String} dependentKey @param {Function} callback @return {Ember.ComputedProperty} an array mapped via the callback @public */ function map(dependentKey, callback) { return arrayMacro(dependentKey, function (value) { return value.map(callback, this); }); } /** Returns an array mapped to the specified key. ```javascript let Person = Ember.Object.extend({ childAges: Ember.computed.mapBy('children', 'age') }); let lordByron = Person.create({ children: [] }); lordByron.get('childAges'); // [] lordByron.get('children').pushObject({ name: 'Augusta Ada Byron', age: 7 }); lordByron.get('childAges'); // [7] lordByron.get('children').pushObjects([{ name: 'Allegra Byron', age: 5 }, { name: 'Elizabeth Medora Leigh', age: 8 }]); lordByron.get('childAges'); // [7, 5, 8] ``` @method mapBy @for Ember.computed @param {String} dependentKey @param {String} propertyKey @return {Ember.ComputedProperty} an array mapped to the specified key @public */ function mapBy(dependentKey, propertyKey) { _emberMetalDebug.assert('Ember.computed.mapBy expects a property string for its second argument, ' + 'perhaps you meant to use "map"', typeof propertyKey === 'string'); return map(dependentKey + '.@each.' + propertyKey, function (item) { return _emberMetalProperty_get.get(item, propertyKey); }); } /** Filters the array by the callback. The callback method you provide should have the following signature. `item` is the current item in the iteration. `index` is the integer index of the current item in the iteration. `array` is the dependant array itself. ```javascript function(item, index, array); ``` ```javascript let Hamster = Ember.Object.extend({ remainingChores: Ember.computed.filter('chores', function(chore, index, array) { return !chore.done; }) }); let hamster = Hamster.create({ chores: [ { name: 'cook', done: true }, { name: 'clean', done: true }, { name: 'write more unit tests', done: false } ] }); hamster.get('remainingChores'); // [{name: 'write more unit tests', done: false}] ``` @method filter @for Ember.computed @param {String} dependentKey @param {Function} callback @return {Ember.ComputedProperty} the filtered array @public */ function filter(dependentKey, callback) { return arrayMacro(dependentKey, function (value) { return value.filter(callback, this); }); } /** Filters the array by the property and value ```javascript let Hamster = Ember.Object.extend({ remainingChores: Ember.computed.filterBy('chores', 'done', false) }); let hamster = Hamster.create({ chores: [ { name: 'cook', done: true }, { name: 'clean', done: true }, { name: 'write more unit tests', done: false } ] }); hamster.get('remainingChores'); // [{ name: 'write more unit tests', done: false }] ``` @method filterBy @for Ember.computed @param {String} dependentKey @param {String} propertyKey @param {*} value @return {Ember.ComputedProperty} the filtered array @public */ function filterBy(dependentKey, propertyKey, value) { var callback = undefined; if (arguments.length === 2) { callback = function (item) { return _emberMetalProperty_get.get(item, propertyKey); }; } else { callback = function (item) { return _emberMetalProperty_get.get(item, propertyKey) === value; }; } return filter(dependentKey + '.@each.' + propertyKey, callback); } /** A computed property which returns a new array with all the unique elements from one or more dependent arrays. Example ```javascript let Hamster = Ember.Object.extend({ uniqueFruits: Ember.computed.uniq('fruits') }); let hamster = Hamster.create({ fruits: [ 'banana', 'grape', 'kale', 'banana' ] }); hamster.get('uniqueFruits'); // ['banana', 'grape', 'kale'] ``` @method uniq @for Ember.computed @param {String} propertyKey* @return {Ember.ComputedProperty} computes a new array with all the unique elements from the dependent array @public */ function uniq() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return multiArrayMacro(args, function (dependentKeys) { var _this2 = this; var uniq = _emberRuntimeSystemNative_array.A(); dependentKeys.forEach(function (dependentKey) { var value = _emberMetalProperty_get.get(_this2, dependentKey); if (_emberRuntimeUtils.isArray(value)) { value.forEach(function (item) { if (uniq.indexOf(item) === -1) { uniq.push(item); } }); } }); return uniq; }); } /** A computed property which returns a new array with all the unique elements from an array, with uniqueness determined by specific key. Example ```javascript let Hamster = Ember.Object.extend({ uniqueFruits: Ember.computed.uniqBy('fruits', 'id') }); let hamster = Hamster.create({ fruits: [ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }, { id: 1, 'banana' } ] }); hamster.get('uniqueFruits'); // [ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }] ``` @method uniqBy @for Ember.computed @param {String} dependentKey @param {String} propertyKey @return {Ember.ComputedProperty} computes a new array with all the unique elements from the dependent array @public */ function uniqBy(dependentKey, propertyKey) { return _emberMetalComputed.computed(dependentKey + '.[]', function () { var uniq = _emberRuntimeSystemNative_array.A(); var seen = new _emberMetalEmpty_object.default(); var list = _emberMetalProperty_get.get(this, dependentKey); if (_emberRuntimeUtils.isArray(list)) { list.forEach(function (item) { var guid = _emberMetalUtils.guidFor(_emberMetalProperty_get.get(item, propertyKey)); if (!(guid in seen)) { seen[guid] = true; uniq.push(item); } }); } return uniq; }).readOnly(); } /** Alias for [Ember.computed.uniq](/api/#method_computed_uniq). @method union @for Ember.computed @param {String} propertyKey* @return {Ember.ComputedProperty} computes a new array with all the unique elements from the dependent array @public */ var union = uniq; exports.union = union; /** A computed property which returns a new array with all the duplicated elements from two or more dependent arrays. Example ```javascript let obj = Ember.Object.extend({ friendsInCommon: Ember.computed.intersect('adaFriends', 'charlesFriends') }).create({ adaFriends: ['Charles Babbage', 'John Hobhouse', 'William King', 'Mary Somerville'], charlesFriends: ['William King', 'Mary Somerville', 'Ada Lovelace', 'George Peacock'] }); obj.get('friendsInCommon'); // ['William King', 'Mary Somerville'] ``` @method intersect @for Ember.computed @param {String} propertyKey* @return {Ember.ComputedProperty} computes a new array with all the duplicated elements from the dependent arrays @public */ function intersect() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return multiArrayMacro(args, function (dependentKeys) { var _this3 = this; var arrays = dependentKeys.map(function (dependentKey) { var array = _emberMetalProperty_get.get(_this3, dependentKey); return _emberRuntimeUtils.isArray(array) ? array : []; }); var results = arrays.pop().filter(function (candidate) { for (var i = 0; i < arrays.length; i++) { var found = false; var array = arrays[i]; for (var j = 0; j < array.length; j++) { if (array[j] === candidate) { found = true; break; } } if (found === false) { return false; } } return true; }); return _emberRuntimeSystemNative_array.A(results); }); } /** A computed property which returns a new array with all the properties from the first dependent array that are not in the second dependent array. Example ```javascript let Hamster = Ember.Object.extend({ likes: ['banana', 'grape', 'kale'], wants: Ember.computed.setDiff('likes', 'fruits') }); let hamster = Hamster.create({ fruits: [ 'grape', 'kale', ] }); hamster.get('wants'); // ['banana'] ``` @method setDiff @for Ember.computed @param {String} setAProperty @param {String} setBProperty @return {Ember.ComputedProperty} computes a new array with all the items from the first dependent array that are not in the second dependent array @public */ function setDiff(setAProperty, setBProperty) { if (arguments.length !== 2) { throw new _emberMetalError.default('setDiff requires exactly two dependent arrays.'); } return _emberMetalComputed.computed(setAProperty + '.[]', setBProperty + '.[]', function () { var setA = this.get(setAProperty); var setB = this.get(setBProperty); if (!_emberRuntimeUtils.isArray(setA)) { return _emberRuntimeSystemNative_array.A(); } if (!_emberRuntimeUtils.isArray(setB)) { return _emberRuntimeSystemNative_array.A(setA); } return setA.filter(function (x) { return setB.indexOf(x) === -1; }); }).readOnly(); } /** A computed property that returns the array of values for the provided dependent properties. Example ```javascript let Hamster = Ember.Object.extend({ clothes: Ember.computed.collect('hat', 'shirt') }); let hamster = Hamster.create(); hamster.get('clothes'); // [null, null] hamster.set('hat', 'Camp Hat'); hamster.set('shirt', 'Camp Shirt'); hamster.get('clothes'); // ['Camp Hat', 'Camp Shirt'] ``` @method collect @for Ember.computed @param {String} dependentKey* @return {Ember.ComputedProperty} computed property which maps values of all passed in properties to an array. @public */ function collect() { for (var _len3 = arguments.length, dependentKeys = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { dependentKeys[_key3] = arguments[_key3]; } return multiArrayMacro(dependentKeys, function () { var properties = _emberMetalGet_properties.default(this, dependentKeys); var res = _emberRuntimeSystemNative_array.A(); for (var key in properties) { if (properties.hasOwnProperty(key)) { if (_emberMetalIs_none.default(properties[key])) { res.push(null); } else { res.push(properties[key]); } } } return res; }); } /** A computed property which returns a new array with all the properties from the first dependent array sorted based on a property or sort function. The callback method you provide should have the following signature: ```javascript function(itemA, itemB); ``` - `itemA` the first item to compare. - `itemB` the second item to compare. This function should return negative number (e.g. `-1`) when `itemA` should come before `itemB`. It should return positive number (e.g. `1`) when `itemA` should come after `itemB`. If the `itemA` and `itemB` are equal this function should return `0`. Therefore, if this function is comparing some numeric values, simple `itemA - itemB` or `itemA.get( 'foo' ) - itemB.get( 'foo' )` can be used instead of series of `if`. Example ```javascript let ToDoList = Ember.Object.extend({ // using standard ascending sort todosSorting: ['name'], sortedTodos: Ember.computed.sort('todos', 'todosSorting'), // using descending sort todosSortingDesc: ['name:desc'], sortedTodosDesc: Ember.computed.sort('todos', 'todosSortingDesc'), // using a custom sort function priorityTodos: Ember.computed.sort('todos', function(a, b){ if (a.priority > b.priority) { return 1; } else if (a.priority < b.priority) { return -1; } return 0; }) }); let todoList = ToDoList.create({todos: [ { name: 'Unit Test', priority: 2 }, { name: 'Documentation', priority: 3 }, { name: 'Release', priority: 1 } ]}); todoList.get('sortedTodos'); // [{ name:'Documentation', priority:3 }, { name:'Release', priority:1 }, { name:'Unit Test', priority:2 }] todoList.get('sortedTodosDesc'); // [{ name:'Unit Test', priority:2 }, { name:'Release', priority:1 }, { name:'Documentation', priority:3 }] todoList.get('priorityTodos'); // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }] ``` @method sort @for Ember.computed @param {String} itemsKey @param {String or Function} sortDefinition a dependent key to an array of sort properties (add `:desc` to the arrays sort properties to sort descending) or a function to use when sorting @return {Ember.ComputedProperty} computes a new sorted array based on the sort property array or callback function @public */ function sort(itemsKey, sortDefinition) { _emberMetalDebug.assert('Ember.computed.sort requires two arguments: an array key to sort and ' + 'either a sort properties key or sort function', arguments.length === 2); if (typeof sortDefinition === 'function') { return customSort(itemsKey, sortDefinition); } else { return propertySort(itemsKey, sortDefinition); } } function customSort(itemsKey, comparator) { return arrayMacro(itemsKey, function (value) { var _this4 = this; return value.slice().sort(function (x, y) { return comparator.call(_this4, x, y); }); }); } // This one needs to dynamically set up and tear down observers on the itemsKey // depending on the sortProperties function propertySort(itemsKey, sortPropertiesKey) { var cp = new _emberMetalComputed.ComputedProperty(function (key) { var _this5 = this; var itemsKeyIsAtThis = itemsKey === '@this'; var sortProperties = _emberMetalProperty_get.get(this, sortPropertiesKey); _emberMetalDebug.assert('The sort definition for \'' + key + '\' on ' + this + ' must be a function or an array of strings', _emberRuntimeUtils.isArray(sortProperties) && sortProperties.every(function (s) { return typeof s === 'string'; })); var normalizedSortProperties = normalizeSortProperties(sortProperties); // Add/remove property observers as required. var activeObserversMap = cp._activeObserverMap || (cp._activeObserverMap = new _emberMetalWeak_map.default()); var activeObservers = activeObserversMap.get(this); if (activeObservers) { activeObservers.forEach(function (args) { return _emberMetalObserver.removeObserver.apply(null, args); }); } function sortPropertyDidChange() { this.notifyPropertyChange(key); } activeObservers = normalizedSortProperties.map(function (_ref) { var prop = _ref[0]; var path = itemsKeyIsAtThis ? '@each.' + prop : itemsKey + '.@each.' + prop; var args = [_this5, path, sortPropertyDidChange]; _emberMetalObserver.addObserver.apply(null, args); return args; }); activeObserversMap.set(this, activeObservers); // Sort and return the array. var items = itemsKeyIsAtThis ? this : _emberMetalProperty_get.get(this, itemsKey); if (_emberRuntimeUtils.isArray(items)) { return sortByNormalizedSortProperties(items, normalizedSortProperties); } else { return _emberRuntimeSystemNative_array.A(); } }); cp._activeObserverMap = undefined; return cp.property(sortPropertiesKey + '.[]').readOnly(); } function normalizeSortProperties(sortProperties) { return sortProperties.map(function (p) { var _p$split = p.split(':'); var prop = _p$split[0]; var direction = _p$split[1]; direction = direction || 'asc'; return [prop, direction]; }); } function sortByNormalizedSortProperties(items, normalizedSortProperties) { return _emberRuntimeSystemNative_array.A(items.slice().sort(function (itemA, itemB) { for (var i = 0; i < normalizedSortProperties.length; i++) { var _normalizedSortProperties$i = normalizedSortProperties[i]; var prop = _normalizedSortProperties$i[0]; var direction = _normalizedSortProperties$i[1]; var result = _emberRuntimeCompare.default(_emberMetalProperty_get.get(itemA, prop), _emberMetalProperty_get.get(itemB, prop)); if (result !== 0) { return direction === 'desc' ? -1 * result : result; } } return 0; })); } }); enifed('ember-runtime/controllers/controller', ['exports', 'ember-metal/debug', 'ember-runtime/system/object', 'ember-runtime/mixins/controller', 'ember-runtime/inject', 'ember-runtime/mixins/action_handler'], function (exports, _emberMetalDebug, _emberRuntimeSystemObject, _emberRuntimeMixinsController, _emberRuntimeInject, _emberRuntimeMixinsAction_handler) { 'use strict'; /** @module ember @submodule ember-runtime */ /** @class Controller @namespace Ember @extends Ember.Object @uses Ember.ControllerMixin @public */ var Controller = _emberRuntimeSystemObject.default.extend(_emberRuntimeMixinsController.default); _emberRuntimeMixinsAction_handler.deprecateUnderscoreActions(Controller); function controllerInjectionHelper(factory) { _emberMetalDebug.assert('Defining an injected controller property on a ' + 'non-controller is not allowed.', _emberRuntimeMixinsController.default.detect(factory.PrototypeMixin)); } /** Creates a property that lazily looks up another controller in the container. Can only be used when defining another controller. Example: ```javascript App.PostController = Ember.Controller.extend({ posts: Ember.inject.controller() }); ``` This example will create a `posts` property on the `post` controller that looks up the `posts` controller in the container, making it easy to reference other controllers. This is functionally equivalent to: ```javascript App.PostController = Ember.Controller.extend({ needs: 'posts', posts: Ember.computed.alias('controllers.posts') }); ``` @method controller @since 1.10.0 @for Ember.inject @param {String} name (optional) name of the controller to inject, defaults to the property's name @return {Ember.InjectedProperty} injection descriptor instance @public */ _emberRuntimeInject.createInjectionHelper('controller', controllerInjectionHelper); exports.default = Controller; }); enifed('ember-runtime/copy', ['exports', 'ember-metal/debug', 'ember-runtime/system/object', 'ember-runtime/mixins/copyable'], function (exports, _emberMetalDebug, _emberRuntimeSystemObject, _emberRuntimeMixinsCopyable) { 'use strict'; exports.default = copy; function _copy(obj, deep, seen, copies) { var ret = undefined, loc = undefined, key = undefined; // primitive data types are immutable, just return them. if (typeof obj !== 'object' || obj === null) { return obj; } // avoid cyclical loops if (deep && (loc = seen.indexOf(obj)) >= 0) { return copies[loc]; } _emberMetalDebug.assert('Cannot clone an Ember.Object that does not implement Ember.Copyable', !(obj instanceof _emberRuntimeSystemObject.default) || _emberRuntimeMixinsCopyable.default && _emberRuntimeMixinsCopyable.default.detect(obj)); // IMPORTANT: this specific test will detect a native array only. Any other // object will need to implement Copyable. if (Array.isArray(obj)) { ret = obj.slice(); if (deep) { loc = ret.length; while (--loc >= 0) { ret[loc] = _copy(ret[loc], deep, seen, copies); } } } else if (_emberRuntimeMixinsCopyable.default && _emberRuntimeMixinsCopyable.default.detect(obj)) { ret = obj.copy(deep, seen, copies); } else if (obj instanceof Date) { ret = new Date(obj.getTime()); } else { ret = {}; for (key in obj) { // support Null prototype if (!Object.prototype.hasOwnProperty.call(obj, key)) { continue; } // Prevents browsers that don't respect non-enumerability from // copying internal Ember properties if (key.substring(0, 2) === '__') { continue; } ret[key] = deep ? _copy(obj[key], deep, seen, copies) : obj[key]; } } if (deep) { seen.push(obj); copies.push(ret); } return ret; } /** Creates a shallow copy of the passed object. A deep copy of the object is returned if the optional `deep` argument is `true`. If the passed object implements the `Ember.Copyable` interface, then this function will delegate to the object's `copy()` method and return the result. See `Ember.Copyable` for further details. For primitive values (which are immutable in JavaScript), the passed object is simply returned. @method copy @for Ember @param {Object} obj The object to clone @param {Boolean} [deep=false] If true, a deep copy of the object is made. @return {Object} The copied object @public */ function copy(obj, deep) { // fast paths if ('object' !== typeof obj || obj === null) { return obj; // can't copy primitives } if (_emberRuntimeMixinsCopyable.default && _emberRuntimeMixinsCopyable.default.detect(obj)) { return obj.copy(deep); } return _copy(obj, deep, deep ? [] : null, deep ? [] : null); } }); enifed('ember-runtime/ext/function', ['exports', 'ember-environment', 'ember-metal/debug', 'ember-metal/computed', 'ember-metal/mixin'], function (exports, _emberEnvironment, _emberMetalDebug, _emberMetalComputed, _emberMetalMixin) { /** @module ember @submodule ember-runtime */ 'use strict'; var a_slice = Array.prototype.slice; var FunctionPrototype = Function.prototype; if (_emberEnvironment.ENV.EXTEND_PROTOTYPES.Function) { /** The `property` extension of Javascript's Function prototype is available when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is `true`, which is the default. Computed properties allow you to treat a function like a property: ```javascript MyApp.President = Ember.Object.extend({ firstName: '', lastName: '', fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); }.property() // Call this flag to mark the function as a property }); let president = MyApp.President.create({ firstName: 'Barack', lastName: 'Obama' }); president.get('fullName'); // 'Barack Obama' ``` Treating a function like a property is useful because they can work with bindings, just like any other property. Many computed properties have dependencies on other properties. For example, in the above example, the `fullName` property depends on `firstName` and `lastName` to determine its value. You can tell Ember about these dependencies like this: ```javascript MyApp.President = Ember.Object.extend({ firstName: '', lastName: '', fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); // Tell Ember.js that this computed property depends on firstName // and lastName }.property('firstName', 'lastName') }); ``` Make sure you list these dependencies so Ember knows when to update bindings that connect to a computed property. Changing a dependency will not immediately trigger an update of the computed property, but will instead clear the cache so that it is updated when the next `get` is called on the property. See [Ember.ComputedProperty](/api/classes/Ember.ComputedProperty.html), [Ember.computed](/api/classes/Ember.computed.html). @method property @for Function @public */ FunctionPrototype.property = function () { var ret = _emberMetalComputed.computed(this); // ComputedProperty.prototype.property expands properties; no need for us to // do so here. return ret.property.apply(ret, arguments); }; /** The `observes` extension of Javascript's Function prototype is available when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is true, which is the default. You can observe property changes simply by adding the `observes` call to the end of your method declarations in classes that you write. For example: ```javascript Ember.Object.extend({ valueObserver: function() { // Executes whenever the "value" property changes }.observes('value') }); ``` In the future this method may become asynchronous. See `Ember.observer`. @method observes @for Function @public */ FunctionPrototype.observes = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.push(this); return _emberMetalMixin.observer.apply(this, args); }; FunctionPrototype._observesImmediately = function () { _emberMetalDebug.assert('Immediate observers must observe internal properties only, ' + 'not properties on other objects.', function checkIsInternalProperty() { for (var i = 0; i < arguments.length; i++) { if (arguments[i].indexOf('.') !== -1) { return false; } } return true; }); // observes handles property expansion return this.observes.apply(this, arguments); }; /** The `observesImmediately` extension of Javascript's Function prototype is available when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is true, which is the default. You can observe property changes simply by adding the `observesImmediately` call to the end of your method declarations in classes that you write. For example: ```javascript Ember.Object.extend({ valueObserver: function() { // Executes immediately after the "value" property changes }.observesImmediately('value') }); ``` In the future, `observes` may become asynchronous. In this event, `observesImmediately` will maintain the synchronous behavior. See `Ember.immediateObserver`. @method observesImmediately @for Function @deprecated @private */ FunctionPrototype.observesImmediately = _emberMetalDebug.deprecateFunc('Function#observesImmediately is deprecated. Use Function#observes instead', { id: 'ember-runtime.ext-function', until: '3.0.0' }, FunctionPrototype._observesImmediately); /** The `on` extension of Javascript's Function prototype is available when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is true, which is the default. You can listen for events simply by adding the `on` call to the end of your method declarations in classes or mixins that you write. For example: ```javascript Ember.Mixin.create({ doSomethingWithElement: function() { // Executes whenever the "didInsertElement" event fires }.on('didInsertElement') }); ``` See `Ember.on`. @method on @for Function @public */ FunctionPrototype.on = function () { var events = a_slice.call(arguments); this.__ember_listens__ = events; return this; }; } }); enifed('ember-runtime/ext/rsvp', ['exports', 'rsvp', 'ember-metal/run_loop', 'ember-metal/debug', 'ember-metal/error_handler'], function (exports, _rsvp, _emberMetalRun_loop, _emberMetalDebug, _emberMetalError_handler) { 'use strict'; exports.onerrorDefault = onerrorDefault; var backburner = _emberMetalRun_loop.default.backburner; _emberMetalRun_loop.default._addQueue('rsvpAfter', 'destroy'); _rsvp.configure('async', function (callback, promise) { backburner.schedule('actions', null, callback, promise); }); _rsvp.configure('after', function (cb) { backburner.schedule('rsvpAfter', null, cb); }); _rsvp.on('error', onerrorDefault); function onerrorDefault(reason) { var error = errorFor(reason); if (error) { _emberMetalError_handler.dispatchError(error); } } function errorFor(reason) { if (!reason) return; if (reason.errorThrown) { return unwrapErrorThrown(reason); } if (reason.name === 'UnrecognizedURLError') { _emberMetalDebug.assert('The URL \'' + reason.message + '\' did not match any routes in your application', false); return; } if (reason.name === 'TransitionAborted') { return; } return reason; } function unwrapErrorThrown(reason) { var error = reason.errorThrown; if (typeof error === 'string') { error = new Error(error); } Object.defineProperty(error, '__reason_with_error_thrown__', { value: reason, enumerable: false }); return error; } exports.default = _rsvp; }); enifed('ember-runtime/ext/string', ['exports', 'ember-environment', 'ember-runtime/system/string'], function (exports, _emberEnvironment, _emberRuntimeSystemString) { /** @module ember @submodule ember-runtime */ 'use strict'; var StringPrototype = String.prototype; if (_emberEnvironment.ENV.EXTEND_PROTOTYPES.String) { /** See [Ember.String.fmt](/api/classes/Ember.String.html#method_fmt). @method fmt @for String @private @deprecated */ StringPrototype.fmt = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _emberRuntimeSystemString.fmt(this, args); }; /** See [Ember.String.w](/api/classes/Ember.String.html#method_w). @method w @for String @private */ StringPrototype.w = function () { return _emberRuntimeSystemString.w(this); }; /** See [Ember.String.loc](/api/classes/Ember.String.html#method_loc). @method loc @for String @private */ StringPrototype.loc = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return _emberRuntimeSystemString.loc(this, args); }; /** See [Ember.String.camelize](/api/classes/Ember.String.html#method_camelize). @method camelize @for String @private */ StringPrototype.camelize = function () { return _emberRuntimeSystemString.camelize(this); }; /** See [Ember.String.decamelize](/api/classes/Ember.String.html#method_decamelize). @method decamelize @for String @private */ StringPrototype.decamelize = function () { return _emberRuntimeSystemString.decamelize(this); }; /** See [Ember.String.dasherize](/api/classes/Ember.String.html#method_dasherize). @method dasherize @for String @private */ StringPrototype.dasherize = function () { return _emberRuntimeSystemString.dasherize(this); }; /** See [Ember.String.underscore](/api/classes/Ember.String.html#method_underscore). @method underscore @for String @private */ StringPrototype.underscore = function () { return _emberRuntimeSystemString.underscore(this); }; /** See [Ember.String.classify](/api/classes/Ember.String.html#method_classify). @method classify @for String @private */ StringPrototype.classify = function () { return _emberRuntimeSystemString.classify(this); }; /** See [Ember.String.capitalize](/api/classes/Ember.String.html#method_capitalize). @method capitalize @for String @private */ StringPrototype.capitalize = function () { return _emberRuntimeSystemString.capitalize(this); }; } }); enifed('ember-runtime/index', ['exports', 'ember-metal', 'ember-runtime/is-equal', 'ember-runtime/compare', 'ember-runtime/copy', 'ember-runtime/inject', 'ember-runtime/system/namespace', 'ember-runtime/system/object', 'ember-runtime/system/container', 'ember-runtime/system/array_proxy', 'ember-runtime/system/object_proxy', 'ember-runtime/system/core_object', 'ember-runtime/system/native_array', 'ember-runtime/system/string', 'ember-runtime/system/lazy_load', 'ember-runtime/mixins/array', 'ember-runtime/mixins/comparable', 'ember-runtime/mixins/copyable', 'ember-runtime/mixins/enumerable', 'ember-runtime/mixins/freezable', 'ember-runtime/mixins/-proxy', 'ember-runtime/mixins/observable', 'ember-runtime/mixins/action_handler', 'ember-runtime/mixins/mutable_enumerable', 'ember-runtime/mixins/mutable_array', 'ember-runtime/mixins/target_action_support', 'ember-runtime/mixins/evented', 'ember-runtime/mixins/promise_proxy', 'ember-metal/features', 'ember-runtime/computed/computed_macros', 'ember-runtime/computed/reduce_computed_macros', 'ember-runtime/controllers/controller', 'ember-runtime/mixins/controller', 'ember-runtime/system/service', 'ember-runtime/ext/rsvp', 'ember-runtime/ext/string', 'ember-runtime/ext/function', 'ember-runtime/utils', 'ember-runtime/mixins/registry_proxy', 'ember-runtime/mixins/container_proxy', 'ember-runtime/string_registry'], function (exports, _emberMetal, _emberRuntimeIsEqual, _emberRuntimeCompare, _emberRuntimeCopy, _emberRuntimeInject, _emberRuntimeSystemNamespace, _emberRuntimeSystemObject, _emberRuntimeSystemContainer, _emberRuntimeSystemArray_proxy, _emberRuntimeSystemObject_proxy, _emberRuntimeSystemCore_object, _emberRuntimeSystemNative_array, _emberRuntimeSystemString, _emberRuntimeSystemLazy_load, _emberRuntimeMixinsArray, _emberRuntimeMixinsComparable, _emberRuntimeMixinsCopyable, _emberRuntimeMixinsEnumerable, _emberRuntimeMixinsFreezable, _emberRuntimeMixinsProxy, _emberRuntimeMixinsObservable, _emberRuntimeMixinsAction_handler, _emberRuntimeMixinsMutable_enumerable, _emberRuntimeMixinsMutable_array, _emberRuntimeMixinsTarget_action_support, _emberRuntimeMixinsEvented, _emberRuntimeMixinsPromise_proxy, _emberMetalFeatures, _emberRuntimeComputedComputed_macros, _emberRuntimeComputedReduce_computed_macros, _emberRuntimeControllersController, _emberRuntimeMixinsController, _emberRuntimeSystemService, _emberRuntimeExtRsvp, _emberRuntimeExtString, _emberRuntimeExtFunction, _emberRuntimeUtils, _emberRuntimeMixinsRegistry_proxy, _emberRuntimeMixinsContainer_proxy, _emberRuntimeString_registry) { /** @module ember @submodule ember-runtime */ // BEGIN IMPORTS 'use strict'; // END IMPORTS // BEGIN EXPORTS _emberMetal.default.compare = _emberRuntimeCompare.default; _emberMetal.default.copy = _emberRuntimeCopy.default; _emberMetal.default.isEqual = _emberRuntimeIsEqual.default; _emberMetal.default.inject = _emberRuntimeInject.default; _emberMetal.default.Array = _emberRuntimeMixinsArray.default; _emberMetal.default.Comparable = _emberRuntimeMixinsComparable.default; _emberMetal.default.Copyable = _emberRuntimeMixinsCopyable.default; _emberMetal.default.Freezable = _emberRuntimeMixinsFreezable.Freezable; _emberMetal.default.FROZEN_ERROR = _emberRuntimeMixinsFreezable.FROZEN_ERROR; _emberMetal.default.MutableEnumerable = _emberRuntimeMixinsMutable_enumerable.default; _emberMetal.default.MutableArray = _emberRuntimeMixinsMutable_array.default; _emberMetal.default.TargetActionSupport = _emberRuntimeMixinsTarget_action_support.default; _emberMetal.default.Evented = _emberRuntimeMixinsEvented.default; _emberMetal.default.PromiseProxyMixin = _emberRuntimeMixinsPromise_proxy.default; _emberMetal.default.Observable = _emberRuntimeMixinsObservable.default; _emberMetal.default.typeOf = _emberRuntimeUtils.typeOf; _emberMetal.default.isArray = _emberRuntimeUtils.isArray; // ES6TODO: this seems a less than ideal way/place to add properties to Ember.computed var EmComputed = _emberMetal.default.computed; EmComputed.empty = _emberRuntimeComputedComputed_macros.empty; EmComputed.notEmpty = _emberRuntimeComputedComputed_macros.notEmpty; EmComputed.none = _emberRuntimeComputedComputed_macros.none; EmComputed.not = _emberRuntimeComputedComputed_macros.not; EmComputed.bool = _emberRuntimeComputedComputed_macros.bool; EmComputed.match = _emberRuntimeComputedComputed_macros.match; EmComputed.equal = _emberRuntimeComputedComputed_macros.equal; EmComputed.gt = _emberRuntimeComputedComputed_macros.gt; EmComputed.gte = _emberRuntimeComputedComputed_macros.gte; EmComputed.lt = _emberRuntimeComputedComputed_macros.lt; EmComputed.lte = _emberRuntimeComputedComputed_macros.lte; EmComputed.oneWay = _emberRuntimeComputedComputed_macros.oneWay; EmComputed.reads = _emberRuntimeComputedComputed_macros.oneWay; EmComputed.readOnly = _emberRuntimeComputedComputed_macros.readOnly; EmComputed.defaultTo = _emberRuntimeComputedComputed_macros.defaultTo; EmComputed.deprecatingAlias = _emberRuntimeComputedComputed_macros.deprecatingAlias; EmComputed.and = _emberRuntimeComputedComputed_macros.and; EmComputed.or = _emberRuntimeComputedComputed_macros.or; EmComputed.any = _emberRuntimeComputedComputed_macros.any; EmComputed.sum = _emberRuntimeComputedReduce_computed_macros.sum; EmComputed.min = _emberRuntimeComputedReduce_computed_macros.min; EmComputed.max = _emberRuntimeComputedReduce_computed_macros.max; EmComputed.map = _emberRuntimeComputedReduce_computed_macros.map; EmComputed.sort = _emberRuntimeComputedReduce_computed_macros.sort; EmComputed.setDiff = _emberRuntimeComputedReduce_computed_macros.setDiff; EmComputed.mapBy = _emberRuntimeComputedReduce_computed_macros.mapBy; EmComputed.filter = _emberRuntimeComputedReduce_computed_macros.filter; EmComputed.filterBy = _emberRuntimeComputedReduce_computed_macros.filterBy; EmComputed.uniq = _emberRuntimeComputedReduce_computed_macros.uniq; if (true) { EmComputed.uniqBy = _emberRuntimeComputedReduce_computed_macros.uniqBy; } EmComputed.union = _emberRuntimeComputedReduce_computed_macros.union; EmComputed.intersect = _emberRuntimeComputedReduce_computed_macros.intersect; EmComputed.collect = _emberRuntimeComputedReduce_computed_macros.collect; _emberMetal.default.String = _emberRuntimeSystemString.default; _emberMetal.default.Object = _emberRuntimeSystemObject.default; _emberMetal.default.Container = _emberRuntimeSystemContainer.Container; _emberMetal.default.Registry = _emberRuntimeSystemContainer.Registry; _emberMetal.default.getOwner = _emberRuntimeSystemContainer.getOwner; _emberMetal.default.setOwner = _emberRuntimeSystemContainer.setOwner; _emberMetal.default._RegistryProxyMixin = _emberRuntimeMixinsRegistry_proxy.default; _emberMetal.default._ContainerProxyMixin = _emberRuntimeMixinsContainer_proxy.default; _emberMetal.default.Namespace = _emberRuntimeSystemNamespace.default; _emberMetal.default.Enumerable = _emberRuntimeMixinsEnumerable.default; _emberMetal.default.ArrayProxy = _emberRuntimeSystemArray_proxy.default; _emberMetal.default.ObjectProxy = _emberRuntimeSystemObject_proxy.default; _emberMetal.default.ActionHandler = _emberRuntimeMixinsAction_handler.default; _emberMetal.default.CoreObject = _emberRuntimeSystemCore_object.default; _emberMetal.default.NativeArray = _emberRuntimeSystemNative_array.default; // ES6TODO: Currently we must rely on the global from ember-metal/core to avoid circular deps // Ember.A = A; _emberMetal.default.onLoad = _emberRuntimeSystemLazy_load.onLoad; _emberMetal.default.runLoadHooks = _emberRuntimeSystemLazy_load.runLoadHooks; _emberMetal.default.Controller = _emberRuntimeControllersController.default; _emberMetal.default.ControllerMixin = _emberRuntimeMixinsController.default; _emberMetal.default.Service = _emberRuntimeSystemService.default; _emberMetal.default._ProxyMixin = _emberRuntimeMixinsProxy.default; _emberMetal.default.RSVP = _emberRuntimeExtRsvp.default; // END EXPORTS /** Defines the hash of localized strings for the current language. Used by the `Ember.String.loc()` helper. To localize, add string values to this hash. @property STRINGS @for Ember @type Object @private */ Object.defineProperty(_emberMetal.default, 'STRINGS', { configurable: false, get: _emberRuntimeString_registry.getStrings, set: _emberRuntimeString_registry.setStrings }); /** Whether searching on the global for new Namespace instances is enabled. This is only exported here as to not break any addons. Given the new visit API, you will have issues if you treat this as a indicator of booted. Internally this is only exposing a flag in Namespace. @property BOOTED @for Ember @type Boolean @private */ Object.defineProperty(_emberMetal.default, 'BOOTED', { configurable: false, enumerable: false, get: _emberRuntimeSystemNamespace.isSearchDisabled, set: _emberRuntimeSystemNamespace.setSearchDisabled }); exports.default = _emberMetal.default; }); // reexports // just for side effect of extending Ember.RSVP // just for side effect of extending String.prototype // just for side effect of extending Function.prototype enifed('ember-runtime/inject', ['exports', 'ember-metal/debug', 'ember-metal/injected_property'], function (exports, _emberMetalDebug, _emberMetalInjected_property) { 'use strict'; exports.default = inject; exports.createInjectionHelper = createInjectionHelper; exports.validatePropertyInjections = validatePropertyInjections; /** Namespace for injection helper methods. @class inject @namespace Ember @static @public */ function inject() { _emberMetalDebug.assert('Injected properties must be created through helpers, see \'' + Object.keys(inject).join('"', '"') + '\''); } // Dictionary of injection validations by type, added to by `createInjectionHelper` var typeValidators = {}; /** This method allows other Ember modules to register injection helpers for a given container type. Helpers are exported to the `inject` namespace as the container type itself. @private @method createInjectionHelper @since 1.10.0 @for Ember @param {String} type The container type the helper will inject @param {Function} validator A validation callback that is executed at mixin-time */ function createInjectionHelper(type, validator) { typeValidators[type] = validator; inject[type] = function (name) { return new _emberMetalInjected_property.default(type, name); }; } /** Validation function that runs per-type validation functions once for each injected type encountered. @private @method validatePropertyInjections @since 1.10.0 @for Ember @param {Object} factory The factory object */ function validatePropertyInjections(factory) { var proto = factory.proto(); var types = []; for (var key in proto) { var desc = proto[key]; if (desc instanceof _emberMetalInjected_property.default && types.indexOf(desc.type) === -1) { types.push(desc.type); } } if (types.length) { for (var i = 0; i < types.length; i++) { var validator = typeValidators[types[i]]; if (typeof validator === 'function') { validator(factory); } } } return true; } }); enifed('ember-runtime/is-equal', ['exports'], function (exports) { /** Compares two objects, returning true if they are equal. ```javascript Ember.isEqual('hello', 'hello'); // true Ember.isEqual(1, 2); // false ``` `isEqual` is a more specific comparison than a triple equal comparison. It will call the `isEqual` instance method on the objects being compared, allowing finer control over when objects should be considered equal to each other. ```javascript let Person = Ember.Object.extend({ isEqual(other) { return this.ssn == other.ssn; } }); let personA = Person.create({name: 'Muhammad Ali', ssn: '123-45-6789'}); let personB = Person.create({name: 'Cassius Clay', ssn: '123-45-6789'}); Ember.isEqual(personA, personB); // true ``` Due to the expense of array comparisons, collections will never be equal to each other even if each of their items are equal to each other. ```javascript Ember.isEqual([4, 2], [4, 2]); // false ``` @method isEqual @for Ember @param {Object} a first object to compare @param {Object} b second object to compare @return {Boolean} @public */ 'use strict'; exports.default = isEqual; function isEqual(a, b) { if (a && typeof a.isEqual === 'function') { return a.isEqual(b); } if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime(); } return a === b; } }); enifed('ember-runtime/mixins/-proxy', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/meta', 'ember-metal/observer', 'ember-metal/property_events', 'ember-runtime/computed/computed_macros', 'ember-metal/properties', 'ember-metal/mixin', 'ember-metal/symbol'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalMeta, _emberMetalObserver, _emberMetalProperty_events, _emberRuntimeComputedComputed_macros, _emberMetalProperties, _emberMetalMixin, _emberMetalSymbol) { /** @module ember @submodule ember-runtime */ 'use strict'; var _Mixin$create; exports.isProxy = isProxy; var IS_PROXY = _emberMetalSymbol.default('IS_PROXY'); function isProxy(value) { return value && value[IS_PROXY]; } function contentPropertyWillChange(content, contentKey) { var key = contentKey.slice(8); // remove "content." if (key in this) { return; } // if shadowed in proxy _emberMetalProperty_events.propertyWillChange(this, key); } function contentPropertyDidChange(content, contentKey) { var key = contentKey.slice(8); // remove "content." if (key in this) { return; } // if shadowed in proxy _emberMetalProperty_events.propertyDidChange(this, key); } /** `Ember.ProxyMixin` forwards all properties not defined by the proxy itself to a proxied `content` object. See Ember.ObjectProxy for more details. @class ProxyMixin @namespace Ember @private */ exports.default = _emberMetalMixin.Mixin.create((_Mixin$create = {}, _Mixin$create[IS_PROXY] = true, _Mixin$create.content = null, _Mixin$create._contentDidChange = _emberMetalMixin.observer('content', function () { _emberMetalDebug.assert('Can\'t set Proxy\'s content to itself', _emberMetalProperty_get.get(this, 'content') !== this); }), _Mixin$create.isTruthy = _emberRuntimeComputedComputed_macros.bool('content'), _Mixin$create._debugContainerKey = null, _Mixin$create.willWatchProperty = function (key) { var contentKey = 'content.' + key; _emberMetalObserver._addBeforeObserver(this, contentKey, null, contentPropertyWillChange); _emberMetalObserver.addObserver(this, contentKey, null, contentPropertyDidChange); }, _Mixin$create.didUnwatchProperty = function (key) { var contentKey = 'content.' + key; _emberMetalObserver._removeBeforeObserver(this, contentKey, null, contentPropertyWillChange); _emberMetalObserver.removeObserver(this, contentKey, null, contentPropertyDidChange); }, _Mixin$create.unknownProperty = function (key) { var content = _emberMetalProperty_get.get(this, 'content'); if (content) { _emberMetalDebug.deprecate('You attempted to access `' + key + '` from `' + this + '`, but object proxying is deprecated. Please use `model.' + key + '` instead.', !this.isController, { id: 'ember-runtime.controller-proxy', until: '3.0.0' }); return _emberMetalProperty_get.get(content, key); } }, _Mixin$create.setUnknownProperty = function (key, value) { var m = _emberMetalMeta.meta(this); if (m.proto === this) { // if marked as prototype then just defineProperty // rather than delegate _emberMetalProperties.defineProperty(this, key, null, value); return value; } var content = _emberMetalProperty_get.get(this, 'content'); _emberMetalDebug.assert('Cannot delegate set(\'' + key + '\', ' + value + ') to the \'content\' property of object proxy ' + this + ': its \'content\' is undefined.', content); _emberMetalDebug.deprecate('You attempted to set `' + key + '` from `' + this + '`, but object proxying is deprecated. Please use `model.' + key + '` instead.', !this.isController, { id: 'ember-runtime.controller-proxy', until: '3.0.0' }); return _emberMetalProperty_set.set(content, key, value); }, _Mixin$create)); }); /** The object whose properties will be forwarded. @property content @type Ember.Object @default null @private */ enifed('ember-runtime/mixins/action_handler', ['exports', 'ember-metal/debug', 'ember-metal/mixin', 'ember-metal/property_get'], function (exports, _emberMetalDebug, _emberMetalMixin, _emberMetalProperty_get) { /** @module ember @submodule ember-runtime */ 'use strict'; exports.deprecateUnderscoreActions = deprecateUnderscoreActions; /** `Ember.ActionHandler` is available on some familiar classes including `Ember.Route`, `Ember.View`, `Ember.Component`, and `Ember.Controller`. (Internally the mixin is used by `Ember.CoreView`, `Ember.ControllerMixin`, and `Ember.Route` and available to the above classes through inheritance.) @class ActionHandler @namespace Ember @private */ var ActionHandler = _emberMetalMixin.Mixin.create({ mergedProperties: ['actions'], /** The collection of functions, keyed by name, available on this `ActionHandler` as action targets. These functions will be invoked when a matching `{{action}}` is triggered from within a template and the application's current route is this route. Actions can also be invoked from other parts of your application via `ActionHandler#send`. The `actions` hash will inherit action handlers from the `actions` hash defined on extended parent classes or mixins rather than just replace the entire hash, e.g.: ```js App.CanDisplayBanner = Ember.Mixin.create({ actions: { displayBanner(msg) { // ... } } }); App.WelcomeRoute = Ember.Route.extend(App.CanDisplayBanner, { actions: { playMusic() { // ... } } }); // `WelcomeRoute`, when active, will be able to respond // to both actions, since the actions hash is merged rather // then replaced when extending mixins / parent classes. this.send('displayBanner'); this.send('playMusic'); ``` Within a Controller, Route, View or Component's action handler, the value of the `this` context is the Controller, Route, View or Component object: ```js App.SongRoute = Ember.Route.extend({ actions: { myAction() { this.controllerFor("song"); this.transitionTo("other.route"); ... } } }); ``` It is also possible to call `this._super(...arguments)` from within an action handler if it overrides a handler defined on a parent class or mixin: Take for example the following routes: ```js App.DebugRoute = Ember.Mixin.create({ actions: { debugRouteInformation() { console.debug("trololo"); } } }); App.AnnoyingDebugRoute = Ember.Route.extend(App.DebugRoute, { actions: { debugRouteInformation() { // also call the debugRouteInformation of mixed in App.DebugRoute this._super(...arguments); // show additional annoyance window.alert(...); } } }); ``` ## Bubbling By default, an action will stop bubbling once a handler defined on the `actions` hash handles it. To continue bubbling the action, you must return `true` from the handler: ```js App.Router.map(function() { this.route("album", function() { this.route("song"); }); }); App.AlbumRoute = Ember.Route.extend({ actions: { startPlaying: function() { } } }); App.AlbumSongRoute = Ember.Route.extend({ actions: { startPlaying() { // ... if (actionShouldAlsoBeTriggeredOnParentRoute) { return true; } } } }); ``` @property actions @type Object @default null @public */ /** Triggers a named action on the `ActionHandler`. Any parameters supplied after the `actionName` string will be passed as arguments to the action target function. If the `ActionHandler` has its `target` property set, actions may bubble to the `target`. Bubbling happens when an `actionName` can not be found in the `ActionHandler`'s `actions` hash or if the action target function returns `true`. Example ```js App.WelcomeRoute = Ember.Route.extend({ actions: { playTheme() { this.send('playMusic', 'theme.mp3'); }, playMusic(track) { // ... } } }); ``` @method send @param {String} actionName The action to trigger @param {*} context a context to send with the action @public */ send: function (actionName) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var target = undefined; if (this.actions && this.actions[actionName]) { var shouldBubble = this.actions[actionName].apply(this, args) === true; if (!shouldBubble) { return; } } if (target = _emberMetalProperty_get.get(this, 'target')) { var _target; _emberMetalDebug.assert('The `target` for ' + this + ' (' + target + ') does not have a `send` method', typeof target.send === 'function'); (_target = target).send.apply(_target, arguments); } }, willMergeMixin: function (props) { _emberMetalDebug.assert('Specifying `_actions` and `actions` in the same mixin is not supported.', !props.actions || !props._actions); if (props._actions) { _emberMetalDebug.deprecate('Specifying actions in `_actions` is deprecated, please use `actions` instead.', false, { id: 'ember-runtime.action-handler-_actions', until: '3.0.0' }); props.actions = props._actions; delete props._actions; } } }); exports.default = ActionHandler; function deprecateUnderscoreActions(factory) { Object.defineProperty(factory.prototype, '_actions', { configurable: true, enumerable: false, set: function (value) { _emberMetalDebug.assert('You cannot set `_actions` on ' + this + ', please use `actions` instead.'); }, get: function () { _emberMetalDebug.deprecate('Usage of `_actions` is deprecated, use `actions` instead.', false, { id: 'ember-runtime.action-handler-_actions', until: '3.0.0' }); return _emberMetalProperty_get.get(this, 'actions'); } }); } }); enifed('ember-runtime/mixins/array', ['exports', 'ember-metal/core', 'ember-metal/symbol', 'ember-metal/property_get', 'ember-metal/computed', 'ember-metal/is_none', 'ember-runtime/mixins/enumerable', 'ember-metal/mixin', 'ember-metal/property_events', 'ember-metal/events', 'ember-metal/meta', 'ember-metal/tags', 'ember-runtime/system/each_proxy', 'ember-metal/debug', 'ember-metal/features'], function (exports, _emberMetalCore, _emberMetalSymbol, _emberMetalProperty_get, _emberMetalComputed, _emberMetalIs_none, _emberRuntimeMixinsEnumerable, _emberMetalMixin, _emberMetalProperty_events, _emberMetalEvents, _emberMetalMeta, _emberMetalTags, _emberRuntimeSystemEach_proxy, _emberMetalDebug, _emberMetalFeatures) { /** @module ember @submodule ember-runtime */ // .......................................................... // HELPERS // 'use strict'; var _Mixin$create; exports.addArrayObserver = addArrayObserver; exports.removeArrayObserver = removeArrayObserver; exports.objectAt = objectAt; exports.arrayContentWillChange = arrayContentWillChange; exports.arrayContentDidChange = arrayContentDidChange; exports.isEmberArray = isEmberArray; function arrayObserversHelper(obj, target, opts, operation, notify) { var willChange = opts && opts.willChange || 'arrayWillChange'; var didChange = opts && opts.didChange || 'arrayDidChange'; var hasObservers = _emberMetalProperty_get.get(obj, 'hasArrayObservers'); if (hasObservers === notify) { _emberMetalProperty_events.propertyWillChange(obj, 'hasArrayObservers'); } operation(obj, '@array:before', target, willChange); operation(obj, '@array:change', target, didChange); if (hasObservers === notify) { _emberMetalProperty_events.propertyDidChange(obj, 'hasArrayObservers'); } return obj; } function addArrayObserver(array, target, opts) { return arrayObserversHelper(array, target, opts, _emberMetalEvents.addListener, false); } function removeArrayObserver(array, target, opts) { return arrayObserversHelper(array, target, opts, _emberMetalEvents.removeListener, true); } function objectAt(content, idx) { if (content.objectAt) { return content.objectAt(idx); } return content[idx]; } function arrayContentWillChange(array, startIdx, removeAmt, addAmt) { var removing = undefined, lim = undefined; // if no args are passed assume everything changes if (startIdx === undefined) { startIdx = 0; removeAmt = addAmt = -1; } else { if (removeAmt === undefined) { removeAmt = -1; } if (addAmt === undefined) { addAmt = -1; } } if (array.__each) { array.__each.arrayWillChange(array, startIdx, removeAmt, addAmt); } _emberMetalEvents.sendEvent(array, '@array:before', [array, startIdx, removeAmt, addAmt]); if (startIdx >= 0 && removeAmt >= 0 && _emberMetalProperty_get.get(array, 'hasEnumerableObservers')) { removing = []; lim = startIdx + removeAmt; for (var idx = startIdx; idx < lim; idx++) { removing.push(objectAt(array, idx)); } } else { removing = removeAmt; } array.enumerableContentWillChange(removing, addAmt); return array; } function arrayContentDidChange(array, startIdx, removeAmt, addAmt) { _emberMetalTags.markObjectAsDirty(_emberMetalMeta.meta(array)); // if no args are passed assume everything changes if (startIdx === undefined) { startIdx = 0; removeAmt = addAmt = -1; } else { if (removeAmt === undefined) { removeAmt = -1; } if (addAmt === undefined) { addAmt = -1; } } var adding = undefined; if (startIdx >= 0 && addAmt >= 0 && _emberMetalProperty_get.get(array, 'hasEnumerableObservers')) { adding = []; var lim = startIdx + addAmt; for (var idx = startIdx; idx < lim; idx++) { adding.push(objectAt(array, idx)); } } else { adding = addAmt; } array.enumerableContentDidChange(removeAmt, adding); if (array.__each) { array.__each.arrayDidChange(array, startIdx, removeAmt, addAmt); } _emberMetalEvents.sendEvent(array, '@array:change', [array, startIdx, removeAmt, addAmt]); var length = _emberMetalProperty_get.get(array, 'length'); var cachedFirst = _emberMetalComputed.cacheFor(array, 'firstObject'); var cachedLast = _emberMetalComputed.cacheFor(array, 'lastObject'); if (objectAt(array, 0) !== cachedFirst) { _emberMetalProperty_events.propertyWillChange(array, 'firstObject'); _emberMetalProperty_events.propertyDidChange(array, 'firstObject'); } if (objectAt(array, length - 1) !== cachedLast) { _emberMetalProperty_events.propertyWillChange(array, 'lastObject'); _emberMetalProperty_events.propertyDidChange(array, 'lastObject'); } return array; } var EMBER_ARRAY = _emberMetalSymbol.default('EMBER_ARRAY'); function isEmberArray(obj) { return obj && !!obj[EMBER_ARRAY]; } // .......................................................... // ARRAY // /** This mixin implements Observer-friendly Array-like behavior. It is not a concrete implementation, but it can be used up by other classes that want to appear like arrays. For example, ArrayProxy is a concrete classes that can be instantiated to implement array-like behavior. Both of these classes use the Array Mixin by way of the MutableArray mixin, which allows observable changes to be made to the underlying array. Unlike `Ember.Enumerable,` this mixin defines methods specifically for collections that provide index-ordered access to their contents. When you are designing code that needs to accept any kind of Array-like object, you should use these methods instead of Array primitives because these will properly notify observers of changes to the array. Although these methods are efficient, they do add a layer of indirection to your application so it is a good idea to use them only when you need the flexibility of using both true JavaScript arrays and "virtual" arrays such as controllers and collections. You can use the methods defined in this module to access and modify array contents in a KVO-friendly way. You can also be notified whenever the membership of an array changes by using `.observes('myArray.[]')`. To support `Ember.Array` in your own class, you must override two primitives to use it: `length()` and `objectAt()`. Note that the Ember.Array mixin also incorporates the `Ember.Enumerable` mixin. All `Ember.Array`-like objects are also enumerable. @class Array @namespace Ember @uses Ember.Enumerable @since Ember 0.9.0 @public */ var ArrayMixin = _emberMetalMixin.Mixin.create(_emberRuntimeMixinsEnumerable.default, (_Mixin$create = {}, _Mixin$create[EMBER_ARRAY] = true, _Mixin$create.length = null, _Mixin$create.objectAt = function (idx) { if (idx < 0 || idx >= _emberMetalProperty_get.get(this, 'length')) { return undefined; } return _emberMetalProperty_get.get(this, idx); }, _Mixin$create.objectsAt = function (indexes) { var _this = this; return indexes.map(function (idx) { return objectAt(_this, idx); }); }, _Mixin$create.nextObject = function (idx) { return objectAt(this, idx); }, _Mixin$create['[]'] = _emberMetalComputed.computed({ get: function (key) { return this; }, set: function (key, value) { this.replace(0, _emberMetalProperty_get.get(this, 'length'), value); return this; } }), _Mixin$create.firstObject = _emberMetalComputed.computed(function () { return objectAt(this, 0); }).readOnly(), _Mixin$create.lastObject = _emberMetalComputed.computed(function () { return objectAt(this, _emberMetalProperty_get.get(this, 'length') - 1); }).readOnly(), _Mixin$create.contains = function (obj) { if (true) { _emberMetalDebug.deprecate('`Enumerable#contains` is deprecated, use `Enumerable#includes` instead.', false, { id: 'ember-runtime.enumerable-contains', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_enumerable-contains' }); } return this.indexOf(obj) >= 0; }, _Mixin$create.slice = function (beginIndex, endIndex) { var ret = _emberMetalCore.default.A(); var length = _emberMetalProperty_get.get(this, 'length'); if (_emberMetalIs_none.default(beginIndex)) { beginIndex = 0; } if (_emberMetalIs_none.default(endIndex) || endIndex > length) { endIndex = length; } if (beginIndex < 0) { beginIndex = length + beginIndex; } if (endIndex < 0) { endIndex = length + endIndex; } while (beginIndex < endIndex) { ret[ret.length] = objectAt(this, beginIndex++); } return ret; }, _Mixin$create.indexOf = function (object, startAt) { var len = _emberMetalProperty_get.get(this, 'length'); if (startAt === undefined) { startAt = 0; } if (startAt < 0) { startAt += len; } for (var idx = startAt; idx < len; idx++) { if (objectAt(this, idx) === object) { return idx; } } return -1; }, _Mixin$create.lastIndexOf = function (object, startAt) { var len = _emberMetalProperty_get.get(this, 'length'); if (startAt === undefined || startAt >= len) { startAt = len - 1; } if (startAt < 0) { startAt += len; } for (var idx = startAt; idx >= 0; idx--) { if (objectAt(this, idx) === object) { return idx; } } return -1; }, _Mixin$create.addArrayObserver = function (target, opts) { return addArrayObserver(this, target, opts); }, _Mixin$create.removeArrayObserver = function (target, opts) { return removeArrayObserver(this, target, opts); }, _Mixin$create.hasArrayObservers = _emberMetalComputed.computed(function () { return _emberMetalEvents.hasListeners(this, '@array:change') || _emberMetalEvents.hasListeners(this, '@array:before'); }), _Mixin$create.arrayContentWillChange = function (startIdx, removeAmt, addAmt) { return arrayContentWillChange(this, startIdx, removeAmt, addAmt); }, _Mixin$create.arrayContentDidChange = function (startIdx, removeAmt, addAmt) { return arrayContentDidChange(this, startIdx, removeAmt, addAmt); }, _Mixin$create['@each'] = _emberMetalComputed.computed(function () { // TODO use Symbol or add to meta if (!this.__each) { this.__each = new _emberRuntimeSystemEach_proxy.default(this); } return this.__each; }).volatile(), _Mixin$create)); if (true) { ArrayMixin.reopen({ /** Returns `true` if the passed object can be found in the array. This method is a Polyfill for ES 2016 Array.includes. If no `startAt` argument is given, the starting location to search is 0. If it's negative, searches from the index of `this.length + startAt` by asc. ```javascript [1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false [1, 2, 3].includes(3, 2); // true [1, 2, 3].includes(3, 3); // false [1, 2, 3].includes(3, -1); // true [1, 2, 3].includes(1, -1); // false [1, 2, 3].includes(1, -4); // true [1, 2, NaN].includes(NaN); // true ``` @method includes @param {Object} obj The object to search for. @param {Number} startAt optional starting location to search, default 0 @return {Boolean} `true` if object is found in the array. @public */ includes: function (obj, startAt) { var len = _emberMetalProperty_get.get(this, 'length'); if (startAt === undefined) { startAt = 0; } if (startAt < 0) { startAt += len; } for (var idx = startAt; idx < len; idx++) { var currentObj = objectAt(this, idx); // SameValueZero comparison (NaN !== NaN) if (obj === currentObj || obj !== obj && currentObj !== currentObj) { return true; } } return false; } }); } exports.default = ArrayMixin; }); // ES6TODO: Ember.A /** __Required.__ You must implement this method to apply this mixin. Your array must support the `length` property. Your replace methods should set this property whenever it changes. @property {Number} length @public */ /** Returns the object at the given `index`. If the given `index` is negative or is greater or equal than the array length, returns `undefined`. This is one of the primitives you must implement to support `Ember.Array`. If your object supports retrieving the value of an array item using `get()` (i.e. `myArray.get(0)`), then you do not need to implement this method yourself. ```javascript let arr = ['a', 'b', 'c', 'd']; arr.objectAt(0); // 'a' arr.objectAt(3); // 'd' arr.objectAt(-1); // undefined arr.objectAt(4); // undefined arr.objectAt(5); // undefined ``` @method objectAt @param {Number} idx The index of the item to return. @return {*} item at index or undefined @public */ /** This returns the objects at the specified indexes, using `objectAt`. ```javascript let arr = ['a', 'b', 'c', 'd']; arr.objectsAt([0, 1, 2]); // ['a', 'b', 'c'] arr.objectsAt([2, 3, 4]); // ['c', 'd', undefined] ``` @method objectsAt @param {Array} indexes An array of indexes of items to return. @return {Array} @public */ // overrides Ember.Enumerable version /** This is the handler for the special array content property. If you get this property, it will return this. If you set this property to a new array, it will replace the current content. This property overrides the default property defined in `Ember.Enumerable`. @property [] @return this @public */ // optimized version from Enumerable // Add any extra methods to Ember.Array that are native to the built-in Array. /** Returns a new array that is a slice of the receiver. This implementation uses the observable array methods to retrieve the objects for the new slice. ```javascript let arr = ['red', 'green', 'blue']; arr.slice(0); // ['red', 'green', 'blue'] arr.slice(0, 2); // ['red', 'green'] arr.slice(1, 100); // ['green', 'blue'] ``` @method slice @param {Number} beginIndex (Optional) index to begin slicing from. @param {Number} endIndex (Optional) index to end the slice at (but not included). @return {Array} New array with specified slice @public */ /** Returns the index of the given object's first occurrence. If no `startAt` argument is given, the starting location to search is 0. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. ```javascript let arr = ['a', 'b', 'c', 'd', 'a']; arr.indexOf('a'); // 0 arr.indexOf('z'); // -1 arr.indexOf('a', 2); // 4 arr.indexOf('a', -1); // 4 arr.indexOf('b', 3); // -1 arr.indexOf('a', 100); // -1 ``` @method indexOf @param {Object} object the item to search for @param {Number} startAt optional starting location to search, default 0 @return {Number} index or -1 if not found @public */ /** Returns the index of the given object's last occurrence. If no `startAt` argument is given, the search starts from the last position. If it's negative, will count backward from the end of the array. Returns -1 if no match is found. ```javascript let arr = ['a', 'b', 'c', 'd', 'a']; arr.lastIndexOf('a'); // 4 arr.lastIndexOf('z'); // -1 arr.lastIndexOf('a', 2); // 0 arr.lastIndexOf('a', -1); // 4 arr.lastIndexOf('b', 3); // 1 arr.lastIndexOf('a', 100); // 4 ``` @method lastIndexOf @param {Object} object the item to search for @param {Number} startAt optional starting location to search, default 0 @return {Number} index or -1 if not found @public */ // .......................................................... // ARRAY OBSERVERS // /** Adds an array observer to the receiving array. The array observer object normally must implement two methods: * `arrayWillChange(observedObj, start, removeCount, addCount)` - This method will be called just before the array is modified. * `arrayDidChange(observedObj, start, removeCount, addCount)` - This method will be called just after the array is modified. Both callbacks will be passed the observed object, starting index of the change as well as a count of the items to be removed and added. You can use these callbacks to optionally inspect the array during the change, clear caches, or do any other bookkeeping necessary. In addition to passing a target, you can also include an options hash which you can use to override the method names that will be invoked on the target. @method addArrayObserver @param {Object} target The observer object. @param {Object} opts Optional hash of configuration options including `willChange` and `didChange` option. @return {Ember.Array} receiver @public */ /** Removes an array observer from the object if the observer is current registered. Calling this method multiple times with the same object will have no effect. @method removeArrayObserver @param {Object} target The object observing the array. @param {Object} opts Optional hash of configuration options including `willChange` and `didChange` option. @return {Ember.Array} receiver @public */ /** Becomes true whenever the array currently has observers watching changes on the array. @property {Boolean} hasArrayObservers @public */ /** If you are implementing an object that supports `Ember.Array`, call this method just before the array content changes to notify any observers and invalidate any related properties. Pass the starting index of the change as well as a delta of the amounts to change. @method arrayContentWillChange @param {Number} startIdx The starting index in the array that will change. @param {Number} removeAmt The number of items that will be removed. If you pass `null` assumes 0 @param {Number} addAmt The number of items that will be added. If you pass `null` assumes 0. @return {Ember.Array} receiver @public */ /** If you are implementing an object that supports `Ember.Array`, call this method just after the array content changes to notify any observers and invalidate any related properties. Pass the starting index of the change as well as a delta of the amounts to change. @method arrayContentDidChange @param {Number} startIdx The starting index in the array that did change. @param {Number} removeAmt The number of items that were removed. If you pass `null` assumes 0 @param {Number} addAmt The number of items that were added. If you pass `null` assumes 0. @return {Ember.Array} receiver @public */ /** Returns a special object that can be used to observe individual properties on the array. Just get an equivalent property on this object and it will return an enumerable that maps automatically to the named key on the member objects. `@each` should only be used in a non-terminal context. Example: ```javascript myMethod: computed('posts.@each.author', function(){ ... }); ``` If you merely want to watch for the array being changed, like an object being replaced, added or removed, use `[]` instead of `@each`. ```javascript myMethod: computed('posts.[]', function(){ ... }); ``` @property @each @public */ enifed('ember-runtime/mixins/comparable', ['exports', 'ember-metal/mixin'], function (exports, _emberMetalMixin) { 'use strict'; /** @module ember @submodule ember-runtime */ /** Implements some standard methods for comparing objects. Add this mixin to any class you create that can compare its instances. You should implement the `compare()` method. @class Comparable @namespace Ember @since Ember 0.9 @private */ exports.default = _emberMetalMixin.Mixin.create({ /** __Required.__ You must implement this method to apply this mixin. Override to return the result of the comparison of the two parameters. The compare method should return: - `-1` if `a < b` - `0` if `a == b` - `1` if `a > b` Default implementation raises an exception. @method compare @param a {Object} the first object to compare @param b {Object} the second object to compare @return {Number} the result of the comparison @private */ compare: null }); }); enifed('ember-runtime/mixins/container_proxy', ['exports', 'ember-metal/run_loop', 'ember-metal/debug', 'ember-metal/mixin'], function (exports, _emberMetalRun_loop, _emberMetalDebug, _emberMetalMixin) { /** @module ember @submodule ember-runtime */ 'use strict'; exports.buildFakeContainerWithDeprecations = buildFakeContainerWithDeprecations; /** ContainerProxyMixin is used to provide public access to specific container functionality. @class ContainerProxyMixin @private */ exports.default = _emberMetalMixin.Mixin.create({ /** The container stores state. @private @property {Ember.Container} __container__ */ __container__: null, /** Returns an object that can be used to provide an owner to a manually created instance. Example: ``` let owner = Ember.getOwner(this); User.create( owner.ownerInjection(), { username: 'rwjblue' } ) ``` @public @method ownerInjection @return {Object} */ ownerInjection: function () { return this.__container__.ownerInjection(); }, /** Given a fullName return a corresponding instance. The default behaviour is for lookup to return a singleton instance. The singleton is scoped to the container, allowing multiple containers to all have their own locally scoped singletons. ```javascript let registry = new Registry(); let container = registry.container(); registry.register('api:twitter', Twitter); let twitter = container.lookup('api:twitter'); twitter instanceof Twitter; // => true // by default the container will return singletons let twitter2 = container.lookup('api:twitter'); twitter2 instanceof Twitter; // => true twitter === twitter2; //=> true ``` If singletons are not wanted an optional flag can be provided at lookup. ```javascript let registry = new Registry(); let container = registry.container(); registry.register('api:twitter', Twitter); let twitter = container.lookup('api:twitter', { singleton: false }); let twitter2 = container.lookup('api:twitter', { singleton: false }); twitter === twitter2; //=> false ``` @public @method lookup @param {String} fullName @param {Object} options @return {any} */ lookup: function (fullName, options) { return this.__container__.lookup(fullName, options); }, /** Given a fullName return the corresponding factory. @private @method _lookupFactory @param {String} fullName @return {any} */ _lookupFactory: function (fullName, options) { return this.__container__.lookupFactory(fullName, options); }, /** Given a name and a source path, resolve the fullName @private @method _resolveLocalLookupName @param {String} fullName @param {String} source @return {String} */ _resolveLocalLookupName: function (name, source) { return this.__container__.registry.expandLocalLookup('component:' + name, { source: source }); }, /** @private */ willDestroy: function () { this._super.apply(this, arguments); if (this.__container__) { _emberMetalRun_loop.default(this.__container__, 'destroy'); } } }); function buildFakeContainerWithDeprecations(container) { var fakeContainer = {}; var propertyMappings = { lookup: 'lookup', lookupFactory: '_lookupFactory' }; for (var containerProperty in propertyMappings) { fakeContainer[containerProperty] = buildFakeContainerFunction(container, containerProperty, propertyMappings[containerProperty]); } return fakeContainer; } function buildFakeContainerFunction(container, containerProperty, ownerProperty) { return function () { _emberMetalDebug.deprecate('Using the injected `container` is deprecated. Please use the `getOwner` helper to access the owner of this object and then call `' + ownerProperty + '` instead.', false, { id: 'ember-application.injected-container', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_injected-container-access' }); return container[containerProperty].apply(container, arguments); }; } }); enifed('ember-runtime/mixins/controller', ['exports', 'ember-metal/mixin', 'ember-metal/alias', 'ember-runtime/mixins/action_handler', 'ember-runtime/mixins/controller_content_model_alias_deprecation'], function (exports, _emberMetalMixin, _emberMetalAlias, _emberRuntimeMixinsAction_handler, _emberRuntimeMixinsController_content_model_alias_deprecation) { 'use strict'; /** @class ControllerMixin @namespace Ember @uses Ember.ActionHandler @private */ exports.default = _emberMetalMixin.Mixin.create(_emberRuntimeMixinsAction_handler.default, _emberRuntimeMixinsController_content_model_alias_deprecation.default, { /* ducktype as a controller */ isController: true, /** The object to which actions from the view should be sent. For example, when a Handlebars template uses the `{{action}}` helper, it will attempt to send the action to the view's controller's `target`. By default, the value of the target property is set to the router, and is injected when a controller is instantiated. This injection is applied as part of the application's initialization process. In most cases the `target` property will automatically be set to the logical consumer of actions for the controller. @property target @default null @public */ target: null, store: null, /** The controller's current model. When retrieving or modifying a controller's model, this property should be used instead of the `content` property. @property model @public */ model: null, /** @private */ content: _emberMetalAlias.default('model') }); }); enifed('ember-runtime/mixins/controller_content_model_alias_deprecation', ['exports', 'ember-metal/debug', 'ember-metal/mixin'], function (exports, _emberMetalDebug, _emberMetalMixin) { 'use strict'; /* The ControllerContentModelAliasDeprecation mixin is used to provide a useful deprecation warning when specifying `content` directly on a `Ember.Controller` (without also specifying `model`). Ember versions prior to 1.7 used `model` as an alias of `content`, but due to much confusion this alias was reversed (so `content` is now an alias of `model). This change reduces many caveats with model/content, and also sets a simple ground rule: Never set a controllers content, rather always set its model and ember will do the right thing. Used internally by Ember in `Ember.Controller`. */ exports.default = _emberMetalMixin.Mixin.create({ /** @private Moves `content` to `model` at extend time if a `model` is not also specified. Note that this currently modifies the mixin themselves, which is technically dubious but is practically of little consequence. This may change in the future. @method willMergeMixin @since 1.4.0 */ willMergeMixin: function (props) { // Calling super is only OK here since we KNOW that // there is another Mixin loaded first. this._super.apply(this, arguments); var modelSpecified = !!props.model; if (props.content && !modelSpecified) { props.model = props.content; delete props['content']; _emberMetalDebug.deprecate('Do not specify `content` on a Controller, use `model` instead.', false, { id: 'ember-runtime.will-merge-mixin', until: '3.0.0' }); } } }); }); enifed('ember-runtime/mixins/copyable', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/mixin', 'ember-runtime/mixins/freezable', 'ember-metal/error'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalMixin, _emberRuntimeMixinsFreezable, _emberMetalError) { /** @module ember @submodule ember-runtime */ 'use strict'; /** Implements some standard methods for copying an object. Add this mixin to any object you create that can create a copy of itself. This mixin is added automatically to the built-in array. You should generally implement the `copy()` method to return a copy of the receiver. Note that `frozenCopy()` will only work if you also implement `Ember.Freezable`. @class Copyable @namespace Ember @since Ember 0.9 @private */ exports.default = _emberMetalMixin.Mixin.create({ /** __Required.__ You must implement this method to apply this mixin. Override to return a copy of the receiver. Default implementation raises an exception. @method copy @param {Boolean} deep if `true`, a deep copy of the object should be made @return {Object} copy of receiver @private */ copy: null, /** If the object implements `Ember.Freezable`, then this will return a new copy if the object is not frozen and the receiver if the object is frozen. Raises an exception if you try to call this method on a object that does not support freezing. You should use this method whenever you want a copy of a freezable object since a freezable object can simply return itself without actually consuming more memory. @method frozenCopy @return {Object} copy of receiver or receiver @deprecated Use `Object.freeze` instead. @private */ frozenCopy: function () { _emberMetalDebug.deprecate('`frozenCopy` is deprecated, use `Object.freeze` instead.', false, { id: 'ember-runtime.frozen-copy', until: '3.0.0' }); if (_emberRuntimeMixinsFreezable.Freezable && _emberRuntimeMixinsFreezable.Freezable.detect(this)) { return _emberMetalProperty_get.get(this, 'isFrozen') ? this : this.copy().freeze(); } else { throw new _emberMetalError.default(this + ' does not support freezing'); } } }); }); enifed('ember-runtime/mixins/enumerable', ['exports', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/mixin', 'ember-metal/utils', 'ember-metal/computed', 'ember-metal/empty_object', 'ember-metal/features', 'ember-metal/property_events', 'ember-metal/events', 'ember-runtime/compare', 'require', 'ember-metal/debug'], function (exports, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalMixin, _emberMetalUtils, _emberMetalComputed, _emberMetalEmpty_object, _emberMetalFeatures, _emberMetalProperty_events, _emberMetalEvents, _emberRuntimeCompare, _require, _emberMetalDebug) { /** @module ember @submodule ember-runtime */ // .......................................................... // HELPERS // 'use strict'; var _emberA = undefined; function emberA() { return (_emberA || (_emberA = _require.default('ember-runtime/system/native_array').A))(); } var contexts = []; function popCtx() { return contexts.length === 0 ? {} : contexts.pop(); } function pushCtx(ctx) { contexts.push(ctx); return null; } function iter(key, value) { var valueProvided = arguments.length === 2; function i(item) { var cur = _emberMetalProperty_get.get(item, key); return valueProvided ? value === cur : !!cur; } return i; } /** This mixin defines the common interface implemented by enumerable objects in Ember. Most of these methods follow the standard Array iteration API defined up to JavaScript 1.8 (excluding language-specific features that cannot be emulated in older versions of JavaScript). This mixin is applied automatically to the Array class on page load, so you can use any of these methods on simple arrays. If Array already implements one of these methods, the mixin will not override them. ## Writing Your Own Enumerable To make your own custom class enumerable, you need two items: 1. You must have a length property. This property should change whenever the number of items in your enumerable object changes. If you use this with an `Ember.Object` subclass, you should be sure to change the length property using `set().` 2. You must implement `nextObject().` See documentation. Once you have these two methods implemented, apply the `Ember.Enumerable` mixin to your class and you will be able to enumerate the contents of your object like any other collection. ## Using Ember Enumeration with Other Libraries Many other libraries provide some kind of iterator or enumeration like facility. This is often where the most common API conflicts occur. Ember's API is designed to be as friendly as possible with other libraries by implementing only methods that mostly correspond to the JavaScript 1.8 API. @class Enumerable @namespace Ember @since Ember 0.9 @private */ var Enumerable = _emberMetalMixin.Mixin.create({ /** __Required.__ You must implement this method to apply this mixin. Implement this method to make your class enumerable. This method will be called repeatedly during enumeration. The index value will always begin with 0 and increment monotonically. You don't have to rely on the index value to determine what object to return, but you should always check the value and start from the beginning when you see the requested index is 0. The `previousObject` is the object that was returned from the last call to `nextObject` for the current iteration. This is a useful way to manage iteration if you are tracing a linked list, for example. Finally the context parameter will always contain a hash you can use as a "scratchpad" to maintain any other state you need in order to iterate properly. The context object is reused and is not reset between iterations so make sure you setup the context with a fresh state whenever the index parameter is 0. Generally iterators will continue to call `nextObject` until the index reaches the current length-1. If you run out of data before this time for some reason, you should simply return undefined. The default implementation of this method simply looks up the index. This works great on any Array-like objects. @method nextObject @param {Number} index the current index of the iteration @param {Object} previousObject the value returned by the last call to `nextObject`. @param {Object} context a context object you can use to maintain state. @return {Object} the next object in the iteration or undefined @private */ nextObject: null, /** Helper method returns the first object from a collection. This is usually used by bindings and other parts of the framework to extract a single object if the enumerable contains only one item. If you override this method, you should implement it so that it will always return the same value each time it is called. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. ```javascript let arr = ['a', 'b', 'c']; arr.get('firstObject'); // 'a' let arr = []; arr.get('firstObject'); // undefined ``` @property firstObject @return {Object} the object or undefined @readOnly @public */ firstObject: _emberMetalComputed.computed('[]', function () { if (_emberMetalProperty_get.get(this, 'length') === 0) { return undefined; } // handle generic enumerables var context = popCtx(); var ret = this.nextObject(0, null, context); pushCtx(context); return ret; }).readOnly(), /** Helper method returns the last object from a collection. If your enumerable contains only one object, this method should always return that object. If your enumerable is empty, this method should return `undefined`. ```javascript let arr = ['a', 'b', 'c']; arr.get('lastObject'); // 'c' let arr = []; arr.get('lastObject'); // undefined ``` @property lastObject @return {Object} the last object or undefined @readOnly @public */ lastObject: _emberMetalComputed.computed('[]', function () { var len = _emberMetalProperty_get.get(this, 'length'); if (len === 0) { return undefined; } var context = popCtx(); var idx = 0; var last = null; var cur = undefined; do { last = cur; cur = this.nextObject(idx++, last, context); } while (cur !== undefined); pushCtx(context); return last; }).readOnly(), /** Returns `true` if the passed object can be found in the receiver. The default version will iterate through the enumerable until the object is found. You may want to override this with a more efficient version. ```javascript let arr = ['a', 'b', 'c']; arr.contains('a'); // true arr.contains('z'); // false ``` @method contains @deprecated Use `Enumerable#includes` instead. See http://emberjs.com/deprecations/v2.x#toc_enumerable-contains @param {Object} obj The object to search for. @return {Boolean} `true` if object is found in enumerable. @public */ contains: function (obj) { if (true) { _emberMetalDebug.deprecate('`Enumerable#contains` is deprecated, use `Enumerable#includes` instead.', false, { id: 'ember-runtime.enumerable-contains', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_enumerable-contains' }); } var found = this.find(function (item) { return item === obj; }); return found !== undefined; }, /** Iterates through the enumerable, calling the passed function on each item. This method corresponds to the `forEach()` method defined in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. @method forEach @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Object} receiver @public */ forEach: function (callback, target) { if (typeof callback !== 'function') { throw new TypeError(); } var context = popCtx(); var len = _emberMetalProperty_get.get(this, 'length'); var last = null; if (target === undefined) { target = null; } for (var idx = 0; idx < len; idx++) { var next = this.nextObject(idx, last, context); callback.call(target, next, idx, this); last = next; } last = null; context = pushCtx(context); return this; }, /** Alias for `mapBy` @method getEach @param {String} key name of the property @return {Array} The mapped array. @public */ getEach: _emberMetalMixin.aliasMethod('mapBy'), /** Sets the value on the named property for each member. This is more ergonomic than using other methods defined on this helper. If the object implements Ember.Observable, the value will be changed to `set(),` otherwise it will be set directly. `null` objects are skipped. @method setEach @param {String} key The key to set @param {Object} value The object to set @return {Object} receiver @public */ setEach: function (key, value) { return this.forEach(function (item) { return _emberMetalProperty_set.set(item, key, value); }); }, /** Maps all of the items in the enumeration to another value, returning a new array. This method corresponds to `map()` defined in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the mapped value. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. @method map @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Array} The mapped array. @public */ map: function (callback, target) { var ret = emberA(); this.forEach(function (x, idx, i) { return ret[idx] = callback.call(target, x, idx, i); }); return ret; }, /** Similar to map, this specialized function returns the value of the named property on all items in the enumeration. @method mapBy @param {String} key name of the property @return {Array} The mapped array. @public */ mapBy: function (key) { return this.map(function (next) { return _emberMetalProperty_get.get(next, key); }); }, /** Returns an array with all of the items in the enumeration that the passed function returns true for. This method corresponds to `filter()` defined in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return `true` to include the item in the results, `false` otherwise. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. @method filter @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Array} A filtered array. @public */ filter: function (callback, target) { var ret = emberA(); this.forEach(function (x, idx, i) { if (callback.call(target, x, idx, i)) { ret.push(x); } }); return ret; }, /** Returns an array with all of the items in the enumeration where the passed function returns false. This method is the inverse of filter(). The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - *item* is the current item in the iteration. - *index* is the current index in the iteration - *enumerable* is the enumerable object itself. It should return a falsey value to include the item in the results. Note that in addition to a callback, you can also pass an optional target object that will be set as "this" on the context. This is a good way to give your iterator function access to the current object. @method reject @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Array} A rejected array. @public */ reject: function (callback, target) { return this.filter(function () { return !callback.apply(target, arguments); }); }, /** Returns an array with just the items with the matched property. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. @method filterBy @param {String} key the property to test @param {*} [value] optional value to test against. @return {Array} filtered array @public */ filterBy: function (key, value) { return this.filter(iter.apply(this, arguments)); }, /** Returns an array with the items that do not have truthy values for key. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to false. @method rejectBy @param {String} key the property to test @param {String} [value] optional value to test against. @return {Array} rejected array @public */ rejectBy: function (key, value) { var exactValue = function (item) { return _emberMetalProperty_get.get(item, key) === value; }; var hasValue = function (item) { return !!_emberMetalProperty_get.get(item, key); }; var use = arguments.length === 2 ? exactValue : hasValue; return this.reject(use); }, /** Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the `true` to include the item in the results, `false` otherwise. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. @method find @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Object} Found item or `undefined`. @public */ find: function (callback, target) { var len = _emberMetalProperty_get.get(this, 'length'); if (target === undefined) { target = null; } var context = popCtx(); var found = false; var last = null; var next = undefined, ret = undefined; for (var idx = 0; idx < len && !found; idx++) { next = this.nextObject(idx, last, context); if (found = callback.call(target, next, idx, this)) { ret = next; } last = next; } next = last = null; context = pushCtx(context); return ret; }, /** Returns the first item with a property matching the passed value. You can pass an optional second argument with the target value. Otherwise this will match any property that evaluates to `true`. This method works much like the more generic `find()` method. @method findBy @param {String} key the property to test @param {String} [value] optional value to test against. @return {Object} found item or `undefined` @public */ findBy: function (key, value) { return this.find(iter.apply(this, arguments)); }, /** Returns `true` if the passed function returns true for every item in the enumeration. This corresponds with the `every()` method in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the `true` or `false`. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. Example Usage: ```javascript if (people.every(isEngineer)) { Paychecks.addBigBonus(); } ``` @method every @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Boolean} @public */ every: function (callback, target) { return !this.find(function (x, idx, i) { return !callback.call(target, x, idx, i); }); }, /** Returns `true` if the passed property resolves to the value of the second argument for all items in the enumerable. This method is often simpler/faster than using a callback. @method isEvery @param {String} key the property to test @param {String} [value] optional value to test against. Defaults to `true` @return {Boolean} @since 1.3.0 @public */ isEvery: function (key, value) { return this.every(iter.apply(this, arguments)); }, /** Returns `true` if the passed function returns true for any item in the enumeration. This corresponds with the `some()` method in JavaScript 1.6. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, enumerable); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. It should return the `true` to include the item in the results, `false` otherwise. Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. This is a good way to give your iterator function access to the current object. Usage Example: ```javascript if (people.any(isManager)) { Paychecks.addBiggerBonus(); } ``` @method any @param {Function} callback The callback to execute @param {Object} [target] The target object to use @return {Boolean} `true` if the passed function returns `true` for any item @public */ any: function (callback, target) { var len = _emberMetalProperty_get.get(this, 'length'); var context = popCtx(); var found = false; var last = null; var next = undefined; if (target === undefined) { target = null; } for (var idx = 0; idx < len && !found; idx++) { next = this.nextObject(idx, last, context); found = callback.call(target, next, idx, this); last = next; } next = last = null; context = pushCtx(context); return found; }, /** Returns `true` if the passed property resolves to the value of the second argument for any item in the enumerable. This method is often simpler/faster than using a callback. @method isAny @param {String} key the property to test @param {String} [value] optional value to test against. Defaults to `true` @return {Boolean} @since 1.3.0 @public */ isAny: function (key, value) { return this.any(iter.apply(this, arguments)); }, /** This will combine the values of the enumerator into a single value. It is a useful way to collect a summary value from an enumeration. This corresponds to the `reduce()` method defined in JavaScript 1.8. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(previousValue, item, index, enumerable); ``` - `previousValue` is the value returned by the last call to the iterator. - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `enumerable` is the enumerable object itself. Return the new cumulative value. In addition to the callback you can also pass an `initialValue`. An error will be raised if you do not pass an initial value and the enumerator is empty. Note that unlike the other methods, this method does not allow you to pass a target object to set as this for the callback. It's part of the spec. Sorry. @method reduce @param {Function} callback The callback to execute @param {Object} initialValue Initial value for the reduce @param {String} reducerProperty internal use only. @return {Object} The reduced value. @public */ reduce: function (callback, initialValue, reducerProperty) { if (typeof callback !== 'function') { throw new TypeError(); } var ret = initialValue; this.forEach(function (item, i) { ret = callback(ret, item, i, this, reducerProperty); }, this); return ret; }, /** Invokes the named method on every object in the receiver that implements it. This method corresponds to the implementation in Prototype 1.6. @method invoke @param {String} methodName the name of the method @param {Object...} args optional arguments to pass as well. @return {Array} return values from calling invoke. @public */ invoke: function (methodName) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var ret = emberA(); this.forEach(function (x, idx) { var method = x && x[methodName]; if ('function' === typeof method) { ret[idx] = args ? method.apply(x, args) : x[methodName](); } }, this); return ret; }, /** Simply converts the enumerable into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. @method toArray @return {Array} the enumerable as an array. @public */ toArray: function () { var ret = emberA(); this.forEach(function (o, idx) { return ret[idx] = o; }); return ret; }, /** Returns a copy of the array with all `null` and `undefined` elements removed. ```javascript let arr = ['a', null, 'c', undefined]; arr.compact(); // ['a', 'c'] ``` @method compact @return {Array} the array without null and undefined elements. @public */ compact: function () { return this.filter(function (value) { return value != null; }); }, /** Returns a new enumerable that excludes the passed value. The default implementation returns an array regardless of the receiver type. If the receiver does not contain the value it returns the original enumerable. ```javascript let arr = ['a', 'b', 'a', 'c']; arr.without('a'); // ['b', 'c'] ``` @method without @param {Object} value @return {Ember.Enumerable} @public */ without: function (value) { if (!this.contains(value)) { return this; // nothing to do } var ret = emberA(); this.forEach(function (k) { if (k !== value) { ret[ret.length] = k; } }); return ret; }, /** Returns a new enumerable that contains only unique values. The default implementation returns an array regardless of the receiver type. ```javascript let arr = ['a', 'a', 'b', 'b']; arr.uniq(); // ['a', 'b'] ``` This only works on primitive data types, e.g. Strings, Numbers, etc. @method uniq @return {Ember.Enumerable} @public */ uniq: function () { var ret = emberA(); this.forEach(function (k) { if (ret.indexOf(k) < 0) { ret.push(k); } }); return ret; }, /** This property will trigger anytime the enumerable's content changes. You can observe this property to be notified of changes to the enumerable's content. For plain enumerables, this property is read only. `Array` overrides this method. @property [] @type Array @return this @private */ '[]': _emberMetalComputed.computed({ get: function (key) { return this; } }), // .......................................................... // ENUMERABLE OBSERVERS // /** Registers an enumerable observer. Must implement `Ember.EnumerableObserver` mixin. @method addEnumerableObserver @param {Object} target @param {Object} [opts] @return this @private */ addEnumerableObserver: function (target, opts) { var willChange = opts && opts.willChange || 'enumerableWillChange'; var didChange = opts && opts.didChange || 'enumerableDidChange'; var hasObservers = _emberMetalProperty_get.get(this, 'hasEnumerableObservers'); if (!hasObservers) { _emberMetalProperty_events.propertyWillChange(this, 'hasEnumerableObservers'); } _emberMetalEvents.addListener(this, '@enumerable:before', target, willChange); _emberMetalEvents.addListener(this, '@enumerable:change', target, didChange); if (!hasObservers) { _emberMetalProperty_events.propertyDidChange(this, 'hasEnumerableObservers'); } return this; }, /** Removes a registered enumerable observer. @method removeEnumerableObserver @param {Object} target @param {Object} [opts] @return this @private */ removeEnumerableObserver: function (target, opts) { var willChange = opts && opts.willChange || 'enumerableWillChange'; var didChange = opts && opts.didChange || 'enumerableDidChange'; var hasObservers = _emberMetalProperty_get.get(this, 'hasEnumerableObservers'); if (hasObservers) { _emberMetalProperty_events.propertyWillChange(this, 'hasEnumerableObservers'); } _emberMetalEvents.removeListener(this, '@enumerable:before', target, willChange); _emberMetalEvents.removeListener(this, '@enumerable:change', target, didChange); if (hasObservers) { _emberMetalProperty_events.propertyDidChange(this, 'hasEnumerableObservers'); } return this; }, /** Becomes true whenever the array currently has observers watching changes on the array. @property hasEnumerableObservers @type Boolean @private */ hasEnumerableObservers: _emberMetalComputed.computed(function () { return _emberMetalEvents.hasListeners(this, '@enumerable:change') || _emberMetalEvents.hasListeners(this, '@enumerable:before'); }), /** Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. @method enumerableContentWillChange @param {Ember.Enumerable|Number} removing An enumerable of the objects to be removed or the number of items to be removed. @param {Ember.Enumerable|Number} adding An enumerable of the objects to be added or the number of items to be added. @chainable @private */ enumerableContentWillChange: function (removing, adding) { var removeCnt = undefined, addCnt = undefined, hasDelta = undefined; if ('number' === typeof removing) { removeCnt = removing; } else if (removing) { removeCnt = _emberMetalProperty_get.get(removing, 'length'); } else { removeCnt = removing = -1; } if ('number' === typeof adding) { addCnt = adding; } else if (adding) { addCnt = _emberMetalProperty_get.get(adding, 'length'); } else { addCnt = adding = -1; } hasDelta = addCnt < 0 || removeCnt < 0 || addCnt - removeCnt !== 0; if (removing === -1) { removing = null; } if (adding === -1) { adding = null; } _emberMetalProperty_events.propertyWillChange(this, '[]'); if (hasDelta) { _emberMetalProperty_events.propertyWillChange(this, 'length'); } _emberMetalEvents.sendEvent(this, '@enumerable:before', [this, removing, adding]); return this; }, /** Invoke this method when the contents of your enumerable has changed. This will notify any observers watching for content changes. If you are implementing an ordered enumerable (such as an array), also pass the start and end values where the content changed so that it can be used to notify range observers. @method enumerableContentDidChange @param {Ember.Enumerable|Number} removing An enumerable of the objects to be removed or the number of items to be removed. @param {Ember.Enumerable|Number} adding An enumerable of the objects to be added or the number of items to be added. @chainable @private */ enumerableContentDidChange: function (removing, adding) { var removeCnt = undefined, addCnt = undefined, hasDelta = undefined; if ('number' === typeof removing) { removeCnt = removing; } else if (removing) { removeCnt = _emberMetalProperty_get.get(removing, 'length'); } else { removeCnt = removing = -1; } if ('number' === typeof adding) { addCnt = adding; } else if (adding) { addCnt = _emberMetalProperty_get.get(adding, 'length'); } else { addCnt = adding = -1; } hasDelta = addCnt < 0 || removeCnt < 0 || addCnt - removeCnt !== 0; if (removing === -1) { removing = null; } if (adding === -1) { adding = null; } _emberMetalEvents.sendEvent(this, '@enumerable:change', [this, removing, adding]); if (hasDelta) { _emberMetalProperty_events.propertyDidChange(this, 'length'); } _emberMetalProperty_events.propertyDidChange(this, '[]'); return this; }, /** Converts the enumerable into an array and sorts by the keys specified in the argument. You may provide multiple arguments to sort by multiple properties. @method sortBy @param {String} property name(s) to sort on @return {Array} The sorted array. @since 1.2.0 @public */ sortBy: function () { var sortKeys = arguments; return this.toArray().sort(function (a, b) { for (var i = 0; i < sortKeys.length; i++) { var key = sortKeys[i]; var propA = _emberMetalProperty_get.get(a, key); var propB = _emberMetalProperty_get.get(b, key); // return 1 or -1 else continue to the next sortKey var compareValue = _emberRuntimeCompare.default(propA, propB); if (compareValue) { return compareValue; } } return 0; }); } }); if (true) { Enumerable.reopen({ /** Returns a new enumerable that contains only items containing a unique property value. The default implementation returns an array regardless of the receiver type. ```javascript let arr = [{ value: 'a' }, { value: 'a' }, { value: 'b' }, { value: 'b' }]; arr.uniqBy('value'); // [{ value: 'a' }, { value: 'b' }] ``` @method uniqBy @return {Ember.Enumerable} @public */ uniqBy: function (key) { var ret = emberA(); var seen = new _emberMetalEmpty_object.default(); this.forEach(function (item) { var guid = _emberMetalUtils.guidFor(_emberMetalProperty_get.get(item, key)); if (!(guid in seen)) { seen[guid] = true; ret.push(item); } }); return ret; } }); } if (true) { Enumerable.reopen({ /** Returns `true` if the passed object can be found in the enumerable. ```javascript [1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false [1, 2, undefined].includes(undefined); // true [1, 2, null].includes(null); // true [1, 2, NaN].includes(NaN); // true ``` @method includes @param {Object} obj The object to search for. @return {Boolean} `true` if object is found in the enumerable. @public */ includes: function (obj) { _emberMetalDebug.assert('Enumerable#includes cannot accept a second argument "startAt" as enumerable items are unordered.', arguments.length === 1); var len = _emberMetalProperty_get.get(this, 'length'); var idx = undefined, next = undefined; var last = null; var found = false; var context = popCtx(); for (idx = 0; idx < len && !found; idx++) { next = this.nextObject(idx, last, context); found = obj === next || obj !== obj && next !== next; last = next; } next = last = null; context = pushCtx(context); return found; }, without: function (value) { if (!this.includes(value)) { return this; // nothing to do } var ret = emberA(); this.forEach(function (k) { // SameValueZero comparison (NaN !== NaN) if (!(k === value || k !== k && value !== value)) { ret[ret.length] = k; } }); return ret; } }); } exports.default = Enumerable; }); enifed('ember-runtime/mixins/evented', ['exports', 'ember-metal/mixin', 'ember-metal/events'], function (exports, _emberMetalMixin, _emberMetalEvents) { 'use strict'; /** @module ember @submodule ember-runtime */ /** This mixin allows for Ember objects to subscribe to and emit events. ```javascript App.Person = Ember.Object.extend(Ember.Evented, { greet: function() { // ... this.trigger('greet'); } }); var person = App.Person.create(); person.on('greet', function() { console.log('Our person has greeted'); }); person.greet(); // outputs: 'Our person has greeted' ``` You can also chain multiple event subscriptions: ```javascript person.on('greet', function() { console.log('Our person has greeted'); }).one('greet', function() { console.log('Offer one-time special'); }).off('event', this, forgetThis); ``` @class Evented @namespace Ember @public */ exports.default = _emberMetalMixin.Mixin.create({ /** Subscribes to a named event with given function. ```javascript person.on('didLoad', function() { // fired once the person has loaded }); ``` An optional target can be passed in as the 2nd argument that will be set as the "this" for the callback. This is a good way to give your function access to the object triggering the event. When the target parameter is used the callback becomes the third argument. @method on @param {String} name The name of the event @param {Object} [target] The "this" binding for the callback @param {Function} method The callback to execute @return this @public */ on: function (name, target, method) { _emberMetalEvents.addListener(this, name, target, method); return this; }, /** Subscribes a function to a named event and then cancels the subscription after the first time the event is triggered. It is good to use ``one`` when you only care about the first time an event has taken place. This function takes an optional 2nd argument that will become the "this" value for the callback. If this argument is passed then the 3rd argument becomes the function. @method one @param {String} name The name of the event @param {Object} [target] The "this" binding for the callback @param {Function} method The callback to execute @return this @public */ one: function (name, target, method) { if (!method) { method = target; target = null; } _emberMetalEvents.addListener(this, name, target, method, true); return this; }, /** Triggers a named event for the object. Any additional arguments will be passed as parameters to the functions that are subscribed to the event. ```javascript person.on('didEat', function(food) { console.log('person ate some ' + food); }); person.trigger('didEat', 'broccoli'); // outputs: person ate some broccoli ``` @method trigger @param {String} name The name of the event @param {Object...} args Optional arguments to pass on @public */ trigger: function (name) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } _emberMetalEvents.sendEvent(this, name, args); }, /** Cancels subscription for given name, target, and method. @method off @param {String} name The name of the event @param {Object} target The target of the subscription @param {Function} method The function of the subscription @return this @public */ off: function (name, target, method) { _emberMetalEvents.removeListener(this, name, target, method); return this; }, /** Checks to see if object has any subscriptions for named event. @method has @param {String} name The name of the event @return {Boolean} does the object have a subscription for event @public */ has: function (name) { return _emberMetalEvents.hasListeners(this, name); } }); }); enifed('ember-runtime/mixins/freezable', ['exports', 'ember-metal/debug', 'ember-metal/mixin', 'ember-metal/property_get', 'ember-metal/property_set'], function (exports, _emberMetalDebug, _emberMetalMixin, _emberMetalProperty_get, _emberMetalProperty_set) { /** @module ember @submodule ember-runtime */ 'use strict'; /** The `Ember.Freezable` mixin implements some basic methods for marking an object as frozen. Once an object is frozen it should be read only. No changes may be made the internal state of the object. ## Enforcement To fully support freezing in your subclass, you must include this mixin and override any method that might alter any property on the object to instead raise an exception. You can check the state of an object by checking the `isFrozen` property. Although future versions of JavaScript may support language-level freezing object objects, that is not the case today. Even if an object is freezable, it is still technically possible to modify the object, even though it could break other parts of your application that do not expect a frozen object to change. It is, therefore, very important that you always respect the `isFrozen` property on all freezable objects. ## Example Usage The example below shows a simple object that implement the `Ember.Freezable` protocol. ```javascript Contact = Ember.Object.extend(Ember.Freezable, { firstName: null, lastName: null, // swaps the names swapNames: function() { if (this.get('isFrozen')) throw Ember.FROZEN_ERROR; var tmp = this.get('firstName'); this.set('firstName', this.get('lastName')); this.set('lastName', tmp); return this; } }); c = Contact.create({ firstName: "John", lastName: "Doe" }); c.swapNames(); // returns c c.freeze(); c.swapNames(); // EXCEPTION ``` ## Copying Usually the `Ember.Freezable` protocol is implemented in cooperation with the `Ember.Copyable` protocol, which defines a `frozenCopy()` method that will return a frozen object, if the object implements this method as well. @class Freezable @namespace Ember @since Ember 0.9 @deprecated Use `Object.freeze` instead. @private */ var Freezable = _emberMetalMixin.Mixin.create({ init: function () { _emberMetalDebug.deprecate('`Ember.Freezable` is deprecated, use `Object.freeze` instead.', false, { id: 'ember-runtime.freezable-init', until: '3.0.0' }); this._super.apply(this, arguments); }, /** Set to `true` when the object is frozen. Use this property to detect whether your object is frozen or not. @property isFrozen @type Boolean @private */ isFrozen: false, /** Freezes the object. Once this method has been called the object should no longer allow any properties to be edited. @method freeze @return {Object} receiver @private */ freeze: function () { if (_emberMetalProperty_get.get(this, 'isFrozen')) { return this; } _emberMetalProperty_set.set(this, 'isFrozen', true); return this; } }); exports.Freezable = Freezable; var FROZEN_ERROR = 'Frozen object cannot be modified.'; exports.FROZEN_ERROR = FROZEN_ERROR; }); enifed('ember-runtime/mixins/mutable_array', ['exports', 'ember-metal/property_get', 'ember-metal/error', 'ember-metal/mixin', 'ember-runtime/mixins/array', 'ember-runtime/mixins/mutable_enumerable', 'ember-runtime/mixins/enumerable', 'ember-metal/features'], function (exports, _emberMetalProperty_get, _emberMetalError, _emberMetalMixin, _emberRuntimeMixinsArray, _emberRuntimeMixinsMutable_enumerable, _emberRuntimeMixinsEnumerable, _emberMetalFeatures) { /** @module ember @submodule ember-runtime */ // require('ember-runtime/mixins/array'); // require('ember-runtime/mixins/mutable_enumerable'); // .......................................................... // CONSTANTS // 'use strict'; exports.removeAt = removeAt; var OUT_OF_RANGE_EXCEPTION = 'Index out of range'; var EMPTY = []; // .......................................................... // HELPERS // function removeAt(array, start, len) { if ('number' === typeof start) { if (start < 0 || start >= _emberMetalProperty_get.get(array, 'length')) { throw new _emberMetalError.default(OUT_OF_RANGE_EXCEPTION); } // fast case if (len === undefined) { len = 1; } array.replace(start, len, EMPTY); } return array; } /** This mixin defines the API for modifying array-like objects. These methods can be applied only to a collection that keeps its items in an ordered set. It builds upon the Array mixin and adds methods to modify the array. One concrete implementations of this class include ArrayProxy. It is important to use the methods in this class to modify arrays so that changes are observable. This allows the binding system in Ember to function correctly. Note that an Array can change even if it does not implement this mixin. For example, one might implement a SparseArray that cannot be directly modified, but if its underlying enumerable changes, it will change also. @class MutableArray @namespace Ember @uses Ember.Array @uses Ember.MutableEnumerable @public */ exports.default = _emberMetalMixin.Mixin.create(_emberRuntimeMixinsArray.default, _emberRuntimeMixinsMutable_enumerable.default, { /** __Required.__ You must implement this method to apply this mixin. This is one of the primitives you must implement to support `Ember.Array`. You should replace amt objects started at idx with the objects in the passed array. You should also call `this.enumerableContentDidChange()` @method replace @param {Number} idx Starting index in the array to replace. If idx >= length, then append to the end of the array. @param {Number} amt Number of elements that should be removed from the array, starting at *idx*. @param {Array} objects An array of zero or more objects that should be inserted into the array at *idx* @public */ replace: null, /** Remove all elements from the array. This is useful if you want to reuse an existing array without having to recreate it. ```javascript let colors = ['red', 'green', 'blue']; color.length(); // 3 colors.clear(); // [] colors.length(); // 0 ``` @method clear @return {Ember.Array} An empty Array. @public */ clear: function () { var len = _emberMetalProperty_get.get(this, 'length'); if (len === 0) { return this; } this.replace(0, len, EMPTY); return this; }, /** This will use the primitive `replace()` method to insert an object at the specified index. ```javascript let colors = ['red', 'green', 'blue']; colors.insertAt(2, 'yellow'); // ['red', 'green', 'yellow', 'blue'] colors.insertAt(5, 'orange'); // Error: Index out of range ``` @method insertAt @param {Number} idx index of insert the object at. @param {Object} object object to insert @return {Ember.Array} receiver @public */ insertAt: function (idx, object) { if (idx > _emberMetalProperty_get.get(this, 'length')) { throw new _emberMetalError.default(OUT_OF_RANGE_EXCEPTION); } this.replace(idx, 0, [object]); return this; }, /** Remove an object at the specified index using the `replace()` primitive method. You can pass either a single index, or a start and a length. If you pass a start and length that is beyond the length this method will throw an `OUT_OF_RANGE_EXCEPTION`. ```javascript let colors = ['red', 'green', 'blue', 'yellow', 'orange']; colors.removeAt(0); // ['green', 'blue', 'yellow', 'orange'] colors.removeAt(2, 2); // ['green', 'blue'] colors.removeAt(4, 2); // Error: Index out of range ``` @method removeAt @param {Number} start index, start of range @param {Number} len length of passing range @return {Ember.Array} receiver @public */ removeAt: function (start, len) { return removeAt(this, start, len); }, /** Push the object onto the end of the array. Works just like `push()` but it is KVO-compliant. ```javascript let colors = ['red', 'green']; colors.pushObject('black'); // ['red', 'green', 'black'] colors.pushObject(['yellow']); // ['red', 'green', ['yellow']] ``` @method pushObject @param {*} obj object to push @return object same object passed as a param @public */ pushObject: function (obj) { this.insertAt(_emberMetalProperty_get.get(this, 'length'), obj); return obj; }, /** Add the objects in the passed numerable to the end of the array. Defers notifying observers of the change until all objects are added. ```javascript let colors = ['red']; colors.pushObjects(['yellow', 'orange']); // ['red', 'yellow', 'orange'] ``` @method pushObjects @param {Ember.Enumerable} objects the objects to add @return {Ember.Array} receiver @public */ pushObjects: function (objects) { if (!(_emberRuntimeMixinsEnumerable.default.detect(objects) || Array.isArray(objects))) { throw new TypeError('Must pass Ember.Enumerable to Ember.MutableArray#pushObjects'); } this.replace(_emberMetalProperty_get.get(this, 'length'), 0, objects); return this; }, /** Pop object from array or nil if none are left. Works just like `pop()` but it is KVO-compliant. ```javascript let colors = ['red', 'green', 'blue']; colors.popObject(); // 'blue' console.log(colors); // ['red', 'green'] ``` @method popObject @return object @public */ popObject: function () { var len = _emberMetalProperty_get.get(this, 'length'); if (len === 0) { return null; } var ret = _emberRuntimeMixinsArray.objectAt(this, len - 1); this.removeAt(len - 1, 1); return ret; }, /** Shift an object from start of array or nil if none are left. Works just like `shift()` but it is KVO-compliant. ```javascript let colors = ['red', 'green', 'blue']; colors.shiftObject(); // 'red' console.log(colors); // ['green', 'blue'] ``` @method shiftObject @return object @public */ shiftObject: function () { if (_emberMetalProperty_get.get(this, 'length') === 0) { return null; } var ret = _emberRuntimeMixinsArray.objectAt(this, 0); this.removeAt(0); return ret; }, /** Unshift an object to start of array. Works just like `unshift()` but it is KVO-compliant. ```javascript let colors = ['red']; colors.unshiftObject('yellow'); // ['yellow', 'red'] colors.unshiftObject(['black']); // [['black'], 'yellow', 'red'] ``` @method unshiftObject @param {*} obj object to unshift @return object same object passed as a param @public */ unshiftObject: function (obj) { this.insertAt(0, obj); return obj; }, /** Adds the named objects to the beginning of the array. Defers notifying observers until all objects have been added. ```javascript let colors = ['red']; colors.unshiftObjects(['black', 'white']); // ['black', 'white', 'red'] colors.unshiftObjects('yellow'); // Type Error: 'undefined' is not a function ``` @method unshiftObjects @param {Ember.Enumerable} objects the objects to add @return {Ember.Array} receiver @public */ unshiftObjects: function (objects) { this.replace(0, 0, objects); return this; }, /** Reverse objects in the array. Works just like `reverse()` but it is KVO-compliant. @method reverseObjects @return {Ember.Array} receiver @public */ reverseObjects: function () { var len = _emberMetalProperty_get.get(this, 'length'); if (len === 0) { return this; } var objects = this.toArray().reverse(); this.replace(0, len, objects); return this; }, /** Replace all the receiver's content with content of the argument. If argument is an empty array receiver will be cleared. ```javascript let colors = ['red', 'green', 'blue']; colors.setObjects(['black', 'white']); // ['black', 'white'] colors.setObjects([]); // [] ``` @method setObjects @param {Ember.Array} objects array whose content will be used for replacing the content of the receiver @return {Ember.Array} receiver with the new content @public */ setObjects: function (objects) { if (objects.length === 0) { return this.clear(); } var len = _emberMetalProperty_get.get(this, 'length'); this.replace(0, len, objects); return this; }, // .......................................................... // IMPLEMENT Ember.MutableEnumerable // /** Remove all occurrences of an object in the array. ```javascript let cities = ['Chicago', 'Berlin', 'Lima', 'Chicago']; cities.removeObject('Chicago'); // ['Berlin', 'Lima'] cities.removeObject('Lima'); // ['Berlin'] cities.removeObject('Tokyo') // ['Berlin'] ``` @method removeObject @param {*} obj object to remove @return {Ember.Array} receiver @public */ removeObject: function (obj) { var loc = _emberMetalProperty_get.get(this, 'length') || 0; while (--loc >= 0) { var curObject = _emberRuntimeMixinsArray.objectAt(this, loc); if (curObject === obj) { this.removeAt(loc); } } return this; }, /** Push the object onto the end of the array if it is not already present in the array. ```javascript let cities = ['Chicago', 'Berlin']; cities.addObject('Lima'); // ['Chicago', 'Berlin', 'Lima'] cities.addObject('Berlin'); // ['Chicago', 'Berlin', 'Lima'] ``` @method addObject @param {*} obj object to add, if not already present @return {Ember.Array} receiver @public */ addObject: function (obj) { var included = undefined; if (true) { included = this.includes(obj); } else { included = this.contains(obj); } if (!included) { this.pushObject(obj); } return this; } }); }); enifed('ember-runtime/mixins/mutable_enumerable', ['exports', 'ember-runtime/mixins/enumerable', 'ember-metal/mixin', 'ember-metal/property_events'], function (exports, _emberRuntimeMixinsEnumerable, _emberMetalMixin, _emberMetalProperty_events) { 'use strict'; /** @module ember @submodule ember-runtime */ /** This mixin defines the API for modifying generic enumerables. These methods can be applied to an object regardless of whether it is ordered or unordered. Note that an Enumerable can change even if it does not implement this mixin. For example, a MappedEnumerable cannot be directly modified but if its underlying enumerable changes, it will change also. ## Adding Objects To add an object to an enumerable, use the `addObject()` method. This method will only add the object to the enumerable if the object is not already present and is of a type supported by the enumerable. ```javascript set.addObject(contact); ``` ## Removing Objects To remove an object from an enumerable, use the `removeObject()` method. This will only remove the object if it is present in the enumerable, otherwise this method has no effect. ```javascript set.removeObject(contact); ``` ## Implementing In Your Own Code If you are implementing an object and want to support this API, just include this mixin in your class and implement the required methods. In your unit tests, be sure to apply the Ember.MutableEnumerableTests to your object. @class MutableEnumerable @namespace Ember @uses Ember.Enumerable @public */ exports.default = _emberMetalMixin.Mixin.create(_emberRuntimeMixinsEnumerable.default, { /** __Required.__ You must implement this method to apply this mixin. Attempts to add the passed object to the receiver if the object is not already present in the collection. If the object is present, this method has no effect. If the passed object is of a type not supported by the receiver, then this method should raise an exception. @method addObject @param {Object} object The object to add to the enumerable. @return {Object} the passed object @public */ addObject: null, /** Adds each object in the passed enumerable to the receiver. @method addObjects @param {Ember.Enumerable} objects the objects to add. @return {Object} receiver @public */ addObjects: function (objects) { var _this = this; _emberMetalProperty_events.beginPropertyChanges(this); objects.forEach(function (obj) { return _this.addObject(obj); }); _emberMetalProperty_events.endPropertyChanges(this); return this; }, /** __Required.__ You must implement this method to apply this mixin. Attempts to remove the passed object from the receiver collection if the object is present in the collection. If the object is not present, this method has no effect. If the passed object is of a type not supported by the receiver, then this method should raise an exception. @method removeObject @param {Object} object The object to remove from the enumerable. @return {Object} the passed object @public */ removeObject: null, /** Removes each object in the passed enumerable from the receiver. @method removeObjects @param {Ember.Enumerable} objects the objects to remove @return {Object} receiver @public */ removeObjects: function (objects) { _emberMetalProperty_events.beginPropertyChanges(this); for (var i = objects.length - 1; i >= 0; i--) { this.removeObject(objects[i]); } _emberMetalProperty_events.endPropertyChanges(this); return this; } }); }); enifed('ember-runtime/mixins/observable', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/get_properties', 'ember-metal/set_properties', 'ember-metal/mixin', 'ember-metal/events', 'ember-metal/property_events', 'ember-metal/observer', 'ember-metal/computed', 'ember-metal/is_none'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalGet_properties, _emberMetalSet_properties, _emberMetalMixin, _emberMetalEvents, _emberMetalProperty_events, _emberMetalObserver, _emberMetalComputed, _emberMetalIs_none) { /** @module ember @submodule ember-runtime */ 'use strict'; /** ## Overview This mixin provides properties and property observing functionality, core features of the Ember object model. Properties and observers allow one object to observe changes to a property on another object. This is one of the fundamental ways that models, controllers and views communicate with each other in an Ember application. Any object that has this mixin applied can be used in observer operations. That includes `Ember.Object` and most objects you will interact with as you write your Ember application. Note that you will not generally apply this mixin to classes yourself, but you will use the features provided by this module frequently, so it is important to understand how to use it. ## Using `get()` and `set()` Because of Ember's support for bindings and observers, you will always access properties using the get method, and set properties using the set method. This allows the observing objects to be notified and computed properties to be handled properly. More documentation about `get` and `set` are below. ## Observing Property Changes You typically observe property changes simply by using the `Ember.observer` function in classes that you write. For example: ```javascript Ember.Object.extend({ valueObserver: Ember.observer('value', function(sender, key, value, rev) { // Executes whenever the "value" property changes // See the addObserver method for more information about the callback arguments }) }); ``` Although this is the most common way to add an observer, this capability is actually built into the `Ember.Object` class on top of two methods defined in this mixin: `addObserver` and `removeObserver`. You can use these two methods to add and remove observers yourself if you need to do so at runtime. To add an observer for a property, call: ```javascript object.addObserver('propertyKey', targetObject, targetAction) ``` This will call the `targetAction` method on the `targetObject` whenever the value of the `propertyKey` changes. Note that if `propertyKey` is a computed property, the observer will be called when any of the property dependencies are changed, even if the resulting value of the computed property is unchanged. This is necessary because computed properties are not computed until `get` is called. @class Observable @namespace Ember @public */ exports.default = _emberMetalMixin.Mixin.create({ /** Retrieves the value of a property from the object. This method is usually similar to using `object[keyName]` or `object.keyName`, however it supports both computed properties and the unknownProperty handler. Because `get` unifies the syntax for accessing all these kinds of properties, it can make many refactorings easier, such as replacing a simple property with a computed property, or vice versa. ### Computed Properties Computed properties are methods defined with the `property` modifier declared at the end, such as: ```javascript fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); }.property('firstName', 'lastName') ``` When you call `get` on a computed property, the function will be called and the return value will be returned instead of the function itself. ### Unknown Properties Likewise, if you try to call `get` on a property whose value is `undefined`, the `unknownProperty()` method will be called on the object. If this method returns any value other than `undefined`, it will be returned instead. This allows you to implement "virtual" properties that are not defined upfront. @method get @param {String} keyName The property to retrieve @return {Object} The property value or undefined. @public */ get: function (keyName) { return _emberMetalProperty_get.get(this, keyName); }, /** To get the values of multiple properties at once, call `getProperties` with a list of strings or an array: ```javascript record.getProperties('firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` is equivalent to: ```javascript record.getProperties(['firstName', 'lastName', 'zipCode']); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` @method getProperties @param {String...|Array} list of keys to get @return {Object} @public */ getProperties: function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _emberMetalGet_properties.default.apply(null, [this].concat(args)); }, /** Sets the provided key or path to the value. This method is generally very similar to calling `object[key] = value` or `object.key = value`, except that it provides support for computed properties, the `setUnknownProperty()` method and property observers. ### Computed Properties If you try to set a value on a key that has a computed property handler defined (see the `get()` method for an example), then `set()` will call that method, passing both the value and key instead of simply changing the value itself. This is useful for those times when you need to implement a property that is composed of one or more member properties. ### Unknown Properties If you try to set a value on a key that is undefined in the target object, then the `setUnknownProperty()` handler will be called instead. This gives you an opportunity to implement complex "virtual" properties that are not predefined on the object. If `setUnknownProperty()` returns undefined, then `set()` will simply set the value on the object. ### Property Observers In addition to changing the property, `set()` will also register a property change with the object. Unless you have placed this call inside of a `beginPropertyChanges()` and `endPropertyChanges(),` any "local" observers (i.e. observer methods declared on the same object), will be called immediately. Any "remote" observers (i.e. observer methods declared on another object) will be placed in a queue and called at a later time in a coalesced manner. @method set @param {String} keyName The property to set @param {Object} value The value to set or `null`. @return {Object} The passed value @public */ set: function (keyName, value) { return _emberMetalProperty_set.set(this, keyName, value); }, /** Sets a list of properties at once. These properties are set inside a single `beginPropertyChanges` and `endPropertyChanges` batch, so observers will be buffered. ```javascript record.setProperties({ firstName: 'Charles', lastName: 'Jolley' }); ``` @method setProperties @param {Object} hash the hash of keys and values to set @return {Object} The passed in hash @public */ setProperties: function (hash) { return _emberMetalSet_properties.default(this, hash); }, /** Begins a grouping of property changes. You can use this method to group property changes so that notifications will not be sent until the changes are finished. If you plan to make a large number of changes to an object at one time, you should call this method at the beginning of the changes to begin deferring change notifications. When you are done making changes, call `endPropertyChanges()` to deliver the deferred change notifications and end deferring. @method beginPropertyChanges @return {Ember.Observable} @private */ beginPropertyChanges: function () { _emberMetalProperty_events.beginPropertyChanges(); return this; }, /** Ends a grouping of property changes. You can use this method to group property changes so that notifications will not be sent until the changes are finished. If you plan to make a large number of changes to an object at one time, you should call `beginPropertyChanges()` at the beginning of the changes to defer change notifications. When you are done making changes, call this method to deliver the deferred change notifications and end deferring. @method endPropertyChanges @return {Ember.Observable} @private */ endPropertyChanges: function () { _emberMetalProperty_events.endPropertyChanges(); return this; }, /** Notify the observer system that a property is about to change. Sometimes you need to change a value directly or indirectly without actually calling `get()` or `set()` on it. In this case, you can use this method and `propertyDidChange()` instead. Calling these two methods together will notify all observers that the property has potentially changed value. Note that you must always call `propertyWillChange` and `propertyDidChange` as a pair. If you do not, it may get the property change groups out of order and cause notifications to be delivered more often than you would like. @method propertyWillChange @param {String} keyName The property key that is about to change. @return {Ember.Observable} @private */ propertyWillChange: function (keyName) { _emberMetalProperty_events.propertyWillChange(this, keyName); return this; }, /** Notify the observer system that a property has just changed. Sometimes you need to change a value directly or indirectly without actually calling `get()` or `set()` on it. In this case, you can use this method and `propertyWillChange()` instead. Calling these two methods together will notify all observers that the property has potentially changed value. Note that you must always call `propertyWillChange` and `propertyDidChange` as a pair. If you do not, it may get the property change groups out of order and cause notifications to be delivered more often than you would like. @method propertyDidChange @param {String} keyName The property key that has just changed. @return {Ember.Observable} @private */ propertyDidChange: function (keyName) { _emberMetalProperty_events.propertyDidChange(this, keyName); return this; }, /** Convenience method to call `propertyWillChange` and `propertyDidChange` in succession. @method notifyPropertyChange @param {String} keyName The property key to be notified about. @return {Ember.Observable} @public */ notifyPropertyChange: function (keyName) { this.propertyWillChange(keyName); this.propertyDidChange(keyName); return this; }, /** Adds an observer on a property. This is the core method used to register an observer for a property. Once you call this method, any time the key's value is set, your observer will be notified. Note that the observers are triggered any time the value is set, regardless of whether it has actually changed. Your observer should be prepared to handle that. You can also pass an optional context parameter to this method. The context will be passed to your observer method whenever it is triggered. Note that if you add the same target/method pair on a key multiple times with different context parameters, your observer will only be called once with the last context you passed. ### Observer Methods Observer methods you pass should generally have the following signature if you do not pass a `context` parameter: ```javascript fooDidChange: function(sender, key, value, rev) { }; ``` The sender is the object that changed. The key is the property that changes. The value property is currently reserved and unused. The rev is the last property revision of the object when it changed, which you can use to detect if the key value has really changed or not. If you pass a `context` parameter, the context will be passed before the revision like so: ```javascript fooDidChange: function(sender, key, value, context, rev) { }; ``` Usually you will not need the value, context or revision parameters at the end. In this case, it is common to write observer methods that take only a sender and key value as parameters or, if you aren't interested in any of these values, to write an observer that has no parameters at all. @method addObserver @param {String} key The key to observer @param {Object} target The target object to invoke @param {String|Function} method The method to invoke. @public */ addObserver: function (key, target, method) { _emberMetalObserver.addObserver(this, key, target, method); }, /** Remove an observer you have previously registered on this object. Pass the same key, target, and method you passed to `addObserver()` and your target will no longer receive notifications. @method removeObserver @param {String} key The key to observer @param {Object} target The target object to invoke @param {String|Function} method The method to invoke. @public */ removeObserver: function (key, target, method) { _emberMetalObserver.removeObserver(this, key, target, method); }, /** Returns `true` if the object currently has observers registered for a particular key. You can use this method to potentially defer performing an expensive action until someone begins observing a particular property on the object. @method hasObserverFor @param {String} key Key to check @return {Boolean} @private */ hasObserverFor: function (key) { return _emberMetalEvents.hasListeners(this, key + ':change'); }, /** Retrieves the value of a property, or a default value in the case that the property returns `undefined`. ```javascript person.getWithDefault('lastName', 'Doe'); ``` @method getWithDefault @param {String} keyName The name of the property to retrieve @param {Object} defaultValue The value to return if the property value is undefined @return {Object} The property value or the defaultValue. @public */ getWithDefault: function (keyName, defaultValue) { return _emberMetalProperty_get.getWithDefault(this, keyName, defaultValue); }, /** Set the value of a property to the current value plus some amount. ```javascript person.incrementProperty('age'); team.incrementProperty('score', 2); ``` @method incrementProperty @param {String} keyName The name of the property to increment @param {Number} increment The amount to increment by. Defaults to 1 @return {Number} The new property value @public */ incrementProperty: function (keyName, increment) { if (_emberMetalIs_none.default(increment)) { increment = 1; } _emberMetalDebug.assert('Must pass a numeric value to incrementProperty', !isNaN(parseFloat(increment)) && isFinite(increment)); return _emberMetalProperty_set.set(this, keyName, (parseFloat(_emberMetalProperty_get.get(this, keyName)) || 0) + increment); }, /** Set the value of a property to the current value minus some amount. ```javascript player.decrementProperty('lives'); orc.decrementProperty('health', 5); ``` @method decrementProperty @param {String} keyName The name of the property to decrement @param {Number} decrement The amount to decrement by. Defaults to 1 @return {Number} The new property value @public */ decrementProperty: function (keyName, decrement) { if (_emberMetalIs_none.default(decrement)) { decrement = 1; } _emberMetalDebug.assert('Must pass a numeric value to decrementProperty', !isNaN(parseFloat(decrement)) && isFinite(decrement)); return _emberMetalProperty_set.set(this, keyName, (_emberMetalProperty_get.get(this, keyName) || 0) - decrement); }, /** Set the value of a boolean property to the opposite of its current value. ```javascript starship.toggleProperty('warpDriveEngaged'); ``` @method toggleProperty @param {String} keyName The name of the property to toggle @return {Boolean} The new property value @public */ toggleProperty: function (keyName) { return _emberMetalProperty_set.set(this, keyName, !_emberMetalProperty_get.get(this, keyName)); }, /** Returns the cached value of a computed property, if it exists. This allows you to inspect the value of a computed property without accidentally invoking it if it is intended to be generated lazily. @method cacheFor @param {String} keyName @return {Object} The cached value of the computed property, if any @public */ cacheFor: function (keyName) { return _emberMetalComputed.cacheFor(this, keyName); }, // intended for debugging purposes observersForKey: function (keyName) { return _emberMetalObserver.observersFor(this, keyName); } }); }); enifed('ember-runtime/mixins/promise_proxy', ['exports', 'ember-metal/property_get', 'ember-metal/set_properties', 'ember-metal/computed', 'ember-runtime/computed/computed_macros', 'ember-metal/mixin', 'ember-metal/error'], function (exports, _emberMetalProperty_get, _emberMetalSet_properties, _emberMetalComputed, _emberRuntimeComputedComputed_macros, _emberMetalMixin, _emberMetalError) { 'use strict'; /** @module ember @submodule ember-runtime */ function tap(proxy, promise) { _emberMetalSet_properties.default(proxy, { isFulfilled: false, isRejected: false }); return promise.then(function (value) { _emberMetalSet_properties.default(proxy, { content: value, isFulfilled: true }); return value; }, function (reason) { _emberMetalSet_properties.default(proxy, { reason: reason, isRejected: true }); throw reason; }, 'Ember: PromiseProxy'); } /** A low level mixin making ObjectProxy promise-aware. ```javascript let ObjectPromiseProxy = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin); let proxy = ObjectPromiseProxy.create({ promise: Ember.RSVP.cast($.getJSON('/some/remote/data.json')) }); proxy.then(function(json){ // the json }, function(reason) { // the reason why you have no json }); ``` the proxy has bindable attributes which track the promises life cycle ```javascript proxy.get('isPending') //=> true proxy.get('isSettled') //=> false proxy.get('isRejected') //=> false proxy.get('isFulfilled') //=> false ``` When the $.getJSON completes, and the promise is fulfilled with json, the life cycle attributes will update accordingly. Note that $.getJSON doesn't return an ECMA specified promise, it is useful to wrap this with an `RSVP.cast` so that it behaves as a spec compliant promise. ```javascript proxy.get('isPending') //=> false proxy.get('isSettled') //=> true proxy.get('isRejected') //=> false proxy.get('isFulfilled') //=> true ``` As the proxy is an ObjectProxy, and the json now its content, all the json properties will be available directly from the proxy. ```javascript // Assuming the following json: { firstName: 'Stefan', lastName: 'Penner' } // both properties will accessible on the proxy proxy.get('firstName') //=> 'Stefan' proxy.get('lastName') //=> 'Penner' ``` @class Ember.PromiseProxyMixin @public */ exports.default = _emberMetalMixin.Mixin.create({ /** If the proxied promise is rejected this will contain the reason provided. @property reason @default null @public */ reason: null, /** Once the proxied promise has settled this will become `false`. @property isPending @default true @public */ isPending: _emberRuntimeComputedComputed_macros.not('isSettled').readOnly(), /** Once the proxied promise has settled this will become `true`. @property isSettled @default false @public */ isSettled: _emberRuntimeComputedComputed_macros.or('isRejected', 'isFulfilled').readOnly(), /** Will become `true` if the proxied promise is rejected. @property isRejected @default false @public */ isRejected: false, /** Will become `true` if the proxied promise is fulfilled. @property isFulfilled @default false @public */ isFulfilled: false, /** The promise whose fulfillment value is being proxied by this object. This property must be specified upon creation, and should not be changed once created. Example: ```javascript Ember.ObjectProxy.extend(Ember.PromiseProxyMixin).create({ promise: <thenable> }); ``` @property promise @public */ promise: _emberMetalComputed.computed({ get: function () { throw new _emberMetalError.default('PromiseProxy\'s promise must be set'); }, set: function (key, promise) { return tap(this, promise); } }), /** An alias to the proxied promise's `then`. See RSVP.Promise.then. @method then @param {Function} callback @return {RSVP.Promise} @public */ then: promiseAlias('then'), /** An alias to the proxied promise's `catch`. See RSVP.Promise.catch. @method catch @param {Function} callback @return {RSVP.Promise} @since 1.3.0 @public */ 'catch': promiseAlias('catch'), /** An alias to the proxied promise's `finally`. See RSVP.Promise.finally. @method finally @param {Function} callback @return {RSVP.Promise} @since 1.3.0 @public */ 'finally': promiseAlias('finally') }); function promiseAlias(name) { return function () { var promise = _emberMetalProperty_get.get(this, 'promise'); return promise[name].apply(promise, arguments); }; } }); enifed('ember-runtime/mixins/registry_proxy', ['exports', 'ember-metal/debug', 'ember-metal/mixin'], function (exports, _emberMetalDebug, _emberMetalMixin) { /** @module ember @submodule ember-runtime */ 'use strict'; exports.buildFakeRegistryWithDeprecations = buildFakeRegistryWithDeprecations; /** RegistryProxyMixin is used to provide public access to specific registry functionality. @class RegistryProxyMixin @private */ exports.default = _emberMetalMixin.Mixin.create({ __registry__: null, /** Given a fullName return the corresponding factory. @public @method resolveRegistration @param {String} fullName @return {Function} fullName's factory */ resolveRegistration: registryAlias('resolve'), /** Registers a factory that can be used for dependency injection (with `inject`) or for service lookup. Each factory is registered with a full name including two parts: `type:name`. A simple example: ```javascript let App = Ember.Application.create(); App.Orange = Ember.Object.extend(); App.register('fruit:favorite', App.Orange); ``` Ember will resolve factories from the `App` namespace automatically. For example `App.CarsController` will be discovered and returned if an application requests `controller:cars`. An example of registering a controller with a non-standard name: ```javascript let App = Ember.Application.create(); let Session = Ember.Controller.extend(); App.register('controller:session', Session); // The Session controller can now be treated like a normal controller, // despite its non-standard name. App.ApplicationController = Ember.Controller.extend({ needs: ['session'] }); ``` Registered factories are **instantiated** by having `create` called on them. Additionally they are **singletons**, each time they are looked up they return the same instance. Some examples modifying that default behavior: ```javascript let App = Ember.Application.create(); App.Person = Ember.Object.extend(); App.Orange = Ember.Object.extend(); App.Email = Ember.Object.extend(); App.session = Ember.Object.create(); App.register('model:user', App.Person, { singleton: false }); App.register('fruit:favorite', App.Orange); App.register('communication:main', App.Email, { singleton: false }); App.register('session', App.session, { instantiate: false }); ``` @method register @param fullName {String} type:name (e.g., 'model:user') @param factory {Function} (e.g., App.Person) @param options {Object} (optional) disable instantiation or singleton usage @public */ register: registryAlias('register'), /** Unregister a factory. ```javascript let App = Ember.Application.create(); let User = Ember.Object.extend(); App.register('model:user', User); App.resolveRegistration('model:user').create() instanceof User //=> true App.unregister('model:user') App.resolveRegistration('model:user') === undefined //=> true ``` @public @method unregister @param {String} fullName */ unregister: registryAlias('unregister'), /** Check if a factory is registered. @public @method hasRegistration @param {String} fullName @return {Boolean} */ hasRegistration: registryAlias('has'), /** Register an option for a particular factory. @public @method registerOption @param {String} fullName @param {String} optionName @param {Object} options */ registerOption: registryAlias('option'), /** Return a specific registered option for a particular factory. @public @method registeredOption @param {String} fullName @param {String} optionName @return {Object} options */ registeredOption: registryAlias('getOption'), /** Register options for a particular factory. @public @method registerOptions @param {String} fullName @param {Object} options */ registerOptions: registryAlias('options'), /** Return registered options for a particular factory. @public @method registeredOptions @param {String} fullName @return {Object} options */ registeredOptions: registryAlias('getOptions'), /** Allow registering options for all factories of a type. ```javascript let App = Ember.Application.create(); let appInstance = App.buildInstance(); // if all of type `connection` must not be singletons appInstance.optionsForType('connection', { singleton: false }); appInstance.register('connection:twitter', TwitterConnection); appInstance.register('connection:facebook', FacebookConnection); let twitter = appInstance.lookup('connection:twitter'); let twitter2 = appInstance.lookup('connection:twitter'); twitter === twitter2; // => false let facebook = appInstance.lookup('connection:facebook'); let facebook2 = appInstance.lookup('connection:facebook'); facebook === facebook2; // => false ``` @public @method registerOptionsForType @param {String} type @param {Object} options */ registerOptionsForType: registryAlias('optionsForType'), /** Return the registered options for all factories of a type. @public @method registeredOptionsForType @param {String} type @return {Object} options */ registeredOptionsForType: registryAlias('getOptionsForType'), /** Define a dependency injection onto a specific factory or all factories of a type. When Ember instantiates a controller, view, or other framework component it can attach a dependency to that component. This is often used to provide services to a set of framework components. An example of providing a session object to all controllers: ```javascript let App = Ember.Application.create(); let Session = Ember.Object.extend({ isAuthenticated: false }); // A factory must be registered before it can be injected App.register('session:main', Session); // Inject 'session:main' onto all factories of the type 'controller' // with the name 'session' App.inject('controller', 'session', 'session:main'); App.IndexController = Ember.Controller.extend({ isLoggedIn: Ember.computed.alias('session.isAuthenticated') }); ``` Injections can also be performed on specific factories. ```javascript App.inject(<full_name or type>, <property name>, <full_name>) App.inject('route', 'source', 'source:main') App.inject('route:application', 'email', 'model:email') ``` It is important to note that injections can only be performed on classes that are instantiated by Ember itself. Instantiating a class directly (via `create` or `new`) bypasses the dependency injection system. **Note:** Ember-Data instantiates its models in a unique manner, and consequently injections onto models (or all models) will not work as expected. Injections on models can be enabled by setting `EmberENV.MODEL_FACTORY_INJECTIONS` to `true`. @public @method inject @param factoryNameOrType {String} @param property {String} @param injectionName {String} **/ inject: registryAlias('injection') }); function registryAlias(name) { return function () { var _registry__; return (_registry__ = this.__registry__)[name].apply(_registry__, arguments); }; } function buildFakeRegistryWithDeprecations(instance, typeForMessage) { var fakeRegistry = {}; var registryProps = { resolve: 'resolveRegistration', register: 'register', unregister: 'unregister', has: 'hasRegistration', option: 'registerOption', options: 'registerOptions', getOptions: 'registeredOptions', optionsForType: 'registerOptionsForType', getOptionsForType: 'registeredOptionsForType', injection: 'inject' }; for (var deprecatedProperty in registryProps) { fakeRegistry[deprecatedProperty] = buildFakeRegistryFunction(instance, typeForMessage, deprecatedProperty, registryProps[deprecatedProperty]); } return fakeRegistry; } function buildFakeRegistryFunction(instance, typeForMessage, deprecatedProperty, nonDeprecatedProperty) { return function () { _emberMetalDebug.deprecate('Using `' + typeForMessage + '.registry.' + deprecatedProperty + '` is deprecated. Please use `' + typeForMessage + '.' + nonDeprecatedProperty + '` instead.', false, { id: 'ember-application.app-instance-registry', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-application-registry-ember-applicationinstance-registry' }); return instance[nonDeprecatedProperty].apply(instance, arguments); }; } }); enifed('ember-runtime/mixins/target_action_support', ['exports', 'ember-environment', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/mixin', 'ember-metal/computed'], function (exports, _emberEnvironment, _emberMetalDebug, _emberMetalProperty_get, _emberMetalMixin, _emberMetalComputed) { /** @module ember @submodule ember-runtime */ 'use strict'; /** `Ember.TargetActionSupport` is a mixin that can be included in a class to add a `triggerAction` method with semantics similar to the Handlebars `{{action}}` helper. In normal Ember usage, the `{{action}}` helper is usually the best choice. This mixin is most often useful when you are doing more complex event handling in View objects. See also `Ember.ViewTargetActionSupport`, which has view-aware defaults for target and actionContext. @class TargetActionSupport @namespace Ember @extends Ember.Mixin @private */ exports.default = _emberMetalMixin.Mixin.create({ target: null, action: null, actionContext: null, actionContextObject: _emberMetalComputed.computed('actionContext', function () { var actionContext = _emberMetalProperty_get.get(this, 'actionContext'); if (typeof actionContext === 'string') { var value = _emberMetalProperty_get.get(this, actionContext); if (value === undefined) { value = _emberMetalProperty_get.get(_emberEnvironment.context.lookup, actionContext); } return value; } else { return actionContext; } }), /** Send an `action` with an `actionContext` to a `target`. The action, actionContext and target will be retrieved from properties of the object. For example: ```javascript App.SaveButtonView = Ember.View.extend(Ember.TargetActionSupport, { target: Ember.computed.alias('controller'), action: 'save', actionContext: Ember.computed.alias('context'), click() { this.triggerAction(); // Sends the `save` action, along with the current context // to the current controller } }); ``` The `target`, `action`, and `actionContext` can be provided as properties of an optional object argument to `triggerAction` as well. ```javascript App.SaveButtonView = Ember.View.extend(Ember.TargetActionSupport, { click() { this.triggerAction({ action: 'save', target: this.get('controller'), actionContext: this.get('context') }); // Sends the `save` action, along with the current context // to the current controller } }); ``` The `actionContext` defaults to the object you are mixing `TargetActionSupport` into. But `target` and `action` must be specified either as properties or with the argument to `triggerAction`, or a combination: ```javascript App.SaveButtonView = Ember.View.extend(Ember.TargetActionSupport, { target: Ember.computed.alias('controller'), click() { this.triggerAction({ action: 'save' }); // Sends the `save` action, along with a reference to `this`, // to the current controller } }); ``` @method triggerAction @param opts {Object} (optional, with the optional keys action, target and/or actionContext) @return {Boolean} true if the action was sent successfully and did not return false @private */ triggerAction: function () { var opts = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = opts.action || _emberMetalProperty_get.get(this, 'action'); var target = opts.target; if (!target) { target = getTarget(this); } var actionContext = opts.actionContext; function args(options, actionName) { var ret = []; if (actionName) { ret.push(actionName); } return ret.concat(options); } if (typeof actionContext === 'undefined') { actionContext = _emberMetalProperty_get.get(this, 'actionContextObject') || this; } if (target && action) { var ret = undefined; if (target.send) { ret = target.send.apply(target, args(actionContext, action)); } else { _emberMetalDebug.assert('The action \'' + action + '\' did not exist on ' + target, typeof target[action] === 'function'); ret = target[action].apply(target, args(actionContext)); } if (ret !== false) { ret = true; } return ret; } else { return false; } } }); function getTarget(instance) { // TODO: Deprecate specifying `targetObject` var target = _emberMetalProperty_get.get(instance, 'targetObject'); // if a `targetObject` CP was provided, use it if (target) { return target; } // if _targetObject use it if (instance._targetObject) { return instance._targetObject; } target = _emberMetalProperty_get.get(instance, 'target'); if (target) { if (typeof target === 'string') { var value = _emberMetalProperty_get.get(instance, target); if (value === undefined) { value = _emberMetalProperty_get.get(_emberEnvironment.context.lookup, target); } return value; } else { return target; } } return null; } }); enifed("ember-runtime/string_registry", ["exports"], function (exports) { // STATE within a module is frowned apon, this exists // to support Ember.STRINGS but shield ember internals from this legacy global // API. "use strict"; exports.setStrings = setStrings; exports.getStrings = getStrings; exports.get = get; var STRINGS = {}; function setStrings(strings) { STRINGS = strings; } function getStrings() { return STRINGS; } function get(name) { return STRINGS[name]; } }); enifed('ember-runtime/system/application', ['exports', 'ember-runtime/system/namespace'], function (exports, _emberRuntimeSystemNamespace) { 'use strict'; exports.default = _emberRuntimeSystemNamespace.default.extend(); }); enifed('ember-runtime/system/array_proxy', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-runtime/utils', 'ember-metal/computed', 'ember-metal/mixin', 'ember-metal/property_events', 'ember-metal/error', 'ember-runtime/system/object', 'ember-runtime/mixins/mutable_array', 'ember-runtime/mixins/enumerable', 'ember-metal/alias', 'ember-runtime/mixins/array'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberRuntimeUtils, _emberMetalComputed, _emberMetalMixin, _emberMetalProperty_events, _emberMetalError, _emberRuntimeSystemObject, _emberRuntimeMixinsMutable_array, _emberRuntimeMixinsEnumerable, _emberMetalAlias, _emberRuntimeMixinsArray) { 'use strict'; /** @module ember @submodule ember-runtime */ var OUT_OF_RANGE_EXCEPTION = 'Index out of range'; var EMPTY = []; function K() { return this; } /** An ArrayProxy wraps any other object that implements `Ember.Array` and/or `Ember.MutableArray,` forwarding all requests. This makes it very useful for a number of binding use cases or other cases where being able to swap out the underlying array is useful. A simple example of usage: ```javascript let pets = ['dog', 'cat', 'fish']; let ap = Ember.ArrayProxy.create({ content: Ember.A(pets) }); ap.get('firstObject'); // 'dog' ap.set('content', ['amoeba', 'paramecium']); ap.get('firstObject'); // 'amoeba' ``` This class can also be useful as a layer to transform the contents of an array, as they are accessed. This can be done by overriding `objectAtContent`: ```javascript let pets = ['dog', 'cat', 'fish']; let ap = Ember.ArrayProxy.create({ content: Ember.A(pets), objectAtContent: function(idx) { return this.get('content').objectAt(idx).toUpperCase(); } }); ap.get('firstObject'); // . 'DOG' ``` @class ArrayProxy @namespace Ember @extends Ember.Object @uses Ember.MutableArray @public */ exports.default = _emberRuntimeSystemObject.default.extend(_emberRuntimeMixinsMutable_array.default, { /** The content array. Must be an object that implements `Ember.Array` and/or `Ember.MutableArray.` @property content @type Ember.Array @private */ content: null, /** The array that the proxy pretends to be. In the default `ArrayProxy` implementation, this and `content` are the same. Subclasses of `ArrayProxy` can override this property to provide things like sorting and filtering. @property arrangedContent @private */ arrangedContent: _emberMetalAlias.default('content'), /** Should actually retrieve the object at the specified index from the content. You can override this method in subclasses to transform the content item to something new. This method will only be called if content is non-`null`. @method objectAtContent @param {Number} idx The index to retrieve. @return {Object} the value or undefined if none found @private */ objectAtContent: function (idx) { return _emberRuntimeMixinsArray.objectAt(_emberMetalProperty_get.get(this, 'arrangedContent'), idx); }, /** Should actually replace the specified objects on the content array. You can override this method in subclasses to transform the content item into something new. This method will only be called if content is non-`null`. @method replaceContent @param {Number} idx The starting index @param {Number} amt The number of items to remove from the content. @param {Array} objects Optional array of objects to insert or null if no objects. @return {void} @private */ replaceContent: function (idx, amt, objects) { _emberMetalProperty_get.get(this, 'content').replace(idx, amt, objects); }, /** Invoked when the content property is about to change. Notifies observers that the entire array content will change. @private @method _contentWillChange */ _contentWillChange: _emberMetalMixin._beforeObserver('content', function () { this._teardownContent(); }), _teardownContent: function () { var content = _emberMetalProperty_get.get(this, 'content'); if (content) { _emberRuntimeMixinsArray.removeArrayObserver(content, this, { willChange: 'contentArrayWillChange', didChange: 'contentArrayDidChange' }); } }, /** Override to implement content array `willChange` observer. @method contentArrayWillChange @param {Ember.Array} contentArray the content array @param {Number} start starting index of the change @param {Number} removeCount count of items removed @param {Number} addCount count of items added @private */ contentArrayWillChange: K, /** Override to implement content array `didChange` observer. @method contentArrayDidChange @param {Ember.Array} contentArray the content array @param {Number} start starting index of the change @param {Number} removeCount count of items removed @param {Number} addCount count of items added @private */ contentArrayDidChange: K, /** Invoked when the content property changes. Notifies observers that the entire array content has changed. @private @method _contentDidChange */ _contentDidChange: _emberMetalMixin.observer('content', function () { var content = _emberMetalProperty_get.get(this, 'content'); _emberMetalDebug.assert('Can\'t set ArrayProxy\'s content to itself', content !== this); this._setupContent(); }), _setupContent: function () { var content = _emberMetalProperty_get.get(this, 'content'); if (content) { _emberMetalDebug.assert('ArrayProxy expects an Array or Ember.ArrayProxy, but you passed ' + typeof content, _emberRuntimeUtils.isArray(content) || content.isDestroyed); _emberRuntimeMixinsArray.addArrayObserver(content, this, { willChange: 'contentArrayWillChange', didChange: 'contentArrayDidChange' }); } }, _arrangedContentWillChange: _emberMetalMixin._beforeObserver('arrangedContent', function () { var arrangedContent = _emberMetalProperty_get.get(this, 'arrangedContent'); var len = arrangedContent ? _emberMetalProperty_get.get(arrangedContent, 'length') : 0; this.arrangedContentArrayWillChange(this, 0, len, undefined); this.arrangedContentWillChange(this); this._teardownArrangedContent(arrangedContent); }), _arrangedContentDidChange: _emberMetalMixin.observer('arrangedContent', function () { var arrangedContent = _emberMetalProperty_get.get(this, 'arrangedContent'); var len = arrangedContent ? _emberMetalProperty_get.get(arrangedContent, 'length') : 0; _emberMetalDebug.assert('Can\'t set ArrayProxy\'s content to itself', arrangedContent !== this); this._setupArrangedContent(); this.arrangedContentDidChange(this); this.arrangedContentArrayDidChange(this, 0, undefined, len); }), _setupArrangedContent: function () { var arrangedContent = _emberMetalProperty_get.get(this, 'arrangedContent'); if (arrangedContent) { _emberMetalDebug.assert('ArrayProxy expects an Array or Ember.ArrayProxy, but you passed ' + typeof arrangedContent, _emberRuntimeUtils.isArray(arrangedContent) || arrangedContent.isDestroyed); _emberRuntimeMixinsArray.addArrayObserver(arrangedContent, this, { willChange: 'arrangedContentArrayWillChange', didChange: 'arrangedContentArrayDidChange' }); } }, _teardownArrangedContent: function () { var arrangedContent = _emberMetalProperty_get.get(this, 'arrangedContent'); if (arrangedContent) { _emberRuntimeMixinsArray.removeArrayObserver(arrangedContent, this, { willChange: 'arrangedContentArrayWillChange', didChange: 'arrangedContentArrayDidChange' }); } }, arrangedContentWillChange: K, arrangedContentDidChange: K, objectAt: function (idx) { return _emberMetalProperty_get.get(this, 'content') && this.objectAtContent(idx); }, length: _emberMetalComputed.computed(function () { var arrangedContent = _emberMetalProperty_get.get(this, 'arrangedContent'); return arrangedContent ? _emberMetalProperty_get.get(arrangedContent, 'length') : 0; // No dependencies since Enumerable notifies length of change }), _replace: function (idx, amt, objects) { var content = _emberMetalProperty_get.get(this, 'content'); _emberMetalDebug.assert('The content property of ' + this.constructor + ' should be set before modifying it', content); if (content) { this.replaceContent(idx, amt, objects); } return this; }, replace: function () { if (_emberMetalProperty_get.get(this, 'arrangedContent') === _emberMetalProperty_get.get(this, 'content')) { this._replace.apply(this, arguments); } else { throw new _emberMetalError.default('Using replace on an arranged ArrayProxy is not allowed.'); } }, _insertAt: function (idx, object) { if (idx > _emberMetalProperty_get.get(this, 'content.length')) { throw new _emberMetalError.default(OUT_OF_RANGE_EXCEPTION); } this._replace(idx, 0, [object]); return this; }, insertAt: function (idx, object) { if (_emberMetalProperty_get.get(this, 'arrangedContent') === _emberMetalProperty_get.get(this, 'content')) { return this._insertAt(idx, object); } else { throw new _emberMetalError.default('Using insertAt on an arranged ArrayProxy is not allowed.'); } }, removeAt: function (start, len) { if ('number' === typeof start) { var content = _emberMetalProperty_get.get(this, 'content'); var arrangedContent = _emberMetalProperty_get.get(this, 'arrangedContent'); var indices = []; if (start < 0 || start >= _emberMetalProperty_get.get(this, 'length')) { throw new _emberMetalError.default(OUT_OF_RANGE_EXCEPTION); } if (len === undefined) { len = 1; } // Get a list of indices in original content to remove for (var i = start; i < start + len; i++) { // Use arrangedContent here so we avoid confusion with objects transformed by objectAtContent indices.push(content.indexOf(_emberRuntimeMixinsArray.objectAt(arrangedContent, i))); } // Replace in reverse order since indices will change indices.sort(function (a, b) { return b - a; }); _emberMetalProperty_events.beginPropertyChanges(); for (var i = 0; i < indices.length; i++) { this._replace(indices[i], 1, EMPTY); } _emberMetalProperty_events.endPropertyChanges(); } return this; }, pushObject: function (obj) { this._insertAt(_emberMetalProperty_get.get(this, 'content.length'), obj); return obj; }, pushObjects: function (objects) { if (!(_emberRuntimeMixinsEnumerable.default.detect(objects) || _emberRuntimeUtils.isArray(objects))) { throw new TypeError('Must pass Ember.Enumerable to Ember.MutableArray#pushObjects'); } this._replace(_emberMetalProperty_get.get(this, 'length'), 0, objects); return this; }, setObjects: function (objects) { if (objects.length === 0) { return this.clear(); } var len = _emberMetalProperty_get.get(this, 'length'); this._replace(0, len, objects); return this; }, unshiftObject: function (obj) { this._insertAt(0, obj); return obj; }, unshiftObjects: function (objects) { this._replace(0, 0, objects); return this; }, slice: function () { var arr = this.toArray(); return arr.slice.apply(arr, arguments); }, arrangedContentArrayWillChange: function (item, idx, removedCnt, addedCnt) { this.arrayContentWillChange(idx, removedCnt, addedCnt); }, arrangedContentArrayDidChange: function (item, idx, removedCnt, addedCnt) { this.arrayContentDidChange(idx, removedCnt, addedCnt); }, init: function () { this._super.apply(this, arguments); this._setupContent(); this._setupArrangedContent(); }, willDestroy: function () { this._teardownArrangedContent(); this._teardownContent(); } }); }); enifed('ember-runtime/system/container', ['exports', 'ember-metal/property_set', 'container/registry', 'container/container', 'container/owner'], function (exports, _emberMetalProperty_set, _containerRegistry, _containerContainer, _containerOwner) { 'use strict'; _containerRegistry.default.set = _emberMetalProperty_set.set; _containerContainer.default.set = _emberMetalProperty_set.set; exports.Registry = _containerRegistry.default; exports.Container = _containerContainer.default; exports.getOwner = _containerOwner.getOwner; exports.setOwner = _containerOwner.setOwner; }); enifed('ember-runtime/system/core_object', ['exports', 'ember-metal/debug', 'ember-metal/features', 'ember-metal/assign', 'ember-metal/property_get', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/chains', 'ember-metal/events', 'ember-metal/mixin', 'ember-metal/error', 'ember-runtime/mixins/action_handler', 'ember-metal/properties', 'ember-metal/binding', 'ember-metal/computed', 'ember-metal/injected_property', 'ember-metal/run_loop', 'ember-metal/watching', 'ember-runtime/inject', 'ember-metal/symbol'], function (exports, _emberMetalDebug, _emberMetalFeatures, _emberMetalAssign, _emberMetalProperty_get, _emberMetalUtils, _emberMetalMeta, _emberMetalChains, _emberMetalEvents, _emberMetalMixin, _emberMetalError, _emberRuntimeMixinsAction_handler, _emberMetalProperties, _emberMetalBinding, _emberMetalComputed, _emberMetalInjected_property, _emberMetalRun_loop, _emberMetalWatching, _emberRuntimeInject, _emberMetalSymbol) { 'no use strict'; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed /** @module ember @submodule ember-runtime */ // using ember-metal/lib/main here to ensure that ember-debug is setup // if present var _Mixin$create; var POST_INIT = _emberMetalSymbol.default('POST_INIT'); exports.POST_INIT = POST_INIT; var schedule = _emberMetalRun_loop.default.schedule; var applyMixin = _emberMetalMixin.Mixin._apply; var finishPartial = _emberMetalMixin.Mixin.finishPartial; var reopen = _emberMetalMixin.Mixin.prototype.reopen; var hasCachedComputedProperties = false; function makeCtor() { // Note: avoid accessing any properties on the object since it makes the // method a lot faster. This is glue code so we want it to be as fast as // possible. var wasApplied = false; var initProperties; var Class = function () { if (!wasApplied) { Class.proto(); // prepare prototype... } if (arguments.length > 0) { initProperties = [arguments[0]]; } this.__defineNonEnumerable(_emberMetalUtils.GUID_KEY_PROPERTY); var m = _emberMetalMeta.meta(this); var proto = m.proto; m.proto = this; if (initProperties) { // capture locally so we can clear the closed over variable var props = initProperties; initProperties = null; var concatenatedProperties = this.concatenatedProperties; var mergedProperties = this.mergedProperties; for (var i = 0; i < props.length; i++) { var properties = props[i]; _emberMetalDebug.assert('Ember.Object.create no longer supports mixing in other ' + 'definitions, use .extend & .create separately instead.', !(properties instanceof _emberMetalMixin.Mixin)); if (typeof properties !== 'object' && properties !== undefined) { throw new _emberMetalError.default('Ember.Object.create only accepts objects.'); } if (!properties) { continue; } var keyNames = Object.keys(properties); for (var j = 0; j < keyNames.length; j++) { var keyName = keyNames[j]; var value = properties[keyName]; if (_emberMetalMixin.detectBinding(keyName)) { m.writeBindings(keyName, value); } var possibleDesc = this[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; _emberMetalDebug.assert('Ember.Object.create no longer supports defining computed ' + 'properties. Define computed properties using extend() or reopen() ' + 'before calling create().', !(value instanceof _emberMetalComputed.ComputedProperty)); _emberMetalDebug.assert('Ember.Object.create no longer supports defining methods that call _super.', !(typeof value === 'function' && value.toString().indexOf('._super') !== -1)); _emberMetalDebug.assert('`actions` must be provided at extend time, not at create time, ' + 'when Ember.ActionHandler is used (i.e. views, controllers & routes).', !(keyName === 'actions' && _emberRuntimeMixinsAction_handler.default.detect(this))); if (concatenatedProperties && concatenatedProperties.length > 0 && concatenatedProperties.indexOf(keyName) >= 0) { var baseValue = this[keyName]; if (baseValue) { if ('function' === typeof baseValue.concat) { value = baseValue.concat(value); } else { value = _emberMetalUtils.makeArray(baseValue).concat(value); } } else { value = _emberMetalUtils.makeArray(value); } } if (mergedProperties && mergedProperties.length && mergedProperties.indexOf(keyName) >= 0) { var originalValue = this[keyName]; value = _emberMetalAssign.default({}, originalValue, value); } if (desc) { desc.set(this, keyName, value); } else { if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) { this.setUnknownProperty(keyName, value); } else { if (true) { _emberMetalProperties.defineProperty(this, keyName, null, value); // setup mandatory setter } else { this[keyName] = value; } } } } } } finishPartial(this, m); this.init.apply(this, arguments); this[POST_INIT](); m.proto = proto; _emberMetalChains.finishChains(this); _emberMetalEvents.sendEvent(this, 'init'); }; Class.toString = _emberMetalMixin.Mixin.prototype.toString; Class.willReopen = function () { if (wasApplied) { Class.PrototypeMixin = _emberMetalMixin.Mixin.create(Class.PrototypeMixin); } wasApplied = false; }; Class._initProperties = function (args) { initProperties = args; }; Class.proto = function () { var superclass = Class.superclass; if (superclass) { superclass.proto(); } if (!wasApplied) { wasApplied = true; Class.PrototypeMixin.applyPartial(Class.prototype); } return this.prototype; }; return Class; } /** @class CoreObject @namespace Ember @public */ var CoreObject = makeCtor(); CoreObject.toString = function () { return 'Ember.CoreObject'; }; CoreObject.PrototypeMixin = _emberMetalMixin.Mixin.create((_Mixin$create = { reopen: function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } applyMixin(this, args, true); return this; }, /** An overridable method called when objects are instantiated. By default, does nothing unless it is overridden during class definition. Example: ```javascript App.Person = Ember.Object.extend({ init: function() { alert('Name is ' + this.get('name')); } }); var steve = App.Person.create({ name: "Steve" }); // alerts 'Name is Steve'. ``` NOTE: If you do override `init` for a framework class like `Ember.View`, be sure to call `this._super(...arguments)` in your `init` declaration! If you don't, Ember may not have an opportunity to do important setup work, and you'll see strange behavior in your application. @method init @public */ init: function () {} }, _Mixin$create[POST_INIT] = function () {}, _Mixin$create.__defineNonEnumerable = function (property) { Object.defineProperty(this, property.name, property.descriptor); //this[property.name] = property.descriptor.value; }, _Mixin$create.concatenatedProperties = null, _Mixin$create.mergedProperties = null, _Mixin$create.isDestroyed = false, _Mixin$create.isDestroying = false, _Mixin$create.destroy = function () { if (this.isDestroying) { return; } this.isDestroying = true; schedule('actions', this, this.willDestroy); schedule('destroy', this, this._scheduledDestroy); return this; }, _Mixin$create.willDestroy = function () {}, _Mixin$create._scheduledDestroy = function () { if (this.isDestroyed) { return; } _emberMetalWatching.destroy(this); this.isDestroyed = true; }, _Mixin$create.bind = function (to, from) { if (!(from instanceof _emberMetalBinding.Binding)) { from = _emberMetalBinding.Binding.from(from); } from.to(to).connect(this); return from; }, _Mixin$create.toString = function () { var hasToStringExtension = typeof this.toStringExtension === 'function'; var extension = hasToStringExtension ? ':' + this.toStringExtension() : ''; var ret = '<' + this.constructor.toString() + ':' + _emberMetalUtils.guidFor(this) + extension + '>'; return ret; }, _Mixin$create)); CoreObject.PrototypeMixin.ownerConstructor = CoreObject; CoreObject.__super__ = null; var ClassMixinProps = { ClassMixin: _emberMetalMixin.REQUIRED, PrototypeMixin: _emberMetalMixin.REQUIRED, isClass: true, isMethod: false, /** Creates a new subclass. ```javascript App.Person = Ember.Object.extend({ say: function(thing) { alert(thing); } }); ``` This defines a new subclass of Ember.Object: `App.Person`. It contains one method: `say()`. You can also create a subclass from any existing class by calling its `extend()` method. For example, you might want to create a subclass of Ember's built-in `Ember.View` class: ```javascript App.PersonView = Ember.View.extend({ tagName: 'li', classNameBindings: ['isAdministrator'] }); ``` When defining a subclass, you can override methods but still access the implementation of your parent class by calling the special `_super()` method: ```javascript App.Person = Ember.Object.extend({ say: function(thing) { var name = this.get('name'); alert(name + ' says: ' + thing); } }); App.Soldier = App.Person.extend({ say: function(thing) { this._super(thing + ", sir!"); }, march: function(numberOfHours) { alert(this.get('name') + ' marches for ' + numberOfHours + ' hours.'); } }); var yehuda = App.Soldier.create({ name: "Yehuda Katz" }); yehuda.say("Yes"); // alerts "Yehuda Katz says: Yes, sir!" ``` The `create()` on line #17 creates an *instance* of the `App.Soldier` class. The `extend()` on line #8 creates a *subclass* of `App.Person`. Any instance of the `App.Person` class will *not* have the `march()` method. You can also pass `Mixin` classes to add additional properties to the subclass. ```javascript App.Person = Ember.Object.extend({ say: function(thing) { alert(this.get('name') + ' says: ' + thing); } }); App.SingingMixin = Mixin.create({ sing: function(thing){ alert(this.get('name') + ' sings: la la la ' + thing); } }); App.BroadwayStar = App.Person.extend(App.SingingMixin, { dance: function() { alert(this.get('name') + ' dances: tap tap tap tap '); } }); ``` The `App.BroadwayStar` class contains three methods: `say()`, `sing()`, and `dance()`. @method extend @static @param {Mixin} [mixins]* One or more Mixin classes @param {Object} [arguments]* Object containing values to use within the new class @public */ extend: function () { var Class = makeCtor(); var proto; Class.ClassMixin = _emberMetalMixin.Mixin.create(this.ClassMixin); Class.PrototypeMixin = _emberMetalMixin.Mixin.create(this.PrototypeMixin); Class.ClassMixin.ownerConstructor = Class; Class.PrototypeMixin.ownerConstructor = Class; reopen.apply(Class.PrototypeMixin, arguments); Class.superclass = this; Class.__super__ = this.prototype; proto = Class.prototype = Object.create(this.prototype); proto.constructor = Class; _emberMetalUtils.generateGuid(proto); _emberMetalMeta.meta(proto).proto = proto; // this will disable observers on prototype Class.ClassMixin.apply(Class); return Class; }, /** Creates an instance of a class. Accepts either no arguments, or an object containing values to initialize the newly instantiated object with. ```javascript App.Person = Ember.Object.extend({ helloWorld: function() { alert("Hi, my name is " + this.get('name')); } }); var tom = App.Person.create({ name: 'Tom Dale' }); tom.helloWorld(); // alerts "Hi, my name is Tom Dale". ``` `create` will call the `init` function if defined during `Ember.AnyObject.extend` If no arguments are passed to `create`, it will not set values to the new instance during initialization: ```javascript var noName = App.Person.create(); noName.helloWorld(); // alerts undefined ``` NOTE: For performance reasons, you cannot declare methods or computed properties during `create`. You should instead declare methods and computed properties when using `extend`. @method create @static @param [arguments]* @public */ create: function () { var C = this; for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } if (args.length > 0) { this._initProperties(args); } return new C(); }, /** Augments a constructor's prototype with additional properties and functions: ```javascript MyObject = Ember.Object.extend({ name: 'an object' }); o = MyObject.create(); o.get('name'); // 'an object' MyObject.reopen({ say: function(msg){ console.log(msg); } }) o2 = MyObject.create(); o2.say("hello"); // logs "hello" o.say("goodbye"); // logs "goodbye" ``` To add functions and properties to the constructor itself, see `reopenClass` @method reopen @public */ reopen: function () { this.willReopen(); reopen.apply(this.PrototypeMixin, arguments); return this; }, /** Augments a constructor's own properties and functions: ```javascript MyObject = Ember.Object.extend({ name: 'an object' }); MyObject.reopenClass({ canBuild: false }); MyObject.canBuild; // false o = MyObject.create(); ``` In other words, this creates static properties and functions for the class. These are only available on the class and not on any instance of that class. ```javascript App.Person = Ember.Object.extend({ name : "", sayHello : function() { alert("Hello. My name is " + this.get('name')); } }); App.Person.reopenClass({ species : "Homo sapiens", createPerson: function(newPersonsName){ return App.Person.create({ name:newPersonsName }); } }); var tom = App.Person.create({ name : "Tom Dale" }); var yehuda = App.Person.createPerson("Yehuda Katz"); tom.sayHello(); // "Hello. My name is Tom Dale" yehuda.sayHello(); // "Hello. My name is Yehuda Katz" alert(App.Person.species); // "Homo sapiens" ``` Note that `species` and `createPerson` are *not* valid on the `tom` and `yehuda` variables. They are only valid on `App.Person`. To add functions and properties to instances of a constructor by extending the constructor's prototype see `reopen` @method reopenClass @public */ reopenClass: function () { reopen.apply(this.ClassMixin, arguments); applyMixin(this, arguments, false); return this; }, detect: function (obj) { if ('function' !== typeof obj) { return false; } while (obj) { if (obj === this) { return true; } obj = obj.superclass; } return false; }, detectInstance: function (obj) { return obj instanceof this; }, /** In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection. You can pass a hash of these values to a computed property like this: ```javascript person: function() { var personId = this.get('personId'); return App.Person.create({ id: personId }); }.property().meta({ type: App.Person }) ``` Once you've done this, you can retrieve the values saved to the computed property from your class like this: ```javascript MyClass.metaForProperty('person'); ``` This will return the original hash that was passed to `meta()`. @static @method metaForProperty @param key {String} property name @private */ metaForProperty: function (key) { var proto = this.proto(); var possibleDesc = proto[key]; var desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; _emberMetalDebug.assert('metaForProperty() could not find a computed property ' + 'with key \'' + key + '\'.', !!desc && desc instanceof _emberMetalComputed.ComputedProperty); return desc._meta || {}; }, _computedProperties: _emberMetalComputed.computed(function () { hasCachedComputedProperties = true; var proto = this.proto(); var property; var properties = []; for (var name in proto) { property = proto[name]; if (property && property.isDescriptor) { properties.push({ name: name, meta: property._meta }); } } return properties; }).readOnly(), /** Iterate over each computed property for the class, passing its name and any associated metadata (see `metaForProperty`) to the callback. @static @method eachComputedProperty @param {Function} callback @param {Object} binding @private */ eachComputedProperty: function (callback, binding) { var property; var empty = {}; var properties = _emberMetalProperty_get.get(this, '_computedProperties'); for (var i = 0; i < properties.length; i++) { property = properties[i]; callback.call(binding || this, property.name, property.meta || empty); } } }; function injectedPropertyAssertion() { _emberMetalDebug.assert('Injected properties are invalid', _emberRuntimeInject.validatePropertyInjections(this)); } _emberMetalDebug.runInDebug(function () { /** Provides lookup-time type validation for injected properties. @private @method _onLookup */ ClassMixinProps._onLookup = injectedPropertyAssertion; }); /** Returns a hash of property names and container names that injected properties will lookup on the container lazily. @method _lazyInjections @return {Object} Hash of all lazy injected property keys to container names @private */ ClassMixinProps._lazyInjections = function () { var injections = {}; var proto = this.proto(); var key, desc; for (key in proto) { desc = proto[key]; if (desc instanceof _emberMetalInjected_property.default) { injections[key] = desc.type + ':' + (desc.name || key); } } return injections; }; var ClassMixin = _emberMetalMixin.Mixin.create(ClassMixinProps); ClassMixin.ownerConstructor = CoreObject; CoreObject.ClassMixin = ClassMixin; ClassMixin.apply(CoreObject); CoreObject.reopen({ didDefineProperty: function (proto, key, value) { if (hasCachedComputedProperties === false) { return; } if (value instanceof _emberMetalComputed.ComputedProperty) { var cache = _emberMetalMeta.meta(this.constructor).readableCache(); if (cache && cache._computedProperties !== undefined) { cache._computedProperties = undefined; } } } }); exports.default = CoreObject; }); // NOTE: this object should never be included directly. Instead use `Ember.Object`. // We only define this separately so that `Ember.Set` can depend on it. /** Defines the properties that will be concatenated from the superclass (instead of overridden). By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by combining the superclass' property value with the subclass' value. An example of this in use within Ember is the `classNames` property of `Ember.View`. Here is some sample code showing the difference between a concatenated property and a normal one: ```javascript App.BarView = Ember.View.extend({ someNonConcatenatedProperty: ['bar'], classNames: ['bar'] }); App.FooBarView = App.BarView.extend({ someNonConcatenatedProperty: ['foo'], classNames: ['foo'] }); var fooBarView = App.FooBarView.create(); fooBarView.get('someNonConcatenatedProperty'); // ['foo'] fooBarView.get('classNames'); // ['ember-view', 'bar', 'foo'] ``` This behavior extends to object creation as well. Continuing the above example: ```javascript var view = App.FooBarView.create({ someNonConcatenatedProperty: ['baz'], classNames: ['baz'] }) view.get('someNonConcatenatedProperty'); // ['baz'] view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz'] ``` Adding a single property that is not an array will just add it in the array: ```javascript var view = App.FooBarView.create({ classNames: 'baz' }) view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz'] ``` Using the `concatenatedProperties` property, we can tell Ember to mix the content of the properties. In `Ember.View` the `classNameBindings` and `attributeBindings` properties are also concatenated, in addition to `classNames`. This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. Since it changes expectations about behavior of properties, you should properly document its usage in each individual concatenated property (to not mislead your users to think they can override the property in a subclass). @property concatenatedProperties @type Array @default null @public */ /** Defines the properties that will be merged from the superclass (instead of overridden). By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by merging the superclass property value with the subclass property's value. An example of this in use within Ember is the `queryParams` property of routes. Here is some sample code showing the difference between a merged property and a normal one: ```javascript App.BarRoute = Ember.Route.extend({ someNonMergedProperty: { nonMerged: 'superclass value of nonMerged' }, queryParams: { page: {replace: false}, limit: {replace: true} } }); App.FooBarRoute = App.BarRoute.extend({ someNonMergedProperty: { completelyNonMerged: 'subclass value of nonMerged' }, queryParams: { limit: {replace: false} } }); var fooBarRoute = App.FooBarRoute.create(); fooBarRoute.get('someNonMergedProperty'); // => { completelyNonMerged: 'subclass value of nonMerged' } // // Note the entire object, including the nonMerged property of // the superclass object, has been replaced fooBarRoute.get('queryParams'); // => { // page: {replace: false}, // limit: {replace: false} // } // // Note the page remains from the superclass, and the // `limit` property's value of `false` has been merged from // the subclass. ``` This behavior is not available during object `create` calls. It is only available at `extend` time. This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. Since it changes expectations about behavior of properties, you should properly document its usage in each individual merged property (to not mislead your users to think they can override the property in a subclass). @property mergedProperties @type Array @default null @public */ /** Destroyed object property flag. if this property is `true` the observers and bindings were already removed by the effect of calling the `destroy()` method. @property isDestroyed @default false @public */ /** Destruction scheduled flag. The `destroy()` method has been called. The object stays intact until the end of the run loop at which point the `isDestroyed` flag is set. @property isDestroying @default false @public */ /** Destroys an object by setting the `isDestroyed` flag and removing its metadata, which effectively destroys observers and bindings. If you try to set a property on a destroyed object, an exception will be raised. Note that destruction is scheduled for the end of the run loop and does not happen immediately. It will set an isDestroying flag immediately. @method destroy @return {Ember.Object} receiver @public */ /** Override to implement teardown. @method willDestroy @public */ /** Invoked by the run loop to actually destroy the object. This is scheduled for execution by the `destroy` method. @private @method _scheduledDestroy */ /** Returns a string representation which attempts to provide more information than Javascript's `toString` typically does, in a generic way for all Ember objects. ```javascript App.Person = Em.Object.extend() person = App.Person.create() person.toString() //=> "<App.Person:ember1024>" ``` If the object's class is not defined on an Ember namespace, it will indicate it is a subclass of the registered superclass: ```javascript Student = App.Person.extend() student = Student.create() student.toString() //=> "<(subclass of App.Person):ember1025>" ``` If the method `toStringExtension` is defined, its return value will be included in the output. ```javascript App.Teacher = App.Person.extend({ toStringExtension: function() { return this.get('fullName'); } }); teacher = App.Teacher.create() teacher.toString(); //=> "<App.Teacher:ember1026:Tom Dale>" ``` @method toString @return {String} string representation @public */ enifed('ember-runtime/system/each_proxy', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/observer', 'ember-metal/property_events', 'ember-metal/empty_object', 'ember-runtime/mixins/array'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalObserver, _emberMetalProperty_events, _emberMetalEmpty_object, _emberRuntimeMixinsArray) { 'use strict'; exports.default = EachProxy; /** This is the object instance returned when you get the `@each` property on an array. It uses the unknownProperty handler to automatically create EachArray instances for property names. @class EachProxy @private */ function EachProxy(content) { this._content = content; this._keys = undefined; this.__ember_meta__ = null; } EachProxy.prototype = { __defineNonEnumerable: function (property) { this[property.name] = property.descriptor.value; }, // .......................................................... // ARRAY CHANGES // Invokes whenever the content array itself changes. arrayWillChange: function (content, idx, removedCnt, addedCnt) { var keys = this._keys; var lim = removedCnt > 0 ? idx + removedCnt : -1; for (var key in keys) { if (lim > 0) { removeObserverForContentKey(content, key, this, idx, lim); } _emberMetalProperty_events.propertyWillChange(this, key); } }, arrayDidChange: function (content, idx, removedCnt, addedCnt) { var keys = this._keys; var lim = addedCnt > 0 ? idx + addedCnt : -1; for (var key in keys) { if (lim > 0) { addObserverForContentKey(content, key, this, idx, lim); } _emberMetalProperty_events.propertyDidChange(this, key); } }, // .......................................................... // LISTEN FOR NEW OBSERVERS AND OTHER EVENT LISTENERS // Start monitoring keys based on who is listening... willWatchProperty: function (property) { this.beginObservingContentKey(property); }, didUnwatchProperty: function (property) { this.stopObservingContentKey(property); }, // .......................................................... // CONTENT KEY OBSERVING // Actual watch keys on the source content. beginObservingContentKey: function (keyName) { var keys = this._keys; if (!keys) { keys = this._keys = new _emberMetalEmpty_object.default(); } if (!keys[keyName]) { keys[keyName] = 1; var content = this._content; var len = _emberMetalProperty_get.get(content, 'length'); addObserverForContentKey(content, keyName, this, 0, len); } else { keys[keyName]++; } }, stopObservingContentKey: function (keyName) { var keys = this._keys; if (keys && keys[keyName] > 0 && --keys[keyName] <= 0) { var content = this._content; var len = _emberMetalProperty_get.get(content, 'length'); removeObserverForContentKey(content, keyName, this, 0, len); } }, contentKeyWillChange: function (obj, keyName) { _emberMetalProperty_events.propertyWillChange(this, keyName); }, contentKeyDidChange: function (obj, keyName) { _emberMetalProperty_events.propertyDidChange(this, keyName); } }; function addObserverForContentKey(content, keyName, proxy, idx, loc) { while (--loc >= idx) { var item = _emberRuntimeMixinsArray.objectAt(content, loc); if (item) { _emberMetalDebug.assert('When using @each to observe the array ' + content + ', the array must return an object', typeof item === 'object'); _emberMetalObserver._addBeforeObserver(item, keyName, proxy, 'contentKeyWillChange'); _emberMetalObserver.addObserver(item, keyName, proxy, 'contentKeyDidChange'); } } } function removeObserverForContentKey(content, keyName, proxy, idx, loc) { while (--loc >= idx) { var item = _emberRuntimeMixinsArray.objectAt(content, loc); if (item) { _emberMetalObserver._removeBeforeObserver(item, keyName, proxy, 'contentKeyWillChange'); _emberMetalObserver.removeObserver(item, keyName, proxy, 'contentKeyDidChange'); } } } }); enifed('ember-runtime/system/lazy_load', ['exports', 'ember-environment'], function (exports, _emberEnvironment) { /*globals CustomEvent */ 'use strict'; exports.onLoad = onLoad; exports.runLoadHooks = runLoadHooks; /** @module ember @submodule ember-runtime */ var loadHooks = _emberEnvironment.ENV.EMBER_LOAD_HOOKS || {}; var loaded = {}; var _loaded = loaded; exports._loaded = _loaded; /** Detects when a specific package of Ember (e.g. 'Ember.Application') has fully loaded and is available for extension. The provided `callback` will be called with the `name` passed resolved from a string into the object: ``` javascript Ember.onLoad('Ember.Application' function(hbars) { hbars.registerHelper(...); }); ``` @method onLoad @for Ember @param name {String} name of hook @param callback {Function} callback to be called @private */ function onLoad(name, callback) { var object = loaded[name]; loadHooks[name] = loadHooks[name] || []; loadHooks[name].push(callback); if (object) { callback(object); } } /** Called when an Ember.js package (e.g Ember.Application) has finished loading. Triggers any callbacks registered for this event. @method runLoadHooks @for Ember @param name {String} name of hook @param object {Object} object to pass to callbacks @private */ function runLoadHooks(name, object) { loaded[name] = object; var window = _emberEnvironment.environment.window; if (window && typeof CustomEvent === 'function') { var _event = new CustomEvent(name, { detail: object, name: name }); window.dispatchEvent(_event); } if (loadHooks[name]) { loadHooks[name].forEach(function (callback) { return callback(object); }); } } }); enifed('ember-runtime/system/namespace', ['exports', 'ember-metal/core', 'ember-environment', 'ember-metal/property_get', 'ember-metal/utils', 'ember-metal/mixin', 'ember-runtime/system/object'], function (exports, _emberMetalCore, _emberEnvironment, _emberMetalProperty_get, _emberMetalUtils, _emberMetalMixin, _emberRuntimeSystemObject) { /** @module ember @submodule ember-runtime */ 'use strict'; exports.isSearchDisabled = isSearchDisabled; exports.setSearchDisabled = setSearchDisabled; var searchDisabled = false; function isSearchDisabled() { return searchDisabled; } function setSearchDisabled(flag) { searchDisabled = !!flag; } /** A Namespace is an object usually used to contain other objects or methods such as an application or framework. Create a namespace anytime you want to define one of these new containers. # Example Usage ```javascript MyFramework = Ember.Namespace.create({ VERSION: '1.0.0' }); ``` @class Namespace @namespace Ember @extends Ember.Object @public */ var Namespace = _emberRuntimeSystemObject.default.extend({ isNamespace: true, init: function () { Namespace.NAMESPACES.push(this); Namespace.PROCESSED = false; }, toString: function () { var name = _emberMetalProperty_get.get(this, 'name') || _emberMetalProperty_get.get(this, 'modulePrefix'); if (name) { return name; } findNamespaces(); return this[_emberMetalMixin.NAME_KEY]; }, nameClasses: function () { processNamespace([this.toString()], this, {}); }, destroy: function () { var namespaces = Namespace.NAMESPACES; var toString = this.toString(); if (toString) { _emberEnvironment.context.lookup[toString] = undefined; delete Namespace.NAMESPACES_BY_ID[toString]; } namespaces.splice(namespaces.indexOf(this), 1); this._super.apply(this, arguments); } }); Namespace.reopenClass({ NAMESPACES: [_emberMetalCore.default], NAMESPACES_BY_ID: { Ember: _emberMetalCore.default }, PROCESSED: false, processAll: processAllNamespaces, byName: function (name) { if (!searchDisabled) { processAllNamespaces(); } return NAMESPACES_BY_ID[name]; } }); var NAMESPACES_BY_ID = Namespace.NAMESPACES_BY_ID; var hasOwnProp = ({}).hasOwnProperty; function processNamespace(paths, root, seen) { var idx = paths.length; NAMESPACES_BY_ID[paths.join('.')] = root; // Loop over all of the keys in the namespace, looking for classes for (var key in root) { if (!hasOwnProp.call(root, key)) { continue; } var obj = root[key]; // If we are processing the `Ember` namespace, for example, the // `paths` will start with `["Ember"]`. Every iteration through // the loop will update the **second** element of this list with // the key, so processing `Ember.View` will make the Array // `['Ember', 'View']`. paths[idx] = key; // If we have found an unprocessed class if (obj && obj.toString === classToString && !obj[_emberMetalMixin.NAME_KEY]) { // Replace the class' `toString` with the dot-separated path // and set its `NAME_KEY` obj[_emberMetalMixin.NAME_KEY] = paths.join('.'); // Support nested namespaces } else if (obj && obj.isNamespace) { // Skip aliased namespaces if (seen[_emberMetalUtils.guidFor(obj)]) { continue; } seen[_emberMetalUtils.guidFor(obj)] = true; // Process the child namespace processNamespace(paths, obj, seen); } } paths.length = idx; // cut out last item } function isUppercase(code) { return code >= 65 && // A code <= 90; // Z } function tryIsNamespace(lookup, prop) { try { var obj = lookup[prop]; return obj && obj.isNamespace && obj; } catch (e) { // continue } } function findNamespaces() { if (Namespace.PROCESSED) { return; } var lookup = _emberEnvironment.context.lookup; var keys = Object.keys(lookup); for (var i = 0; i < keys.length; i++) { var key = keys[i]; // Only process entities that start with uppercase A-Z if (!isUppercase(key.charCodeAt(0))) { continue; } var obj = tryIsNamespace(lookup, key); if (obj) { obj[_emberMetalMixin.NAME_KEY] = key; } } } function superClassString(mixin) { var superclass = mixin.superclass; if (superclass) { if (superclass[_emberMetalMixin.NAME_KEY]) { return superclass[_emberMetalMixin.NAME_KEY]; } return superClassString(superclass); } } function classToString() { if (!searchDisabled && !this[_emberMetalMixin.NAME_KEY]) { processAllNamespaces(); } var ret = undefined; if (this[_emberMetalMixin.NAME_KEY]) { ret = this[_emberMetalMixin.NAME_KEY]; } else if (this._toString) { ret = this._toString; } else { var str = superClassString(this); if (str) { ret = '(subclass of ' + str + ')'; } else { ret = '(unknown mixin)'; } this.toString = makeToString(ret); } return ret; } function processAllNamespaces() { var unprocessedNamespaces = !Namespace.PROCESSED; var unprocessedMixins = _emberMetalMixin.hasUnprocessedMixins(); if (unprocessedNamespaces) { findNamespaces(); Namespace.PROCESSED = true; } if (unprocessedNamespaces || unprocessedMixins) { var namespaces = Namespace.NAMESPACES; var namespace = undefined; for (var i = 0; i < namespaces.length; i++) { namespace = namespaces[i]; processNamespace([namespace.toString()], namespace, {}); } _emberMetalMixin.clearUnprocessedMixins(); } } function makeToString(ret) { return function () { return ret; }; } _emberMetalMixin.Mixin.prototype.toString = classToString; // ES6TODO: altering imported objects. SBB. exports.default = Namespace; }); // Preloaded into namespaces enifed('ember-runtime/system/native_array', ['exports', 'ember-metal/core', 'ember-environment', 'ember-metal/replace', 'ember-metal/property_get', 'ember-metal/mixin', 'ember-runtime/mixins/array', 'ember-runtime/mixins/mutable_array', 'ember-runtime/mixins/observable', 'ember-runtime/mixins/copyable', 'ember-runtime/mixins/freezable', 'ember-runtime/copy'], function (exports, _emberMetalCore, _emberEnvironment, _emberMetalReplace, _emberMetalProperty_get, _emberMetalMixin, _emberRuntimeMixinsArray, _emberRuntimeMixinsMutable_array, _emberRuntimeMixinsObservable, _emberRuntimeMixinsCopyable, _emberRuntimeMixinsFreezable, _emberRuntimeCopy) { /** @module ember @submodule ember-runtime */ 'use strict'; // Add Ember.Array to Array.prototype. Remove methods with native // implementations and supply some more optimized versions of generic methods // because they are so common. /** The NativeArray mixin contains the properties needed to make the native Array support Ember.MutableArray and all of its dependent APIs. Unless you have `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Array` set to false, this will be applied automatically. Otherwise you can apply the mixin at anytime by calling `Ember.NativeArray.apply(Array.prototype)`. @class NativeArray @namespace Ember @uses Ember.MutableArray @uses Ember.Observable @uses Ember.Copyable @public */ var NativeArray = _emberMetalMixin.Mixin.create(_emberRuntimeMixinsMutable_array.default, _emberRuntimeMixinsObservable.default, _emberRuntimeMixinsCopyable.default, { // because length is a built-in property we need to know to just get the // original property. get: function (key) { if ('number' === typeof key) { return this[key]; } else { return this._super(key); } }, objectAt: function (idx) { return this[idx]; }, // primitive for array support. replace: function (idx, amt, objects) { if (this.isFrozen) { throw _emberRuntimeMixinsFreezable.FROZEN_ERROR; } // if we replaced exactly the same number of items, then pass only the // replaced range. Otherwise, pass the full remaining array length // since everything has shifted var len = objects ? _emberMetalProperty_get.get(objects, 'length') : 0; _emberRuntimeMixinsArray.arrayContentWillChange(this, idx, amt, len); if (len === 0) { this.splice(idx, amt); } else { _emberMetalReplace.default(this, idx, amt, objects); } _emberRuntimeMixinsArray.arrayContentDidChange(this, idx, amt, len); return this; }, // If you ask for an unknown property, then try to collect the value // from member items. unknownProperty: function (key, value) { var ret = undefined; // = this.reducedProperty(key, value); if (value !== undefined && ret === undefined) { ret = this[key] = value; } return ret; }, indexOf: Array.prototype.indexOf, lastIndexOf: Array.prototype.lastIndexOf, copy: function (deep) { if (deep) { return this.map(function (item) { return _emberRuntimeCopy.default(item, true); }); } return this.slice(); } }); // Remove any methods implemented natively so we don't override them var ignore = ['length']; NativeArray.keys().forEach(function (methodName) { if (Array.prototype[methodName]) { ignore.push(methodName); } }); exports.NativeArray // TODO: only use default export = NativeArray = NativeArray.without.apply(NativeArray, ignore); /** Creates an `Ember.NativeArray` from an Array like object. Does not modify the original object. Ember.A is not needed if `EmberENV.EXTEND_PROTOTYPES` is `true` (the default value). However, it is recommended that you use Ember.A when creating addons for ember or when you can not guarantee that `EmberENV.EXTEND_PROTOTYPES` will be `true`. Example ```js export default Ember.Component.extend({ tagName: 'ul', classNames: ['pagination'], init() { this._super(...arguments); if (!this.get('content')) { this.set('content', Ember.A()); } } }); ``` @method A @for Ember @return {Ember.NativeArray} @public */ var A = undefined; if (_emberEnvironment.ENV.EXTEND_PROTOTYPES.Array) { NativeArray.apply(Array.prototype); exports. // ES6TODO: Setting A onto the object returned by ember-metal/core to avoid circles A = A = function (arr) { return arr || []; }; } else { exports.A = A = function (arr) { if (!arr) { arr = []; } return _emberRuntimeMixinsArray.default.detect(arr) ? arr : NativeArray.apply(arr); }; } _emberMetalCore.default.A = A;exports.A = A; exports.NativeArray = NativeArray; exports.default = NativeArray; }); // Ember.A circular enifed('ember-runtime/system/object', ['exports', 'ember-runtime/system/core_object', 'ember-runtime/mixins/observable'], function (exports, _emberRuntimeSystemCore_object, _emberRuntimeMixinsObservable) { /** @module ember @submodule ember-runtime */ 'use strict'; /** `Ember.Object` is the main base class for all Ember objects. It is a subclass of `Ember.CoreObject` with the `Ember.Observable` mixin applied. For details, see the documentation for each of these. @class Object @namespace Ember @extends Ember.CoreObject @uses Ember.Observable @public */ var EmberObject = _emberRuntimeSystemCore_object.default.extend(_emberRuntimeMixinsObservable.default); EmberObject.toString = function () { return 'Ember.Object'; }; exports.default = EmberObject; }); enifed('ember-runtime/system/object_proxy', ['exports', 'ember-runtime/system/object', 'ember-runtime/mixins/-proxy'], function (exports, _emberRuntimeSystemObject, _emberRuntimeMixinsProxy) { 'use strict'; /** `Ember.ObjectProxy` forwards all properties not defined by the proxy itself to a proxied `content` object. ```javascript object = Ember.Object.create({ name: 'Foo' }); proxy = Ember.ObjectProxy.create({ content: object }); // Access and change existing properties proxy.get('name') // 'Foo' proxy.set('name', 'Bar'); object.get('name') // 'Bar' // Create new 'description' property on `object` proxy.set('description', 'Foo is a whizboo baz'); object.get('description') // 'Foo is a whizboo baz' ``` While `content` is unset, setting a property to be delegated will throw an Error. ```javascript proxy = Ember.ObjectProxy.create({ content: null, flag: null }); proxy.set('flag', true); proxy.get('flag'); // true proxy.get('foo'); // undefined proxy.set('foo', 'data'); // throws Error ``` Delegated properties can be bound to and will change when content is updated. Computed properties on the proxy itself can depend on delegated properties. ```javascript ProxyWithComputedProperty = Ember.ObjectProxy.extend({ fullName: function() { var firstName = this.get('firstName'), lastName = this.get('lastName'); if (firstName && lastName) { return firstName + ' ' + lastName; } return firstName || lastName; }.property('firstName', 'lastName') }); proxy = ProxyWithComputedProperty.create(); proxy.get('fullName'); // undefined proxy.set('content', { firstName: 'Tom', lastName: 'Dale' }); // triggers property change for fullName on proxy proxy.get('fullName'); // 'Tom Dale' ``` @class ObjectProxy @namespace Ember @extends Ember.Object @extends Ember._ProxyMixin @public */ exports.default = _emberRuntimeSystemObject.default.extend(_emberRuntimeMixinsProxy.default); }); enifed('ember-runtime/system/service', ['exports', 'ember-runtime/system/object', 'ember-runtime/inject'], function (exports, _emberRuntimeSystemObject, _emberRuntimeInject) { 'use strict'; /** Creates a property that lazily looks up a service in the container. There are no restrictions as to what objects a service can be injected into. Example: ```javascript App.ApplicationRoute = Ember.Route.extend({ authManager: Ember.inject.service('auth'), model: function() { return this.get('authManager').findCurrentUser(); } }); ``` This example will create an `authManager` property on the application route that looks up the `auth` service in the container, making it easily accessible in the `model` hook. @method service @since 1.10.0 @for Ember.inject @param {String} name (optional) name of the service to inject, defaults to the property's name @return {Ember.InjectedProperty} injection descriptor instance @public */ _emberRuntimeInject.createInjectionHelper('service'); /** @class Service @namespace Ember @extends Ember.Object @since 1.10.0 @public */ var Service = _emberRuntimeSystemObject.default.extend(); Service.reopenClass({ isServiceFactory: true }); exports.default = Service; }); enifed('ember-runtime/system/string', ['exports', 'ember-metal/debug', 'ember-metal/utils', 'ember-runtime/utils', 'ember-runtime/string_registry', 'ember-metal/cache'], function (exports, _emberMetalDebug, _emberMetalUtils, _emberRuntimeUtils, _emberRuntimeString_registry, _emberMetalCache) { /** @module ember @submodule ember-runtime */ 'use strict'; var STRING_DASHERIZE_REGEXP = /[ _]/g; var STRING_DASHERIZE_CACHE = new _emberMetalCache.default(1000, function (key) { return decamelize(key).replace(STRING_DASHERIZE_REGEXP, '-'); }); var STRING_CAMELIZE_REGEXP_1 = /(\-|\_|\.|\s)+(.)?/g; var STRING_CAMELIZE_REGEXP_2 = /(^|\/)([A-Z])/g; var CAMELIZE_CACHE = new _emberMetalCache.default(1000, function (key) { return key.replace(STRING_CAMELIZE_REGEXP_1, function (match, separator, chr) { return chr ? chr.toUpperCase() : ''; }).replace(STRING_CAMELIZE_REGEXP_2, function (match, separator, chr) { return match.toLowerCase(); }); }); var STRING_CLASSIFY_REGEXP_1 = /^(\-|_)+(.)?/; var STRING_CLASSIFY_REGEXP_2 = /(.)(\-|\_|\.|\s)+(.)?/g; var STRING_CLASSIFY_REGEXP_3 = /(^|\/|\.)([a-z])/g; var CLASSIFY_CACHE = new _emberMetalCache.default(1000, function (str) { var replace1 = function (match, separator, chr) { return chr ? '_' + chr.toUpperCase() : ''; }; var replace2 = function (match, initialChar, separator, chr) { return initialChar + (chr ? chr.toUpperCase() : ''); }; var parts = str.split('/'); for (var i = 0; i < parts.length; i++) { parts[i] = parts[i].replace(STRING_CLASSIFY_REGEXP_1, replace1).replace(STRING_CLASSIFY_REGEXP_2, replace2); } return parts.join('/').replace(STRING_CLASSIFY_REGEXP_3, function (match, separator, chr) { return match.toUpperCase(); }); }); var STRING_UNDERSCORE_REGEXP_1 = /([a-z\d])([A-Z]+)/g; var STRING_UNDERSCORE_REGEXP_2 = /\-|\s+/g; var UNDERSCORE_CACHE = new _emberMetalCache.default(1000, function (str) { return str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2').replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase(); }); var STRING_CAPITALIZE_REGEXP = /(^|\/)([a-z])/g; var CAPITALIZE_CACHE = new _emberMetalCache.default(1000, function (str) { return str.replace(STRING_CAPITALIZE_REGEXP, function (match, separator, chr) { return match.toUpperCase(); }); }); var STRING_DECAMELIZE_REGEXP = /([a-z\d])([A-Z])/g; var DECAMELIZE_CACHE = new _emberMetalCache.default(1000, function (str) { return str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase(); }); function _fmt(str, formats) { var cachedFormats = formats; if (!_emberRuntimeUtils.isArray(cachedFormats) || arguments.length > 2) { cachedFormats = new Array(arguments.length - 1); for (var i = 1; i < arguments.length; i++) { cachedFormats[i - 1] = arguments[i]; } } // first, replace any ORDERED replacements. var idx = 0; // the current index for non-numerical replacements return str.replace(/%@([0-9]+)?/g, function (s, argIndex) { argIndex = argIndex ? parseInt(argIndex, 10) - 1 : idx++; s = cachedFormats[argIndex]; return s === null ? '(null)' : s === undefined ? '' : _emberMetalUtils.inspect(s); }); } function fmt(str, formats) { _emberMetalDebug.deprecate('Ember.String.fmt is deprecated, use ES6 template strings instead.', false, { id: 'ember-string-utils.fmt', until: '3.0.0', url: 'http://babeljs.io/docs/learn-es2015/#template-strings' }); return _fmt.apply(undefined, arguments); } function loc(str, formats) { if (!_emberRuntimeUtils.isArray(formats) || arguments.length > 2) { formats = Array.prototype.slice.call(arguments, 1); } str = _emberRuntimeString_registry.get(str) || str; return _fmt(str, formats); } function w(str) { return str.split(/\s+/); } function decamelize(str) { return DECAMELIZE_CACHE.get(str); } function dasherize(str) { return STRING_DASHERIZE_CACHE.get(str); } function camelize(str) { return CAMELIZE_CACHE.get(str); } function classify(str) { return CLASSIFY_CACHE.get(str); } function underscore(str) { return UNDERSCORE_CACHE.get(str); } function capitalize(str) { return CAPITALIZE_CACHE.get(str); } /** Defines string helper methods including string formatting and localization. Unless `EmberENV.EXTEND_PROTOTYPES.String` is `false` these methods will also be added to the `String.prototype` as well. @class String @namespace Ember @static @public */ exports.default = { /** Apply formatting options to the string. This will look for occurrences of "%@" in your string and substitute them with the arguments you pass into this method. If you want to control the specific order of replacement, you can add a number after the key as well to indicate which argument you want to insert. Ordered insertions are most useful when building loc strings where values you need to insert may appear in different orders. ```javascript "Hello %@ %@".fmt('John', 'Doe'); // "Hello John Doe" "Hello %@2, %@1".fmt('John', 'Doe'); // "Hello Doe, John" ``` @method fmt @param {String} str The string to format @param {Array} formats An array of parameters to interpolate into string. @return {String} formatted string @public @deprecated Use ES6 template strings instead: http://babeljs.io/docs/learn-es2015/#template-strings */ fmt: fmt, /** Formats the passed string, but first looks up the string in the localized strings hash. This is a convenient way to localize text. See `Ember.String.fmt()` for more information on formatting. Note that it is traditional but not required to prefix localized string keys with an underscore or other character so you can easily identify localized strings. ```javascript Ember.STRINGS = { '_Hello World': 'Bonjour le monde', '_Hello %@ %@': 'Bonjour %@ %@' }; Ember.String.loc("_Hello World"); // 'Bonjour le monde'; Ember.String.loc("_Hello %@ %@", ["John", "Smith"]); // "Bonjour John Smith"; ``` @method loc @param {String} str The string to format @param {Array} formats Optional array of parameters to interpolate into string. @return {String} formatted string @public */ loc: loc, /** Splits a string into separate units separated by spaces, eliminating any empty strings in the process. This is a convenience method for split that is mostly useful when applied to the `String.prototype`. ```javascript Ember.String.w("alpha beta gamma").forEach(function(key) { console.log(key); }); // > alpha // > beta // > gamma ``` @method w @param {String} str The string to split @return {Array} array containing the split strings @public */ w: w, /** Converts a camelized string into all lower case separated by underscores. ```javascript 'innerHTML'.decamelize(); // 'inner_html' 'action_name'.decamelize(); // 'action_name' 'css-class-name'.decamelize(); // 'css-class-name' 'my favorite items'.decamelize(); // 'my favorite items' ``` @method decamelize @param {String} str The string to decamelize. @return {String} the decamelized string. @public */ decamelize: decamelize, /** Replaces underscores, spaces, or camelCase with dashes. ```javascript 'innerHTML'.dasherize(); // 'inner-html' 'action_name'.dasherize(); // 'action-name' 'css-class-name'.dasherize(); // 'css-class-name' 'my favorite items'.dasherize(); // 'my-favorite-items' 'privateDocs/ownerInvoice'.dasherize(); // 'private-docs/owner-invoice' ``` @method dasherize @param {String} str The string to dasherize. @return {String} the dasherized string. @public */ dasherize: dasherize, /** Returns the lowerCamelCase form of a string. ```javascript 'innerHTML'.camelize(); // 'innerHTML' 'action_name'.camelize(); // 'actionName' 'css-class-name'.camelize(); // 'cssClassName' 'my favorite items'.camelize(); // 'myFavoriteItems' 'My Favorite Items'.camelize(); // 'myFavoriteItems' 'private-docs/owner-invoice'.camelize(); // 'privateDocs/ownerInvoice' ``` @method camelize @param {String} str The string to camelize. @return {String} the camelized string. @public */ camelize: camelize, /** Returns the UpperCamelCase form of a string. ```javascript 'innerHTML'.classify(); // 'InnerHTML' 'action_name'.classify(); // 'ActionName' 'css-class-name'.classify(); // 'CssClassName' 'my favorite items'.classify(); // 'MyFavoriteItems' 'private-docs/owner-invoice'.classify(); // 'PrivateDocs/OwnerInvoice' ``` @method classify @param {String} str the string to classify @return {String} the classified string @public */ classify: classify, /** More general than decamelize. Returns the lower\_case\_and\_underscored form of a string. ```javascript 'innerHTML'.underscore(); // 'inner_html' 'action_name'.underscore(); // 'action_name' 'css-class-name'.underscore(); // 'css_class_name' 'my favorite items'.underscore(); // 'my_favorite_items' 'privateDocs/ownerInvoice'.underscore(); // 'private_docs/owner_invoice' ``` @method underscore @param {String} str The string to underscore. @return {String} the underscored string. @public */ underscore: underscore, /** Returns the Capitalized form of a string ```javascript 'innerHTML'.capitalize() // 'InnerHTML' 'action_name'.capitalize() // 'Action_name' 'css-class-name'.capitalize() // 'Css-class-name' 'my favorite items'.capitalize() // 'My favorite items' 'privateDocs/ownerInvoice'.capitalize(); // 'PrivateDocs/ownerInvoice' ``` @method capitalize @param {String} str The string to capitalize. @return {String} The capitalized string. @public */ capitalize: capitalize }; exports.fmt = fmt; exports.loc = loc; exports.w = w; exports.decamelize = decamelize; exports.dasherize = dasherize; exports.camelize = camelize; exports.classify = classify; exports.underscore = underscore; exports.capitalize = capitalize; }); enifed('ember-runtime/utils', ['exports', 'ember-runtime/mixins/array', 'ember-runtime/system/object'], function (exports, _emberRuntimeMixinsArray, _emberRuntimeSystemObject) { 'use strict'; exports.isArray = isArray; exports.typeOf = typeOf; // ........................................ // TYPING & ARRAY MESSAGING // var TYPE_MAP = { '[object Boolean]': 'boolean', '[object Number]': 'number', '[object String]': 'string', '[object Function]': 'function', '[object Array]': 'array', '[object Date]': 'date', '[object RegExp]': 'regexp', '[object Object]': 'object' }; var toString = Object.prototype.toString; /** Returns true if the passed object is an array or Array-like. Objects are considered Array-like if any of the following are true: - the object is a native Array - the object has an objectAt property - the object is an Object, and has a length property Unlike `Ember.typeOf` this method returns true even if the passed object is not formally an array but appears to be array-like (i.e. implements `Ember.Array`) ```javascript Ember.isArray(); // false Ember.isArray([]); // true Ember.isArray(Ember.ArrayProxy.create({ content: [] })); // true ``` @method isArray @for Ember @param {Object} obj The object to test @return {Boolean} true if the passed object is an array or Array-like @public */ function isArray(obj) { if (!obj || obj.setInterval) { return false; } if (Array.isArray(obj)) { return true; } if (_emberRuntimeMixinsArray.default.detect(obj)) { return true; } var type = typeOf(obj); if ('array' === type) { return true; } if (obj.length !== undefined && 'object' === type) { return true; } return false; } /** Returns a consistent type for the passed object. Use this instead of the built-in `typeof` to get the type of an item. It will return the same result across all browsers and includes a bit more detail. Here is what will be returned: | Return Value | Meaning | |---------------|------------------------------------------------------| | 'string' | String primitive or String object. | | 'number' | Number primitive or Number object. | | 'boolean' | Boolean primitive or Boolean object. | | 'null' | Null value | | 'undefined' | Undefined value | | 'function' | A function | | 'array' | An instance of Array | | 'regexp' | An instance of RegExp | | 'date' | An instance of Date | | 'class' | An Ember class (created using Ember.Object.extend()) | | 'instance' | An Ember object instance | | 'error' | An instance of the Error object | | 'object' | A JavaScript object not inheriting from Ember.Object | Examples: ```javascript Ember.typeOf(); // 'undefined' Ember.typeOf(null); // 'null' Ember.typeOf(undefined); // 'undefined' Ember.typeOf('michael'); // 'string' Ember.typeOf(new String('michael')); // 'string' Ember.typeOf(101); // 'number' Ember.typeOf(new Number(101)); // 'number' Ember.typeOf(true); // 'boolean' Ember.typeOf(new Boolean(true)); // 'boolean' Ember.typeOf(Ember.makeArray); // 'function' Ember.typeOf([1, 2, 90]); // 'array' Ember.typeOf(/abc/); // 'regexp' Ember.typeOf(new Date()); // 'date' Ember.typeOf(Ember.Object.extend()); // 'class' Ember.typeOf(Ember.Object.create()); // 'instance' Ember.typeOf(new Error('teamocil')); // 'error' // 'normal' JavaScript object Ember.typeOf({ a: 'b' }); // 'object' ``` @method typeOf @for Ember @param {Object} item the item to check @return {String} the type @public */ function typeOf(item) { if (item === null) { return 'null'; } if (item === undefined) { return 'undefined'; } var ret = TYPE_MAP[toString.call(item)] || 'object'; if (ret === 'function') { if (_emberRuntimeSystemObject.default.detect(item)) { ret = 'class'; } } else if (ret === 'object') { if (item instanceof Error) { ret = 'error'; } else if (item instanceof _emberRuntimeSystemObject.default) { ret = 'instance'; } else if (item instanceof Date) { ret = 'date'; } } return ret; } }); enifed('ember-templates/compat', ['exports', 'ember-metal/core', 'ember-templates/template', 'ember-templates/string', 'ember-runtime/system/string', 'ember-metal/features', 'ember-templates/make-bound-helper'], function (exports, _emberMetalCore, _emberTemplatesTemplate, _emberTemplatesString, _emberRuntimeSystemString, _emberMetalFeatures, _emberTemplatesMakeBoundHelper) { 'use strict'; var EmberHandlebars = _emberMetalCore.default.Handlebars = _emberMetalCore.default.Handlebars || {}; exports.EmberHandlebars = EmberHandlebars; var EmberHTMLBars = _emberMetalCore.default.HTMLBars = _emberMetalCore.default.HTMLBars || {}; exports.EmberHTMLBars = EmberHTMLBars; var EmberHandleBarsUtils = EmberHandlebars.Utils = EmberHandlebars.Utils || {}; exports.EmberHandleBarsUtils = EmberHandleBarsUtils; Object.defineProperty(EmberHandlebars, 'SafeString', { get: _emberTemplatesString.getSafeString }); EmberHTMLBars.template = EmberHandlebars.template = _emberTemplatesTemplate.default; EmberHandleBarsUtils.escapeExpression = _emberTemplatesString.escapeExpression; _emberRuntimeSystemString.default.htmlSafe = _emberTemplatesString.htmlSafe; if (true) { _emberRuntimeSystemString.default.isHTMLSafe = _emberTemplatesString.isHTMLSafe; } EmberHTMLBars.makeBoundHelper = _emberTemplatesMakeBoundHelper.default; }); // reexports enifed('ember-templates/component', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/component').default; } else { return _require.default('ember-htmlbars/component').default; } })(); }); enifed('ember-templates/components/checkbox', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/components/checkbox').default; } else { return _require.default('ember-htmlbars/components/checkbox').default; } })(); }); enifed('ember-templates/components/link-to', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/components/link-to').default; } else { return _require.default('ember-htmlbars/components/link-to').default; } })(); }); enifed('ember-templates/components/text_area', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/components/text_area').default; } else { return _require.default('ember-htmlbars/components/text_area').default; } })(); }); enifed('ember-templates/components/text_field', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/components/text_field').default; } else { return _require.default('ember-htmlbars/components/text_field').default; } })(); }); enifed('ember-templates/helper', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/helper').default; } else { return _require.default('ember-htmlbars/helper').default; } })(); var helper = (function () { if (false) { return _require.default('ember-glimmer/helper').helper; } else { return _require.default('ember-htmlbars/helper').helper; } })(); exports.helper = helper; }); enifed('ember-templates/index', ['exports', 'ember-metal/core', 'ember-templates/template_registry', 'ember-templates/renderer', 'ember-templates/component', 'ember-templates/helper', 'ember-templates/components/checkbox', 'ember-templates/components/text_field', 'ember-templates/components/text_area', 'ember-templates/components/link-to', 'ember-templates/string', 'ember-environment', 'ember-templates/compat'], function (exports, _emberMetalCore, _emberTemplatesTemplate_registry, _emberTemplatesRenderer, _emberTemplatesComponent, _emberTemplatesHelper, _emberTemplatesComponentsCheckbox, _emberTemplatesComponentsText_field, _emberTemplatesComponentsText_area, _emberTemplatesComponentsLinkTo, _emberTemplatesString, _emberEnvironment, _emberTemplatesCompat) { 'use strict'; _emberMetalCore.default._Renderer = _emberTemplatesRenderer.Renderer; _emberMetalCore.default.Component = _emberTemplatesComponent.default; _emberTemplatesHelper.default.helper = _emberTemplatesHelper.helper; _emberMetalCore.default.Helper = _emberTemplatesHelper.default; _emberMetalCore.default.Checkbox = _emberTemplatesComponentsCheckbox.default; _emberMetalCore.default.TextField = _emberTemplatesComponentsText_field.default; _emberMetalCore.default.TextArea = _emberTemplatesComponentsText_area.default; _emberMetalCore.default.LinkComponent = _emberTemplatesComponentsLinkTo.default; if (_emberEnvironment.ENV.EXTEND_PROTOTYPES.String) { String.prototype.htmlSafe = function () { return _emberTemplatesString.htmlSafe(this); }; } /** Global hash of shared templates. This will automatically be populated by the build tools so that you can store your Handlebars templates in separate files that get loaded into JavaScript at buildtime. @property TEMPLATES @for Ember @type Object @private */ Object.defineProperty(_emberMetalCore.default, 'TEMPLATES', { get: _emberTemplatesTemplate_registry.getTemplates, set: _emberTemplatesTemplate_registry.setTemplates, configurable: false, enumerable: false }); exports.default = _emberMetalCore.default; }); // reexports enifed('ember-templates/make-bound-helper', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/make-bound-helper').default; } else { return _require.default('ember-htmlbars/make-bound-helper').default; } })(); }); enifed('ember-templates/renderer', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; var InteractiveRenderer = (function () { if (false) { return _require.default('ember-glimmer/renderer').InteractiveRenderer; } else { return _require.default('ember-htmlbars/renderer').InteractiveRenderer; } })(); exports.InteractiveRenderer = InteractiveRenderer; var InertRenderer = (function () { if (false) { return _require.default('ember-glimmer/renderer').InertRenderer; } else { return _require.default('ember-htmlbars/renderer').InertRenderer; } })(); exports.InertRenderer = InertRenderer; var Renderer = (function () { if (false) { return _require.default('ember-glimmer/renderer').Renderer; } else { return _require.default('ember-htmlbars/renderer').Renderer; } })(); exports.Renderer = Renderer; }); enifed('ember-templates/string', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; var strings = (function () { if (false) { return _require.default('ember-glimmer/utils/string'); } else { return _require.default('ember-htmlbars/utils/string'); } })(); var SafeString = strings.SafeString; exports.SafeString = SafeString; var escapeExpression = strings.escapeExpression; exports.escapeExpression = escapeExpression; var htmlSafe = strings.htmlSafe; exports.htmlSafe = htmlSafe; var isHTMLSafe = strings.isHTMLSafe; exports.isHTMLSafe = isHTMLSafe; var getSafeString = strings.getSafeString; exports.getSafeString = getSafeString; }); enifed('ember-templates/template', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; var htmlbarsTemplate = undefined, glimmerTemplate = undefined; if (_require.has('ember-htmlbars')) { htmlbarsTemplate = _require.default('ember-htmlbars').template; } if (_require.has('ember-glimmer')) { glimmerTemplate = _require.default('ember-glimmer').template; } var template = false ? glimmerTemplate : htmlbarsTemplate; exports.default = template; }); enifed("ember-templates/template_registry", ["exports"], function (exports) { // STATE within a module is frowned apon, this exists // to support Ember.TEMPLATES but shield ember internals from this legacy // global API. "use strict"; exports.setTemplates = setTemplates; exports.getTemplates = getTemplates; exports.get = get; exports.has = has; exports.set = set; var TEMPLATES = {}; function setTemplates(templates) { TEMPLATES = templates; } function getTemplates() { return TEMPLATES; } function get(name) { if (TEMPLATES.hasOwnProperty(name)) { return TEMPLATES[name]; } } function has(name) { return TEMPLATES.hasOwnProperty(name); } function set(name, template) { return TEMPLATES[name] = template; } }); enifed('ember-testing/adapters/adapter', ['exports', 'ember-runtime/system/object'], function (exports, _emberRuntimeSystemObject) { 'use strict'; function K() { return this; } /** @module ember @submodule ember-testing */ /** The primary purpose of this class is to create hooks that can be implemented by an adapter for various test frameworks. @class Adapter @namespace Ember.Test @public */ exports.default = _emberRuntimeSystemObject.default.extend({ /** This callback will be called whenever an async operation is about to start. Override this to call your framework's methods that handle async operations. @public @method asyncStart */ asyncStart: K, /** This callback will be called whenever an async operation has completed. @public @method asyncEnd */ asyncEnd: K, /** Override this method with your testing framework's false assertion. This function is called whenever an exception occurs causing the testing promise to fail. QUnit example: ```javascript exception: function(error) { ok(false, error); }; ``` @public @method exception @param {String} error The exception to be raised. */ exception: function (error) { throw error; } }); }); enifed('ember-testing/adapters/qunit', ['exports', 'ember-testing/adapters/adapter', 'ember-metal/utils'], function (exports, _emberTestingAdaptersAdapter, _emberMetalUtils) { 'use strict'; /** This class implements the methods defined by Ember.Test.Adapter for the QUnit testing framework. @class QUnitAdapter @namespace Ember.Test @extends Ember.Test.Adapter @public */ exports.default = _emberTestingAdaptersAdapter.default.extend({ asyncStart: function () { QUnit.stop(); }, asyncEnd: function () { QUnit.start(); }, exception: function (error) { ok(false, _emberMetalUtils.inspect(error)); } }); }); enifed('ember-testing/events', ['exports', 'ember-views/system/jquery', 'ember-metal/run_loop'], function (exports, _emberViewsSystemJquery, _emberMetalRun_loop) { 'use strict'; exports.focus = focus; exports.fireEvent = fireEvent; var DEFAULT_EVENT_OPTIONS = { canBubble: true, cancelable: true }; var KEYBOARD_EVENT_TYPES = ['keydown', 'keypress', 'keyup']; var MOUSE_EVENT_TYPES = ['click', 'mousedown', 'mouseup', 'dblclick', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover']; function focus(el) { if (!el) { return; } var $el = _emberViewsSystemJquery.default(el); if ($el.is(':input, [contenteditable=true]')) { var type = $el.prop('type'); if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') { _emberMetalRun_loop.default(null, function () { // Firefox does not trigger the `focusin` event if the window // does not have focus. If the document doesn't have focus just // use trigger('focusin') instead. if (!document.hasFocus || document.hasFocus()) { el.focus(); } else { $el.trigger('focusin'); } }); } } } function fireEvent(element, type) { var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; if (!element) { return; } var event = undefined; if (KEYBOARD_EVENT_TYPES.indexOf(type) > -1) { event = buildKeyboardEvent(type, options); } else if (MOUSE_EVENT_TYPES.indexOf(type) > -1) { var rect = element.getBoundingClientRect(); var x = rect.left + 1; var y = rect.top + 1; var simulatedCoordinates = { screenX: x + 5, screenY: y + 95, clientX: x, clientY: y }; event = buildMouseEvent(type, _emberViewsSystemJquery.default.extend(simulatedCoordinates, options)); } else { event = buildBasicEvent(type, options); } element.dispatchEvent(event); } function buildBasicEvent(type) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var event = document.createEvent('Events'); event.initEvent(type, true, true); _emberViewsSystemJquery.default.extend(event, options); return event; } function buildMouseEvent(type) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var event = undefined; try { event = document.createEvent('MouseEvents'); var eventOpts = _emberViewsSystemJquery.default.extend({}, DEFAULT_EVENT_OPTIONS, options); event.initMouseEvent(type, eventOpts.canBubble, eventOpts.cancelable, window, eventOpts.detail, eventOpts.screenX, eventOpts.screenY, eventOpts.clientX, eventOpts.clientY, eventOpts.ctrlKey, eventOpts.altKey, eventOpts.shiftKey, eventOpts.metaKey, eventOpts.button, eventOpts.relatedTarget); } catch (e) { event = buildBasicEvent(type, options); } return event; } function buildKeyboardEvent(type) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var event = undefined; try { event = document.createEvent('KeyEvents'); var eventOpts = _emberViewsSystemJquery.default.extend({}, DEFAULT_EVENT_OPTIONS, options); event.initKeyEvent(type, eventOpts.canBubble, eventOpts.cancelable, window, eventOpts.ctrlKey, eventOpts.altKey, eventOpts.shiftKey, eventOpts.metaKey, eventOpts.keyCode, eventOpts.charCode); } catch (e) { event = buildBasicEvent(type, options); } return event; } }); enifed('ember-testing/ext/application', ['exports', 'ember-application/system/application', 'ember-testing/setup_for_testing', 'ember-testing/test/helpers', 'ember-testing/test/promise', 'ember-testing/test/run', 'ember-testing/test/on_inject_helpers', 'ember-testing/test/adapter'], function (exports, _emberApplicationSystemApplication, _emberTestingSetup_for_testing, _emberTestingTestHelpers, _emberTestingTestPromise, _emberTestingTestRun, _emberTestingTestOn_inject_helpers, _emberTestingTestAdapter) { 'use strict'; _emberApplicationSystemApplication.default.reopen({ /** This property contains the testing helpers for the current application. These are created once you call `injectTestHelpers` on your `Ember.Application` instance. The included helpers are also available on the `window` object by default, but can be used from this object on the individual application also. @property testHelpers @type {Object} @default {} @public */ testHelpers: {}, /** This property will contain the original methods that were registered on the `helperContainer` before `injectTestHelpers` is called. When `removeTestHelpers` is called, these methods are restored to the `helperContainer`. @property originalMethods @type {Object} @default {} @private @since 1.3.0 */ originalMethods: {}, /** This property indicates whether or not this application is currently in testing mode. This is set when `setupForTesting` is called on the current application. @property testing @type {Boolean} @default false @since 1.3.0 @public */ testing: false, /** This hook defers the readiness of the application, so that you can start the app when your tests are ready to run. It also sets the router's location to 'none', so that the window's location will not be modified (preventing both accidental leaking of state between tests and interference with your testing framework). Example: ``` App.setupForTesting(); ``` @method setupForTesting @public */ setupForTesting: function () { _emberTestingSetup_for_testing.default(); this.testing = true; this.Router.reopen({ location: 'none' }); }, /** This will be used as the container to inject the test helpers into. By default the helpers are injected into `window`. @property helperContainer @type {Object} The object to be used for test helpers. @default window @since 1.2.0 @private */ helperContainer: null, /** This injects the test helpers into the `helperContainer` object. If an object is provided it will be used as the helperContainer. If `helperContainer` is not set it will default to `window`. If a function of the same name has already been defined it will be cached (so that it can be reset if the helper is removed with `unregisterHelper` or `removeTestHelpers`). Any callbacks registered with `onInjectHelpers` will be called once the helpers have been injected. Example: ``` App.injectTestHelpers(); ``` @method injectTestHelpers @public */ injectTestHelpers: function (helperContainer) { if (helperContainer) { this.helperContainer = helperContainer; } else { this.helperContainer = window; } this.reopen({ willDestroy: function () { this._super.apply(this, arguments); this.removeTestHelpers(); } }); this.testHelpers = {}; for (var _name in _emberTestingTestHelpers.helpers) { this.originalMethods[_name] = this.helperContainer[_name]; this.testHelpers[_name] = this.helperContainer[_name] = helper(this, _name); protoWrap(_emberTestingTestPromise.default.prototype, _name, helper(this, _name), _emberTestingTestHelpers.helpers[_name].meta.wait); } _emberTestingTestOn_inject_helpers.invokeInjectHelpersCallbacks(this); }, /** This removes all helpers that have been registered, and resets and functions that were overridden by the helpers. Example: ```javascript App.removeTestHelpers(); ``` @public @method removeTestHelpers */ removeTestHelpers: function () { if (!this.helperContainer) { return; } for (var _name2 in _emberTestingTestHelpers.helpers) { this.helperContainer[_name2] = this.originalMethods[_name2]; delete _emberTestingTestPromise.default.prototype[_name2]; delete this.testHelpers[_name2]; delete this.originalMethods[_name2]; } } }); // This method is no longer needed // But still here for backwards compatibility // of helper chaining function protoWrap(proto, name, callback, isAsync) { proto[name] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (isAsync) { return callback.apply(this, args); } else { return this.then(function () { return callback.apply(this, args); }); } }; } function helper(app, name) { var fn = _emberTestingTestHelpers.helpers[name].method; var meta = _emberTestingTestHelpers.helpers[name].meta; if (!meta.wait) { return function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return fn.apply(app, [app].concat(args)); }; } return function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } var lastPromise = _emberTestingTestRun.default(function () { return _emberTestingTestPromise.resolve(_emberTestingTestPromise.getLastPromise()); }); // wait for last helper's promise to resolve and then // execute. To be safe, we need to tell the adapter we're going // asynchronous here, because fn may not be invoked before we // return. _emberTestingTestAdapter.asyncStart(); return lastPromise.then(function () { return fn.apply(app, [app].concat(args)); }).finally(_emberTestingTestAdapter.asyncEnd); }; } }); enifed('ember-testing/ext/rsvp', ['exports', 'ember-runtime/ext/rsvp', 'ember-metal/run_loop', 'ember-metal/testing', 'ember-testing/test/adapter'], function (exports, _emberRuntimeExtRsvp, _emberMetalRun_loop, _emberMetalTesting, _emberTestingTestAdapter) { 'use strict'; _emberRuntimeExtRsvp.default.configure('async', function (callback, promise) { // if schedule will cause autorun, we need to inform adapter if (_emberMetalTesting.isTesting() && !_emberMetalRun_loop.default.backburner.currentInstance) { _emberTestingTestAdapter.asyncStart(); _emberMetalRun_loop.default.backburner.schedule('actions', function () { _emberTestingTestAdapter.asyncEnd(); callback(promise); }); } else { _emberMetalRun_loop.default.backburner.schedule('actions', function () { return callback(promise); }); } }); exports.default = _emberRuntimeExtRsvp.default; }); enifed('ember-testing/helpers', ['exports', 'ember-testing/test/helpers', 'ember-testing/helpers/and_then', 'ember-testing/helpers/click', 'ember-testing/helpers/current_path', 'ember-testing/helpers/current_route_name', 'ember-testing/helpers/current_url', 'ember-testing/helpers/fill_in', 'ember-testing/helpers/find', 'ember-testing/helpers/find_with_assert', 'ember-testing/helpers/key_event', 'ember-testing/helpers/pause_test', 'ember-testing/helpers/trigger_event', 'ember-testing/helpers/visit', 'ember-testing/helpers/wait'], function (exports, _emberTestingTestHelpers, _emberTestingHelpersAnd_then, _emberTestingHelpersClick, _emberTestingHelpersCurrent_path, _emberTestingHelpersCurrent_route_name, _emberTestingHelpersCurrent_url, _emberTestingHelpersFill_in, _emberTestingHelpersFind, _emberTestingHelpersFind_with_assert, _emberTestingHelpersKey_event, _emberTestingHelpersPause_test, _emberTestingHelpersTrigger_event, _emberTestingHelpersVisit, _emberTestingHelpersWait) { 'use strict'; /** @module ember @submodule ember-testing */ /** Loads a route, sets up any controllers, and renders any templates associated with the route as though a real user had triggered the route change while using your app. Example: ```javascript visit('posts/index').then(function() { // assert something }); ``` @method visit @param {String} url the name of the route @return {RSVP.Promise} @public */ _emberTestingTestHelpers.registerAsyncHelper('visit', _emberTestingHelpersVisit.default); /** Clicks an element and triggers any actions triggered by the element's `click` event. Example: ```javascript click('.some-jQuery-selector').then(function() { // assert something }); ``` @method click @param {String} selector jQuery selector for finding element on the DOM @param {Object} context A DOM Element, Document, or jQuery to use as context @return {RSVP.Promise} @public */ _emberTestingTestHelpers.registerAsyncHelper('click', _emberTestingHelpersClick.default); /** Simulates a key event, e.g. `keypress`, `keydown`, `keyup` with the desired keyCode Example: ```javascript keyEvent('.some-jQuery-selector', 'keypress', 13).then(function() { // assert something }); ``` @method keyEvent @param {String} selector jQuery selector for finding element on the DOM @param {String} type the type of key event, e.g. `keypress`, `keydown`, `keyup` @param {Number} keyCode the keyCode of the simulated key event @return {RSVP.Promise} @since 1.5.0 @public */ _emberTestingTestHelpers.registerAsyncHelper('keyEvent', _emberTestingHelpersKey_event.default); /** Fills in an input element with some text. Example: ```javascript fillIn('#email', 'you@example.com').then(function() { // assert something }); ``` @method fillIn @param {String} selector jQuery selector finding an input element on the DOM to fill text with @param {String} text text to place inside the input element @return {RSVP.Promise} @public */ _emberTestingTestHelpers.registerAsyncHelper('fillIn', _emberTestingHelpersFill_in.default); /** Finds an element in the context of the app's container element. A simple alias for `app.$(selector)`. Example: ```javascript var $el = find('.my-selector'); ``` @method find @param {String} selector jQuery string selector for element lookup @return {Object} jQuery object representing the results of the query @public */ _emberTestingTestHelpers.registerHelper('find', _emberTestingHelpersFind.default); /** Like `find`, but throws an error if the element selector returns no results. Example: ```javascript var $el = findWithAssert('.doesnt-exist'); // throws error ``` @method findWithAssert @param {String} selector jQuery selector string for finding an element within the DOM @return {Object} jQuery object representing the results of the query @throws {Error} throws error if jQuery object returned has a length of 0 @public */ _emberTestingTestHelpers.registerHelper('findWithAssert', _emberTestingHelpersFind_with_assert.default); /** Causes the run loop to process any pending events. This is used to ensure that any async operations from other helpers (or your assertions) have been processed. This is most often used as the return value for the helper functions (see 'click', 'fillIn','visit',etc). Example: ```javascript Ember.Test.registerAsyncHelper('loginUser', function(app, username, password) { visit('secured/path/here') .fillIn('#username', username) .fillIn('#password', password) .click('.submit') return app.testHelpers.wait(); }); @method wait @param {Object} value The value to be returned. @return {RSVP.Promise} @public */ _emberTestingTestHelpers.registerAsyncHelper('wait', _emberTestingHelpersWait.default); _emberTestingTestHelpers.registerAsyncHelper('andThen', _emberTestingHelpersAnd_then.default); _emberTestingTestHelpers.registerHelper('currentRouteName', _emberTestingHelpersCurrent_route_name.default); /** Returns the current path. Example: ```javascript function validateURL() { equal(currentPath(), 'some.path.index', "correct path was transitioned into."); } click('#some-link-id').then(validateURL); ``` @method currentPath @return {Object} The currently active path. @since 1.5.0 @public */ _emberTestingTestHelpers.registerHelper('currentPath', _emberTestingHelpersCurrent_path.default); /** Returns the current URL. Example: ```javascript function validateURL() { equal(currentURL(), '/some/path', "correct URL was transitioned into."); } click('#some-link-id').then(validateURL); ``` @method currentURL @return {Object} The currently active URL. @since 1.5.0 @public */ _emberTestingTestHelpers.registerHelper('currentURL', _emberTestingHelpersCurrent_url.default); _emberTestingTestHelpers.registerAsyncHelper('pauseTest', _emberTestingHelpersPause_test.default); _emberTestingTestHelpers.registerAsyncHelper('triggerEvent', _emberTestingHelpersTrigger_event.default); }); enifed("ember-testing/helpers/and_then", ["exports"], function (exports) { "use strict"; exports.default = andThen; function andThen(app, callback) { return app.testHelpers.wait(callback(app)); } }); enifed('ember-testing/helpers/click', ['exports', 'ember-testing/events'], function (exports, _emberTestingEvents) { 'use strict'; exports.default = click; function click(app, selector, context) { var $el = app.testHelpers.findWithAssert(selector, context); var el = $el[0]; _emberTestingEvents.fireEvent(el, 'mousedown'); _emberTestingEvents.focus(el); _emberTestingEvents.fireEvent(el, 'mouseup'); _emberTestingEvents.fireEvent(el, 'click'); return app.testHelpers.wait(); } }); enifed('ember-testing/helpers/current_path', ['exports', 'ember-metal/property_get'], function (exports, _emberMetalProperty_get) { 'use strict'; exports.default = currentPath; function currentPath(app) { var routingService = app.__container__.lookup('service:-routing'); return _emberMetalProperty_get.get(routingService, 'currentPath'); } }); enifed('ember-testing/helpers/current_route_name', ['exports', 'ember-metal/property_get'], function (exports, _emberMetalProperty_get) { /** @module ember @submodule ember-testing */ 'use strict'; exports.default = currentRouteName; /** Returns the currently active route name. Example: ```javascript function validateRouteName() { equal(currentRouteName(), 'some.path', "correct route was transitioned into."); } visit('/some/path').then(validateRouteName) ``` @method currentRouteName @return {Object} The name of the currently active route. @since 1.5.0 @public */ function currentRouteName(app) { var routingService = app.__container__.lookup('service:-routing'); return _emberMetalProperty_get.get(routingService, 'currentRouteName'); } }); enifed('ember-testing/helpers/current_url', ['exports', 'ember-metal/property_get'], function (exports, _emberMetalProperty_get) { 'use strict'; exports.default = currentURL; function currentURL(app) { var router = app.__container__.lookup('router:main'); return _emberMetalProperty_get.get(router, 'location').getURL(); } }); enifed('ember-testing/helpers/fill_in', ['exports', 'ember-testing/events'], function (exports, _emberTestingEvents) { 'use strict'; exports.default = fillIn; function fillIn(app, selector, contextOrText, text) { var $el = undefined, el = undefined, context = undefined; if (typeof text === 'undefined') { text = contextOrText; } else { context = contextOrText; } $el = app.testHelpers.findWithAssert(selector, context); el = $el[0]; _emberTestingEvents.focus(el); $el.eq(0).val(text); _emberTestingEvents.fireEvent(el, 'input'); _emberTestingEvents.fireEvent(el, 'change'); return app.testHelpers.wait(); } }); enifed('ember-testing/helpers/find', ['exports', 'ember-metal/property_get'], function (exports, _emberMetalProperty_get) { 'use strict'; exports.default = find; function find(app, selector, context) { var $el = undefined; context = context || _emberMetalProperty_get.get(app, 'rootElement'); $el = app.$(selector, context); return $el; } }); enifed('ember-testing/helpers/find_with_assert', ['exports'], function (exports) { 'use strict'; exports.default = findWithAssert; function findWithAssert(app, selector, context) { var $el = app.testHelpers.find(selector, context); if ($el.length === 0) { throw new Error('Element ' + selector + ' not found.'); } return $el; } }); enifed('ember-testing/helpers/key_event', ['exports'], function (exports) { 'use strict'; exports.default = keyEvent; function keyEvent(app, selector, contextOrType, typeOrKeyCode, keyCode) { var context = undefined, type = undefined; if (typeof keyCode === 'undefined') { context = null; keyCode = typeOrKeyCode; type = contextOrType; } else { context = contextOrType; type = typeOrKeyCode; } return app.testHelpers.triggerEvent(selector, context, type, { keyCode: keyCode, which: keyCode }); } }); enifed('ember-testing/helpers/pause_test', ['exports', 'ember-runtime/ext/rsvp'], function (exports, _emberRuntimeExtRsvp) { /** @module ember @submodule ember-testing */ 'use strict'; exports.default = pauseTest; /** Pauses the current test - this is useful for debugging while testing or for test-driving. It allows you to inspect the state of your application at any point. Example (The test will pause before clicking the button): ```javascript visit('/') return pauseTest(); click('.btn'); ``` @since 1.9.0 @method pauseTest @return {Object} A promise that will never resolve @public */ function pauseTest() { return new _emberRuntimeExtRsvp.default.Promise(function () {}, 'TestAdapter paused promise'); } }); enifed('ember-testing/helpers/trigger_event', ['exports', 'ember-testing/events'], function (exports, _emberTestingEvents) { /** @module ember @submodule ember-testing */ 'use strict'; exports.default = triggerEvent; /** Triggers the given DOM event on the element identified by the provided selector. Example: ```javascript triggerEvent('#some-elem-id', 'blur'); ``` This is actually used internally by the `keyEvent` helper like so: ```javascript triggerEvent('#some-elem-id', 'keypress', { keyCode: 13 }); ``` @method triggerEvent @param {String} selector jQuery selector for finding element on the DOM @param {String} [context] jQuery selector that will limit the selector argument to find only within the context's children @param {String} type The event type to be triggered. @param {Object} [options] The options to be passed to jQuery.Event. @return {RSVP.Promise} @since 1.5.0 @public */ function triggerEvent(app, selector, contextOrType, typeOrOptions, possibleOptions) { var arity = arguments.length; var context = undefined, type = undefined, options = undefined; if (arity === 3) { // context and options are optional, so this is // app, selector, type context = null; type = contextOrType; options = {}; } else if (arity === 4) { // context and options are optional, so this is if (typeof typeOrOptions === 'object') { // either // app, selector, type, options context = null; type = contextOrType; options = typeOrOptions; } else { // or // app, selector, context, type context = contextOrType; type = typeOrOptions; options = {}; } } else { context = contextOrType; type = typeOrOptions; options = possibleOptions; } var $el = app.testHelpers.findWithAssert(selector, context); var el = $el[0]; _emberTestingEvents.fireEvent(el, type, options); return app.testHelpers.wait(); } }); enifed('ember-testing/helpers/visit', ['exports', 'ember-metal/run_loop'], function (exports, _emberMetalRun_loop) { 'use strict'; exports.default = visit; function visit(app, url) { var router = app.__container__.lookup('router:main'); var shouldHandleURL = false; app.boot().then(function () { router.location.setURL(url); if (shouldHandleURL) { _emberMetalRun_loop.default(app.__deprecatedInstance__, 'handleURL', url); } }); if (app._readinessDeferrals > 0) { router['initialURL'] = url; _emberMetalRun_loop.default(app, 'advanceReadiness'); delete router['initialURL']; } else { shouldHandleURL = true; } return app.testHelpers.wait(); } }); enifed('ember-testing/helpers/wait', ['exports', 'ember-testing/test/waiters', 'ember-runtime/ext/rsvp', 'ember-metal/run_loop', 'ember-testing/test/pending_requests'], function (exports, _emberTestingTestWaiters, _emberRuntimeExtRsvp, _emberMetalRun_loop, _emberTestingTestPending_requests) { 'use strict'; exports.default = wait; function wait(app, value) { return new _emberRuntimeExtRsvp.default.Promise(function (resolve) { var router = app.__container__.lookup('router:main'); // Every 10ms, poll for the async thing to have finished var watcher = setInterval(function () { // 1. If the router is loading, keep polling var routerIsLoading = router.router && !!router.router.activeTransition; if (routerIsLoading) { return; } // 2. If there are pending Ajax requests, keep polling if (_emberTestingTestPending_requests.pendingRequests()) { return; } // 3. If there are scheduled timers or we are inside of a run loop, keep polling if (_emberMetalRun_loop.default.hasScheduledTimers() || _emberMetalRun_loop.default.currentRunLoop) { return; } if (_emberTestingTestWaiters.checkWaiters()) { return; } // Stop polling clearInterval(watcher); // Synchronously resolve the promise _emberMetalRun_loop.default(null, resolve, value); }, 10); }); } }); enifed('ember-testing/index', ['exports', 'ember-metal/core', 'ember-testing/test', 'ember-testing/adapters/adapter', 'ember-testing/setup_for_testing', 'require', 'ember-testing/support', 'ember-testing/ext/application', 'ember-testing/ext/rsvp', 'ember-testing/helpers', 'ember-testing/initializers'], function (exports, _emberMetalCore, _emberTestingTest, _emberTestingAdaptersAdapter, _emberTestingSetup_for_testing, _require, _emberTestingSupport, _emberTestingExtApplication, _emberTestingExtRsvp, _emberTestingHelpers, _emberTestingInitializers) { 'use strict'; // to setup initializer /** @module ember @submodule ember-testing */ _emberMetalCore.default.Test = _emberTestingTest.default; _emberMetalCore.default.Test.Adapter = _emberTestingAdaptersAdapter.default; _emberMetalCore.default.setupForTesting = _emberTestingSetup_for_testing.default; Object.defineProperty(_emberTestingTest.default, 'QUnitAdapter', { get: function () { return _require.default('ember-testing/adapters/qunit').default; } }); }); // reexports // to handle various edge cases // adds helpers to helpers object in Test enifed('ember-testing/initializers', ['exports', 'ember-runtime/system/lazy_load'], function (exports, _emberRuntimeSystemLazy_load) { 'use strict'; var name = 'deferReadiness in `testing` mode'; _emberRuntimeSystemLazy_load.onLoad('Ember.Application', function (Application) { if (!Application.initializers[name]) { Application.initializer({ name: name, initialize: function (application) { if (application.testing) { application.deferReadiness(); } } }); } }); }); enifed('ember-testing/setup_for_testing', ['exports', 'ember-metal/testing', 'ember-views/system/jquery', 'ember-testing/test/adapter', 'ember-testing/test/pending_requests', 'require'], function (exports, _emberMetalTesting, _emberViewsSystemJquery, _emberTestingTestAdapter, _emberTestingTestPending_requests, _require) { 'use strict'; exports.default = setupForTesting; /** Sets Ember up for testing. This is useful to perform basic setup steps in order to unit test. Use `App.setupForTesting` to perform integration tests (full application testing). @method setupForTesting @namespace Ember @since 1.5.0 @private */ function setupForTesting() { _emberMetalTesting.setTesting(true); var adapter = _emberTestingTestAdapter.getAdapter(); // if adapter is not manually set default to QUnit if (!adapter) { var QUnitAdapter = _require.default('ember-testing/adapters/qunit').default; _emberTestingTestAdapter.setAdapter(new QUnitAdapter()); } _emberViewsSystemJquery.default(document).off('ajaxSend', _emberTestingTestPending_requests.incrementPendingRequests); _emberViewsSystemJquery.default(document).off('ajaxComplete', _emberTestingTestPending_requests.decrementPendingRequests); _emberTestingTestPending_requests.clearPendingRequests(); _emberViewsSystemJquery.default(document).on('ajaxSend', _emberTestingTestPending_requests.incrementPendingRequests); _emberViewsSystemJquery.default(document).on('ajaxComplete', _emberTestingTestPending_requests.decrementPendingRequests); } }); enifed('ember-testing/support', ['exports', 'ember-metal/debug', 'ember-views/system/jquery', 'ember-environment'], function (exports, _emberMetalDebug, _emberViewsSystemJquery, _emberEnvironment) { 'use strict'; /** @module ember @submodule ember-testing */ var $ = _emberViewsSystemJquery.default; /** This method creates a checkbox and triggers the click event to fire the passed in handler. It is used to correct for a bug in older versions of jQuery (e.g 1.8.3). @private @method testCheckboxClick */ function testCheckboxClick(handler) { $('<input type="checkbox">').css({ position: 'absolute', left: '-1000px', top: '-1000px' }).appendTo('body').on('click', handler).trigger('click').remove(); } if (_emberEnvironment.environment.hasDOM) { $(function () { /* Determine whether a checkbox checked using jQuery's "click" method will have the correct value for its checked property. If we determine that the current jQuery version exhibits this behavior, patch it to work correctly as in the commit for the actual fix: https://github.com/jquery/jquery/commit/1fb2f92. */ testCheckboxClick(function () { if (!this.checked && !$.event.special.click) { $.event.special.click = { // For checkbox, fire native event so checked state will be right trigger: function () { if ($.nodeName(this, 'input') && this.type === 'checkbox' && this.click) { this.click(); return false; } } }; } }); // Try again to verify that the patch took effect or blow up. testCheckboxClick(function () { _emberMetalDebug.warn('clicked checkboxes should be checked! the jQuery patch didn\'t work', this.checked, { id: 'ember-testing.test-checkbox-click' }); }); }); } }); enifed('ember-testing/test', ['exports', 'ember-testing/test/helpers', 'ember-testing/test/on_inject_helpers', 'ember-testing/test/promise', 'ember-testing/test/waiters', 'ember-testing/test/adapter', 'ember-metal/features'], function (exports, _emberTestingTestHelpers, _emberTestingTestOn_inject_helpers, _emberTestingTestPromise, _emberTestingTestWaiters, _emberTestingTestAdapter, _emberMetalFeatures) { /** @module ember @submodule ember-testing */ 'use strict'; /** This is a container for an assortment of testing related functionality: * Choose your default test adapter (for your framework of choice). * Register/Unregister additional test helpers. * Setup callbacks to be fired when the test helpers are injected into your application. @class Test @namespace Ember @public */ var Test = { /** Hash containing all known test helpers. @property _helpers @private @since 1.7.0 */ _helpers: _emberTestingTestHelpers.helpers, registerHelper: _emberTestingTestHelpers.registerHelper, registerAsyncHelper: _emberTestingTestHelpers.registerAsyncHelper, unregisterHelper: _emberTestingTestHelpers.unregisterHelper, onInjectHelpers: _emberTestingTestOn_inject_helpers.onInjectHelpers, Promise: _emberTestingTestPromise.default, promise: _emberTestingTestPromise.promise, resolve: _emberTestingTestPromise.resolve, registerWaiter: _emberTestingTestWaiters.registerWaiter, unregisterWaiter: _emberTestingTestWaiters.unregisterWaiter }; if (true) { Test.checkWaiters = _emberTestingTestWaiters.checkWaiters; } /** Used to allow ember-testing to communicate with a specific testing framework. You can manually set it before calling `App.setupForTesting()`. Example: ```javascript Ember.Test.adapter = MyCustomAdapter.create() ``` If you do not set it, ember-testing will default to `Ember.Test.QUnitAdapter`. @public @for Ember.Test @property adapter @type {Class} The adapter to be used. @default Ember.Test.QUnitAdapter */ Object.defineProperty(Test, 'adapter', { get: _emberTestingTestAdapter.getAdapter, set: _emberTestingTestAdapter.setAdapter }); Object.defineProperty(Test, 'waiters', { get: _emberTestingTestWaiters.generateDeprecatedWaitersArray }); exports.default = Test; }); enifed('ember-testing/test/adapter', ['exports', 'ember-console', 'ember-metal/error_handler'], function (exports, _emberConsole, _emberMetalError_handler) { 'use strict'; exports.getAdapter = getAdapter; exports.setAdapter = setAdapter; exports.asyncStart = asyncStart; exports.asyncEnd = asyncEnd; var adapter = undefined; function getAdapter() { return adapter; } function setAdapter(value) { adapter = value; if (value) { _emberMetalError_handler.setDispatchOverride(adapterDispatch); } else { _emberMetalError_handler.setDispatchOverride(null); } } function asyncStart() { if (adapter) { adapter.asyncStart(); } } function asyncEnd() { if (adapter) { adapter.asyncEnd(); } } function adapterDispatch(error) { adapter.exception(error); _emberConsole.default.error(error.stack); } }); enifed('ember-testing/test/helpers', ['exports', 'ember-testing/test/promise'], function (exports, _emberTestingTestPromise) { 'use strict'; exports.registerHelper = registerHelper; exports.registerAsyncHelper = registerAsyncHelper; exports.unregisterHelper = unregisterHelper; var helpers = {}; exports.helpers = helpers; /** `registerHelper` is used to register a test helper that will be injected when `App.injectTestHelpers` is called. The helper method will always be called with the current Application as the first parameter. For example: ```javascript Ember.Test.registerHelper('boot', function(app) { Ember.run(app, app.advanceReadiness); }); ``` This helper can later be called without arguments because it will be called with `app` as the first parameter. ```javascript App = Ember.Application.create(); App.injectTestHelpers(); boot(); ``` @public @for Ember.Test @method registerHelper @param {String} name The name of the helper method to add. @param {Function} helperMethod @param options {Object} */ function registerHelper(name, helperMethod) { helpers[name] = { method: helperMethod, meta: { wait: false } }; } /** `registerAsyncHelper` is used to register an async test helper that will be injected when `App.injectTestHelpers` is called. The helper method will always be called with the current Application as the first parameter. For example: ```javascript Ember.Test.registerAsyncHelper('boot', function(app) { Ember.run(app, app.advanceReadiness); }); ``` The advantage of an async helper is that it will not run until the last async helper has completed. All async helpers after it will wait for it complete before running. For example: ```javascript Ember.Test.registerAsyncHelper('deletePost', function(app, postId) { click('.delete-' + postId); }); // ... in your test visit('/post/2'); deletePost(2); visit('/post/3'); deletePost(3); ``` @public @for Ember.Test @method registerAsyncHelper @param {String} name The name of the helper method to add. @param {Function} helperMethod @since 1.2.0 */ function registerAsyncHelper(name, helperMethod) { helpers[name] = { method: helperMethod, meta: { wait: true } }; } /** Remove a previously added helper method. Example: ```javascript Ember.Test.unregisterHelper('wait'); ``` @public @method unregisterHelper @param {String} name The helper to remove. */ function unregisterHelper(name) { delete helpers[name]; delete _emberTestingTestPromise.default.prototype[name]; } }); enifed("ember-testing/test/on_inject_helpers", ["exports"], function (exports) { "use strict"; exports.onInjectHelpers = onInjectHelpers; exports.invokeInjectHelpersCallbacks = invokeInjectHelpersCallbacks; var callbacks = []; exports.callbacks = callbacks; /** Used to register callbacks to be fired whenever `App.injectTestHelpers` is called. The callback will receive the current application as an argument. Example: ```javascript Ember.Test.onInjectHelpers(function() { Ember.$(document).ajaxSend(function() { Test.pendingRequests++; }); Ember.$(document).ajaxComplete(function() { Test.pendingRequests--; }); }); ``` @public @for Ember.Test @method onInjectHelpers @param {Function} callback The function to be called. */ function onInjectHelpers(callback) { callbacks.push(callback); } function invokeInjectHelpersCallbacks(app) { for (var i = 0; i < callbacks.length; i++) { callbacks[i](app); } } }); enifed("ember-testing/test/pending_requests", ["exports"], function (exports) { "use strict"; exports.pendingRequests = pendingRequests; exports.clearPendingRequests = clearPendingRequests; exports.incrementPendingRequests = incrementPendingRequests; exports.decrementPendingRequests = decrementPendingRequests; var requests = []; function pendingRequests() { return requests.length; } function clearPendingRequests() { requests.length = 0; } function incrementPendingRequests(_, xhr) { requests.push(xhr); } function decrementPendingRequests(_, xhr) { for (var i = 0; i < requests.length; i++) { if (xhr === requests[i]) { requests.splice(i, 1); break; } } } }); enifed('ember-testing/test/promise', ['exports', 'ember-runtime/ext/rsvp', 'ember-testing/test/run'], function (exports, _emberRuntimeExtRsvp, _emberTestingTestRun) { 'use strict'; exports.promise = promise; exports.resolve = resolve; exports.getLastPromise = getLastPromise; function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } var lastPromise = undefined; var TestPromise = (function (_RSVP$Promise) { _inherits(TestPromise, _RSVP$Promise); function TestPromise() { _classCallCheck(this, TestPromise); _RSVP$Promise.apply(this, arguments); lastPromise = this; } /** This returns a thenable tailored for testing. It catches failed `onSuccess` callbacks and invokes the `Ember.Test.adapter.exception` callback in the last chained then. This method should be returned by async helpers such as `wait`. @public @for Ember.Test @method promise @param {Function} resolver The function used to resolve the promise. @param {String} label An optional string for identifying the promise. */ TestPromise.resolve = function resolve(val) { return new TestPromise(function (resolve) { return resolve(val); }); }; TestPromise.prototype.then = function then(onFulfillment) { var _RSVP$Promise$prototype$then; for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return (_RSVP$Promise$prototype$then = _RSVP$Promise.prototype.then).call.apply(_RSVP$Promise$prototype$then, [this, function (result) { return isolate(onFulfillment, result); }].concat(args)); }; return TestPromise; })(_emberRuntimeExtRsvp.default.Promise); exports.default = TestPromise; function promise(resolver, label) { var fullLabel = 'Ember.Test.promise: ' + (label || '<Unknown Promise>'); return new TestPromise(resolver, fullLabel); } /** Replacement for `Ember.RSVP.resolve` The only difference is this uses an instance of `Ember.Test.Promise` @public @for Ember.Test @method resolve @param {Mixed} The value to resolve @since 1.2.0 */ function resolve(result) { return new TestPromise(function (resolve) { return resolve(result); }); } function getLastPromise() { return lastPromise; } // This method isolates nested async methods // so that they don't conflict with other last promises. // // 1. Set `Ember.Test.lastPromise` to null // 2. Invoke method // 3. Return the last promise created during method function isolate(onFulfillment, result) { // Reset lastPromise for nested helpers lastPromise = null; var value = onFulfillment(result); var promise = lastPromise; lastPromise = null; // If the method returned a promise // return that promise. If not, // return the last async helper's promise if (value && value instanceof TestPromise || !promise) { return value; } else { return _emberTestingTestRun.default(function () { return resolve(promise).then(function () { return value; }); }); } } }); enifed('ember-testing/test/run', ['exports', 'ember-metal/run_loop'], function (exports, _emberMetalRun_loop) { 'use strict'; exports.default = run; function run(fn) { if (!_emberMetalRun_loop.default.currentRunLoop) { return _emberMetalRun_loop.default(fn); } else { return fn(); } } }); enifed('ember-testing/test/waiters', ['exports', 'ember-metal/features', 'ember-metal/debug'], function (exports, _emberMetalFeatures, _emberMetalDebug) { 'use strict'; exports.registerWaiter = registerWaiter; exports.unregisterWaiter = unregisterWaiter; exports.checkWaiters = checkWaiters; exports.generateDeprecatedWaitersArray = generateDeprecatedWaitersArray; var contexts = []; var callbacks = []; /** This allows ember-testing to play nicely with other asynchronous events, such as an application that is waiting for a CSS3 transition or an IndexDB transaction. For example: ```javascript Ember.Test.registerWaiter(function() { return myPendingTransactions() == 0; }); ``` The `context` argument allows you to optionally specify the `this` with which your callback will be invoked. For example: ```javascript Ember.Test.registerWaiter(MyDB, MyDB.hasPendingTransactions); ``` @public @for Ember.Test @method registerWaiter @param {Object} context (optional) @param {Function} callback @since 1.2.0 */ function registerWaiter(context, callback) { if (arguments.length === 1) { callback = context; context = null; } if (indexOf(context, callback) > -1) { return; } contexts.push(context); callbacks.push(callback); } /** `unregisterWaiter` is used to unregister a callback that was registered with `registerWaiter`. @public @for Ember.Test @method unregisterWaiter @param {Object} context (optional) @param {Function} callback @since 1.2.0 */ function unregisterWaiter(context, callback) { if (!callbacks.length) { return; } if (arguments.length === 1) { callback = context; context = null; } var i = indexOf(context, callback); if (i === -1) { return; } contexts.splice(i, 1); callbacks.splice(i, 1); } /** Iterates through each registered test waiter, and invokes its callback. If any waiter returns false, this method will return true indicating that the waiters have not settled yet. This is generally used internally from the acceptance/integration test infrastructure. @public @for Ember.Test @static @method checkWaiters */ function checkWaiters() { if (!callbacks.length) { return false; } for (var i = 0; i < callbacks.length; i++) { var context = contexts[i]; var callback = callbacks[i]; if (!callback.call(context)) { return true; } } return false; } function indexOf(context, callback) { for (var i = 0; i < callbacks.length; i++) { if (callbacks[i] === callback && contexts[i] === context) { return i; } } return -1; } function generateDeprecatedWaitersArray() { _emberMetalDebug.deprecate('Usage of `Ember.Test.waiters` is deprecated. Please refactor to `Ember.Test.checkWaiters`.', !true, { until: '2.8.0', id: 'ember-testing.test-waiters' }); var array = new Array(callbacks.length); for (var i = 0; i < callbacks.length; i++) { var context = contexts[i]; var callback = callbacks[i]; array[i] = [context, callback]; } return array; } }); enifed('ember-views/compat/attrs-proxy', ['exports', 'ember-metal/mixin', 'ember-metal/symbol', 'ember-metal/property_events'], function (exports, _emberMetalMixin, _emberMetalSymbol, _emberMetalProperty_events) { 'use strict'; exports.deprecation = deprecation; exports.getAttrFor = getAttrFor; function deprecation(key) { return 'You tried to look up an attribute directly on the component. This is deprecated. Use attrs.' + key + ' instead.'; } var MUTABLE_CELL = _emberMetalSymbol.default('MUTABLE_CELL'); exports.MUTABLE_CELL = MUTABLE_CELL; function isCell(val) { return val && val[MUTABLE_CELL]; } function getAttrFor(attrs, key) { var val = attrs[key]; return isCell(val) ? val.value : val; } var AttrsProxyMixin = { attrs: null, getAttr: function (key) { var attrs = this.attrs; if (!attrs) { return; } return getAttrFor(attrs, key); }, setAttr: function (key, value) { var attrs = this.attrs; var val = attrs[key]; if (!isCell(val)) { throw new Error('You can\'t update attrs.' + key + ', because it\'s not mutable'); } val.update(value); }, _propagateAttrsToThis: function (attrs) { this._isDispatchingAttrs = true; this.setProperties(attrs); this._isDispatchingAttrs = false; } }; AttrsProxyMixin[_emberMetalProperty_events.PROPERTY_DID_CHANGE] = function (key) { if (this._isDispatchingAttrs) { return; } if (this._currentState) { this._currentState.legacyPropertyDidChange(this, key); } }; exports.default = _emberMetalMixin.Mixin.create(AttrsProxyMixin); }); enifed('ember-views/compat/fallback-view-registry', ['exports', 'ember-metal/dictionary'], function (exports, _emberMetalDictionary) { 'use strict'; exports.default = _emberMetalDictionary.default(null); }); enifed('ember-views/component_lookup', ['exports', 'ember-metal/debug', 'ember-runtime/system/object'], function (exports, _emberMetalDebug, _emberRuntimeSystemObject) { 'use strict'; exports.default = _emberRuntimeSystemObject.default.extend({ componentFor: function (name, owner, options) { _emberMetalDebug.assert('You cannot use \'' + name + '\' as a component name. Component names must contain a hyphen.', ~name.indexOf('-')); var fullName = 'component:' + name; return owner._lookupFactory(fullName, options); }, layoutFor: function (name, owner, options) { _emberMetalDebug.assert('You cannot use \'' + name + '\' as a component name. Component names must contain a hyphen.', ~name.indexOf('-')); var templateFullName = 'template:components/' + name; return owner.lookup(templateFullName, options); } }); }); enifed('ember-views/index', ['exports', 'ember-runtime', 'ember-views/system/jquery', 'ember-views/system/utils', 'ember-views/system/ext', 'ember-views/system/event_dispatcher', 'ember-views/mixins/view_target_action_support', 'ember-views/component_lookup', 'ember-views/mixins/text_support'], function (exports, _emberRuntime, _emberViewsSystemJquery, _emberViewsSystemUtils, _emberViewsSystemExt, _emberViewsSystemEvent_dispatcher, _emberViewsMixinsView_target_action_support, _emberViewsComponent_lookup, _emberViewsMixinsText_support) { /** @module ember @submodule ember-views */ // BEGIN IMPORTS 'use strict'; // END IMPORTS /** Alias for jQuery @method $ @for Ember @public */ // BEGIN EXPORTS _emberRuntime.default.$ = _emberViewsSystemJquery.default; _emberRuntime.default.ViewTargetActionSupport = _emberViewsMixinsView_target_action_support.default; var ViewUtils = _emberRuntime.default.ViewUtils = {}; ViewUtils.isSimpleClick = _emberViewsSystemUtils.isSimpleClick; ViewUtils.getViewClientRects = _emberViewsSystemUtils.getViewClientRects; ViewUtils.getViewBoundingClientRect = _emberViewsSystemUtils.getViewBoundingClientRect; _emberRuntime.default.TextSupport = _emberViewsMixinsText_support.default; _emberRuntime.default.ComponentLookup = _emberViewsComponent_lookup.default; _emberRuntime.default.EventDispatcher = _emberViewsSystemEvent_dispatcher.default; // END EXPORTS exports.default = _emberRuntime.default; }); // for the side effect of extending Ember.run.queues enifed('ember-views/mixins/action_support', ['exports', 'ember-metal/mixin', 'ember-metal/property_get', 'ember-metal/is_none', 'ember-metal/debug', 'ember-views/compat/attrs-proxy', 'ember-metal/utils'], function (exports, _emberMetalMixin, _emberMetalProperty_get, _emberMetalIs_none, _emberMetalDebug, _emberViewsCompatAttrsProxy, _emberMetalUtils) { 'use strict'; function validateAction(component, actionName) { if (actionName && actionName[_emberViewsCompatAttrsProxy.MUTABLE_CELL]) { actionName = actionName.value; } _emberMetalDebug.assert('The default action was triggered on the component ' + component.toString() + ', but the action name (' + actionName + ') was not a string.', _emberMetalIs_none.default(actionName) || typeof actionName === 'string' || typeof actionName === 'function'); return actionName; } exports.default = _emberMetalMixin.Mixin.create({ /** Calls an action passed to a component. For example a component for playing or pausing music may translate click events into action notifications of "play" or "stop" depending on some internal state of the component: ```javascript // app/components/play-button.js export default Ember.Component.extend({ click() { if (this.get('isPlaying')) { this.sendAction('play'); } else { this.sendAction('stop'); } } }); ``` The actions "play" and "stop" must be passed to this `play-button` component: ```handlebars {{! app/templates/application.hbs }} {{play-button play=(action "musicStarted") stop=(action "musicStopped")}} ``` When the component receives a browser `click` event it translate this interaction into application-specific semantics ("play" or "stop") and calls the specified action. ```javascript // app/controller/application.js export default Ember.Controller.extend({ actions: { musicStarted() { // called when the play button is clicked // and the music started playing }, musicStopped() { // called when the play button is clicked // and the music stopped playing } } }); ``` If no action is passed to `sendAction` a default name of "action" is assumed. ```javascript // app/components/next-button.js export default Ember.Component.extend({ click() { this.sendAction(); } }); ``` ```handlebars {{! app/templates/application.hbs }} {{next-button action=(action "playNextSongInAlbum")}} ``` ```javascript // app/controllers/application.js App.ApplicationController = Ember.Controller.extend({ actions: { playNextSongInAlbum() { ... } } }); ``` @method sendAction @param [action] {String} the action to call @param [params] {*} arguments for the action @public */ sendAction: function (action) { for (var _len = arguments.length, contexts = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { contexts[_key - 1] = arguments[_key]; } var actionName = undefined; // Send the default action if (action === undefined) { action = 'action'; } actionName = _emberMetalProperty_get.get(this, 'attrs.' + action) || _emberMetalProperty_get.get(this, action); actionName = validateAction(this, actionName); // If no action name for that action could be found, just abort. if (actionName === undefined) { return; } if (typeof actionName === 'function') { actionName.apply(undefined, contexts); } else { this.triggerAction({ action: actionName, actionContext: contexts }); } }, send: function (actionName) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } var target = undefined; var action = this.actions && this.actions[actionName]; if (action) { var shouldBubble = action.apply(this, args) === true; if (!shouldBubble) { return; } } target = _emberMetalProperty_get.get(this, 'target') || _emberMetalProperty_get.get(this, '_targetObject'); if (target) { var _target; _emberMetalDebug.assert('The `target` for ' + this + ' (' + target + ') does not have a `send` method', typeof target.send === 'function'); (_target = target).send.apply(_target, arguments); } else { _emberMetalDebug.assert(_emberMetalUtils.inspect(this) + ' had no action handler for: ' + actionName, action); } } }); }); enifed('ember-views/mixins/aria_role_support', ['exports', 'ember-metal/mixin'], function (exports, _emberMetalMixin) { /** @module ember @submodule ember-views */ 'use strict'; /** @class AriaRoleSupport @namespace Ember @private */ exports.default = _emberMetalMixin.Mixin.create({ /** The WAI-ARIA role of the control represented by this view. For example, a button may have a role of type 'button', or a pane may have a role of type 'alertdialog'. This property is used by assistive software to help visually challenged users navigate rich web applications. The full list of valid WAI-ARIA roles is available at: [http://www.w3.org/TR/wai-aria/roles#roles_categorization](http://www.w3.org/TR/wai-aria/roles#roles_categorization) @property ariaRole @type String @default null @public */ ariaRole: null }); }); enifed('ember-views/mixins/child_views_support', ['exports', 'ember-metal/mixin', 'container/owner'], function (exports, _emberMetalMixin, _containerOwner) { /** @module ember @submodule ember-views */ 'use strict'; exports.default = _emberMetalMixin.Mixin.create({ init: function () { this._super.apply(this, arguments); /** Array of child views. You should never edit this array directly. @property childViews @type Array @default [] @private */ this.childViews = []; this.ownerView = this.ownerView || this; }, appendChild: function (view) { this.linkChild(view); this.childViews.push(view); }, destroyChild: function (view) { view.destroy(); }, /** Removes the child view from the parent view. @method removeChild @param {Ember.View} view @return {Ember.View} receiver @private */ removeChild: function (view) { // If we're destroying, the entire subtree will be // freed, and the DOM will be handled separately, // so no need to mess with childViews. if (this.isDestroying) { return; } // update parent node this.unlinkChild(view); // remove view from childViews array. var childViews = this.childViews; var index = childViews.indexOf(view); if (index !== -1) { childViews.splice(index, 1); } return this; }, linkChild: function (instance) { if (!instance[_containerOwner.OWNER]) { _containerOwner.setOwner(instance, _containerOwner.getOwner(this)); } instance.parentView = this; instance.ownerView = this.ownerView; }, unlinkChild: function (instance) { instance.parentView = null; } }); }); enifed('ember-views/mixins/class_names_support', ['exports', 'ember-metal/debug', 'ember-metal/mixin', 'ember-runtime/system/native_array'], function (exports, _emberMetalDebug, _emberMetalMixin, _emberRuntimeSystemNative_array) { /** @module ember @submodule ember-views */ 'use strict'; var EMPTY_ARRAY = []; /** @class ClassNamesSupport @namespace Ember @private */ exports.default = _emberMetalMixin.Mixin.create({ concatenatedProperties: ['classNames', 'classNameBindings'], init: function () { this._super.apply(this, arguments); _emberMetalDebug.assert('Only arrays are allowed for \'classNameBindings\'', Array.isArray(this.classNameBindings)); this.classNameBindings = _emberRuntimeSystemNative_array.A(this.classNameBindings.slice()); _emberMetalDebug.assert('Only arrays of static class strings are allowed for \'classNames\'. For dynamic classes, use \'classNameBindings\'.', Array.isArray(this.classNames)); this.classNames = _emberRuntimeSystemNative_array.A(this.classNames.slice()); }, /** Standard CSS class names to apply to the view's outer element. This property automatically inherits any class names defined by the view's superclasses as well. @property classNames @type Array @default ['ember-view'] @public */ classNames: ['ember-view'], /** A list of properties of the view to apply as class names. If the property is a string value, the value of that string will be applied as a class name. ```javascript // Applies the 'high' class to the view element Ember.View.extend({ classNameBindings: ['priority'], priority: 'high' }); ``` If the value of the property is a Boolean, the name of that property is added as a dasherized class name. ```javascript // Applies the 'is-urgent' class to the view element Ember.View.extend({ classNameBindings: ['isUrgent'], isUrgent: true }); ``` If you would prefer to use a custom value instead of the dasherized property name, you can pass a binding like this: ```javascript // Applies the 'urgent' class to the view element Ember.View.extend({ classNameBindings: ['isUrgent:urgent'], isUrgent: true }); ``` This list of properties is inherited from the view's superclasses as well. @property classNameBindings @type Array @default [] @public */ classNameBindings: EMPTY_ARRAY }); }); enifed('ember-views/mixins/instrumentation_support', ['exports', 'ember-metal/mixin', 'ember-metal/property_get'], function (exports, _emberMetalMixin, _emberMetalProperty_get) { /** @module ember @submodule ember-views */ 'use strict'; /** @class InstrumentationSupport @namespace Ember @public */ exports.default = _emberMetalMixin.Mixin.create({ /** Used to identify this view during debugging @property instrumentDisplay @type String @public */ instrumentDisplay: '', instrumentName: 'view', instrumentDetails: function (hash) { hash.template = _emberMetalProperty_get.get(this, 'templateName'); this._super(hash); } }); }); enifed('ember-views/mixins/template_support', ['exports', 'ember-metal/error', 'ember-metal/computed', 'container/owner', 'ember-metal/mixin', 'ember-metal/property_get', 'ember-metal/debug'], function (exports, _emberMetalError, _emberMetalComputed, _containerOwner, _emberMetalMixin, _emberMetalProperty_get, _emberMetalDebug) { 'use strict'; exports.default = _emberMetalMixin.Mixin.create({ /** @property isView @type Boolean @default true @static @private */ isView: true, // .......................................................... // TEMPLATE SUPPORT // /** The name of the template to lookup if no template is provided. By default `Ember.View` will lookup a template with this name in `Ember.TEMPLATES` (a shared global object). @property templateName @type String @default null @private */ templateName: null, /** The name of the layout to lookup if no layout is provided. By default `Ember.View` will lookup a template with this name in `Ember.TEMPLATES` (a shared global object). @property layoutName @type String @default null @private */ layoutName: null, /** The template used to render the view. This should be a function that accepts an optional context parameter and returns a string of HTML that will be inserted into the DOM relative to its parent view. In general, you should set the `templateName` property instead of setting the template yourself. @property template @type Function @private */ template: _emberMetalComputed.computed({ get: function () { var templateName = _emberMetalProperty_get.get(this, 'templateName'); var template = this.templateForName(templateName, 'template'); _emberMetalDebug.assert('You specified the templateName ' + templateName + ' for ' + this + ', but it did not exist.', !templateName || !!template); return template || _emberMetalProperty_get.get(this, 'defaultTemplate'); }, set: function (key, value) { if (value !== undefined) { return value; } return _emberMetalProperty_get.get(this, key); } }), /** A view may contain a layout. A layout is a regular template but supersedes the `template` property during rendering. It is the responsibility of the layout template to retrieve the `template` property from the view (or alternatively, call `Handlebars.helpers.yield`, `{{yield}}`) to render it in the correct location. This is useful for a view that has a shared wrapper, but which delegates the rendering of the contents of the wrapper to the `template` property on a subclass. @property layout @type Function @private */ layout: _emberMetalComputed.computed({ get: function (key) { var layoutName = _emberMetalProperty_get.get(this, 'layoutName'); var layout = this.templateForName(layoutName, 'layout'); _emberMetalDebug.assert('You specified the layoutName ' + layoutName + ' for ' + this + ', but it did not exist.', !layoutName || !!layout); return layout || _emberMetalProperty_get.get(this, 'defaultLayout'); }, set: function (key, value) { return value; } }), templateForName: function (name, type) { if (!name) { return; } _emberMetalDebug.assert('templateNames are not allowed to contain periods: ' + name, name.indexOf('.') === -1); var owner = _containerOwner.getOwner(this); if (!owner) { throw new _emberMetalError.default('Container was not found when looking up a views template. ' + 'This is most likely due to manually instantiating an Ember.View. ' + 'See: http://git.io/EKPpnA'); } return owner.lookup('template:' + name); } }); }); enifed('ember-views/mixins/text_support', ['exports', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/mixin', 'ember-runtime/mixins/target_action_support'], function (exports, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalMixin, _emberRuntimeMixinsTarget_action_support) { /** @module ember @submodule ember-views */ 'use strict'; var KEY_EVENTS = { 13: 'insertNewline', 27: 'cancel' }; /** `TextSupport` is a shared mixin used by both `Ember.TextField` and `Ember.TextArea`. `TextSupport` adds a number of methods that allow you to specify a controller action to invoke when a certain event is fired on your text field or textarea. The specifed controller action would get the current value of the field passed in as the only argument unless the value of the field is empty. In that case, the instance of the field itself is passed in as the only argument. Let's use the pressing of the escape key as an example. If you wanted to invoke a controller action when a user presses the escape key while on your field, you would use the `escape-press` attribute on your field like so: ```handlebars {{! application.hbs}} {{input escape-press='alertUser'}} ``` ```javascript App = Ember.Application.create(); App.ApplicationController = Ember.Controller.extend({ actions: { alertUser: function ( currentValue ) { alert( 'escape pressed, current value: ' + currentValue ); } } }); ``` The following chart is a visual representation of what takes place when the escape key is pressed in this scenario: ``` The Template +---------------------------+ | | | escape-press='alertUser' | | | TextSupport Mixin +----+----------------------+ +-------------------------------+ | | cancel method | | escape button pressed | | +-------------------------------> | checks for the `escape-press` | | attribute and pulls out the | +-------------------------------+ | `alertUser` value | | action name 'alertUser' +-------------------------------+ | sent to controller v Controller +------------------------------------------ + | | | actions: { | | alertUser: function( currentValue ){ | | alert( 'the esc key was pressed!' ) | | } | | } | | | +-------------------------------------------+ ``` Here are the events that we currently support along with the name of the attribute you would need to use on your field. To reiterate, you would use the attribute name like so: ```handlebars {{input attribute-name='controllerAction'}} ``` ``` +--------------------+----------------+ | | | | event | attribute name | +--------------------+----------------+ | new line inserted | insert-newline | | | | | enter key pressed | insert-newline | | | | | cancel key pressed | escape-press | | | | | focusin | focus-in | | | | | focusout | focus-out | | | | | keypress | key-press | | | | | keyup | key-up | | | | | keydown | key-down | +--------------------+----------------+ ``` @class TextSupport @namespace Ember @uses Ember.TargetActionSupport @extends Ember.Mixin @private */ exports.default = _emberMetalMixin.Mixin.create(_emberRuntimeMixinsTarget_action_support.default, { value: '', attributeBindings: ['autocapitalize', 'autocorrect', 'autofocus', 'disabled', 'form', 'maxlength', 'placeholder', 'readonly', 'required', 'selectionDirection', 'spellcheck', 'tabindex', 'title'], placeholder: null, disabled: false, maxlength: null, init: function () { this._super.apply(this, arguments); this.on('paste', this, this._elementValueDidChange); this.on('cut', this, this._elementValueDidChange); this.on('input', this, this._elementValueDidChange); }, /** The action to be sent when the user presses the return key. This is similar to the `{{action}}` helper, but is fired when the user presses the return key when editing a text field, and sends the value of the field as the context. @property action @type String @default null @private */ action: null, /** The event that should send the action. Options are: * `enter`: the user pressed enter * `keyPress`: the user pressed a key @property onEvent @type String @default enter @private */ onEvent: 'enter', /** Whether the `keyUp` event that triggers an `action` to be sent continues propagating to other views. By default, when the user presses the return key on their keyboard and the text field has an `action` set, the action will be sent to the view's controller and the key event will stop propagating. If you would like parent views to receive the `keyUp` event even after an action has been dispatched, set `bubbles` to true. @property bubbles @type Boolean @default false @private */ bubbles: false, interpretKeyEvents: function (event) { var map = KEY_EVENTS; var method = map[event.keyCode]; this._elementValueDidChange(); if (method) { return this[method](event); } }, _elementValueDidChange: function () { _emberMetalProperty_set.set(this, 'value', this.element.value); }, change: function (event) { this._elementValueDidChange(event); }, /** Allows you to specify a controller action to invoke when either the `enter` key is pressed or, in the case of the field being a textarea, when a newline is inserted. To use this method, give your field an `insert-newline` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `insert-newline` attribute, please reference the example near the top of this file. @method insertNewline @param {Event} event @private */ insertNewline: function (event) { sendAction('enter', this, event); sendAction('insert-newline', this, event); }, /** Allows you to specify a controller action to invoke when the escape button is pressed. To use this method, give your field an `escape-press` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `escape-press` attribute, please reference the example near the top of this file. @method cancel @param {Event} event @private */ cancel: function (event) { sendAction('escape-press', this, event); }, /** Allows you to specify a controller action to invoke when a field receives focus. To use this method, give your field a `focus-in` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `focus-in` attribute, please reference the example near the top of this file. @method focusIn @param {Event} event @private */ focusIn: function (event) { sendAction('focus-in', this, event); }, /** Allows you to specify a controller action to invoke when a field loses focus. To use this method, give your field a `focus-out` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `focus-out` attribute, please reference the example near the top of this file. @method focusOut @param {Event} event @private */ focusOut: function (event) { this._elementValueDidChange(event); sendAction('focus-out', this, event); }, /** Allows you to specify a controller action to invoke when a key is pressed. To use this method, give your field a `key-press` attribute. The value of that attribute should be the name of the action in your controller you that wish to invoke. For an example on how to use the `key-press` attribute, please reference the example near the top of this file. @method keyPress @param {Event} event @private */ keyPress: function (event) { sendAction('key-press', this, event); }, /** Allows you to specify a controller action to invoke when a key-up event is fired. To use this method, give your field a `key-up` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `key-up` attribute, please reference the example near the top of this file. @method keyUp @param {Event} event @private */ keyUp: function (event) { this.interpretKeyEvents(event); this.sendAction('key-up', _emberMetalProperty_get.get(this, 'value'), event); }, /** Allows you to specify a controller action to invoke when a key-down event is fired. To use this method, give your field a `key-down` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `key-down` attribute, please reference the example near the top of this file. @method keyDown @param {Event} event @private */ keyDown: function (event) { this.sendAction('key-down', _emberMetalProperty_get.get(this, 'value'), event); } }); // In principle, this shouldn't be necessary, but the legacy // sendAction semantics for TextField are different from // the component semantics so this method normalizes them. function sendAction(eventName, view, event) { var action = _emberMetalProperty_get.get(view, 'attrs.' + eventName) || _emberMetalProperty_get.get(view, eventName); var on = _emberMetalProperty_get.get(view, 'onEvent'); var value = _emberMetalProperty_get.get(view, 'value'); // back-compat support for keyPress as an event name even though // it's also a method name that consumes the event (and therefore // incompatible with sendAction semantics). if (on === eventName || on === 'keyPress' && eventName === 'key-press') { view.sendAction('action', value); } view.sendAction(eventName, value); if (action || on === eventName) { if (!_emberMetalProperty_get.get(view, 'bubbles')) { event.stopPropagation(); } } } }); enifed('ember-views/mixins/view_state_support', ['exports', 'ember-metal/mixin'], function (exports, _emberMetalMixin) { 'use strict'; exports.default = _emberMetalMixin.Mixin.create({ _transitionTo: function (state) { var priorState = this._currentState; var currentState = this._currentState = this._states[state]; this._state = state; if (priorState && priorState.exit) { priorState.exit(this); } if (currentState.enter) { currentState.enter(this); } } }); }); enifed('ember-views/mixins/view_support', ['exports', 'ember-metal/debug', 'ember-metal/run_loop', 'ember-metal/utils', 'ember-metal/mixin', 'ember-runtime/system/core_object', 'ember-metal/symbol', 'ember-views/system/jquery'], function (exports, _emberMetalDebug, _emberMetalRun_loop, _emberMetalUtils, _emberMetalMixin, _emberRuntimeSystemCore_object, _emberMetalSymbol, _emberViewsSystemJquery) { 'use strict'; var _Mixin$create; var INIT_WAS_CALLED = _emberMetalSymbol.default('INIT_WAS_CALLED'); function K() { return this; } exports.default = _emberMetalMixin.Mixin.create((_Mixin$create = { concatenatedProperties: ['attributeBindings'], // .......................................................... // TEMPLATE SUPPORT // /** Return the nearest ancestor that is an instance of the provided class or mixin. @method nearestOfType @param {Class,Mixin} klass Subclass of Ember.View (or Ember.View itself), or an instance of Ember.Mixin. @return Ember.View @deprecated use `yield` and contextual components for composition instead. @private */ nearestOfType: function (klass) { var view = this.parentView; var isOfType = klass instanceof _emberMetalMixin.Mixin ? function (view) { return klass.detect(view); } : function (view) { return klass.detect(view.constructor); }; while (view) { if (isOfType(view)) { return view; } view = view.parentView; } }, /** Return the nearest ancestor that has a given property. @method nearestWithProperty @param {String} property A property name @return Ember.View @deprecated use `yield` and contextual components for composition instead. @private */ nearestWithProperty: function (property) { var view = this.parentView; while (view) { if (property in view) { return view; } view = view.parentView; } }, /** Renders the view again. This will work regardless of whether the view is already in the DOM or not. If the view is in the DOM, the rendering process will be deferred to give bindings a chance to synchronize. If children were added during the rendering process using `appendChild`, `rerender` will remove them, because they will be added again if needed by the next `render`. In general, if the display of your view changes, you should modify the DOM element directly instead of manually calling `rerender`, which can be slow. @method rerender @public */ rerender: function () { return this._currentState.rerender(this); }, // .......................................................... // ELEMENT SUPPORT // /** Returns the current DOM element for the view. @property element @type DOMElement @public */ element: null, /** Returns a jQuery object for this view's element. If you pass in a selector string, this method will return a jQuery object, using the current element as its buffer. For example, calling `view.$('li')` will return a jQuery object containing all of the `li` elements inside the DOM element of this view. @method $ @param {String} [selector] a jQuery-compatible selector string @return {jQuery} the jQuery object for the DOM node @public */ $: function (sel) { _emberMetalDebug.assert('You cannot access this.$() on a component with `tagName: \'\'` specified.', this.tagName !== ''); return this._currentState.$(this, sel); }, /** Appends the view's element to the specified parent element. Note that this method just schedules the view to be appended; the DOM element will not be appended to the given element until all bindings have finished synchronizing. This is not typically a function that you will need to call directly when building your application. If you do need to use `appendTo`, be sure that the target element you are providing is associated with an `Ember.Application` and does not have an ancestor element that is associated with an Ember view. @method appendTo @param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object @return {Ember.View} receiver @private */ appendTo: function (selector) { var $ = this._environment ? this._environment.options.jQuery : _emberViewsSystemJquery.default; if ($) { var target = $(selector); _emberMetalDebug.assert('You tried to append to (' + selector + ') but that isn\'t in the DOM', target.length > 0); _emberMetalDebug.assert('You cannot append to an existing Ember.View.', !target.is('.ember-view') && !target.parents().is('.ember-view')); this.renderer.appendTo(this, target[0]); } else { var target = selector; _emberMetalDebug.assert('You tried to append to a selector string (' + selector + ') in an environment without jQuery', typeof target !== 'string'); _emberMetalDebug.assert('You tried to append to a non-Element (' + selector + ') in an environment without jQuery', typeof selector.appendChild === 'function'); this.renderer.appendTo(this, target); } return this; }, /** Creates a new DOM element, renders the view into it, then returns the element. By default, the element created and rendered into will be a `BODY` element, since this is the default context that views are rendered into when being inserted directly into the DOM. ```js let element = view.renderToElement(); element.tagName; // => "BODY" ``` You can override the kind of element rendered into and returned by specifying an optional tag name as the first argument. ```js let element = view.renderToElement('table'); element.tagName; // => "TABLE" ``` This method is useful if you want to render the view into an element that is not in the document's body. Instead, a new `body` element, detached from the DOM is returned. FastBoot uses this to serialize the rendered view into a string for transmission over the network. ```js app.visit('/').then(function(instance) { let element; Ember.run(function() { element = renderToElement(instance); }); res.send(serialize(element)); }); ``` @method renderToElement @param {String} tagName The tag of the element to create and render into. Defaults to "body". @return {HTMLBodyElement} element @private */ renderToElement: function (tagName) { tagName = tagName || 'body'; var element = this.renderer._dom.createElement(tagName); this.renderer.appendTo(this, element); return element; }, /** Replaces the content of the specified parent element with this view's element. If the view does not have an HTML representation yet, the element will be generated automatically. Note that this method just schedules the view to be appended; the DOM element will not be appended to the given element until all bindings have finished synchronizing @method replaceIn @param {String|DOMElement|jQuery} target A selector, element, HTML string, or jQuery object @return {Ember.View} received @private */ replaceIn: function (selector) { var target = _emberViewsSystemJquery.default(selector); _emberMetalDebug.assert('You tried to replace in (' + selector + ') but that isn\'t in the DOM', target.length > 0); _emberMetalDebug.assert('You cannot replace an existing Ember.View.', !target.is('.ember-view') && !target.parents().is('.ember-view')); this.renderer.replaceIn(this, target[0]); return this; }, /** Appends the view's element to the document body. If the view does not have an HTML representation yet the element will be generated automatically. If your application uses the `rootElement` property, you must append the view within that element. Rendering views outside of the `rootElement` is not supported. Note that this method just schedules the view to be appended; the DOM element will not be appended to the document body until all bindings have finished synchronizing. @method append @return {Ember.View} receiver @private */ append: function () { return this.appendTo(document.body); }, /** The HTML `id` of the view's element in the DOM. You can provide this value yourself but it must be unique (just as in HTML): ```handlebars {{my-component elementId="a-really-cool-id"}} ``` If not manually set a default value will be provided by the framework. Once rendered an element's `elementId` is considered immutable and you should never change it. If you need to compute a dynamic value for the `elementId`, you should do this when the component or element is being instantiated: ```javascript export default Ember.Component.extend({ setElementId: Ember.on('init', function() { let index = this.get('index'); this.set('elementId', 'component-id' + index); }) }); ``` @property elementId @type String @public */ elementId: null, /** Attempts to discover the element in the parent element. The default implementation looks for an element with an ID of `elementId` (or the view's guid if `elementId` is null). You can override this method to provide your own form of lookup. For example, if you want to discover your element using a CSS class name instead of an ID. @method findElementInParentElement @param {DOMElement} parentElement The parent's DOM element @return {DOMElement} The discovered element @private */ findElementInParentElement: function (parentElem) { var id = '#' + this.elementId; return _emberViewsSystemJquery.default(id)[0] || _emberViewsSystemJquery.default(id, parentElem)[0]; }, /** Called when a view is going to insert an element into the DOM. @event willInsertElement @public */ willInsertElement: K, /** Called when the element of the view has been inserted into the DOM or after the view was re-rendered. Override this function to do any set up that requires an element in the document body. When a view has children, didInsertElement will be called on the child view(s) first, bubbling upwards through the hierarchy. @event didInsertElement @public */ didInsertElement: K, /** Called when the view is about to rerender, but before anything has been torn down. This is a good opportunity to tear down any manual observers you have installed based on the DOM state @event willClearRender @public */ willClearRender: K, /** You must call `destroy` on a view to destroy the view (and all of its child views). This will remove the view from any parent node, then make sure that the DOM element managed by the view can be released by the memory manager. @method destroy @private */ destroy: function () { this._super.apply(this, arguments); this._currentState.destroy(this); }, /** Called when the element of the view is going to be destroyed. Override this function to do any teardown that requires an element, like removing event listeners. Please note: any property changes made during this event will have no effect on object observers. @event willDestroyElement @public */ willDestroyElement: K, /** Called when the parentView property has changed. @event parentViewDidChange @private */ parentViewDidChange: K, // .......................................................... // STANDARD RENDER PROPERTIES // /** Tag name for the view's outer element. The tag name is only used when an element is first created. If you change the `tagName` for an element, you must destroy and recreate the view element. By default, the render buffer will use a `<div>` tag for views. @property tagName @type String @default null @public */ // We leave this null by default so we can tell the difference between // the default case and a user-specified tag. tagName: null, // ....................................................... // CORE DISPLAY METHODS // /** Setup a view, but do not finish waking it up. * configure `childViews` * register the view with the global views hash, which is used for event dispatch @method init @private */ init: function () { this._super.apply(this, arguments); if (!this.elementId && this.tagName !== '') { this.elementId = _emberMetalUtils.guidFor(this); } this.scheduledRevalidation = false; this[INIT_WAS_CALLED] = true; if (typeof this.didInitAttrs === 'function') { _emberMetalDebug.deprecate('[DEPRECATED] didInitAttrs called in ' + this.toString() + '.', false, { id: 'ember-views.did-init-attrs', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_ember-component-didinitattrs' }); } _emberMetalDebug.assert('Using a custom `.render` function is no longer supported.', !this.render); } }, _Mixin$create[_emberRuntimeSystemCore_object.POST_INIT] = function () { this._super(); _emberMetalDebug.assert('You must call `this._super(...arguments);` when implementing `init` in a component. Please update ' + this + ' to call `this._super` from `init`.', this[INIT_WAS_CALLED]); this.renderer.componentInitAttrs(this, this.attrs || {}); }, _Mixin$create.__defineNonEnumerable = function (property) { this[property.name] = property.descriptor.value; }, _Mixin$create.revalidate = function () { this.renderer.revalidateTopLevelView(this); this.scheduledRevalidation = false; }, _Mixin$create.scheduleRevalidate = function (node, label, manualRerender) { if (node && !this._dispatching && this._env.renderedNodes.has(node)) { if (manualRerender) { _emberMetalDebug.deprecate('You manually rerendered ' + label + ' (a parent component) from a child component during the rendering process. This rarely worked in Ember 1.x and will be removed in Ember 3.0', false, { id: 'ember-views.manual-parent-rerender', until: '3.0.0' }); } else { _emberMetalDebug.deprecate('You modified ' + label + ' twice in a single render. This was unreliable in Ember 1.x and will be removed in Ember 3.0', false, { id: 'ember-views.render-double-modify', until: '3.0.0' }); } _emberMetalRun_loop.default.scheduleOnce('render', this, this.revalidate); return; } _emberMetalDebug.deprecate('A property of ' + this + ' was modified inside the ' + this._dispatching + ' hook. You should never change properties on components, services or models during ' + this._dispatching + ' because it causes significant performance degradation.', !this._dispatching, { id: 'ember-views.dispatching-modify-property', until: '3.0.0' }); if (!this.scheduledRevalidation || this._dispatching) { this.scheduledRevalidation = true; _emberMetalRun_loop.default.scheduleOnce('render', this, this.revalidate); } }, _Mixin$create.handleEvent = function (eventName, evt) { return this._currentState.handleEvent(this, eventName, evt); }, _Mixin$create)); }); /* This is a special hook implemented in CoreObject, that allows Views/Components to have a way to ensure that `init` fires before `didInitAttrs` / `didReceiveAttrs` (so that `this._super` in init does not trigger `didReceiveAttrs` before the classes own `init` is finished). @method __postInitInitialization @private */ // ....................................................... // EVENT HANDLING // /** Handle events from `Ember.EventDispatcher` @method handleEvent @param eventName {String} @param evt {Event} @private */ enifed('ember-views/mixins/view_target_action_support', ['exports', 'ember-metal/mixin', 'ember-runtime/mixins/target_action_support', 'ember-metal/alias'], function (exports, _emberMetalMixin, _emberRuntimeMixinsTarget_action_support, _emberMetalAlias) { 'use strict'; /** `Ember.ViewTargetActionSupport` is a mixin that can be included in a view class to add a `triggerAction` method with semantics similar to the Handlebars `{{action}}` helper. It provides intelligent defaults for the action's target: the view's controller; and the context that is sent with the action: the view's context. Note: In normal Ember usage, the `{{action}}` helper is usually the best choice. This mixin is most often useful when you are doing more complex event handling in custom View subclasses. For example: ```javascript App.SaveButtonView = Ember.View.extend(Ember.ViewTargetActionSupport, { action: 'save', click: function() { this.triggerAction(); // Sends the `save` action, along with the current context // to the current controller } }); ``` The `action` can be provided as properties of an optional object argument to `triggerAction` as well. ```javascript App.SaveButtonView = Ember.View.extend(Ember.ViewTargetActionSupport, { click: function() { this.triggerAction({ action: 'save' }); // Sends the `save` action, along with the current context // to the current controller } }); ``` @class ViewTargetActionSupport @namespace Ember @extends Ember.TargetActionSupport @private */ exports.default = _emberMetalMixin.Mixin.create(_emberRuntimeMixinsTarget_action_support.default, { /** @property target @private */ target: _emberMetalAlias.default('controller'), /** @property actionContext @private */ actionContext: _emberMetalAlias.default('context') }); }); enifed('ember-views/mixins/visibility_support', ['exports', 'ember-metal/mixin', 'ember-metal/property_get', 'ember-metal/run_loop'], function (exports, _emberMetalMixin, _emberMetalProperty_get, _emberMetalRun_loop) { /** @module ember @submodule ember-views */ 'use strict'; function K() { return this; } /** @class VisibilitySupport @namespace Ember @public */ exports.default = _emberMetalMixin.Mixin.create({ /** If `false`, the view will appear hidden in DOM. @property isVisible @type Boolean @default null @public */ isVisible: true, becameVisible: K, becameHidden: K, /** When the view's `isVisible` property changes, toggle the visibility element of the actual DOM element. @method _isVisibleDidChange @private */ _isVisibleDidChange: _emberMetalMixin.observer('isVisible', function () { if (this._isVisible === _emberMetalProperty_get.get(this, 'isVisible')) { return; } _emberMetalRun_loop.default.scheduleOnce('render', this, this._toggleVisibility); }), _toggleVisibility: function () { var $el = this.$(); var isVisible = _emberMetalProperty_get.get(this, 'isVisible'); if (this._isVisible === isVisible) { return; } // It's important to keep these in sync, even if we don't yet have // an element in the DOM to manipulate: this._isVisible = isVisible; if (!$el) { return; } $el.toggle(isVisible); if (this._isAncestorHidden()) { return; } if (isVisible) { this._notifyBecameVisible(); } else { this._notifyBecameHidden(); } }, _notifyBecameVisible: function () { this.trigger('becameVisible'); var childViews = this.childViews; for (var i = 0; i < childViews.length; i++) { var view = childViews[i]; var isVisible = _emberMetalProperty_get.get(view, 'isVisible'); if (isVisible || isVisible === null) { view._notifyBecameVisible(); } } }, _notifyBecameHidden: function () { this.trigger('becameHidden'); var childViews = this.childViews; for (var i = 0; i < childViews.length; i++) { var view = childViews[i]; var isVisible = _emberMetalProperty_get.get(view, 'isVisible'); if (isVisible || isVisible === null) { view._notifyBecameHidden(); } } }, _isAncestorHidden: function () { var parent = this.parentView; while (parent) { if (_emberMetalProperty_get.get(parent, 'isVisible') === false) { return true; } parent = parent.parentView; } return false; } }); }); enifed("ember-views/system/action_manager", ["exports"], function (exports) { /** @module ember @submodule ember-views */ "use strict"; exports.default = ActionManager; function ActionManager() {} /** Global action id hash. @private @property registeredActions @type Object */ ActionManager.registeredActions = {}; }); enifed('ember-views/system/event_dispatcher', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/is_none', 'ember-metal/run_loop', 'ember-runtime/system/object', 'ember-views/system/jquery', 'ember-views/system/action_manager', 'ember-metal/assign', 'container/owner', 'ember-environment', 'ember-views/compat/fallback-view-registry'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalIs_none, _emberMetalRun_loop, _emberRuntimeSystemObject, _emberViewsSystemJquery, _emberViewsSystemAction_manager, _emberMetalAssign, _containerOwner, _emberEnvironment, _emberViewsCompatFallbackViewRegistry) { /** @module ember @submodule ember-views */ 'use strict'; var ROOT_ELEMENT_CLASS = 'ember-application'; var ROOT_ELEMENT_SELECTOR = '.' + ROOT_ELEMENT_CLASS; /** `Ember.EventDispatcher` handles delegating browser events to their corresponding `Ember.Views.` For example, when you click on a view, `Ember.EventDispatcher` ensures that that view's `mouseDown` method gets called. @class EventDispatcher @namespace Ember @private @extends Ember.Object */ exports.default = _emberRuntimeSystemObject.default.extend({ /** The set of events names (and associated handler function names) to be setup and dispatched by the `EventDispatcher`. Modifications to this list can be done at setup time, generally via the `Ember.Application.customEvents` hash. To add new events to be listened to: ```javascript let App = Ember.Application.create({ customEvents: { paste: 'paste' } }); ``` To prevent default events from being listened to: ```javascript let App = Ember.Application.create({ customEvents: { mouseenter: null, mouseleave: null } }); ``` @property events @type Object @private */ events: { touchstart: 'touchStart', touchmove: 'touchMove', touchend: 'touchEnd', touchcancel: 'touchCancel', keydown: 'keyDown', keyup: 'keyUp', keypress: 'keyPress', mousedown: 'mouseDown', mouseup: 'mouseUp', contextmenu: 'contextMenu', click: 'click', dblclick: 'doubleClick', mousemove: 'mouseMove', focusin: 'focusIn', focusout: 'focusOut', mouseenter: 'mouseEnter', mouseleave: 'mouseLeave', submit: 'submit', input: 'input', change: 'change', dragstart: 'dragStart', drag: 'drag', dragenter: 'dragEnter', dragleave: 'dragLeave', dragover: 'dragOver', drop: 'drop', dragend: 'dragEnd' }, /** The root DOM element to which event listeners should be attached. Event listeners will be attached to the document unless this is overridden. Can be specified as a DOMElement or a selector string. The default body is a string since this may be evaluated before document.body exists in the DOM. @private @property rootElement @type DOMElement @default 'body' */ rootElement: 'body', /** It enables events to be dispatched to the view's `eventManager.` When present, this object takes precedence over handling of events on the view itself. Note that most Ember applications do not use this feature. If your app also does not use it, consider setting this property to false to gain some performance improvement by allowing the EventDispatcher to skip the search for the `eventManager` on the view tree. ```javascript let EventDispatcher = Em.EventDispatcher.extend({ events: { click : 'click', focusin : 'focusIn', focusout : 'focusOut', change : 'change' }, canDispatchToEventManager: false }); container.register('event_dispatcher:main', EventDispatcher); ``` @property canDispatchToEventManager @type boolean @default 'true' @since 1.7.0 @private */ canDispatchToEventManager: true, init: function () { this._super(); _emberMetalDebug.assert('EventDispatcher should never be instantiated in fastboot mode. Please report this as an Ember bug.', _emberEnvironment.environment.hasDOM); }, /** Sets up event listeners for standard browser events. This will be called after the browser sends a `DOMContentReady` event. By default, it will set up all of the listeners on the document body. If you would like to register the listeners on a different element, set the event dispatcher's `root` property. @private @method setup @param addedEvents {Object} */ setup: function (addedEvents, rootElement) { var event = undefined; var events = this._finalEvents = _emberMetalAssign.default({}, _emberMetalProperty_get.get(this, 'events'), addedEvents); if (!_emberMetalIs_none.default(rootElement)) { _emberMetalProperty_set.set(this, 'rootElement', rootElement); } rootElement = _emberViewsSystemJquery.default(_emberMetalProperty_get.get(this, 'rootElement')); _emberMetalDebug.assert('You cannot use the same root element (' + (rootElement.selector || rootElement[0].tagName) + ') multiple times in an Ember.Application', !rootElement.is(ROOT_ELEMENT_SELECTOR)); _emberMetalDebug.assert('You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application', !rootElement.closest(ROOT_ELEMENT_SELECTOR).length); _emberMetalDebug.assert('You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application', !rootElement.find(ROOT_ELEMENT_SELECTOR).length); rootElement.addClass(ROOT_ELEMENT_CLASS); if (!rootElement.is(ROOT_ELEMENT_SELECTOR)) { throw new TypeError('Unable to add \'' + ROOT_ELEMENT_CLASS + '\' class to root element (' + (rootElement.selector || rootElement[0].tagName) + '). Make sure you set rootElement to the body or an element in the body.'); } for (event in events) { if (events.hasOwnProperty(event)) { this.setupHandler(rootElement, event, events[event]); } } }, /** Registers an event listener on the rootElement. If the given event is triggered, the provided event handler will be triggered on the target view. If the target view does not implement the event handler, or if the handler returns `false`, the parent view will be called. The event will continue to bubble to each successive parent view until it reaches the top. @private @method setupHandler @param {Element} rootElement @param {String} event the browser-originated event to listen to @param {String} eventName the name of the method to call on the view */ setupHandler: function (rootElement, event, eventName) { var self = this; var owner = _containerOwner.getOwner(this); var viewRegistry = owner && owner.lookup('-view-registry:main') || _emberViewsCompatFallbackViewRegistry.default; if (eventName === null) { return; } rootElement.on(event + '.ember', '.ember-view', function (evt, triggeringManager) { var view = viewRegistry[this.id]; var result = true; var manager = self.canDispatchToEventManager ? self._findNearestEventManager(view, eventName) : null; if (manager && manager !== triggeringManager) { result = self._dispatchEvent(manager, evt, eventName, view); } else if (view) { result = self._bubbleEvent(view, evt, eventName); } return result; }); rootElement.on(event + '.ember', '[data-ember-action]', function (evt) { var actionId = _emberViewsSystemJquery.default(evt.currentTarget).attr('data-ember-action'); var actions = _emberViewsSystemAction_manager.default.registeredActions[actionId]; // In Glimmer2 this attribute is set to an empty string and an additional // attribute it set for each action on a given element. In this case, the // attributes need to be read so that a proper set of action handlers can // be coalesced. if (actionId === '') { var attributes = evt.currentTarget.attributes; var attributeCount = attributes.length; actions = []; for (var i = 0; i < attributeCount; i++) { var attr = attributes.item(i); var attrName = attr.name; if (attrName.indexOf('data-ember-action-') === 0) { actions = actions.concat(_emberViewsSystemAction_manager.default.registeredActions[attr.value]); } } } // We have to check for actions here since in some cases, jQuery will trigger // an event on `removeChild` (i.e. focusout) after we've already torn down the // action handlers for the view. if (!actions) { return; } for (var index = 0; index < actions.length; index++) { var action = actions[index]; if (action && action.eventName === eventName) { return action.handler(evt); } } }); }, _findNearestEventManager: function (view, eventName) { var manager = null; while (view) { manager = _emberMetalProperty_get.get(view, 'eventManager'); if (manager && manager[eventName]) { break; } view = _emberMetalProperty_get.get(view, 'parentView'); } return manager; }, _dispatchEvent: function (object, evt, eventName, view) { var result = true; var handler = object[eventName]; if (typeof handler === 'function') { result = _emberMetalRun_loop.default(object, handler, evt, view); // Do not preventDefault in eventManagers. evt.stopPropagation(); } else { result = this._bubbleEvent(view, evt, eventName); } return result; }, _bubbleEvent: function (view, evt, eventName) { return view.handleEvent(eventName, evt); }, destroy: function () { var rootElement = _emberMetalProperty_get.get(this, 'rootElement'); _emberViewsSystemJquery.default(rootElement).off('.ember', '**').removeClass(ROOT_ELEMENT_CLASS); return this._super.apply(this, arguments); }, toString: function () { return '(EventDispatcher)'; } }); }); enifed('ember-views/system/ext', ['exports', 'ember-metal/run_loop'], function (exports, _emberMetalRun_loop) { /** @module ember @submodule ember-views */ 'use strict'; // Add a new named queue for rendering views that happens // after bindings have synced, and a queue for scheduling actions // that should occur after view rendering. _emberMetalRun_loop.default._addQueue('render', 'actions'); _emberMetalRun_loop.default._addQueue('afterRender', 'render'); }); enifed('ember-views/system/jquery', ['exports', 'ember-environment'], function (exports, _emberEnvironment) { 'use strict'; var jQuery = undefined; if (_emberEnvironment.environment.hasDOM) { jQuery = _emberEnvironment.context.imports.jQuery; if (jQuery) { if (jQuery.event.addProp) { jQuery.event.addProp('dataTransfer'); } else { // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dndevents ['dragstart', 'drag', 'dragenter', 'dragleave', 'dragover', 'drop', 'dragend'].forEach(function (eventName) { jQuery.event.fixHooks[eventName] = { props: ['dataTransfer'] }; }); } } } exports.default = jQuery; }); enifed('ember-views/system/lookup_partial', ['exports', 'ember-metal/debug', 'ember-metal/error'], function (exports, _emberMetalDebug, _emberMetalError) { 'use strict'; exports.default = lookupPartial; exports.hasPartial = hasPartial; function parseUnderscoredName(templateName) { var nameParts = templateName.split('/'); var lastPart = nameParts[nameParts.length - 1]; nameParts[nameParts.length - 1] = '_' + lastPart; return nameParts.join('/'); } function lookupPartial(env, templateName) { if (templateName == null) { return; } var template = templateFor(env, parseUnderscoredName(templateName), templateName); _emberMetalDebug.assert('Unable to find partial with name "' + templateName + '"', !!template); return template; } function hasPartial(env, name) { if (!env.owner) { throw new _emberMetalError.default('Container was not found when looking up a views template. ' + 'This is most likely due to manually instantiating an Ember.View. ' + 'See: http://git.io/EKPpnA'); } return env.owner.hasRegistration('template:' + parseUnderscoredName(name)) || env.owner.hasRegistration('template:' + name); } function templateFor(env, underscored, name) { if (!name) { return; } _emberMetalDebug.assert('templateNames are not allowed to contain periods: ' + name, name.indexOf('.') === -1); if (!env.owner) { throw new _emberMetalError.default('Container was not found when looking up a views template. ' + 'This is most likely due to manually instantiating an Ember.View. ' + 'See: http://git.io/EKPpnA'); } return env.owner.lookup('template:' + underscored) || env.owner.lookup('template:' + name); } }); enifed('ember-views/system/utils', ['exports'], function (exports) { /** @module ember @submodule ember-views */ 'use strict'; exports.isSimpleClick = isSimpleClick; exports.getViewClientRects = getViewClientRects; exports.getViewBoundingClientRect = getViewBoundingClientRect; function isSimpleClick(event) { var modifier = event.shiftKey || event.metaKey || event.altKey || event.ctrlKey; var secondaryClick = event.which > 1; // IE9 may return undefined return !modifier && !secondaryClick; } var STYLE_WARNING = '' + 'Binding style attributes may introduce cross-site scripting vulnerabilities; ' + 'please ensure that values being bound are properly escaped. For more information, ' + 'including how to disable this warning, see ' + 'http://emberjs.com/deprecations/v1.x/#toc_binding-style-attributes.'; exports.STYLE_WARNING = STYLE_WARNING; /** @private @method getViewRange @param {Ember.View} view */ function getViewRange(view) { var range = document.createRange(); range.setStartBefore(view._renderNode.firstNode); range.setEndAfter(view._renderNode.lastNode); return range; } /** `getViewClientRects` provides information about the position of the border box edges of a view relative to the viewport. It is only intended to be used by development tools like the Ember Inspector and may not work on older browsers. @private @method getViewClientRects @param {Ember.View} view */ function getViewClientRects(view) { var range = getViewRange(view); return range.getClientRects(); } /** `getViewBoundingClientRect` provides information about the position of the bounding border box edges of a view relative to the viewport. It is only intended to be used by development tools like the Ember Inpsector and may not work on older browsers. @private @method getViewBoundingClientRect @param {Ember.View} view */ function getViewBoundingClientRect(view) { var range = getViewRange(view); return range.getBoundingClientRect(); } }); enifed('ember-views/utils/lookup-component', ['exports', 'container/registry'], function (exports, _containerRegistry) { 'use strict'; exports.default = lookupComponent; var _templateObject = _taggedTemplateLiteralLoose(['component:-default'], ['component:-default']); function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } function lookupComponentPair(componentLookup, owner, name, options) { var component = componentLookup.componentFor(name, owner, options); var layout = componentLookup.layoutFor(name, owner, options); var result = { layout: layout, component: component }; if (layout && !component) { result.component = owner._lookupFactory(_containerRegistry.privatize(_templateObject)); } return result; } function lookupComponent(owner, name, options) { var componentLookup = owner.lookup('component-lookup:main'); var source = options && options.source; if (source) { var localResult = lookupComponentPair(componentLookup, owner, name, options); if (localResult.component || localResult.layout) { return localResult; } } return lookupComponentPair(componentLookup, owner, name); } }); enifed('ember-views/views/core_view', ['exports', 'ember-metal/property_get', 'ember-runtime/system/object', 'ember-runtime/mixins/evented', 'ember-runtime/mixins/action_handler', 'ember-runtime/utils', 'ember-views/views/states', 'require'], function (exports, _emberMetalProperty_get, _emberRuntimeSystemObject, _emberRuntimeMixinsEvented, _emberRuntimeMixinsAction_handler, _emberRuntimeUtils, _emberViewsViewsStates, _require) { 'use strict'; // Normally, the renderer is injected by the container when the view is looked // up. However, if someone creates a view without looking it up via the // container (e.g. `Ember.View.create().append()`) then we create a fallback // DOM renderer that is shared. In general, this path should be avoided since // views created this way cannot run in a node environment. var renderer = undefined; /** `Ember.CoreView` is an abstract class that exists to give view-like behavior to both Ember's main view class `Ember.View` and other classes that don't need the fully functionaltiy of `Ember.View`. Unless you have specific needs for `CoreView`, you will use `Ember.View` in your applications. @class CoreView @namespace Ember @extends Ember.Object @deprecated Use `Ember.View` instead. @uses Ember.Evented @uses Ember.ActionHandler @private */ var CoreView = _emberRuntimeSystemObject.default.extend(_emberRuntimeMixinsEvented.default, _emberRuntimeMixinsAction_handler.default, { isView: true, _states: _emberViewsViewsStates.cloneStates(_emberViewsViewsStates.states), init: function () { this._super.apply(this, arguments); this._state = 'preRender'; this._currentState = this._states.preRender; this._willInsert = false; this._renderNode = null; this.lastResult = null; this._dispatching = null; this._destroyingSubtreeForView = null; this._isDispatchingAttrs = false; this._isVisible = false; this.element = null; this._env = null; this._isVisible = _emberMetalProperty_get.get(this, 'isVisible'); // Fallback for legacy cases where the view was created directly // via `create()` instead of going through the container. if (!this.renderer) { renderer = renderer || htmlbarsRenderer(); this.renderer = renderer; } }, /** If the view is currently inserted into the DOM of a parent view, this property will point to the parent of the view. @property parentView @type Ember.View @default null @private */ parentView: null, instrumentName: 'core_view', instrumentDetails: function (hash) { hash.object = this.toString(); hash.containerKey = this._debugContainerKey; hash.view = this; }, /** Override the default event firing from `Ember.Evented` to also call methods with the given name. @method trigger @param name {String} @private */ trigger: function () { this._super.apply(this, arguments); var name = arguments[0]; var method = this[name]; if (method) { var args = new Array(arguments.length - 1); for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } return method.apply(this, args); } }, has: function (name) { return _emberRuntimeUtils.typeOf(this[name]) === 'function' || this._super(name); } }); _emberRuntimeMixinsAction_handler.deprecateUnderscoreActions(CoreView); CoreView.reopenClass({ isViewFactory: true }); var InteractiveRenderer = undefined, DOMHelper = undefined; function htmlbarsRenderer() { DOMHelper = DOMHelper || _require.default('ember-htmlbars/system/dom-helper').default; InteractiveRenderer = InteractiveRenderer || _require.default('ember-htmlbars/renderer').InteractiveRenderer; return InteractiveRenderer.create({ dom: new DOMHelper() }); } exports.default = CoreView; }); enifed('ember-views/views/states', ['exports', 'ember-metal/assign', 'ember-views/views/states/default', 'ember-views/views/states/pre_render', 'ember-views/views/states/has_element', 'ember-views/views/states/in_dom', 'ember-views/views/states/destroying'], function (exports, _emberMetalAssign, _emberViewsViewsStatesDefault, _emberViewsViewsStatesPre_render, _emberViewsViewsStatesHas_element, _emberViewsViewsStatesIn_dom, _emberViewsViewsStatesDestroying) { 'use strict'; exports.cloneStates = cloneStates; function cloneStates(from) { var into = {}; into._default = {}; into.preRender = Object.create(into._default); into.destroying = Object.create(into._default); into.hasElement = Object.create(into._default); into.inDOM = Object.create(into.hasElement); for (var stateName in from) { if (!from.hasOwnProperty(stateName)) { continue; } _emberMetalAssign.default(into[stateName], from[stateName]); } return into; } var states = { _default: _emberViewsViewsStatesDefault.default, preRender: _emberViewsViewsStatesPre_render.default, inDOM: _emberViewsViewsStatesIn_dom.default, hasElement: _emberViewsViewsStatesHas_element.default, destroying: _emberViewsViewsStatesDestroying.default }; exports.states = states; }); enifed('ember-views/views/states/default', ['exports', 'ember-metal/error', 'ember-metal/property_get', 'ember-views/compat/attrs-proxy'], function (exports, _emberMetalError, _emberMetalProperty_get, _emberViewsCompatAttrsProxy) { 'use strict'; /** @module ember @submodule ember-views */ exports.default = { // appendChild is only legal while rendering the buffer. appendChild: function () { throw new _emberMetalError.default('You can\'t use appendChild outside of the rendering process'); }, $: function () { return undefined; }, getElement: function () { return null; }, legacyPropertyDidChange: function (view, key) { var attrs = view.attrs; if (attrs && key in attrs) { var possibleCell = attrs[key]; if (possibleCell && possibleCell[_emberViewsCompatAttrsProxy.MUTABLE_CELL]) { var value = _emberMetalProperty_get.get(view, key); if (value === possibleCell.value) { return; } possibleCell.update(value); } } }, // Handle events from `Ember.EventDispatcher` handleEvent: function () { return true; // continue event propagation }, destroy: function () {}, rerender: function (view) { view.renderer.ensureViewNotRendering(view); } }; }); enifed('ember-views/views/states/destroying', ['exports', 'ember-metal/assign', 'ember-views/views/states/default', 'ember-metal/error'], function (exports, _emberMetalAssign, _emberViewsViewsStatesDefault, _emberMetalError) { 'use strict'; /** @module ember @submodule ember-views */ var destroying = Object.create(_emberViewsViewsStatesDefault.default); _emberMetalAssign.default(destroying, { appendChild: function () { throw new _emberMetalError.default('You can\'t call appendChild on a view being destroyed'); }, rerender: function () { throw new _emberMetalError.default('You can\'t call rerender on a view being destroyed'); } }); exports.default = destroying; }); enifed('ember-views/views/states/has_element', ['exports', 'ember-views/views/states/default', 'ember-metal/assign', 'ember-views/system/jquery', 'ember-metal/run_loop', 'ember-metal/instrumentation', 'ember-metal/property_get'], function (exports, _emberViewsViewsStatesDefault, _emberMetalAssign, _emberViewsSystemJquery, _emberMetalRun_loop, _emberMetalInstrumentation, _emberMetalProperty_get) { 'use strict'; var hasElement = Object.create(_emberViewsViewsStatesDefault.default); _emberMetalAssign.default(hasElement, { $: function (view, sel) { var elem = view.element; return sel ? _emberViewsSystemJquery.default(sel, elem) : _emberViewsSystemJquery.default(elem); }, getElement: function (view) { var parent = _emberMetalProperty_get.get(view, 'parentView'); if (parent) { parent = _emberMetalProperty_get.get(parent, 'element'); } if (parent) { return view.findElementInParentElement(parent); } return _emberViewsSystemJquery.default('#' + _emberMetalProperty_get.get(view, 'elementId'))[0]; }, // once the view has been inserted into the DOM, rerendering is // deferred to allow bindings to synchronize. rerender: function (view) { view.renderer.ensureViewNotRendering(view); view.renderer.rerender(view); }, destroy: function (view) { view.renderer.remove(view); }, // Handle events from `Ember.EventDispatcher` handleEvent: function (view, eventName, event) { if (view.has(eventName)) { // Handler should be able to re-dispatch events, so we don't // preventDefault or stopPropagation. return _emberMetalInstrumentation.flaggedInstrument('interaction.' + eventName, { event: event, view: view }, function () { return _emberMetalRun_loop.default.join(view, view.trigger, eventName, event); }); } else { return true; // continue event propagation } } }); exports.default = hasElement; }); /** @module ember @submodule ember-views */ enifed('ember-views/views/states/in_dom', ['exports', 'ember-metal/debug', 'ember-metal/assign', 'ember-metal/error', 'ember-metal/observer', 'ember-views/views/states/has_element'], function (exports, _emberMetalDebug, _emberMetalAssign, _emberMetalError, _emberMetalObserver, _emberViewsViewsStatesHas_element) { 'use strict'; /** @module ember @submodule ember-views */ var inDOM = Object.create(_emberViewsViewsStatesHas_element.default); _emberMetalAssign.default(inDOM, { enter: function (view) { // Register the view for event handling. This hash is used by // Ember.EventDispatcher to dispatch incoming events. if (view.tagName !== '') { view.renderer._register(view); } _emberMetalDebug.runInDebug(function () { _emberMetalObserver._addBeforeObserver(view, 'elementId', function () { throw new _emberMetalError.default('Changing a view\'s elementId after creation is not allowed'); }); }); }, exit: function (view) { if (view.tagName !== '') { view.renderer._unregister(view); } } }); exports.default = inDOM; }); enifed('ember-views/views/states/pre_render', ['exports', 'ember-views/views/states/default', 'ember-metal/assign'], function (exports, _emberViewsViewsStatesDefault, _emberMetalAssign) { 'use strict'; /** @module ember @submodule ember-views */ var preRender = Object.create(_emberViewsViewsStatesDefault.default); _emberMetalAssign.default(preRender, { legacyPropertyDidChange: function (view, key) {} }); exports.default = preRender; }); enifed('ember-views/views/view', ['exports', 'ember-views/system/ext', 'ember-views/views/core_view', 'ember-views/mixins/child_views_support', 'ember-views/mixins/view_state_support', 'ember-views/mixins/class_names_support', 'ember-views/mixins/instrumentation_support', 'ember-views/mixins/aria_role_support', 'ember-views/mixins/visibility_support', 'ember-views/compat/attrs-proxy', 'ember-views/mixins/view_support'], function (exports, _emberViewsSystemExt, _emberViewsViewsCore_view, _emberViewsMixinsChild_views_support, _emberViewsMixinsView_state_support, _emberViewsMixinsClass_names_support, _emberViewsMixinsInstrumentation_support, _emberViewsMixinsAria_role_support, _emberViewsMixinsVisibility_support, _emberViewsCompatAttrsProxy, _emberViewsMixinsView_support) { 'use strict'; /** @module ember @submodule ember-views */ /** `Ember.View` is the class in Ember responsible for encapsulating templates of HTML content, combining templates with data to render as sections of a page's DOM, and registering and responding to user-initiated events. ## HTML Tag The default HTML tag name used for a view's DOM representation is `div`. This can be customized by setting the `tagName` property. The following view class: ```javascript ParagraphView = Ember.View.extend({ tagName: 'em' }); ``` Would result in instances with the following HTML: ```html <em id="ember1" class="ember-view"></em> ``` ## HTML `class` Attribute The HTML `class` attribute of a view's tag can be set by providing a `classNames` property that is set to an array of strings: ```javascript MyView = Ember.View.extend({ classNames: ['my-class', 'my-other-class'] }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view my-class my-other-class"></div> ``` `class` attribute values can also be set by providing a `classNameBindings` property set to an array of properties names for the view. The return value of these properties will be added as part of the value for the view's `class` attribute. These properties can be computed properties: ```javascript MyView = Ember.View.extend({ classNameBindings: ['propertyA', 'propertyB'], propertyA: 'from-a', propertyB: Ember.computed(function() { if (someLogic) { return 'from-b'; } }) }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view from-a from-b"></div> ``` If the value of a class name binding returns a boolean the property name itself will be used as the class name if the property is true. The class name will not be added if the value is `false` or `undefined`. ```javascript MyView = Ember.View.extend({ classNameBindings: ['hovered'], hovered: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view hovered"></div> ``` When using boolean class name bindings you can supply a string value other than the property name for use as the `class` HTML attribute by appending the preferred value after a ":" character when defining the binding: ```javascript MyView = Ember.View.extend({ classNameBindings: ['awesome:so-very-cool'], awesome: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view so-very-cool"></div> ``` Boolean value class name bindings whose property names are in a camelCase-style format will be converted to a dasherized format: ```javascript MyView = Ember.View.extend({ classNameBindings: ['isUrgent'], isUrgent: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view is-urgent"></div> ``` Class name bindings can also refer to object values that are found by traversing a path relative to the view itself: ```javascript MyView = Ember.View.extend({ classNameBindings: ['messages.empty'] messages: Ember.Object.create({ empty: true }) }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view empty"></div> ``` If you want to add a class name for a property which evaluates to true and and a different class name if it evaluates to false, you can pass a binding like this: ```javascript // Applies 'enabled' class when isEnabled is true and 'disabled' when isEnabled is false Ember.View.extend({ classNameBindings: ['isEnabled:enabled:disabled'] isEnabled: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view enabled"></div> ``` When isEnabled is `false`, the resulting HTML representation looks like this: ```html <div id="ember1" class="ember-view disabled"></div> ``` This syntax offers the convenience to add a class if a property is `false`: ```javascript // Applies no class when isEnabled is true and class 'disabled' when isEnabled is false Ember.View.extend({ classNameBindings: ['isEnabled::disabled'] isEnabled: true }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view"></div> ``` When the `isEnabled` property on the view is set to `false`, it will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view disabled"></div> ``` Updates to the value of a class name binding will result in automatic update of the HTML `class` attribute in the view's rendered HTML representation. If the value becomes `false` or `undefined` the class name will be removed. Both `classNames` and `classNameBindings` are concatenated properties. See [Ember.Object](/api/classes/Ember.Object.html) documentation for more information about concatenated properties. ## HTML Attributes The HTML attribute section of a view's tag can be set by providing an `attributeBindings` property set to an array of property names on the view. The return value of these properties will be used as the value of the view's HTML associated attribute: ```javascript AnchorView = Ember.View.extend({ tagName: 'a', attributeBindings: ['href'], href: 'http://google.com' }); ``` Will result in view instances with an HTML representation of: ```html <a id="ember1" class="ember-view" href="http://google.com"></a> ``` One property can be mapped on to another by placing a ":" between the source property and the destination property: ```javascript AnchorView = Ember.View.extend({ tagName: 'a', attributeBindings: ['url:href'], url: 'http://google.com' }); ``` Will result in view instances with an HTML representation of: ```html <a id="ember1" class="ember-view" href="http://google.com"></a> ``` Namespaced attributes (e.g. `xlink:href`) are supported, but have to be mapped, since `:` is not a valid character for properties in Javascript: ```javascript UseView = Ember.View.extend({ tagName: 'use', attributeBindings: ['xlinkHref:xlink:href'], xlinkHref: '#triangle' }); ``` Will result in view instances with an HTML representation of: ```html <use xlink:href="#triangle"></use> ``` If the return value of an `attributeBindings` monitored property is a boolean the attribute will be present or absent depending on the value: ```javascript MyTextInput = Ember.View.extend({ tagName: 'input', attributeBindings: ['disabled'], disabled: false }); ``` Will result in a view instance with an HTML representation of: ```html <input id="ember1" class="ember-view" /> ``` `attributeBindings` can refer to computed properties: ```javascript MyTextInput = Ember.View.extend({ tagName: 'input', attributeBindings: ['disabled'], disabled: Ember.computed(function() { if (someLogic) { return true; } else { return false; } }) }); ``` To prevent setting an attribute altogether, use `null` or `undefined` as the return value of the `attributeBindings` monitored property: ```javascript MyTextInput = Ember.View.extend({ tagName: 'form', attributeBindings: ['novalidate'], novalidate: null }); ``` Updates to the property of an attribute binding will result in automatic update of the HTML attribute in the view's rendered HTML representation. `attributeBindings` is a concatenated property. See [Ember.Object](/api/classes/Ember.Object.html) documentation for more information about concatenated properties. ## Layouts Views can have a secondary template that wraps their main template. Like primary templates, layouts can be any function that accepts an optional context parameter and returns a string of HTML that will be inserted inside view's tag. Views whose HTML element is self closing (e.g. `<input />`) cannot have a layout and this property will be ignored. Most typically in Ember a layout will be a compiled template. A view's layout can be set directly with the `layout` property or reference an existing template by name with the `layoutName` property. A template used as a layout must contain a single use of the `{{yield}}` helper. The HTML contents of a view's rendered `template` will be inserted at this location: ```javascript AViewWithLayout = Ember.View.extend({ layout: Ember.HTMLBars.compile("<div class='my-decorative-class'>{{yield}}</div>"), template: Ember.HTMLBars.compile("I got wrapped") }); ``` Will result in view instances with an HTML representation of: ```html <div id="ember1" class="ember-view"> <div class="my-decorative-class"> I got wrapped </div> </div> ``` See [Ember.Templates.helpers.yield](/api/classes/Ember.Templates.helpers.html#method_yield) for more information. ## Responding to Browser Events Views can respond to user-initiated events in one of three ways: method implementation, through an event manager, and through `{{action}}` helper use in their template or layout. ### Method Implementation Views can respond to user-initiated events by implementing a method that matches the event name. A `jQuery.Event` object will be passed as the argument to this method. ```javascript AView = Ember.View.extend({ click: function(event) { // will be called when an instance's // rendered element is clicked } }); ``` ### Event Managers Views can define an object as their `eventManager` property. This object can then implement methods that match the desired event names. Matching events that occur on the view's rendered HTML or the rendered HTML of any of its DOM descendants will trigger this method. A `jQuery.Event` object will be passed as the first argument to the method and an `Ember.View` object as the second. The `Ember.View` will be the view whose rendered HTML was interacted with. This may be the view with the `eventManager` property or one of its descendant views. ```javascript AView = Ember.View.extend({ eventManager: Ember.Object.create({ doubleClick: function(event, view) { // will be called when an instance's // rendered element or any rendering // of this view's descendant // elements is clicked } }) }); ``` An event defined for an event manager takes precedence over events of the same name handled through methods on the view. ```javascript AView = Ember.View.extend({ mouseEnter: function(event) { // will never trigger. }, eventManager: Ember.Object.create({ mouseEnter: function(event, view) { // takes precedence over AView#mouseEnter } }) }); ``` Similarly a view's event manager will take precedence for events of any views rendered as a descendant. A method name that matches an event name will not be called if the view instance was rendered inside the HTML representation of a view that has an `eventManager` property defined that handles events of the name. Events not handled by the event manager will still trigger method calls on the descendant. ```javascript var App = Ember.Application.create(); App.OuterView = Ember.View.extend({ template: Ember.HTMLBars.compile("outer {{#view 'inner'}}inner{{/view}} outer"), eventManager: Ember.Object.create({ mouseEnter: function(event, view) { // view might be instance of either // OuterView or InnerView depending on // where on the page the user interaction occurred } }) }); App.InnerView = Ember.View.extend({ click: function(event) { // will be called if rendered inside // an OuterView because OuterView's // eventManager doesn't handle click events }, mouseEnter: function(event) { // will never be called if rendered inside // an OuterView. } }); ``` ### `{{action}}` Helper See [Ember.Templates.helpers.action](/api/classes/Ember.Templates.helpers.html#method_action). ### Event Names All of the event handling approaches described above respond to the same set of events. The names of the built-in events are listed below. (The hash of built-in events exists in `Ember.EventDispatcher`.) Additional, custom events can be registered by using `Ember.Application.customEvents`. Touch events: * `touchStart` * `touchMove` * `touchEnd` * `touchCancel` Keyboard events * `keyDown` * `keyUp` * `keyPress` Mouse events * `mouseDown` * `mouseUp` * `contextMenu` * `click` * `doubleClick` * `mouseMove` * `focusIn` * `focusOut` * `mouseEnter` * `mouseLeave` Form events: * `submit` * `change` * `focusIn` * `focusOut` * `input` HTML5 drag and drop events: * `dragStart` * `drag` * `dragEnter` * `dragLeave` * `dragOver` * `dragEnd` * `drop` @class View @namespace Ember @extends Ember.CoreView @deprecated See http://emberjs.com/deprecations/v1.x/#toc_ember-view @uses Ember.ViewSupport @uses Ember.ViewChildViewsSupport @uses Ember.ClassNamesSupport @uses Ember.AttributeBindingsSupport @uses Ember.InstrumentationSupport @uses Ember.VisibilitySupport @uses Ember.AriaRoleSupport @public */ // jscs:disable validateIndentation var View = _emberViewsViewsCore_view.default.extend(_emberViewsMixinsChild_views_support.default, _emberViewsMixinsView_state_support.default, _emberViewsMixinsClass_names_support.default, _emberViewsMixinsInstrumentation_support.default, _emberViewsMixinsVisibility_support.default, _emberViewsCompatAttrsProxy.default, _emberViewsMixinsAria_role_support.default, _emberViewsMixinsView_support.default); // jscs:enable validateIndentation /* Describe how the specified actions should behave in the various states that a view can exist in. Possible states: * preRender: when a view is first instantiated, and after its element was destroyed, it is in the preRender state * inBuffer: once a view has been rendered, but before it has been inserted into the DOM, it is in the inBuffer state * hasElement: the DOM representation of the view is created, and is ready to be inserted * inDOM: once a view has been inserted into the DOM it is in the inDOM state. A view spends the vast majority of its existence in this state. * destroyed: once a view has been destroyed (using the destroy method), it is in this state. No further actions can be invoked on a destroyed view. */ // in the destroyed state, everything is illegal // before rendering has begun, all legal manipulations are noops. // inside the buffer, legal manipulations are done on the buffer // once the view has been inserted into the DOM, legal manipulations // are done on the DOM element. exports.default = View; exports.ViewChildViewsSupport = _emberViewsMixinsChild_views_support.default; exports.ViewStateSupport = _emberViewsMixinsView_state_support.default; exports.ClassNamesSupport = _emberViewsMixinsClass_names_support.default; }); // for the side effect of extending Ember.run.queues enifed("ember/features", ["exports"], function (exports) { "use strict"; exports.default = {}; }); enifed('ember/index', ['exports', 'require', 'ember-metal', 'ember-runtime', 'ember-views', 'ember-routing', 'ember-application', 'ember-extension-support', 'ember-templates', 'ember-runtime/system/lazy_load'], function (exports, _require, _emberMetal, _emberRuntime, _emberViews, _emberRouting, _emberApplication, _emberExtensionSupport, _emberTemplates, _emberRuntimeSystemLazy_load) { // require the main entry points for each of these packages // this is so that the global exports occur properly 'use strict'; if (_require.has('ember-htmlbars')) { _require.default('ember-htmlbars'); } if (_require.has('ember-glimmer')) { _require.default('ember-glimmer'); } if (_require.has('ember-template-compiler')) { _require.default('ember-template-compiler'); } // do this to ensure that Ember.Test is defined properly on the global // if it is present. if (_require.has('ember-testing')) { _require.default('ember-testing'); } _emberRuntimeSystemLazy_load.runLoadHooks('Ember'); /** @module ember */ }); enifed("ember/version", ["exports"], function (exports) { "use strict"; exports.default = "2.8.0"; }); enifed('htmlbars-runtime', ['exports', 'htmlbars-runtime/hooks', 'htmlbars-runtime/render', 'htmlbars-util/morph-utils', 'htmlbars-util/template-utils'], function (exports, _htmlbarsRuntimeHooks, _htmlbarsRuntimeRender, _htmlbarsUtilMorphUtils, _htmlbarsUtilTemplateUtils) { 'use strict'; var internal = { blockFor: _htmlbarsUtilTemplateUtils.blockFor, manualElement: _htmlbarsRuntimeRender.manualElement, hostBlock: _htmlbarsRuntimeHooks.hostBlock, continueBlock: _htmlbarsRuntimeHooks.continueBlock, hostYieldWithShadowTemplate: _htmlbarsRuntimeHooks.hostYieldWithShadowTemplate, visitChildren: _htmlbarsUtilMorphUtils.visitChildren, validateChildMorphs: _htmlbarsUtilMorphUtils.validateChildMorphs, clearMorph: _htmlbarsUtilTemplateUtils.clearMorph }; exports.hooks = _htmlbarsRuntimeHooks.default; exports.render = _htmlbarsRuntimeRender.default; exports.internal = internal; }); enifed('htmlbars-runtime/expression-visitor', ['exports'], function (exports) { /** # Expression Nodes: These nodes are not directly responsible for any part of the DOM, but are eventually passed to a Statement Node. * get * subexpr * concat */ 'use strict'; exports.acceptParams = acceptParams; exports.acceptHash = acceptHash; function acceptParams(nodes, env, scope) { var array = []; for (var i = 0, l = nodes.length; i < l; i++) { array.push(acceptExpression(nodes[i], env, scope).value); } return array; } function acceptHash(pairs, env, scope) { var object = {}; for (var i = 0, l = pairs.length; i < l; i += 2) { var key = pairs[i]; var value = pairs[i + 1]; object[key] = acceptExpression(value, env, scope).value; } return object; } function acceptExpression(node, env, scope) { var ret = { value: null }; // Primitive literals are unambiguously non-array representations of // themselves. if (Array.isArray(node)) { // if (node.length !== 7) { throw new Error('FIXME: Invalid statement length!'); } ret.value = evaluateNode(node, env, scope); } else { ret.value = node; } return ret; } function evaluateNode(node, env, scope) { switch (node[0]) { // can be used by manualElement case 'value': return node[1]; case 'get': return evaluateGet(node, env, scope); case 'subexpr': return evaluateSubexpr(node, env, scope); case 'concat': return evaluateConcat(node, env, scope); } } function evaluateGet(node, env, scope) { var path = node[1]; return env.hooks.get(env, scope, path); } function evaluateSubexpr(node, env, scope) { var path = node[1]; var rawParams = node[2]; var rawHash = node[3]; var params = acceptParams(rawParams, env, scope); var hash = acceptHash(rawHash, env, scope); return env.hooks.subexpr(env, scope, path, params, hash); } function evaluateConcat(node, env, scope) { var rawParts = node[1]; var parts = acceptParams(rawParts, env, scope); return env.hooks.concat(env, parts); } }); enifed("htmlbars-runtime/hooks", ["exports", "htmlbars-runtime/render", "morph-range/morph-list", "htmlbars-util/object-utils", "htmlbars-util/morph-utils", "htmlbars-util/template-utils"], function (exports, _htmlbarsRuntimeRender, _morphRangeMorphList, _htmlbarsUtilObjectUtils, _htmlbarsUtilMorphUtils, _htmlbarsUtilTemplateUtils) { "use strict"; exports.wrap = wrap; exports.wrapForHelper = wrapForHelper; exports.createScope = createScope; exports.createFreshScope = createFreshScope; exports.bindShadowScope = bindShadowScope; exports.createChildScope = createChildScope; exports.bindSelf = bindSelf; exports.updateSelf = updateSelf; exports.bindLocal = bindLocal; exports.updateLocal = updateLocal; exports.bindBlock = bindBlock; exports.block = block; exports.continueBlock = continueBlock; exports.hostBlock = hostBlock; exports.handleRedirect = handleRedirect; exports.handleKeyword = handleKeyword; exports.linkRenderNode = linkRenderNode; exports.inline = inline; exports.keyword = keyword; exports.invokeHelper = invokeHelper; exports.classify = classify; exports.partial = partial; exports.range = range; exports.element = element; exports.attribute = attribute; exports.subexpr = subexpr; exports.get = get; exports.getRoot = getRoot; exports.getBlock = getBlock; exports.getChild = getChild; exports.getValue = getValue; exports.getCellOrValue = getCellOrValue; exports.component = component; exports.concat = concat; exports.hasHelper = hasHelper; exports.lookupHelper = lookupHelper; exports.bindScope = bindScope; exports.updateScope = updateScope; /** HTMLBars delegates the runtime behavior of a template to hooks provided by the host environment. These hooks explain the lexical environment of a Handlebars template, the internal representation of references, and the interaction between an HTMLBars template and the DOM it is managing. While HTMLBars host hooks have access to all of this internal machinery, templates and helpers have access to the abstraction provided by the host hooks. ## The Lexical Environment The default lexical environment of an HTMLBars template includes: * Any local variables, provided by *block arguments* * The current value of `self` ## Simple Nesting Let's look at a simple template with a nested block: ```hbs <h1>{{title}}</h1> {{#if author}} <p class="byline">{{author}}</p> {{/if}} ``` In this case, the lexical environment at the top-level of the template does not change inside of the `if` block. This is achieved via an implementation of `if` that looks like this: ```js registerHelper('if', function(params) { if (!!params[0]) { return this.yield(); } }); ``` A call to `this.yield` invokes the child template using the current lexical environment. ## Block Arguments It is possible for nested blocks to introduce new local variables: ```hbs {{#count-calls as |i|}} <h1>{{title}}</h1> <p>Called {{i}} times</p> {{/count}} ``` In this example, the child block inherits its surrounding lexical environment, but augments it with a single new variable binding. The implementation of `count-calls` supplies the value of `i`, but does not otherwise alter the environment: ```js var count = 0; registerHelper('count-calls', function() { return this.yield([ ++count ]); }); ``` */ function wrap(template) { if (template === null) { return null; } return { meta: template.meta, arity: template.arity, raw: template, render: function (self, env, options, blockArguments) { var scope = env.hooks.createFreshScope(); var contextualElement = options && options.contextualElement; var renderOptions = new _htmlbarsRuntimeRender.RenderOptions(null, self, blockArguments, contextualElement); return _htmlbarsRuntimeRender.default(template, env, scope, renderOptions); } }; } function wrapForHelper(template, env, scope, morph, renderState, visitor) { if (!template) { return {}; } var yieldArgs = yieldTemplate(template, env, scope, morph, renderState, visitor); return { meta: template.meta, arity: template.arity, 'yield': yieldArgs, // quoted since it's a reserved word, see issue #420 yieldItem: yieldItem(template, env, scope, morph, renderState, visitor), raw: template, render: function (self, blockArguments) { yieldArgs(blockArguments, self); } }; } // Called by a user-land helper to render a template. function yieldTemplate(template, env, parentScope, morph, renderState, visitor) { return function (blockArguments, self) { // Render state is used to track the progress of the helper (since it // may call into us multiple times). As the user-land helper calls // into library code, we track what needs to be cleaned up after the // helper has returned. // // Here, we remember that a template has been yielded and so we do not // need to remove the previous template. (If no template is yielded // this render by the helper, we assume nothing should be shown and // remove any previous rendered templates.) renderState.morphToClear = null; // In this conditional is true, it means that on the previous rendering pass // the helper yielded multiple items via `yieldItem()`, but this time they // are yielding a single template. In that case, we mark the morph list for // cleanup so it is removed from the DOM. if (morph.morphList) { _htmlbarsUtilTemplateUtils.clearMorphList(morph.morphList, morph, env); renderState.morphListToClear = null; } var scope = parentScope; if (morph.lastYielded && isStableTemplate(template, morph.lastYielded)) { return morph.lastResult.revalidateWith(env, undefined, self, blockArguments, visitor); } // Check to make sure that we actually **need** a new scope, and can't // share the parent scope. Note that we need to move this check into // a host hook, because the host's notion of scope may require a new // scope in more cases than the ones we can determine statically. if (self !== undefined || parentScope === null || template.arity) { scope = env.hooks.createChildScope(parentScope); } morph.lastYielded = { self: self, template: template, shadowTemplate: null }; // Render the template that was selected by the helper var renderOptions = new _htmlbarsRuntimeRender.RenderOptions(morph, self, blockArguments); _htmlbarsRuntimeRender.default(template, env, scope, renderOptions); }; } function yieldItem(template, env, parentScope, morph, renderState, visitor) { // Initialize state that tracks multiple items being // yielded in. var currentMorph = null; // Candidate morphs for deletion. var candidates = {}; // Reuse existing MorphList if this is not a first-time // render. var morphList = morph.morphList; if (morphList) { currentMorph = morphList.firstChildMorph; } // Advances the currentMorph pointer to the morph in the previously-rendered // list that matches the yielded key. While doing so, it marks any morphs // that it advances past as candidates for deletion. Assuming those morphs // are not yielded in later, they will be removed in the prune step during // cleanup. // Note that this helper function assumes that the morph being seeked to is // guaranteed to exist in the previous MorphList; if this is called and the // morph does not exist, it will result in an infinite loop function advanceToKey(key) { var seek = currentMorph; while (seek.key !== key) { candidates[seek.key] = seek; seek = seek.nextMorph; } currentMorph = seek.nextMorph; return seek; } return function (_key, blockArguments, self) { if (typeof _key !== 'string') { throw new Error("You must provide a string key when calling `yieldItem`; you provided " + _key); } // At least one item has been yielded, so we do not wholesale // clear the last MorphList but instead apply a prune operation. renderState.morphListToClear = null; morph.lastYielded = null; var morphList, morphMap; if (!morph.morphList) { morph.morphList = new _morphRangeMorphList.default(); morph.morphMap = {}; morph.setMorphList(morph.morphList); } morphList = morph.morphList; morphMap = morph.morphMap; // A map of morphs that have been yielded in on this // rendering pass. Any morphs that do not make it into // this list will be pruned from the MorphList during the cleanup // process. var handledMorphs = renderState.handledMorphs; var key = undefined; if (_key in handledMorphs) { // In this branch we are dealing with a duplicate key. The strategy // is to take the original key and append a counter to it that is // incremented every time the key is reused. In order to greatly // reduce the chance of colliding with another valid key we also add // an extra string "--z8mS2hvDW0A--" to the new key. var collisions = renderState.collisions; if (collisions === undefined) { collisions = renderState.collisions = {}; } var count = collisions[_key] | 0; collisions[_key] = ++count; key = _key + '--z8mS2hvDW0A--' + count; } else { key = _key; } if (currentMorph && currentMorph.key === key) { yieldTemplate(template, env, parentScope, currentMorph, renderState, visitor)(blockArguments, self); currentMorph = currentMorph.nextMorph; handledMorphs[key] = currentMorph; } else if (morphMap[key] !== undefined) { var foundMorph = morphMap[key]; if (key in candidates) { // If we already saw this morph, move it forward to this position morphList.insertBeforeMorph(foundMorph, currentMorph); } else { // Otherwise, move the pointer forward to the existing morph for this key advanceToKey(key); } handledMorphs[foundMorph.key] = foundMorph; yieldTemplate(template, env, parentScope, foundMorph, renderState, visitor)(blockArguments, self); } else { var childMorph = _htmlbarsRuntimeRender.createChildMorph(env.dom, morph); childMorph.key = key; morphMap[key] = handledMorphs[key] = childMorph; morphList.insertBeforeMorph(childMorph, currentMorph); yieldTemplate(template, env, parentScope, childMorph, renderState, visitor)(blockArguments, self); } renderState.morphListToPrune = morphList; morph.childNodes = null; }; } function isStableTemplate(template, lastYielded) { return !lastYielded.shadowTemplate && template === lastYielded.template; } function optionsFor(template, inverse, env, scope, morph, visitor) { // If there was a template yielded last time, set morphToClear so it will be cleared // if no template is yielded on this render. var morphToClear = morph.lastResult ? morph : null; var renderState = new _htmlbarsUtilTemplateUtils.RenderState(morphToClear, morph.morphList || null); return { templates: { template: wrapForHelper(template, env, scope, morph, renderState, visitor), inverse: wrapForHelper(inverse, env, scope, morph, renderState, visitor) }, renderState: renderState }; } function thisFor(options) { return { arity: options.template.arity, 'yield': options.template.yield, // quoted since it's a reserved word, see issue #420 yieldItem: options.template.yieldItem, yieldIn: options.template.yieldIn }; } /** Host Hook: createScope @param {Scope?} parentScope @return Scope Corresponds to entering a new HTMLBars block. This hook is invoked when a block is entered with a new `self` or additional local variables. When invoked for a top-level template, the `parentScope` is `null`, and this hook should return a fresh Scope. When invoked for a child template, the `parentScope` is the scope for the parent environment. Note that the `Scope` is an opaque value that is passed to other host hooks. For example, the `get` hook uses the scope to retrieve a value for a given scope and variable name. */ function createScope(env, parentScope) { if (parentScope) { return env.hooks.createChildScope(parentScope); } else { return env.hooks.createFreshScope(); } } function createFreshScope() { // because `in` checks have unpredictable performance, keep a // separate dictionary to track whether a local was bound. // See `bindLocal` for more information. return { self: null, blocks: {}, locals: {}, localPresent: {} }; } /** Host Hook: bindShadowScope @param {Scope?} parentScope @return Scope Corresponds to rendering a new template into an existing render tree, but with a new top-level lexical scope. This template is called the "shadow root". If a shadow template invokes `{{yield}}`, it will render the block provided to the shadow root in the original lexical scope. ```hbs {{!-- post template --}} <p>{{props.title}}</p> {{yield}} {{!-- blog template --}} {{#post title="Hello world"}} <p>by {{byline}}</p> <article>This is my first post</article> {{/post}} {{#post title="Goodbye world"}} <p>by {{byline}}</p> <article>This is my last post</article> {{/post}} ``` ```js helpers.post = function(params, hash, options) { options.template.yieldIn(postTemplate, { props: hash }); }; blog.render({ byline: "Yehuda Katz" }); ``` Produces: ```html <p>Hello world</p> <p>by Yehuda Katz</p> <article>This is my first post</article> <p>Goodbye world</p> <p>by Yehuda Katz</p> <article>This is my last post</article> ``` In short, `yieldIn` creates a new top-level scope for the provided template and renders it, making the original block available to `{{yield}}` in that template. */ function bindShadowScope(env /*, parentScope, shadowScope */) { return env.hooks.createFreshScope(); } function createChildScope(parent) { var scope = Object.create(parent); scope.locals = Object.create(parent.locals); scope.localPresent = Object.create(parent.localPresent); scope.blocks = Object.create(parent.blocks); return scope; } /** Host Hook: bindSelf @param {Scope} scope @param {any} self Corresponds to entering a template. This hook is invoked when the `self` value for a scope is ready to be bound. The host must ensure that child scopes reflect the change to the `self` in future calls to the `get` hook. */ function bindSelf(env, scope, self) { scope.self = self; } function updateSelf(env, scope, self) { env.hooks.bindSelf(env, scope, self); } /** Host Hook: bindLocal @param {Environment} env @param {Scope} scope @param {String} name @param {any} value Corresponds to entering a template with block arguments. This hook is invoked when a local variable for a scope has been provided. The host must ensure that child scopes reflect the change in future calls to the `get` hook. */ function bindLocal(env, scope, name, value) { scope.localPresent[name] = true; scope.locals[name] = value; } function updateLocal(env, scope, name, value) { env.hooks.bindLocal(env, scope, name, value); } /** Host Hook: bindBlock @param {Environment} env @param {Scope} scope @param {Function} block Corresponds to entering a shadow template that was invoked by a block helper with `yieldIn`. This hook is invoked with an opaque block that will be passed along to the shadow template, and inserted into the shadow template when `{{yield}}` is used. Optionally provide a non-default block name that can be targeted by `{{yield to=blockName}}`. */ function bindBlock(env, scope, block) { var name = arguments.length <= 3 || arguments[3] === undefined ? 'default' : arguments[3]; scope.blocks[name] = block; } /** Host Hook: block @param {RenderNode} renderNode @param {Environment} env @param {Scope} scope @param {String} path @param {Array} params @param {Object} hash @param {Block} block @param {Block} elseBlock Corresponds to: ```hbs {{#helper param1 param2 key1=val1 key2=val2}} {{!-- child template --}} {{/helper}} ``` This host hook is a workhorse of the system. It is invoked whenever a block is encountered, and is responsible for resolving the helper to call, and then invoke it. The helper should be invoked with: - `{Array} params`: the parameters passed to the helper in the template. - `{Object} hash`: an object containing the keys and values passed in the hash position in the template. The values in `params` and `hash` will already be resolved through a previous call to the `get` host hook. The helper should be invoked with a `this` value that is an object with one field: `{Function} yield`: when invoked, this function executes the block with the current scope. It takes an optional array of block parameters. If block parameters are supplied, HTMLBars will invoke the `bindLocal` host hook to bind the supplied values to the block arguments provided by the template. In general, the default implementation of `block` should work for most host environments. It delegates to other host hooks where appropriate, and properly invokes the helper with the appropriate arguments. */ function block(morph, env, scope, path, params, hash, template, inverse, visitor) { if (handleRedirect(morph, env, scope, path, params, hash, template, inverse, visitor)) { return; } continueBlock(morph, env, scope, path, params, hash, template, inverse, visitor); } function continueBlock(morph, env, scope, path, params, hash, template, inverse, visitor) { hostBlock(morph, env, scope, template, inverse, null, visitor, function (options) { var helper = env.hooks.lookupHelper(env, scope, path); return env.hooks.invokeHelper(morph, env, scope, visitor, params, hash, helper, options.templates, thisFor(options.templates)); }); } function hostBlock(morph, env, scope, template, inverse, shadowOptions, visitor, callback) { var options = optionsFor(template, inverse, env, scope, morph, visitor); _htmlbarsUtilTemplateUtils.renderAndCleanup(morph, env, options, shadowOptions, callback); } function handleRedirect(morph, env, scope, path, params, hash, template, inverse, visitor) { if (!path) { return false; } var redirect = env.hooks.classify(env, scope, path); if (redirect) { switch (redirect) { case 'component': env.hooks.component(morph, env, scope, path, params, hash, { default: template, inverse: inverse }, visitor);break; case 'inline': env.hooks.inline(morph, env, scope, path, params, hash, visitor);break; case 'block': env.hooks.block(morph, env, scope, path, params, hash, template, inverse, visitor);break; default: throw new Error("Internal HTMLBars redirection to " + redirect + " not supported"); } return true; } if (handleKeyword(path, morph, env, scope, params, hash, template, inverse, visitor)) { return true; } return false; } function handleKeyword(path, morph, env, scope, params, hash, template, inverse, visitor) { var keyword = env.hooks.keywords[path]; if (!keyword) { return false; } if (typeof keyword === 'function') { return keyword(morph, env, scope, params, hash, template, inverse, visitor); } if (keyword.willRender) { keyword.willRender(morph, env); } var lastState, newState; if (keyword.setupState) { lastState = _htmlbarsUtilObjectUtils.shallowCopy(morph.getState()); newState = morph.setState(keyword.setupState(lastState, env, scope, params, hash)); } if (keyword.childEnv) { // Build the child environment... env = keyword.childEnv(morph.getState(), env); // ..then save off the child env builder on the render node. If the render // node tree is re-rendered and this node is not dirty, the child env // builder will still be invoked so that child dirty render nodes still get // the correct child env. morph.buildChildEnv = keyword.childEnv; } var firstTime = !morph.rendered; if (keyword.isEmpty) { var isEmpty = keyword.isEmpty(morph.getState(), env, scope, params, hash); if (isEmpty) { if (!firstTime) { _htmlbarsUtilTemplateUtils.clearMorph(morph, env, false); } return true; } } if (firstTime) { if (keyword.render) { keyword.render(morph, env, scope, params, hash, template, inverse, visitor); } morph.rendered = true; return true; } var isStable; if (keyword.isStable) { isStable = keyword.isStable(lastState, newState); } else { isStable = stableState(lastState, newState); } if (isStable) { if (keyword.rerender) { var newEnv = keyword.rerender(morph, env, scope, params, hash, template, inverse, visitor); env = newEnv || env; } _htmlbarsUtilMorphUtils.validateChildMorphs(env, morph, visitor); return true; } else { _htmlbarsUtilTemplateUtils.clearMorph(morph, env, false); } // If the node is unstable, re-render from scratch if (keyword.render) { keyword.render(morph, env, scope, params, hash, template, inverse, visitor); morph.rendered = true; return true; } } function stableState(oldState, newState) { if (_htmlbarsUtilObjectUtils.keyLength(oldState) !== _htmlbarsUtilObjectUtils.keyLength(newState)) { return false; } for (var prop in oldState) { if (oldState[prop] !== newState[prop]) { return false; } } return true; } function linkRenderNode() /* morph, env, scope, params, hash */{ return; } /** Host Hook: inline @param {RenderNode} renderNode @param {Environment} env @param {Scope} scope @param {String} path @param {Array} params @param {Hash} hash Corresponds to: ```hbs {{helper param1 param2 key1=val1 key2=val2}} ``` This host hook is similar to the `block` host hook, but it invokes helpers that do not supply an attached block. Like the `block` hook, the helper should be invoked with: - `{Array} params`: the parameters passed to the helper in the template. - `{Object} hash`: an object containing the keys and values passed in the hash position in the template. The values in `params` and `hash` will already be resolved through a previous call to the `get` host hook. In general, the default implementation of `inline` should work for most host environments. It delegates to other host hooks where appropriate, and properly invokes the helper with the appropriate arguments. The default implementation of `inline` also makes `partial` a keyword. Instead of invoking a helper named `partial`, it invokes the `partial` host hook. */ function inline(morph, env, scope, path, params, hash, visitor) { if (handleRedirect(morph, env, scope, path, params, hash, null, null, visitor)) { return; } var value = undefined, hasValue = undefined; if (morph.linkedResult) { value = env.hooks.getValue(morph.linkedResult); hasValue = true; } else { var options = optionsFor(null, null, env, scope, morph); var helper = env.hooks.lookupHelper(env, scope, path); var result = env.hooks.invokeHelper(morph, env, scope, visitor, params, hash, helper, options.templates, thisFor(options.templates)); if (result && result.link) { morph.linkedResult = result.value; _htmlbarsUtilMorphUtils.linkParams(env, scope, morph, '@content-helper', [morph.linkedResult], null); } if (result && 'value' in result) { value = env.hooks.getValue(result.value); hasValue = true; } } if (hasValue) { if (morph.lastValue !== value) { morph.setContent(value); } morph.lastValue = value; } } function keyword(path, morph, env, scope, params, hash, template, inverse, visitor) { handleKeyword(path, morph, env, scope, params, hash, template, inverse, visitor); } function invokeHelper(morph, env, scope, visitor, _params, _hash, helper, templates, context) { var params = normalizeArray(env, _params); var hash = normalizeObject(env, _hash); return { value: helper.call(context, params, hash, templates) }; } function normalizeArray(env, array) { var out = new Array(array.length); for (var i = 0, l = array.length; i < l; i++) { out[i] = env.hooks.getCellOrValue(array[i]); } return out; } function normalizeObject(env, object) { var out = {}; for (var prop in object) { out[prop] = env.hooks.getCellOrValue(object[prop]); } return out; } function classify() /* env, scope, path */{ return null; } var keywords = { partial: function (morph, env, scope, params) { var value = env.hooks.partial(morph, env, scope, params[0]); morph.setContent(value); return true; }, // quoted since it's a reserved word, see issue #420 'yield': function (morph, env, scope, params, hash, template, inverse, visitor) { // the current scope is provided purely for the creation of shadow // scopes; it should not be provided to user code. var to = env.hooks.getValue(hash.to) || 'default'; var block = env.hooks.getBlock(scope, to); if (block) { block.invoke(env, params, hash.self, morph, scope, visitor); } return true; }, hasBlock: function (morph, env, scope, params) { var name = env.hooks.getValue(params[0]) || 'default'; return !!env.hooks.getBlock(scope, name); }, hasBlockParams: function (morph, env, scope, params) { var name = env.hooks.getValue(params[0]) || 'default'; var block = env.hooks.getBlock(scope, name); return !!(block && block.arity); } }; exports.keywords = keywords; /** Host Hook: partial @param {RenderNode} renderNode @param {Environment} env @param {Scope} scope @param {String} path Corresponds to: ```hbs {{partial "location"}} ``` This host hook is invoked by the default implementation of the `inline` hook. This makes `partial` a keyword in an HTMLBars environment using the default `inline` host hook. It is implemented as a host hook so that it can retrieve the named partial out of the `Environment`. Helpers, in contrast, only have access to the values passed in to them, and not to the ambient lexical environment. The host hook should invoke the referenced partial with the ambient `self`. */ function partial(renderNode, env, scope, path) { var template = env.partials[path]; return template.render(scope.self, env, {}).fragment; } /** Host hook: range @param {RenderNode} renderNode @param {Environment} env @param {Scope} scope @param {any} value Corresponds to: ```hbs {{content}} {{{unescaped}}} ``` This hook is responsible for updating a render node that represents a range of content with a value. */ function range(morph, env, scope, path, value, visitor) { if (handleRedirect(morph, env, scope, path, [], {}, null, null, visitor)) { return; } value = env.hooks.getValue(value); if (morph.lastValue !== value) { morph.setContent(value); } morph.lastValue = value; } /** Host hook: element @param {RenderNode} renderNode @param {Environment} env @param {Scope} scope @param {String} path @param {Array} params @param {Hash} hash Corresponds to: ```hbs <div {{bind-attr foo=bar}}></div> ``` This hook is responsible for invoking a helper that modifies an element. Its purpose is largely legacy support for awkward idioms that became common when using the string-based Handlebars engine. Most of the uses of the `element` hook are expected to be superseded by component syntax and the `attribute` hook. */ function element(morph, env, scope, path, params, hash, visitor) { if (handleRedirect(morph, env, scope, path, params, hash, null, null, visitor)) { return; } var helper = env.hooks.lookupHelper(env, scope, path); if (helper) { env.hooks.invokeHelper(null, env, scope, null, params, hash, helper, { element: morph.element }); } } /** Host hook: attribute @param {RenderNode} renderNode @param {Environment} env @param {String} name @param {any} value Corresponds to: ```hbs <div foo={{bar}}></div> ``` This hook is responsible for updating a render node that represents an element's attribute with a value. It receives the name of the attribute as well as an already-resolved value, and should update the render node with the value if appropriate. */ function attribute(morph, env, scope, name, value) { value = env.hooks.getValue(value); if (morph.lastValue !== value) { morph.setContent(value); } morph.lastValue = value; } function subexpr(env, scope, helperName, params, hash) { var helper = env.hooks.lookupHelper(env, scope, helperName); var result = env.hooks.invokeHelper(null, env, scope, null, params, hash, helper, {}); if (result && 'value' in result) { return env.hooks.getValue(result.value); } } /** Host Hook: get @param {Environment} env @param {Scope} scope @param {String} path Corresponds to: ```hbs {{foo.bar}} ^ {{helper foo.bar key=value}} ^ ^ ``` This hook is the "leaf" hook of the system. It is used to resolve a path relative to the current scope. */ function get(env, scope, path) { if (path === '') { return scope.self; } var keys = path.split('.'); var value = env.hooks.getRoot(scope, keys[0])[0]; for (var i = 1; i < keys.length; i++) { if (value) { value = env.hooks.getChild(value, keys[i]); } else { break; } } return value; } function getRoot(scope, key) { if (scope.localPresent[key]) { return [scope.locals[key]]; } else if (scope.self) { return [scope.self[key]]; } else { return [undefined]; } } function getBlock(scope, key) { return scope.blocks[key]; } function getChild(value, key) { return value[key]; } function getValue(reference) { return reference; } function getCellOrValue(reference) { return reference; } function component(morph, env, scope, tagName, params, attrs, templates, visitor) { if (env.hooks.hasHelper(env, scope, tagName)) { return env.hooks.block(morph, env, scope, tagName, params, attrs, templates.default, templates.inverse, visitor); } componentFallback(morph, env, scope, tagName, attrs, templates.default); } function concat(env, params) { var value = ""; for (var i = 0, l = params.length; i < l; i++) { value += env.hooks.getValue(params[i]); } return value; } function componentFallback(morph, env, scope, tagName, attrs, template) { var element = env.dom.createElement(tagName); for (var name in attrs) { element.setAttribute(name, env.hooks.getValue(attrs[name])); } var fragment = _htmlbarsRuntimeRender.default(template, env, scope, {}).fragment; element.appendChild(fragment); morph.setNode(element); } function hasHelper(env, scope, helperName) { return env.helpers[helperName] !== undefined; } function lookupHelper(env, scope, helperName) { return env.helpers[helperName]; } function bindScope() /* env, scope */{ // this function is used to handle host-specified extensions to scope // other than `self`, `locals` and `block`. } function updateScope(env, scope) { env.hooks.bindScope(env, scope); } exports.default = { // fundamental hooks that you will likely want to override bindLocal: bindLocal, bindSelf: bindSelf, bindScope: bindScope, classify: classify, component: component, concat: concat, createFreshScope: createFreshScope, getChild: getChild, getRoot: getRoot, getBlock: getBlock, getValue: getValue, getCellOrValue: getCellOrValue, keywords: keywords, linkRenderNode: linkRenderNode, partial: partial, subexpr: subexpr, // fundamental hooks with good default behavior bindBlock: bindBlock, bindShadowScope: bindShadowScope, updateLocal: updateLocal, updateSelf: updateSelf, updateScope: updateScope, createChildScope: createChildScope, hasHelper: hasHelper, lookupHelper: lookupHelper, invokeHelper: invokeHelper, cleanupRenderNode: null, destroyRenderNode: null, willCleanupTree: null, didCleanupTree: null, willRenderNode: null, didRenderNode: null, // derived hooks attribute: attribute, block: block, createScope: createScope, element: element, get: get, inline: inline, range: range, keyword: keyword }; }); enifed("htmlbars-runtime/morph", ["exports", "morph-range"], function (exports, _morphRange) { "use strict"; var guid = 1; function HTMLBarsMorph(domHelper, contextualElement) { this.super$constructor(domHelper, contextualElement); this._state = undefined; this.ownerNode = null; this.isDirty = false; this.isSubtreeDirty = false; this.lastYielded = null; this.lastResult = null; this.lastValue = null; this.buildChildEnv = null; this.morphList = null; this.morphMap = null; this.key = null; this.linkedParams = null; this.linkedResult = null; this.childNodes = null; this.rendered = false; this.guid = "range" + guid++; this.seen = false; } HTMLBarsMorph.empty = function (domHelper, contextualElement) { var morph = new HTMLBarsMorph(domHelper, contextualElement); morph.clear(); return morph; }; HTMLBarsMorph.create = function (domHelper, contextualElement, node) { var morph = new HTMLBarsMorph(domHelper, contextualElement); morph.setNode(node); return morph; }; HTMLBarsMorph.attach = function (domHelper, contextualElement, firstNode, lastNode) { var morph = new HTMLBarsMorph(domHelper, contextualElement); morph.setRange(firstNode, lastNode); return morph; }; var prototype = HTMLBarsMorph.prototype = Object.create(_morphRange.default.prototype); prototype.constructor = HTMLBarsMorph; prototype.super$constructor = _morphRange.default; prototype.getState = function () { if (!this._state) { this._state = {}; } return this._state; }; prototype.setState = function (newState) { /*jshint -W093 */ return this._state = newState; }; exports.default = HTMLBarsMorph; }); enifed("htmlbars-runtime/node-visitor", ["exports", "htmlbars-util/morph-utils", "htmlbars-runtime/expression-visitor"], function (exports, _htmlbarsUtilMorphUtils, _htmlbarsRuntimeExpressionVisitor) { "use strict"; /** Node classification: # Primary Statement Nodes: These nodes are responsible for a render node that represents a morph-range. * block * inline * content * element * component # Leaf Statement Nodes: This node is responsible for a render node that represents a morph-attr. * attribute */ function linkParamsAndHash(env, scope, morph, path, params, hash) { if (morph.linkedParams) { params = morph.linkedParams.params; hash = morph.linkedParams.hash; } else { params = params && _htmlbarsRuntimeExpressionVisitor.acceptParams(params, env, scope); hash = hash && _htmlbarsRuntimeExpressionVisitor.acceptHash(hash, env, scope); } _htmlbarsUtilMorphUtils.linkParams(env, scope, morph, path, params, hash); return [params, hash]; } var AlwaysDirtyVisitor = { block: function (node, morph, env, scope, template, visitor) { var path = node[1]; var params = node[2]; var hash = node[3]; var templateId = node[4]; var inverseId = node[5]; var paramsAndHash = linkParamsAndHash(env, scope, morph, path, params, hash); morph.isDirty = morph.isSubtreeDirty = false; env.hooks.block(morph, env, scope, path, paramsAndHash[0], paramsAndHash[1], templateId === null ? null : template.templates[templateId], inverseId === null ? null : template.templates[inverseId], visitor); }, inline: function (node, morph, env, scope, visitor) { var path = node[1]; var params = node[2]; var hash = node[3]; var paramsAndHash = linkParamsAndHash(env, scope, morph, path, params, hash); morph.isDirty = morph.isSubtreeDirty = false; env.hooks.inline(morph, env, scope, path, paramsAndHash[0], paramsAndHash[1], visitor); }, content: function (node, morph, env, scope, visitor) { var path = node[1]; morph.isDirty = morph.isSubtreeDirty = false; if (isHelper(env, scope, path)) { env.hooks.inline(morph, env, scope, path, [], {}, visitor); if (morph.linkedResult) { _htmlbarsUtilMorphUtils.linkParams(env, scope, morph, '@content-helper', [morph.linkedResult], null); } return; } var params = undefined; if (morph.linkedParams) { params = morph.linkedParams.params; } else { params = [env.hooks.get(env, scope, path)]; } _htmlbarsUtilMorphUtils.linkParams(env, scope, morph, '@range', params, null); env.hooks.range(morph, env, scope, path, params[0], visitor); }, element: function (node, morph, env, scope, visitor) { var path = node[1]; var params = node[2]; var hash = node[3]; var paramsAndHash = linkParamsAndHash(env, scope, morph, path, params, hash); morph.isDirty = morph.isSubtreeDirty = false; env.hooks.element(morph, env, scope, path, paramsAndHash[0], paramsAndHash[1], visitor); }, attribute: function (node, morph, env, scope) { var name = node[1]; var value = node[2]; var paramsAndHash = linkParamsAndHash(env, scope, morph, '@attribute', [value], null); morph.isDirty = morph.isSubtreeDirty = false; env.hooks.attribute(morph, env, scope, name, paramsAndHash[0][0]); }, component: function (node, morph, env, scope, template, visitor) { var path = node[1]; var attrs = node[2]; var templateId = node[3]; var inverseId = node[4]; var paramsAndHash = linkParamsAndHash(env, scope, morph, path, [], attrs); var templates = { default: template.templates[templateId], inverse: template.templates[inverseId] }; morph.isDirty = morph.isSubtreeDirty = false; env.hooks.component(morph, env, scope, path, paramsAndHash[0], paramsAndHash[1], templates, visitor); }, attributes: function (node, morph, env, scope, parentMorph, visitor) { var template = node[1]; env.hooks.attributes(morph, env, scope, template, parentMorph, visitor); } }; exports.AlwaysDirtyVisitor = AlwaysDirtyVisitor; exports.default = { block: function (node, morph, env, scope, template, visitor) { dirtyCheck(env, morph, visitor, function (visitor) { AlwaysDirtyVisitor.block(node, morph, env, scope, template, visitor); }); }, inline: function (node, morph, env, scope, visitor) { dirtyCheck(env, morph, visitor, function (visitor) { AlwaysDirtyVisitor.inline(node, morph, env, scope, visitor); }); }, content: function (node, morph, env, scope, visitor) { dirtyCheck(env, morph, visitor, function (visitor) { AlwaysDirtyVisitor.content(node, morph, env, scope, visitor); }); }, element: function (node, morph, env, scope, template, visitor) { dirtyCheck(env, morph, visitor, function (visitor) { AlwaysDirtyVisitor.element(node, morph, env, scope, template, visitor); }); }, attribute: function (node, morph, env, scope, template) { dirtyCheck(env, morph, null, function () { AlwaysDirtyVisitor.attribute(node, morph, env, scope, template); }); }, component: function (node, morph, env, scope, template, visitor) { dirtyCheck(env, morph, visitor, function (visitor) { AlwaysDirtyVisitor.component(node, morph, env, scope, template, visitor); }); }, attributes: function (node, morph, env, scope, parentMorph, visitor) { AlwaysDirtyVisitor.attributes(node, morph, env, scope, parentMorph, visitor); } }; function dirtyCheck(_env, morph, visitor, callback) { var isDirty = morph.isDirty; var isSubtreeDirty = morph.isSubtreeDirty; var env = _env; if (isSubtreeDirty) { visitor = AlwaysDirtyVisitor; } if (isDirty || isSubtreeDirty) { callback(visitor); } else { if (morph.buildChildEnv) { env = morph.buildChildEnv(morph.getState(), env); } _htmlbarsUtilMorphUtils.validateChildMorphs(env, morph, visitor); } } function isHelper(env, scope, path) { return env.hooks.keywords[path] !== undefined || env.hooks.hasHelper(env, scope, path); } }); enifed("htmlbars-runtime/render", ["exports", "htmlbars-util/morph-utils", "htmlbars-runtime/node-visitor", "htmlbars-runtime/morph", "htmlbars-util/template-utils", "htmlbars-util/void-tag-names"], function (exports, _htmlbarsUtilMorphUtils, _htmlbarsRuntimeNodeVisitor, _htmlbarsRuntimeMorph, _htmlbarsUtilTemplateUtils, _htmlbarsUtilVoidTagNames) { "use strict"; exports.default = render; exports.RenderOptions = RenderOptions; exports.manualElement = manualElement; exports.attachAttributes = attachAttributes; exports.createChildMorph = createChildMorph; exports.getCachedFragment = getCachedFragment; var svgNamespace = "http://www.w3.org/2000/svg"; function render(template, env, scope, options) { var dom = env.dom; var contextualElement; if (options) { if (options.renderNode) { contextualElement = options.renderNode.contextualElement; } else if (options.contextualElement) { contextualElement = options.contextualElement; } } dom.detectNamespace(contextualElement); var renderResult = RenderResult.build(env, scope, template, options, contextualElement); renderResult.render(); return renderResult; } function RenderOptions(renderNode, self, blockArguments, contextualElement) { this.renderNode = renderNode || null; this.self = self; this.blockArguments = blockArguments || null; this.contextualElement = contextualElement || null; } function RenderResult(env, scope, options, rootNode, ownerNode, nodes, fragment, template, shouldSetContent) { this.root = rootNode; this.fragment = fragment; this.nodes = nodes; this.template = template; this.statements = template.statements.slice(); this.env = env; this.scope = scope; this.shouldSetContent = shouldSetContent; if (options.self !== undefined) { this.bindSelf(options.self); } if (options.blockArguments !== undefined) { this.bindLocals(options.blockArguments); } this.initializeNodes(ownerNode); } RenderResult.build = function (env, scope, template, options, contextualElement) { var dom = env.dom; var fragment = getCachedFragment(template, env); var nodes = template.buildRenderNodes(dom, fragment, contextualElement); var rootNode, ownerNode, shouldSetContent; if (options && options.renderNode) { rootNode = options.renderNode; ownerNode = rootNode.ownerNode; shouldSetContent = true; } else { rootNode = dom.createMorph(null, fragment.firstChild, fragment.lastChild, contextualElement); ownerNode = rootNode; rootNode.ownerNode = ownerNode; shouldSetContent = false; } if (rootNode.childNodes) { _htmlbarsUtilMorphUtils.visitChildren(rootNode.childNodes, function (node) { _htmlbarsUtilTemplateUtils.clearMorph(node, env, true); }); } rootNode.childNodes = nodes; return new RenderResult(env, scope, options, rootNode, ownerNode, nodes, fragment, template, shouldSetContent); }; function manualElement(tagName, attributes, _isEmpty) { var statements = []; for (var key in attributes) { if (typeof attributes[key] === 'string') { continue; } statements.push(_htmlbarsUtilTemplateUtils.buildStatement("attribute", key, attributes[key])); } var isEmpty = _isEmpty || _htmlbarsUtilVoidTagNames.default[tagName]; if (!isEmpty) { statements.push(_htmlbarsUtilTemplateUtils.buildStatement('content', 'yield')); } var template = { arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); if (tagName === 'svg') { dom.setNamespace(svgNamespace); } var el1 = dom.createElement(tagName); for (var key in attributes) { if (typeof attributes[key] !== 'string') { continue; } dom.setAttribute(el1, key, attributes[key]); } if (!isEmpty) { var el2 = dom.createComment(""); dom.appendChild(el1, el2); } dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment) { var element = dom.childAt(fragment, [0]); var morphs = []; for (var key in attributes) { if (typeof attributes[key] === 'string') { continue; } morphs.push(dom.createAttrMorph(element, key)); } if (!isEmpty) { morphs.push(dom.createMorphAt(element, 0, 0)); } return morphs; }, statements: statements, locals: [], templates: [] }; return template; } function attachAttributes(attributes) { var statements = []; for (var key in attributes) { if (typeof attributes[key] === 'string') { continue; } statements.push(_htmlbarsUtilTemplateUtils.buildStatement("attribute", key, attributes[key])); } var template = { arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = this.element; if (el0.namespaceURI === "http://www.w3.org/2000/svg") { dom.setNamespace(svgNamespace); } for (var key in attributes) { if (typeof attributes[key] !== 'string') { continue; } dom.setAttribute(el0, key, attributes[key]); } return el0; }, buildRenderNodes: function buildRenderNodes(dom) { var element = this.element; var morphs = []; for (var key in attributes) { if (typeof attributes[key] === 'string') { continue; } morphs.push(dom.createAttrMorph(element, key)); } return morphs; }, statements: statements, locals: [], templates: [], element: null }; return template; } RenderResult.prototype.initializeNodes = function (ownerNode) { var childNodes = this.root.childNodes; for (var i = 0, l = childNodes.length; i < l; i++) { childNodes[i].ownerNode = ownerNode; } }; RenderResult.prototype.render = function () { this.root.lastResult = this; this.root.rendered = true; this.populateNodes(_htmlbarsRuntimeNodeVisitor.AlwaysDirtyVisitor); if (this.shouldSetContent && this.root.setContent) { this.root.setContent(this.fragment); } }; RenderResult.prototype.dirty = function () { _htmlbarsUtilMorphUtils.visitChildren([this.root], function (node) { node.isDirty = true; }); }; RenderResult.prototype.revalidate = function (env, self, blockArguments, scope) { this.revalidateWith(env, scope, self, blockArguments, _htmlbarsRuntimeNodeVisitor.default); }; RenderResult.prototype.rerender = function (env, self, blockArguments, scope) { this.revalidateWith(env, scope, self, blockArguments, _htmlbarsRuntimeNodeVisitor.AlwaysDirtyVisitor); }; RenderResult.prototype.revalidateWith = function (env, scope, self, blockArguments, visitor) { if (env !== undefined) { this.env = env; } if (scope !== undefined) { this.scope = scope; } this.updateScope(); if (self !== undefined) { this.updateSelf(self); } if (blockArguments !== undefined) { this.updateLocals(blockArguments); } this.populateNodes(visitor); }; RenderResult.prototype.destroy = function () { var rootNode = this.root; _htmlbarsUtilTemplateUtils.clearMorph(rootNode, this.env, true); }; RenderResult.prototype.populateNodes = function (visitor) { var env = this.env; var scope = this.scope; var template = this.template; var nodes = this.nodes; var statements = this.statements; var i, l; for (i = 0, l = statements.length; i < l; i++) { var statement = statements[i]; var morph = nodes[i]; if (env.hooks.willRenderNode) { env.hooks.willRenderNode(morph, env, scope); } switch (statement[0]) { case 'block': visitor.block(statement, morph, env, scope, template, visitor);break; case 'inline': visitor.inline(statement, morph, env, scope, visitor);break; case 'content': visitor.content(statement, morph, env, scope, visitor);break; case 'element': visitor.element(statement, morph, env, scope, template, visitor);break; case 'attribute': visitor.attribute(statement, morph, env, scope);break; case 'component': visitor.component(statement, morph, env, scope, template, visitor);break; } if (env.hooks.didRenderNode) { env.hooks.didRenderNode(morph, env, scope); } } }; RenderResult.prototype.bindScope = function () { this.env.hooks.bindScope(this.env, this.scope); }; RenderResult.prototype.updateScope = function () { this.env.hooks.updateScope(this.env, this.scope); }; RenderResult.prototype.bindSelf = function (self) { this.env.hooks.bindSelf(this.env, this.scope, self); }; RenderResult.prototype.updateSelf = function (self) { this.env.hooks.updateSelf(this.env, this.scope, self); }; RenderResult.prototype.bindLocals = function (blockArguments) { var localNames = this.template.locals; for (var i = 0, l = localNames.length; i < l; i++) { this.env.hooks.bindLocal(this.env, this.scope, localNames[i], blockArguments[i]); } }; RenderResult.prototype.updateLocals = function (blockArguments) { var localNames = this.template.locals; for (var i = 0, l = localNames.length; i < l; i++) { this.env.hooks.updateLocal(this.env, this.scope, localNames[i], blockArguments[i]); } }; function initializeNode(node, owner) { node.ownerNode = owner; } function createChildMorph(dom, parentMorph, contextualElement) { var morph = _htmlbarsRuntimeMorph.default.empty(dom, contextualElement || parentMorph.contextualElement); initializeNode(morph, parentMorph.ownerNode); return morph; } function getCachedFragment(template, env) { var dom = env.dom, fragment; if (env.useFragmentCache && dom.canClone) { if (template.cachedFragment === null) { fragment = template.buildFragment(dom); if (template.hasRendered) { template.cachedFragment = fragment; } else { template.hasRendered = true; } } if (template.cachedFragment) { fragment = dom.cloneNode(template.cachedFragment, true); } } else if (!fragment) { fragment = template.buildFragment(dom); } return fragment; } }); enifed('htmlbars-util', ['exports', 'htmlbars-util/safe-string', 'htmlbars-util/handlebars/utils', 'htmlbars-util/namespaces', 'htmlbars-util/morph-utils'], function (exports, _htmlbarsUtilSafeString, _htmlbarsUtilHandlebarsUtils, _htmlbarsUtilNamespaces, _htmlbarsUtilMorphUtils) { 'use strict'; exports.SafeString = _htmlbarsUtilSafeString.default; exports.escapeExpression = _htmlbarsUtilHandlebarsUtils.escapeExpression; exports.getAttrNamespace = _htmlbarsUtilNamespaces.getAttrNamespace; exports.validateChildMorphs = _htmlbarsUtilMorphUtils.validateChildMorphs; exports.linkParams = _htmlbarsUtilMorphUtils.linkParams; exports.dump = _htmlbarsUtilMorphUtils.dump; }); enifed('htmlbars-util/array-utils', ['exports'], function (exports) { 'use strict'; exports.forEach = forEach; exports.map = map; function forEach(array, callback, binding) { var i, l; if (binding === undefined) { for (i = 0, l = array.length; i < l; i++) { callback(array[i], i, array); } } else { for (i = 0, l = array.length; i < l; i++) { callback.call(binding, array[i], i, array); } } } function map(array, callback) { var output = []; var i, l; for (i = 0, l = array.length; i < l; i++) { output.push(callback(array[i], i, array)); } return output; } var getIdx; if (Array.prototype.indexOf) { getIdx = function (array, obj, from) { return array.indexOf(obj, from); }; } else { getIdx = function (array, obj, from) { if (from === undefined || from === null) { from = 0; } else if (from < 0) { from = Math.max(0, array.length + from); } for (var i = from, l = array.length; i < l; i++) { if (array[i] === obj) { return i; } } return -1; }; } var isArray = Array.isArray || function (array) { return Object.prototype.toString.call(array) === '[object Array]'; }; exports.isArray = isArray; var indexOfArray = getIdx; exports.indexOfArray = indexOfArray; }); enifed('htmlbars-util/handlebars/safe-string', ['exports'], function (exports) { // Build out our basic SafeString type 'use strict'; function SafeString(string) { this.string = string; } SafeString.prototype.toString = SafeString.prototype.toHTML = function () { return '' + this.string; }; exports.default = SafeString; }); enifed('htmlbars-util/handlebars/utils', ['exports'], function (exports) { 'use strict'; exports.extend = extend; exports.indexOf = indexOf; exports.escapeExpression = escapeExpression; exports.isEmpty = isEmpty; exports.blockParams = blockParams; exports.appendContextPath = appendContextPath; var escape = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`' }; var badChars = /[&<>"'`]/g, possible = /[&<>"'`]/; function escapeChar(chr) { return escape[chr]; } function extend(obj /* , ...source */) { for (var i = 1; i < arguments.length; i++) { for (var key in arguments[i]) { if (Object.prototype.hasOwnProperty.call(arguments[i], key)) { obj[key] = arguments[i][key]; } } } return obj; } var toString = Object.prototype.toString; exports.toString = toString; // Sourced from lodash // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt /*eslint-disable func-style, no-var */ var isFunction = function (value) { return typeof value === 'function'; }; // fallback for older versions of Chrome and Safari /* istanbul ignore next */ if (isFunction(/x/)) { exports.isFunction = isFunction = function (value) { return typeof value === 'function' && toString.call(value) === '[object Function]'; }; } var isFunction; exports.isFunction = isFunction; /*eslint-enable func-style, no-var */ /* istanbul ignore next */ var isArray = Array.isArray || function (value) { return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false; }; exports.isArray = isArray; // Older IE versions do not directly support indexOf so we must implement our own, sadly. function indexOf(array, value) { for (var i = 0, len = array.length; i < len; i++) { if (array[i] === value) { return i; } } return -1; } function escapeExpression(string) { if (typeof string !== 'string') { // don't escape SafeStrings, since they're already safe if (string && string.toHTML) { return string.toHTML(); } else if (string == null) { return ''; } else if (!string) { return string + ''; } // Force a string conversion as this will be done by the append regardless and // the regex test will do this transparently behind the scenes, causing issues if // an object's to string has escaped characters in it. string = '' + string; } if (!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); } function isEmpty(value) { if (!value && value !== 0) { return true; } else if (isArray(value) && value.length === 0) { return true; } else { return false; } } function blockParams(params, ids) { params.path = ids; return params; } function appendContextPath(contextPath, id) { return (contextPath ? contextPath + '.' : '') + id; } }); enifed("htmlbars-util/morph-utils", ["exports"], function (exports) { /*globals console*/ "use strict"; exports.visitChildren = visitChildren; exports.validateChildMorphs = validateChildMorphs; exports.linkParams = linkParams; exports.dump = dump; function visitChildren(nodes, callback) { if (!nodes || nodes.length === 0) { return; } nodes = nodes.slice(); while (nodes.length) { var node = nodes.pop(); callback(node); if (node.childNodes) { nodes.push.apply(nodes, node.childNodes); } else if (node.firstChildMorph) { var current = node.firstChildMorph; while (current) { nodes.push(current); current = current.nextMorph; } } else if (node.morphList) { var current = node.morphList.firstChildMorph; while (current) { nodes.push(current); current = current.nextMorph; } } } } function validateChildMorphs(env, morph, visitor) { var morphList = morph.morphList; if (morph.morphList) { var current = morphList.firstChildMorph; while (current) { var next = current.nextMorph; validateChildMorphs(env, current, visitor); current = next; } } else if (morph.lastResult) { morph.lastResult.revalidateWith(env, undefined, undefined, undefined, visitor); } else if (morph.childNodes) { // This means that the childNodes were wired up manually for (var i = 0, l = morph.childNodes.length; i < l; i++) { validateChildMorphs(env, morph.childNodes[i], visitor); } } } function linkParams(env, scope, morph, path, params, hash) { if (morph.linkedParams) { return; } if (env.hooks.linkRenderNode(morph, env, scope, path, params, hash)) { morph.linkedParams = { params: params, hash: hash }; } } function dump(node) { console.group(node, node.isDirty); if (node.childNodes) { map(node.childNodes, dump); } else if (node.firstChildMorph) { var current = node.firstChildMorph; while (current) { dump(current); current = current.nextMorph; } } else if (node.morphList) { dump(node.morphList); } console.groupEnd(); } function map(nodes, cb) { for (var i = 0, l = nodes.length; i < l; i++) { cb(nodes[i]); } } }); enifed('htmlbars-util/namespaces', ['exports'], function (exports) { // ref http://dev.w3.org/html5/spec-LC/namespaces.html 'use strict'; exports.getAttrNamespace = getAttrNamespace; var defaultNamespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg', xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; function getAttrNamespace(attrName, detectedNamespace) { if (detectedNamespace) { return detectedNamespace; } var namespace; var colonIndex = attrName.indexOf(':'); if (colonIndex !== -1) { var prefix = attrName.slice(0, colonIndex); namespace = defaultNamespaces[prefix]; } return namespace || null; } }); enifed("htmlbars-util/object-utils", ["exports"], function (exports) { "use strict"; exports.merge = merge; exports.shallowCopy = shallowCopy; exports.keySet = keySet; exports.keyLength = keyLength; function merge(options, defaults) { for (var prop in defaults) { if (options.hasOwnProperty(prop)) { continue; } options[prop] = defaults[prop]; } return options; } function shallowCopy(obj) { return merge({}, obj); } function keySet(obj) { var set = {}; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { set[prop] = true; } } return set; } function keyLength(obj) { var count = 0; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { count++; } } return count; } }); enifed("htmlbars-util/quoting", ["exports"], function (exports) { "use strict"; exports.hash = hash; exports.repeat = repeat; function escapeString(str) { str = str.replace(/\\/g, "\\\\"); str = str.replace(/"/g, '\\"'); str = str.replace(/\n/g, "\\n"); return str; } exports.escapeString = escapeString; function string(str) { return '"' + escapeString(str) + '"'; } exports.string = string; function array(a) { return "[" + a + "]"; } exports.array = array; function hash(pairs) { return "{" + pairs.join(", ") + "}"; } function repeat(chars, times) { var str = ""; while (times--) { str += chars; } return str; } }); enifed('htmlbars-util/safe-string', ['exports', 'htmlbars-util/handlebars/safe-string'], function (exports, _htmlbarsUtilHandlebarsSafeString) { 'use strict'; exports.default = _htmlbarsUtilHandlebarsSafeString.default; }); enifed("htmlbars-util/template-utils", ["exports", "htmlbars-util/morph-utils", "htmlbars-runtime/render"], function (exports, _htmlbarsUtilMorphUtils, _htmlbarsRuntimeRender) { "use strict"; var _slice = Array.prototype.slice; exports.RenderState = RenderState; exports.blockFor = blockFor; exports.renderAndCleanup = renderAndCleanup; exports.clearMorph = clearMorph; exports.clearMorphList = clearMorphList; exports.buildStatement = buildStatement; function RenderState(renderNode, morphList) { // The morph list that is no longer needed and can be // destroyed. this.morphListToClear = morphList; // The morph list that needs to be pruned of any items // that were not yielded on a subsequent render. this.morphListToPrune = null; // A map of morphs for each item yielded in during this // rendering pass. Any morphs in the DOM but not in this map // will be pruned during cleanup. this.handledMorphs = {}; this.collisions = undefined; // The morph to clear once rendering is complete. By // default, we set this to the previous morph (to catch // the case where nothing is yielded; in that case, we // should just clear the morph). Otherwise this gets set // to null if anything is rendered. this.morphToClear = renderNode; this.shadowOptions = null; } function Block(render, template, blockOptions) { this.render = render; this.template = template; this.blockOptions = blockOptions; this.arity = template.arity; } Block.prototype.invoke = function (env, blockArguments, _self, renderNode, parentScope, visitor) { if (renderNode.lastResult) { renderNode.lastResult.revalidateWith(env, undefined, _self, blockArguments, visitor); } else { this._firstRender(env, blockArguments, _self, renderNode, parentScope); } }; Block.prototype._firstRender = function (env, blockArguments, _self, renderNode, parentScope) { var options = { renderState: new RenderState(renderNode) }; var render = this.render; var template = this.template; var scope = this.blockOptions.scope; var shadowScope = scope ? env.hooks.createChildScope(scope) : env.hooks.createFreshScope(); env.hooks.bindShadowScope(env, parentScope, shadowScope, this.blockOptions.options); if (_self !== undefined) { env.hooks.bindSelf(env, shadowScope, _self); } else if (this.blockOptions.self !== undefined) { env.hooks.bindSelf(env, shadowScope, this.blockOptions.self); } bindBlocks(env, shadowScope, this.blockOptions.yieldTo); renderAndCleanup(renderNode, env, options, null, function () { options.renderState.morphToClear = null; var renderOptions = new _htmlbarsRuntimeRender.RenderOptions(renderNode, undefined, blockArguments); render(template, env, shadowScope, renderOptions); }); }; function blockFor(render, template, blockOptions) { return new Block(render, template, blockOptions); } function bindBlocks(env, shadowScope, blocks) { if (!blocks) { return; } if (blocks instanceof Block) { env.hooks.bindBlock(env, shadowScope, blocks); } else { for (var name in blocks) { if (blocks.hasOwnProperty(name)) { env.hooks.bindBlock(env, shadowScope, blocks[name], name); } } } } function renderAndCleanup(morph, env, options, shadowOptions, callback) { // The RenderState object is used to collect information about what the // helper or hook being invoked has yielded. Once it has finished either // yielding multiple items (via yieldItem) or a single template (via // yieldTemplate), we detect what was rendered and how it differs from // the previous render, cleaning up old state in DOM as appropriate. var renderState = options.renderState; renderState.collisions = undefined; renderState.shadowOptions = shadowOptions; // Invoke the callback, instructing it to save information about what it // renders into RenderState. var result = callback(options); // The hook can opt-out of cleanup if it handled cleanup itself. if (result && result.handled) { return; } var morphMap = morph.morphMap; // Walk the morph list, clearing any items that were yielded in a previous // render but were not yielded during this render. var morphList = renderState.morphListToPrune; if (morphList) { var handledMorphs = renderState.handledMorphs; var item = morphList.firstChildMorph; while (item) { var next = item.nextMorph; // If we don't see the key in handledMorphs, it wasn't // yielded in and we can safely remove it from DOM. if (!(item.key in handledMorphs)) { morphMap[item.key] = undefined; clearMorph(item, env, true); item.destroy(); } item = next; } } morphList = renderState.morphListToClear; if (morphList) { clearMorphList(morphList, morph, env); } var toClear = renderState.morphToClear; if (toClear) { clearMorph(toClear, env); } } function clearMorph(morph, env, destroySelf) { var cleanup = env.hooks.cleanupRenderNode; var destroy = env.hooks.destroyRenderNode; var willCleanup = env.hooks.willCleanupTree; var didCleanup = env.hooks.didCleanupTree; function destroyNode(node) { if (cleanup) { cleanup(node); } if (destroy) { destroy(node); } } if (willCleanup) { willCleanup(env, morph, destroySelf); } if (cleanup) { cleanup(morph); } if (destroySelf && destroy) { destroy(morph); } _htmlbarsUtilMorphUtils.visitChildren(morph.childNodes, destroyNode); // TODO: Deal with logical children that are not in the DOM tree morph.clear(); if (didCleanup) { didCleanup(env, morph, destroySelf); } morph.lastResult = null; morph.lastYielded = null; morph.childNodes = null; } function clearMorphList(morphList, morph, env) { var item = morphList.firstChildMorph; while (item) { var next = item.nextMorph; morph.morphMap[item.key] = undefined; clearMorph(item, env, true); item.destroy(); item = next; } // Remove the MorphList from the morph. morphList.clear(); morph.morphList = null; } function buildStatement() { var statement = [].concat(_slice.call(arguments)); // ensure array length is 7 by padding with 0 for (var i = arguments.length; i < 7; i++) { statement[i] = 0; } return statement; } }); enifed("htmlbars-util/void-tag-names", ["exports", "htmlbars-util/array-utils"], function (exports, _htmlbarsUtilArrayUtils) { "use strict"; // The HTML elements in this list are speced by // http://www.w3.org/TR/html-markup/syntax.html#syntax-elements, // and will be forced to close regardless of if they have a // self-closing /> at the end. var voidTagNames = "area base br col command embed hr img input keygen link meta param source track wbr"; var voidMap = {}; _htmlbarsUtilArrayUtils.forEach(voidTagNames.split(" "), function (tagName) { voidMap[tagName] = true; }); exports.default = voidMap; }); enifed("morph-attr", ["exports", "morph-attr/sanitize-attribute-value", "dom-helper/prop", "dom-helper/build-html-dom", "htmlbars-util"], function (exports, _morphAttrSanitizeAttributeValue, _domHelperProp, _domHelperBuildHtmlDom, _htmlbarsUtil) { "use strict"; function getProperty() { return this.domHelper.getPropertyStrict(this.element, this.attrName); } function updateProperty(value) { if (this._renderedInitially === true || !_domHelperProp.isAttrRemovalValue(value)) { var element = this.element; var attrName = this.attrName; if (attrName === 'value' && element.tagName === 'INPUT' && element.value === value) { // Do nothing. Attempts to avoid accidently changing the input cursor location. // See https://github.com/tildeio/htmlbars/pull/447 for more details. } else { // do not render if initial value is undefined or null this.domHelper.setPropertyStrict(element, attrName, value); } } this._renderedInitially = true; } function getAttribute() { return this.domHelper.getAttribute(this.element, this.attrName); } // normalize to be more inline with updateProperty behavior function normalizeAttributeValue(value) { if (value === false || value === undefined || value === null) { return null; } if (value === true) { return ''; } // onclick function etc in SSR if (typeof value === 'function') { return null; } return String(value); } function updateAttribute(_value) { var value = normalizeAttributeValue(_value); if (_domHelperProp.isAttrRemovalValue(value)) { this.domHelper.removeAttribute(this.element, this.attrName); } else { this.domHelper.setAttribute(this.element, this.attrName, value); } } function getAttributeNS() { return this.domHelper.getAttributeNS(this.element, this.namespace, this.attrName); } function updateAttributeNS(_value) { var value = normalizeAttributeValue(_value); if (_domHelperProp.isAttrRemovalValue(value)) { this.domHelper.removeAttribute(this.element, this.attrName); } else { this.domHelper.setAttributeNS(this.element, this.namespace, this.attrName, value); } } var UNSET = { unset: true }; var guid = 1; AttrMorph.create = function (element, attrName, domHelper, namespace) { var ns = _htmlbarsUtil.getAttrNamespace(attrName, namespace); if (ns) { return new AttributeNSAttrMorph(element, attrName, domHelper, ns); } else { return createNonNamespacedAttrMorph(element, attrName, domHelper); } }; function createNonNamespacedAttrMorph(element, attrName, domHelper) { var _normalizeProperty = _domHelperProp.normalizeProperty(element, attrName); var normalized = _normalizeProperty.normalized; var type = _normalizeProperty.type; if (element.namespaceURI === _domHelperBuildHtmlDom.svgNamespace || attrName === 'style' || type === 'attr') { return new AttributeAttrMorph(element, normalized, domHelper); } else { return new PropertyAttrMorph(element, normalized, domHelper); } } function AttrMorph(element, attrName, domHelper) { this.element = element; this.domHelper = domHelper; this.attrName = attrName; this._state = undefined; this.isDirty = false; this.isSubtreeDirty = false; this.escaped = true; this.lastValue = UNSET; this.lastResult = null; this.lastYielded = null; this.childNodes = null; this.linkedParams = null; this.linkedResult = null; this.guid = "attr" + guid++; this.seen = false; this.ownerNode = null; this.rendered = false; this._renderedInitially = false; this.namespace = undefined; this.didInit(); } AttrMorph.prototype.getState = function () { if (!this._state) { this._state = {}; } return this._state; }; AttrMorph.prototype.setState = function (newState) { /*jshint -W093 */ return this._state = newState; }; AttrMorph.prototype.didInit = function () {}; AttrMorph.prototype.willSetContent = function () {}; AttrMorph.prototype.setContent = function (value) { this.willSetContent(value); if (this.lastValue === value) { return; } this.lastValue = value; if (this.escaped) { var sanitized = _morphAttrSanitizeAttributeValue.sanitizeAttributeValue(this.domHelper, this.element, this.attrName, value); this._update(sanitized, this.namespace); } else { this._update(value, this.namespace); } }; AttrMorph.prototype.getContent = function () { var value = this.lastValue = this._get(); return value; }; // renderAndCleanup calls `clear` on all items in the morph map // just before calling `destroy` on the morph. // // As a future refactor this could be changed to set the property // back to its original/default value. AttrMorph.prototype.clear = function () {}; AttrMorph.prototype.destroy = function () { this.element = null; this.domHelper = null; }; AttrMorph.prototype._$superAttrMorph = AttrMorph; function PropertyAttrMorph(element, attrName, domHelper) { this._$superAttrMorph(element, attrName, domHelper); } PropertyAttrMorph.prototype = Object.create(AttrMorph.prototype); PropertyAttrMorph.prototype._update = updateProperty; PropertyAttrMorph.prototype._get = getProperty; function AttributeNSAttrMorph(element, attrName, domHelper, namespace) { this._$superAttrMorph(element, attrName, domHelper); this.namespace = namespace; } AttributeNSAttrMorph.prototype = Object.create(AttrMorph.prototype); AttributeNSAttrMorph.prototype._update = updateAttributeNS; AttributeNSAttrMorph.prototype._get = getAttributeNS; function AttributeAttrMorph(element, attrName, domHelper) { this._$superAttrMorph(element, attrName, domHelper); } AttributeAttrMorph.prototype = Object.create(AttrMorph.prototype); AttributeAttrMorph.prototype._update = updateAttribute; AttributeAttrMorph.prototype._get = getAttribute; exports.default = AttrMorph; exports.sanitizeAttributeValue = _morphAttrSanitizeAttributeValue.sanitizeAttributeValue; }); enifed('morph-attr/sanitize-attribute-value', ['exports'], function (exports) { /* jshint scripturl:true */ 'use strict'; exports.sanitizeAttributeValue = sanitizeAttributeValue; var badProtocols = { 'javascript:': true, 'vbscript:': true }; var badTags = { 'A': true, 'BODY': true, 'LINK': true, 'IMG': true, 'IFRAME': true, 'BASE': true, 'FORM': true }; var badTagsForDataURI = { 'EMBED': true }; var badAttributes = { 'href': true, 'src': true, 'background': true, 'action': true }; exports.badAttributes = badAttributes; var badAttributesForDataURI = { 'src': true }; function sanitizeAttributeValue(dom, element, attribute, value) { var tagName; if (!element) { tagName = null; } else { tagName = element.tagName.toUpperCase(); } if (value && value.toHTML) { return value.toHTML(); } if ((tagName === null || badTags[tagName]) && badAttributes[attribute]) { var protocol = dom.protocolForURL(value); if (badProtocols[protocol] === true) { return 'unsafe:' + value; } } if (badTagsForDataURI[tagName] && badAttributesForDataURI[attribute]) { return 'unsafe:' + value; } return value; } }); enifed('morph-range', ['exports', 'morph-range/utils'], function (exports, _morphRangeUtils) { 'use strict'; // constructor just initializes the fields // use one of the static initializers to create a valid morph. function Morph(domHelper, contextualElement) { this.domHelper = domHelper; // context if content if current content is detached this.contextualElement = contextualElement; // inclusive range of morph // these should be nodeType 1, 3, or 8 this.firstNode = null; this.lastNode = null; // flag to force text to setContent to be treated as html this.parseTextAsHTML = false; // morph list graph this.parentMorphList = null; this.previousMorph = null; this.nextMorph = null; } Morph.empty = function (domHelper, contextualElement) { var morph = new Morph(domHelper, contextualElement); morph.clear(); return morph; }; Morph.create = function (domHelper, contextualElement, node) { var morph = new Morph(domHelper, contextualElement); morph.setNode(node); return morph; }; Morph.attach = function (domHelper, contextualElement, firstNode, lastNode) { var morph = new Morph(domHelper, contextualElement); morph.setRange(firstNode, lastNode); return morph; }; Morph.prototype.setContent = function Morph$setContent(content) { if (content === null || content === undefined) { return this.clear(); } var type = typeof content; switch (type) { case 'string': if (this.parseTextAsHTML) { return this.domHelper.setMorphHTML(this, content); } return this.setText(content); case 'object': if (typeof content.nodeType === 'number') { return this.setNode(content); } /* Handlebars.SafeString */ if (typeof content.toHTML === 'function') { return this.setHTML(content.toHTML()); } if (this.parseTextAsHTML) { return this.setHTML(content.toString()); } /* falls through */ case 'boolean': case 'number': return this.setText(content.toString()); case 'function': raiseCannotBindToFunction(content); default: throw new TypeError('unsupported content'); } }; function raiseCannotBindToFunction(content) { var functionName = content.name; var message; if (functionName) { message = 'Unsupported Content: Cannot bind to function `' + functionName + '`'; } else { message = 'Unsupported Content: Cannot bind to function'; } throw new TypeError(message); } Morph.prototype.clear = function Morph$clear() { var node = this.setNode(this.domHelper.createComment('')); return node; }; Morph.prototype.setText = function Morph$setText(text) { var firstNode = this.firstNode; var lastNode = this.lastNode; if (firstNode && lastNode === firstNode && firstNode.nodeType === 3) { firstNode.nodeValue = text; return firstNode; } return this.setNode(text ? this.domHelper.createTextNode(text) : this.domHelper.createComment('')); }; Morph.prototype.setNode = function Morph$setNode(newNode) { var firstNode, lastNode; switch (newNode.nodeType) { case 3: firstNode = newNode; lastNode = newNode; break; case 11: firstNode = newNode.firstChild; lastNode = newNode.lastChild; if (firstNode === null) { firstNode = this.domHelper.createComment(''); newNode.appendChild(firstNode); lastNode = firstNode; } break; default: firstNode = newNode; lastNode = newNode; break; } this.setRange(firstNode, lastNode); return newNode; }; Morph.prototype.setRange = function (firstNode, lastNode) { var previousFirstNode = this.firstNode; if (previousFirstNode !== null) { var parentNode = previousFirstNode.parentNode; if (parentNode !== null) { _morphRangeUtils.insertBefore(parentNode, firstNode, lastNode, previousFirstNode); _morphRangeUtils.clear(parentNode, previousFirstNode, this.lastNode); } } this.firstNode = firstNode; this.lastNode = lastNode; if (this.parentMorphList) { this._syncFirstNode(); this._syncLastNode(); } }; Morph.prototype.destroy = function Morph$destroy() { this.unlink(); var firstNode = this.firstNode; var lastNode = this.lastNode; var parentNode = firstNode && firstNode.parentNode; this.firstNode = null; this.lastNode = null; _morphRangeUtils.clear(parentNode, firstNode, lastNode); }; Morph.prototype.unlink = function Morph$unlink() { var parentMorphList = this.parentMorphList; var previousMorph = this.previousMorph; var nextMorph = this.nextMorph; if (previousMorph) { if (nextMorph) { previousMorph.nextMorph = nextMorph; nextMorph.previousMorph = previousMorph; } else { previousMorph.nextMorph = null; parentMorphList.lastChildMorph = previousMorph; } } else { if (nextMorph) { nextMorph.previousMorph = null; parentMorphList.firstChildMorph = nextMorph; } else if (parentMorphList) { parentMorphList.lastChildMorph = parentMorphList.firstChildMorph = null; } } this.parentMorphList = null; this.nextMorph = null; this.previousMorph = null; if (parentMorphList && parentMorphList.mountedMorph) { if (!parentMorphList.firstChildMorph) { // list is empty parentMorphList.mountedMorph.clear(); return; } else { parentMorphList.firstChildMorph._syncFirstNode(); parentMorphList.lastChildMorph._syncLastNode(); } } }; Morph.prototype.setHTML = function (text) { var fragment = this.domHelper.parseHTML(text, this.contextualElement); return this.setNode(fragment); }; Morph.prototype.setMorphList = function Morph$appendMorphList(morphList) { morphList.mountedMorph = this; this.clear(); var originalFirstNode = this.firstNode; if (morphList.firstChildMorph) { this.firstNode = morphList.firstChildMorph.firstNode; this.lastNode = morphList.lastChildMorph.lastNode; var current = morphList.firstChildMorph; while (current) { var next = current.nextMorph; current.insertBeforeNode(originalFirstNode, null); current = next; } originalFirstNode.parentNode.removeChild(originalFirstNode); } }; Morph.prototype._syncFirstNode = function Morph$syncFirstNode() { var morph = this; var parentMorphList; while (parentMorphList = morph.parentMorphList) { if (parentMorphList.mountedMorph === null) { break; } if (morph !== parentMorphList.firstChildMorph) { break; } if (morph.firstNode === parentMorphList.mountedMorph.firstNode) { break; } parentMorphList.mountedMorph.firstNode = morph.firstNode; morph = parentMorphList.mountedMorph; } }; Morph.prototype._syncLastNode = function Morph$syncLastNode() { var morph = this; var parentMorphList; while (parentMorphList = morph.parentMorphList) { if (parentMorphList.mountedMorph === null) { break; } if (morph !== parentMorphList.lastChildMorph) { break; } if (morph.lastNode === parentMorphList.mountedMorph.lastNode) { break; } parentMorphList.mountedMorph.lastNode = morph.lastNode; morph = parentMorphList.mountedMorph; } }; Morph.prototype.insertBeforeNode = function Morph$insertBeforeNode(parentNode, refNode) { _morphRangeUtils.insertBefore(parentNode, this.firstNode, this.lastNode, refNode); }; Morph.prototype.appendToNode = function Morph$appendToNode(parentNode) { _morphRangeUtils.insertBefore(parentNode, this.firstNode, this.lastNode, null); }; exports.default = Morph; }); enifed('morph-range/morph-list', ['exports', 'morph-range/utils'], function (exports, _morphRangeUtils) { 'use strict'; function MorphList() { // morph graph this.firstChildMorph = null; this.lastChildMorph = null; this.mountedMorph = null; } var prototype = MorphList.prototype; prototype.clear = function MorphList$clear() { var current = this.firstChildMorph; while (current) { var next = current.nextMorph; current.previousMorph = null; current.nextMorph = null; current.parentMorphList = null; current = next; } this.firstChildMorph = this.lastChildMorph = null; }; prototype.destroy = function MorphList$destroy() {}; prototype.appendMorph = function MorphList$appendMorph(morph) { this.insertBeforeMorph(morph, null); }; prototype.insertBeforeMorph = function MorphList$insertBeforeMorph(morph, referenceMorph) { if (morph.parentMorphList !== null) { morph.unlink(); } if (referenceMorph && referenceMorph.parentMorphList !== this) { throw new Error('The morph before which the new morph is to be inserted is not a child of this morph.'); } var mountedMorph = this.mountedMorph; if (mountedMorph) { var parentNode = mountedMorph.firstNode.parentNode; var referenceNode = referenceMorph ? referenceMorph.firstNode : mountedMorph.lastNode.nextSibling; _morphRangeUtils.insertBefore(parentNode, morph.firstNode, morph.lastNode, referenceNode); // was not in list mode replace current content if (!this.firstChildMorph) { _morphRangeUtils.clear(this.mountedMorph.firstNode.parentNode, this.mountedMorph.firstNode, this.mountedMorph.lastNode); } } morph.parentMorphList = this; var previousMorph = referenceMorph ? referenceMorph.previousMorph : this.lastChildMorph; if (previousMorph) { previousMorph.nextMorph = morph; morph.previousMorph = previousMorph; } else { this.firstChildMorph = morph; } if (referenceMorph) { referenceMorph.previousMorph = morph; morph.nextMorph = referenceMorph; } else { this.lastChildMorph = morph; } this.firstChildMorph._syncFirstNode(); this.lastChildMorph._syncLastNode(); }; prototype.removeChildMorph = function MorphList$removeChildMorph(morph) { if (morph.parentMorphList !== this) { throw new Error("Cannot remove a morph from a parent it is not inside of"); } morph.destroy(); }; exports.default = MorphList; }); enifed('morph-range/morph-list.umd', ['exports', 'morph-range/morph-list'], function (exports, _morphRangeMorphList) { 'use strict'; (function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.MorphList = factory(); } })(undefined, function () { return _morphRangeMorphList.default; }); }); enifed("morph-range/utils", ["exports"], function (exports) { // inclusive of both nodes "use strict"; exports.clear = clear; exports.insertBefore = insertBefore; function clear(parentNode, firstNode, lastNode) { if (!parentNode) { return; } var node = firstNode; var nextNode; do { nextNode = node.nextSibling; parentNode.removeChild(node); if (node === lastNode) { break; } node = nextNode; } while (node); } function insertBefore(parentNode, firstNode, lastNode, refNode) { var node = firstNode; var nextNode; do { nextNode = node.nextSibling; parentNode.insertBefore(node, refNode); if (node === lastNode) { break; } node = nextNode; } while (node); } }); enifed("route-recognizer", ["exports"], function (exports) { "use strict"; function Target(path, matcher, delegate) { this.path = path; this.matcher = matcher; this.delegate = delegate; } Target.prototype = { to: function (target, callback) { var delegate = this.delegate; if (delegate && delegate.willAddRoute) { target = delegate.willAddRoute(this.matcher.target, target); } this.matcher.add(this.path, target); if (callback) { if (callback.length === 0) { throw new Error("You must have an argument in the function passed to `to`"); } this.matcher.addChild(this.path, target, callback, this.delegate); } return this; } }; function Matcher(target) { this.routes = {}; this.children = {}; this.target = target; } Matcher.prototype = { add: function (path, handler) { this.routes[path] = handler; }, addChild: function (path, target, callback, delegate) { var matcher = new Matcher(target); this.children[path] = matcher; var match = generateMatch(path, matcher, delegate); if (delegate && delegate.contextEntered) { delegate.contextEntered(target, match); } callback(match); } }; function generateMatch(startingPath, matcher, delegate) { return function (path, nestedCallback) { var fullPath = startingPath + path; if (nestedCallback) { nestedCallback(generateMatch(fullPath, matcher, delegate)); } else { return new Target(startingPath + path, matcher, delegate); } }; } function addRoute(routeArray, path, handler) { var len = 0; for (var i = 0; i < routeArray.length; i++) { len += routeArray[i].path.length; } path = path.substr(len); var route = { path: path, handler: handler }; routeArray.push(route); } function eachRoute(baseRoute, matcher, callback, binding) { var routes = matcher.routes; for (var path in routes) { if (routes.hasOwnProperty(path)) { var routeArray = baseRoute.slice(); addRoute(routeArray, path, routes[path]); if (matcher.children[path]) { eachRoute(routeArray, matcher.children[path], callback, binding); } else { callback.call(binding, routeArray); } } } } function map(callback, addRouteCallback) { var matcher = new Matcher(); callback(generateMatch("", matcher, this.delegate)); eachRoute([], matcher, function (route) { if (addRouteCallback) { addRouteCallback(this, route); } else { this.add(route); } }, this); } // Normalizes percent-encoded values in `path` to upper-case and decodes percent-encoded // values that are not reserved (i.e., unicode characters, emoji, etc). The reserved // chars are "/" and "%". // Safe to call multiple times on the same path. function normalizePath(path) { return path.split('/').map(normalizeSegment).join('/'); } // We want to ensure the characters "%" and "/" remain in percent-encoded // form when normalizing paths, so replace them with their encoded form after // decoding the rest of the path var SEGMENT_RESERVED_CHARS = /%|\//g; function normalizeSegment(segment) { return decodeURIComponent(segment).replace(SEGMENT_RESERVED_CHARS, encodeURIComponent); } // We do not want to encode these characters when generating dynamic path segments // See https://tools.ietf.org/html/rfc3986#section-3.3 // sub-delims: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" // others allowed by RFC 3986: ":", "@" // // First encode the entire path segment, then decode any of the encoded special chars. // // The chars "!", "'", "(", ")", "*" do not get changed by `encodeURIComponent`, // so the possible encoded chars are: // ['%24', '%26', '%2B', '%2C', '%3B', '%3D', '%3A', '%40']. var PATH_SEGMENT_ENCODINGS = /%(?:24|26|2B|2C|3B|3D|3A|40)/g; function encodePathSegment(str) { return encodeURIComponent(str).replace(PATH_SEGMENT_ENCODINGS, decodeURIComponent); } var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\']; var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); function isArray(test) { return Object.prototype.toString.call(test) === "[object Array]"; } // A Segment represents a segment in the original route description. // Each Segment type provides an `eachChar` and `regex` method. // // The `eachChar` method invokes the callback with one or more character // specifications. A character specification consumes one or more input // characters. // // The `regex` method returns a regex fragment for the segment. If the // segment is a dynamic of star segment, the regex fragment also includes // a capture. // // A character specification contains: // // * `validChars`: a String with a list of all valid characters, or // * `invalidChars`: a String with a list of all invalid characters // * `repeat`: true if the character specification can repeat function StaticSegment(string) { this.string = normalizeSegment(string); } StaticSegment.prototype = { eachChar: function (currentState) { var string = this.string, ch; for (var i = 0; i < string.length; i++) { ch = string.charAt(i); currentState = currentState.put({ invalidChars: undefined, repeat: false, validChars: ch }); } return currentState; }, regex: function () { return this.string.replace(escapeRegex, '\\$1'); }, generate: function () { return this.string; } }; function DynamicSegment(name) { this.name = normalizeSegment(name); } DynamicSegment.prototype = { eachChar: function (currentState) { return currentState.put({ invalidChars: "/", repeat: true, validChars: undefined }); }, regex: function () { return "([^/]+)"; }, generate: function (params) { if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) { return encodePathSegment(params[this.name]); } else { return params[this.name]; } } }; function StarSegment(name) { this.name = name; } StarSegment.prototype = { eachChar: function (currentState) { return currentState.put({ invalidChars: "", repeat: true, validChars: undefined }); }, regex: function () { return "(.+)"; }, generate: function (params) { return params[this.name]; } }; function EpsilonSegment() {} EpsilonSegment.prototype = { eachChar: function (currentState) { return currentState; }, regex: function () { return ""; }, generate: function () { return ""; } }; // The `names` will be populated with the paramter name for each dynamic/star // segment. `shouldDecodes` will be populated with a boolean for each dyanamic/star // segment, indicating whether it should be decoded during recognition. function parse(route, names, types, shouldDecodes) { // normalize route as not starting with a "/". Recognition will // also normalize. if (route.charAt(0) === "/") { route = route.substr(1); } var segments = route.split("/"); var results = new Array(segments.length); for (var i = 0; i < segments.length; i++) { var segment = segments[i], match; if (match = segment.match(/^:([^\/]+)$/)) { results[i] = new DynamicSegment(match[1]); names.push(match[1]); shouldDecodes.push(true); types.dynamics++; } else if (match = segment.match(/^\*([^\/]+)$/)) { results[i] = new StarSegment(match[1]); names.push(match[1]); shouldDecodes.push(false); types.stars++; } else if (segment === "") { results[i] = new EpsilonSegment(); } else { results[i] = new StaticSegment(segment); types.statics++; } } return results; } function isEqualCharSpec(specA, specB) { return specA.validChars === specB.validChars && specA.invalidChars === specB.invalidChars; } // A State has a character specification and (`charSpec`) and a list of possible // subsequent states (`nextStates`). // // If a State is an accepting state, it will also have several additional // properties: // // * `regex`: A regular expression that is used to extract parameters from paths // that reached this accepting state. // * `handlers`: Information on how to convert the list of captures into calls // to registered handlers with the specified parameters // * `types`: How many static, dynamic or star segments in this route. Used to // decide which route to use if multiple registered routes match a path. // // Currently, State is implemented naively by looping over `nextStates` and // comparing a character specification against a character. A more efficient // implementation would use a hash of keys pointing at one or more next states. function State(charSpec) { this.charSpec = charSpec; this.nextStates = []; this.regex = undefined; this.handlers = undefined; this.specificity = undefined; } State.prototype = { get: function (charSpec) { var nextStates = this.nextStates; for (var i = 0; i < nextStates.length; i++) { var child = nextStates[i]; if (isEqualCharSpec(child.charSpec, charSpec)) { return child; } } }, put: function (charSpec) { var state; // If the character specification already exists in a child of the current // state, just return that state. if (state = this.get(charSpec)) { return state; } // Make a new state for the character spec state = new State(charSpec); // Insert the new state as a child of the current state this.nextStates.push(state); // If this character specification repeats, insert the new state as a child // of itself. Note that this will not trigger an infinite loop because each // transition during recognition consumes a character. if (charSpec.repeat) { state.nextStates.push(state); } // Return the new state return state; }, // Find a list of child states matching the next character match: function (ch) { var nextStates = this.nextStates, child, charSpec, chars; var returned = []; for (var i = 0; i < nextStates.length; i++) { child = nextStates[i]; charSpec = child.charSpec; if (typeof (chars = charSpec.validChars) !== 'undefined') { if (chars.indexOf(ch) !== -1) { returned.push(child); } } else if (typeof (chars = charSpec.invalidChars) !== 'undefined') { if (chars.indexOf(ch) === -1) { returned.push(child); } } } return returned; } }; // This is a somewhat naive strategy, but should work in a lot of cases // A better strategy would properly resolve /posts/:id/new and /posts/edit/:id. // // This strategy generally prefers more static and less dynamic matching. // Specifically, it // // * prefers fewer stars to more, then // * prefers using stars for less of the match to more, then // * prefers fewer dynamic segments to more, then // * prefers more static segments to more function sortSolutions(states) { return states.sort(function (a, b) { if (a.types.stars !== b.types.stars) { return a.types.stars - b.types.stars; } if (a.types.stars) { if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } if (a.types.dynamics !== b.types.dynamics) { return b.types.dynamics - a.types.dynamics; } } if (a.types.dynamics !== b.types.dynamics) { return a.types.dynamics - b.types.dynamics; } if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } return 0; }); } function recognizeChar(states, ch) { var nextStates = []; for (var i = 0, l = states.length; i < l; i++) { var state = states[i]; nextStates = nextStates.concat(state.match(ch)); } return nextStates; } var oCreate = Object.create || function (proto) { function F() {} F.prototype = proto; return new F(); }; function RecognizeResults(queryParams) { this.queryParams = queryParams || {}; } RecognizeResults.prototype = oCreate({ splice: Array.prototype.splice, slice: Array.prototype.slice, push: Array.prototype.push, length: 0, queryParams: null }); function findHandler(state, originalPath, queryParams) { var handlers = state.handlers, regex = state.regex; var captures = originalPath.match(regex), currentCapture = 1; var result = new RecognizeResults(queryParams); result.length = handlers.length; for (var i = 0; i < handlers.length; i++) { var handler = handlers[i], names = handler.names, shouldDecodes = handler.shouldDecodes, params = {}; var name, shouldDecode, capture; for (var j = 0; j < names.length; j++) { name = names[j]; shouldDecode = shouldDecodes[j]; capture = captures[currentCapture++]; if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) { if (shouldDecode) { params[name] = decodeURIComponent(capture); } else { params[name] = capture; } } else { params[name] = capture; } } result[i] = { handler: handler.handler, params: params, isDynamic: !!names.length }; } return result; } function decodeQueryParamPart(part) { // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 part = part.replace(/\+/gm, '%20'); var result; try { result = decodeURIComponent(part); } catch (error) { result = ''; } return result; } // The main interface var RouteRecognizer = function () { this.rootState = new State(); this.names = {}; }; RouteRecognizer.prototype = { add: function (routes, options) { var currentState = this.rootState, regex = "^", types = { statics: 0, dynamics: 0, stars: 0 }, handlers = new Array(routes.length), allSegments = [], name; var isEmpty = true; for (var i = 0; i < routes.length; i++) { var route = routes[i], names = [], shouldDecodes = []; var segments = parse(route.path, names, types, shouldDecodes); allSegments = allSegments.concat(segments); for (var j = 0; j < segments.length; j++) { var segment = segments[j]; if (segment instanceof EpsilonSegment) { continue; } isEmpty = false; // Add a "/" for the new segment currentState = currentState.put({ invalidChars: undefined, repeat: false, validChars: "/" }); regex += "/"; // Add a representation of the segment to the NFA and regex currentState = segment.eachChar(currentState); regex += segment.regex(); } var handler = { handler: route.handler, names: names, shouldDecodes: shouldDecodes }; handlers[i] = handler; } if (isEmpty) { currentState = currentState.put({ invalidChars: undefined, repeat: false, validChars: "/" }); regex += "/"; } currentState.handlers = handlers; currentState.regex = new RegExp(regex + "$"); currentState.types = types; if (name = options && options.as) { this.names[name] = { segments: allSegments, handlers: handlers }; } }, handlersFor: function (name) { var route = this.names[name]; if (!route) { throw new Error("There is no route named " + name); } var result = new Array(route.handlers.length); for (var i = 0; i < route.handlers.length; i++) { result[i] = route.handlers[i]; } return result; }, hasRoute: function (name) { return !!this.names[name]; }, generate: function (name, params) { var route = this.names[name], output = ""; if (!route) { throw new Error("There is no route named " + name); } var segments = route.segments; for (var i = 0; i < segments.length; i++) { var segment = segments[i]; if (segment instanceof EpsilonSegment) { continue; } output += "/"; output += segment.generate(params); } if (output.charAt(0) !== '/') { output = '/' + output; } if (params && params.queryParams) { output += this.generateQueryString(params.queryParams, route.handlers); } return output; }, generateQueryString: function (params) { var pairs = []; var keys = []; for (var key in params) { if (params.hasOwnProperty(key)) { keys.push(key); } } keys.sort(); for (var i = 0; i < keys.length; i++) { key = keys[i]; var value = params[key]; if (value == null) { continue; } var pair = encodeURIComponent(key); if (isArray(value)) { for (var j = 0; j < value.length; j++) { var arrayPair = key + '[]' + '=' + encodeURIComponent(value[j]); pairs.push(arrayPair); } } else { pair += "=" + encodeURIComponent(value); pairs.push(pair); } } if (pairs.length === 0) { return ''; } return "?" + pairs.join("&"); }, parseQueryString: function (queryString) { var pairs = queryString.split("&"), queryParams = {}; for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='), key = decodeQueryParamPart(pair[0]), keyLength = key.length, isArray = false, value; if (pair.length === 1) { value = 'true'; } else { //Handle arrays if (keyLength > 2 && key.slice(keyLength - 2) === '[]') { isArray = true; key = key.slice(0, keyLength - 2); if (!queryParams[key]) { queryParams[key] = []; } } value = pair[1] ? decodeQueryParamPart(pair[1]) : ''; } if (isArray) { queryParams[key].push(value); } else { queryParams[key] = value; } } return queryParams; }, recognize: function (path) { var states = [this.rootState], pathLen, i, queryStart, queryParams = {}, hashStart, isSlashDropped = false; hashStart = path.indexOf('#'); if (hashStart !== -1) { path = path.substr(0, hashStart); } queryStart = path.indexOf('?'); if (queryStart !== -1) { var queryString = path.substr(queryStart + 1, path.length); path = path.substr(0, queryStart); queryParams = this.parseQueryString(queryString); } if (path.charAt(0) !== "/") { path = "/" + path; } var originalPath = path; if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) { path = normalizePath(path); } else { path = decodeURI(path); originalPath = decodeURI(originalPath); } pathLen = path.length; if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { path = path.substr(0, pathLen - 1); originalPath = originalPath.substr(0, pathLen - 1); isSlashDropped = true; } for (i = 0; i < path.length; i++) { states = recognizeChar(states, path.charAt(i)); if (!states.length) { break; } } var solutions = []; for (i = 0; i < states.length; i++) { if (states[i].handlers) { solutions.push(states[i]); } } states = sortSolutions(solutions); var state = solutions[0]; if (state && state.handlers) { // if a trailing slash was dropped and a star segment is the last segment // specified, put the trailing slash back if (isSlashDropped && state.regex.source.slice(-5) === "(.+)$") { originalPath = originalPath + "/"; } return findHandler(state, originalPath, queryParams); } } }; RouteRecognizer.prototype.map = map; RouteRecognizer.VERSION = '0.2.6'; // Set to false to opt-out of encoding and decoding path segments. // See https://github.com/tildeio/route-recognizer/pull/55 RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS = true; RouteRecognizer.Normalizer = { normalizeSegment: normalizeSegment, normalizePath: normalizePath, encodePathSegment: encodePathSegment }; exports.default = RouteRecognizer; }); enifed('router', ['exports', 'router/router'], function (exports, _routerRouter) { 'use strict'; exports.default = _routerRouter.default; }); enifed('router/handler-info', ['exports', 'router/utils', 'rsvp/promise'], function (exports, _routerUtils, _rsvpPromise) { 'use strict'; var DEFAULT_HANDLER = Object.freeze({}); function HandlerInfo(_props) { var props = _props || {}; // Set a default handler to ensure consistent object shape this._handler = DEFAULT_HANDLER; if (props.handler) { var name = props.name; // Setup a handlerPromise so that we can wait for asynchronously loaded handlers this.handlerPromise = _rsvpPromise.default.resolve(props.handler); // Wait until the 'handler' property has been updated when chaining to a handler // that is a promise if (_routerUtils.isPromise(props.handler)) { this.handlerPromise = this.handlerPromise.then(_routerUtils.bind(this, this.updateHandler)); props.handler = undefined; } else if (props.handler) { // Store the name of the handler on the handler for easy checks later props.handler._handlerName = name; } } _routerUtils.merge(this, props); this.initialize(props); } HandlerInfo.prototype = { name: null, getHandler: function () {}, fetchHandler: function () { var handler = this.getHandler(this.name); // Setup a handlerPromise so that we can wait for asynchronously loaded handlers this.handlerPromise = _rsvpPromise.default.resolve(handler); // Wait until the 'handler' property has been updated when chaining to a handler // that is a promise if (_routerUtils.isPromise(handler)) { this.handlerPromise = this.handlerPromise.then(_routerUtils.bind(this, this.updateHandler)); } else if (handler) { // Store the name of the handler on the handler for easy checks later handler._handlerName = this.name; return this.handler = handler; } return this.handler = undefined; }, _handlerPromise: undefined, params: null, context: null, // Injected by the handler info factory. factory: null, initialize: function () {}, log: function (payload, message) { if (payload.log) { payload.log(this.name + ': ' + message); } }, promiseLabel: function (label) { return _routerUtils.promiseLabel("'" + this.name + "' " + label); }, getUnresolved: function () { return this; }, serialize: function () { return this.params || {}; }, updateHandler: function (handler) { // Store the name of the handler on the handler for easy checks later handler._handlerName = this.name; return this.handler = handler; }, resolve: function (shouldContinue, payload) { var checkForAbort = _routerUtils.bind(this, this.checkForAbort, shouldContinue), beforeModel = _routerUtils.bind(this, this.runBeforeModelHook, payload), model = _routerUtils.bind(this, this.getModel, payload), afterModel = _routerUtils.bind(this, this.runAfterModelHook, payload), becomeResolved = _routerUtils.bind(this, this.becomeResolved, payload), self = this; return _rsvpPromise.default.resolve(this.handlerPromise, this.promiseLabel("Start handler")).then(function (handler) { // We nest this chain in case the handlerPromise has an error so that // we don't have to bubble it through every step return _rsvpPromise.default.resolve(handler).then(checkForAbort, null, self.promiseLabel("Check for abort")).then(beforeModel, null, self.promiseLabel("Before model")).then(checkForAbort, null, self.promiseLabel("Check if aborted during 'beforeModel' hook")).then(model, null, self.promiseLabel("Model")).then(checkForAbort, null, self.promiseLabel("Check if aborted in 'model' hook")).then(afterModel, null, self.promiseLabel("After model")).then(checkForAbort, null, self.promiseLabel("Check if aborted in 'afterModel' hook")).then(becomeResolved, null, self.promiseLabel("Become resolved")); }, function (error) { throw error; }); }, runBeforeModelHook: function (payload) { if (payload.trigger) { payload.trigger(true, 'willResolveModel', payload, this.handler); } return this.runSharedModelHook(payload, 'beforeModel', []); }, runAfterModelHook: function (payload, resolvedModel) { // Stash the resolved model on the payload. // This makes it possible for users to swap out // the resolved model in afterModel. var name = this.name; this.stashResolvedModel(payload, resolvedModel); return this.runSharedModelHook(payload, 'afterModel', [resolvedModel]).then(function () { // Ignore the fulfilled value returned from afterModel. // Return the value stashed in resolvedModels, which // might have been swapped out in afterModel. return payload.resolvedModels[name]; }, null, this.promiseLabel("Ignore fulfillment value and return model value")); }, runSharedModelHook: function (payload, hookName, args) { this.log(payload, "calling " + hookName + " hook"); if (this.queryParams) { args.push(this.queryParams); } args.push(payload); var result = _routerUtils.applyHook(this.handler, hookName, args); if (result && result.isTransition) { result = null; } return _rsvpPromise.default.resolve(result, this.promiseLabel("Resolve value returned from one of the model hooks")); }, // overridden by subclasses getModel: null, checkForAbort: function (shouldContinue, promiseValue) { return _rsvpPromise.default.resolve(shouldContinue(), this.promiseLabel("Check for abort")).then(function () { // We don't care about shouldContinue's resolve value; // pass along the original value passed to this fn. return promiseValue; }, null, this.promiseLabel("Ignore fulfillment value and continue")); }, stashResolvedModel: function (payload, resolvedModel) { payload.resolvedModels = payload.resolvedModels || {}; payload.resolvedModels[this.name] = resolvedModel; }, becomeResolved: function (payload, resolvedContext) { var params = this.serialize(resolvedContext); if (payload) { this.stashResolvedModel(payload, resolvedContext); payload.params = payload.params || {}; payload.params[this.name] = params; } return this.factory('resolved', { context: resolvedContext, name: this.name, handler: this.handler, params: params }); }, shouldSupercede: function (other) { // Prefer this newer handlerInfo over `other` if: // 1) The other one doesn't exist // 2) The names don't match // 3) This handler has a context that doesn't match // the other one (or the other one doesn't have one). // 4) This handler has parameters that don't match the other. if (!other) { return true; } var contextsMatch = other.context === this.context; return other.name !== this.name || this.hasOwnProperty('context') && !contextsMatch || this.hasOwnProperty('params') && !paramsMatch(this.params, other.params); } }; Object.defineProperty(HandlerInfo.prototype, 'handler', { get: function () { // _handler could be set to either a handler object or undefined, so we // compare against a default reference to know when it's been set if (this._handler !== DEFAULT_HANDLER) { return this._handler; } return this.fetchHandler(); }, set: function (handler) { return this._handler = handler; } }); Object.defineProperty(HandlerInfo.prototype, 'handlerPromise', { get: function () { if (this._handlerPromise) { return this._handlerPromise; } this.fetchHandler(); return this._handlerPromise; }, set: function (handlerPromise) { return this._handlerPromise = handlerPromise; } }); function paramsMatch(a, b) { if (!a ^ !b) { // Only one is null. return false; } if (!a) { // Both must be null. return true; } // Note: this assumes that both params have the same // number of keys, but since we're comparing the // same handlers, they should. for (var k in a) { if (a.hasOwnProperty(k) && a[k] !== b[k]) { return false; } } return true; } exports.default = HandlerInfo; }); enifed('router/handler-info/factory', ['exports', 'router/handler-info/resolved-handler-info', 'router/handler-info/unresolved-handler-info-by-object', 'router/handler-info/unresolved-handler-info-by-param'], function (exports, _routerHandlerInfoResolvedHandlerInfo, _routerHandlerInfoUnresolvedHandlerInfoByObject, _routerHandlerInfoUnresolvedHandlerInfoByParam) { 'use strict'; handlerInfoFactory.klasses = { resolved: _routerHandlerInfoResolvedHandlerInfo.default, param: _routerHandlerInfoUnresolvedHandlerInfoByParam.default, object: _routerHandlerInfoUnresolvedHandlerInfoByObject.default }; function handlerInfoFactory(name, props) { var Ctor = handlerInfoFactory.klasses[name], handlerInfo = new Ctor(props || {}); handlerInfo.factory = handlerInfoFactory; return handlerInfo; } exports.default = handlerInfoFactory; }); enifed('router/handler-info/resolved-handler-info', ['exports', 'router/handler-info', 'router/utils', 'rsvp/promise'], function (exports, _routerHandlerInfo, _routerUtils, _rsvpPromise) { 'use strict'; var ResolvedHandlerInfo = _routerUtils.subclass(_routerHandlerInfo.default, { resolve: function (shouldContinue, payload) { // A ResolvedHandlerInfo just resolved with itself. if (payload && payload.resolvedModels) { payload.resolvedModels[this.name] = this.context; } return _rsvpPromise.default.resolve(this, this.promiseLabel("Resolve")); }, getUnresolved: function () { return this.factory('param', { name: this.name, handler: this.handler, params: this.params }); }, isResolved: true }); exports.default = ResolvedHandlerInfo; }); enifed('router/handler-info/unresolved-handler-info-by-object', ['exports', 'router/handler-info', 'router/utils', 'rsvp/promise'], function (exports, _routerHandlerInfo, _routerUtils, _rsvpPromise) { 'use strict'; var UnresolvedHandlerInfoByObject = _routerUtils.subclass(_routerHandlerInfo.default, { getModel: function (payload) { this.log(payload, this.name + ": resolving provided model"); return _rsvpPromise.default.resolve(this.context); }, initialize: function (props) { this.names = props.names || []; this.context = props.context; }, /** @private Serializes a handler using its custom `serialize` method or by a default that looks up the expected property name from the dynamic segment. @param {Object} model the model to be serialized for this handler */ serialize: function (_model) { var model = _model || this.context, names = this.names, serializer = this.serializer || this.handler && this.handler.serialize; var object = {}; if (_routerUtils.isParam(model)) { object[names[0]] = model; return object; } // Use custom serialize if it exists. if (serializer) { return serializer(model, names); } if (names.length !== 1) { return; } var name = names[0]; if (/_id$/.test(name)) { object[name] = model.id; } else { object[name] = model; } return object; } }); exports.default = UnresolvedHandlerInfoByObject; }); enifed('router/handler-info/unresolved-handler-info-by-param', ['exports', 'router/handler-info', 'router/utils'], function (exports, _routerHandlerInfo, _routerUtils) { 'use strict'; // Generated by URL transitions and non-dynamic route segments in named Transitions. var UnresolvedHandlerInfoByParam = _routerUtils.subclass(_routerHandlerInfo.default, { initialize: function (props) { this.params = props.params || {}; }, getModel: function (payload) { var fullParams = this.params; if (payload && payload.queryParams) { fullParams = {}; _routerUtils.merge(fullParams, this.params); fullParams.queryParams = payload.queryParams; } var handler = this.handler; var hookName = _routerUtils.resolveHook(handler, 'deserialize') || _routerUtils.resolveHook(handler, 'model'); return this.runSharedModelHook(payload, hookName, [fullParams]); } }); exports.default = UnresolvedHandlerInfoByParam; }); enifed('router/router', ['exports', 'route-recognizer', 'rsvp/promise', 'router/utils', 'router/transition-state', 'router/transition', 'router/transition-intent/named-transition-intent', 'router/transition-intent/url-transition-intent'], function (exports, _routeRecognizer, _rsvpPromise, _routerUtils, _routerTransitionState, _routerTransition, _routerTransitionIntentNamedTransitionIntent, _routerTransitionIntentUrlTransitionIntent) { 'use strict'; var pop = Array.prototype.pop; function Router(_options) { var options = _options || {}; this.getHandler = options.getHandler || this.getHandler; this.getSerializer = options.getSerializer || this.getSerializer; this.updateURL = options.updateURL || this.updateURL; this.replaceURL = options.replaceURL || this.replaceURL; this.didTransition = options.didTransition || this.didTransition; this.willTransition = options.willTransition || this.willTransition; this.delegate = options.delegate || this.delegate; this.triggerEvent = options.triggerEvent || this.triggerEvent; this.log = options.log || this.log; this.dslCallBacks = []; // NOTE: set by Ember this.state = undefined; this.activeTransition = undefined; this._changedQueryParams = undefined; this.oldState = undefined; this.currentHandlerInfos = undefined; this.state = undefined; this.recognizer = new _routeRecognizer.default(); this.reset(); } function getTransitionByIntent(intent, isIntermediate) { var wasTransitioning = !!this.activeTransition; var oldState = wasTransitioning ? this.activeTransition.state : this.state; var newTransition; var newState = intent.applyToState(oldState, this.recognizer, this.getHandler, isIntermediate, this.getSerializer); var queryParamChangelist = _routerUtils.getChangelist(oldState.queryParams, newState.queryParams); if (handlerInfosEqual(newState.handlerInfos, oldState.handlerInfos)) { // This is a no-op transition. See if query params changed. if (queryParamChangelist) { newTransition = this.queryParamsTransition(queryParamChangelist, wasTransitioning, oldState, newState); if (newTransition) { return newTransition; } } // No-op. No need to create a new transition. return this.activeTransition || new _routerTransition.Transition(this); } if (isIntermediate) { setupContexts(this, newState); return; } // Create a new transition to the destination route. newTransition = new _routerTransition.Transition(this, intent, newState); // Abort and usurp any previously active transition. if (this.activeTransition) { this.activeTransition.abort(); } this.activeTransition = newTransition; // Transition promises by default resolve with resolved state. // For our purposes, swap out the promise to resolve // after the transition has been finalized. newTransition.promise = newTransition.promise.then(function (result) { return finalizeTransition(newTransition, result.state); }, null, _routerUtils.promiseLabel("Settle transition promise when transition is finalized")); if (!wasTransitioning) { notifyExistingHandlers(this, newState, newTransition); } fireQueryParamDidChange(this, newState, queryParamChangelist); return newTransition; } Router.prototype = { /** The main entry point into the router. The API is essentially the same as the `map` method in `route-recognizer`. This method extracts the String handler at the last `.to()` call and uses it as the name of the whole route. @param {Function} callback */ map: function (callback) { this.recognizer.delegate = this.delegate; this.recognizer.map(callback, function (recognizer, routes) { for (var i = routes.length - 1, proceed = true; i >= 0 && proceed; --i) { var route = routes[i]; recognizer.add(routes, { as: route.handler }); proceed = route.path === '/' || route.path === '' || route.handler.slice(-6) === '.index'; } }); }, hasRoute: function (route) { return this.recognizer.hasRoute(route); }, getHandler: function () {}, getSerializer: function () {}, queryParamsTransition: function (changelist, wasTransitioning, oldState, newState) { var router = this; fireQueryParamDidChange(this, newState, changelist); if (!wasTransitioning && this.activeTransition) { // One of the handlers in queryParamsDidChange // caused a transition. Just return that transition. return this.activeTransition; } else { // Running queryParamsDidChange didn't change anything. // Just update query params and be on our way. // We have to return a noop transition that will // perform a URL update at the end. This gives // the user the ability to set the url update // method (default is replaceState). var newTransition = new _routerTransition.Transition(this); newTransition.queryParamsOnly = true; oldState.queryParams = finalizeQueryParamChange(this, newState.handlerInfos, newState.queryParams, newTransition); newTransition.promise = newTransition.promise.then(function (result) { updateURL(newTransition, oldState, true); if (router.didTransition) { router.didTransition(router.currentHandlerInfos); } return result; }, null, _routerUtils.promiseLabel("Transition complete")); return newTransition; } }, // NOTE: this doesn't really belong here, but here // it shall remain until our ES6 transpiler can // handle cyclical deps. transitionByIntent: function (intent /*, isIntermediate*/) { try { return getTransitionByIntent.apply(this, arguments); } catch (e) { return new _routerTransition.Transition(this, intent, null, e); } }, /** Clears the current and target route handlers and triggers exit on each of them starting at the leaf and traversing up through its ancestors. */ reset: function () { if (this.state) { _routerUtils.forEach(this.state.handlerInfos.slice().reverse(), function (handlerInfo) { var handler = handlerInfo.handler; _routerUtils.callHook(handler, 'exit'); }); } this.oldState = undefined; this.state = new _routerTransitionState.default(); this.currentHandlerInfos = null; }, activeTransition: null, /** var handler = handlerInfo.handler; The entry point for handling a change to the URL (usually via the back and forward button). Returns an Array of handlers and the parameters associated with those parameters. @param {String} url a URL to process @return {Array} an Array of `[handler, parameter]` tuples */ handleURL: function (url) { // Perform a URL-based transition, but don't change // the URL afterward, since it already happened. var args = _routerUtils.slice.call(arguments); if (url.charAt(0) !== '/') { args[0] = '/' + url; } return doTransition(this, args).method(null); }, /** Hook point for updating the URL. @param {String} url a URL to update to */ updateURL: function () { throw new Error("updateURL is not implemented"); }, /** Hook point for replacing the current URL, i.e. with replaceState By default this behaves the same as `updateURL` @param {String} url a URL to update to */ replaceURL: function (url) { this.updateURL(url); }, /** Transition into the specified named route. If necessary, trigger the exit callback on any handlers that are no longer represented by the target route. @param {String} name the name of the route */ transitionTo: function () /*name*/{ return doTransition(this, arguments); }, intermediateTransitionTo: function () /*name*/{ return doTransition(this, arguments, true); }, refresh: function (pivotHandler) { var state = this.activeTransition ? this.activeTransition.state : this.state; var handlerInfos = state.handlerInfos; var params = {}; for (var i = 0, len = handlerInfos.length; i < len; ++i) { var handlerInfo = handlerInfos[i]; params[handlerInfo.name] = handlerInfo.params || {}; } _routerUtils.log(this, "Starting a refresh transition"); var intent = new _routerTransitionIntentNamedTransitionIntent.default({ name: handlerInfos[handlerInfos.length - 1].name, pivotHandler: pivotHandler || handlerInfos[0].handler, contexts: [], // TODO collect contexts...? queryParams: this._changedQueryParams || state.queryParams || {} }); return this.transitionByIntent(intent, false); }, /** Identical to `transitionTo` except that the current URL will be replaced if possible. This method is intended primarily for use with `replaceState`. @param {String} name the name of the route */ replaceWith: function () /*name*/{ return doTransition(this, arguments).method('replace'); }, /** Take a named route and context objects and generate a URL. @param {String} name the name of the route to generate a URL for @param {...Object} objects a list of objects to serialize @return {String} a URL */ generate: function (handlerName) { var partitionedArgs = _routerUtils.extractQueryParams(_routerUtils.slice.call(arguments, 1)), suppliedParams = partitionedArgs[0], queryParams = partitionedArgs[1]; // Construct a TransitionIntent with the provided params // and apply it to the present state of the router. var intent = new _routerTransitionIntentNamedTransitionIntent.default({ name: handlerName, contexts: suppliedParams }); var state = intent.applyToState(this.state, this.recognizer, this.getHandler, null, this.getSerializer); var params = {}; for (var i = 0, len = state.handlerInfos.length; i < len; ++i) { var handlerInfo = state.handlerInfos[i]; var handlerParams = handlerInfo.serialize(); _routerUtils.merge(params, handlerParams); } params.queryParams = queryParams; return this.recognizer.generate(handlerName, params); }, applyIntent: function (handlerName, contexts) { var intent = new _routerTransitionIntentNamedTransitionIntent.default({ name: handlerName, contexts: contexts }); var state = this.activeTransition && this.activeTransition.state || this.state; return intent.applyToState(state, this.recognizer, this.getHandler, null, this.getSerializer); }, isActiveIntent: function (handlerName, contexts, queryParams, _state) { var state = _state || this.state, targetHandlerInfos = state.handlerInfos, handlerInfo, len; if (!targetHandlerInfos.length) { return false; } var targetHandler = targetHandlerInfos[targetHandlerInfos.length - 1].name; var recogHandlers = this.recognizer.handlersFor(targetHandler); var index = 0; for (len = recogHandlers.length; index < len; ++index) { handlerInfo = targetHandlerInfos[index]; if (handlerInfo.name === handlerName) { break; } } if (index === recogHandlers.length) { // The provided route name isn't even in the route hierarchy. return false; } var testState = new _routerTransitionState.default(); testState.handlerInfos = targetHandlerInfos.slice(0, index + 1); recogHandlers = recogHandlers.slice(0, index + 1); var intent = new _routerTransitionIntentNamedTransitionIntent.default({ name: targetHandler, contexts: contexts }); var newState = intent.applyToHandlers(testState, recogHandlers, this.getHandler, targetHandler, true, true, this.getSerializer); var handlersEqual = handlerInfosEqual(newState.handlerInfos, testState.handlerInfos); if (!queryParams || !handlersEqual) { return handlersEqual; } // Get a hash of QPs that will still be active on new route var activeQPsOnNewHandler = {}; _routerUtils.merge(activeQPsOnNewHandler, queryParams); var activeQueryParams = state.queryParams; for (var key in activeQueryParams) { if (activeQueryParams.hasOwnProperty(key) && activeQPsOnNewHandler.hasOwnProperty(key)) { activeQPsOnNewHandler[key] = activeQueryParams[key]; } } return handlersEqual && !_routerUtils.getChangelist(activeQPsOnNewHandler, queryParams); }, isActive: function (handlerName) { var partitionedArgs = _routerUtils.extractQueryParams(_routerUtils.slice.call(arguments, 1)); return this.isActiveIntent(handlerName, partitionedArgs[0], partitionedArgs[1]); }, trigger: function () /*name*/{ var args = _routerUtils.slice.call(arguments); _routerUtils.trigger(this, this.currentHandlerInfos, false, args); }, /** Hook point for logging transition status updates. @param {String} message The message to log. */ log: null }; /** @private Fires queryParamsDidChange event */ function fireQueryParamDidChange(router, newState, queryParamChangelist) { // If queryParams changed trigger event if (queryParamChangelist) { // This is a little hacky but we need some way of storing // changed query params given that no activeTransition // is guaranteed to have occurred. router._changedQueryParams = queryParamChangelist.all; _routerUtils.trigger(router, newState.handlerInfos, true, ['queryParamsDidChange', queryParamChangelist.changed, queryParamChangelist.all, queryParamChangelist.removed]); router._changedQueryParams = null; } } /** @private Takes an Array of `HandlerInfo`s, figures out which ones are exiting, entering, or changing contexts, and calls the proper handler hooks. For example, consider the following tree of handlers. Each handler is followed by the URL segment it handles. ``` |~index ("/") | |~posts ("/posts") | | |-showPost ("/:id") | | |-newPost ("/new") | | |-editPost ("/edit") | |~about ("/about/:id") ``` Consider the following transitions: 1. A URL transition to `/posts/1`. 1. Triggers the `*model` callbacks on the `index`, `posts`, and `showPost` handlers 2. Triggers the `enter` callback on the same 3. Triggers the `setup` callback on the same 2. A direct transition to `newPost` 1. Triggers the `exit` callback on `showPost` 2. Triggers the `enter` callback on `newPost` 3. Triggers the `setup` callback on `newPost` 3. A direct transition to `about` with a specified context object 1. Triggers the `exit` callback on `newPost` and `posts` 2. Triggers the `serialize` callback on `about` 3. Triggers the `enter` callback on `about` 4. Triggers the `setup` callback on `about` @param {Router} transition @param {TransitionState} newState */ function setupContexts(router, newState, transition) { var partition = partitionHandlers(router.state, newState); var i, l, handler; for (i = 0, l = partition.exited.length; i < l; i++) { handler = partition.exited[i].handler; delete handler.context; _routerUtils.callHook(handler, 'reset', true, transition); _routerUtils.callHook(handler, 'exit', transition); } var oldState = router.oldState = router.state; router.state = newState; var currentHandlerInfos = router.currentHandlerInfos = partition.unchanged.slice(); try { for (i = 0, l = partition.reset.length; i < l; i++) { handler = partition.reset[i].handler; _routerUtils.callHook(handler, 'reset', false, transition); } for (i = 0, l = partition.updatedContext.length; i < l; i++) { handlerEnteredOrUpdated(currentHandlerInfos, partition.updatedContext[i], false, transition); } for (i = 0, l = partition.entered.length; i < l; i++) { handlerEnteredOrUpdated(currentHandlerInfos, partition.entered[i], true, transition); } } catch (e) { router.state = oldState; router.currentHandlerInfos = oldState.handlerInfos; throw e; } router.state.queryParams = finalizeQueryParamChange(router, currentHandlerInfos, newState.queryParams, transition); } /** @private Helper method used by setupContexts. Handles errors or redirects that may happen in enter/setup. */ function handlerEnteredOrUpdated(currentHandlerInfos, handlerInfo, enter, transition) { var handler = handlerInfo.handler, context = handlerInfo.context; function _handlerEnteredOrUpdated(handler) { if (enter) { _routerUtils.callHook(handler, 'enter', transition); } if (transition && transition.isAborted) { throw new _routerTransition.TransitionAborted(); } handler.context = context; _routerUtils.callHook(handler, 'contextDidChange'); _routerUtils.callHook(handler, 'setup', context, transition); if (transition && transition.isAborted) { throw new _routerTransition.TransitionAborted(); } currentHandlerInfos.push(handlerInfo); } // If the handler doesn't exist, it means we haven't resolved the handler promise yet if (!handler) { handlerInfo.handlerPromise = handlerInfo.handlerPromise.then(_handlerEnteredOrUpdated); } else { _handlerEnteredOrUpdated(handler); } return true; } /** @private This function is called when transitioning from one URL to another to determine which handlers are no longer active, which handlers are newly active, and which handlers remain active but have their context changed. Take a list of old handlers and new handlers and partition them into four buckets: * unchanged: the handler was active in both the old and new URL, and its context remains the same * updated context: the handler was active in both the old and new URL, but its context changed. The handler's `setup` method, if any, will be called with the new context. * exited: the handler was active in the old URL, but is no longer active. * entered: the handler was not active in the old URL, but is now active. The PartitionedHandlers structure has four fields: * `updatedContext`: a list of `HandlerInfo` objects that represent handlers that remain active but have a changed context * `entered`: a list of `HandlerInfo` objects that represent handlers that are newly active * `exited`: a list of `HandlerInfo` objects that are no longer active. * `unchanged`: a list of `HanderInfo` objects that remain active. @param {Array[HandlerInfo]} oldHandlers a list of the handler information for the previous URL (or `[]` if this is the first handled transition) @param {Array[HandlerInfo]} newHandlers a list of the handler information for the new URL @return {Partition} */ function partitionHandlers(oldState, newState) { var oldHandlers = oldState.handlerInfos; var newHandlers = newState.handlerInfos; var handlers = { updatedContext: [], exited: [], entered: [], unchanged: [], reset: undefined }; var handlerChanged, contextChanged = false, i, l; for (i = 0, l = newHandlers.length; i < l; i++) { var oldHandler = oldHandlers[i], newHandler = newHandlers[i]; if (!oldHandler || oldHandler.handler !== newHandler.handler) { handlerChanged = true; } if (handlerChanged) { handlers.entered.push(newHandler); if (oldHandler) { handlers.exited.unshift(oldHandler); } } else if (contextChanged || oldHandler.context !== newHandler.context) { contextChanged = true; handlers.updatedContext.push(newHandler); } else { handlers.unchanged.push(oldHandler); } } for (i = newHandlers.length, l = oldHandlers.length; i < l; i++) { handlers.exited.unshift(oldHandlers[i]); } handlers.reset = handlers.updatedContext.slice(); handlers.reset.reverse(); return handlers; } function updateURL(transition, state /*, inputUrl*/) { var urlMethod = transition.urlMethod; if (!urlMethod) { return; } var router = transition.router, handlerInfos = state.handlerInfos, handlerName = handlerInfos[handlerInfos.length - 1].name, params = {}; for (var i = handlerInfos.length - 1; i >= 0; --i) { var handlerInfo = handlerInfos[i]; _routerUtils.merge(params, handlerInfo.params); if (handlerInfo.handler.inaccessibleByURL) { urlMethod = null; } } if (urlMethod) { params.queryParams = transition._visibleQueryParams || state.queryParams; var url = router.recognizer.generate(handlerName, params); if (urlMethod === 'replace') { router.replaceURL(url); } else { router.updateURL(url); } } } /** @private Updates the URL (if necessary) and calls `setupContexts` to update the router's array of `currentHandlerInfos`. */ function finalizeTransition(transition, newState) { try { _routerUtils.log(transition.router, transition.sequence, "Resolved all models on destination route; finalizing transition."); var router = transition.router, handlerInfos = newState.handlerInfos; // Run all the necessary enter/setup/exit hooks setupContexts(router, newState, transition); // Check if a redirect occurred in enter/setup if (transition.isAborted) { // TODO: cleaner way? distinguish b/w targetHandlerInfos? router.state.handlerInfos = router.currentHandlerInfos; return _rsvpPromise.default.reject(_routerTransition.logAbort(transition)); } updateURL(transition, newState, transition.intent.url); transition.isActive = false; router.activeTransition = null; _routerUtils.trigger(router, router.currentHandlerInfos, true, ['didTransition']); if (router.didTransition) { router.didTransition(router.currentHandlerInfos); } _routerUtils.log(router, transition.sequence, "TRANSITION COMPLETE."); // Resolve with the final handler. return handlerInfos[handlerInfos.length - 1].handler; } catch (e) { if (!(e instanceof _routerTransition.TransitionAborted)) { //var erroneousHandler = handlerInfos.pop(); var infos = transition.state.handlerInfos; transition.trigger(true, 'error', e, transition, infos[infos.length - 1].handler); transition.abort(); } throw e; } } /** @private Begins and returns a Transition based on the provided arguments. Accepts arguments in the form of both URL transitions and named transitions. @param {Router} router @param {Array[Object]} args arguments passed to transitionTo, replaceWith, or handleURL */ function doTransition(router, args, isIntermediate) { // Normalize blank transitions to root URL transitions. var name = args[0] || '/'; var lastArg = args[args.length - 1]; var queryParams = {}; if (lastArg && lastArg.hasOwnProperty('queryParams')) { queryParams = pop.call(args).queryParams; } var intent; if (args.length === 0) { _routerUtils.log(router, "Updating query params"); // A query param update is really just a transition // into the route you're already on. var handlerInfos = router.state.handlerInfos; intent = new _routerTransitionIntentNamedTransitionIntent.default({ name: handlerInfos[handlerInfos.length - 1].name, contexts: [], queryParams: queryParams }); } else if (name.charAt(0) === '/') { _routerUtils.log(router, "Attempting URL transition to " + name); intent = new _routerTransitionIntentUrlTransitionIntent.default({ url: name }); } else { _routerUtils.log(router, "Attempting transition to " + name); intent = new _routerTransitionIntentNamedTransitionIntent.default({ name: args[0], contexts: _routerUtils.slice.call(args, 1), queryParams: queryParams }); } return router.transitionByIntent(intent, isIntermediate); } function handlerInfosEqual(handlerInfos, otherHandlerInfos) { if (handlerInfos.length !== otherHandlerInfos.length) { return false; } for (var i = 0, len = handlerInfos.length; i < len; ++i) { if (handlerInfos[i] !== otherHandlerInfos[i]) { return false; } } return true; } function finalizeQueryParamChange(router, resolvedHandlers, newQueryParams, transition) { // We fire a finalizeQueryParamChange event which // gives the new route hierarchy a chance to tell // us which query params it's consuming and what // their final values are. If a query param is // no longer consumed in the final route hierarchy, // its serialized segment will be removed // from the URL. for (var k in newQueryParams) { if (newQueryParams.hasOwnProperty(k) && newQueryParams[k] === null) { delete newQueryParams[k]; } } var finalQueryParamsArray = []; _routerUtils.trigger(router, resolvedHandlers, true, ['finalizeQueryParamChange', newQueryParams, finalQueryParamsArray, transition]); if (transition) { transition._visibleQueryParams = {}; } var finalQueryParams = {}; for (var i = 0, len = finalQueryParamsArray.length; i < len; ++i) { var qp = finalQueryParamsArray[i]; finalQueryParams[qp.key] = qp.value; if (transition && qp.visible !== false) { transition._visibleQueryParams[qp.key] = qp.value; } } return finalQueryParams; } function notifyExistingHandlers(router, newState, newTransition) { var oldHandlers = router.state.handlerInfos, changing = [], leavingIndex = null, leaving, leavingChecker, i, oldHandlerLen, oldHandler, newHandler; oldHandlerLen = oldHandlers.length; for (i = 0; i < oldHandlerLen; i++) { oldHandler = oldHandlers[i]; newHandler = newState.handlerInfos[i]; if (!newHandler || oldHandler.name !== newHandler.name) { leavingIndex = i; break; } if (!newHandler.isResolved) { changing.push(oldHandler); } } if (leavingIndex !== null) { leaving = oldHandlers.slice(leavingIndex, oldHandlerLen); leavingChecker = function (name) { for (var h = 0, len = leaving.length; h < len; h++) { if (leaving[h].name === name) { return true; } } return false; }; } _routerUtils.trigger(router, oldHandlers, true, ['willTransition', newTransition]); if (router.willTransition) { router.willTransition(oldHandlers, newState.handlerInfos, newTransition); } } exports.default = Router; }); enifed("router/transition-intent", ["exports"], function (exports) { "use strict"; function TransitionIntent(props) { this.initialize(props); // TODO: wat this.data = this.data || {}; } TransitionIntent.prototype = { initialize: null, applyToState: null }; exports.default = TransitionIntent; }); enifed('router/transition-intent/named-transition-intent', ['exports', 'router/transition-intent', 'router/transition-state', 'router/handler-info/factory', 'router/utils'], function (exports, _routerTransitionIntent, _routerTransitionState, _routerHandlerInfoFactory, _routerUtils) { 'use strict'; exports.default = _routerUtils.subclass(_routerTransitionIntent.default, { name: null, pivotHandler: null, contexts: null, queryParams: null, initialize: function (props) { this.name = props.name; this.pivotHandler = props.pivotHandler; this.contexts = props.contexts || []; this.queryParams = props.queryParams; }, applyToState: function (oldState, recognizer, getHandler, isIntermediate, getSerializer) { var partitionedArgs = _routerUtils.extractQueryParams([this.name].concat(this.contexts)), pureArgs = partitionedArgs[0], handlers = recognizer.handlersFor(pureArgs[0]); var targetRouteName = handlers[handlers.length - 1].handler; return this.applyToHandlers(oldState, handlers, getHandler, targetRouteName, isIntermediate, null, getSerializer); }, applyToHandlers: function (oldState, handlers, getHandler, targetRouteName, isIntermediate, checkingIfActive, getSerializer) { var i, len; var newState = new _routerTransitionState.default(); var objects = this.contexts.slice(0); var invalidateIndex = handlers.length; // Pivot handlers are provided for refresh transitions if (this.pivotHandler) { for (i = 0, len = handlers.length; i < len; ++i) { if (handlers[i].handler === this.pivotHandler._handlerName) { invalidateIndex = i; break; } } } for (i = handlers.length - 1; i >= 0; --i) { var result = handlers[i]; var name = result.handler; var oldHandlerInfo = oldState.handlerInfos[i]; var newHandlerInfo = null; if (result.names.length > 0) { if (i >= invalidateIndex) { newHandlerInfo = this.createParamHandlerInfo(name, getHandler, result.names, objects, oldHandlerInfo); } else { var serializer = getSerializer(name); newHandlerInfo = this.getHandlerInfoForDynamicSegment(name, getHandler, result.names, objects, oldHandlerInfo, targetRouteName, i, serializer); } } else { // This route has no dynamic segment. // Therefore treat as a param-based handlerInfo // with empty params. This will cause the `model` // hook to be called with empty params, which is desirable. newHandlerInfo = this.createParamHandlerInfo(name, getHandler, result.names, objects, oldHandlerInfo); } if (checkingIfActive) { // If we're performing an isActive check, we want to // serialize URL params with the provided context, but // ignore mismatches between old and new context. newHandlerInfo = newHandlerInfo.becomeResolved(null, newHandlerInfo.context); var oldContext = oldHandlerInfo && oldHandlerInfo.context; if (result.names.length > 0 && newHandlerInfo.context === oldContext) { // If contexts match in isActive test, assume params also match. // This allows for flexibility in not requiring that every last // handler provide a `serialize` method newHandlerInfo.params = oldHandlerInfo && oldHandlerInfo.params; } newHandlerInfo.context = oldContext; } var handlerToUse = oldHandlerInfo; if (i >= invalidateIndex || newHandlerInfo.shouldSupercede(oldHandlerInfo)) { invalidateIndex = Math.min(i, invalidateIndex); handlerToUse = newHandlerInfo; } if (isIntermediate && !checkingIfActive) { handlerToUse = handlerToUse.becomeResolved(null, handlerToUse.context); } newState.handlerInfos.unshift(handlerToUse); } if (objects.length > 0) { throw new Error("More context objects were passed than there are dynamic segments for the route: " + targetRouteName); } if (!isIntermediate) { this.invalidateChildren(newState.handlerInfos, invalidateIndex); } _routerUtils.merge(newState.queryParams, this.queryParams || {}); return newState; }, invalidateChildren: function (handlerInfos, invalidateIndex) { for (var i = invalidateIndex, l = handlerInfos.length; i < l; ++i) { var handlerInfo = handlerInfos[i]; handlerInfos[i] = handlerInfo.getUnresolved(); } }, getHandlerInfoForDynamicSegment: function (name, getHandler, names, objects, oldHandlerInfo, targetRouteName, i, serializer) { var objectToUse; if (objects.length > 0) { // Use the objects provided for this transition. objectToUse = objects[objects.length - 1]; if (_routerUtils.isParam(objectToUse)) { return this.createParamHandlerInfo(name, getHandler, names, objects, oldHandlerInfo); } else { objects.pop(); } } else if (oldHandlerInfo && oldHandlerInfo.name === name) { // Reuse the matching oldHandlerInfo return oldHandlerInfo; } else { if (this.preTransitionState) { var preTransitionHandlerInfo = this.preTransitionState.handlerInfos[i]; objectToUse = preTransitionHandlerInfo && preTransitionHandlerInfo.context; } else { // Ideally we should throw this error to provide maximal // information to the user that not enough context objects // were provided, but this proves too cumbersome in Ember // in cases where inner template helpers are evaluated // before parent helpers un-render, in which cases this // error somewhat prematurely fires. //throw new Error("Not enough context objects were provided to complete a transition to " + targetRouteName + ". Specifically, the " + name + " route needs an object that can be serialized into its dynamic URL segments [" + names.join(', ') + "]"); return oldHandlerInfo; } } return _routerHandlerInfoFactory.default('object', { name: name, getHandler: getHandler, serializer: serializer, context: objectToUse, names: names }); }, createParamHandlerInfo: function (name, getHandler, names, objects, oldHandlerInfo) { var params = {}; // Soak up all the provided string/numbers var numNames = names.length; while (numNames--) { // Only use old params if the names match with the new handler var oldParams = oldHandlerInfo && name === oldHandlerInfo.name && oldHandlerInfo.params || {}; var peek = objects[objects.length - 1]; var paramName = names[numNames]; if (_routerUtils.isParam(peek)) { params[paramName] = "" + objects.pop(); } else { // If we're here, this means only some of the params // were string/number params, so try and use a param // value from a previous handler. if (oldParams.hasOwnProperty(paramName)) { params[paramName] = oldParams[paramName]; } else { throw new Error("You didn't provide enough string/numeric parameters to satisfy all of the dynamic segments for route " + name); } } } return _routerHandlerInfoFactory.default('param', { name: name, getHandler: getHandler, params: params }); } }); }); enifed('router/transition-intent/url-transition-intent', ['exports', 'router/transition-intent', 'router/transition-state', 'router/handler-info/factory', 'router/utils', 'router/unrecognized-url-error'], function (exports, _routerTransitionIntent, _routerTransitionState, _routerHandlerInfoFactory, _routerUtils, _routerUnrecognizedUrlError) { 'use strict'; exports.default = _routerUtils.subclass(_routerTransitionIntent.default, { url: null, initialize: function (props) { this.url = props.url; }, applyToState: function (oldState, recognizer, getHandler) { var newState = new _routerTransitionState.default(); var results = recognizer.recognize(this.url), i, len; if (!results) { throw new _routerUnrecognizedUrlError.default(this.url); } var statesDiffer = false; var url = this.url; // Checks if a handler is accessible by URL. If it is not, an error is thrown. // For the case where the handler is loaded asynchronously, the error will be // thrown once it is loaded. function checkHandlerAccessibility(handler) { if (handler && handler.inaccessibleByURL) { throw new _routerUnrecognizedUrlError.default(url); } return handler; } for (i = 0, len = results.length; i < len; ++i) { var result = results[i]; var name = result.handler; var newHandlerInfo = _routerHandlerInfoFactory.default('param', { name: name, getHandler: getHandler, params: result.params }); var handler = newHandlerInfo.handler; if (handler) { checkHandlerAccessibility(handler); } else { // If the hanlder is being loaded asynchronously, check if we can // access it after it has resolved newHandlerInfo.handlerPromise = newHandlerInfo.handlerPromise.then(checkHandlerAccessibility); } var oldHandlerInfo = oldState.handlerInfos[i]; if (statesDiffer || newHandlerInfo.shouldSupercede(oldHandlerInfo)) { statesDiffer = true; newState.handlerInfos[i] = newHandlerInfo; } else { newState.handlerInfos[i] = oldHandlerInfo; } } _routerUtils.merge(newState.queryParams, results.queryParams); return newState; } }); }); enifed('router/transition-state', ['exports', 'router/utils', 'rsvp/promise'], function (exports, _routerUtils, _rsvpPromise) { 'use strict'; function TransitionState() { this.handlerInfos = []; this.queryParams = {}; this.params = {}; } TransitionState.prototype = { promiseLabel: function (label) { var targetName = ''; _routerUtils.forEach(this.handlerInfos, function (handlerInfo) { if (targetName !== '') { targetName += '.'; } targetName += handlerInfo.name; }); return _routerUtils.promiseLabel("'" + targetName + "': " + label); }, resolve: function (shouldContinue, payload) { // First, calculate params for this state. This is useful // information to provide to the various route hooks. var params = this.params; _routerUtils.forEach(this.handlerInfos, function (handlerInfo) { params[handlerInfo.name] = handlerInfo.params || {}; }); payload = payload || {}; payload.resolveIndex = 0; var currentState = this; var wasAborted = false; // The prelude RSVP.resolve() asyncs us into the promise land. return _rsvpPromise.default.resolve(null, this.promiseLabel("Start transition")).then(resolveOneHandlerInfo, null, this.promiseLabel('Resolve handler'))['catch'](handleError, this.promiseLabel('Handle error')); function innerShouldContinue() { return _rsvpPromise.default.resolve(shouldContinue(), currentState.promiseLabel("Check if should continue"))['catch'](function (reason) { // We distinguish between errors that occurred // during resolution (e.g. beforeModel/model/afterModel), // and aborts due to a rejecting promise from shouldContinue(). wasAborted = true; return _rsvpPromise.default.reject(reason); }, currentState.promiseLabel("Handle abort")); } function handleError(error) { // This is the only possible // reject value of TransitionState#resolve var handlerInfos = currentState.handlerInfos; var errorHandlerIndex = payload.resolveIndex >= handlerInfos.length ? handlerInfos.length - 1 : payload.resolveIndex; return _rsvpPromise.default.reject({ error: error, handlerWithError: currentState.handlerInfos[errorHandlerIndex].handler, wasAborted: wasAborted, state: currentState }); } function proceed(resolvedHandlerInfo) { var wasAlreadyResolved = currentState.handlerInfos[payload.resolveIndex].isResolved; // Swap the previously unresolved handlerInfo with // the resolved handlerInfo currentState.handlerInfos[payload.resolveIndex++] = resolvedHandlerInfo; if (!wasAlreadyResolved) { // Call the redirect hook. The reason we call it here // vs. afterModel is so that redirects into child // routes don't re-run the model hooks for this // already-resolved route. var handler = resolvedHandlerInfo.handler; _routerUtils.callHook(handler, 'redirect', resolvedHandlerInfo.context, payload); } // Proceed after ensuring that the redirect hook // didn't abort this transition by transitioning elsewhere. return innerShouldContinue().then(resolveOneHandlerInfo, null, currentState.promiseLabel('Resolve handler')); } function resolveOneHandlerInfo() { if (payload.resolveIndex === currentState.handlerInfos.length) { // This is is the only possible // fulfill value of TransitionState#resolve return { error: null, state: currentState }; } var handlerInfo = currentState.handlerInfos[payload.resolveIndex]; return handlerInfo.resolve(innerShouldContinue, payload).then(proceed, null, currentState.promiseLabel('Proceed')); } } }; exports.default = TransitionState; }); enifed('router/transition', ['exports', 'rsvp/promise', 'router/utils'], function (exports, _rsvpPromise, _routerUtils) { 'use strict'; /** A Transition is a thennable (a promise-like object) that represents an attempt to transition to another route. It can be aborted, either explicitly via `abort` or by attempting another transition while a previous one is still underway. An aborted transition can also be `retry()`d later. @class Transition @constructor @param {Object} router @param {Object} intent @param {Object} state @param {Object} error @private */ function Transition(router, intent, state, error) { var transition = this; this.state = state || router.state; this.intent = intent; this.router = router; this.data = this.intent && this.intent.data || {}; this.resolvedModels = {}; this.queryParams = {}; this.promise = undefined; this.error = undefined; this.params = undefined; this.handlerInfos = undefined; this.targetName = undefined; this.pivotHandler = undefined; this.sequence = undefined; this.isAborted = undefined; this.isActive = undefined; if (error) { this.promise = _rsvpPromise.default.reject(error); this.error = error; return; } if (state) { this.params = state.params; this.queryParams = state.queryParams; this.handlerInfos = state.handlerInfos; var len = state.handlerInfos.length; if (len) { this.targetName = state.handlerInfos[len - 1].name; } for (var i = 0; i < len; ++i) { var handlerInfo = state.handlerInfos[i]; // TODO: this all seems hacky if (!handlerInfo.isResolved) { break; } this.pivotHandler = handlerInfo.handler; } this.sequence = Transition.currentSequence++; this.promise = state.resolve(checkForAbort, this)['catch'](function (result) { if (result.wasAborted || transition.isAborted) { return _rsvpPromise.default.reject(logAbort(transition)); } else { transition.trigger('error', result.error, transition, result.handlerWithError); transition.abort(); return _rsvpPromise.default.reject(result.error); } }, _routerUtils.promiseLabel('Handle Abort')); } else { this.promise = _rsvpPromise.default.resolve(this.state); this.params = {}; } function checkForAbort() { if (transition.isAborted) { return _rsvpPromise.default.reject(undefined, _routerUtils.promiseLabel("Transition aborted - reject")); } } } Transition.currentSequence = 0; Transition.prototype = { targetName: null, urlMethod: 'update', intent: null, pivotHandler: null, resolveIndex: 0, resolvedModels: null, isActive: true, state: null, queryParamsOnly: false, isTransition: true, isExiting: function (handler) { var handlerInfos = this.handlerInfos; for (var i = 0, len = handlerInfos.length; i < len; ++i) { var handlerInfo = handlerInfos[i]; if (handlerInfo.name === handler || handlerInfo.handler === handler) { return false; } } return true; }, /** The Transition's internal promise. Calling `.then` on this property is that same as calling `.then` on the Transition object itself, but this property is exposed for when you want to pass around a Transition's promise, but not the Transition object itself, since Transition object can be externally `abort`ed, while the promise cannot. @property promise @type {Object} @public */ promise: null, /** Custom state can be stored on a Transition's `data` object. This can be useful for decorating a Transition within an earlier hook and shared with a later hook. Properties set on `data` will be copied to new transitions generated by calling `retry` on this transition. @property data @type {Object} @public */ data: null, /** A standard promise hook that resolves if the transition succeeds and rejects if it fails/redirects/aborts. Forwards to the internal `promise` property which you can use in situations where you want to pass around a thennable, but not the Transition itself. @method then @param {Function} onFulfilled @param {Function} onRejected @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} @public */ then: function (onFulfilled, onRejected, label) { return this.promise.then(onFulfilled, onRejected, label); }, /** Forwards to the internal `promise` property which you can use in situations where you want to pass around a thennable, but not the Transition itself. @method catch @param {Function} onRejection @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} @public */ catch: function (onRejection, label) { return this.promise.catch(onRejection, label); }, /** Forwards to the internal `promise` property which you can use in situations where you want to pass around a thennable, but not the Transition itself. @method finally @param {Function} callback @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} @public */ finally: function (callback, label) { return this.promise.finally(callback, label); }, /** Aborts the Transition. Note you can also implicitly abort a transition by initiating another transition while a previous one is underway. @method abort @return {Transition} this transition @public */ abort: function () { if (this.isAborted) { return this; } _routerUtils.log(this.router, this.sequence, this.targetName + ": transition was aborted"); this.intent.preTransitionState = this.router.state; this.isAborted = true; this.isActive = false; this.router.activeTransition = null; return this; }, /** Retries a previously-aborted transition (making sure to abort the transition if it's still active). Returns a new transition that represents the new attempt to transition. @method retry @return {Transition} new transition @public */ retry: function () { // TODO: add tests for merged state retry()s this.abort(); return this.router.transitionByIntent(this.intent, false); }, /** Sets the URL-changing method to be employed at the end of a successful transition. By default, a new Transition will just use `updateURL`, but passing 'replace' to this method will cause the URL to update using 'replaceWith' instead. Omitting a parameter will disable the URL change, allowing for transitions that don't update the URL at completion (this is also used for handleURL, since the URL has already changed before the transition took place). @method method @param {String} method the type of URL-changing method to use at the end of a transition. Accepted values are 'replace', falsy values, or any other non-falsy value (which is interpreted as an updateURL transition). @return {Transition} this transition @public */ method: function (method) { this.urlMethod = method; return this; }, /** Fires an event on the current list of resolved/resolving handlers within this transition. Useful for firing events on route hierarchies that haven't fully been entered yet. Note: This method is also aliased as `send` @method trigger @param {Boolean} [ignoreFailure=false] a boolean specifying whether unhandled events throw an error @param {String} name the name of the event to fire @public */ trigger: function (ignoreFailure) { var args = _routerUtils.slice.call(arguments); if (typeof ignoreFailure === 'boolean') { args.shift(); } else { // Throw errors on unhandled trigger events by default ignoreFailure = false; } _routerUtils.trigger(this.router, this.state.handlerInfos.slice(0, this.resolveIndex + 1), ignoreFailure, args); }, /** Transitions are aborted and their promises rejected when redirects occur; this method returns a promise that will follow any redirects that occur and fulfill with the value fulfilled by any redirecting transitions that occur. @method followRedirects @return {Promise} a promise that fulfills with the same value that the final redirecting transition fulfills with @public */ followRedirects: function () { var router = this.router; return this.promise['catch'](function (reason) { if (router.activeTransition) { return router.activeTransition.followRedirects(); } return _rsvpPromise.default.reject(reason); }); }, toString: function () { return "Transition (sequence " + this.sequence + ")"; }, /** @private */ log: function (message) { _routerUtils.log(this.router, this.sequence, message); } }; // Alias 'trigger' as 'send' Transition.prototype.send = Transition.prototype.trigger; /** @private Logs and returns a TransitionAborted error. */ function logAbort(transition) { _routerUtils.log(transition.router, transition.sequence, "detected abort."); return new TransitionAborted(); } function TransitionAborted(message) { this.message = message || "TransitionAborted"; this.name = "TransitionAborted"; } exports.Transition = Transition; exports.logAbort = logAbort; exports.TransitionAborted = TransitionAborted; }); enifed("router/unrecognized-url-error", ["exports", "router/utils"], function (exports, _routerUtils) { "use strict"; /** Promise reject reasons passed to promise rejection handlers for failed transitions. */ function UnrecognizedURLError(message) { this.message = message || "UnrecognizedURLError"; this.name = "UnrecognizedURLError"; Error.call(this); } UnrecognizedURLError.prototype = _routerUtils.oCreate(Error.prototype); exports.default = UnrecognizedURLError; }); enifed('router/utils', ['exports'], function (exports) { 'use strict'; exports.isPromise = isPromise; exports.extractQueryParams = extractQueryParams; exports.log = log; exports.bind = bind; exports.forEach = forEach; exports.trigger = trigger; exports.getChangelist = getChangelist; exports.promiseLabel = promiseLabel; exports.subclass = subclass; var slice = Array.prototype.slice; var _isArray; if (!Array.isArray) { _isArray = function (x) { return Object.prototype.toString.call(x) === "[object Array]"; }; } else { _isArray = Array.isArray; } var isArray = _isArray; exports.isArray = isArray; /** Determines if an object is Promise by checking if it is "thenable". **/ function isPromise(obj) { return (typeof obj === 'object' && obj !== null || typeof obj === 'function') && typeof obj.then === 'function'; } function merge(hash, other) { for (var prop in other) { if (other.hasOwnProperty(prop)) { hash[prop] = other[prop]; } } } var oCreate = Object.create || function (proto) { function F() {} F.prototype = proto; return new F(); }; exports.oCreate = oCreate; /** @private Extracts query params from the end of an array **/ function extractQueryParams(array) { var len = array && array.length, head, queryParams; if (len && len > 0 && array[len - 1] && array[len - 1].hasOwnProperty('queryParams')) { queryParams = array[len - 1].queryParams; head = slice.call(array, 0, len - 1); return [head, queryParams]; } else { return [array, null]; } } /** @private Coerces query param properties and array elements into strings. **/ function coerceQueryParamsToString(queryParams) { for (var key in queryParams) { if (typeof queryParams[key] === 'number') { queryParams[key] = '' + queryParams[key]; } else if (isArray(queryParams[key])) { for (var i = 0, l = queryParams[key].length; i < l; i++) { queryParams[key][i] = '' + queryParams[key][i]; } } } } /** @private */ function log(router, sequence, msg) { if (!router.log) { return; } if (arguments.length === 3) { router.log("Transition #" + sequence + ": " + msg); } else { msg = sequence; router.log(msg); } } function bind(context, fn) { var boundArgs = arguments; return function (value) { var args = slice.call(boundArgs, 2); args.push(value); return fn.apply(context, args); }; } function isParam(object) { return typeof object === "string" || object instanceof String || typeof object === "number" || object instanceof Number; } function forEach(array, callback) { for (var i = 0, l = array.length; i < l && false !== callback(array[i]); i++) {} } function trigger(router, handlerInfos, ignoreFailure, args) { if (router.triggerEvent) { router.triggerEvent(handlerInfos, ignoreFailure, args); return; } var name = args.shift(); if (!handlerInfos) { if (ignoreFailure) { return; } throw new Error("Could not trigger event '" + name + "'. There are no active handlers"); } var eventWasHandled = false; function delayedEvent(name, args, handler) { handler.events[name].apply(handler, args); } for (var i = handlerInfos.length - 1; i >= 0; i--) { var handlerInfo = handlerInfos[i], handler = handlerInfo.handler; // If there is no handler, it means the handler hasn't resolved yet which // means that we should trigger the event later when the handler is available if (!handler) { handlerInfo.handlerPromise.then(bind(null, delayedEvent, name, args)); continue; } if (handler.events && handler.events[name]) { if (handler.events[name].apply(handler, args) === true) { eventWasHandled = true; } else { return; } } } // In the case that we got an UnrecognizedURLError as an event with no handler, // let it bubble up if (name === 'error' && args[0].name === 'UnrecognizedURLError') { throw args[0]; } else if (!eventWasHandled && !ignoreFailure) { throw new Error("Nothing handled the event '" + name + "'."); } } function getChangelist(oldObject, newObject) { var key; var results = { all: {}, changed: {}, removed: {} }; merge(results.all, newObject); var didChange = false; coerceQueryParamsToString(oldObject); coerceQueryParamsToString(newObject); // Calculate removals for (key in oldObject) { if (oldObject.hasOwnProperty(key)) { if (!newObject.hasOwnProperty(key)) { didChange = true; results.removed[key] = oldObject[key]; } } } // Calculate changes for (key in newObject) { if (newObject.hasOwnProperty(key)) { if (isArray(oldObject[key]) && isArray(newObject[key])) { if (oldObject[key].length !== newObject[key].length) { results.changed[key] = newObject[key]; didChange = true; } else { for (var i = 0, l = oldObject[key].length; i < l; i++) { if (oldObject[key][i] !== newObject[key][i]) { results.changed[key] = newObject[key]; didChange = true; } } } } else { if (oldObject[key] !== newObject[key]) { results.changed[key] = newObject[key]; didChange = true; } } } } return didChange && results; } function promiseLabel(label) { return 'Router: ' + label; } function subclass(parentConstructor, proto) { function C(props) { parentConstructor.call(this, props || {}); } C.prototype = oCreate(parentConstructor.prototype); merge(C.prototype, proto); return C; } function resolveHook(obj, hookName) { if (!obj) { return; } var underscored = "_" + hookName; return obj[underscored] && underscored || obj[hookName] && hookName; } function callHook(obj, _hookName, arg1, arg2) { var hookName = resolveHook(obj, _hookName); return hookName && obj[hookName].call(obj, arg1, arg2); } function applyHook(obj, _hookName, args) { var hookName = resolveHook(obj, _hookName); if (hookName) { if (args.length === 0) { return obj[hookName].call(obj); } else if (args.length === 1) { return obj[hookName].call(obj, args[0]); } else if (args.length === 2) { return obj[hookName].call(obj, args[0], args[1]); } else { return obj[hookName].apply(obj, args); } } } exports.merge = merge; exports.slice = slice; exports.isParam = isParam; exports.coerceQueryParamsToString = coerceQueryParamsToString; exports.callHook = callHook; exports.resolveHook = resolveHook; exports.applyHook = applyHook; }); enifed('rsvp', ['exports', 'rsvp/promise', 'rsvp/events', 'rsvp/node', 'rsvp/all', 'rsvp/all-settled', 'rsvp/race', 'rsvp/hash', 'rsvp/hash-settled', 'rsvp/rethrow', 'rsvp/defer', 'rsvp/config', 'rsvp/map', 'rsvp/resolve', 'rsvp/reject', 'rsvp/filter', 'rsvp/asap'], function (exports, _rsvpPromise, _rsvpEvents, _rsvpNode, _rsvpAll, _rsvpAllSettled, _rsvpRace, _rsvpHash, _rsvpHashSettled, _rsvpRethrow, _rsvpDefer, _rsvpConfig, _rsvpMap, _rsvpResolve, _rsvpReject, _rsvpFilter, _rsvpAsap) { 'use strict'; // defaults _rsvpConfig.config.async = _rsvpAsap.default; _rsvpConfig.config.after = function (cb) { setTimeout(cb, 0); }; var cast = _rsvpResolve.default; function async(callback, arg) { _rsvpConfig.config.async(callback, arg); } function on() { _rsvpConfig.config['on'].apply(_rsvpConfig.config, arguments); } function off() { _rsvpConfig.config['off'].apply(_rsvpConfig.config, arguments); } // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') { var callbacks = window['__PROMISE_INSTRUMENTATION__']; _rsvpConfig.configure('instrument', true); for (var eventName in callbacks) { if (callbacks.hasOwnProperty(eventName)) { on(eventName, callbacks[eventName]); } } } exports.cast = cast; exports.Promise = _rsvpPromise.default; exports.EventTarget = _rsvpEvents.default; exports.all = _rsvpAll.default; exports.allSettled = _rsvpAllSettled.default; exports.race = _rsvpRace.default; exports.hash = _rsvpHash.default; exports.hashSettled = _rsvpHashSettled.default; exports.rethrow = _rsvpRethrow.default; exports.defer = _rsvpDefer.default; exports.denodeify = _rsvpNode.default; exports.configure = _rsvpConfig.configure; exports.on = on; exports.off = off; exports.resolve = _rsvpResolve.default; exports.reject = _rsvpReject.default; exports.async = async; exports.map = _rsvpMap.default; exports.filter = _rsvpFilter.default; }); enifed('rsvp.umd', ['exports', 'rsvp/platform', 'rsvp'], function (exports, _rsvpPlatform, _rsvp) { 'use strict'; var RSVP = { 'race': _rsvp.race, 'Promise': _rsvp.Promise, 'allSettled': _rsvp.allSettled, 'hash': _rsvp.hash, 'hashSettled': _rsvp.hashSettled, 'denodeify': _rsvp.denodeify, 'on': _rsvp.on, 'off': _rsvp.off, 'map': _rsvp.map, 'filter': _rsvp.filter, 'resolve': _rsvp.resolve, 'reject': _rsvp.reject, 'all': _rsvp.all, 'rethrow': _rsvp.rethrow, 'defer': _rsvp.defer, 'EventTarget': _rsvp.EventTarget, 'configure': _rsvp.configure, 'async': _rsvp.async }; /* global define:true module:true window: true */ if (typeof define === 'function' && define['amd']) { define(function () { return RSVP; }); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = RSVP; } else if (typeof _rsvpPlatform.default !== 'undefined') { _rsvpPlatform.default['RSVP'] = RSVP; } }); enifed('rsvp/-internal', ['exports', 'rsvp/utils', 'rsvp/instrument', 'rsvp/config'], function (exports, _rsvpUtils, _rsvpInstrument, _rsvpConfig) { 'use strict'; function withOwnPromise() { return new TypeError('A promises callback cannot return that same promise.'); } function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var GET_THEN_ERROR = new ErrorObject(); function getThen(promise) { try { return promise.then; } catch (error) { GET_THEN_ERROR.error = error; return GET_THEN_ERROR; } } function tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then) { _rsvpConfig.config.async(function (promise) { var sealed = false; var error = tryThen(then, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { thenable._onError = null; reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { if (thenable !== value) { resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { handleOwnThenable(promise, maybeThenable); } else { var then = getThen(maybeThenable); if (then === GET_THEN_ERROR) { reject(promise, GET_THEN_ERROR.error); } else if (then === undefined) { fulfill(promise, maybeThenable); } else if (_rsvpUtils.isFunction(then)) { handleForeignThenable(promise, maybeThenable, then); } else { fulfill(promise, maybeThenable); } } } function resolve(promise, value) { if (promise === value) { fulfill(promise, value); } else if (_rsvpUtils.objectOrFunction(value)) { handleMaybeThenable(promise, value); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onError) { promise._onError(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length === 0) { if (_rsvpConfig.config.instrument) { _rsvpInstrument.default('fulfilled', promise); } } else { _rsvpConfig.config.async(publish, promise); } } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; _rsvpConfig.config.async(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onError = null; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { _rsvpConfig.config.async(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (_rsvpConfig.config.instrument) { _rsvpInstrument.default(settled === FULFILLED ? 'fulfilled' : 'rejected', promise); } if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function ErrorObject() { this.error = null; } var TRY_CATCH_ERROR = new ErrorObject(); function tryCatch(callback, detail) { try { return callback(detail); } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR; } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = _rsvpUtils.isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { reject(promise, withOwnPromise()); return; } } else { value = detail; succeeded = true; } if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { fulfill(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } function initializePromise(promise, resolver) { var resolved = false; try { resolver(function resolvePromise(value) { if (resolved) { return; } resolved = true; resolve(promise, value); }, function rejectPromise(reason) { if (resolved) { return; } resolved = true; reject(promise, reason); }); } catch (e) { reject(promise, e); } } exports.noop = noop; exports.resolve = resolve; exports.reject = reject; exports.fulfill = fulfill; exports.subscribe = subscribe; exports.publish = publish; exports.publishRejection = publishRejection; exports.initializePromise = initializePromise; exports.invokeCallback = invokeCallback; exports.FULFILLED = FULFILLED; exports.REJECTED = REJECTED; exports.PENDING = PENDING; }); enifed('rsvp/all-settled', ['exports', 'rsvp/enumerator', 'rsvp/promise', 'rsvp/utils'], function (exports, _rsvpEnumerator, _rsvpPromise, _rsvpUtils) { 'use strict'; exports.default = allSettled; function AllSettled(Constructor, entries, label) { this._superConstructor(Constructor, entries, false, /* don't abort on reject */label); } AllSettled.prototype = _rsvpUtils.o_create(_rsvpEnumerator.default.prototype); AllSettled.prototype._superConstructor = _rsvpEnumerator.default; AllSettled.prototype._makeResult = _rsvpEnumerator.makeSettledResult; AllSettled.prototype._validationError = function () { return new Error('allSettled must be called with an array'); }; /** `RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing a fail-fast method, it waits until all the promises have returned and shows you all the results. This is useful if you want to handle multiple promises' failure states together as a set. Returns a promise that is fulfilled when all the given promises have been settled. The return promise is fulfilled with an array of the states of the promises passed into the `promises` array argument. Each state object will either indicate fulfillment or rejection, and provide the corresponding value or reason. The states will take one of the following formats: ```javascript { state: 'fulfilled', value: value } or { state: 'rejected', reason: reason } ``` Example: ```javascript var promise1 = RSVP.Promise.resolve(1); var promise2 = RSVP.Promise.reject(new Error('2')); var promise3 = RSVP.Promise.reject(new Error('3')); var promises = [ promise1, promise2, promise3 ]; RSVP.allSettled(promises).then(function(array){ // array == [ // { state: 'fulfilled', value: 1 }, // { state: 'rejected', reason: Error }, // { state: 'rejected', reason: Error } // ] // Note that for the second item, reason.message will be '2', and for the // third item, reason.message will be '3'. }, function(error) { // Not run. (This block would only be called if allSettled had failed, // for instance if passed an incorrect argument type.) }); ``` @method allSettled @static @for RSVP @param {Array} entries @param {String} label - optional string that describes the promise. Useful for tooling. @return {Promise} promise that is fulfilled with an array of the settled states of the constituent promises. */ function allSettled(entries, label) { return new AllSettled(_rsvpPromise.default, entries, label).promise; } }); enifed("rsvp/all", ["exports", "rsvp/promise"], function (exports, _rsvpPromise) { "use strict"; exports.default = all; /** This is a convenient alias for `RSVP.Promise.all`. @method all @static @for RSVP @param {Array} array Array of promises. @param {String} label An optional label. This is useful for tooling. */ function all(array, label) { return _rsvpPromise.default.all(array, label); } }); enifed('rsvp/asap', ['exports'], function (exports) { 'use strict'; exports.default = asap; var len = 0; var toString = ({}).toString; var vertxNext; function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // If len is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. scheduleFlush(); } } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof window === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { var nextTick = process.nextTick; // node version 0.10.x displays a deprecation warning when nextTick is used recursively // setImmediate should be used instead instead var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { nextTick = setImmediate; } return function () { nextTick(flush); }; } // vertx function useVertxTimer() { return function () { vertxNext(flush); }; } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function () { node.data = iterations = ++iterations % 2; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { channel.port2.postMessage(0); }; } function useSetTimeout() { return function () { setTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptVertex() { try { var r = require; var vertx = r('vertx'); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else if (browserWindow === undefined && typeof require === 'function') { scheduleFlush = attemptVertex(); } else { scheduleFlush = useSetTimeout(); } }); enifed('rsvp/config', ['exports', 'rsvp/events'], function (exports, _rsvpEvents) { 'use strict'; var config = { instrument: false }; _rsvpEvents.default['mixin'](config); function configure(name, value) { if (name === 'onerror') { // handle for legacy users that expect the actual // error to be passed to their function added via // `RSVP.configure('onerror', someFunctionHere);` config['on']('error', value); return; } if (arguments.length === 2) { config[name] = value; } else { return config[name]; } } exports.config = config; exports.configure = configure; }); enifed('rsvp/defer', ['exports', 'rsvp/promise'], function (exports, _rsvpPromise) { 'use strict'; exports.default = defer; /** `RSVP.defer` returns an object similar to jQuery's `$.Deferred`. `RSVP.defer` should be used when porting over code reliant on `$.Deferred`'s interface. New code should use the `RSVP.Promise` constructor instead. The object returned from `RSVP.defer` is a plain object with three properties: * promise - an `RSVP.Promise`. * reject - a function that causes the `promise` property on this object to become rejected * resolve - a function that causes the `promise` property on this object to become fulfilled. Example: ```javascript var deferred = RSVP.defer(); deferred.resolve("Success!"); deferred.promise.then(function(value){ // value here is "Success!" }); ``` @method defer @static @for RSVP @param {String} label optional string for labeling the promise. Useful for tooling. @return {Object} */ function defer(label) { var deferred = {}; deferred['promise'] = new _rsvpPromise.default(function (resolve, reject) { deferred['resolve'] = resolve; deferred['reject'] = reject; }, label); return deferred; } }); enifed('rsvp/enumerator', ['exports', 'rsvp/utils', 'rsvp/-internal'], function (exports, _rsvpUtils, _rsvpInternal) { 'use strict'; exports.makeSettledResult = makeSettledResult; function makeSettledResult(state, position, value) { if (state === _rsvpInternal.FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } function Enumerator(Constructor, input, abortOnReject, label) { var enumerator = this; enumerator._instanceConstructor = Constructor; enumerator.promise = new Constructor(_rsvpInternal.noop, label); enumerator._abortOnReject = abortOnReject; if (enumerator._validateInput(input)) { enumerator._input = input; enumerator.length = input.length; enumerator._remaining = input.length; enumerator._init(); if (enumerator.length === 0) { _rsvpInternal.fulfill(enumerator.promise, enumerator._result); } else { enumerator.length = enumerator.length || 0; enumerator._enumerate(); if (enumerator._remaining === 0) { _rsvpInternal.fulfill(enumerator.promise, enumerator._result); } } } else { _rsvpInternal.reject(enumerator.promise, enumerator._validationError()); } } exports.default = Enumerator; Enumerator.prototype._validateInput = function (input) { return _rsvpUtils.isArray(input); }; Enumerator.prototype._validationError = function () { return new Error('Array Methods must be provided an Array'); }; Enumerator.prototype._init = function () { this._result = new Array(this.length); }; Enumerator.prototype._enumerate = function () { var enumerator = this; var length = enumerator.length; var promise = enumerator.promise; var input = enumerator._input; for (var i = 0; promise._state === _rsvpInternal.PENDING && i < length; i++) { enumerator._eachEntry(input[i], i); } }; Enumerator.prototype._eachEntry = function (entry, i) { var enumerator = this; var c = enumerator._instanceConstructor; if (_rsvpUtils.isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== _rsvpInternal.PENDING) { entry._onError = null; enumerator._settledAt(entry._state, i, entry._result); } else { enumerator._willSettleAt(c.resolve(entry), i); } } else { enumerator._remaining--; enumerator._result[i] = enumerator._makeResult(_rsvpInternal.FULFILLED, i, entry); } }; Enumerator.prototype._settledAt = function (state, i, value) { var enumerator = this; var promise = enumerator.promise; if (promise._state === _rsvpInternal.PENDING) { enumerator._remaining--; if (enumerator._abortOnReject && state === _rsvpInternal.REJECTED) { _rsvpInternal.reject(promise, value); } else { enumerator._result[i] = enumerator._makeResult(state, i, value); } } if (enumerator._remaining === 0) { _rsvpInternal.fulfill(promise, enumerator._result); } }; Enumerator.prototype._makeResult = function (state, i, value) { return value; }; Enumerator.prototype._willSettleAt = function (promise, i) { var enumerator = this; _rsvpInternal.subscribe(promise, undefined, function (value) { enumerator._settledAt(_rsvpInternal.FULFILLED, i, value); }, function (reason) { enumerator._settledAt(_rsvpInternal.REJECTED, i, reason); }); }; }); enifed('rsvp/events', ['exports'], function (exports) { 'use strict'; function indexOf(callbacks, callback) { for (var i = 0, l = callbacks.length; i < l; i++) { if (callbacks[i] === callback) { return i; } } return -1; } function callbacksFor(object) { var callbacks = object._promiseCallbacks; if (!callbacks) { callbacks = object._promiseCallbacks = {}; } return callbacks; } /** @class RSVP.EventTarget */ exports.default = { /** `RSVP.EventTarget.mixin` extends an object with EventTarget methods. For Example: ```javascript var object = {}; RSVP.EventTarget.mixin(object); object.on('finished', function(event) { // handle event }); object.trigger('finished', { detail: value }); ``` `EventTarget.mixin` also works with prototypes: ```javascript var Person = function() {}; RSVP.EventTarget.mixin(Person.prototype); var yehuda = new Person(); var tom = new Person(); yehuda.on('poke', function(event) { console.log('Yehuda says OW'); }); tom.on('poke', function(event) { console.log('Tom says OW'); }); yehuda.trigger('poke'); tom.trigger('poke'); ``` @method mixin @for RSVP.EventTarget @private @param {Object} object object to extend with EventTarget methods */ 'mixin': function (object) { object['on'] = this['on']; object['off'] = this['off']; object['trigger'] = this['trigger']; object._promiseCallbacks = undefined; return object; }, /** Registers a callback to be executed when `eventName` is triggered ```javascript object.on('event', function(eventInfo){ // handle the event }); object.trigger('event'); ``` @method on @for RSVP.EventTarget @private @param {String} eventName name of the event to listen for @param {Function} callback function to be called when the event is triggered. */ 'on': function (eventName, callback) { if (typeof callback !== 'function') { throw new TypeError('Callback must be a function'); } var allCallbacks = callbacksFor(this), callbacks; callbacks = allCallbacks[eventName]; if (!callbacks) { callbacks = allCallbacks[eventName] = []; } if (indexOf(callbacks, callback) === -1) { callbacks.push(callback); } }, /** You can use `off` to stop firing a particular callback for an event: ```javascript function doStuff() { // do stuff! } object.on('stuff', doStuff); object.trigger('stuff'); // doStuff will be called // Unregister ONLY the doStuff callback object.off('stuff', doStuff); object.trigger('stuff'); // doStuff will NOT be called ``` If you don't pass a `callback` argument to `off`, ALL callbacks for the event will not be executed when the event fires. For example: ```javascript var callback1 = function(){}; var callback2 = function(){}; object.on('stuff', callback1); object.on('stuff', callback2); object.trigger('stuff'); // callback1 and callback2 will be executed. object.off('stuff'); object.trigger('stuff'); // callback1 and callback2 will not be executed! ``` @method off @for RSVP.EventTarget @private @param {String} eventName event to stop listening to @param {Function} callback optional argument. If given, only the function given will be removed from the event's callback queue. If no `callback` argument is given, all callbacks will be removed from the event's callback queue. */ 'off': function (eventName, callback) { var allCallbacks = callbacksFor(this), callbacks, index; if (!callback) { allCallbacks[eventName] = []; return; } callbacks = allCallbacks[eventName]; index = indexOf(callbacks, callback); if (index !== -1) { callbacks.splice(index, 1); } }, /** Use `trigger` to fire custom events. For example: ```javascript object.on('foo', function(){ console.log('foo event happened!'); }); object.trigger('foo'); // 'foo event happened!' logged to the console ``` You can also pass a value as a second argument to `trigger` that will be passed as an argument to all event listeners for the event: ```javascript object.on('foo', function(value){ console.log(value.name); }); object.trigger('foo', { name: 'bar' }); // 'bar' logged to the console ``` @method trigger @for RSVP.EventTarget @private @param {String} eventName name of the event to be triggered @param {*} options optional value to be passed to any event handlers for the given `eventName` */ 'trigger': function (eventName, options) { var allCallbacks = callbacksFor(this), callbacks, callback; if (callbacks = allCallbacks[eventName]) { // Don't cache the callbacks.length since it may grow for (var i = 0; i < callbacks.length; i++) { callback = callbacks[i]; callback(options); } } } }; }); enifed('rsvp/filter', ['exports', 'rsvp/promise', 'rsvp/utils'], function (exports, _rsvpPromise, _rsvpUtils) { 'use strict'; exports.default = filter; /** `RSVP.filter` is similar to JavaScript's native `filter` method, except that it waits for all promises to become fulfilled before running the `filterFn` on each item in given to `promises`. `RSVP.filter` returns a promise that will become fulfilled with the result of running `filterFn` on the values the promises become fulfilled with. For example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [promise1, promise2, promise3]; var filterFn = function(item){ return item > 1; }; RSVP.filter(promises, filterFn).then(function(result){ // result is [ 2, 3 ] }); ``` If any of the `promises` given to `RSVP.filter` are rejected, the first promise that is rejected will be given as an argument to the returned promise's rejection handler. For example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error('2')); var promise3 = RSVP.reject(new Error('3')); var promises = [ promise1, promise2, promise3 ]; var filterFn = function(item){ return item > 1; }; RSVP.filter(promises, filterFn).then(function(array){ // Code here never runs because there are rejected promises! }, function(reason) { // reason.message === '2' }); ``` `RSVP.filter` will also wait for any promises returned from `filterFn`. For instance, you may want to fetch a list of users then return a subset of those users based on some asynchronous operation: ```javascript var alice = { name: 'alice' }; var bob = { name: 'bob' }; var users = [ alice, bob ]; var promises = users.map(function(user){ return RSVP.resolve(user); }); var filterFn = function(user){ // Here, Alice has permissions to create a blog post, but Bob does not. return getPrivilegesForUser(user).then(function(privs){ return privs.can_create_blog_post === true; }); }; RSVP.filter(promises, filterFn).then(function(users){ // true, because the server told us only Alice can create a blog post. users.length === 1; // false, because Alice is the only user present in `users` users[0] === bob; }); ``` @method filter @static @for RSVP @param {Array} promises @param {Function} filterFn - function to be called on each resolved value to filter the final results. @param {String} label optional string describing the promise. Useful for tooling. @return {Promise} */ function filter(promises, filterFn, label) { return _rsvpPromise.default.all(promises, label).then(function (values) { if (!_rsvpUtils.isFunction(filterFn)) { throw new TypeError("You must pass a function as filter's second argument."); } var length = values.length; var filtered = new Array(length); for (var i = 0; i < length; i++) { filtered[i] = filterFn(values[i]); } return _rsvpPromise.default.all(filtered, label).then(function (filtered) { var results = new Array(length); var newLength = 0; for (var i = 0; i < length; i++) { if (filtered[i]) { results[newLength] = values[i]; newLength++; } } results.length = newLength; return results; }); }); } }); enifed('rsvp/hash-settled', ['exports', 'rsvp/promise', 'rsvp/enumerator', 'rsvp/promise-hash', 'rsvp/utils'], function (exports, _rsvpPromise, _rsvpEnumerator, _rsvpPromiseHash, _rsvpUtils) { 'use strict'; exports.default = hashSettled; function HashSettled(Constructor, object, label) { this._superConstructor(Constructor, object, false, label); } HashSettled.prototype = _rsvpUtils.o_create(_rsvpPromiseHash.default.prototype); HashSettled.prototype._superConstructor = _rsvpEnumerator.default; HashSettled.prototype._makeResult = _rsvpEnumerator.makeSettledResult; HashSettled.prototype._validationError = function () { return new Error('hashSettled must be called with an object'); }; /** `RSVP.hashSettled` is similar to `RSVP.allSettled`, but takes an object instead of an array for its `promises` argument. Unlike `RSVP.all` or `RSVP.hash`, which implement a fail-fast method, but like `RSVP.allSettled`, `hashSettled` waits until all the constituent promises have returned and then shows you all the results with their states and values/reasons. This is useful if you want to handle multiple promises' failure states together as a set. Returns a promise that is fulfilled when all the given promises have been settled, or rejected if the passed parameters are invalid. The returned promise is fulfilled with a hash that has the same key names as the `promises` object argument. If any of the values in the object are not promises, they will be copied over to the fulfilled object and marked with state 'fulfilled'. Example: ```javascript var promises = { myPromise: RSVP.Promise.resolve(1), yourPromise: RSVP.Promise.resolve(2), theirPromise: RSVP.Promise.resolve(3), notAPromise: 4 }; RSVP.hashSettled(promises).then(function(hash){ // hash here is an object that looks like: // { // myPromise: { state: 'fulfilled', value: 1 }, // yourPromise: { state: 'fulfilled', value: 2 }, // theirPromise: { state: 'fulfilled', value: 3 }, // notAPromise: { state: 'fulfilled', value: 4 } // } }); ``` If any of the `promises` given to `RSVP.hash` are rejected, the state will be set to 'rejected' and the reason for rejection provided. Example: ```javascript var promises = { myPromise: RSVP.Promise.resolve(1), rejectedPromise: RSVP.Promise.reject(new Error('rejection')), anotherRejectedPromise: RSVP.Promise.reject(new Error('more rejection')), }; RSVP.hashSettled(promises).then(function(hash){ // hash here is an object that looks like: // { // myPromise: { state: 'fulfilled', value: 1 }, // rejectedPromise: { state: 'rejected', reason: Error }, // anotherRejectedPromise: { state: 'rejected', reason: Error }, // } // Note that for rejectedPromise, reason.message == 'rejection', // and for anotherRejectedPromise, reason.message == 'more rejection'. }); ``` An important note: `RSVP.hashSettled` is intended for plain JavaScript objects that are just a set of keys and values. `RSVP.hashSettled` will NOT preserve prototype chains. Example: ```javascript function MyConstructor(){ this.example = RSVP.Promise.resolve('Example'); } MyConstructor.prototype = { protoProperty: RSVP.Promise.resolve('Proto Property') }; var myObject = new MyConstructor(); RSVP.hashSettled(myObject).then(function(hash){ // protoProperty will not be present, instead you will just have an // object that looks like: // { // example: { state: 'fulfilled', value: 'Example' } // } // // hash.hasOwnProperty('protoProperty'); // false // 'undefined' === typeof hash.protoProperty }); ``` @method hashSettled @for RSVP @param {Object} object @param {String} label optional string that describes the promise. Useful for tooling. @return {Promise} promise that is fulfilled when when all properties of `promises` have been settled. @static */ function hashSettled(object, label) { return new HashSettled(_rsvpPromise.default, object, label).promise; } }); enifed('rsvp/hash', ['exports', 'rsvp/promise', 'rsvp/promise-hash'], function (exports, _rsvpPromise, _rsvpPromiseHash) { 'use strict'; exports.default = hash; /** `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array for its `promises` argument. Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The returned promise is fulfilled with a hash that has the same key names as the `promises` object argument. If any of the values in the object are not promises, they will simply be copied over to the fulfilled object. Example: ```javascript var promises = { myPromise: RSVP.resolve(1), yourPromise: RSVP.resolve(2), theirPromise: RSVP.resolve(3), notAPromise: 4 }; RSVP.hash(promises).then(function(hash){ // hash here is an object that looks like: // { // myPromise: 1, // yourPromise: 2, // theirPromise: 3, // notAPromise: 4 // } }); ```` If any of the `promises` given to `RSVP.hash` are rejected, the first promise that is rejected will be given as the reason to the rejection handler. Example: ```javascript var promises = { myPromise: RSVP.resolve(1), rejectedPromise: RSVP.reject(new Error('rejectedPromise')), anotherRejectedPromise: RSVP.reject(new Error('anotherRejectedPromise')), }; RSVP.hash(promises).then(function(hash){ // Code here never runs because there are rejected promises! }, function(reason) { // reason.message === 'rejectedPromise' }); ``` An important note: `RSVP.hash` is intended for plain JavaScript objects that are just a set of keys and values. `RSVP.hash` will NOT preserve prototype chains. Example: ```javascript function MyConstructor(){ this.example = RSVP.resolve('Example'); } MyConstructor.prototype = { protoProperty: RSVP.resolve('Proto Property') }; var myObject = new MyConstructor(); RSVP.hash(myObject).then(function(hash){ // protoProperty will not be present, instead you will just have an // object that looks like: // { // example: 'Example' // } // // hash.hasOwnProperty('protoProperty'); // false // 'undefined' === typeof hash.protoProperty }); ``` @method hash @static @for RSVP @param {Object} object @param {String} label optional string that describes the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all properties of `promises` have been fulfilled, or rejected if any of them become rejected. */ function hash(object, label) { return new _rsvpPromiseHash.default(_rsvpPromise.default, object, label).promise; } }); enifed('rsvp/instrument', ['exports', 'rsvp/config', 'rsvp/utils'], function (exports, _rsvpConfig, _rsvpUtils) { 'use strict'; exports.default = instrument; var queue = []; function scheduleFlush() { setTimeout(function () { var entry; for (var i = 0; i < queue.length; i++) { entry = queue[i]; var payload = entry.payload; payload.guid = payload.key + payload.id; payload.childGuid = payload.key + payload.childId; if (payload.error) { payload.stack = payload.error.stack; } _rsvpConfig.config['trigger'](entry.name, entry.payload); } queue.length = 0; }, 50); } function instrument(eventName, promise, child) { if (1 === queue.push({ name: eventName, payload: { key: promise._guidKey, id: promise._id, eventName: eventName, detail: promise._result, childId: child && child._id, label: promise._label, timeStamp: _rsvpUtils.now(), error: _rsvpConfig.config["instrument-with-stack"] ? new Error(promise._label) : null } })) { scheduleFlush(); } } }); enifed('rsvp/map', ['exports', 'rsvp/promise', 'rsvp/utils'], function (exports, _rsvpPromise, _rsvpUtils) { 'use strict'; exports.default = map; /** `RSVP.map` is similar to JavaScript's native `map` method, except that it waits for all promises to become fulfilled before running the `mapFn` on each item in given to `promises`. `RSVP.map` returns a promise that will become fulfilled with the result of running `mapFn` on the values the promises become fulfilled with. For example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; var mapFn = function(item){ return item + 1; }; RSVP.map(promises, mapFn).then(function(result){ // result is [ 2, 3, 4 ] }); ``` If any of the `promises` given to `RSVP.map` are rejected, the first promise that is rejected will be given as an argument to the returned promise's rejection handler. For example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error('2')); var promise3 = RSVP.reject(new Error('3')); var promises = [ promise1, promise2, promise3 ]; var mapFn = function(item){ return item + 1; }; RSVP.map(promises, mapFn).then(function(array){ // Code here never runs because there are rejected promises! }, function(reason) { // reason.message === '2' }); ``` `RSVP.map` will also wait if a promise is returned from `mapFn`. For example, say you want to get all comments from a set of blog posts, but you need the blog posts first because they contain a url to those comments. ```javscript var mapFn = function(blogPost){ // getComments does some ajax and returns an RSVP.Promise that is fulfilled // with some comments data return getComments(blogPost.comments_url); }; // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled // with some blog post data RSVP.map(getBlogPosts(), mapFn).then(function(comments){ // comments is the result of asking the server for the comments // of all blog posts returned from getBlogPosts() }); ``` @method map @static @for RSVP @param {Array} promises @param {Function} mapFn function to be called on each fulfilled promise. @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled with the result of calling `mapFn` on each fulfilled promise or value when they become fulfilled. The promise will be rejected if any of the given `promises` become rejected. @static */ function map(promises, mapFn, label) { return _rsvpPromise.default.all(promises, label).then(function (values) { if (!_rsvpUtils.isFunction(mapFn)) { throw new TypeError("You must pass a function as map's second argument."); } var length = values.length; var results = new Array(length); for (var i = 0; i < length; i++) { results[i] = mapFn(values[i]); } return _rsvpPromise.default.all(results, label); }); } }); enifed('rsvp/node', ['exports', 'rsvp/promise', 'rsvp/-internal', 'rsvp/utils'], function (exports, _rsvpPromise, _rsvpInternal, _rsvpUtils) { 'use strict'; exports.default = denodeify; function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function Result() { this.value = undefined; } var ERROR = new Result(); var GET_THEN_ERROR = new Result(); function getThen(obj) { try { return obj.then; } catch (error) { ERROR.value = error; return ERROR; } } function tryApply(f, s, a) { try { f.apply(s, a); } catch (error) { ERROR.value = error; return ERROR; } } function makeObject(_, argumentNames) { var obj = {}; var name; var i; var length = _.length; var args = new Array(length); for (var x = 0; x < length; x++) { args[x] = _[x]; } for (i = 0; i < argumentNames.length; i++) { name = argumentNames[i]; obj[name] = args[i + 1]; } return obj; } function arrayResult(_) { var length = _.length; var args = new Array(length - 1); for (var i = 1; i < length; i++) { args[i - 1] = _[i]; } return args; } function wrapThenable(then, promise) { return { then: function (onFulFillment, onRejection) { return then.call(promise, onFulFillment, onRejection); } }; } /** `RSVP.denodeify` takes a 'node-style' function and returns a function that will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the browser when you'd prefer to use promises over using callbacks. For example, `denodeify` transforms the following: ```javascript var fs = require('fs'); fs.readFile('myfile.txt', function(err, data){ if (err) return handleError(err); handleData(data); }); ``` into: ```javascript var fs = require('fs'); var readFile = RSVP.denodeify(fs.readFile); readFile('myfile.txt').then(handleData, handleError); ``` If the node function has multiple success parameters, then `denodeify` just returns the first one: ```javascript var request = RSVP.denodeify(require('request')); request('http://example.com').then(function(res) { // ... }); ``` However, if you need all success parameters, setting `denodeify`'s second parameter to `true` causes it to return all success parameters as an array: ```javascript var request = RSVP.denodeify(require('request'), true); request('http://example.com').then(function(result) { // result[0] -> res // result[1] -> body }); ``` Or if you pass it an array with names it returns the parameters as a hash: ```javascript var request = RSVP.denodeify(require('request'), ['res', 'body']); request('http://example.com').then(function(result) { // result.res // result.body }); ``` Sometimes you need to retain the `this`: ```javascript var app = require('express')(); var render = RSVP.denodeify(app.render.bind(app)); ``` The denodified function inherits from the original function. It works in all environments, except IE 10 and below. Consequently all properties of the original function are available to you. However, any properties you change on the denodeified function won't be changed on the original function. Example: ```javascript var request = RSVP.denodeify(require('request')), cookieJar = request.jar(); // <- Inheritance is used here request('http://example.com', {jar: cookieJar}).then(function(res) { // cookieJar.cookies holds now the cookies returned by example.com }); ``` Using `denodeify` makes it easier to compose asynchronous operations instead of using callbacks. For example, instead of: ```javascript var fs = require('fs'); fs.readFile('myfile.txt', function(err, data){ if (err) { ... } // Handle error fs.writeFile('myfile2.txt', data, function(err){ if (err) { ... } // Handle error console.log('done') }); }); ``` you can chain the operations together using `then` from the returned promise: ```javascript var fs = require('fs'); var readFile = RSVP.denodeify(fs.readFile); var writeFile = RSVP.denodeify(fs.writeFile); readFile('myfile.txt').then(function(data){ return writeFile('myfile2.txt', data); }).then(function(){ console.log('done') }).catch(function(error){ // Handle error }); ``` @method denodeify @static @for RSVP @param {Function} nodeFunc a 'node-style' function that takes a callback as its last argument. The callback expects an error to be passed as its first argument (if an error occurred, otherwise null), and the value from the operation as its second argument ('function(err, value){ }'). @param {Boolean|Array} [options] An optional paramter that if set to `true` causes the promise to fulfill with the callback's success arguments as an array. This is useful if the node function has multiple success paramters. If you set this paramter to an array with names, the promise will fulfill with a hash with these names as keys and the success parameters as values. @return {Function} a function that wraps `nodeFunc` to return an `RSVP.Promise` @static */ function denodeify(nodeFunc, options) { var fn = function () { var self = this; var l = arguments.length; var args = new Array(l + 1); var arg; var promiseInput = false; for (var i = 0; i < l; ++i) { arg = arguments[i]; if (!promiseInput) { // TODO: clean this up promiseInput = needsPromiseInput(arg); if (promiseInput === GET_THEN_ERROR) { var p = new _rsvpPromise.default(_rsvpInternal.noop); _rsvpInternal.reject(p, GET_THEN_ERROR.value); return p; } else if (promiseInput && promiseInput !== true) { arg = wrapThenable(promiseInput, arg); } } args[i] = arg; } var promise = new _rsvpPromise.default(_rsvpInternal.noop); args[l] = function (err, val) { if (err) _rsvpInternal.reject(promise, err);else if (options === undefined) _rsvpInternal.resolve(promise, val);else if (options === true) _rsvpInternal.resolve(promise, arrayResult(arguments));else if (_rsvpUtils.isArray(options)) _rsvpInternal.resolve(promise, makeObject(arguments, options));else _rsvpInternal.resolve(promise, val); }; if (promiseInput) { return handlePromiseInput(promise, args, nodeFunc, self); } else { return handleValueInput(promise, args, nodeFunc, self); } }; _defaults(fn, nodeFunc); return fn; } function handleValueInput(promise, args, nodeFunc, self) { var result = tryApply(nodeFunc, self, args); if (result === ERROR) { _rsvpInternal.reject(promise, result.value); } return promise; } function handlePromiseInput(promise, args, nodeFunc, self) { return _rsvpPromise.default.all(args).then(function (args) { var result = tryApply(nodeFunc, self, args); if (result === ERROR) { _rsvpInternal.reject(promise, result.value); } return promise; }); } function needsPromiseInput(arg) { if (arg && typeof arg === 'object') { if (arg.constructor === _rsvpPromise.default) { return true; } else { return getThen(arg); } } else { return false; } } }); enifed('rsvp/platform', ['exports'], function (exports) { 'use strict'; var platform; /* global self */ if (typeof self === 'object') { platform = self; /* global global */ } else if (typeof global === 'object') { platform = global; } else { throw new Error('no global: `self` or `global` found'); } exports.default = platform; }); enifed('rsvp/promise-hash', ['exports', 'rsvp/enumerator', 'rsvp/-internal', 'rsvp/utils'], function (exports, _rsvpEnumerator, _rsvpInternal, _rsvpUtils) { 'use strict'; function PromiseHash(Constructor, object, label) { this._superConstructor(Constructor, object, true, label); } exports.default = PromiseHash; PromiseHash.prototype = _rsvpUtils.o_create(_rsvpEnumerator.default.prototype); PromiseHash.prototype._superConstructor = _rsvpEnumerator.default; PromiseHash.prototype._init = function () { this._result = {}; }; PromiseHash.prototype._validateInput = function (input) { return input && typeof input === 'object'; }; PromiseHash.prototype._validationError = function () { return new Error('Promise.hash must be called with an object'); }; PromiseHash.prototype._enumerate = function () { var enumerator = this; var promise = enumerator.promise; var input = enumerator._input; var results = []; for (var key in input) { if (promise._state === _rsvpInternal.PENDING && Object.prototype.hasOwnProperty.call(input, key)) { results.push({ position: key, entry: input[key] }); } } var length = results.length; enumerator._remaining = length; var result; for (var i = 0; promise._state === _rsvpInternal.PENDING && i < length; i++) { result = results[i]; enumerator._eachEntry(result.entry, result.position); } }; }); enifed('rsvp/promise', ['exports', 'rsvp/config', 'rsvp/instrument', 'rsvp/utils', 'rsvp/-internal', 'rsvp/promise/all', 'rsvp/promise/race', 'rsvp/promise/resolve', 'rsvp/promise/reject'], function (exports, _rsvpConfig, _rsvpInstrument, _rsvpUtils, _rsvpInternal, _rsvpPromiseAll, _rsvpPromiseRace, _rsvpPromiseResolve, _rsvpPromiseReject) { 'use strict'; exports.default = Promise; var guidKey = 'rsvp_' + _rsvpUtils.now() + '-'; var counter = 0; function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class RSVP.Promise @param {function} resolver @param {String} label optional string for labeling the promise. Useful for tooling. @constructor */ function Promise(resolver, label) { var promise = this; promise._id = counter++; promise._label = label; promise._state = undefined; promise._result = undefined; promise._subscribers = []; if (_rsvpConfig.config.instrument) { _rsvpInstrument.default('created', promise); } if (_rsvpInternal.noop !== resolver) { if (!_rsvpUtils.isFunction(resolver)) { needsResolver(); } if (!(promise instanceof Promise)) { needsNew(); } _rsvpInternal.initializePromise(promise, resolver); } } Promise.cast = _rsvpPromiseResolve.default; // deprecated Promise.all = _rsvpPromiseAll.default; Promise.race = _rsvpPromiseRace.default; Promise.resolve = _rsvpPromiseResolve.default; Promise.reject = _rsvpPromiseReject.default; Promise.prototype = { constructor: Promise, _guidKey: guidKey, _onError: function (reason) { var promise = this; _rsvpConfig.config.after(function () { if (promise._onError) { _rsvpConfig.config['trigger']('error', reason); } }); }, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfillment @param {Function} onRejection @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ then: function (onFulfillment, onRejection, label) { var parent = this; var state = parent._state; if (state === _rsvpInternal.FULFILLED && !onFulfillment || state === _rsvpInternal.REJECTED && !onRejection) { if (_rsvpConfig.config.instrument) { _rsvpInstrument.default('chained', parent, parent); } return parent; } parent._onError = null; var child = new parent.constructor(_rsvpInternal.noop, label); var result = parent._result; if (_rsvpConfig.config.instrument) { _rsvpInstrument.default('chained', parent, child); } if (state) { var callback = arguments[state - 1]; _rsvpConfig.config.async(function () { _rsvpInternal.invokeCallback(state, child, callback, result); }); } else { _rsvpInternal.subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ 'catch': function (onRejection, label) { return this.then(undefined, onRejection, label); }, /** `finally` will be invoked regardless of the promise's fate just as native try/catch/finally behaves Synchronous example: ```js findAuthor() { if (Math.random() > 0.5) { throw new Error(); } return new Author(); } try { return findAuthor(); // succeed or fail } catch(error) { return findOtherAuther(); } finally { // always runs // doesn't affect the return value } ``` Asynchronous example: ```js findAuthor().catch(function(reason){ return findOtherAuther(); }).finally(function(){ // author was either found, or not }); ``` @method finally @param {Function} callback @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ 'finally': function (callback, label) { var promise = this; var constructor = promise.constructor; return promise.then(function (value) { return constructor.resolve(callback()).then(function () { return value; }); }, function (reason) { return constructor.resolve(callback()).then(function () { throw reason; }); }, label); } }; }); enifed('rsvp/promise/all', ['exports', 'rsvp/enumerator'], function (exports, _rsvpEnumerator) { 'use strict'; exports.default = all; /** `RSVP.Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; RSVP.Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `RSVP.all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; RSVP.Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all(entries, label) { return new _rsvpEnumerator.default(this, entries, true, /* abort on reject */label).promise; } }); enifed('rsvp/promise/race', ['exports', 'rsvp/utils', 'rsvp/-internal'], function (exports, _rsvpUtils, _rsvpInternal) { 'use strict'; exports.default = race; /** `RSVP.Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); RSVP.Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `RSVP.Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); RSVP.Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript RSVP.Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} entries array of promises to observe @param {String} label optional string for describing the promise returned. Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(_rsvpInternal.noop, label); if (!_rsvpUtils.isArray(entries)) { _rsvpInternal.reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { _rsvpInternal.resolve(promise, value); } function onRejection(reason) { _rsvpInternal.reject(promise, reason); } for (var i = 0; promise._state === _rsvpInternal.PENDING && i < length; i++) { _rsvpInternal.subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; } }); enifed('rsvp/promise/reject', ['exports', 'rsvp/-internal'], function (exports, _rsvpInternal) { 'use strict'; exports.default = reject; /** `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript var promise = new RSVP.Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript var promise = RSVP.Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {*} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(_rsvpInternal.noop, label); _rsvpInternal.reject(promise, reason); return promise; } }); enifed('rsvp/promise/resolve', ['exports', 'rsvp/-internal'], function (exports, _rsvpInternal) { 'use strict'; exports.default = resolve; /** `RSVP.Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript var promise = new RSVP.Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript var promise = RSVP.Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {*} object value that the returned promise will be resolved with @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(_rsvpInternal.noop, label); _rsvpInternal.resolve(promise, object); return promise; } }); enifed('rsvp/race', ['exports', 'rsvp/promise'], function (exports, _rsvpPromise) { 'use strict'; exports.default = race; /** This is a convenient alias for `RSVP.Promise.race`. @method race @static @for RSVP @param {Array} array Array of promises. @param {String} label An optional label. This is useful for tooling. */ function race(array, label) { return _rsvpPromise.default.race(array, label); } }); enifed('rsvp/reject', ['exports', 'rsvp/promise'], function (exports, _rsvpPromise) { 'use strict'; exports.default = reject; /** This is a convenient alias for `RSVP.Promise.reject`. @method reject @static @for RSVP @param {*} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject(reason, label) { return _rsvpPromise.default.reject(reason, label); } }); enifed('rsvp/resolve', ['exports', 'rsvp/promise'], function (exports, _rsvpPromise) { 'use strict'; exports.default = resolve; /** This is a convenient alias for `RSVP.Promise.resolve`. @method resolve @static @for RSVP @param {*} value value that the returned promise will be resolved with @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve(value, label) { return _rsvpPromise.default.resolve(value, label); } }); enifed("rsvp/rethrow", ["exports"], function (exports) { /** `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event loop in order to aid debugging. Promises A+ specifies that any exceptions that occur with a promise must be caught by the promises implementation and bubbled to the last handler. For this reason, it is recommended that you always specify a second rejection handler function to `then`. However, `RSVP.rethrow` will throw the exception outside of the promise, so it bubbles up to your console if in the browser, or domain/cause uncaught exception in Node. `rethrow` will also throw the error again so the error can be handled by the promise per the spec. ```javascript function throws(){ throw new Error('Whoops!'); } var promise = new RSVP.Promise(function(resolve, reject){ throws(); }); promise.catch(RSVP.rethrow).then(function(){ // Code here doesn't run because the promise became rejected due to an // error! }, function (err){ // handle the error here }); ``` The 'Whoops' error will be thrown on the next turn of the event loop and you can watch for it in your console. You can also handle it using a rejection handler given to `.then` or `.catch` on the returned promise. @method rethrow @static @for RSVP @param {Error} reason reason the promise became rejected. @throws Error @static */ "use strict"; exports.default = rethrow; function rethrow(reason) { setTimeout(function () { throw reason; }); throw reason; } }); enifed('rsvp/utils', ['exports'], function (exports) { 'use strict'; exports.objectOrFunction = objectOrFunction; exports.isFunction = isFunction; exports.isMaybeThenable = isMaybeThenable; function objectOrFunction(x) { return typeof x === 'function' || typeof x === 'object' && x !== null; } function isFunction(x) { return typeof x === 'function'; } function isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var _isArray; if (!Array.isArray) { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { _isArray = Array.isArray; } var isArray = _isArray; exports.isArray = isArray; // Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function () { return new Date().getTime(); }; exports.now = now; function F() {} var o_create = Object.create || function (o) { if (arguments.length > 1) { throw new Error('Second argument not supported'); } if (typeof o !== 'object') { throw new TypeError('Argument must be an object'); } F.prototype = o; return new F(); }; exports.o_create = o_create; }); enifed("vertex", ["exports"], function (exports) { /** * DAG Vertex * * @class Vertex * @constructor */ "use strict"; exports.default = Vertex; function Vertex(name) { this.name = name; this.incoming = {}; this.incomingNames = []; this.hasOutgoing = false; this.value = null; } }); enifed("visit", ["exports"], function (exports) { "use strict"; exports.default = visit; function visit(vertex, fn, visited, path) { var name = vertex.name; var vertices = vertex.incoming; var names = vertex.incomingNames; var len = names.length; var i; if (!visited) { visited = {}; } if (!path) { path = []; } if (visited.hasOwnProperty(name)) { return; } path.push(name); visited[name] = true; for (i = 0; i < len; i++) { visit(vertices[names[i]], fn, visited, path); } fn(vertex, path); path.pop(); } }); requireModule("ember"); }()); ;(function() { /* globals define, Ember, jQuery */ function processEmberShims() { var shims = { 'ember': { 'default': Ember }, 'ember-application': { 'default': Ember.Application }, 'ember-array': { 'default': Ember.Array }, 'ember-array/mutable': { 'default': Ember.MutableArray }, 'ember-array/utils': { 'A': Ember.A, 'isEmberArray': Ember.isArray, 'wrap': Ember.makeArray }, 'ember-component': { 'default': Ember.Component }, 'ember-components/checkbox': { 'default': Ember.Checkbox }, 'ember-components/text-area': { 'default': Ember.TextArea }, 'ember-components/text-field': { 'default': Ember.TextField }, 'ember-controller': { 'default': Ember.Controller }, 'ember-controller/inject': { 'default': Ember.inject.controller }, 'ember-controller/proxy': { 'default': Ember.ArrayProxy }, 'ember-controllers/sortable': { 'default': Ember.SortableMixin }, 'ember-debug': { 'log': Ember.debug, 'inspect': Ember.inspect, 'run': Ember.runInDebug, 'warn': Ember.warn }, 'ember-debug/container-debug-adapter': { 'default': Ember.ContainerDebugAdapter }, 'ember-debug/data-adapter': { 'default': Ember.DataAdapter }, 'ember-deprecations': { 'deprecate': Ember.deprecate, 'deprecateFunc': Ember.deprecateFunc }, 'ember-enumerable': { 'default': Ember.Enumerable }, 'ember-evented': { 'default': Ember.Evented }, 'ember-evented/on': { 'default': Ember.on }, 'ember-globals-resolver': { 'default': Ember.DefaultResolver }, 'ember-helper': { 'default': Ember.Helper, 'helper': Ember.Helper && Ember.Helper.helper }, 'ember-instrumentation': { 'instrument': Ember.Instrumentation.instrument, 'reset': Ember.Instrumentation.reset, 'subscribe': Ember.Instrumentation.subscribe, 'unsubscribe': Ember.Instrumentation.unsubscribe }, 'ember-locations/hash': { 'default': Ember.HashLocation }, 'ember-locations/history': { 'default': Ember.HistoryLocation }, 'ember-locations/none': { 'default': Ember.NoneLocation }, 'ember-map': { 'default': Ember.Map, 'withDefault': Ember.MapWithDefault }, 'ember-metal/destroy': { 'default': Ember.destroy }, 'ember-metal/events': { 'addListener': Ember.addListener, 'removeListener': Ember.removeListener, 'send': Ember.sendEvent }, 'ember-metal/get': { 'default': Ember.get, 'getProperties': Ember.getProperties }, 'ember-metal/mixin': { 'default': Ember.Mixin }, 'ember-metal/observer': { 'default': Ember.observer, 'addObserver': Ember.addObserver, 'removeObserver': Ember.removeObserver }, 'ember-metal/on-load': { 'default': Ember.onLoad, 'run': Ember.runLoadHooks }, 'ember-metal/set': { 'default': Ember.set, 'setProperties': Ember.setProperties, 'trySet': Ember.trySet }, 'ember-metal/utils': { 'aliasMethod': Ember.aliasMethod, 'assert': Ember.assert, 'cacheFor': Ember.cacheFor, 'copy': Ember.copy, 'guidFor': Ember.guidFor }, 'ember-object': { 'default': Ember.Object }, 'ember-owner/get': { 'default': Ember.getOwner }, 'ember-owner/set': { 'default': Ember.setOwner }, 'ember-platform': { 'assign': Ember.assign || Ember.merge, 'create': Ember.create, 'defineProperty': Ember.platform.defineProperty, 'hasAccessors': Ember.platform.hasPropertyAccessors, 'keys': Ember.keys }, 'ember-route': { 'default': Ember.Route }, 'ember-router': { 'default': Ember.Router }, 'ember-runloop': { 'default': Ember.run, 'begin': Ember.run.begin, 'bind': Ember.run.bind, 'cancel': Ember.run.cancel, 'debounce': Ember.run.debounce, 'end': Ember.run.end, 'join': Ember.run.join, 'later': Ember.run.later, 'next': Ember.run.next, 'once': Ember.run.once, 'schedule': Ember.run.schedule, 'scheduleOnce': Ember.run.scheduleOnce, 'throttle': Ember.run.throttle }, 'ember-service': { 'default': Ember.Service }, 'ember-service/inject': { 'default': Ember.inject.service }, 'ember-set/ordered': { 'default': Ember.OrderedSet }, 'ember-string': { 'camelize': Ember.String.camelize, 'capitalize': Ember.String.capitalize, 'classify': Ember.String.classify, 'dasherize': Ember.String.dasherize, 'decamelize': Ember.String.decamelize, 'fmt': Ember.String.fmt, 'htmlSafe': Ember.String.htmlSafe, 'loc': Ember.String.loc, 'underscore': Ember.String.underscore, 'w': Ember.String.w }, 'ember-utils': { 'isBlank': Ember.isBlank, 'isEmpty': Ember.isEmpty, 'isNone': Ember.isNone, 'isPresent': Ember.isPresent, 'tryInvoke': Ember.tryInvoke, 'typeOf': Ember.typeOf } }; // populate `ember/computed` named exports shims['ember-computed'] = { 'default': Ember.computed }; var computedMacros = [ "empty","notEmpty", "none", "not", "bool", "match", "equal", "gt", "gte", "lt", "lte", "alias", "oneWay", "reads", "readOnly", "deprecatingAlias", "and", "or", "collect", "sum", "min", "max", "map", "sort", "setDiff", "mapBy", "mapProperty", "filter", "filterBy", "filterProperty", "uniq", "union", "intersect" ]; for (var i = 0, l = computedMacros.length; i < l; i++) { var key = computedMacros[i]; shims['ember-computed'][key] = Ember.computed[key]; } for (var moduleName in shims) { generateModule(moduleName, shims[moduleName]); } } function processTestShims() { if (Ember.Test) { var testShims = { 'ember-test': { 'default': Ember.Test }, 'ember-test/adapter': { 'default': Ember.Test.Adapter }, 'ember-test/qunit-adapter': { 'default': Ember.Test.QUnitAdapter } }; for (var moduleName in testShims) { generateModule(moduleName, testShims[moduleName]); } } } function generateModule(name, values) { define(name, [], function() { 'use strict'; Object.defineProperty(values, '__esModule', { value: true }); return values; }); } processEmberShims(); processTestShims(); generateModule('jquery', { 'default': self.jQuery }); generateModule('rsvp', { 'default': Ember.RSVP }); })(); ;(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/index.js":[function(require,module,exports){ /* this index.js file is used for including the Faker library as a CommonJS module, instead of a bundle you can include the Faker library into your existing node.js application by requiring the entire /Faker directory var faker = require(./faker); var randomName = Faker.Name.findName(); you can also simply include the "Faker.js" file which is the auto-generated bundled version of the Faker library var Faker = require(./customAppPath/Faker); var randomName = Faker.Name.findName(); if you plan on modifying the Faker library you should be performing your changes in the /lib/ directory */ exports.Name = require('./lib/name'); exports.Address = require('./lib/address'); exports.PhoneNumber = require('./lib/phone_number'); exports.Internet = require('./lib/internet'); exports.Company = require('./lib/company'); exports.Image = require('./lib/image'); exports.Lorem = require('./lib/lorem'); exports.Helpers = require('./lib/helpers'); exports.Tree = require('./lib/tree'); exports.Date = require('./lib/date'); exports.random = require('./lib/random'); exports.definitions = require('./lib/definitions'); },{"./lib/address":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/address.js","./lib/company":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/company.js","./lib/date":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/date.js","./lib/definitions":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/definitions.js","./lib/helpers":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/helpers.js","./lib/image":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/image.js","./lib/internet":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/internet.js","./lib/lorem":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/lorem.js","./lib/name":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/name.js","./lib/phone_number":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/phone_number.js","./lib/random":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/random.js","./lib/tree":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/tree.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/address.js":[function(require,module,exports){ var Helpers = require('./helpers'); var Faker = require('../index'); var definitions = require('../lib/definitions'); var address = { zipCode: function () { return Helpers.replaceSymbolWithNumber(Faker.random.array_element(["#####", '#####-####'])); }, zipCodeFormat: function (format) { return Helpers.replaceSymbolWithNumber(["#####", '#####-####'][format]); }, city: function () { var result; switch (Faker.random.number(4)) { case 0: result = Faker.random.city_prefix() + " " + Faker.random.first_name() + Faker.random.city_suffix(); break; case 1: result = Faker.random.city_prefix() + " " + Faker.random.first_name(); break; case 2: result = Faker.random.first_name() + Faker.random.city_suffix(); break; case 3: result = Faker.random.last_name() + Faker.random.city_suffix(); break; } return result; }, streetName: function () { var result; switch (Faker.random.number(2)) { case 0: result = Faker.random.last_name() + " " + Faker.random.street_suffix(); break; case 1: result = Faker.random.first_name() + " " + Faker.random.street_suffix(); break; } return result; }, // // TODO: change all these methods that accept a boolean to instead accept an options hash. // streetAddress: function (useFullAddress) { if (useFullAddress === undefined) { useFullAddress = false; } var address = ""; switch (Faker.random.number(3)) { case 0: address = Helpers.replaceSymbolWithNumber("#####") + " " + this.streetName(); break; case 1: address = Helpers.replaceSymbolWithNumber("####") + " " + this.streetName(); break; case 2: address = Helpers.replaceSymbolWithNumber("###") + " " + this.streetName(); break; } return useFullAddress ? (address + " " + this.secondaryAddress()) : address; }, secondaryAddress: function () { return Helpers.replaceSymbolWithNumber(Faker.random.array_element( [ 'Apt. ###', 'Suite ###' ] )); }, brState: function (useAbbr) { return useAbbr ? Faker.random.br_state_abbr() : Faker.random.br_state(); }, ukCounty: function () { return Faker.random.uk_county(); }, ukCountry: function () { return Faker.random.uk_country(); }, usState: function (useAbbr) { return useAbbr ? Faker.random.us_state_abbr() : Faker.random.us_state(); }, latitude: function () { return (Faker.random.number(180 * 10000) / 10000.0 - 90.0).toFixed(4); }, longitude: function () { return (Faker.random.number(360 * 10000) / 10000.0 - 180.0).toFixed(4); } }; module.exports = address; },{"../index":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/index.js","../lib/definitions":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/definitions.js","./helpers":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/helpers.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/company.js":[function(require,module,exports){ var Faker = require('../index'); var company = { suffixes: function () { return ["Inc", "and Sons", "LLC", "Group", "and Daughters"]; }, companyName: function (format) { switch ((format ? format : Faker.random.number(3))) { case 0: return Faker.Name.lastName() + " " + this.companySuffix(); case 1: return Faker.Name.lastName() + "-" + Faker.Name.lastName(); case 2: return Faker.Name.lastName() + ", " + Faker.Name.lastName() + " and " + Faker.Name.lastName(); } }, companySuffix: function () { return Faker.random.array_element(this.suffixes()); }, catchPhrase: function () { return Faker.random.catch_phrase_adjective() + " " + Faker.random.catch_phrase_descriptor() + " " + Faker.random.catch_phrase_noun(); }, bs: function () { return Faker.random.bs_adjective() + " " + Faker.random.bs_buzz() + " " + Faker.random.bs_noun(); } }; module.exports = company; },{"../index":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/date.js":[function(require,module,exports){ var Faker = require('../index'); var date = { past: function (years, refDate) { var date = (refDate) ? new Date(Date.parse(refDate)) : new Date(); var past = date.getTime(); past -= Faker.random.number(years) * 365 * 3600 * 1000; // some time from now to N years ago, in milliseconds date.setTime(past) return date.toJSON(); }, future: function (years, refDate) { var date = (refDate) ? new Date(Date.parse(refDate)) : new Date(); var future = date.getTime(); future += Faker.random.number(years) * 365 * 3600 * 1000; // some time from now to N years later, in milliseconds date.setTime(future) return date.toJSON(); }, between: function(from, to) { var fromMilli = Date.parse(from); var dateOffset = Faker.random.number(Date.parse(to) - fromMilli); var newDate = new Date(fromMilli + dateOffset); return newDate.toJSON(); }, recent: function (days) { var date = new Date(); var future = date.getTime(); future -= Faker.random.number(days) * 3600 * 1000; // some time from now to N days ago, in milliseconds date.setTime(future) return date.toJSON(); } }; module.exports = date; },{"../index":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/definitions.js":[function(require,module,exports){ // name.js definitions exports.first_name = ["Aaliyah", "Aaron", "Abagail", "Abbey", "Abbie", "Abbigail", "Abby", "Abdiel", "Abdul", "Abdullah", "Abe", "Abel", "Abelardo", "Abigail", "Abigale", "Abigayle", "Abner", "Abraham", "Ada", "Adah", "Adalberto", "Adaline", "Adam", "Adan", "Addie", "Addison", "Adela", "Adelbert", "Adele", "Adelia", "Adeline", "Adell", "Adella", "Adelle", "Aditya", "Adolf", "Adolfo", "Adolph", "Adolphus", "Adonis", "Adrain", "Adrian", "Adriana", "Adrianna", "Adriel", "Adrien", "Adrienne", "Afton", "Aglae", "Agnes", "Agustin", "Agustina", "Ahmad", "Ahmed", "Aida", "Aidan", "Aiden", "Aileen", "Aimee", "Aisha", "Aiyana", "Akeem", "Al", "Alaina", "Alan", "Alana", "Alanis", "Alanna", "Alayna", "Alba", "Albert", "Alberta", "Albertha", "Alberto", "Albin", "Albina", "Alda", "Alden", "Alec", "Aleen", "Alejandra", "Alejandrin", "Alek", "Alena", "Alene", "Alessandra", "Alessandro", "Alessia", "Aletha", "Alex", "Alexa", "Alexander", "Alexandra", "Alexandre", "Alexandrea", "Alexandria", "Alexandrine", "Alexandro", "Alexane", "Alexanne", "Alexie", "Alexis", "Alexys", "Alexzander", "Alf", "Alfonso", "Alfonzo", "Alford", "Alfred", "Alfreda", "Alfredo", "Ali", "Alia", "Alice", "Alicia", "Alisa", "Alisha", "Alison", "Alivia", "Aliya", "Aliyah", "Aliza", "Alize", "Allan", "Allen", "Allene", "Allie", "Allison", "Ally", "Alphonso", "Alta", "Althea", "Alva", "Alvah", "Alvena", "Alvera", "Alverta", "Alvina", "Alvis", "Alyce", "Alycia", "Alysa", "Alysha", "Alyson", "Alysson", "Amalia", "Amanda", "Amani", "Amara", "Amari", "Amaya", "Amber", "Ambrose", "Amelia", "Amelie", "Amely", "America", "Americo", "Amie", "Amina", "Amir", "Amira", "Amiya", "Amos", "Amparo", "Amy", "Amya", "Ana", "Anabel", "Anabelle", "Anahi", "Anais", "Anastacio", "Anastasia", "Anderson", "Andre", "Andreane", "Andreanne", "Andres", "Andrew", "Andy", "Angel", "Angela", "Angelica", "Angelina", "Angeline", "Angelita", "Angelo", "Angie", "Angus", "Anibal", "Anika", "Anissa", "Anita", "Aniya", "Aniyah", "Anjali", "Anna", "Annabel", "Annabell", "Annabelle", "Annalise", "Annamae", "Annamarie", "Anne", "Annetta", "Annette", "Annie", "Ansel", "Ansley", "Anthony", "Antoinette", "Antone", "Antonetta", "Antonette", "Antonia", "Antonietta", "Antonina", "Antonio", "Antwan", "Antwon", "Anya", "April", "Ara", "Araceli", "Aracely", "Arch", "Archibald", "Ardella", "Arden", "Ardith", "Arely", "Ari", "Ariane", "Arianna", "Aric", "Ariel", "Arielle", "Arjun", "Arlene", "Arlie", "Arlo", "Armand", "Armando", "Armani", "Arnaldo", "Arne", "Arno", "Arnold", "Arnoldo", "Arnulfo", "Aron", "Art", "Arthur", "Arturo", "Arvel", "Arvid", "Arvilla", "Aryanna", "Asa", "Asha", "Ashlee", "Ashleigh", "Ashley", "Ashly", "Ashlynn", "Ashton", "Ashtyn", "Asia", "Assunta", "Astrid", "Athena", "Aubree", "Aubrey", "Audie", "Audra", "Audreanne", "Audrey", "August", "Augusta", "Augustine", "Augustus", "Aurelia", "Aurelie", "Aurelio", "Aurore", "Austen", "Austin", "Austyn", "Autumn", "Ava", "Avery", "Avis", "Axel", "Ayana", "Ayden", "Ayla", "Aylin", "Baby", "Bailee", "Bailey", "Barbara", "Barney", "Baron", "Barrett", "Barry", "Bart", "Bartholome", "Barton", "Baylee", "Beatrice", "Beau", "Beaulah", "Bell", "Bella", "Belle", "Ben", "Benedict", "Benjamin", "Bennett", "Bennie", "Benny", "Benton", "Berenice", "Bernadette", "Bernadine", "Bernard", "Bernardo", "Berneice", "Bernhard", "Bernice", "Bernie", "Berniece", "Bernita", "Berry", "Bert", "Berta", "Bertha", "Bertram", "Bertrand", "Beryl", "Bessie", "Beth", "Bethany", "Bethel", "Betsy", "Bette", "Bettie", "Betty", "Bettye", "Beulah", "Beverly", "Bianka", "Bill", "Billie", "Billy", "Birdie", "Blair", "Blaise", "Blake", "Blanca", "Blanche", "Blaze", "Bo", "Bobbie", "Bobby", "Bonita", "Bonnie", "Boris", "Boyd", "Brad", "Braden", "Bradford", "Bradley", "Bradly", "Brady", "Braeden", "Brain", "Brandi", "Brando", "Brandon", "Brandt", "Brandy", "Brandyn", "Brannon", "Branson", "Brant", "Braulio", "Braxton", "Brayan", "Breana", "Breanna", "Breanne", "Brenda", "Brendan", "Brenden", "Brendon", "Brenna", "Brennan", "Brennon", "Brent", "Bret", "Brett", "Bria", "Brian", "Briana", "Brianne", "Brice", "Bridget", "Bridgette", "Bridie", "Brielle", "Brigitte", "Brionna", "Brisa", "Britney", "Brittany", "Brock", "Broderick", "Brody", "Brook", "Brooke", "Brooklyn", "Brooks", "Brown", "Bruce", "Bryana", "Bryce", "Brycen", "Bryon", "Buck", "Bud", "Buddy", "Buford", "Bulah", "Burdette", "Burley", "Burnice", "Buster", "Cade", "Caden", "Caesar", "Caitlyn", "Cale", "Caleb", "Caleigh", "Cali", "Calista", "Callie", "Camden", "Cameron", "Camila", "Camilla", "Camille", "Camren", "Camron", "Camryn", "Camylle", "Candace", "Candelario", "Candice", "Candida", "Candido", "Cara", "Carey", "Carissa", "Carlee", "Carleton", "Carley", "Carli", "Carlie", "Carlo", "Carlos", "Carlotta", "Carmel", "Carmela", "Carmella", "Carmelo", "Carmen", "Carmine", "Carol", "Carolanne", "Carole", "Carolina", "Caroline", "Carolyn", "Carolyne", "Carrie", "Carroll", "Carson", "Carter", "Cary", "Casandra", "Casey", "Casimer", "Casimir", "Casper", "Cassandra", "Cassandre", "Cassidy", "Cassie", "Catalina", "Caterina", "Catharine", "Catherine", "Cathrine", "Cathryn", "Cathy", "Cayla", "Ceasar", "Cecelia", "Cecil", "Cecile", "Cecilia", "Cedrick", "Celestine", "Celestino", "Celia", "Celine", "Cesar", "Chad", "Chadd", "Chadrick", "Chaim", "Chance", "Chandler", "Chanel", "Chanelle", "Charity", "Charlene", "Charles", "Charley", "Charlie", "Charlotte", "Chase", "Chasity", "Chauncey", "Chaya", "Chaz", "Chelsea", "Chelsey", "Chelsie", "Chesley", "Chester", "Chet", "Cheyanne", "Cheyenne", "Chloe", "Chris", "Christ", "Christa", "Christelle", "Christian", "Christiana", "Christina", "Christine", "Christop", "Christophe", "Christopher", "Christy", "Chyna", "Ciara", "Cicero", "Cielo", "Cierra", "Cindy", "Citlalli", "Clair", "Claire", "Clara", "Clarabelle", "Clare", "Clarissa", "Clark", "Claud", "Claude", "Claudia", "Claudie", "Claudine", "Clay", "Clemens", "Clement", "Clementina", "Clementine", "Clemmie", "Cleo", "Cleora", "Cleta", "Cletus", "Cleve", "Cleveland", "Clifford", "Clifton", "Clint", "Clinton", "Clotilde", "Clovis", "Cloyd", "Clyde", "Coby", "Cody", "Colby", "Cole", "Coleman", "Colin", "Colleen", "Collin", "Colt", "Colten", "Colton", "Columbus", "Concepcion", "Conner", "Connie", "Connor", "Conor", "Conrad", "Constance", "Constantin", "Consuelo", "Cooper", "Cora", "Coralie", "Corbin", "Cordelia", "Cordell", "Cordia", "Cordie", "Corene", "Corine", "Cornelius", "Cornell", "Corrine", "Cortez", "Cortney", "Cory", "Coty", "Courtney", "Coy", "Craig", "Crawford", "Creola", "Cristal", "Cristian", "Cristina", "Cristobal", "Cristopher", "Cruz", "Crystal", "Crystel", "Cullen", "Curt", "Curtis", "Cydney", "Cynthia", "Cyril", "Cyrus", "Dagmar", "Dahlia", "Daija", "Daisha", "Daisy", "Dakota", "Dale", "Dallas", "Dallin", "Dalton", "Damaris", "Dameon", "Damian", "Damien", "Damion", "Damon", "Dan", "Dana", "Dandre", "Dane", "D'angelo", "Dangelo", "Danial", "Daniela", "Daniella", "Danielle", "Danika", "Dannie", "Danny", "Dante", "Danyka", "Daphne", "Daphnee", "Daphney", "Darby", "Daren", "Darian", "Dariana", "Darien", "Dario", "Darion", "Darius", "Darlene", "Daron", "Darrel", "Darrell", "Darren", "Darrick", "Darrin", "Darrion", "Darron", "Darryl", "Darwin", "Daryl", "Dashawn", "Dasia", "Dave", "David", "Davin", "Davion", "Davon", "Davonte", "Dawn", "Dawson", "Dax", "Dayana", "Dayna", "Dayne", "Dayton", "Dean", "Deangelo", "Deanna", "Deborah", "Declan", "Dedric", "Dedrick", "Dee", "Deion", "Deja", "Dejah", "Dejon", "Dejuan", "Delaney", "Delbert", "Delfina", "Delia", "Delilah", "Dell", "Della", "Delmer", "Delores", "Delpha", "Delphia", "Delphine", "Delta", "Demarco", "Demarcus", "Demario", "Demetris", "Demetrius", "Demond", "Dena", "Denis", "Dennis", "Deon", "Deondre", "Deontae", "Deonte", "Dereck", "Derek", "Derick", "Deron", "Derrick", "Deshaun", "Deshawn", "Desiree", "Desmond", "Dessie", "Destany", "Destin", "Destinee", "Destiney", "Destini", "Destiny", "Devan", "Devante", "Deven", "Devin", "Devon", "Devonte", "Devyn", "Dewayne", "Dewitt", "Dexter", "Diamond", "Diana", "Dianna", "Diego", "Dillan", "Dillon", "Dimitri", "Dina", "Dino", "Dion", "Dixie", "Dock", "Dolly", "Dolores", "Domenic", "Domenica", "Domenick", "Domenico", "Domingo", "Dominic", "Dominique", "Don", "Donald", "Donato", "Donavon", "Donna", "Donnell", "Donnie", "Donny", "Dora", "Dorcas", "Dorian", "Doris", "Dorothea", "Dorothy", "Dorris", "Dortha", "Dorthy", "Doug", "Douglas", "Dovie", "Doyle", "Drake", "Drew", "Duane", "Dudley", "Dulce", "Duncan", "Durward", "Dustin", "Dusty", "Dwight", "Dylan", "Earl", "Earlene", "Earline", "Earnest", "Earnestine", "Easter", "Easton", "Ebba", "Ebony", "Ed", "Eda", "Edd", "Eddie", "Eden", "Edgar", "Edgardo", "Edison", "Edmond", "Edmund", "Edna", "Eduardo", "Edward", "Edwardo", "Edwin", "Edwina", "Edyth", "Edythe", "Effie", "Efrain", "Efren", "Eileen", "Einar", "Eino", "Eladio", "Elaina", "Elbert", "Elda", "Eldon", "Eldora", "Eldred", "Eldridge", "Eleanora", "Eleanore", "Eleazar", "Electa", "Elena", "Elenor", "Elenora", "Eleonore", "Elfrieda", "Eli", "Elian", "Eliane", "Elias", "Eliezer", "Elijah", "Elinor", "Elinore", "Elisa", "Elisabeth", "Elise", "Eliseo", "Elisha", "Elissa", "Eliza", "Elizabeth", "Ella", "Ellen", "Ellie", "Elliot", "Elliott", "Ellis", "Ellsworth", "Elmer", "Elmira", "Elmo", "Elmore", "Elna", "Elnora", "Elody", "Eloisa", "Eloise", "Elouise", "Eloy", "Elroy", "Elsa", "Else", "Elsie", "Elta", "Elton", "Elva", "Elvera", "Elvie", "Elvis", "Elwin", "Elwyn", "Elyse", "Elyssa", "Elza", "Emanuel", "Emelia", "Emelie", "Emely", "Emerald", "Emerson", "Emery", "Emie", "Emil", "Emile", "Emilia", "Emiliano", "Emilie", "Emilio", "Emily", "Emma", "Emmalee", "Emmanuel", "Emmanuelle", "Emmet", "Emmett", "Emmie", "Emmitt", "Emmy", "Emory", "Ena", "Enid", "Enoch", "Enola", "Enos", "Enrico", "Enrique", "Ephraim", "Era", "Eriberto", "Eric", "Erica", "Erich", "Erick", "Ericka", "Erik", "Erika", "Erin", "Erling", "Erna", "Ernest", "Ernestina", "Ernestine", "Ernesto", "Ernie", "Ervin", "Erwin", "Eryn", "Esmeralda", "Esperanza", "Esta", "Esteban", "Estefania", "Estel", "Estell", "Estella", "Estelle", "Estevan", "Esther", "Estrella", "Etha", "Ethan", "Ethel", "Ethelyn", "Ethyl", "Ettie", "Eudora", "Eugene", "Eugenia", "Eula", "Eulah", "Eulalia", "Euna", "Eunice", "Eusebio", "Eva", "Evalyn", "Evan", "Evangeline", "Evans", "Eve", "Eveline", "Evelyn", "Everardo", "Everett", "Everette", "Evert", "Evie", "Ewald", "Ewell", "Ezekiel", "Ezequiel", "Ezra", "Fabian", "Fabiola", "Fae", "Fannie", "Fanny", "Fatima", "Faustino", "Fausto", "Favian", "Fay", "Faye", "Federico", "Felicia", "Felicita", "Felicity", "Felipa", "Felipe", "Felix", "Felton", "Fermin", "Fern", "Fernando", "Ferne", "Fidel", "Filiberto", "Filomena", "Finn", "Fiona", "Flavie", "Flavio", "Fleta", "Fletcher", "Flo", "Florence", "Florencio", "Florian", "Florida", "Florine", "Flossie", "Floy", "Floyd", "Ford", "Forest", "Forrest", "Foster", "Frances", "Francesca", "Francesco", "Francis", "Francisca", "Francisco", "Franco", "Frank", "Frankie", "Franz", "Fred", "Freda", "Freddie", "Freddy", "Frederic", "Frederick", "Frederik", "Frederique", "Fredrick", "Fredy", "Freeda", "Freeman", "Freida", "Frida", "Frieda", "Friedrich", "Fritz", "Furman", "Gabe", "Gabriel", "Gabriella", "Gabrielle", "Gaetano", "Gage", "Gail", "Gardner", "Garett", "Garfield", "Garland", "Garnet", "Garnett", "Garret", "Garrett", "Garrick", "Garrison", "Garry", "Garth", "Gaston", "Gavin", "Gay", "Gayle", "Gaylord", "Gene", "General", "Genesis", "Genevieve", "Gennaro", "Genoveva", "Geo", "Geoffrey", "George", "Georgette", "Georgiana", "Georgianna", "Geovanni", "Geovanny", "Geovany", "Gerald", "Geraldine", "Gerard", "Gerardo", "Gerda", "Gerhard", "Germaine", "German", "Gerry", "Gerson", "Gertrude", "Gia", "Gianni", "Gideon", "Gilbert", "Gilberto", "Gilda", "Giles", "Gillian", "Gina", "Gino", "Giovani", "Giovanna", "Giovanni", "Giovanny", "Gisselle", "Giuseppe", "Gladyce", "Gladys", "Glen", "Glenda", "Glenna", "Glennie", "Gloria", "Godfrey", "Golda", "Golden", "Gonzalo", "Gordon", "Grace", "Gracie", "Graciela", "Grady", "Graham", "Grant", "Granville", "Grayce", "Grayson", "Green", "Greg", "Gregg", "Gregoria", "Gregorio", "Gregory", "Greta", "Gretchen", "Greyson", "Griffin", "Grover", "Guadalupe", "Gudrun", "Guido", "Guillermo", "Guiseppe", "Gunnar", "Gunner", "Gus", "Gussie", "Gust", "Gustave", "Guy", "Gwen", "Gwendolyn", "Hadley", "Hailee", "Hailey", "Hailie", "Hal", "Haleigh", "Haley", "Halie", "Halle", "Hallie", "Hank", "Hanna", "Hannah", "Hans", "Hardy", "Harley", "Harmon", "Harmony", "Harold", "Harrison", "Harry", "Harvey", "Haskell", "Hassan", "Hassie", "Hattie", "Haven", "Hayden", "Haylee", "Hayley", "Haylie", "Hazel", "Hazle", "Heath", "Heather", "Heaven", "Heber", "Hector", "Heidi", "Helen", "Helena", "Helene", "Helga", "Hellen", "Helmer", "Heloise", "Henderson", "Henri", "Henriette", "Henry", "Herbert", "Herman", "Hermann", "Hermina", "Herminia", "Herminio", "Hershel", "Herta", "Hertha", "Hester", "Hettie", "Hilario", "Hilbert", "Hilda", "Hildegard", "Hillard", "Hillary", "Hilma", "Hilton", "Hipolito", "Hiram", "Hobart", "Holden", "Hollie", "Hollis", "Holly", "Hope", "Horace", "Horacio", "Hortense", "Hosea", "Houston", "Howard", "Howell", "Hoyt", "Hubert", "Hudson", "Hugh", "Hulda", "Humberto", "Hunter", "Hyman", "Ian", "Ibrahim", "Icie", "Ida", "Idell", "Idella", "Ignacio", "Ignatius", "Ike", "Ila", "Ilene", "Iliana", "Ima", "Imani", "Imelda", "Immanuel", "Imogene", "Ines", "Irma", "Irving", "Irwin", "Isaac", "Isabel", "Isabell", "Isabella", "Isabelle", "Isac", "Isadore", "Isai", "Isaiah", "Isaias", "Isidro", "Ismael", "Isobel", "Isom", "Israel", "Issac", "Itzel", "Iva", "Ivah", "Ivory", "Ivy", "Izabella", "Izaiah", "Jabari", "Jace", "Jacey", "Jacinthe", "Jacinto", "Jack", "Jackeline", "Jackie", "Jacklyn", "Jackson", "Jacky", "Jaclyn", "Jacquelyn", "Jacques", "Jacynthe", "Jada", "Jade", "Jaden", "Jadon", "Jadyn", "Jaeden", "Jaida", "Jaiden", "Jailyn", "Jaime", "Jairo", "Jakayla", "Jake", "Jakob", "Jaleel", "Jalen", "Jalon", "Jalyn", "Jamaal", "Jamal", "Jamar", "Jamarcus", "Jamel", "Jameson", "Jamey", "Jamie", "Jamil", "Jamir", "Jamison", "Jammie", "Jan", "Jana", "Janae", "Jane", "Janelle", "Janessa", "Janet", "Janice", "Janick", "Janie", "Janis", "Janiya", "Jannie", "Jany", "Jaquan", "Jaquelin", "Jaqueline", "Jared", "Jaren", "Jarod", "Jaron", "Jarred", "Jarrell", "Jarret", "Jarrett", "Jarrod", "Jarvis", "Jasen", "Jasmin", "Jason", "Jasper", "Jaunita", "Javier", "Javon", "Javonte", "Jay", "Jayce", "Jaycee", "Jayda", "Jayde", "Jayden", "Jaydon", "Jaylan", "Jaylen", "Jaylin", "Jaylon", "Jayme", "Jayne", "Jayson", "Jazlyn", "Jazmin", "Jazmyn", "Jazmyne", "Jean", "Jeanette", "Jeanie", "Jeanne", "Jed", "Jedediah", "Jedidiah", "Jeff", "Jefferey", "Jeffery", "Jeffrey", "Jeffry", "Jena", "Jenifer", "Jennie", "Jennifer", "Jennings", "Jennyfer", "Jensen", "Jerad", "Jerald", "Jeramie", "Jeramy", "Jerel", "Jeremie", "Jeremy", "Jermain", "Jermaine", "Jermey", "Jerod", "Jerome", "Jeromy", "Jerrell", "Jerrod", "Jerrold", "Jerry", "Jess", "Jesse", "Jessica", "Jessie", "Jessika", "Jessy", "Jessyca", "Jesus", "Jett", "Jettie", "Jevon", "Jewel", "Jewell", "Jillian", "Jimmie", "Jimmy", "Jo", "Joan", "Joana", "Joanie", "Joanne", "Joannie", "Joanny", "Joany", "Joaquin", "Jocelyn", "Jodie", "Jody", "Joe", "Joel", "Joelle", "Joesph", "Joey", "Johan", "Johann", "Johanna", "Johathan", "John", "Johnathan", "Johnathon", "Johnnie", "Johnny", "Johnpaul", "Johnson", "Jolie", "Jon", "Jonas", "Jonatan", "Jonathan", "Jonathon", "Jordan", "Jordane", "Jordi", "Jordon", "Jordy", "Jordyn", "Jorge", "Jose", "Josefa", "Josefina", "Joseph", "Josephine", "Josh", "Joshua", "Joshuah", "Josiah", "Josiane", "Josianne", "Josie", "Josue", "Jovan", "Jovani", "Jovanny", "Jovany", "Joy", "Joyce", "Juana", "Juanita", "Judah", "Judd", "Jude", "Judge", "Judson", "Judy", "Jules", "Julia", "Julian", "Juliana", "Julianne", "Julie", "Julien", "Juliet", "Julio", "Julius", "June", "Junior", "Junius", "Justen", "Justice", "Justina", "Justine", "Juston", "Justus", "Justyn", "Juvenal", "Juwan", "Kacey", "Kaci", "Kacie", "Kade", "Kaden", "Kadin", "Kaela", "Kaelyn", "Kaia", "Kailee", "Kailey", "Kailyn", "Kaitlin", "Kaitlyn", "Kale", "Kaleb", "Kaleigh", "Kaley", "Kali", "Kallie", "Kameron", "Kamille", "Kamren", "Kamron", "Kamryn", "Kane", "Kara", "Kareem", "Karelle", "Karen", "Kari", "Kariane", "Karianne", "Karina", "Karine", "Karl", "Karlee", "Karley", "Karli", "Karlie", "Karolann", "Karson", "Kasandra", "Kasey", "Kassandra", "Katarina", "Katelin", "Katelyn", "Katelynn", "Katharina", "Katherine", "Katheryn", "Kathleen", "Kathlyn", "Kathryn", "Kathryne", "Katlyn", "Katlynn", "Katrina", "Katrine", "Kattie", "Kavon", "Kay", "Kaya", "Kaycee", "Kayden", "Kayla", "Kaylah", "Kaylee", "Kayleigh", "Kayley", "Kayli", "Kaylie", "Kaylin", "Keagan", "Keanu", "Keara", "Keaton", "Keegan", "Keeley", "Keely", "Keenan", "Keira", "Keith", "Kellen", "Kelley", "Kelli", "Kellie", "Kelly", "Kelsi", "Kelsie", "Kelton", "Kelvin", "Ken", "Kendall", "Kendra", "Kendrick", "Kenna", "Kennedi", "Kennedy", "Kenneth", "Kennith", "Kenny", "Kenton", "Kenya", "Kenyatta", "Kenyon", "Keon", "Keshaun", "Keshawn", "Keven", "Kevin", "Kevon", "Keyon", "Keyshawn", "Khalid", "Khalil", "Kian", "Kiana", "Kianna", "Kiara", "Kiarra", "Kiel", "Kiera", "Kieran", "Kiley", "Kim", "Kimberly", "King", "Kip", "Kira", "Kirk", "Kirsten", "Kirstin", "Kitty", "Kobe", "Koby", "Kody", "Kolby", "Kole", "Korbin", "Korey", "Kory", "Kraig", "Kris", "Krista", "Kristian", "Kristin", "Kristina", "Kristofer", "Kristoffer", "Kristopher", "Kristy", "Krystal", "Krystel", "Krystina", "Kurt", "Kurtis", "Kyla", "Kyle", "Kylee", "Kyleigh", "Kyler", "Kylie", "Kyra", "Lacey", "Lacy", "Ladarius", "Lafayette", "Laila", "Laisha", "Lamar", "Lambert", "Lamont", "Lance", "Landen", "Lane", "Laney", "Larissa", "Laron", "Larry", "Larue", "Laura", "Laurel", "Lauren", "Laurence", "Lauretta", "Lauriane", "Laurianne", "Laurie", "Laurine", "Laury", "Lauryn", "Lavada", "Lavern", "Laverna", "Laverne", "Lavina", "Lavinia", "Lavon", "Lavonne", "Lawrence", "Lawson", "Layla", "Layne", "Lazaro", "Lea", "Leann", "Leanna", "Leanne", "Leatha", "Leda", "Lee", "Leif", "Leila", "Leilani", "Lela", "Lelah", "Leland", "Lelia", "Lempi", "Lemuel", "Lenna", "Lennie", "Lenny", "Lenora", "Lenore", "Leo", "Leola", "Leon", "Leonard", "Leonardo", "Leone", "Leonel", "Leonie", "Leonor", "Leonora", "Leopold", "Leopoldo", "Leora", "Lera", "Lesley", "Leslie", "Lesly", "Lessie", "Lester", "Leta", "Letha", "Letitia", "Levi", "Lew", "Lewis", "Lexi", "Lexie", "Lexus", "Lia", "Liam", "Liana", "Libbie", "Libby", "Lila", "Lilian", "Liliana", "Liliane", "Lilla", "Lillian", "Lilliana", "Lillie", "Lilly", "Lily", "Lilyan", "Lina", "Lincoln", "Linda", "Lindsay", "Lindsey", "Linnea", "Linnie", "Linwood", "Lionel", "Lisa", "Lisandro", "Lisette", "Litzy", "Liza", "Lizeth", "Lizzie", "Llewellyn", "Lloyd", "Logan", "Lois", "Lola", "Lolita", "Loma", "Lon", "London", "Lonie", "Lonnie", "Lonny", "Lonzo", "Lora", "Loraine", "Loren", "Lorena", "Lorenz", "Lorenza", "Lorenzo", "Lori", "Lorine", "Lorna", "Lottie", "Lou", "Louie", "Louisa", "Lourdes", "Louvenia", "Lowell", "Loy", "Loyal", "Loyce", "Lucas", "Luciano", "Lucie", "Lucienne", "Lucile", "Lucinda", "Lucio", "Lucious", "Lucius", "Lucy", "Ludie", "Ludwig", "Lue", "Luella", "Luigi", "Luis", "Luisa", "Lukas", "Lula", "Lulu", "Luna", "Lupe", "Lura", "Lurline", "Luther", "Luz", "Lyda", "Lydia", "Lyla", "Lynn", "Lyric", "Lysanne", "Mabel", "Mabelle", "Mable", "Mac", "Macey", "Maci", "Macie", "Mack", "Mackenzie", "Macy", "Madaline", "Madalyn", "Maddison", "Madeline", "Madelyn", "Madelynn", "Madge", "Madie", "Madilyn", "Madisen", "Madison", "Madisyn", "Madonna", "Madyson", "Mae", "Maegan", "Maeve", "Mafalda", "Magali", "Magdalen", "Magdalena", "Maggie", "Magnolia", "Magnus", "Maia", "Maida", "Maiya", "Major", "Makayla", "Makenna", "Makenzie", "Malachi", "Malcolm", "Malika", "Malinda", "Mallie", "Mallory", "Malvina", "Mandy", "Manley", "Manuel", "Manuela", "Mara", "Marc", "Marcel", "Marcelina", "Marcelino", "Marcella", "Marcelle", "Marcellus", "Marcelo", "Marcia", "Marco", "Marcos", "Marcus", "Margaret", "Margarete", "Margarett", "Margaretta", "Margarette", "Margarita", "Marge", "Margie", "Margot", "Margret", "Marguerite", "Maria", "Mariah", "Mariam", "Marian", "Mariana", "Mariane", "Marianna", "Marianne", "Mariano", "Maribel", "Marie", "Mariela", "Marielle", "Marietta", "Marilie", "Marilou", "Marilyne", "Marina", "Mario", "Marion", "Marisa", "Marisol", "Maritza", "Marjolaine", "Marjorie", "Marjory", "Mark", "Markus", "Marlee", "Marlen", "Marlene", "Marley", "Marlin", "Marlon", "Marques", "Marquis", "Marquise", "Marshall", "Marta", "Martin", "Martina", "Martine", "Marty", "Marvin", "Mary", "Maryam", "Maryjane", "Maryse", "Mason", "Mateo", "Mathew", "Mathias", "Mathilde", "Matilda", "Matilde", "Matt", "Matteo", "Mattie", "Maud", "Maude", "Maudie", "Maureen", "Maurice", "Mauricio", "Maurine", "Maverick", "Mavis", "Max", "Maxie", "Maxime", "Maximilian", "Maximillia", "Maximillian", "Maximo", "Maximus", "Maxine", "Maxwell", "May", "Maya", "Maybell", "Maybelle", "Maye", "Maymie", "Maynard", "Mayra", "Mazie", "Mckayla", "Mckenna", "Mckenzie", "Meagan", "Meaghan", "Meda", "Megane", "Meggie", "Meghan", "Mekhi", "Melany", "Melba", "Melisa", "Melissa", "Mellie", "Melody", "Melvin", "Melvina", "Melyna", "Melyssa", "Mercedes", "Meredith", "Merl", "Merle", "Merlin", "Merritt", "Mertie", "Mervin", "Meta", "Mia", "Micaela", "Micah", "Michael", "Michaela", "Michale", "Micheal", "Michel", "Michele", "Michelle", "Miguel", "Mikayla", "Mike", "Mikel", "Milan", "Miles", "Milford", "Miller", "Millie", "Milo", "Milton", "Mina", "Minerva", "Minnie", "Miracle", "Mireille", "Mireya", "Misael", "Missouri", "Misty", "Mitchel", "Mitchell", "Mittie", "Modesta", "Modesto", "Mohamed", "Mohammad", "Mohammed", "Moises", "Mollie", "Molly", "Mona", "Monica", "Monique", "Monroe", "Monserrat", "Monserrate", "Montana", "Monte", "Monty", "Morgan", "Moriah", "Morris", "Mortimer", "Morton", "Mose", "Moses", "Moshe", "Mossie", "Mozell", "Mozelle", "Muhammad", "Muriel", "Murl", "Murphy", "Murray", "Mustafa", "Mya", "Myah", "Mylene", "Myles", "Myra", "Myriam", "Myrl", "Myrna", "Myron", "Myrtice", "Myrtie", "Myrtis", "Myrtle", "Nadia", "Nakia", "Name", "Nannie", "Naomi", "Naomie", "Napoleon", "Narciso", "Nash", "Nasir", "Nat", "Natalia", "Natalie", "Natasha", "Nathan", "Nathanael", "Nathanial", "Nathaniel", "Nathen", "Nayeli", "Neal", "Ned", "Nedra", "Neha", "Neil", "Nelda", "Nella", "Nelle", "Nellie", "Nels", "Nelson", "Neoma", "Nestor", "Nettie", "Neva", "Newell", "Newton", "Nia", "Nicholas", "Nicholaus", "Nichole", "Nick", "Nicklaus", "Nickolas", "Nico", "Nicola", "Nicolas", "Nicole", "Nicolette", "Nigel", "Nikita", "Nikki", "Nikko", "Niko", "Nikolas", "Nils", "Nina", "Noah", "Noble", "Noe", "Noel", "Noelia", "Noemi", "Noemie", "Noemy", "Nola", "Nolan", "Nona", "Nora", "Norbert", "Norberto", "Norene", "Norma", "Norris", "Norval", "Norwood", "Nova", "Novella", "Nya", "Nyah", "Nyasia", "Obie", "Oceane", "Ocie", "Octavia", "Oda", "Odell", "Odessa", "Odie", "Ofelia", "Okey", "Ola", "Olaf", "Ole", "Olen", "Oleta", "Olga", "Olin", "Oliver", "Ollie", "Oma", "Omari", "Omer", "Ona", "Onie", "Opal", "Ophelia", "Ora", "Oral", "Oran", "Oren", "Orie", "Orin", "Orion", "Orland", "Orlando", "Orlo", "Orpha", "Orrin", "Orval", "Orville", "Osbaldo", "Osborne", "Oscar", "Osvaldo", "Oswald", "Oswaldo", "Otha", "Otho", "Otilia", "Otis", "Ottilie", "Ottis", "Otto", "Ova", "Owen", "Ozella", "Pablo", "Paige", "Palma", "Pamela", "Pansy", "Paolo", "Paris", "Parker", "Pascale", "Pasquale", "Pat", "Patience", "Patricia", "Patrick", "Patsy", "Pattie", "Paul", "Paula", "Pauline", "Paxton", "Payton", "Pearl", "Pearlie", "Pearline", "Pedro", "Peggie", "Penelope", "Percival", "Percy", "Perry", "Pete", "Peter", "Petra", "Peyton", "Philip", "Phoebe", "Phyllis", "Pierce", "Pierre", "Pietro", "Pink", "Pinkie", "Piper", "Polly", "Porter", "Precious", "Presley", "Preston", "Price", "Prince", "Princess", "Priscilla", "Providenci", "Prudence", "Queen", "Queenie", "Quentin", "Quincy", "Quinn", "Quinten", "Quinton", "Rachael", "Rachel", "Rachelle", "Rae", "Raegan", "Rafael", "Rafaela", "Raheem", "Rahsaan", "Rahul", "Raina", "Raleigh", "Ralph", "Ramiro", "Ramon", "Ramona", "Randal", "Randall", "Randi", "Randy", "Ransom", "Raoul", "Raphael", "Raphaelle", "Raquel", "Rashad", "Rashawn", "Rasheed", "Raul", "Raven", "Ray", "Raymond", "Raymundo", "Reagan", "Reanna", "Reba", "Rebeca", "Rebecca", "Rebeka", "Rebekah", "Reece", "Reed", "Reese", "Regan", "Reggie", "Reginald", "Reid", "Reilly", "Reina", "Reinhold", "Remington", "Rene", "Renee", "Ressie", "Reta", "Retha", "Retta", "Reuben", "Reva", "Rex", "Rey", "Reyes", "Reymundo", "Reyna", "Reynold", "Rhea", "Rhett", "Rhianna", "Rhiannon", "Rhoda", "Ricardo", "Richard", "Richie", "Richmond", "Rick", "Rickey", "Rickie", "Ricky", "Rico", "Rigoberto", "Riley", "Rita", "River", "Robb", "Robbie", "Robert", "Roberta", "Roberto", "Robin", "Robyn", "Rocio", "Rocky", "Rod", "Roderick", "Rodger", "Rodolfo", "Rodrick", "Rodrigo", "Roel", "Rogelio", "Roger", "Rogers", "Rolando", "Rollin", "Roma", "Romaine", "Roman", "Ron", "Ronaldo", "Ronny", "Roosevelt", "Rory", "Rosa", "Rosalee", "Rosalia", "Rosalind", "Rosalinda", "Rosalyn", "Rosamond", "Rosanna", "Rosario", "Roscoe", "Rose", "Rosella", "Roselyn", "Rosemarie", "Rosemary", "Rosendo", "Rosetta", "Rosie", "Rosina", "Roslyn", "Ross", "Rossie", "Rowan", "Rowena", "Rowland", "Roxane", "Roxanne", "Roy", "Royal", "Royce", "Rozella", "Ruben", "Rubie", "Ruby", "Rubye", "Rudolph", "Rudy", "Rupert", "Russ", "Russel", "Russell", "Rusty", "Ruth", "Ruthe", "Ruthie", "Ryan", "Ryann", "Ryder", "Rylan", "Rylee", "Ryleigh", "Ryley", "Sabina", "Sabrina", "Sabryna", "Sadie", "Sadye", "Sage", "Saige", "Sallie", "Sally", "Salma", "Salvador", "Salvatore", "Sam", "Samanta", "Samantha", "Samara", "Samir", "Sammie", "Sammy", "Samson", "Sandra", "Sandrine", "Sandy", "Sanford", "Santa", "Santiago", "Santina", "Santino", "Santos", "Sarah", "Sarai", "Sarina", "Sasha", "Saul", "Savanah", "Savanna", "Savannah", "Savion", "Scarlett", "Schuyler", "Scot", "Scottie", "Scotty", "Seamus", "Sean", "Sebastian", "Sedrick", "Selena", "Selina", "Selmer", "Serena", "Serenity", "Seth", "Shad", "Shaina", "Shakira", "Shana", "Shane", "Shanel", "Shanelle", "Shania", "Shanie", "Shaniya", "Shanna", "Shannon", "Shanny", "Shanon", "Shany", "Sharon", "Shaun", "Shawn", "Shawna", "Shaylee", "Shayna", "Shayne", "Shea", "Sheila", "Sheldon", "Shemar", "Sheridan", "Sherman", "Sherwood", "Shirley", "Shyann", "Shyanne", "Sibyl", "Sid", "Sidney", "Sienna", "Sierra", "Sigmund", "Sigrid", "Sigurd", "Silas", "Sim", "Simeon", "Simone", "Sincere", "Sister", "Skye", "Skyla", "Skylar", "Sofia", "Soledad", "Solon", "Sonia", "Sonny", "Sonya", "Sophia", "Sophie", "Spencer", "Stacey", "Stacy", "Stan", "Stanford", "Stanley", "Stanton", "Stefan", "Stefanie", "Stella", "Stephan", "Stephania", "Stephanie", "Stephany", "Stephen", "Stephon", "Sterling", "Steve", "Stevie", "Stewart", "Stone", "Stuart", "Summer", "Sunny", "Susan", "Susana", "Susanna", "Susie", "Suzanne", "Sven", "Syble", "Sydnee", "Sydney", "Sydni", "Sydnie", "Sylvan", "Sylvester", "Sylvia", "Tabitha", "Tad", "Talia", "Talon", "Tamara", "Tamia", "Tania", "Tanner", "Tanya", "Tara", "Taryn", "Tate", "Tatum", "Tatyana", "Taurean", "Tavares", "Taya", "Taylor", "Teagan", "Ted", "Telly", "Terence", "Teresa", "Terrance", "Terrell", "Terrence", "Terrill", "Terry", "Tess", "Tessie", "Tevin", "Thad", "Thaddeus", "Thalia", "Thea", "Thelma", "Theo", "Theodora", "Theodore", "Theresa", "Therese", "Theresia", "Theron", "Thomas", "Thora", "Thurman", "Tia", "Tiana", "Tianna", "Tiara", "Tierra", "Tiffany", "Tillman", "Timmothy", "Timmy", "Timothy", "Tina", "Tito", "Titus", "Tobin", "Toby", "Tod", "Tom", "Tomas", "Tomasa", "Tommie", "Toney", "Toni", "Tony", "Torey", "Torrance", "Torrey", "Toy", "Trace", "Tracey", "Tracy", "Travis", "Travon", "Tre", "Tremaine", "Tremayne", "Trent", "Trenton", "Tressa", "Tressie", "Treva", "Trever", "Trevion", "Trevor", "Trey", "Trinity", "Trisha", "Tristian", "Tristin", "Triston", "Troy", "Trudie", "Trycia", "Trystan", "Turner", "Twila", "Tyler", "Tyra", "Tyree", "Tyreek", "Tyrel", "Tyrell", "Tyrese", "Tyrique", "Tyshawn", "Tyson", "Ubaldo", "Ulices", "Ulises", "Una", "Unique", "Urban", "Uriah", "Uriel", "Ursula", "Vada", "Valentin", "Valentina", "Valentine", "Valerie", "Vallie", "Van", "Vance", "Vanessa", "Vaughn", "Veda", "Velda", "Vella", "Velma", "Velva", "Vena", "Verda", "Verdie", "Vergie", "Verla", "Verlie", "Vern", "Verna", "Verner", "Vernice", "Vernie", "Vernon", "Verona", "Veronica", "Vesta", "Vicenta", "Vicente", "Vickie", "Vicky", "Victor", "Victoria", "Vida", "Vidal", "Vilma", "Vince", "Vincent", "Vincenza", "Vincenzo", "Vinnie", "Viola", "Violet", "Violette", "Virgie", "Virgil", "Virginia", "Virginie", "Vita", "Vito", "Viva", "Vivian", "Viviane", "Vivianne", "Vivien", "Vivienne", "Vladimir", "Wade", "Waino", "Waldo", "Walker", "Wallace", "Walter", "Walton", "Wanda", "Ward", "Warren", "Watson", "Wava", "Waylon", "Wayne", "Webster", "Weldon", "Wellington", "Wendell", "Wendy", "Werner", "Westley", "Weston", "Whitney", "Wilber", "Wilbert", "Wilburn", "Wiley", "Wilford", "Wilfred", "Wilfredo", "Wilfrid", "Wilhelm", "Wilhelmine", "Will", "Willa", "Willard", "William", "Willie", "Willis", "Willow", "Willy", "Wilma", "Wilmer", "Wilson", "Wilton", "Winfield", "Winifred", "Winnifred", "Winona", "Winston", "Woodrow", "Wyatt", "Wyman", "Xander", "Xavier", "Xzavier", "Yadira", "Yasmeen", "Yasmin", "Yasmine", "Yazmin", "Yesenia", "Yessenia", "Yolanda", "Yoshiko", "Yvette", "Yvonne", "Zachariah", "Zachary", "Zachery", "Zack", "Zackary", "Zackery", "Zakary", "Zander", "Zane", "Zaria", "Zechariah", "Zelda", "Zella", "Zelma", "Zena", "Zetta", "Zion", "Zita", "Zoe", "Zoey", "Zoie", "Zoila", "Zola", "Zora", "Zul"]; exports.last_name = ["Abbott", "Abernathy", "Abshire", "Adams", "Altenwerth", "Anderson", "Ankunding", "Armstrong", "Auer", "Aufderhar", "Bahringer", "Bailey", "Balistreri", "Barrows", "Bartell", "Bartoletti", "Barton", "Bashirian", "Batz", "Bauch", "Baumbach", "Bayer", "Beahan", "Beatty", "Bechtelar", "Becker", "Bednar", "Beer", "Beier", "Berge", "Bergnaum", "Bergstrom", "Bernhard", "Bernier", "Bins", "Blanda", "Blick", "Block", "Bode", "Boehm", "Bogan", "Bogisich", "Borer", "Bosco", "Botsford", "Boyer", "Boyle", "Bradtke", "Brakus", "Braun", "Breitenberg", "Brekke", "Brown", "Bruen", "Buckridge", "Carroll", "Carter", "Cartwright", "Casper", "Cassin", "Champlin", "Christiansen", "Cole", "Collier", "Collins", "Conn", "Connelly", "Conroy", "Considine", "Corkery", "Cormier", "Corwin", "Cremin", "Crist", "Crona", "Cronin", "Crooks", "Cruickshank", "Cummerata", "Cummings", "Dach", "D'Amore", "Daniel", "Dare", "Daugherty", "Davis", "Deckow", "Denesik", "Dibbert", "Dickens", "Dicki", "Dickinson", "Dietrich", "Donnelly", "Dooley", "Douglas", "Doyle", "DuBuque", "Durgan", "Ebert", "Effertz", "Eichmann", "Emard", "Emmerich", "Erdman", "Ernser", "Fadel", "Fahey", "Farrell", "Fay", "Feeney", "Feest", "Feil", "Ferry", "Fisher", "Flatley", "Frami", "Franecki", "Friesen", "Fritsch", "Funk", "Gaylord", "Gerhold", "Gerlach", "Gibson", "Gislason", "Gleason", "Gleichner", "Glover", "Goldner", "Goodwin", "Gorczany", "Gottlieb", "Goyette", "Grady", "Graham", "Grant", "Green", "Greenfelder", "Greenholt", "Grimes", "Gulgowski", "Gusikowski", "Gutkowski", "Guªann", "Haag", "Hackett", "Hagenes", "Hahn", "Haley", "Halvorson", "Hamill", "Hammes", "Hand", "Hane", "Hansen", "Harber", "Harris", "Harªann", "Harvey", "Hauck", "Hayes", "Heaney", "Heathcote", "Hegmann", "Heidenreich", "Heller", "Herman", "Hermann", "Hermiston", "Herzog", "Hessel", "Hettinger", "Hickle", "Hilll", "Hills", "Hilpert", "Hintz", "Hirthe", "Hodkiewicz", "Hoeger", "Homenick", "Hoppe", "Howe", "Howell", "Hudson", "Huel", "Huels", "Hyatt", "Jacobi", "Jacobs", "Jacobson", "Jakubowski", "Jaskolski", "Jast", "Jenkins", "Jerde", "Jewess", "Johns", "Johnson", "Johnston", "Jones", "Kassulke", "Kautzer", "Keebler", "Keeling", "Kemmer", "Kerluke", "Kertzmann", "Kessler", "Kiehn", "Kihn", "Kilback", "King", "Kirlin", "Klein", "Kling", "Klocko", "Koch", "Koelpin", "Koepp", "Kohler", "Konopelski", "Koss", "Kovacek", "Kozey", "Krajcik", "Kreiger", "Kris", "Kshlerin", "Kub", "Kuhic", "Kuhlman", "Kuhn", "Kulas", "Kunde", "Kunze", "Kuphal", "Kutch", "Kuvalis", "Labadie", "Lakin", "Lang", "Langosh", "Langworth", "Larkin", "Larson", "Leannon", "Lebsack", "Ledner", "Leffler", "Legros", "Lehner", "Lemke", "Lesch", "Leuschke", "Lind", "Lindgren", "Littel", "Little", "Lockman", "Lowe", "Lubowitz", "Lueilwitz", "Luettgen", "Lynch", "Macejkovic", "Maggio", "Mann", "Mante", "Marks", "Marquardt", "Marvin", "Mayer", "Mayert", "McClure", "McCullough", "McDermott", "McGlynn", "McKenzie", "McLaughlin", "Medhurst", "Mertz", "Metz", "Miller", "Mills", "Mitchell", "Moen", "Mohr", "Monahan", "Moore", "Morar", "Morissette", "Mosciski", "Mraz", "Mueller", "Muller", "Murazik", "Murphy", "Murray", "Nader", "Nicolas", "Nienow", "Nikolaus", "Nitzsche", "Nolan", "Oberbrunner", "O'Connell", "O'Conner", "O'Hara", "O'Keefe", "O'Kon", "Okuneva", "Olson", "Ondricka", "O'Reilly", "Orn", "Ortiz", "Osinski", "Pacocha", "Padberg", "Pagac", "Parisian", "Parker", "Paucek", "Pfannerstill", "Pfeffer", "Pollich", "Pouros", "Powlowski", "Predovic", "Price", "Prohaska", "Prosacco", "Purdy", "Quigley", "Quitzon", "Rath", "Ratke", "Rau", "Raynor", "Reichel", "Reichert", "Reilly", "Reinger", "Rempel", "Renner", "Reynolds", "Rice", "Rippin", "Ritchie", "Robel", "Roberts", "Rodriguez", "Rogahn", "Rohan", "Rolfson", "Romaguera", "Roob", "Rosenbaum", "Rowe", "Ruecker", "Runolfsdottir", "Runolfsson", "Runte", "Russel", "Rutherford", "Ryan", "Sanford", "Satterfield", "Sauer", "Sawayn", "Schaden", "Schaefer", "Schamberger", "Schiller", "Schimmel", "Schinner", "Schmeler", "Schmidt", "Schmitt", "Schneider", "Schoen", "Schowalter", "Schroeder", "Schulist", "Schultz", "Schumm", "Schuppe", "Schuster", "Senger", "Shanahan", "Shields", "Simonis", "Sipes", "Skiles", "Smith", "Smitham", "Spencer", "Spinka", "Sporer", "Stamm", "Stanton", "Stark", "Stehr", "Steuber", "Stiedemann", "Stokes", "Stoltenberg", "Stracke", "Streich", "Stroman", "Strosin", "Swaniawski", "Swift", "Terry", "Thiel", "Thompson", "Tillman", "Torp", "Torphy", "Towne", "Toy", "Trantow", "Tremblay", "Treutel", "Tromp", "Turcotte", "Turner", "Ullrich", "Upton", "Vandervort", "Veum", "Volkman", "Von", "VonRueden", "Waelchi", "Walker", "Walsh", "Walter", "Ward", "Waters", "Watsica", "Weber", "Wehner", "Weimann", "Weissnat", "Welch", "West", "White", "Wiegand", "Wilderman", "Wilkinson", "Will", "Williamson", "Willms", "Windler", "Wintheiser", "Wisoky", "Wisozk", "Witting", "Wiza", "Wolf", "Wolff", "Wuckert", "Wunsch", "Wyman", "Yost", "Yundt", "Zboncak", "Zemlak", "Ziemann", "Zieme", "Zulauf"]; exports.name_prefix = ["Mr.", "Mrs.", "Ms.", "Miss", "Dr."]; exports.name_suffix = ["Jr.", "Sr.", "I", "II", "III", "IV", "V", "MD", "DDS", "PhD", "DVM"]; // address.js definitions exports.br_state = [ 'Acre', 'Alagoas', 'Amapá', 'Amazonas', 'Bahia', 'Ceará', 'Distrito Federal', 'Espírito Santo', 'Goiás', 'Maranhão', 'Mato Grosso', 'Mato Grosso do Sul', 'Minas Gerais', 'Paraná', 'Paraíba', 'Pará', 'Pernambuco', 'Piauí', 'Rio de Janeiro', 'Rio Grande do Norte', 'Rio Grande do Sul', 'Rondônia', 'Roraima', 'Santa Catarina', 'Sergipe', 'São Paulo', 'Tocantins' ]; exports.br_state_abbr = [ 'AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MT', 'MS', 'MG', 'PR', 'PB', 'PA', 'PE', 'PI', 'RJ', 'RN', 'RS', 'RO', 'RR', 'SC', 'SE', 'SP', 'TO' ]; exports.us_state = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']; exports.us_state_abbr = ["AL", "AK", "AS", "AZ", "AR", "CA", "CO", 'CT', "DE", "DC", "FM", "FL", "GA", "GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MH", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VI", "VA", "WA", "WV", "WI", "WY", "AE", "AA", "AP"]; exports.city_prefix = ["North", "East", "West", "South", "New", "Lake", "Port"]; exports.city_suffix = ["town", "ton", "land", "ville", "berg", "burgh", "borough", "bury", "view", "port", "mouth", "stad", "furt", "chester", "mouth", "fort", "haven", "side", "shire"]; exports.street_suffix = ["Alley", "Avenue", "Branch", "Bridge", "Brook", "Brooks", "Burg", "Burgs", "Bypass", "Camp", "Canyon", "Cape", "Causeway", "Center", "Centers", "Circle", "Circles", "Cliff", "Cliffs", "Club", "Common", "Corner", "Corners", "Course", "Court", "Courts", "Cove", "Coves", "Creek", "Crescent", "Crest", "Crossing", "Crossroad", "Curve", "Dale", "Dam", "Divide", "Drive", "Drive", "Drives", "Estate", "Estates", "Expressway", "Extension", "Extensions", "Fall", "Falls", "Ferry", "Field", "Fields", "Flat", "Flats", "Ford", "Fords", "Forest", "Forge", "Forges", "Fork", "Forks", "Fort", "Freeway", "Garden", "Gardens", "Gateway", "Glen", "Glens", "Green", "Greens", "Grove", "Groves", "Harbor", "Harbors", "Haven", "Heights", "Highway", "Hill", "Hills", "Hollow", "Inlet", "Inlet", "Island", "Island", "Islands", "Islands", "Isle", "Isle", "Junction", "Junctions", "Key", "Keys", "Knoll", "Knolls", "Lake", "Lakes", "Land", "Landing", "Lane", "Light", "Lights", "Loaf", "Lock", "Locks", "Locks", "Lodge", "Lodge", "Loop", "Mall", "Manor", "Manors", "Meadow", "Meadows", "Mews", "Mill", "Mills", "Mission", "Mission", "Motorway", "Mount", "Mountain", "Mountain", "Mountains", "Mountains", "Neck", "Orchard", "Oval", "Overpass", "Park", "Parks", "Parkway", "Parkways", "Pass", "Passage", "Path", "Pike", "Pine", "Pines", "Place", "Plain", "Plains", "Plains", "Plaza", "Plaza", "Point", "Points", "Port", "Port", "Ports", "Ports", "Prairie", "Prairie", "Radial", "Ramp", "Ranch", "Rapid", "Rapids", "Rest", "Ridge", "Ridges", "River", "Road", "Road", "Roads", "Roads", "Route", "Row", "Rue", "Run", "Shoal", "Shoals", "Shore", "Shores", "Skyway", "Spring", "Springs", "Springs", "Spur", "Spurs", "Square", "Square", "Squares", "Squares", "Station", "Station", "Stravenue", "Stravenue", "Stream", "Stream", "Street", "Street", "Streets", "Summit", "Summit", "Terrace", "Throughway", "Trace", "Track", "Trafficway", "Trail", "Trail", "Tunnel", "Tunnel", "Turnpike", "Turnpike", "Underpass", "Union", "Unions", "Valley", "Valleys", "Via", "Viaduct", "View", "Views", "Village", "Village", "", "Villages", "Ville", "Vista", "Vista", "Walk", "Walks", "Wall", "Way", "Ways", "Well", "Wells"]; exports.uk_county = ['Avon', 'Bedfordshire', 'Berkshire', 'Borders', 'Buckinghamshire', 'Cambridgeshire', 'Central', 'Cheshire', 'Cleveland', 'Clwyd', 'Cornwall', 'County Antrim', 'County Armagh', 'County Down', 'County Fermanagh', 'County Londonderry', 'County Tyrone', 'Cumbria', 'Derbyshire', 'Devon', 'Dorset', 'Dumfries and Galloway', 'Durham', 'Dyfed', 'East Sussex', 'Essex', 'Fife', 'Gloucestershire', 'Grampian', 'Greater Manchester', 'Gwent', 'Gwynedd County', 'Hampshire', 'Herefordshire', 'Hertfordshire', 'Highlands and Islands', 'Humberside', 'Isle of Wight', 'Kent', 'Lancashire', 'Leicestershire', 'Lincolnshire', 'Lothian', 'Merseyside', 'Mid Glamorgan', 'Norfolk', 'North Yorkshire', 'Northamptonshire', 'Northumberland', 'Nottinghamshire', 'Oxfordshire', 'Powys', 'Rutland', 'Shropshire', 'Somerset', 'South Glamorgan', 'South Yorkshire', 'Staffordshire', 'Strathclyde', 'Suffolk', 'Surrey', 'Tayside', 'Tyne and Wear', 'Warwickshire', 'West Glamorgan', 'West Midlands', 'West Sussex', 'West Yorkshire', 'Wiltshire', 'Worcestershire']; exports.uk_country = ['England', 'Scotland', 'Wales', 'Northern Ireland']; // internet.js definitions exports.catch_phrase_adjective = ["Adaptive", "Advanced", "Ameliorated", "Assimilated", "Automated", "Balanced", "Business-focused", "Centralized", "Cloned", "Compatible", "Configurable", "Cross-group", "Cross-platform", "Customer-focused", "Customizable", "Decentralized", "De-engineered", "Devolved", "Digitized", "Distributed", "Diverse", "Down-sized", "Enhanced", "Enterprise-wide", "Ergonomic", "Exclusive", "Expanded", "Extended", "Face to face", "Focused", "Front-line", "Fully-configurable", "Function-based", "Fundamental", "Future-proofed", "Grass-roots", "Horizontal", "Implemented", "Innovative", "Integrated", "Intuitive", "Inverse", "Managed", "Mandatory", "Monitored", "Multi-channelled", "Multi-lateral", "Multi-layered", "Multi-tiered", "Networked", "Object-based", "Open-architected", "Open-source", "Operative", "Optimized", "Optional", "Organic", "Organized", "Persevering", "Persistent", "Phased", "Polarised", "Pre-emptive", "Proactive", "Profit-focused", "Profound", "Programmable", "Progressive", "Public-key", "Quality-focused", "Reactive", "Realigned", "Re-contextualized", "Re-engineered", "Reduced", "Reverse-engineered", "Right-sized", "Robust", "Seamless", "Secured", "Self-enabling", "Sharable", "Stand-alone", "Streamlined", "Switchable", "Synchronised", "Synergistic", "Synergized", "Team-oriented", "Total", "Triple-buffered", "Universal", "Up-sized", "Upgradable", "User-centric", "User-friendly", "Versatile", "Virtual", "Visionary", "Vision-oriented"]; exports.catch_phrase_descriptor = ["24 hour", "24/7", "3rd generation", "4th generation", "5th generation", "6th generation", "actuating", "analyzing", "assymetric", "asynchronous", "attitude-oriented", "background", "bandwidth-monitored", "bi-directional", "bifurcated", "bottom-line", "clear-thinking", "client-driven", "client-server", "coherent", "cohesive", "composite", "context-sensitive", "contextually-based", "content-based", "dedicated", "demand-driven", "didactic", "directional", "discrete", "disintermediate", "dynamic", "eco-centric", "empowering", "encompassing", "even-keeled", "executive", "explicit", "exuding", "fault-tolerant", "foreground", "fresh-thinking", "full-range", "global", "grid-enabled", "heuristic", "high-level", "holistic", "homogeneous", "human-resource", "hybrid", "impactful", "incremental", "intangible", "interactive", "intermediate", "leading edge", "local", "logistical", "maximized", "methodical", "mission-critical", "mobile", "modular", "motivating", "multimedia", "multi-state", "multi-tasking", "national", "needs-based", "neutral", "next generation", "non-volatile", "object-oriented", "optimal", "optimizing", "radical", "real-time", "reciprocal", "regional", "responsive", "scalable", "secondary", "solution-oriented", "stable", "static", "systematic", "systemic", "system-worthy", "tangible", "tertiary", "transitional", "uniform", "upward-trending", "user-facing", "value-added", "web-enabled", "well-modulated", "zero administration", "zero defect", "zero tolerance"]; exports.catch_phrase_noun = ["ability", "access", "adapter", "algorithm", "alliance", "analyzer", "application", "approach", "architecture", "archive", "artificial intelligence", "array", "attitude", "benchmark", "budgetary management", "capability", "capacity", "challenge", "circuit", "collaboration", "complexity", "concept", "conglomeration", "contingency", "core", "customer loyalty", "database", "data-warehouse", "definition", "emulation", "encoding", "encryption", "extranet", "firmware", "flexibility", "focus group", "forecast", "frame", "framework", "function", "functionalities", "Graphic Interface", "groupware", "Graphical User Interface", "hardware", "help-desk", "hierarchy", "hub", "implementation", "info-mediaries", "infrastructure", "initiative", "installation", "instruction set", "interface", "internet solution", "intranet", "knowledge user", "knowledge base", "local area network", "leverage", "matrices", "matrix", "methodology", "middleware", "migration", "model", "moderator", "monitoring", "moratorium", "neural-net", "open architecture", "open system", "orchestration", "paradigm", "parallelism", "policy", "portal", "pricing structure", "process improvement", "product", "productivity", "project", "projection", "protocol", "secured line", "service-desk", "software", "solution", "standardization", "strategy", "structure", "success", "superstructure", "support", "synergy", "system engine", "task-force", "throughput", "time-frame", "toolset", "utilisation", "website", "workforce"]; exports.bs_adjective = ["implement", "utilize", "integrate", "streamline", "optimize", "evolve", "transform", "embrace", "enable", "orchestrate", "leverage", "reinvent", "aggregate", "architect", "enhance", "incentivize", "morph", "empower", "envisioneer", "monetize", "harness", "facilitate", "seize", "disintermediate", "synergize", "strategize", "deploy", "brand", "grow", "target", "syndicate", "synthesize", "deliver", "mesh", "incubate", "engage", "maximize", "benchmark", "expedite", "reintermediate", "whiteboard", "visualize", "repurpose", "innovate", "scale", "unleash", "drive", "extend", "engineer", "revolutionize", "generate", "exploit", "transition", "e-enable", "iterate", "cultivate", "matrix", "productize", "redefine", "recontextualize"]; exports.bs_buzz = ["clicks-and-mortar", "value-added", "vertical", "proactive", "robust", "revolutionary", "scalable", "leading-edge", "innovative", "intuitive", "strategic", "e-business", "mission-critical", "sticky", "one-to-one", "24/7", "end-to-end", "global", "B2B", "B2C", "granular", "frictionless", "virtual", "viral", "dynamic", "24/365", "best-of-breed", "killer", "magnetic", "bleeding-edge", "web-enabled", "interactive", "dot-com", "sexy", "back-end", "real-time", "efficient", "front-end", "distributed", "seamless", "extensible", "turn-key", "world-class", "open-source", "cross-platform", "cross-media", "synergistic", "bricks-and-clicks", "out-of-the-box", "enterprise", "integrated", "impactful", "wireless", "transparent", "next-generation", "cutting-edge", "user-centric", "visionary", "customized", "ubiquitous", "plug-and-play", "collaborative", "compelling", "holistic", "rich"]; exports.bs_noun = ["synergies", "web-readiness", "paradigms", "markets", "partnerships", "infrastructures", "platforms", "initiatives", "channels", "eyeballs", "communities", "ROI", "solutions", "e-tailers", "e-services", "action-items", "portals", "niches", "technologies", "content", "vortals", "supply-chains", "convergence", "relationships", "architectures", "interfaces", "e-markets", "e-commerce", "systems", "bandwidth", "infomediaries", "models", "mindshare", "deliverables", "users", "schemas", "networks", "applications", "metrics", "e-business", "functionalities", "experiences", "web services", "methodologies"]; exports.domain_suffix = ["co.uk", "com", "us", "net", "ca", "biz", "info", "name", "io", "org", "biz", "tv", "me"]; // lorem.js definitions exports.lorem = ["alias", "consequatur", "aut", "perferendis", "sit", "voluptatem", "accusantium", "doloremque", "aperiam", "eaque", "ipsa", "quae", "ab", "illo", "inventore", "veritatis", "et", "quasi", "architecto", "beatae", "vitae", "dicta", "sunt", "explicabo", "aspernatur", "aut", "odit", "aut", "fugit", "sed", "quia", "consequuntur", "magni", "dolores", "eos", "qui", "ratione", "voluptatem", "sequi", "nesciunt", "neque", "dolorem", "ipsum", "quia", "dolor", "sit", "amet", "consectetur", "adipisci", "velit", "sed", "quia", "non", "numquam", "eius", "modi", "tempora", "incidunt", "ut", "labore", "et", "dolore", "magnam", "aliquam", "quaerat", "voluptatem", "ut", "enim", "ad", "minima", "veniam", "quis", "nostrum", "exercitationem", "ullam", "corporis", "nemo", "enim", "ipsam", "voluptatem", "quia", "voluptas", "sit", "suscipit", "laboriosam", "nisi", "ut", "aliquid", "ex", "ea", "commodi", "consequatur", "quis", "autem", "vel", "eum", "iure", "reprehenderit", "qui", "in", "ea", "voluptate", "velit", "esse", "quam", "nihil", "molestiae", "et", "iusto", "odio", "dignissimos", "ducimus", "qui", "blanditiis", "praesentium", "laudantium", "totam", "rem", "voluptatum", "deleniti", "atque", "corrupti", "quos", "dolores", "et", "quas", "molestias", "excepturi", "sint", "occaecati", "cupiditate", "non", "provident", "sed", "ut", "perspiciatis", "unde", "omnis", "iste", "natus", "error", "similique", "sunt", "in", "culpa", "qui", "officia", "deserunt", "mollitia", "animi", "id", "est", "laborum", "et", "dolorum", "fuga", "et", "harum", "quidem", "rerum", "facilis", "est", "et", "expedita", "distinctio", "nam", "libero", "tempore", "cum", "soluta", "nobis", "est", "eligendi", "optio", "cumque", "nihil", "impedit", "quo", "porro", "quisquam", "est", "qui", "minus", "id", "quod", "maxime", "placeat", "facere", "possimus", "omnis", "voluptas", "assumenda", "est", "omnis", "dolor", "repellendus", "temporibus", "autem", "quibusdam", "et", "aut", "consequatur", "vel", "illum", "qui", "dolorem", "eum", "fugiat", "quo", "voluptas", "nulla", "pariatur", "at", "vero", "eos", "et", "accusamus", "officiis", "debitis", "aut", "rerum", "necessitatibus", "saepe", "eveniet", "ut", "et", "voluptates", "repudiandae", "sint", "et", "molestiae", "non", "recusandae", "itaque", "earum", "rerum", "hic", "tenetur", "a", "sapiente", "delectus", "ut", "aut", "reiciendis", "voluptatibus", "maiores", "doloribus", "asperiores", "repellat"]; // phone_number.js definitions exports.phone_formats = [ '###-###-####', '(###)###-####', '1-###-###-####', '###.###.####', '###-###-####', '(###)###-####', '1-###-###-####', '###.###.####', '###-###-#### x###', '(###)###-#### x###', '1-###-###-#### x###', '###.###.#### x###', '###-###-#### x####', '(###)###-#### x####', '1-###-###-#### x####', '###.###.#### x####', '###-###-#### x#####', '(###)###-#### x#####', '1-###-###-#### x#####', '###.###.#### x#####' ]; //All this avatar have been authorized by its awesome users to be use on live websites (not just mockups) //For more information, please visit: http://uifaces.com/authorized exports.avatar_uri = ["https://s3.amazonaws.com/uifaces/faces/twitter/jarjan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mahdif/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sprayaga/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ruzinav/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Skyhartman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/moscoz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kurafire/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/91bilal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/igorgarybaldi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/malykhinv/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joelhelin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kushsolitary/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/coreyweb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/snowshade/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/areus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/holdenweb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/heyimjuani/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/envex/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/unterdreht/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/collegeman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/peejfancher/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andyisonline/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ultragex/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fuck_you_two/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adellecharles/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ateneupopular/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ahmetalpbalkan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Stievius/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kerem/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/osvaldas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/angelceballos/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thierrykoblentz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/peterlandt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/catarino/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/weglov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brandclay/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/flame_kaizar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ahmetsulek/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nicolasfolliot/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jayrobinson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/victorerixon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kolage/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michzen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/markjenkins/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nicolai_larsen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/noxdzine/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alagoon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/idiot/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mizko/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chadengle/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mutlu82/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/simobenso/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vocino/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/guiiipontes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/soyjavi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joshaustin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tomaslau/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/VinThomas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ManikRathee/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/langate/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cemshid/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/leemunroe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_shahedk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/enda/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/BillSKenney/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/divya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joshhemsley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sindresorhus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/soffes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/9lessons/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/linux29/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Chakintosh/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/anaami/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joreira/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shadeed9/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scottkclark/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jedbridges/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/salleedesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marakasina/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ariil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/BrianPurkiss/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michaelmartinho/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bublienko/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/devankoshal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ZacharyZorbas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/timmillwood/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joshuasortino/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/damenleeturks/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tomas_janousek/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/herrhaase/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/RussellBishop/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brajeshwar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nachtmeister/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cbracco/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bermonpainter/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/abdullindenis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/isacosta/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/suprb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yalozhkin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chandlervdw/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iamgarth/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_victa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/commadelimited/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/roybarberuk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/axel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vladarbatov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ffbel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/syropian/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ankitind/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/traneblow/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/flashmurphy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ChrisFarina78/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/baliomega/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/saschamt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jm_denis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/anoff/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kennyadr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chatyrko/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dingyi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mds/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/terryxlife/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aaroni/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kinday/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/prrstn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/eduardostuart/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dhilipsiva/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/GavicoInd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/baires/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rohixx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/blakesimkins/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/leeiio/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tjrus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/uberschizo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kylefoundry/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/claudioguglieri/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ripplemdk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/exentrich/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jakemoore/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joaoedumedeiros/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/poormini/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tereshenkov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/keryilmaz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/haydn_woods/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rude/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/llun/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sgaurav_baghel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jamiebrittain/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/badlittleduck/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pifagor/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/agromov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/benefritz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/erwanhesry/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/diesellaws/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeremiaha/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/koridhandy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chaensel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andrewcohen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/smaczny/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gonzalorobaina/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nandini_m/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sydlawrence/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cdharrison/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tgerken/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lewisainslie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/charliecwaite/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/robbschiller/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/flexrs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mattdetails/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/raquelwilson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/karsh/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mrmartineau/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/opnsrce/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hgharrygo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/maximseshuk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/uxalex/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/samihah/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chanpory/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sharvin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/josemarques/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jefffis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/krystalfister/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lokesh_coder/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thedamianhdez/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dpmachado/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/funwatercat/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/timothycd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ivanfilipovbg/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/picard102/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marcobarbosa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/krasnoukhov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/g3d/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ademilter/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rickdt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/operatino/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bungiwan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hugomano/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/logorado/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dc_user/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/horaciobella/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/SlaapMe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/teeragit/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iqonicd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ilya_pestov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andrewarrow/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ssiskind/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/HenryHoffman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rdsaunders/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adamsxu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/curiousoffice/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/themadray/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michigangraham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kohette/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nickfratter/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/runningskull/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/madysondesigns/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brenton_clarke/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jennyshen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bradenhamm/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kurtinc/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/amanruzaini/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/coreyhaggard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Karimmove/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aaronalfred/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wtrsld/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jitachi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/therealmarvin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pmeissner/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ooomz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chacky14/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jesseddy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thinmatt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shanehudson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/akmur/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/IsaryAmairani/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/arthurholcombe1/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andychipster/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/boxmodel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ehsandiary/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/LucasPerdidao/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shalt0ni/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/swaplord/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kaelifa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/plbabin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/guillemboti/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/arindam_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/renbyrd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thiagovernetti/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jmillspaysbills/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mikemai2awesome/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jervo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mekal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sta1ex/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/robergd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/felipecsl/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andrea211087/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/garand/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dhooyenga/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/abovefunction/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pcridesagain/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/randomlies/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/BryanHorsey/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/heykenneth/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dahparra/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/allthingssmitty/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danvernon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/beweinreich/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/increase/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/falvarad/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alxndrustinov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/souuf/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/orkuncaylar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/AM_Kn2/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gearpixels/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bassamology/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vimarethomas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kosmar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/SULiik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mrjamesnoble/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/silvanmuhlemann/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shaneIxD/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nacho/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yigitpinarbasi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/buzzusborne/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aaronkwhite/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rmlewisuk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/giancarlon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nbirckel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/d_nny_m_cher/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sdidonato/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/atariboy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/abotap/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/karalek/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/psdesignuk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ludwiczakpawel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nemanjaivanovic/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/baluli/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ahmadajmi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vovkasolovev/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/samgrover/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/derienzo777/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jonathansimmons/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nelsonjoyce/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/S0ufi4n3/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xtopherpaul/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/oaktreemedia/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nateschulte/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/findingjenny/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/namankreative/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/antonyzotov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/we_social/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/leehambley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/solid_color/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/abelcabans/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mbilderbach/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kkusaa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jordyvdboom/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carlosgavina/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pechkinator/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vc27/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rdbannon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/croakx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/suribbles/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kerihenare/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/catadeleon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gcmorley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/duivvv/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/saschadroste/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/victorDubugras/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wintopia/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mattbilotti/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/taylorling/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/megdraws/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/meln1ks/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mahmoudmetwally/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Silveredge9/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/derekebradley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/happypeter1983/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/travis_arnold/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/artem_kostenko/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adobi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/daykiine/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alek_djuric/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scips/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/miguelmendes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/justinrhee/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alsobrooks/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fronx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mcflydesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/santi_urso/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/allfordesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stayuber/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bertboerland/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marosholly/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adamnac/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cynthiasavard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/muringa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danro/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hiemil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jackiesaik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/zacsnider/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iduuck/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/antjanus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aroon_sharma/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dshster/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thehacker/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michaelbrooksjr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ryanmclaughlin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/clubb3rry/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/taybenlor/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xripunov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/myastro/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adityasutomo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/digitalmaverick/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hjartstrorn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/itolmach/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vaughanmoffitt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/abdots/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/isnifer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sergeysafonov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/maz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scrapdnb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chrismj83/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vitorleal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sokaniwaal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/zaki3d/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/illyzoren/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mocabyte/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/osmanince/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/djsherman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/davidhemphill/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/waghner/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/necodymiconer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/praveen_vijaya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fabbrucci/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cliffseal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/travishines/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kuldarkalvik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Elt_n/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/phillapier/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/okseanjay/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/id835559/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kudretkeskin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/anjhero/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/duck4fuck/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scott_riley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/noufalibrahim/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/h1brd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/borges_marcos/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/devinhalladay/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ciaranr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stefooo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mikebeecham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tonymillion/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joshuaraichur/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/irae/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/petrangr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dmitriychuta/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/charliegann/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/arashmanteghi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ainsleywagon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/svenlen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/faisalabid/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/beshur/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carlyson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dutchnadia/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/teddyzetterlund/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/samuelkraft/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aoimedia/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/toddrew/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/codepoet_ru/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/artvavs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/benoitboucart/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jomarmen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kolmarlopez/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/creartinc/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/homka/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gaborenton/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/robinclediere/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/maximsorokin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/plasticine/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/j2deme/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/peachananr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kapaluccio/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/de_ascanio/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rikas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dawidwu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/angelcreative/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rpatey/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/popey/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rehatkathuria/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/the_purplebunny/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/1markiz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ajaxy_ru/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brenmurrell/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dudestein/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/oskarlevinson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/victorstuber/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nehfy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vicivadeline/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/leandrovaranda/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scottgallant/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/victor_haydin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sawrb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ryhanhassan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/amayvs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/a_brixen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/karolkrakowiak_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/herkulano/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/geran7/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cggaurav/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chris_witko/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lososina/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/polarity/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mattlat/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brandonburke/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/constantx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/teylorfeliz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/craigelimeliah/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rachelreveley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/reabo101/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rahmeen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ky/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rickyyean/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/j04ntoh/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/spbroma/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sebashton/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jpenico/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/francis_vega/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/oktayelipek/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kikillo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fabbianz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/larrygerard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/BroumiYoussef/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/0therplanet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mbilalsiddique1/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ionuss/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/grrr_nl/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/liminha/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rawdiggie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ryandownie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sethlouey/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pixage/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/arpitnj/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/switmer777/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/josevnclch/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kanickairaj/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/puzik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tbakdesigns/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/besbujupi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/supjoey/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lowie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/linkibol/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/balintorosz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/imcoding/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/agustincruiz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gusoto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thomasschrijer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/superoutman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kalmerrautam/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gabrielizalo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gojeanyn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/davidbaldie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_vojto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/laurengray/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jydesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mymyboy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nellleo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marciotoledo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ninjad3m0/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/to_soham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hasslunsford/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/muridrahhal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/levisan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/grahamkennery/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lepetitogre/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/antongenkin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nessoila/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/amandabuzard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/safrankov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cocolero/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dss49/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/matt3224/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bluesix/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/quailandquasar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/AlbertoCococi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lepinski/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sementiy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mhudobivnik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thibaut_re/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/olgary/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shojberg/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mtolokonnikov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bereto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/naupintos/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wegotvices/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xadhix/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/macxim/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rodnylobos/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/madcampos/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/madebyvadim/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bartoszdawydzik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/supervova/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/markretzloff/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vonachoo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/darylws/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stevedesigner/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mylesb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/herbigt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/depaulawagner/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/geshan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gizmeedevil1991/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_scottburgess/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lisovsky/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/davidsasda/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/artd_sign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/YoungCutlass/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mgonto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/itstotallyamy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/victorquinn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/osmond/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/oksanafrewer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/zauerkraut/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iamkeithmason/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nitinhayaran/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lmjabreu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mandalareopens/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thinkleft/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ponchomendivil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/juamperro/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brunodesign1206/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/caseycavanagh/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/luxe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dotgridline/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/spedwig/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/madewulf/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mattsapii/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/helderleal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chrisstumph/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jayphen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nsamoylov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chrisvanderkooi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/justme_timothyg/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/otozk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/prinzadi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gu5taf/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cyril_gaillard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/d_kobelyatsky/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/daniloc/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nwdsha/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/romanbulah/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/skkirilov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dvdwinden/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dannol/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thekevinjones/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jwalter14/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/timgthomas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/buddhasource/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/uxpiper/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thatonetommy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/diansigitp/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adrienths/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/klimmka/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gkaam/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/derekcramer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jennyyo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nerrsoft/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xalionmalik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/edhenderson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/keyuri85/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/roxanejammet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kimcool/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/edkf/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/matkins/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alessandroribe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jacksonlatka/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lebronjennan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kostaspt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/karlkanall/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/moynihan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danpliego/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/saulihirvi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wesleytrankin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fjaguero/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bowbrick/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mashaaaaal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yassiryahya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dparrelli/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fotomagin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aka_james/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/denisepires/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iqbalperkasa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/martinansty/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jarsen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/r_oy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/justinrob/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gabrielrosser/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/malgordon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carlfairclough/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michaelabehsera/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pierrestoffe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/enjoythetau/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/loganjlambert/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rpeezy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/coreyginnivan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michalhron/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/msveet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lingeswaran/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kolsvein/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/peter576/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/reideiredale/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joeymurdah/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/raphaelnikson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mvdheuvel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/maxlinderman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/begreative/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/frankiefreesbie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/robturlinckx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Talbi_ConSept/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/longlivemyword/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vanchesz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/maiklam/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hermanobrother/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rez___a/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gregsqueeb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/greenbes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_ragzor/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/anthonysukow/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fluidbrush/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dactrtr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jehnglynn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bergmartin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hugocornejo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_kkga/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dzantievm/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sawalazar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sovesove/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jonsgotwood/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/byryan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vytautas_a/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mizhgan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cicerobr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nilshelmersson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/d33pthought/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/davecraige/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nckjrvs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alexandermayes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jcubic/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/craigrcoles/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bagawarman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rob_thomas10/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cofla/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/maikelk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rtgibbons/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/russell_baylis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mhesslow/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/codysanfilippo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/webtanya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/madebybrenton/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dcalonaci/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/perfectflow/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jjsiii/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/saarabpreet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kumarrajan12123/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iamsteffen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/themikenagle/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ceekaytweet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/larrybolt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/conspirator/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dallasbpeters/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/n3dmax/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/terpimost/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kirillz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/byrnecore/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/j_drake_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/calebjoyce/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hoangloi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tobysaxon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gofrasdesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dimaposnyy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tjisousa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/okandungel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/billyroshan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/oskamaya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/motionthinks/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/knilob/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ashocka18/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marrimo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bartjo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/omnizya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ernestsemerda/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andreas_pr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/edgarchris99/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thomasgeisen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gseguin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joannefournier/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/demersdesigns/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adammarsbar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nasirwd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/n_tassone/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/javorszky/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/themrdave/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yecidsm/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nicollerich/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/canapud/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nicoleglynn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/judzhin_miles/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/designervzm/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kianoshp/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/evandrix/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alterchuca/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dhrubo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ma_tiax/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ssbb_me/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dorphern/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mauriolg/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bruno_mart/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mactopus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/the_winslet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joemdesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/Shriiiiimp/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jacobbennett/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nfedoroff/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iamglimy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/allagringaus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aiiaiiaii/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/olaolusoga/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/buryaknick/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wim1k/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nicklacke/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/a1chapone/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/steynviljoen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/strikewan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ryankirkman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andrewabogado/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/doooon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jagan123/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ariffsetiawan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/elenadissi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mwarkentin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thierrymeier_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/r_garcia/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dmackerman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/borantula/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/konus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/spacewood_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ryuchi311/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/evanshajed/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tristanlegros/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shoaib253/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aislinnkelly/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/okcoker/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/timpetricola/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sunshinedgirl/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chadami/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aleclarsoniv/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nomidesigns/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/petebernardo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scottiedude/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/millinet/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/imsoper/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/imammuht/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/benjamin_knight/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nepdud/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joki4/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lanceguyatt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bboy1895/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/amywebbb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rweve/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/haruintesettden/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ricburton/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nelshd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/batsirai/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/primozcigler/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jffgrdnr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/8d3k/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/geneseleznev/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/al_li/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/souperphly/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mslarkina/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/2fockus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cdavis565/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xiel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/turkutuuli/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/uxward/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lebinoclard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gauravjassal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/davidmerrique/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mdsisto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andrewofficer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kojourin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dnirmal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kevka/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mr_shiznit/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aluisio_azevedo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cloudstudio/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danvierich/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alexivanichkin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fran_mchamy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/perretmagali/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/betraydan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cadikkara/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/matbeedotcom/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeremyworboys/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bpartridge/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michaelkoper/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/silv3rgvn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alevizio/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/johnsmithagency/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lawlbwoy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vitor376/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/desastrozo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thimo_cz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jasonmarkjones/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lhausermann/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xravil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/guischmitt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vigobronx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/panghal0/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/miguelkooreman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/surgeonist/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/christianoliff/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/caspergrl/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iamkarna/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ipavelek/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pierre_nel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/y2graphic/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sterlingrules/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/elbuscainfo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bennyjien/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stushona/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/estebanuribe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/embrcecreations/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danillos/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/elliotlewis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/charlesrpratt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vladyn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/emmeffess/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carlosblanco_eu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/leonfedotov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rangafangs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chris_frees/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tgormtx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bryan_topham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jpscribbles/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mighty55/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carbontwelve/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/isaacfifth/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/iamjdeleon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/snowwrite/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/barputro/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/drewbyreese/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sachacorazzi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bistrianiosip/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/magoo04/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pehamondello/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yayteejay/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/a_harris88/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/algunsanabria/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/zforrester/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ovall/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carlosjgsousa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/geobikas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ah_lice/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/looneydoodle/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nerdgr8/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ddggccaa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/zackeeler/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/normanbox/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/el_fuertisimo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ismail_biltagi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/juangomezw/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jnmnrd/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/patrickcoombe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ryanjohnson_me/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/markolschesky/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeffgolenski/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kvasnic/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lindseyzilla/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gauchomatt/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/afusinatto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kevinoh/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/okansurreel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adamawesomeface/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/emileboudeling/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/arishi_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/juanmamartinez/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wikiziner/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danthms/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mkginfo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/terrorpixel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/curiousonaut/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/prheemo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michaelcolenso/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/foczzi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/martip07/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thaodang17/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/johncafazza/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/robinlayfield/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/franciscoamk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/abdulhyeuk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marklamb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/edobene/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andresenfredrik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mikaeljorhult/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chrisslowik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vinciarts/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/meelford/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/elliotnolten/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yehudab/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vijaykarthik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bfrohs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/josep_martins/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/attacks/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sur4dye/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tumski/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/instalox/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mangosango/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/paulfarino/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kazaky999/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kiwiupover/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nvkznemo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tom_even/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ratbus/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/woodsman001/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joshmedeski/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thewillbeard/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/psaikali/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joe_black/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aleinadsays/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marcusgorillius/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hota_v/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jghyllebert/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shinze/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/janpalounek/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeremiespoken/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/her_ruu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dansowter/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/felipeapiress/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/magugzbrand2d/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/posterjob/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nathalie_fs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bobbytwoshoes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dreizle/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeremymouton/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/elisabethkjaer/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/notbadart/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mohanrohith/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jlsolerdeltoro/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/itskawsar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/slowspock/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/zvchkelly/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wiljanslofstra/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/craighenneberry/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/trubeatto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/juaumlol/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/samscouto/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/BenouarradeM/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gipsy_raf/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/netonet_il/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/arkokoley/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/itsajimithing/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/smalonso/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/victordeanda/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_dwite_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/richardgarretts/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gregrwilkinson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/anatolinicolae/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lu4sh1i/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stefanotirloni/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ostirbu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/darcystonge/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/naitanamoreno/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/michaelcomiskey/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/adhiardana/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marcomano_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/davidcazalis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/falconerie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gregkilian/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bcrad/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bolzanmarco/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/low_res/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vlajki/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/petar_prog/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jonkspr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/akmalfikri/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mfacchinello/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/atanism/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/harry_sistalam/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/murrayswift/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bobwassermann/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gavr1l0/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/madshensel/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mr_subtle/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/deviljho_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/salimianoff/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joetruesdell/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/twittypork/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/airskylar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dnezkumar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dgajjar/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cherif_b/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/salvafc/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/louis_currie/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/deeenright/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cybind/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/eyronn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vickyshits/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sweetdelisa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/cboller1/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andresdjasso/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/melvindidit/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andysolomon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thaisselenator_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lvovenok/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/giuliusa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/belyaev_rs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/overcloacked/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kamal_chaneman/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/incubo82/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hellofeverrrr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mhaligowski/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sunlandictwin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bu7921/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/andytlaw/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeremery/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/finchjke/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/manigm/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/umurgdk/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/scottfeltham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ganserene/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mutu_krish/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jodytaggart/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ntfblog/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tanveerrao/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hfalucas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alxleroydeval/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kucingbelang4/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bargaorobalo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/colgruv/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stalewine/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kylefrost/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/baumannzone/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/angelcolberg/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sachingawas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jjshaw14/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ramanathan_pdy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/johndezember/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nilshoenson/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brandonmorreale/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nutzumi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/brandonflatsoda/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sergeyalmone/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/klefue/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kirangopal/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/baumann_alex/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/matthewkay_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jay_wilburn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shesgared/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/apriendeau/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/johnriordan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wake_gs/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aleksitappura/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/emsgulam/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xilantra/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/imomenui/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sircalebgrove/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/newbrushes/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hsinyo23/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/m4rio/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/katiemdaly/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/s4f1/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ecommerceil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marlinjayakody/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/swooshycueb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sangdth/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/coderdiaz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bluefx_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sasha_shestakov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/eugeneeweb/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dgclegg/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/n1ght_coder/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dixchen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/blakehawksworth/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/trueblood_33/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hai_ninh_nguyen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marclgonzales/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/yesmeck/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stephcoue/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/doronmalki/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ruehldesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/anasnakawa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kijanmaharjan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/wearesavas/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stefvdham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tweetubhai/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alecarpentier/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/fiterik/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/antonyryndya/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/d00maz/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/theonlyzeke/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/missaaamy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/carlosm/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/manekenthe/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/reetajayendra/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jeremyshimko/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/justinrgraham/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/stefanozoffoli/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/overra/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mrebay007/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/shvelo96/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/pyronite/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/thedjpetersen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/rtyukmaev/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_williamguerra/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/albertaugustin/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vikashpathak18/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kevinjohndayy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vj_demien/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/colirpixoil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/goddardlewis/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/laasli/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jqiuss/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/heycamtaylor/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nastya_mane/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mastermindesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ccinojasso1/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/nyancecom/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sandywoodruff/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/bighanddesign/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sbtransparent/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aviddayentonbay/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/richwild/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kaysix_dizzy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/tur8le/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/seyedhossein1/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/privetwagner/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/emmandenn/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dev_essentials/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jmfsocial/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_yardenoon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mateaodviteza/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/weavermedia/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mufaddal_mw/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hafeeskhan/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ashernatali/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sulaqo/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/eddiechen/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/josecarlospsh/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vm_f/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/enricocicconi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/danmartin70/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/gmourier/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/donjain/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mrxloka/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/_pedropinho/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/eitarafa/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/oscarowusu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ralph_lam/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/panchajanyag/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/woodydotmx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/jerrybai1907/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/marshallchen_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/xamorep/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aio___/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/chaabane_wail/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/txcx/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/akashsharma39/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/falling_soul/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sainraja/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mugukamil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/johannesneu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/markwienands/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/karthipanraj/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/balakayuriy/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/alan_zhang_/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/layerssss/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/kaspernordkvist/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/mirfanqureshi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/hanna_smi/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/VMilescu/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/aeon56/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/m_kalibry/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/sreejithexp/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dicesales/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/dhoot_amit/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/smenov/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/lonesomelemon/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vladimirdevic/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/joelcipriano/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/haligaliharun/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/buleswapnil/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/serefka/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/ifarafonow/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/vikasvinfotech/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/urrutimeoli/128.jpg", "https://s3.amazonaws.com/uifaces/faces/twitter/areandacom/128.jpg"]; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/helpers.js":[function(require,module,exports){ var Faker = require('../index'); // backword-compatibility exports.randomNumber = function (range) { return Faker.random.number(range); }; // backword-compatibility exports.randomize = function (array) { return Faker.random.array_element(array); }; // slugifies string exports.slugify = function (string) { return string.replace(/ /g, '-').replace(/[^\w\.\-]+/g, ''); }; // parses string for a symbol and replace it with a random number from 1-10 exports.replaceSymbolWithNumber = function (string, symbol) { // default symbol is '#' if (symbol === undefined) { symbol = '#'; } var str = ''; for (var i = 0; i < string.length; i++) { if (string[i] == symbol) { str += Math.floor(Math.random() * 10); } else { str += string[i]; } } return str; }; // takes an array and returns it randomized exports.shuffle = function (o) { for (var j, x, i = o.length; i; j = parseInt(Math.random() * i, 10), x = o[--i], o[i] = o[j], o[j] = x); return o; }; exports.createCard = function () { return { "name": Faker.Name.findName(), "username": Faker.Internet.userName(), "email": Faker.Internet.email(), "address": { "streetA": Faker.Address.streetName(), "streetB": Faker.Address.streetAddress(), "streetC": Faker.Address.streetAddress(true), "streetD": Faker.Address.secondaryAddress(), "city": Faker.Address.city(), "ukCounty": Faker.Address.ukCounty(), "ukCountry": Faker.Address.ukCountry(), "zipcode": Faker.Address.zipCode(), "geo": { "lat": Faker.Address.latitude(), "lng": Faker.Address.longitude() } }, "phone": Faker.PhoneNumber.phoneNumber(), "website": Faker.Internet.domainName(), "company": { "name": Faker.Company.companyName(), "catchPhrase": Faker.Company.catchPhrase(), "bs": Faker.Company.bs() }, "posts": [ { "words": Faker.Lorem.words(), "sentence": Faker.Lorem.sentence(), "sentences": Faker.Lorem.sentences(), "paragraph": Faker.Lorem.paragraph() }, { "words": Faker.Lorem.words(), "sentence": Faker.Lorem.sentence(), "sentences": Faker.Lorem.sentences(), "paragraph": Faker.Lorem.paragraph() }, { "words": Faker.Lorem.words(), "sentence": Faker.Lorem.sentence(), "sentences": Faker.Lorem.sentences(), "paragraph": Faker.Lorem.paragraph() } ] }; }; exports.userCard = function () { return { "name": Faker.Name.findName(), "username": Faker.Internet.userName(), "email": Faker.Internet.email(), "address": { "street": Faker.Address.streetName(true), "suite": Faker.Address.secondaryAddress(), "city": Faker.Address.city(), "zipcode": Faker.Address.zipCode(), "geo": { "lat": Faker.Address.latitude(), "lng": Faker.Address.longitude() } }, "phone": Faker.PhoneNumber.phoneNumber(), "website": Faker.Internet.domainName(), "company": { "name": Faker.Company.companyName(), "catchPhrase": Faker.Company.catchPhrase(), "bs": Faker.Company.bs() } }; }; /* String.prototype.capitalize = function () { //v1.0 return this.replace(/\w+/g, function (a) { return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase(); }); }; */ },{"../index":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/image.js":[function(require,module,exports){ var Faker = require('../index'); var image = { avatar: function () { return Faker.random.avatar_uri(); }, imageUrl: function (width, height, category) { var width = width || 640; var height = height || 480; var url ='http://lorempixel.com/' + width + '/' + height; if (typeof category !== 'undefined') { url += '/' + category; } return url; }, abstractImage: function (width, height) { return this.imageUrl(width, height, 'abstract'); }, animals: function (width, height) { return this.imageUrl(width, height, 'animals'); }, business: function (width, height) { return this.imageUrl(width, height, 'business'); }, cats: function (width, height) { return this.imageUrl(width, height, 'cats'); }, city: function (width, height) { return this.imageUrl(width, height, 'city'); }, food: function (width, height) { return this.imageUrl(width, height, 'food'); }, nightlife: function (width, height) { return this.imageUrl(width, height, 'nightlife'); }, fashion: function (width, height) { return this.imageUrl(width, height, 'fashion'); }, people: function (width, height) { return this.imageUrl(width, height, 'people'); }, nature: function (width, height) { return this.imageUrl(width, height, 'nature'); }, sports: function (width, height) { return this.imageUrl(width, height, 'sports'); }, technics: function (width, height) { return this.imageUrl(width, height, 'technics'); }, transport: function (width, height) { return this.imageUrl(width, height, 'transport'); } }; module.exports = image; },{"../index":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/internet.js":[function(require,module,exports){ var Faker = require('../index'); var internet = { email: function () { return Faker.Helpers.slugify(this.userName()) + "@" + Faker.Helpers.slugify(this.domainName()); }, userName: function () { var result; switch (Faker.random.number(2)) { case 0: result = Faker.random.first_name(); break; case 1: result = Faker.random.first_name() + Faker.random.array_element([".", "_"]) + Faker.random.last_name(); break; } return result; }, domainName: function () { return this.domainWord() + "." + Faker.random.domain_suffix(); }, domainWord: function () { return Faker.random.first_name().toLowerCase(); }, ip: function () { var randNum = function () { return (Math.random() * 254 + 1).toFixed(0); }; var result = []; for (var i = 0; i < 4; i++) { result[i] = randNum(); } return result.join("."); }, color: function (baseRed255, baseGreen255, baseBlue255) { // based on awesome response : http://stackoverflow.com/questions/43044/algorithm-to-randomly-generate-an-aesthetically-pleasing-color-palette var red = Math.floor((Faker.random.number(256) + baseRed255) / 2); var green = Math.floor((Faker.random.number(256) + baseRed255) / 2); var blue = Math.floor((Faker.random.number(256) + baseRed255) / 2); return '#' + red.toString(16) + green.toString(16) + blue.toString(16); } }; module.exports = internet; },{"../index":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/lorem.js":[function(require,module,exports){ var Faker = require('../index'); var Helpers = require('./helpers'); var definitions = require('../lib/definitions'); var lorem = { words: function (num) { if (typeof num == 'undefined') { num = 3; } return Helpers.shuffle(definitions.lorem).slice(0, num); }, sentence: function (wordCount, range) { if (typeof wordCount == 'undefined') { wordCount = 3; } if (typeof range == 'undefined') { range = 7; } // strange issue with the node_min_test failing for captialize, please fix and add this back //return this.words(wordCount + Helpers.randomNumber(range)).join(' ').capitalize(); return this.words(wordCount + Faker.random.number(7)).join(' '); }, sentences: function (sentenceCount) { if (typeof sentenceCount == 'undefined') { sentenceCount = 3; } var sentences = []; for (sentenceCount; sentenceCount > 0; sentenceCount--) { sentences.push(this.sentence()); } return sentences.join("\n"); }, paragraph: function (sentenceCount) { if (typeof sentenceCount == 'undefined') { sentenceCount = 3; } return this.sentences(sentenceCount + Faker.random.number(3)); }, paragraphs: function (paragraphCount) { if (typeof paragraphCount == 'undefined') { paragraphCount = 3; } var paragraphs = []; for (paragraphCount; paragraphCount > 0; paragraphCount--) { paragraphs.push(this.paragraph()); } return paragraphs.join("\n \r\t"); } }; module.exports = lorem; },{"../index":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/index.js","../lib/definitions":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/definitions.js","./helpers":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/helpers.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/name.js":[function(require,module,exports){ var Faker = require('../index'); var _name = { firstName: function () { return Faker.random.first_name(); }, //Working as intended firstNameFemale: function () { return Faker.random.first_name(); }, //Working as intended firstNameMale: function () { return Faker.random.first_name(); }, lastName: function () { return Faker.random.last_name(); }, findName: function () { var r = Faker.random.number(8); switch (r) { case 0: return Faker.random.name_prefix() + " " + this.firstName() + " " + this.lastName(); case 1: return this.firstName() + " " + this.lastName() + " " + Faker.random.name_suffix(); } return this.firstName() + " " + this.lastName(); } }; module.exports = _name; },{"../index":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/phone_number.js":[function(require,module,exports){ var Faker = require('../index'); var Helpers = require('./helpers'); var definitions = require('./definitions'); var phone = { phoneNumber: function () { return Helpers.replaceSymbolWithNumber(Faker.random.phone_formats()); }, // FIXME: this is strange passing in an array index. phoneNumberFormat: function (phoneFormatsArrayIndex) { return Helpers.replaceSymbolWithNumber(definitions.phone_formats[phoneFormatsArrayIndex]); } }; module.exports = phone; },{"../index":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/index.js","./definitions":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/definitions.js","./helpers":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/helpers.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/random.js":[function(require,module,exports){ var definitions = require('./definitions'); var random = { // returns a single random number based on a range number: function (range) { return Math.floor(Math.random() * range); }, // takes an array and returns the array randomly sorted array_element: function (array) { var r = Math.floor(Math.random() * array.length); return array[r]; }, city_prefix: function () { return this.array_element(definitions.city_prefix); }, city_suffix: function () { return this.array_element(definitions.city_suffix); }, street_suffix: function () { return this.array_element(definitions.street_suffix); }, br_state: function () { return this.array_element(definitions.br_state); }, br_state_abbr: function () { return this.array_element(definitions.br_state_abbr); }, us_state: function () { return this.array_element(definitions.us_state); }, us_state_abbr: function () { return this.array_element(definitions.us_state_abbr); }, uk_county: function () { return this.array_element(definitions.uk_county); }, uk_country: function () { return this.array_element(definitions.uk_country); }, first_name: function () { return this.array_element(definitions.first_name); }, last_name: function () { return this.array_element(definitions.last_name); }, name_prefix: function () { return this.array_element(definitions.name_prefix); }, name_suffix: function () { return this.array_element(definitions.name_suffix); }, catch_phrase_adjective: function () { return this.array_element(definitions.catch_phrase_adjective); }, catch_phrase_descriptor: function () { return this.array_element(definitions.catch_phrase_descriptor); }, catch_phrase_noun: function () { return this.array_element(definitions.catch_phrase_noun); }, bs_adjective: function () { return this.array_element(definitions.bs_adjective); }, bs_buzz: function () { return this.array_element(definitions.bs_buzz); }, bs_noun: function () { return this.array_element(definitions.bs_noun); }, phone_formats: function () { return this.array_element(definitions.phone_formats); }, domain_suffix: function () { return this.array_element(definitions.domain_suffix); }, avatar_uri: function () { return this.array_element(definitions.avatar_uri); } }; module.exports = random; },{"./definitions":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/definitions.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/lib/tree.js":[function(require,module,exports){ var Faker = require('../index'); var tree = { clone: function clone(obj) { if (obj == null || typeof(obj) != 'object') return obj; var temp = obj.constructor(); // changed for (var key in obj) { temp[key] = this.clone(obj[key]); } return temp; }, createTree: function (depth, width, obj) { if (!obj) { throw { name: "ObjectError", message: "there needs to be an object passed in" }; } if (width <= 0) { throw { name: "TreeParamError", message: "width must be greater than zero" }; } var newObj = this.clone(obj); for (var prop in newObj) { if (newObj.hasOwnProperty(prop)) { var value = null; if (newObj[prop] !== "__RECURSE__") { value = eval(newObj[prop]); } else { if (depth !== 0) { value = []; var evalWidth = 1; if (typeof(width) == "function") { evalWidth = width(); } else { evalWidth = width; } for (var i = 0; i < evalWidth; i++) { value.push(this.createTree(depth - 1, width, obj)); } } } newObj[prop] = value; } } return newObj; } }; module.exports = tree; },{"../index":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/assert/assert.js":[function(require,module,exports){ (function (global){ 'use strict'; // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js // original notice: /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ function compare(a, b) { if (a === b) { return 0; } var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) { return -1; } if (y < x) { return 1; } return 0; } function isBuffer(b) { if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { return global.Buffer.isBuffer(b); } return !!(b != null && b._isBuffer); } // based on node assert, original notice: // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 // // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! // // Originally from narwhal.js (http://narwhaljs.org) // Copyright (c) 2009 Thomas Robinson <280north.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util/'); var hasOwn = Object.prototype.hasOwnProperty; var pSlice = Array.prototype.slice; var functionsHaveNames = (function () { return function foo() {}.name === 'foo'; }()); function pToString (obj) { return Object.prototype.toString.call(obj); } function isView(arrbuf) { if (isBuffer(arrbuf)) { return false; } if (typeof global.ArrayBuffer !== 'function') { return false; } if (typeof ArrayBuffer.isView === 'function') { return ArrayBuffer.isView(arrbuf); } if (!arrbuf) { return false; } if (arrbuf instanceof DataView) { return true; } if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { return true; } return false; } // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = module.exports = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) var regex = /\s*function\s+([^\(\s]*)\s*/; // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js function getName(func) { if (!util.isFunction(func)) { return; } if (functionsHaveNames) { return func.name; } var str = func.toString(); var match = str.match(regex); return match && match[1]; } assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; this.generatedMessage = false; } else { this.message = getMessage(this); this.generatedMessage = true; } var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } else { // non v8 browsers so we can have a stacktrace var err = new Error(); if (err.stack) { var out = err.stack; // try to strip useless frames var fn_name = getName(stackStartFunction); var idx = out.indexOf('\n' + fn_name); if (idx >= 0) { // once we have located the function frame // we need to strip out everything before it (and its line) var next_line = out.indexOf('\n', idx + 1); out = out.substring(next_line + 1); } this.stack = out; } } }; // assert.AssertionError instanceof Error util.inherits(assert.AssertionError, Error); function truncate(s, n) { if (typeof s === 'string') { return s.length < n ? s : s.slice(0, n); } else { return s; } } function inspect(something) { if (functionsHaveNames || !util.isFunction(something)) { return util.inspect(something); } var rawname = getName(something); var name = rawname ? ': ' + rawname : ''; return '[Function' + name + ']'; } function getMessage(self) { return truncate(inspect(self.actual), 128) + ' ' + self.operator + ' ' + truncate(inspect(self.expected), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { if (!_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); } }; function _deepEqual(actual, expected, strict, memos) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (isBuffer(actual) && isBuffer(expected)) { return compare(actual, expected) === 0; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if ((actual === null || typeof actual !== 'object') && (expected === null || typeof expected !== 'object')) { return strict ? actual === expected : actual == expected; // If both values are instances of typed arrays, wrap their underlying // ArrayBuffers in a Buffer each to increase performance // This optimization requires the arrays to have the same type as checked by // Object.prototype.toString (aka pToString). Never perform binary // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their // bit patterns are not identical. } else if (isView(actual) && isView(expected) && pToString(actual) === pToString(expected) && !(actual instanceof Float32Array || actual instanceof Float64Array)) { return compare(new Uint8Array(actual.buffer), new Uint8Array(expected.buffer)) === 0; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else if (isBuffer(actual) !== isBuffer(expected)) { return false; } else { memos = memos || {actual: [], expected: []}; var actualIndex = memos.actual.indexOf(actual); if (actualIndex !== -1) { if (actualIndex === memos.expected.indexOf(expected)) { return true; } } memos.actual.push(actual); memos.expected.push(expected); return objEquiv(actual, expected, strict, memos); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b, strict, actualVisitedObjects) { if (a === null || a === undefined || b === null || b === undefined) return false; // if one is a primitive, the other must be same if (util.isPrimitive(a) || util.isPrimitive(b)) return a === b; if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false; var aIsArgs = isArguments(a); var bIsArgs = isArguments(b); if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) return false; if (aIsArgs) { a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b, strict); } var ka = objectKeys(a); var kb = objectKeys(b); var key, i; // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length !== kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] !== kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; assert.notDeepStrictEqual = notDeepStrictEqual; function notDeepStrictEqual(actual, expected, message) { if (_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); } } // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } try { if (actual instanceof expected) { return true; } } catch (e) { // Ignore. The instanceof check doesn't work for arrow functions. } if (Error.isPrototypeOf(expected)) { return false; } return expected.call({}, actual) === true; } function _tryBlock(block) { var error; try { block(); } catch (e) { error = e; } return error; } function _throws(shouldThrow, block, expected, message) { var actual; if (typeof block !== 'function') { throw new TypeError('"block" argument must be a function'); } if (typeof expected === 'string') { message = expected; expected = null; } actual = _tryBlock(block); message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } var userProvidedMessage = typeof message === 'string'; var isUnwantedException = !shouldThrow && util.isError(actual); var isUnexpectedException = !shouldThrow && actual && !expected; if ((isUnwantedException && userProvidedMessage && expectedException(actual, expected)) || isUnexpectedException) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws(true, block, error, message); }; // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { _throws(false, block, error, message); }; assert.ifError = function(err) { if (err) throw err; }; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (hasOwn.call(obj, key)) keys.push(key); } return keys; }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"util/":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/util/util.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/atoa/atoa.js":[function(require,module,exports){ module.exports = function atoa (a, n) { return Array.prototype.slice.call(a, n); } },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/base64-js/index.js":[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function placeHoldersCount (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data return (b64.length * 3 / 4) - placeHoldersCount(b64) } function toByteArray (b64) { var i, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) arr = new Arr((len * 3 / 4) - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 for (i = 0; i < l; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var output = '' var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] output += lookup[tmp >> 2] output += lookup[(tmp << 4) & 0x3F] output += '==' } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) output += lookup[tmp >> 10] output += lookup[(tmp >> 4) & 0x3F] output += lookup[(tmp << 2) & 0x3F] output += '=' } parts.push(output) return parts.join('') } },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/bowser/src/bowser.js":[function(require,module,exports){ /*! * Bowser - a browser detector * https://github.com/ded/bowser * MIT License | (c) Dustin Diaz 2015 */ !function (root, name, definition) { if (typeof module != 'undefined' && module.exports) module.exports = definition() else if (typeof define == 'function' && define.amd) define(name, definition) else root[name] = definition() }(this, 'bowser', function () { /** * See useragents.js for examples of navigator.userAgent */ var t = true function detect(ua) { function getFirstMatch(regex) { var match = ua.match(regex); return (match && match.length > 1 && match[1]) || ''; } function getSecondMatch(regex) { var match = ua.match(regex); return (match && match.length > 1 && match[2]) || ''; } var iosdevice = getFirstMatch(/(ipod|iphone|ipad)/i).toLowerCase() , likeAndroid = /like android/i.test(ua) , android = !likeAndroid && /android/i.test(ua) , nexusMobile = /nexus\s*[0-6]\s*/i.test(ua) , nexusTablet = !nexusMobile && /nexus\s*[0-9]+/i.test(ua) , chromeos = /CrOS/.test(ua) , silk = /silk/i.test(ua) , sailfish = /sailfish/i.test(ua) , tizen = /tizen/i.test(ua) , webos = /(web|hpw)os/i.test(ua) , windowsphone = /windows phone/i.test(ua) , samsungBrowser = /SamsungBrowser/i.test(ua) , windows = !windowsphone && /windows/i.test(ua) , mac = !iosdevice && !silk && /macintosh/i.test(ua) , linux = !android && !sailfish && !tizen && !webos && /linux/i.test(ua) , edgeVersion = getFirstMatch(/edge\/(\d+(\.\d+)?)/i) , versionIdentifier = getFirstMatch(/version\/(\d+(\.\d+)?)/i) , tablet = /tablet/i.test(ua) , mobile = !tablet && /[^-]mobi/i.test(ua) , xbox = /xbox/i.test(ua) , result if (/opera/i.test(ua)) { // an old Opera result = { name: 'Opera' , opera: t , version: versionIdentifier || getFirstMatch(/(?:opera|opr|opios)[\s\/](\d+(\.\d+)?)/i) } } else if (/opr|opios/i.test(ua)) { // a new Opera result = { name: 'Opera' , opera: t , version: getFirstMatch(/(?:opr|opios)[\s\/](\d+(\.\d+)?)/i) || versionIdentifier } } else if (/SamsungBrowser/i.test(ua)) { result = { name: 'Samsung Internet for Android' , samsungBrowser: t , version: versionIdentifier || getFirstMatch(/(?:SamsungBrowser)[\s\/](\d+(\.\d+)?)/i) } } else if (/coast/i.test(ua)) { result = { name: 'Opera Coast' , coast: t , version: versionIdentifier || getFirstMatch(/(?:coast)[\s\/](\d+(\.\d+)?)/i) } } else if (/yabrowser/i.test(ua)) { result = { name: 'Yandex Browser' , yandexbrowser: t , version: versionIdentifier || getFirstMatch(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i) } } else if (/ucbrowser/i.test(ua)) { result = { name: 'UC Browser' , ucbrowser: t , version: getFirstMatch(/(?:ucbrowser)[\s\/](\d+(?:\.\d+)+)/i) } } else if (/mxios/i.test(ua)) { result = { name: 'Maxthon' , maxthon: t , version: getFirstMatch(/(?:mxios)[\s\/](\d+(?:\.\d+)+)/i) } } else if (/epiphany/i.test(ua)) { result = { name: 'Epiphany' , epiphany: t , version: getFirstMatch(/(?:epiphany)[\s\/](\d+(?:\.\d+)+)/i) } } else if (/puffin/i.test(ua)) { result = { name: 'Puffin' , puffin: t , version: getFirstMatch(/(?:puffin)[\s\/](\d+(?:\.\d+)?)/i) } } else if (/sleipnir/i.test(ua)) { result = { name: 'Sleipnir' , sleipnir: t , version: getFirstMatch(/(?:sleipnir)[\s\/](\d+(?:\.\d+)+)/i) } } else if (/k-meleon/i.test(ua)) { result = { name: 'K-Meleon' , kMeleon: t , version: getFirstMatch(/(?:k-meleon)[\s\/](\d+(?:\.\d+)+)/i) } } else if (windowsphone) { result = { name: 'Windows Phone' , windowsphone: t } if (edgeVersion) { result.msedge = t result.version = edgeVersion } else { result.msie = t result.version = getFirstMatch(/iemobile\/(\d+(\.\d+)?)/i) } } else if (/msie|trident/i.test(ua)) { result = { name: 'Internet Explorer' , msie: t , version: getFirstMatch(/(?:msie |rv:)(\d+(\.\d+)?)/i) } } else if (chromeos) { result = { name: 'Chrome' , chromeos: t , chromeBook: t , chrome: t , version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i) } } else if (/chrome.+? edge/i.test(ua)) { result = { name: 'Microsoft Edge' , msedge: t , version: edgeVersion } } else if (/vivaldi/i.test(ua)) { result = { name: 'Vivaldi' , vivaldi: t , version: getFirstMatch(/vivaldi\/(\d+(\.\d+)?)/i) || versionIdentifier } } else if (sailfish) { result = { name: 'Sailfish' , sailfish: t , version: getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i) } } else if (/seamonkey\//i.test(ua)) { result = { name: 'SeaMonkey' , seamonkey: t , version: getFirstMatch(/seamonkey\/(\d+(\.\d+)?)/i) } } else if (/firefox|iceweasel|fxios/i.test(ua)) { result = { name: 'Firefox' , firefox: t , version: getFirstMatch(/(?:firefox|iceweasel|fxios)[ \/](\d+(\.\d+)?)/i) } if (/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(ua)) { result.firefoxos = t } } else if (silk) { result = { name: 'Amazon Silk' , silk: t , version : getFirstMatch(/silk\/(\d+(\.\d+)?)/i) } } else if (/phantom/i.test(ua)) { result = { name: 'PhantomJS' , phantom: t , version: getFirstMatch(/phantomjs\/(\d+(\.\d+)?)/i) } } else if (/slimerjs/i.test(ua)) { result = { name: 'SlimerJS' , slimer: t , version: getFirstMatch(/slimerjs\/(\d+(\.\d+)?)/i) } } else if (/blackberry|\bbb\d+/i.test(ua) || /rim\stablet/i.test(ua)) { result = { name: 'BlackBerry' , blackberry: t , version: versionIdentifier || getFirstMatch(/blackberry[\d]+\/(\d+(\.\d+)?)/i) } } else if (webos) { result = { name: 'WebOS' , webos: t , version: versionIdentifier || getFirstMatch(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i) }; /touchpad\//i.test(ua) && (result.touchpad = t) } else if (/bada/i.test(ua)) { result = { name: 'Bada' , bada: t , version: getFirstMatch(/dolfin\/(\d+(\.\d+)?)/i) }; } else if (tizen) { result = { name: 'Tizen' , tizen: t , version: getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i) || versionIdentifier }; } else if (/qupzilla/i.test(ua)) { result = { name: 'QupZilla' , qupzilla: t , version: getFirstMatch(/(?:qupzilla)[\s\/](\d+(?:\.\d+)+)/i) || versionIdentifier } } else if (/chromium/i.test(ua)) { result = { name: 'Chromium' , chromium: t , version: getFirstMatch(/(?:chromium)[\s\/](\d+(?:\.\d+)?)/i) || versionIdentifier } } else if (/chrome|crios|crmo/i.test(ua)) { result = { name: 'Chrome' , chrome: t , version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i) } } else if (android) { result = { name: 'Android' , version: versionIdentifier } } else if (/safari|applewebkit/i.test(ua)) { result = { name: 'Safari' , safari: t } if (versionIdentifier) { result.version = versionIdentifier } } else if (iosdevice) { result = { name : iosdevice == 'iphone' ? 'iPhone' : iosdevice == 'ipad' ? 'iPad' : 'iPod' } // WTF: version is not part of user agent in web apps if (versionIdentifier) { result.version = versionIdentifier } } else if(/googlebot/i.test(ua)) { result = { name: 'Googlebot' , googlebot: t , version: getFirstMatch(/googlebot\/(\d+(\.\d+))/i) || versionIdentifier } } else { result = { name: getFirstMatch(/^(.*)\/(.*) /), version: getSecondMatch(/^(.*)\/(.*) /) }; } // set webkit or gecko flag for browsers based on these engines if (!result.msedge && /(apple)?webkit/i.test(ua)) { if (/(apple)?webkit\/537\.36/i.test(ua)) { result.name = result.name || "Blink" result.blink = t } else { result.name = result.name || "Webkit" result.webkit = t } if (!result.version && versionIdentifier) { result.version = versionIdentifier } } else if (!result.opera && /gecko\//i.test(ua)) { result.name = result.name || "Gecko" result.gecko = t result.version = result.version || getFirstMatch(/gecko\/(\d+(\.\d+)?)/i) } // set OS flags for platforms that have multiple browsers if (!result.windowsphone && !result.msedge && (android || result.silk)) { result.android = t } else if (!result.windowsphone && !result.msedge && iosdevice) { result[iosdevice] = t result.ios = t } else if (mac) { result.mac = t } else if (xbox) { result.xbox = t } else if (windows) { result.windows = t } else if (linux) { result.linux = t } function getWindowsVersion (s) { switch (s) { case 'NT': return 'NT' case 'XP': return 'XP' case 'NT 5.0': return '2000' case 'NT 5.1': return 'XP' case 'NT 5.2': return '2003' case 'NT 6.0': return 'Vista' case 'NT 6.1': return '7' case 'NT 6.2': return '8' case 'NT 6.3': return '8.1' case 'NT 10.0': return '10' default: return undefined } } // OS version extraction var osVersion = ''; if (result.windows) { osVersion = getWindowsVersion(getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i)) } else if (result.windowsphone) { osVersion = getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i); } else if (result.mac) { osVersion = getFirstMatch(/Mac OS X (\d+([_\.\s]\d+)*)/i); osVersion = osVersion.replace(/[_\s]/g, '.'); } else if (iosdevice) { osVersion = getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i); osVersion = osVersion.replace(/[_\s]/g, '.'); } else if (android) { osVersion = getFirstMatch(/android[ \/-](\d+(\.\d+)*)/i); } else if (result.webos) { osVersion = getFirstMatch(/(?:web|hpw)os\/(\d+(\.\d+)*)/i); } else if (result.blackberry) { osVersion = getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i); } else if (result.bada) { osVersion = getFirstMatch(/bada\/(\d+(\.\d+)*)/i); } else if (result.tizen) { osVersion = getFirstMatch(/tizen[\/\s](\d+(\.\d+)*)/i); } if (osVersion) { result.osversion = osVersion; } // device type extraction var osMajorVersion = !result.windows && osVersion.split('.')[0]; if ( tablet || nexusTablet || iosdevice == 'ipad' || (android && (osMajorVersion == 3 || (osMajorVersion >= 4 && !mobile))) || result.silk ) { result.tablet = t } else if ( mobile || iosdevice == 'iphone' || iosdevice == 'ipod' || android || nexusMobile || result.blackberry || result.webos || result.bada ) { result.mobile = t } // Graded Browser Support // http://developer.yahoo.com/yui/articles/gbs if (result.msedge || (result.msie && result.version >= 10) || (result.yandexbrowser && result.version >= 15) || (result.vivaldi && result.version >= 1.0) || (result.chrome && result.version >= 20) || (result.samsungBrowser && result.version >= 4) || (result.firefox && result.version >= 20.0) || (result.safari && result.version >= 6) || (result.opera && result.version >= 10.0) || (result.ios && result.osversion && result.osversion.split(".")[0] >= 6) || (result.blackberry && result.version >= 10.1) || (result.chromium && result.version >= 20) ) { result.a = t; } else if ((result.msie && result.version < 10) || (result.chrome && result.version < 20) || (result.firefox && result.version < 20.0) || (result.safari && result.version < 6) || (result.opera && result.version < 10.0) || (result.ios && result.osversion && result.osversion.split(".")[0] < 6) || (result.chromium && result.version < 20) ) { result.c = t } else result.x = t return result } var bowser = detect(typeof navigator !== 'undefined' ? navigator.userAgent || '' : '') bowser.test = function (browserList) { for (var i = 0; i < browserList.length; ++i) { var browserItem = browserList[i]; if (typeof browserItem=== 'string') { if (browserItem in bowser) { return true; } } } return false; } /** * Get version precisions count * * @example * getVersionPrecision("1.10.3") // 3 * * @param {string} version * @return {number} */ function getVersionPrecision(version) { return version.split(".").length; } /** * Array::map polyfill * * @param {Array} arr * @param {Function} iterator * @return {Array} */ function map(arr, iterator) { var result = [], i; if (Array.prototype.map) { return Array.prototype.map.call(arr, iterator); } for (i = 0; i < arr.length; i++) { result.push(iterator(arr[i])); } return result; } /** * Calculate browser version weight * * @example * compareVersions(['1.10.2.1', '1.8.2.1.90']) // 1 * compareVersions(['1.010.2.1', '1.09.2.1.90']); // 1 * compareVersions(['1.10.2.1', '1.10.2.1']); // 0 * compareVersions(['1.10.2.1', '1.0800.2']); // -1 * * @param {Array<String>} versions versions to compare * @return {Number} comparison result */ function compareVersions(versions) { // 1) get common precision for both versions, for example for "10.0" and "9" it should be 2 var precision = Math.max(getVersionPrecision(versions[0]), getVersionPrecision(versions[1])); var chunks = map(versions, function (version) { var delta = precision - getVersionPrecision(version); // 2) "9" -> "9.0" (for precision = 2) version = version + new Array(delta + 1).join(".0"); // 3) "9.0" -> ["000000000"", "000000009"] return map(version.split("."), function (chunk) { return new Array(20 - chunk.length).join("0") + chunk; }).reverse(); }); // iterate in reverse order by reversed chunks array while (--precision >= 0) { // 4) compare: "000000009" > "000000010" = false (but "9" > "10" = true) if (chunks[0][precision] > chunks[1][precision]) { return 1; } else if (chunks[0][precision] === chunks[1][precision]) { if (precision === 0) { // all version chunks are same return 0; } } else { return -1; } } } /** * Check if browser is unsupported * * @example * bowser.isUnsupportedBrowser({ * msie: "10", * firefox: "23", * chrome: "29", * safari: "5.1", * opera: "16", * phantom: "534" * }); * * @param {Object} minVersions map of minimal version to browser * @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map * @param {String} [ua] user agent string * @return {Boolean} */ function isUnsupportedBrowser(minVersions, strictMode, ua) { var _bowser = bowser; // make strictMode param optional with ua param usage if (typeof strictMode === 'string') { ua = strictMode; strictMode = void(0); } if (strictMode === void(0)) { strictMode = false; } if (ua) { _bowser = detect(ua); } var version = "" + _bowser.version; for (var browser in minVersions) { if (minVersions.hasOwnProperty(browser)) { if (_bowser[browser]) { if (typeof minVersions[browser] !== 'string') { throw new Error('Browser version in the minVersion map should be a string: ' + browser + ': ' + String(minVersions)); } // browser version and min supported version. return compareVersions([version, minVersions[browser]]) < 0; } } } return strictMode; // not found } /** * Check if browser is supported * * @param {Object} minVersions map of minimal version to browser * @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map * @param {String} [ua] user agent string * @return {Boolean} */ function check(minVersions, strictMode, ua) { return !isUnsupportedBrowser(minVersions, strictMode, ua); } bowser.isUnsupportedBrowser = isUnsupportedBrowser; bowser.compareVersions = compareVersions; bowser.check = check; /* * Set our detect method to the main bowser object so we can * reuse it to test other user agents. * This is needed to implement future tests. */ bowser._detect = detect; return bowser }); },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/console-browserify/index.js":[function(require,module,exports){ (function (global){ /*global window, global*/ var util = require("util") var assert = require("assert") var now = require("date-now") var slice = Array.prototype.slice var console var times = {} if (typeof global !== "undefined" && global.console) { console = global.console } else if (typeof window !== "undefined" && window.console) { console = window.console } else { console = {} } var functions = [ [log, "log"], [info, "info"], [warn, "warn"], [error, "error"], [time, "time"], [timeEnd, "timeEnd"], [trace, "trace"], [dir, "dir"], [consoleAssert, "assert"] ] for (var i = 0; i < functions.length; i++) { var tuple = functions[i] var f = tuple[0] var name = tuple[1] if (!console[name]) { console[name] = f } } module.exports = console function log() {} function info() { console.log.apply(console, arguments) } function warn() { console.log.apply(console, arguments) } function error() { console.warn.apply(console, arguments) } function time(label) { times[label] = now() } function timeEnd(label) { var time = times[label] if (!time) { throw new Error("No such label: " + label) } var duration = now() - time console.log(label + ": " + duration + "ms") } function trace() { var err = new Error() err.name = "Trace" err.message = util.format.apply(null, arguments) console.error(err.stack) } function dir(object) { console.log(util.inspect(object) + "\n") } function consoleAssert(expression) { if (!expression) { var arr = slice.call(arguments, 1) assert.ok(false, util.format.apply(null, arr)) } } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"assert":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/assert/assert.js","date-now":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/date-now/index.js","util":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/util/util.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/contra/debounce.js":[function(require,module,exports){ 'use strict'; var ticky = require('ticky'); module.exports = function debounce (fn, args, ctx) { if (!fn) { return; } ticky(function run () { fn.apply(ctx || null, args || []); }); }; },{"ticky":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/ticky/ticky-browser.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/contra/emitter.js":[function(require,module,exports){ 'use strict'; var atoa = require('atoa'); var debounce = require('./debounce'); module.exports = function emitter (thing, options) { var opts = options || {}; var evt = {}; if (thing === undefined) { thing = {}; } thing.on = function (type, fn) { if (!evt[type]) { evt[type] = [fn]; } else { evt[type].push(fn); } return thing; }; thing.once = function (type, fn) { fn._once = true; // thing.off(fn) still works! thing.on(type, fn); return thing; }; thing.off = function (type, fn) { var c = arguments.length; if (c === 1) { delete evt[type]; } else if (c === 0) { evt = {}; } else { var et = evt[type]; if (!et) { return thing; } et.splice(et.indexOf(fn), 1); } return thing; }; thing.emit = function () { var args = atoa(arguments); return thing.emitterSnapshot(args.shift()).apply(this, args); }; thing.emitterSnapshot = function (type) { var et = (evt[type] || []).slice(0); return function () { var args = atoa(arguments); var ctx = this || thing; if (type === 'error' && opts.throws !== false && !et.length) { throw args.length === 1 ? args[0] : args; } et.forEach(function emitter (listen) { if (opts.async) { debounce(listen, args, ctx); } else { listen.apply(ctx, args); } if (listen._once) { thing.off(type, listen); } }); return thing; }; }; return thing; }; },{"./debounce":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/contra/debounce.js","atoa":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/atoa/atoa.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/crossvent/src/crossvent.js":[function(require,module,exports){ (function (global){ 'use strict'; var customEvent = require('custom-event'); var eventmap = require('./eventmap'); var doc = global.document; var addEvent = addEventEasy; var removeEvent = removeEventEasy; var hardCache = []; if (!global.addEventListener) { addEvent = addEventHard; removeEvent = removeEventHard; } module.exports = { add: addEvent, remove: removeEvent, fabricate: fabricateEvent }; function addEventEasy (el, type, fn, capturing) { return el.addEventListener(type, fn, capturing); } function addEventHard (el, type, fn) { return el.attachEvent('on' + type, wrap(el, type, fn)); } function removeEventEasy (el, type, fn, capturing) { return el.removeEventListener(type, fn, capturing); } function removeEventHard (el, type, fn) { var listener = unwrap(el, type, fn); if (listener) { return el.detachEvent('on' + type, listener); } } function fabricateEvent (el, type, model) { var e = eventmap.indexOf(type) === -1 ? makeCustomEvent() : makeClassicEvent(); if (el.dispatchEvent) { el.dispatchEvent(e); } else { el.fireEvent('on' + type, e); } function makeClassicEvent () { var e; if (doc.createEvent) { e = doc.createEvent('Event'); e.initEvent(type, true, true); } else if (doc.createEventObject) { e = doc.createEventObject(); } return e; } function makeCustomEvent () { return new customEvent(type, { detail: model }); } } function wrapperFactory (el, type, fn) { return function wrapper (originalEvent) { var e = originalEvent || global.event; e.target = e.target || e.srcElement; e.preventDefault = e.preventDefault || function preventDefault () { e.returnValue = false; }; e.stopPropagation = e.stopPropagation || function stopPropagation () { e.cancelBubble = true; }; e.which = e.which || e.keyCode; fn.call(el, e); }; } function wrap (el, type, fn) { var wrapper = unwrap(el, type, fn) || wrapperFactory(el, type, fn); hardCache.push({ wrapper: wrapper, element: el, type: type, fn: fn }); return wrapper; } function unwrap (el, type, fn) { var i = find(el, type, fn); if (i) { var wrapper = hardCache[i].wrapper; hardCache.splice(i, 1); // free up a tad of memory return wrapper; } } function find (el, type, fn) { var i, item; for (i = 0; i < hardCache.length; i++) { item = hardCache[i]; if (item.element === el && item.type === type && item.fn === fn) { return i; } } } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./eventmap":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/crossvent/src/eventmap.js","custom-event":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/custom-event/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/crossvent/src/eventmap.js":[function(require,module,exports){ (function (global){ 'use strict'; var eventmap = []; var eventname = ''; var ron = /^on/; for (eventname in global) { if (ron.test(eventname)) { eventmap.push(eventname.slice(2)); } } module.exports = eventmap; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/csslint/lib/csslint-node.js":[function(require,module,exports){ /*! CSSLint Copyright (c) 2013 Nicole Sullivan and Nicholas C. Zakas. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Build: v0.10.0 15-August-2013 01:07:22 */ var parserlib = require("parserlib"); /** * Main CSSLint object. * @class CSSLint * @static * @extends parserlib.util.EventTarget */ /*global parserlib, Reporter*/ var CSSLint = (function(){ var rules = [], formatters = [], embeddedRuleset = /\/\*csslint([^\*]*)\*\//, api = new parserlib.util.EventTarget(); api.version = "0.10.0"; //------------------------------------------------------------------------- // Rule Management //------------------------------------------------------------------------- /** * Adds a new rule to the engine. * @param {Object} rule The rule to add. * @method addRule */ api.addRule = function(rule){ rules.push(rule); rules[rule.id] = rule; }; /** * Clears all rule from the engine. * @method clearRules */ api.clearRules = function(){ rules = []; }; /** * Returns the rule objects. * @return An array of rule objects. * @method getRules */ api.getRules = function(){ return [].concat(rules).sort(function(a,b){ return a.id > b.id ? 1 : 0; }); }; /** * Returns a ruleset configuration object with all current rules. * @return A ruleset object. * @method getRuleset */ api.getRuleset = function() { var ruleset = {}, i = 0, len = rules.length; while (i < len){ ruleset[rules[i++].id] = 1; //by default, everything is a warning } return ruleset; }; /** * Returns a ruleset object based on embedded rules. * @param {String} text A string of css containing embedded rules. * @param {Object} ruleset A ruleset object to modify. * @return {Object} A ruleset object. * @method getEmbeddedRuleset */ function applyEmbeddedRuleset(text, ruleset){ var valueMap, embedded = text && text.match(embeddedRuleset), rules = embedded && embedded[1]; if (rules) { valueMap = { "true": 2, // true is error "": 1, // blank is warning "false": 0, // false is ignore "2": 2, // explicit error "1": 1, // explicit warning "0": 0 // explicit ignore }; rules.toLowerCase().split(",").forEach(function(rule){ var pair = rule.split(":"), property = pair[0] || "", value = pair[1] || ""; ruleset[property.trim()] = valueMap[value.trim()]; }); } return ruleset; } //------------------------------------------------------------------------- // Formatters //------------------------------------------------------------------------- /** * Adds a new formatter to the engine. * @param {Object} formatter The formatter to add. * @method addFormatter */ api.addFormatter = function(formatter) { // formatters.push(formatter); formatters[formatter.id] = formatter; }; /** * Retrieves a formatter for use. * @param {String} formatId The name of the format to retrieve. * @return {Object} The formatter or undefined. * @method getFormatter */ api.getFormatter = function(formatId){ return formatters[formatId]; }; /** * Formats the results in a particular format for a single file. * @param {Object} result The results returned from CSSLint.verify(). * @param {String} filename The filename for which the results apply. * @param {String} formatId The name of the formatter to use. * @param {Object} options (Optional) for special output handling. * @return {String} A formatted string for the results. * @method format */ api.format = function(results, filename, formatId, options) { var formatter = this.getFormatter(formatId), result = null; if (formatter){ result = formatter.startFormat(); result += formatter.formatResults(results, filename, options || {}); result += formatter.endFormat(); } return result; }; /** * Indicates if the given format is supported. * @param {String} formatId The ID of the format to check. * @return {Boolean} True if the format exists, false if not. * @method hasFormat */ api.hasFormat = function(formatId){ return formatters.hasOwnProperty(formatId); }; //------------------------------------------------------------------------- // Verification //------------------------------------------------------------------------- /** * Starts the verification process for the given CSS text. * @param {String} text The CSS text to verify. * @param {Object} ruleset (Optional) List of rules to apply. If null, then * all rules are used. If a rule has a value of 1 then it's a warning, * a value of 2 means it's an error. * @return {Object} Results of the verification. * @method verify */ api.verify = function(text, ruleset){ var i = 0, len = rules.length, reporter, lines, report, parser = new parserlib.css.Parser({ starHack: true, ieFilters: true, underscoreHack: true, strict: false }); // normalize line endings lines = text.replace(/\n\r?/g, "$split$").split('$split$'); if (!ruleset){ ruleset = this.getRuleset(); } if (embeddedRuleset.test(text)){ ruleset = applyEmbeddedRuleset(text, ruleset); } reporter = new Reporter(lines, ruleset); ruleset.errors = 2; //always report parsing errors as errors for (i in ruleset){ if(ruleset.hasOwnProperty(i) && ruleset[i]){ if (rules[i]){ rules[i].init(parser, reporter); } } } //capture most horrible error type try { parser.parse(text); } catch (ex) { reporter.error("Fatal error, cannot continue: " + ex.message, ex.line, ex.col, {}); } report = { messages : reporter.messages, stats : reporter.stats, ruleset : reporter.ruleset }; //sort by line numbers, rollups at the bottom report.messages.sort(function (a, b){ if (a.rollup && !b.rollup){ return 1; } else if (!a.rollup && b.rollup){ return -1; } else { return a.line - b.line; } }); return report; }; //------------------------------------------------------------------------- // Publish the API //------------------------------------------------------------------------- return api; })(); /*global CSSLint*/ /** * An instance of Report is used to report results of the * verification back to the main API. * @class Reporter * @constructor * @param {String[]} lines The text lines of the source. * @param {Object} ruleset The set of rules to work with, including if * they are errors or warnings. */ function Reporter(lines, ruleset){ /** * List of messages being reported. * @property messages * @type String[] */ this.messages = []; /** * List of statistics being reported. * @property stats * @type String[] */ this.stats = []; /** * Lines of code being reported on. Used to provide contextual information * for messages. * @property lines * @type String[] */ this.lines = lines; /** * Information about the rules. Used to determine whether an issue is an * error or warning. * @property ruleset * @type Object */ this.ruleset = ruleset; } Reporter.prototype = { //restore constructor constructor: Reporter, /** * Report an error. * @param {String} message The message to store. * @param {int} line The line number. * @param {int} col The column number. * @param {Object} rule The rule this message relates to. * @method error */ error: function(message, line, col, rule){ this.messages.push({ type : "error", line : line, col : col, message : message, evidence: this.lines[line-1], rule : rule || {} }); }, /** * Report an warning. * @param {String} message The message to store. * @param {int} line The line number. * @param {int} col The column number. * @param {Object} rule The rule this message relates to. * @method warn * @deprecated Use report instead. */ warn: function(message, line, col, rule){ this.report(message, line, col, rule); }, /** * Report an issue. * @param {String} message The message to store. * @param {int} line The line number. * @param {int} col The column number. * @param {Object} rule The rule this message relates to. * @method report */ report: function(message, line, col, rule){ this.messages.push({ type : this.ruleset[rule.id] == 2 ? "error" : "warning", line : line, col : col, message : message, evidence: this.lines[line-1], rule : rule }); }, /** * Report some informational text. * @param {String} message The message to store. * @param {int} line The line number. * @param {int} col The column number. * @param {Object} rule The rule this message relates to. * @method info */ info: function(message, line, col, rule){ this.messages.push({ type : "info", line : line, col : col, message : message, evidence: this.lines[line-1], rule : rule }); }, /** * Report some rollup error information. * @param {String} message The message to store. * @param {Object} rule The rule this message relates to. * @method rollupError */ rollupError: function(message, rule){ this.messages.push({ type : "error", rollup : true, message : message, rule : rule }); }, /** * Report some rollup warning information. * @param {String} message The message to store. * @param {Object} rule The rule this message relates to. * @method rollupWarn */ rollupWarn: function(message, rule){ this.messages.push({ type : "warning", rollup : true, message : message, rule : rule }); }, /** * Report a statistic. * @param {String} name The name of the stat to store. * @param {Variant} value The value of the stat. * @method stat */ stat: function(name, value){ this.stats[name] = value; } }; //expose for testing purposes CSSLint._Reporter = Reporter; /*global CSSLint*/ /* * Utility functions that make life easier. */ CSSLint.Util = { /* * Adds all properties from supplier onto receiver, * overwriting if the same name already exists on * reciever. * @param {Object} The object to receive the properties. * @param {Object} The object to provide the properties. * @return {Object} The receiver */ mix: function(receiver, supplier){ var prop; for (prop in supplier){ if (supplier.hasOwnProperty(prop)){ receiver[prop] = supplier[prop]; } } return prop; }, /* * Polyfill for array indexOf() method. * @param {Array} values The array to search. * @param {Variant} value The value to search for. * @return {int} The index of the value if found, -1 if not. */ indexOf: function(values, value){ if (values.indexOf){ return values.indexOf(value); } else { for (var i=0, len=values.length; i < len; i++){ if (values[i] === value){ return i; } } return -1; } }, /* * Polyfill for array forEach() method. * @param {Array} values The array to operate on. * @param {Function} func The function to call on each item. * @return {void} */ forEach: function(values, func) { if (values.forEach){ return values.forEach(func); } else { for (var i=0, len=values.length; i < len; i++){ func(values[i], i, values); } } } }; /*global CSSLint*/ /* * Rule: Don't use adjoining classes (.foo.bar). */ CSSLint.addRule({ //rule information id: "adjoining-classes", name: "Disallow adjoining classes", desc: "Don't use adjoining classes.", browsers: "IE6", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, modifier, classCount, i, j, k; for (i=0; i < selectors.length; i++){ selector = selectors[i]; for (j=0; j < selector.parts.length; j++){ part = selector.parts[j]; if (part.type == parser.SELECTOR_PART_TYPE){ classCount = 0; for (k=0; k < part.modifiers.length; k++){ modifier = part.modifiers[k]; if (modifier.type == "class"){ classCount++; } if (classCount > 1){ reporter.report("Don't use adjoining classes.", part.line, part.col, rule); } } } } } }); } }); /*global CSSLint*/ /* * Rule: Don't use width or height when using padding or border. */ CSSLint.addRule({ //rule information id: "box-model", name: "Beware of broken box size", desc: "Don't use width or height when using padding or border.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, widthProperties = { border: 1, "border-left": 1, "border-right": 1, padding: 1, "padding-left": 1, "padding-right": 1 }, heightProperties = { border: 1, "border-bottom": 1, "border-top": 1, padding: 1, "padding-bottom": 1, "padding-top": 1 }, properties, boxSizing = false; function startRule(){ properties = {}; boxSizing = false; } function endRule(){ var prop, value; if (!boxSizing) { if (properties.height){ for (prop in heightProperties){ if (heightProperties.hasOwnProperty(prop) && properties[prop]){ value = properties[prop].value; //special case for padding if (!(prop == "padding" && value.parts.length === 2 && value.parts[0].value === 0)){ reporter.report("Using height with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule); } } } } if (properties.width){ for (prop in widthProperties){ if (widthProperties.hasOwnProperty(prop) && properties[prop]){ value = properties[prop].value; if (!(prop == "padding" && value.parts.length === 2 && value.parts[1].value === 0)){ reporter.report("Using width with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule); } } } } } } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startpage", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("property", function(event){ var name = event.property.text.toLowerCase(); if (heightProperties[name] || widthProperties[name]){ if (!/^0\S*$/.test(event.value) && !(name == "border" && event.value == "none")){ properties[name] = { line: event.property.line, col: event.property.col, value: event.value }; } } else { if (/^(width|height)/i.test(name) && /^(length|percentage)/.test(event.value.parts[0].type)){ properties[name] = 1; } else if (name == "box-sizing") { boxSizing = true; } } }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); parser.addListener("endpage", endRule); parser.addListener("endpagemargin", endRule); parser.addListener("endkeyframerule", endRule); } }); /*global CSSLint*/ /* * Rule: box-sizing doesn't work in IE6 and IE7. */ CSSLint.addRule({ //rule information id: "box-sizing", name: "Disallow use of box-sizing", desc: "The box-sizing properties isn't supported in IE6 and IE7.", browsers: "IE6, IE7", tags: ["Compatibility"], //initialization init: function(parser, reporter){ var rule = this; parser.addListener("property", function(event){ var name = event.property.text.toLowerCase(); if (name == "box-sizing"){ reporter.report("The box-sizing property isn't supported in IE6 and IE7.", event.line, event.col, rule); } }); } }); /* * Rule: Use the bulletproof @font-face syntax to avoid 404's in old IE * (http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax) */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "bulletproof-font-face", name: "Use the bulletproof @font-face syntax", desc: "Use the bulletproof @font-face syntax to avoid 404's in old IE (http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax).", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, count = 0, fontFaceRule = false, firstSrc = true, ruleFailed = false, line, col; // Mark the start of a @font-face declaration so we only test properties inside it parser.addListener("startfontface", function(event){ fontFaceRule = true; }); parser.addListener("property", function(event){ // If we aren't inside an @font-face declaration then just return if (!fontFaceRule) { return; } var propertyName = event.property.toString().toLowerCase(), value = event.value.toString(); // Set the line and col numbers for use in the endfontface listener line = event.line; col = event.col; // This is the property that we care about, we can ignore the rest if (propertyName === 'src') { var regex = /^\s?url\(['"].+\.eot\?.*['"]\)\s*format\(['"]embedded-opentype['"]\).*$/i; // We need to handle the advanced syntax with two src properties if (!value.match(regex) && firstSrc) { ruleFailed = true; firstSrc = false; } else if (value.match(regex) && !firstSrc) { ruleFailed = false; } } }); // Back to normal rules that we don't need to test parser.addListener("endfontface", function(event){ fontFaceRule = false; if (ruleFailed) { reporter.report("@font-face declaration doesn't follow the fontspring bulletproof syntax.", line, col, rule); } }); } }); /* * Rule: Include all compatible vendor prefixes to reach a wider * range of users. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "compatible-vendor-prefixes", name: "Require compatible vendor prefixes", desc: "Include all compatible vendor prefixes to reach a wider range of users.", browsers: "All", //initialization init: function (parser, reporter) { var rule = this, compatiblePrefixes, properties, prop, variations, prefixed, i, len, inKeyFrame = false, arrayPush = Array.prototype.push, applyTo = []; // See http://peter.sh/experiments/vendor-prefixed-css-property-overview/ for details compatiblePrefixes = { "animation" : "webkit moz", "animation-delay" : "webkit moz", "animation-direction" : "webkit moz", "animation-duration" : "webkit moz", "animation-fill-mode" : "webkit moz", "animation-iteration-count" : "webkit moz", "animation-name" : "webkit moz", "animation-play-state" : "webkit moz", "animation-timing-function" : "webkit moz", "appearance" : "webkit moz", "border-end" : "webkit moz", "border-end-color" : "webkit moz", "border-end-style" : "webkit moz", "border-end-width" : "webkit moz", "border-image" : "webkit moz o", "border-radius" : "webkit", "border-start" : "webkit moz", "border-start-color" : "webkit moz", "border-start-style" : "webkit moz", "border-start-width" : "webkit moz", "box-align" : "webkit moz ms", "box-direction" : "webkit moz ms", "box-flex" : "webkit moz ms", "box-lines" : "webkit ms", "box-ordinal-group" : "webkit moz ms", "box-orient" : "webkit moz ms", "box-pack" : "webkit moz ms", "box-sizing" : "webkit moz", "box-shadow" : "webkit moz", "column-count" : "webkit moz ms", "column-gap" : "webkit moz ms", "column-rule" : "webkit moz ms", "column-rule-color" : "webkit moz ms", "column-rule-style" : "webkit moz ms", "column-rule-width" : "webkit moz ms", "column-width" : "webkit moz ms", "hyphens" : "epub moz", "line-break" : "webkit ms", "margin-end" : "webkit moz", "margin-start" : "webkit moz", "marquee-speed" : "webkit wap", "marquee-style" : "webkit wap", "padding-end" : "webkit moz", "padding-start" : "webkit moz", "tab-size" : "moz o", "text-size-adjust" : "webkit ms", "transform" : "webkit moz ms o", "transform-origin" : "webkit moz ms o", "transition" : "webkit moz o", "transition-delay" : "webkit moz o", "transition-duration" : "webkit moz o", "transition-property" : "webkit moz o", "transition-timing-function" : "webkit moz o", "user-modify" : "webkit moz", "user-select" : "webkit moz ms", "word-break" : "epub ms", "writing-mode" : "epub ms" }; for (prop in compatiblePrefixes) { if (compatiblePrefixes.hasOwnProperty(prop)) { variations = []; prefixed = compatiblePrefixes[prop].split(' '); for (i = 0, len = prefixed.length; i < len; i++) { variations.push('-' + prefixed[i] + '-' + prop); } compatiblePrefixes[prop] = variations; arrayPush.apply(applyTo, variations); } } parser.addListener("startrule", function () { properties = []; }); parser.addListener("startkeyframes", function (event) { inKeyFrame = event.prefix || true; }); parser.addListener("endkeyframes", function (event) { inKeyFrame = false; }); parser.addListener("property", function (event) { var name = event.property; if (CSSLint.Util.indexOf(applyTo, name.text) > -1) { // e.g., -moz-transform is okay to be alone in @-moz-keyframes if (!inKeyFrame || typeof inKeyFrame != "string" || name.text.indexOf("-" + inKeyFrame + "-") !== 0) { properties.push(name); } } }); parser.addListener("endrule", function (event) { if (!properties.length) { return; } var propertyGroups = {}, i, len, name, prop, variations, value, full, actual, item, propertiesSpecified; for (i = 0, len = properties.length; i < len; i++) { name = properties[i]; for (prop in compatiblePrefixes) { if (compatiblePrefixes.hasOwnProperty(prop)) { variations = compatiblePrefixes[prop]; if (CSSLint.Util.indexOf(variations, name.text) > -1) { if (!propertyGroups[prop]) { propertyGroups[prop] = { full : variations.slice(0), actual : [], actualNodes: [] }; } if (CSSLint.Util.indexOf(propertyGroups[prop].actual, name.text) === -1) { propertyGroups[prop].actual.push(name.text); propertyGroups[prop].actualNodes.push(name); } } } } } for (prop in propertyGroups) { if (propertyGroups.hasOwnProperty(prop)) { value = propertyGroups[prop]; full = value.full; actual = value.actual; if (full.length > actual.length) { for (i = 0, len = full.length; i < len; i++) { item = full[i]; if (CSSLint.Util.indexOf(actual, item) === -1) { propertiesSpecified = (actual.length === 1) ? actual[0] : (actual.length == 2) ? actual.join(" and ") : actual.join(", "); reporter.report("The property " + item + " is compatible with " + propertiesSpecified + " and should be included as well.", value.actualNodes[0].line, value.actualNodes[0].col, rule); } } } } } }); } }); /* * Rule: Certain properties don't play well with certain display values. * - float should not be used with inline-block * - height, width, margin-top, margin-bottom, float should not be used with inline * - vertical-align should not be used with block * - margin, float should not be used with table-* */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "display-property-grouping", name: "Require properties appropriate for display", desc: "Certain properties shouldn't be used with certain display property values.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; var propertiesToCheck = { display: 1, "float": "none", height: 1, width: 1, margin: 1, "margin-left": 1, "margin-right": 1, "margin-bottom": 1, "margin-top": 1, padding: 1, "padding-left": 1, "padding-right": 1, "padding-bottom": 1, "padding-top": 1, "vertical-align": 1 }, properties; function reportProperty(name, display, msg){ if (properties[name]){ if (typeof propertiesToCheck[name] != "string" || properties[name].value.toLowerCase() != propertiesToCheck[name]){ reporter.report(msg || name + " can't be used with display: " + display + ".", properties[name].line, properties[name].col, rule); } } } function startRule(){ properties = {}; } function endRule(){ var display = properties.display ? properties.display.value : null; if (display){ switch(display){ case "inline": //height, width, margin-top, margin-bottom, float should not be used with inline reportProperty("height", display); reportProperty("width", display); reportProperty("margin", display); reportProperty("margin-top", display); reportProperty("margin-bottom", display); reportProperty("float", display, "display:inline has no effect on floated elements (but may be used to fix the IE6 double-margin bug)."); break; case "block": //vertical-align should not be used with block reportProperty("vertical-align", display); break; case "inline-block": //float should not be used with inline-block reportProperty("float", display); break; default: //margin, float should not be used with table if (display.indexOf("table-") === 0){ reportProperty("margin", display); reportProperty("margin-left", display); reportProperty("margin-right", display); reportProperty("margin-top", display); reportProperty("margin-bottom", display); reportProperty("float", display); } //otherwise do nothing } } } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startpage", startRule); parser.addListener("property", function(event){ var name = event.property.text.toLowerCase(); if (propertiesToCheck[name]){ properties[name] = { value: event.value.text, line: event.property.line, col: event.property.col }; } }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); parser.addListener("endkeyframerule", endRule); parser.addListener("endpagemargin", endRule); parser.addListener("endpage", endRule); } }); /* * Rule: Disallow duplicate background-images (using url). */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "duplicate-background-images", name: "Disallow duplicate background images", desc: "Every background-image should be unique. Use a common class for e.g. sprites.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, stack = {}; parser.addListener("property", function(event){ var name = event.property.text, value = event.value, i, len; if (name.match(/background/i)) { for (i=0, len=value.parts.length; i < len; i++) { if (value.parts[i].type == 'uri') { if (typeof stack[value.parts[i].uri] === 'undefined') { stack[value.parts[i].uri] = event; } else { reporter.report("Background image '" + value.parts[i].uri + "' was used multiple times, first declared at line " + stack[value.parts[i].uri].line + ", col " + stack[value.parts[i].uri].col + ".", event.line, event.col, rule); } } } } }); } }); /* * Rule: Duplicate properties must appear one after the other. If an already-defined * property appears somewhere else in the rule, then it's likely an error. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "duplicate-properties", name: "Disallow duplicate properties", desc: "Duplicate properties must appear one after the other.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, properties, lastProperty; function startRule(event){ properties = {}; } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startpage", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("property", function(event){ var property = event.property, name = property.text.toLowerCase(); if (properties[name] && (lastProperty != name || properties[name] == event.value.text)){ reporter.report("Duplicate property '" + event.property + "' found.", event.line, event.col, rule); } properties[name] = event.value.text; lastProperty = name; }); } }); /* * Rule: Style rules without any properties defined should be removed. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "empty-rules", name: "Disallow empty rules", desc: "Rules without any properties specified should be removed.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, count = 0; parser.addListener("startrule", function(){ count=0; }); parser.addListener("property", function(){ count++; }); parser.addListener("endrule", function(event){ var selectors = event.selectors; if (count === 0){ reporter.report("Rule is empty.", selectors[0].line, selectors[0].col, rule); } }); } }); /* * Rule: There should be no syntax errors. (Duh.) */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "errors", name: "Parsing Errors", desc: "This rule looks for recoverable syntax errors.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("error", function(event){ reporter.error(event.message, event.line, event.col, rule); }); } }); /*global CSSLint*/ CSSLint.addRule({ //rule information id: "fallback-colors", name: "Require fallback colors", desc: "For older browsers that don't support RGBA, HSL, or HSLA, provide a fallback color.", browsers: "IE6,IE7,IE8", //initialization init: function(parser, reporter){ var rule = this, lastProperty, propertiesToCheck = { color: 1, background: 1, "border-color": 1, "border-top-color": 1, "border-right-color": 1, "border-bottom-color": 1, "border-left-color": 1, border: 1, "border-top": 1, "border-right": 1, "border-bottom": 1, "border-left": 1, "background-color": 1 }, properties; function startRule(event){ properties = {}; lastProperty = null; } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startpage", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("property", function(event){ var property = event.property, name = property.text.toLowerCase(), parts = event.value.parts, i = 0, colorType = "", len = parts.length; if(propertiesToCheck[name]){ while(i < len){ if (parts[i].type == "color"){ if ("alpha" in parts[i] || "hue" in parts[i]){ if (/([^\)]+)\(/.test(parts[i])){ colorType = RegExp.$1.toUpperCase(); } if (!lastProperty || (lastProperty.property.text.toLowerCase() != name || lastProperty.colorType != "compat")){ reporter.report("Fallback " + name + " (hex or RGB) should precede " + colorType + " " + name + ".", event.line, event.col, rule); } } else { event.colorType = "compat"; } } i++; } } lastProperty = event; }); } }); /* * Rule: You shouldn't use more than 10 floats. If you do, there's probably * room for some abstraction. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "floats", name: "Disallow too many floats", desc: "This rule tests if the float property is used too many times", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; var count = 0; //count how many times "float" is used parser.addListener("property", function(event){ if (event.property.text.toLowerCase() == "float" && event.value.text.toLowerCase() != "none"){ count++; } }); //report the results parser.addListener("endstylesheet", function(){ reporter.stat("floats", count); if (count >= 10){ reporter.rollupWarn("Too many floats (" + count + "), you're probably using them for layout. Consider using a grid system instead.", rule); } }); } }); /* * Rule: Avoid too many @font-face declarations in the same stylesheet. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "font-faces", name: "Don't use too many web fonts", desc: "Too many different web fonts in the same stylesheet.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, count = 0; parser.addListener("startfontface", function(){ count++; }); parser.addListener("endstylesheet", function(){ if (count > 5){ reporter.rollupWarn("Too many @font-face declarations (" + count + ").", rule); } }); } }); /* * Rule: You shouldn't need more than 9 font-size declarations. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "font-sizes", name: "Disallow too many font sizes", desc: "Checks the number of font-size declarations.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, count = 0; //check for use of "font-size" parser.addListener("property", function(event){ if (event.property == "font-size"){ count++; } }); //report the results parser.addListener("endstylesheet", function(){ reporter.stat("font-sizes", count); if (count >= 10){ reporter.rollupWarn("Too many font-size declarations (" + count + "), abstraction needed.", rule); } }); } }); /* * Rule: When using a vendor-prefixed gradient, make sure to use them all. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "gradients", name: "Require all gradient definitions", desc: "When using a vendor-prefixed gradient, make sure to use them all.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, gradients; parser.addListener("startrule", function(){ gradients = { moz: 0, webkit: 0, oldWebkit: 0, o: 0 }; }); parser.addListener("property", function(event){ if (/\-(moz|o|webkit)(?:\-(?:linear|radial))\-gradient/i.test(event.value)){ gradients[RegExp.$1] = 1; } else if (/\-webkit\-gradient/i.test(event.value)){ gradients.oldWebkit = 1; } }); parser.addListener("endrule", function(event){ var missing = []; if (!gradients.moz){ missing.push("Firefox 3.6+"); } if (!gradients.webkit){ missing.push("Webkit (Safari 5+, Chrome)"); } if (!gradients.oldWebkit){ missing.push("Old Webkit (Safari 4+, Chrome)"); } if (!gradients.o){ missing.push("Opera 11.1+"); } if (missing.length && missing.length < 4){ reporter.report("Missing vendor-prefixed CSS gradients for " + missing.join(", ") + ".", event.selectors[0].line, event.selectors[0].col, rule); } }); } }); /* * Rule: Don't use IDs for selectors. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "ids", name: "Disallow IDs in selectors", desc: "Selectors should not contain IDs.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, modifier, idCount, i, j, k; for (i=0; i < selectors.length; i++){ selector = selectors[i]; idCount = 0; for (j=0; j < selector.parts.length; j++){ part = selector.parts[j]; if (part.type == parser.SELECTOR_PART_TYPE){ for (k=0; k < part.modifiers.length; k++){ modifier = part.modifiers[k]; if (modifier.type == "id"){ idCount++; } } } } if (idCount == 1){ reporter.report("Don't use IDs in selectors.", selector.line, selector.col, rule); } else if (idCount > 1){ reporter.report(idCount + " IDs in the selector, really?", selector.line, selector.col, rule); } } }); } }); /* * Rule: Don't use @import, use <link> instead. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "import", name: "Disallow @import", desc: "Don't use @import, use <link> instead.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("import", function(event){ reporter.report("@import prevents parallel downloads, use <link> instead.", event.line, event.col, rule); }); } }); /* * Rule: Make sure !important is not overused, this could lead to specificity * war. Display a warning on !important declarations, an error if it's * used more at least 10 times. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "important", name: "Disallow !important", desc: "Be careful when using !important declaration", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, count = 0; //warn that important is used and increment the declaration counter parser.addListener("property", function(event){ if (event.important === true){ count++; reporter.report("Use of !important", event.line, event.col, rule); } }); //if there are more than 10, show an error parser.addListener("endstylesheet", function(){ reporter.stat("important", count); if (count >= 10){ reporter.rollupWarn("Too many !important declarations (" + count + "), try to use less than 10 to avoid specificity issues.", rule); } }); } }); /* * Rule: Properties should be known (listed in CSS3 specification) or * be a vendor-prefixed property. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "known-properties", name: "Require use of known properties", desc: "Properties should be known (listed in CSS3 specification) or be a vendor-prefixed property.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("property", function(event){ var name = event.property.text.toLowerCase(); // the check is handled entirely by the parser-lib (https://github.com/nzakas/parser-lib) if (event.invalid) { reporter.report(event.invalid.message, event.line, event.col, rule); } }); } }); /* * Rule: outline: none or outline: 0 should only be used in a :focus rule * and only if there are other properties in the same rule. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "outline-none", name: "Disallow outline: none", desc: "Use of outline: none or outline: 0 should be limited to :focus rules.", browsers: "All", tags: ["Accessibility"], //initialization init: function(parser, reporter){ var rule = this, lastRule; function startRule(event){ if (event.selectors){ lastRule = { line: event.line, col: event.col, selectors: event.selectors, propCount: 0, outline: false }; } else { lastRule = null; } } function endRule(event){ if (lastRule){ if (lastRule.outline){ if (lastRule.selectors.toString().toLowerCase().indexOf(":focus") == -1){ reporter.report("Outlines should only be modified using :focus.", lastRule.line, lastRule.col, rule); } else if (lastRule.propCount == 1) { reporter.report("Outlines shouldn't be hidden unless other visual changes are made.", lastRule.line, lastRule.col, rule); } } } } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startpage", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("property", function(event){ var name = event.property.text.toLowerCase(), value = event.value; if (lastRule){ lastRule.propCount++; if (name == "outline" && (value == "none" || value == "0")){ lastRule.outline = true; } } }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); parser.addListener("endpage", endRule); parser.addListener("endpagemargin", endRule); parser.addListener("endkeyframerule", endRule); } }); /* * Rule: Don't use classes or IDs with elements (a.foo or a#foo). */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "overqualified-elements", name: "Disallow overqualified elements", desc: "Don't use classes or IDs with elements (a.foo or a#foo).", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, classes = {}; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, modifier, i, j, k; for (i=0; i < selectors.length; i++){ selector = selectors[i]; for (j=0; j < selector.parts.length; j++){ part = selector.parts[j]; if (part.type == parser.SELECTOR_PART_TYPE){ for (k=0; k < part.modifiers.length; k++){ modifier = part.modifiers[k]; if (part.elementName && modifier.type == "id"){ reporter.report("Element (" + part + ") is overqualified, just use " + modifier + " without element name.", part.line, part.col, rule); } else if (modifier.type == "class"){ if (!classes[modifier]){ classes[modifier] = []; } classes[modifier].push({ modifier: modifier, part: part }); } } } } } }); parser.addListener("endstylesheet", function(){ var prop; for (prop in classes){ if (classes.hasOwnProperty(prop)){ //one use means that this is overqualified if (classes[prop].length == 1 && classes[prop][0].part.elementName){ reporter.report("Element (" + classes[prop][0].part + ") is overqualified, just use " + classes[prop][0].modifier + " without element name.", classes[prop][0].part.line, classes[prop][0].part.col, rule); } } } }); } }); /* * Rule: Headings (h1-h6) should not be qualified (namespaced). */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "qualified-headings", name: "Disallow qualified headings", desc: "Headings should not be qualified (namespaced).", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, i, j; for (i=0; i < selectors.length; i++){ selector = selectors[i]; for (j=0; j < selector.parts.length; j++){ part = selector.parts[j]; if (part.type == parser.SELECTOR_PART_TYPE){ if (part.elementName && /h[1-6]/.test(part.elementName.toString()) && j > 0){ reporter.report("Heading (" + part.elementName + ") should not be qualified.", part.line, part.col, rule); } } } } }); } }); /* * Rule: Selectors that look like regular expressions are slow and should be avoided. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "regex-selectors", name: "Disallow selectors that look like regexs", desc: "Selectors that look like regular expressions are slow and should be avoided.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, modifier, i, j, k; for (i=0; i < selectors.length; i++){ selector = selectors[i]; for (j=0; j < selector.parts.length; j++){ part = selector.parts[j]; if (part.type == parser.SELECTOR_PART_TYPE){ for (k=0; k < part.modifiers.length; k++){ modifier = part.modifiers[k]; if (modifier.type == "attribute"){ if (/([\~\|\^\$\*]=)/.test(modifier)){ reporter.report("Attribute selectors with " + RegExp.$1 + " are slow!", modifier.line, modifier.col, rule); } } } } } } }); } }); /* * Rule: Total number of rules should not exceed x. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "rules-count", name: "Rules Count", desc: "Track how many rules there are.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, count = 0; //count each rule parser.addListener("startrule", function(){ count++; }); parser.addListener("endstylesheet", function(){ reporter.stat("rule-count", count); }); } }); /* * Rule: Warn people with approaching the IE 4095 limit */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "selector-max-approaching", name: "Warn when approaching the 4095 selector limit for IE", desc: "Will warn when selector count is >= 3800 selectors.", browsers: "IE", //initialization init: function(parser, reporter) { var rule = this, count = 0; parser.addListener('startrule', function(event) { count += event.selectors.length; }); parser.addListener("endstylesheet", function() { if (count >= 3800) { reporter.report("You have " + count + " selectors. Internet Explorer supports a maximum of 4095 selectors per stylesheet. Consider refactoring.",0,0,rule); } }); } }); /* * Rule: Warn people past the IE 4095 limit */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "selector-max", name: "Error when past the 4095 selector limit for IE", desc: "Will error when selector count is > 4095.", browsers: "IE", //initialization init: function(parser, reporter){ var rule = this, count = 0; parser.addListener('startrule',function(event) { count += event.selectors.length; }); parser.addListener("endstylesheet", function() { if (count > 4095) { reporter.report("You have " + count + " selectors. Internet Explorer supports a maximum of 4095 selectors per stylesheet. Consider refactoring.",0,0,rule); } }); } }); /* * Rule: Use shorthand properties where possible. * */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "shorthand", name: "Require shorthand properties", desc: "Use shorthand properties where possible.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, prop, i, len, propertiesToCheck = {}, properties, mapping = { "margin": [ "margin-top", "margin-bottom", "margin-left", "margin-right" ], "padding": [ "padding-top", "padding-bottom", "padding-left", "padding-right" ] }; //initialize propertiesToCheck for (prop in mapping){ if (mapping.hasOwnProperty(prop)){ for (i=0, len=mapping[prop].length; i < len; i++){ propertiesToCheck[mapping[prop][i]] = prop; } } } function startRule(event){ properties = {}; } //event handler for end of rules function endRule(event){ var prop, i, len, total; //check which properties this rule has for (prop in mapping){ if (mapping.hasOwnProperty(prop)){ total=0; for (i=0, len=mapping[prop].length; i < len; i++){ total += properties[mapping[prop][i]] ? 1 : 0; } if (total == mapping[prop].length){ reporter.report("The properties " + mapping[prop].join(", ") + " can be replaced by " + prop + ".", event.line, event.col, rule); } } } } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); //check for use of "font-size" parser.addListener("property", function(event){ var name = event.property.toString().toLowerCase(), value = event.value.parts[0].value; if (propertiesToCheck[name]){ properties[name] = 1; } }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); } }); /* * Rule: Don't use properties with a star prefix. * */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "star-property-hack", name: "Disallow properties with a star prefix", desc: "Checks for the star property hack (targets IE6/7)", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; //check if property name starts with "*" parser.addListener("property", function(event){ var property = event.property; if (property.hack == "*") { reporter.report("Property with star prefix found.", event.property.line, event.property.col, rule); } }); } }); /* * Rule: Don't use text-indent for image replacement if you need to support rtl. * */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "text-indent", name: "Disallow negative text-indent", desc: "Checks for text indent less than -99px", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, textIndent, direction; function startRule(event){ textIndent = false; direction = "inherit"; } //event handler for end of rules function endRule(event){ if (textIndent && direction != "ltr"){ reporter.report("Negative text-indent doesn't work well with RTL. If you use text-indent for image replacement explicitly set direction for that item to ltr.", textIndent.line, textIndent.col, rule); } } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); //check for use of "font-size" parser.addListener("property", function(event){ var name = event.property.toString().toLowerCase(), value = event.value; if (name == "text-indent" && value.parts[0].value < -99){ textIndent = event.property; } else if (name == "direction" && value == "ltr"){ direction = "ltr"; } }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); } }); /* * Rule: Don't use properties with a underscore prefix. * */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "underscore-property-hack", name: "Disallow properties with an underscore prefix", desc: "Checks for the underscore property hack (targets IE6)", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; //check if property name starts with "_" parser.addListener("property", function(event){ var property = event.property; if (property.hack == "_") { reporter.report("Property with underscore prefix found.", event.property.line, event.property.col, rule); } }); } }); /* * Rule: Headings (h1-h6) should be defined only once. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "unique-headings", name: "Headings should only be defined once", desc: "Headings should be defined only once.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; var headings = { h1: 0, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 }; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, pseudo, i, j; for (i=0; i < selectors.length; i++){ selector = selectors[i]; part = selector.parts[selector.parts.length-1]; if (part.elementName && /(h[1-6])/i.test(part.elementName.toString())){ for (j=0; j < part.modifiers.length; j++){ if (part.modifiers[j].type == "pseudo"){ pseudo = true; break; } } if (!pseudo){ headings[RegExp.$1]++; if (headings[RegExp.$1] > 1) { reporter.report("Heading (" + part.elementName + ") has already been defined.", part.line, part.col, rule); } } } } }); parser.addListener("endstylesheet", function(event){ var prop, messages = []; for (prop in headings){ if (headings.hasOwnProperty(prop)){ if (headings[prop] > 1){ messages.push(headings[prop] + " " + prop + "s"); } } } if (messages.length){ reporter.rollupWarn("You have " + messages.join(", ") + " defined in this stylesheet.", rule); } }); } }); /* * Rule: Don't use universal selector because it's slow. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "universal-selector", name: "Disallow universal selector", desc: "The universal selector (*) is known to be slow.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, modifier, i, j, k; for (i=0; i < selectors.length; i++){ selector = selectors[i]; part = selector.parts[selector.parts.length-1]; if (part.elementName == "*"){ reporter.report(rule.desc, part.line, part.col, rule); } } }); } }); /* * Rule: Don't use unqualified attribute selectors because they're just like universal selectors. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "unqualified-attributes", name: "Disallow unqualified attribute selectors", desc: "Unqualified attribute selectors are known to be slow.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; parser.addListener("startrule", function(event){ var selectors = event.selectors, selector, part, modifier, i, j, k; for (i=0; i < selectors.length; i++){ selector = selectors[i]; part = selector.parts[selector.parts.length-1]; if (part.type == parser.SELECTOR_PART_TYPE){ for (k=0; k < part.modifiers.length; k++){ modifier = part.modifiers[k]; if (modifier.type == "attribute" && (!part.elementName || part.elementName == "*")){ reporter.report(rule.desc, part.line, part.col, rule); } } } } }); } }); /* * Rule: When using a vendor-prefixed property, make sure to * include the standard one. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "vendor-prefix", name: "Require standard property with vendor prefix", desc: "When using a vendor-prefixed property, make sure to include the standard one.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this, properties, num, propertiesToCheck = { "-webkit-border-radius": "border-radius", "-webkit-border-top-left-radius": "border-top-left-radius", "-webkit-border-top-right-radius": "border-top-right-radius", "-webkit-border-bottom-left-radius": "border-bottom-left-radius", "-webkit-border-bottom-right-radius": "border-bottom-right-radius", "-o-border-radius": "border-radius", "-o-border-top-left-radius": "border-top-left-radius", "-o-border-top-right-radius": "border-top-right-radius", "-o-border-bottom-left-radius": "border-bottom-left-radius", "-o-border-bottom-right-radius": "border-bottom-right-radius", "-moz-border-radius": "border-radius", "-moz-border-radius-topleft": "border-top-left-radius", "-moz-border-radius-topright": "border-top-right-radius", "-moz-border-radius-bottomleft": "border-bottom-left-radius", "-moz-border-radius-bottomright": "border-bottom-right-radius", "-moz-column-count": "column-count", "-webkit-column-count": "column-count", "-moz-column-gap": "column-gap", "-webkit-column-gap": "column-gap", "-moz-column-rule": "column-rule", "-webkit-column-rule": "column-rule", "-moz-column-rule-style": "column-rule-style", "-webkit-column-rule-style": "column-rule-style", "-moz-column-rule-color": "column-rule-color", "-webkit-column-rule-color": "column-rule-color", "-moz-column-rule-width": "column-rule-width", "-webkit-column-rule-width": "column-rule-width", "-moz-column-width": "column-width", "-webkit-column-width": "column-width", "-webkit-column-span": "column-span", "-webkit-columns": "columns", "-moz-box-shadow": "box-shadow", "-webkit-box-shadow": "box-shadow", "-moz-transform" : "transform", "-webkit-transform" : "transform", "-o-transform" : "transform", "-ms-transform" : "transform", "-moz-transform-origin" : "transform-origin", "-webkit-transform-origin" : "transform-origin", "-o-transform-origin" : "transform-origin", "-ms-transform-origin" : "transform-origin", "-moz-box-sizing" : "box-sizing", "-webkit-box-sizing" : "box-sizing", "-moz-user-select" : "user-select", "-khtml-user-select" : "user-select", "-webkit-user-select" : "user-select" }; //event handler for beginning of rules function startRule(){ properties = {}; num=1; } //event handler for end of rules function endRule(event){ var prop, i, len, standard, needed, actual, needsStandard = []; for (prop in properties){ if (propertiesToCheck[prop]){ needsStandard.push({ actual: prop, needed: propertiesToCheck[prop]}); } } for (i=0, len=needsStandard.length; i < len; i++){ needed = needsStandard[i].needed; actual = needsStandard[i].actual; if (!properties[needed]){ reporter.report("Missing standard property '" + needed + "' to go along with '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule); } else { //make sure standard property is last if (properties[needed][0].pos < properties[actual][0].pos){ reporter.report("Standard property '" + needed + "' should come after vendor-prefixed property '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule); } } } } parser.addListener("startrule", startRule); parser.addListener("startfontface", startRule); parser.addListener("startpage", startRule); parser.addListener("startpagemargin", startRule); parser.addListener("startkeyframerule", startRule); parser.addListener("property", function(event){ var name = event.property.text.toLowerCase(); if (!properties[name]){ properties[name] = []; } properties[name].push({ name: event.property, value : event.value, pos:num++ }); }); parser.addListener("endrule", endRule); parser.addListener("endfontface", endRule); parser.addListener("endpage", endRule); parser.addListener("endpagemargin", endRule); parser.addListener("endkeyframerule", endRule); } }); /* * Rule: You don't need to specify units when a value is 0. */ /*global CSSLint*/ CSSLint.addRule({ //rule information id: "zero-units", name: "Disallow units for 0 values", desc: "You don't need to specify units when a value is 0.", browsers: "All", //initialization init: function(parser, reporter){ var rule = this; //count how many times "float" is used parser.addListener("property", function(event){ var parts = event.value.parts, i = 0, len = parts.length; while(i < len){ if ((parts[i].units || parts[i].type == "percentage") && parts[i].value === 0 && parts[i].type != "time"){ reporter.report("Values of 0 shouldn't have units specified.", parts[i].line, parts[i].col, rule); } i++; } }); } }); /*global CSSLint*/ (function() { /** * Replace special characters before write to output. * * Rules: * - single quotes is the escape sequence for double-quotes * - & is the escape sequence for & * - < is the escape sequence for < * - > is the escape sequence for > * * @param {String} message to escape * @return escaped message as {String} */ var xmlEscape = function(str) { if (!str || str.constructor !== String) { return ""; } return str.replace(/[\"&><]/g, function(match) { switch (match) { case "\"": return """; case "&": return "&"; case "<": return "<"; case ">": return ">"; } }); }; CSSLint.addFormatter({ //format information id: "checkstyle-xml", name: "Checkstyle XML format", /** * Return opening root XML tag. * @return {String} to prepend before all results */ startFormat: function(){ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><checkstyle>"; }, /** * Return closing root XML tag. * @return {String} to append after all results */ endFormat: function(){ return "</checkstyle>"; }, /** * Returns message when there is a file read error. * @param {String} filename The name of the file that caused the error. * @param {String} message The error message * @return {String} The error message. */ readError: function(filename, message) { return "<file name=\"" + xmlEscape(filename) + "\"><error line=\"0\" column=\"0\" severty=\"error\" message=\"" + xmlEscape(message) + "\"></error></file>"; }, /** * Given CSS Lint results for a file, return output for this format. * @param results {Object} with error and warning messages * @param filename {String} relative file path * @param options {Object} (UNUSED for now) specifies special handling of output * @return {String} output for results */ formatResults: function(results, filename, options) { var messages = results.messages, output = []; /** * Generate a source string for a rule. * Checkstyle source strings usually resemble Java class names e.g * net.csslint.SomeRuleName * @param {Object} rule * @return rule source as {String} */ var generateSource = function(rule) { if (!rule || !('name' in rule)) { return ""; } return 'net.csslint.' + rule.name.replace(/\s/g,''); }; if (messages.length > 0) { output.push("<file name=\""+filename+"\">"); CSSLint.Util.forEach(messages, function (message, i) { //ignore rollups for now if (!message.rollup) { output.push("<error line=\"" + message.line + "\" column=\"" + message.col + "\" severity=\"" + message.type + "\"" + " message=\"" + xmlEscape(message.message) + "\" source=\"" + generateSource(message.rule) +"\"/>"); } }); output.push("</file>"); } return output.join(""); } }); }()); /*global CSSLint*/ CSSLint.addFormatter({ //format information id: "compact", name: "Compact, 'porcelain' format", /** * Return content to be printed before all file results. * @return {String} to prepend before all results */ startFormat: function() { return ""; }, /** * Return content to be printed after all file results. * @return {String} to append after all results */ endFormat: function() { return ""; }, /** * Given CSS Lint results for a file, return output for this format. * @param results {Object} with error and warning messages * @param filename {String} relative file path * @param options {Object} (Optional) specifies special handling of output * @return {String} output for results */ formatResults: function(results, filename, options) { var messages = results.messages, output = ""; options = options || {}; /** * Capitalize and return given string. * @param str {String} to capitalize * @return {String} capitalized */ var capitalize = function(str) { return str.charAt(0).toUpperCase() + str.slice(1); }; if (messages.length === 0) { return options.quiet ? "" : filename + ": Lint Free!"; } CSSLint.Util.forEach(messages, function(message, i) { if (message.rollup) { output += filename + ": " + capitalize(message.type) + " - " + message.message + "\n"; } else { output += filename + ": " + "line " + message.line + ", col " + message.col + ", " + capitalize(message.type) + " - " + message.message + "\n"; } }); return output; } }); /*global CSSLint*/ CSSLint.addFormatter({ //format information id: "csslint-xml", name: "CSSLint XML format", /** * Return opening root XML tag. * @return {String} to prepend before all results */ startFormat: function(){ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><csslint>"; }, /** * Return closing root XML tag. * @return {String} to append after all results */ endFormat: function(){ return "</csslint>"; }, /** * Given CSS Lint results for a file, return output for this format. * @param results {Object} with error and warning messages * @param filename {String} relative file path * @param options {Object} (UNUSED for now) specifies special handling of output * @return {String} output for results */ formatResults: function(results, filename, options) { var messages = results.messages, output = []; /** * Replace special characters before write to output. * * Rules: * - single quotes is the escape sequence for double-quotes * - & is the escape sequence for & * - < is the escape sequence for < * - > is the escape sequence for > * * @param {String} message to escape * @return escaped message as {String} */ var escapeSpecialCharacters = function(str) { if (!str || str.constructor !== String) { return ""; } return str.replace(/\"/g, "'").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); }; if (messages.length > 0) { output.push("<file name=\""+filename+"\">"); CSSLint.Util.forEach(messages, function (message, i) { if (message.rollup) { output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>"); } else { output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" + " reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>"); } }); output.push("</file>"); } return output.join(""); } }); /*global CSSLint*/ CSSLint.addFormatter({ //format information id: "junit-xml", name: "JUNIT XML format", /** * Return opening root XML tag. * @return {String} to prepend before all results */ startFormat: function(){ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><testsuites>"; }, /** * Return closing root XML tag. * @return {String} to append after all results */ endFormat: function() { return "</testsuites>"; }, /** * Given CSS Lint results for a file, return output for this format. * @param results {Object} with error and warning messages * @param filename {String} relative file path * @param options {Object} (UNUSED for now) specifies special handling of output * @return {String} output for results */ formatResults: function(results, filename, options) { var messages = results.messages, output = [], tests = { 'error': 0, 'failure': 0 }; /** * Generate a source string for a rule. * JUNIT source strings usually resemble Java class names e.g * net.csslint.SomeRuleName * @param {Object} rule * @return rule source as {String} */ var generateSource = function(rule) { if (!rule || !('name' in rule)) { return ""; } return 'net.csslint.' + rule.name.replace(/\s/g,''); }; /** * Replace special characters before write to output. * * Rules: * - single quotes is the escape sequence for double-quotes * - < is the escape sequence for < * - > is the escape sequence for > * * @param {String} message to escape * @return escaped message as {String} */ var escapeSpecialCharacters = function(str) { if (!str || str.constructor !== String) { return ""; } return str.replace(/\"/g, "'").replace(/</g, "<").replace(/>/g, ">"); }; if (messages.length > 0) { messages.forEach(function (message, i) { // since junit has no warning class // all issues as errors var type = message.type === 'warning' ? 'error' : message.type; //ignore rollups for now if (!message.rollup) { // build the test case seperately, once joined // we'll add it to a custom array filtered by type output.push("<testcase time=\"0\" name=\"" + generateSource(message.rule) + "\">"); output.push("<" + type + " message=\"" + escapeSpecialCharacters(message.message) + "\"><![CDATA[" + message.line + ':' + message.col + ':' + escapeSpecialCharacters(message.evidence) + "]]></" + type + ">"); output.push("</testcase>"); tests[type] += 1; } }); output.unshift("<testsuite time=\"0\" tests=\"" + messages.length + "\" skipped=\"0\" errors=\"" + tests.error + "\" failures=\"" + tests.failure + "\" package=\"net.csslint\" name=\"" + filename + "\">"); output.push("</testsuite>"); } return output.join(""); } }); /*global CSSLint*/ CSSLint.addFormatter({ //format information id: "lint-xml", name: "Lint XML format", /** * Return opening root XML tag. * @return {String} to prepend before all results */ startFormat: function(){ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><lint>"; }, /** * Return closing root XML tag. * @return {String} to append after all results */ endFormat: function(){ return "</lint>"; }, /** * Given CSS Lint results for a file, return output for this format. * @param results {Object} with error and warning messages * @param filename {String} relative file path * @param options {Object} (UNUSED for now) specifies special handling of output * @return {String} output for results */ formatResults: function(results, filename, options) { var messages = results.messages, output = []; /** * Replace special characters before write to output. * * Rules: * - single quotes is the escape sequence for double-quotes * - & is the escape sequence for & * - < is the escape sequence for < * - > is the escape sequence for > * * @param {String} message to escape * @return escaped message as {String} */ var escapeSpecialCharacters = function(str) { if (!str || str.constructor !== String) { return ""; } return str.replace(/\"/g, "'").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); }; if (messages.length > 0) { output.push("<file name=\""+filename+"\">"); CSSLint.Util.forEach(messages, function (message, i) { if (message.rollup) { output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>"); } else { output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" + " reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>"); } }); output.push("</file>"); } return output.join(""); } }); /*global CSSLint*/ CSSLint.addFormatter({ //format information id: "text", name: "Plain Text", /** * Return content to be printed before all file results. * @return {String} to prepend before all results */ startFormat: function() { return ""; }, /** * Return content to be printed after all file results. * @return {String} to append after all results */ endFormat: function() { return ""; }, /** * Given CSS Lint results for a file, return output for this format. * @param results {Object} with error and warning messages * @param filename {String} relative file path * @param options {Object} (Optional) specifies special handling of output * @return {String} output for results */ formatResults: function(results, filename, options) { var messages = results.messages, output = ""; options = options || {}; if (messages.length === 0) { return options.quiet ? "" : "\n\ncsslint: No errors in " + filename + "."; } output = "\n\ncsslint: There are " + messages.length + " problems in " + filename + "."; var pos = filename.lastIndexOf("/"), shortFilename = filename; if (pos === -1){ pos = filename.lastIndexOf("\\"); } if (pos > -1){ shortFilename = filename.substring(pos+1); } CSSLint.Util.forEach(messages, function (message, i) { output = output + "\n\n" + shortFilename; if (message.rollup) { output += "\n" + (i+1) + ": " + message.type; output += "\n" + message.message; } else { output += "\n" + (i+1) + ": " + message.type + " at line " + message.line + ", col " + message.col; output += "\n" + message.message; output += "\n" + message.evidence; } }); return output; } }); exports.CSSLint = CSSLint; },{"parserlib":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/parserlib/lib/node-parserlib.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/custom-event/index.js":[function(require,module,exports){ (function (global){ var NativeCustomEvent = global.CustomEvent; function useNative () { try { var p = new NativeCustomEvent('cat', { detail: { foo: 'bar' } }); return 'cat' === p.type && 'bar' === p.detail.foo; } catch (e) { } return false; } /** * Cross-browser `CustomEvent` constructor. * * https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent.CustomEvent * * @public */ module.exports = useNative() ? NativeCustomEvent : // IE >= 9 'function' === typeof document.createEvent ? function CustomEvent (type, params) { var e = document.createEvent('CustomEvent'); if (params) { e.initCustomEvent(type, params.bubbles, params.cancelable, params.detail); } else { e.initCustomEvent(type, false, false, void 0); } return e; } : // IE <= 8 function CustomEvent (type, params) { var e = document.createEventObject(); e.type = type; if (params) { e.bubbles = Boolean(params.bubbles); e.cancelable = Boolean(params.cancelable); e.detail = params.detail; } else { e.bubbles = false; e.cancelable = false; e.detail = void 0; } return e; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/date-now/index.js":[function(require,module,exports){ module.exports = now function now() { return new Date().getTime() } },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/dropzone/dist/dropzone.js":[function(require,module,exports){ /* * * More info at [www.dropzonejs.com](http://www.dropzonejs.com) * * Copyright (c) 2012, Matias Meno * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ (function() { var Dropzone, Emitter, camelize, contentLoaded, detectVerticalSquash, drawImageIOSFix, noop, without, __slice = [].slice, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; noop = function() {}; Emitter = (function() { function Emitter() {} Emitter.prototype.addEventListener = Emitter.prototype.on; Emitter.prototype.on = function(event, fn) { this._callbacks = this._callbacks || {}; if (!this._callbacks[event]) { this._callbacks[event] = []; } this._callbacks[event].push(fn); return this; }; Emitter.prototype.emit = function() { var args, callback, callbacks, event, _i, _len; event = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; this._callbacks = this._callbacks || {}; callbacks = this._callbacks[event]; if (callbacks) { for (_i = 0, _len = callbacks.length; _i < _len; _i++) { callback = callbacks[_i]; callback.apply(this, args); } } return this; }; Emitter.prototype.removeListener = Emitter.prototype.off; Emitter.prototype.removeAllListeners = Emitter.prototype.off; Emitter.prototype.removeEventListener = Emitter.prototype.off; Emitter.prototype.off = function(event, fn) { var callback, callbacks, i, _i, _len; if (!this._callbacks || arguments.length === 0) { this._callbacks = {}; return this; } callbacks = this._callbacks[event]; if (!callbacks) { return this; } if (arguments.length === 1) { delete this._callbacks[event]; return this; } for (i = _i = 0, _len = callbacks.length; _i < _len; i = ++_i) { callback = callbacks[i]; if (callback === fn) { callbacks.splice(i, 1); break; } } return this; }; return Emitter; })(); Dropzone = (function(_super) { var extend, resolveOption; __extends(Dropzone, _super); Dropzone.prototype.Emitter = Emitter; /* This is a list of all available events you can register on a dropzone object. You can register an event handler like this: dropzone.on("dragEnter", function() { }); */ Dropzone.prototype.events = ["drop", "dragstart", "dragend", "dragenter", "dragover", "dragleave", "addedfile", "addedfiles", "removedfile", "thumbnail", "error", "errormultiple", "processing", "processingmultiple", "uploadprogress", "totaluploadprogress", "sending", "sendingmultiple", "success", "successmultiple", "canceled", "canceledmultiple", "complete", "completemultiple", "reset", "maxfilesexceeded", "maxfilesreached", "queuecomplete"]; Dropzone.prototype.defaultOptions = { url: null, method: "post", withCredentials: false, parallelUploads: 2, uploadMultiple: false, maxFilesize: 256, paramName: "file", createImageThumbnails: true, maxThumbnailFilesize: 10, thumbnailWidth: 120, thumbnailHeight: 120, filesizeBase: 1000, maxFiles: null, params: {}, clickable: true, ignoreHiddenFiles: true, acceptedFiles: null, acceptedMimeTypes: null, autoProcessQueue: true, autoQueue: true, addRemoveLinks: false, previewsContainer: null, hiddenInputContainer: "body", capture: null, renameFilename: null, dictDefaultMessage: "Drop files here to upload", dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.", dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.", dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.", dictInvalidFileType: "You can't upload files of this type.", dictResponseError: "Server responded with {{statusCode}} code.", dictCancelUpload: "Cancel upload", dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?", dictRemoveFile: "Remove file", dictRemoveFileConfirmation: null, dictMaxFilesExceeded: "You can not upload any more files.", accept: function(file, done) { return done(); }, init: function() { return noop; }, forceFallback: false, fallback: function() { var child, messageElement, span, _i, _len, _ref; this.element.className = "" + this.element.className + " dz-browser-not-supported"; _ref = this.element.getElementsByTagName("div"); for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; if (/(^| )dz-message($| )/.test(child.className)) { messageElement = child; child.className = "dz-message"; continue; } } if (!messageElement) { messageElement = Dropzone.createElement("<div class=\"dz-message\"><span></span></div>"); this.element.appendChild(messageElement); } span = messageElement.getElementsByTagName("span")[0]; if (span) { if (span.textContent != null) { span.textContent = this.options.dictFallbackMessage; } else if (span.innerText != null) { span.innerText = this.options.dictFallbackMessage; } } return this.element.appendChild(this.getFallbackForm()); }, resize: function(file) { var info, srcRatio, trgRatio; info = { srcX: 0, srcY: 0, srcWidth: file.width, srcHeight: file.height }; srcRatio = file.width / file.height; info.optWidth = this.options.thumbnailWidth; info.optHeight = this.options.thumbnailHeight; if ((info.optWidth == null) && (info.optHeight == null)) { info.optWidth = info.srcWidth; info.optHeight = info.srcHeight; } else if (info.optWidth == null) { info.optWidth = srcRatio * info.optHeight; } else if (info.optHeight == null) { info.optHeight = (1 / srcRatio) * info.optWidth; } trgRatio = info.optWidth / info.optHeight; if (file.height < info.optHeight || file.width < info.optWidth) { info.trgHeight = info.srcHeight; info.trgWidth = info.srcWidth; } else { if (srcRatio > trgRatio) { info.srcHeight = file.height; info.srcWidth = info.srcHeight * trgRatio; } else { info.srcWidth = file.width; info.srcHeight = info.srcWidth / trgRatio; } } info.srcX = (file.width - info.srcWidth) / 2; info.srcY = (file.height - info.srcHeight) / 2; return info; }, /* Those functions register themselves to the events on init and handle all the user interface specific stuff. Overwriting them won't break the upload but can break the way it's displayed. You can overwrite them if you don't like the default behavior. If you just want to add an additional event handler, register it on the dropzone object and don't overwrite those options. */ drop: function(e) { return this.element.classList.remove("dz-drag-hover"); }, dragstart: noop, dragend: function(e) { return this.element.classList.remove("dz-drag-hover"); }, dragenter: function(e) { return this.element.classList.add("dz-drag-hover"); }, dragover: function(e) { return this.element.classList.add("dz-drag-hover"); }, dragleave: function(e) { return this.element.classList.remove("dz-drag-hover"); }, paste: noop, reset: function() { return this.element.classList.remove("dz-started"); }, addedfile: function(file) { var node, removeFileEvent, removeLink, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _results; if (this.element === this.previewsContainer) { this.element.classList.add("dz-started"); } if (this.previewsContainer) { file.previewElement = Dropzone.createElement(this.options.previewTemplate.trim()); file.previewTemplate = file.previewElement; this.previewsContainer.appendChild(file.previewElement); _ref = file.previewElement.querySelectorAll("[data-dz-name]"); for (_i = 0, _len = _ref.length; _i < _len; _i++) { node = _ref[_i]; node.textContent = this._renameFilename(file.name); } _ref1 = file.previewElement.querySelectorAll("[data-dz-size]"); for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { node = _ref1[_j]; node.innerHTML = this.filesize(file.size); } if (this.options.addRemoveLinks) { file._removeLink = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\" data-dz-remove>" + this.options.dictRemoveFile + "</a>"); file.previewElement.appendChild(file._removeLink); } removeFileEvent = (function(_this) { return function(e) { e.preventDefault(); e.stopPropagation(); if (file.status === Dropzone.UPLOADING) { return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() { return _this.removeFile(file); }); } else { if (_this.options.dictRemoveFileConfirmation) { return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() { return _this.removeFile(file); }); } else { return _this.removeFile(file); } } }; })(this); _ref2 = file.previewElement.querySelectorAll("[data-dz-remove]"); _results = []; for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { removeLink = _ref2[_k]; _results.push(removeLink.addEventListener("click", removeFileEvent)); } return _results; } }, removedfile: function(file) { var _ref; if (file.previewElement) { if ((_ref = file.previewElement) != null) { _ref.parentNode.removeChild(file.previewElement); } } return this._updateMaxFilesReachedClass(); }, thumbnail: function(file, dataUrl) { var thumbnailElement, _i, _len, _ref; if (file.previewElement) { file.previewElement.classList.remove("dz-file-preview"); _ref = file.previewElement.querySelectorAll("[data-dz-thumbnail]"); for (_i = 0, _len = _ref.length; _i < _len; _i++) { thumbnailElement = _ref[_i]; thumbnailElement.alt = file.name; thumbnailElement.src = dataUrl; } return setTimeout(((function(_this) { return function() { return file.previewElement.classList.add("dz-image-preview"); }; })(this)), 1); } }, error: function(file, message) { var node, _i, _len, _ref, _results; if (file.previewElement) { file.previewElement.classList.add("dz-error"); if (typeof message !== "String" && message.error) { message = message.error; } _ref = file.previewElement.querySelectorAll("[data-dz-errormessage]"); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { node = _ref[_i]; _results.push(node.textContent = message); } return _results; } }, errormultiple: noop, processing: function(file) { if (file.previewElement) { file.previewElement.classList.add("dz-processing"); if (file._removeLink) { return file._removeLink.textContent = this.options.dictCancelUpload; } } }, processingmultiple: noop, uploadprogress: function(file, progress, bytesSent) { var node, _i, _len, _ref, _results; if (file.previewElement) { _ref = file.previewElement.querySelectorAll("[data-dz-uploadprogress]"); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { node = _ref[_i]; if (node.nodeName === 'PROGRESS') { _results.push(node.value = progress); } else { _results.push(node.style.width = "" + progress + "%"); } } return _results; } }, totaluploadprogress: noop, sending: noop, sendingmultiple: noop, success: function(file) { if (file.previewElement) { return file.previewElement.classList.add("dz-success"); } }, successmultiple: noop, canceled: function(file) { return this.emit("error", file, "Upload canceled."); }, canceledmultiple: noop, complete: function(file) { if (file._removeLink) { file._removeLink.textContent = this.options.dictRemoveFile; } if (file.previewElement) { return file.previewElement.classList.add("dz-complete"); } }, completemultiple: noop, maxfilesexceeded: noop, maxfilesreached: noop, queuecomplete: noop, addedfiles: noop, previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n <div class=\"dz-image\"><img data-dz-thumbnail /></div>\n <div class=\"dz-details\">\n <div class=\"dz-size\"><span data-dz-size></span></div>\n <div class=\"dz-filename\"><span data-dz-name></span></div>\n </div>\n <div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress></span></div>\n <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n <div class=\"dz-success-mark\">\n <svg width=\"54px\" height=\"54px\" viewBox=\"0 0 54 54\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:sketch=\"http://www.bohemiancoding.com/sketch/ns\">\n <title>Check</title>\n <defs></defs>\n <g id=\"Page-1\" stroke=\"none\" stroke-width=\"1\" fill=\"none\" fill-rule=\"evenodd\" sketch:type=\"MSPage\">\n <path d=\"M23.5,31.8431458 L17.5852419,25.9283877 C16.0248253,24.3679711 13.4910294,24.366835 11.9289322,25.9289322 C10.3700136,27.4878508 10.3665912,30.0234455 11.9283877,31.5852419 L20.4147581,40.0716123 C20.5133999,40.1702541 20.6159315,40.2626649 20.7218615,40.3488435 C22.2835669,41.8725651 24.794234,41.8626202 26.3461564,40.3106978 L43.3106978,23.3461564 C44.8771021,21.7797521 44.8758057,19.2483887 43.3137085,17.6862915 C41.7547899,16.1273729 39.2176035,16.1255422 37.6538436,17.6893022 L23.5,31.8431458 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z\" id=\"Oval-2\" stroke-opacity=\"0.198794158\" stroke=\"#747474\" fill-opacity=\"0.816519475\" fill=\"#FFFFFF\" sketch:type=\"MSShapeGroup\"></path>\n </g>\n </svg>\n </div>\n <div class=\"dz-error-mark\">\n <svg width=\"54px\" height=\"54px\" viewBox=\"0 0 54 54\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:sketch=\"http://www.bohemiancoding.com/sketch/ns\">\n <title>Error</title>\n <defs></defs>\n <g id=\"Page-1\" stroke=\"none\" stroke-width=\"1\" fill=\"none\" fill-rule=\"evenodd\" sketch:type=\"MSPage\">\n <g id=\"Check-+-Oval-2\" sketch:type=\"MSLayerGroup\" stroke=\"#747474\" stroke-opacity=\"0.198794158\" fill=\"#FFFFFF\" fill-opacity=\"0.816519475\">\n <path d=\"M32.6568542,29 L38.3106978,23.3461564 C39.8771021,21.7797521 39.8758057,19.2483887 38.3137085,17.6862915 C36.7547899,16.1273729 34.2176035,16.1255422 32.6538436,17.6893022 L27,23.3431458 L21.3461564,17.6893022 C19.7823965,16.1255422 17.2452101,16.1273729 15.6862915,17.6862915 C14.1241943,19.2483887 14.1228979,21.7797521 15.6893022,23.3461564 L21.3431458,29 L15.6893022,34.6538436 C14.1228979,36.2202479 14.1241943,38.7516113 15.6862915,40.3137085 C17.2452101,41.8726271 19.7823965,41.8744578 21.3461564,40.3106978 L27,34.6568542 L32.6538436,40.3106978 C34.2176035,41.8744578 36.7547899,41.8726271 38.3137085,40.3137085 C39.8758057,38.7516113 39.8771021,36.2202479 38.3106978,34.6538436 L32.6568542,29 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z\" id=\"Oval-2\" sketch:type=\"MSShapeGroup\"></path>\n </g>\n </g>\n </svg>\n </div>\n</div>" }; extend = function() { var key, object, objects, target, val, _i, _len; target = arguments[0], objects = 2 <= arguments.length ? __slice.call(arguments, 1) : []; for (_i = 0, _len = objects.length; _i < _len; _i++) { object = objects[_i]; for (key in object) { val = object[key]; target[key] = val; } } return target; }; function Dropzone(element, options) { var elementOptions, fallback, _ref; this.element = element; this.version = Dropzone.version; this.defaultOptions.previewTemplate = this.defaultOptions.previewTemplate.replace(/\n*/g, ""); this.clickableElements = []; this.listeners = []; this.files = []; if (typeof this.element === "string") { this.element = document.querySelector(this.element); } if (!(this.element && (this.element.nodeType != null))) { throw new Error("Invalid dropzone element."); } if (this.element.dropzone) { throw new Error("Dropzone already attached."); } Dropzone.instances.push(this); this.element.dropzone = this; elementOptions = (_ref = Dropzone.optionsForElement(this.element)) != null ? _ref : {}; this.options = extend({}, this.defaultOptions, elementOptions, options != null ? options : {}); if (this.options.forceFallback || !Dropzone.isBrowserSupported()) { return this.options.fallback.call(this); } if (this.options.url == null) { this.options.url = this.element.getAttribute("action"); } if (!this.options.url) { throw new Error("No URL provided."); } if (this.options.acceptedFiles && this.options.acceptedMimeTypes) { throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."); } if (this.options.acceptedMimeTypes) { this.options.acceptedFiles = this.options.acceptedMimeTypes; delete this.options.acceptedMimeTypes; } this.options.method = this.options.method.toUpperCase(); if ((fallback = this.getExistingFallback()) && fallback.parentNode) { fallback.parentNode.removeChild(fallback); } if (this.options.previewsContainer !== false) { if (this.options.previewsContainer) { this.previewsContainer = Dropzone.getElement(this.options.previewsContainer, "previewsContainer"); } else { this.previewsContainer = this.element; } } if (this.options.clickable) { if (this.options.clickable === true) { this.clickableElements = [this.element]; } else { this.clickableElements = Dropzone.getElements(this.options.clickable, "clickable"); } } this.init(); } Dropzone.prototype.getAcceptedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.accepted) { _results.push(file); } } return _results; }; Dropzone.prototype.getRejectedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (!file.accepted) { _results.push(file); } } return _results; }; Dropzone.prototype.getFilesWithStatus = function(status) { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status === status) { _results.push(file); } } return _results; }; Dropzone.prototype.getQueuedFiles = function() { return this.getFilesWithStatus(Dropzone.QUEUED); }; Dropzone.prototype.getUploadingFiles = function() { return this.getFilesWithStatus(Dropzone.UPLOADING); }; Dropzone.prototype.getAddedFiles = function() { return this.getFilesWithStatus(Dropzone.ADDED); }; Dropzone.prototype.getActiveFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status === Dropzone.UPLOADING || file.status === Dropzone.QUEUED) { _results.push(file); } } return _results; }; Dropzone.prototype.init = function() { var eventName, noPropagation, setupHiddenFileInput, _i, _len, _ref, _ref1; if (this.element.tagName === "form") { this.element.setAttribute("enctype", "multipart/form-data"); } if (this.element.classList.contains("dropzone") && !this.element.querySelector(".dz-message")) { this.element.appendChild(Dropzone.createElement("<div class=\"dz-default dz-message\"><span>" + this.options.dictDefaultMessage + "</span></div>")); } if (this.clickableElements.length) { setupHiddenFileInput = (function(_this) { return function() { if (_this.hiddenFileInput) { _this.hiddenFileInput.parentNode.removeChild(_this.hiddenFileInput); } _this.hiddenFileInput = document.createElement("input"); _this.hiddenFileInput.setAttribute("type", "file"); if ((_this.options.maxFiles == null) || _this.options.maxFiles > 1) { _this.hiddenFileInput.setAttribute("multiple", "multiple"); } _this.hiddenFileInput.className = "dz-hidden-input"; if (_this.options.acceptedFiles != null) { _this.hiddenFileInput.setAttribute("accept", _this.options.acceptedFiles); } if (_this.options.capture != null) { _this.hiddenFileInput.setAttribute("capture", _this.options.capture); } _this.hiddenFileInput.style.visibility = "hidden"; _this.hiddenFileInput.style.position = "absolute"; _this.hiddenFileInput.style.top = "0"; _this.hiddenFileInput.style.left = "0"; _this.hiddenFileInput.style.height = "0"; _this.hiddenFileInput.style.width = "0"; document.querySelector(_this.options.hiddenInputContainer).appendChild(_this.hiddenFileInput); return _this.hiddenFileInput.addEventListener("change", function() { var file, files, _i, _len; files = _this.hiddenFileInput.files; if (files.length) { for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; _this.addFile(file); } } _this.emit("addedfiles", files); return setupHiddenFileInput(); }); }; })(this); setupHiddenFileInput(); } this.URL = (_ref = window.URL) != null ? _ref : window.webkitURL; _ref1 = this.events; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { eventName = _ref1[_i]; this.on(eventName, this.options[eventName]); } this.on("uploadprogress", (function(_this) { return function() { return _this.updateTotalUploadProgress(); }; })(this)); this.on("removedfile", (function(_this) { return function() { return _this.updateTotalUploadProgress(); }; })(this)); this.on("canceled", (function(_this) { return function(file) { return _this.emit("complete", file); }; })(this)); this.on("complete", (function(_this) { return function(file) { if (_this.getAddedFiles().length === 0 && _this.getUploadingFiles().length === 0 && _this.getQueuedFiles().length === 0) { return setTimeout((function() { return _this.emit("queuecomplete"); }), 0); } }; })(this)); noPropagation = function(e) { e.stopPropagation(); if (e.preventDefault) { return e.preventDefault(); } else { return e.returnValue = false; } }; this.listeners = [ { element: this.element, events: { "dragstart": (function(_this) { return function(e) { return _this.emit("dragstart", e); }; })(this), "dragenter": (function(_this) { return function(e) { noPropagation(e); return _this.emit("dragenter", e); }; })(this), "dragover": (function(_this) { return function(e) { var efct; try { efct = e.dataTransfer.effectAllowed; } catch (_error) {} e.dataTransfer.dropEffect = 'move' === efct || 'linkMove' === efct ? 'move' : 'copy'; noPropagation(e); return _this.emit("dragover", e); }; })(this), "dragleave": (function(_this) { return function(e) { return _this.emit("dragleave", e); }; })(this), "drop": (function(_this) { return function(e) { noPropagation(e); return _this.drop(e); }; })(this), "dragend": (function(_this) { return function(e) { return _this.emit("dragend", e); }; })(this) } } ]; this.clickableElements.forEach((function(_this) { return function(clickableElement) { return _this.listeners.push({ element: clickableElement, events: { "click": function(evt) { if ((clickableElement !== _this.element) || (evt.target === _this.element || Dropzone.elementInside(evt.target, _this.element.querySelector(".dz-message")))) { _this.hiddenFileInput.click(); } return true; } } }); }; })(this)); this.enable(); return this.options.init.call(this); }; Dropzone.prototype.destroy = function() { var _ref; this.disable(); this.removeAllFiles(true); if ((_ref = this.hiddenFileInput) != null ? _ref.parentNode : void 0) { this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput); this.hiddenFileInput = null; } delete this.element.dropzone; return Dropzone.instances.splice(Dropzone.instances.indexOf(this), 1); }; Dropzone.prototype.updateTotalUploadProgress = function() { var activeFiles, file, totalBytes, totalBytesSent, totalUploadProgress, _i, _len, _ref; totalBytesSent = 0; totalBytes = 0; activeFiles = this.getActiveFiles(); if (activeFiles.length) { _ref = this.getActiveFiles(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; totalBytesSent += file.upload.bytesSent; totalBytes += file.upload.total; } totalUploadProgress = 100 * totalBytesSent / totalBytes; } else { totalUploadProgress = 100; } return this.emit("totaluploadprogress", totalUploadProgress, totalBytes, totalBytesSent); }; Dropzone.prototype._getParamName = function(n) { if (typeof this.options.paramName === "function") { return this.options.paramName(n); } else { return "" + this.options.paramName + (this.options.uploadMultiple ? "[" + n + "]" : ""); } }; Dropzone.prototype._renameFilename = function(name) { if (typeof this.options.renameFilename !== "function") { return name; } return this.options.renameFilename(name); }; Dropzone.prototype.getFallbackForm = function() { var existingFallback, fields, fieldsString, form; if (existingFallback = this.getExistingFallback()) { return existingFallback; } fieldsString = "<div class=\"dz-fallback\">"; if (this.options.dictFallbackText) { fieldsString += "<p>" + this.options.dictFallbackText + "</p>"; } fieldsString += "<input type=\"file\" name=\"" + (this._getParamName(0)) + "\" " + (this.options.uploadMultiple ? 'multiple="multiple"' : void 0) + " /><input type=\"submit\" value=\"Upload!\"></div>"; fields = Dropzone.createElement(fieldsString); if (this.element.tagName !== "FORM") { form = Dropzone.createElement("<form action=\"" + this.options.url + "\" enctype=\"multipart/form-data\" method=\"" + this.options.method + "\"></form>"); form.appendChild(fields); } else { this.element.setAttribute("enctype", "multipart/form-data"); this.element.setAttribute("method", this.options.method); } return form != null ? form : fields; }; Dropzone.prototype.getExistingFallback = function() { var fallback, getFallback, tagName, _i, _len, _ref; getFallback = function(elements) { var el, _i, _len; for (_i = 0, _len = elements.length; _i < _len; _i++) { el = elements[_i]; if (/(^| )fallback($| )/.test(el.className)) { return el; } } }; _ref = ["div", "form"]; for (_i = 0, _len = _ref.length; _i < _len; _i++) { tagName = _ref[_i]; if (fallback = getFallback(this.element.getElementsByTagName(tagName))) { return fallback; } } }; Dropzone.prototype.setupEventListeners = function() { var elementListeners, event, listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { elementListeners = _ref[_i]; _results.push((function() { var _ref1, _results1; _ref1 = elementListeners.events; _results1 = []; for (event in _ref1) { listener = _ref1[event]; _results1.push(elementListeners.element.addEventListener(event, listener, false)); } return _results1; })()); } return _results; }; Dropzone.prototype.removeEventListeners = function() { var elementListeners, event, listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { elementListeners = _ref[_i]; _results.push((function() { var _ref1, _results1; _ref1 = elementListeners.events; _results1 = []; for (event in _ref1) { listener = _ref1[event]; _results1.push(elementListeners.element.removeEventListener(event, listener, false)); } return _results1; })()); } return _results; }; Dropzone.prototype.disable = function() { var file, _i, _len, _ref, _results; this.clickableElements.forEach(function(element) { return element.classList.remove("dz-clickable"); }); this.removeEventListeners(); _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; _results.push(this.cancelUpload(file)); } return _results; }; Dropzone.prototype.enable = function() { this.clickableElements.forEach(function(element) { return element.classList.add("dz-clickable"); }); return this.setupEventListeners(); }; Dropzone.prototype.filesize = function(size) { var cutoff, i, selectedSize, selectedUnit, unit, units, _i, _len; selectedSize = 0; selectedUnit = "b"; if (size > 0) { units = ['TB', 'GB', 'MB', 'KB', 'b']; for (i = _i = 0, _len = units.length; _i < _len; i = ++_i) { unit = units[i]; cutoff = Math.pow(this.options.filesizeBase, 4 - i) / 10; if (size >= cutoff) { selectedSize = size / Math.pow(this.options.filesizeBase, 4 - i); selectedUnit = unit; break; } } selectedSize = Math.round(10 * selectedSize) / 10; } return "<strong>" + selectedSize + "</strong> " + selectedUnit; }; Dropzone.prototype._updateMaxFilesReachedClass = function() { if ((this.options.maxFiles != null) && this.getAcceptedFiles().length >= this.options.maxFiles) { if (this.getAcceptedFiles().length === this.options.maxFiles) { this.emit('maxfilesreached', this.files); } return this.element.classList.add("dz-max-files-reached"); } else { return this.element.classList.remove("dz-max-files-reached"); } }; Dropzone.prototype.drop = function(e) { var files, items; if (!e.dataTransfer) { return; } this.emit("drop", e); files = e.dataTransfer.files; this.emit("addedfiles", files); if (files.length) { items = e.dataTransfer.items; if (items && items.length && (items[0].webkitGetAsEntry != null)) { this._addFilesFromItems(items); } else { this.handleFiles(files); } } }; Dropzone.prototype.paste = function(e) { var items, _ref; if ((e != null ? (_ref = e.clipboardData) != null ? _ref.items : void 0 : void 0) == null) { return; } this.emit("paste", e); items = e.clipboardData.items; if (items.length) { return this._addFilesFromItems(items); } }; Dropzone.prototype.handleFiles = function(files) { var file, _i, _len, _results; _results = []; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; _results.push(this.addFile(file)); } return _results; }; Dropzone.prototype._addFilesFromItems = function(items) { var entry, item, _i, _len, _results; _results = []; for (_i = 0, _len = items.length; _i < _len; _i++) { item = items[_i]; if ((item.webkitGetAsEntry != null) && (entry = item.webkitGetAsEntry())) { if (entry.isFile) { _results.push(this.addFile(item.getAsFile())); } else if (entry.isDirectory) { _results.push(this._addFilesFromDirectory(entry, entry.name)); } else { _results.push(void 0); } } else if (item.getAsFile != null) { if ((item.kind == null) || item.kind === "file") { _results.push(this.addFile(item.getAsFile())); } else { _results.push(void 0); } } else { _results.push(void 0); } } return _results; }; Dropzone.prototype._addFilesFromDirectory = function(directory, path) { var dirReader, errorHandler, readEntries; dirReader = directory.createReader(); errorHandler = function(error) { return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log(error) : void 0 : void 0; }; readEntries = (function(_this) { return function() { return dirReader.readEntries(function(entries) { var entry, _i, _len; if (entries.length > 0) { for (_i = 0, _len = entries.length; _i < _len; _i++) { entry = entries[_i]; if (entry.isFile) { entry.file(function(file) { if (_this.options.ignoreHiddenFiles && file.name.substring(0, 1) === '.') { return; } file.fullPath = "" + path + "/" + file.name; return _this.addFile(file); }); } else if (entry.isDirectory) { _this._addFilesFromDirectory(entry, "" + path + "/" + entry.name); } } readEntries(); } return null; }, errorHandler); }; })(this); return readEntries(); }; Dropzone.prototype.accept = function(file, done) { if (file.size > this.options.maxFilesize * 1024 * 1024) { return done(this.options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", this.options.maxFilesize)); } else if (!Dropzone.isValidFile(file, this.options.acceptedFiles)) { return done(this.options.dictInvalidFileType); } else if ((this.options.maxFiles != null) && this.getAcceptedFiles().length >= this.options.maxFiles) { done(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}", this.options.maxFiles)); return this.emit("maxfilesexceeded", file); } else { return this.options.accept.call(this, file, done); } }; Dropzone.prototype.addFile = function(file) { file.upload = { progress: 0, total: file.size, bytesSent: 0 }; this.files.push(file); file.status = Dropzone.ADDED; this.emit("addedfile", file); this._enqueueThumbnail(file); return this.accept(file, (function(_this) { return function(error) { if (error) { file.accepted = false; _this._errorProcessing([file], error); } else { file.accepted = true; if (_this.options.autoQueue) { _this.enqueueFile(file); } } return _this._updateMaxFilesReachedClass(); }; })(this)); }; Dropzone.prototype.enqueueFiles = function(files) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; this.enqueueFile(file); } return null; }; Dropzone.prototype.enqueueFile = function(file) { if (file.status === Dropzone.ADDED && file.accepted === true) { file.status = Dropzone.QUEUED; if (this.options.autoProcessQueue) { return setTimeout(((function(_this) { return function() { return _this.processQueue(); }; })(this)), 0); } } else { throw new Error("This file can't be queued because it has already been processed or was rejected."); } }; Dropzone.prototype._thumbnailQueue = []; Dropzone.prototype._processingThumbnail = false; Dropzone.prototype._enqueueThumbnail = function(file) { if (this.options.createImageThumbnails && file.type.match(/image.*/) && file.size <= this.options.maxThumbnailFilesize * 1024 * 1024) { this._thumbnailQueue.push(file); return setTimeout(((function(_this) { return function() { return _this._processThumbnailQueue(); }; })(this)), 0); } }; Dropzone.prototype._processThumbnailQueue = function() { if (this._processingThumbnail || this._thumbnailQueue.length === 0) { return; } this._processingThumbnail = true; return this.createThumbnail(this._thumbnailQueue.shift(), (function(_this) { return function() { _this._processingThumbnail = false; return _this._processThumbnailQueue(); }; })(this)); }; Dropzone.prototype.removeFile = function(file) { if (file.status === Dropzone.UPLOADING) { this.cancelUpload(file); } this.files = without(this.files, file); this.emit("removedfile", file); if (this.files.length === 0) { return this.emit("reset"); } }; Dropzone.prototype.removeAllFiles = function(cancelIfNecessary) { var file, _i, _len, _ref; if (cancelIfNecessary == null) { cancelIfNecessary = false; } _ref = this.files.slice(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status !== Dropzone.UPLOADING || cancelIfNecessary) { this.removeFile(file); } } return null; }; Dropzone.prototype.createThumbnail = function(file, callback) { var fileReader; fileReader = new FileReader; fileReader.onload = (function(_this) { return function() { if (file.type === "image/svg+xml") { _this.emit("thumbnail", file, fileReader.result); if (callback != null) { callback(); } return; } return _this.createThumbnailFromUrl(file, fileReader.result, callback); }; })(this); return fileReader.readAsDataURL(file); }; Dropzone.prototype.createThumbnailFromUrl = function(file, imageUrl, callback, crossOrigin) { var img; img = document.createElement("img"); if (crossOrigin) { img.crossOrigin = crossOrigin; } img.onload = (function(_this) { return function() { var canvas, ctx, resizeInfo, thumbnail, _ref, _ref1, _ref2, _ref3; file.width = img.width; file.height = img.height; resizeInfo = _this.options.resize.call(_this, file); if (resizeInfo.trgWidth == null) { resizeInfo.trgWidth = resizeInfo.optWidth; } if (resizeInfo.trgHeight == null) { resizeInfo.trgHeight = resizeInfo.optHeight; } canvas = document.createElement("canvas"); ctx = canvas.getContext("2d"); canvas.width = resizeInfo.trgWidth; canvas.height = resizeInfo.trgHeight; drawImageIOSFix(ctx, img, (_ref = resizeInfo.srcX) != null ? _ref : 0, (_ref1 = resizeInfo.srcY) != null ? _ref1 : 0, resizeInfo.srcWidth, resizeInfo.srcHeight, (_ref2 = resizeInfo.trgX) != null ? _ref2 : 0, (_ref3 = resizeInfo.trgY) != null ? _ref3 : 0, resizeInfo.trgWidth, resizeInfo.trgHeight); thumbnail = canvas.toDataURL("image/png"); _this.emit("thumbnail", file, thumbnail); if (callback != null) { return callback(); } }; })(this); if (callback != null) { img.onerror = callback; } return img.src = imageUrl; }; Dropzone.prototype.processQueue = function() { var i, parallelUploads, processingLength, queuedFiles; parallelUploads = this.options.parallelUploads; processingLength = this.getUploadingFiles().length; i = processingLength; if (processingLength >= parallelUploads) { return; } queuedFiles = this.getQueuedFiles(); if (!(queuedFiles.length > 0)) { return; } if (this.options.uploadMultiple) { return this.processFiles(queuedFiles.slice(0, parallelUploads - processingLength)); } else { while (i < parallelUploads) { if (!queuedFiles.length) { return; } this.processFile(queuedFiles.shift()); i++; } } }; Dropzone.prototype.processFile = function(file) { return this.processFiles([file]); }; Dropzone.prototype.processFiles = function(files) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.processing = true; file.status = Dropzone.UPLOADING; this.emit("processing", file); } if (this.options.uploadMultiple) { this.emit("processingmultiple", files); } return this.uploadFiles(files); }; Dropzone.prototype._getFilesWithXhr = function(xhr) { var file, files; return files = (function() { var _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.xhr === xhr) { _results.push(file); } } return _results; }).call(this); }; Dropzone.prototype.cancelUpload = function(file) { var groupedFile, groupedFiles, _i, _j, _len, _len1, _ref; if (file.status === Dropzone.UPLOADING) { groupedFiles = this._getFilesWithXhr(file.xhr); for (_i = 0, _len = groupedFiles.length; _i < _len; _i++) { groupedFile = groupedFiles[_i]; groupedFile.status = Dropzone.CANCELED; } file.xhr.abort(); for (_j = 0, _len1 = groupedFiles.length; _j < _len1; _j++) { groupedFile = groupedFiles[_j]; this.emit("canceled", groupedFile); } if (this.options.uploadMultiple) { this.emit("canceledmultiple", groupedFiles); } } else if ((_ref = file.status) === Dropzone.ADDED || _ref === Dropzone.QUEUED) { file.status = Dropzone.CANCELED; this.emit("canceled", file); if (this.options.uploadMultiple) { this.emit("canceledmultiple", [file]); } } if (this.options.autoProcessQueue) { return this.processQueue(); } }; resolveOption = function() { var args, option; option = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; if (typeof option === 'function') { return option.apply(this, args); } return option; }; Dropzone.prototype.uploadFile = function(file) { return this.uploadFiles([file]); }; Dropzone.prototype.uploadFiles = function(files) { var file, formData, handleError, headerName, headerValue, headers, i, input, inputName, inputType, key, method, option, progressObj, response, updateProgress, url, value, xhr, _i, _j, _k, _l, _len, _len1, _len2, _len3, _m, _ref, _ref1, _ref2, _ref3, _ref4, _ref5; xhr = new XMLHttpRequest(); for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.xhr = xhr; } method = resolveOption(this.options.method, files); url = resolveOption(this.options.url, files); xhr.open(method, url, true); xhr.withCredentials = !!this.options.withCredentials; response = null; handleError = (function(_this) { return function() { var _j, _len1, _results; _results = []; for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; _results.push(_this._errorProcessing(files, response || _this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr)); } return _results; }; })(this); updateProgress = (function(_this) { return function(e) { var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results; if (e != null) { progress = 100 * e.loaded / e.total; for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; file.upload = { progress: progress, total: e.total, bytesSent: e.loaded }; } } else { allFilesFinished = true; progress = 100; for (_k = 0, _len2 = files.length; _k < _len2; _k++) { file = files[_k]; if (!(file.upload.progress === 100 && file.upload.bytesSent === file.upload.total)) { allFilesFinished = false; } file.upload.progress = progress; file.upload.bytesSent = file.upload.total; } if (allFilesFinished) { return; } } _results = []; for (_l = 0, _len3 = files.length; _l < _len3; _l++) { file = files[_l]; _results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent)); } return _results; }; })(this); xhr.onload = (function(_this) { return function(e) { var _ref; if (files[0].status === Dropzone.CANCELED) { return; } if (xhr.readyState !== 4) { return; } response = xhr.responseText; if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) { try { response = JSON.parse(response); } catch (_error) { e = _error; response = "Invalid JSON response from server."; } } updateProgress(); if (!((200 <= (_ref = xhr.status) && _ref < 300))) { return handleError(); } else { return _this._finished(files, response, e); } }; })(this); xhr.onerror = (function(_this) { return function() { if (files[0].status === Dropzone.CANCELED) { return; } return handleError(); }; })(this); progressObj = (_ref = xhr.upload) != null ? _ref : xhr; progressObj.onprogress = updateProgress; headers = { "Accept": "application/json", "Cache-Control": "no-cache", "X-Requested-With": "XMLHttpRequest" }; if (this.options.headers) { extend(headers, this.options.headers); } for (headerName in headers) { headerValue = headers[headerName]; if (headerValue) { xhr.setRequestHeader(headerName, headerValue); } } formData = new FormData(); if (this.options.params) { _ref1 = this.options.params; for (key in _ref1) { value = _ref1[key]; formData.append(key, value); } } for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; this.emit("sending", file, xhr, formData); } if (this.options.uploadMultiple) { this.emit("sendingmultiple", files, xhr, formData); } if (this.element.tagName === "FORM") { _ref2 = this.element.querySelectorAll("input, textarea, select, button"); for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { input = _ref2[_k]; inputName = input.getAttribute("name"); inputType = input.getAttribute("type"); if (input.tagName === "SELECT" && input.hasAttribute("multiple")) { _ref3 = input.options; for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) { option = _ref3[_l]; if (option.selected) { formData.append(inputName, option.value); } } } else if (!inputType || ((_ref4 = inputType.toLowerCase()) !== "checkbox" && _ref4 !== "radio") || input.checked) { formData.append(inputName, input.value); } } } for (i = _m = 0, _ref5 = files.length - 1; 0 <= _ref5 ? _m <= _ref5 : _m >= _ref5; i = 0 <= _ref5 ? ++_m : --_m) { formData.append(this._getParamName(i), files[i], this._renameFilename(files[i].name)); } return this.submitRequest(xhr, formData, files); }; Dropzone.prototype.submitRequest = function(xhr, formData, files) { return xhr.send(formData); }; Dropzone.prototype._finished = function(files, responseText, e) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.status = Dropzone.SUCCESS; this.emit("success", file, responseText, e); this.emit("complete", file); } if (this.options.uploadMultiple) { this.emit("successmultiple", files, responseText, e); this.emit("completemultiple", files); } if (this.options.autoProcessQueue) { return this.processQueue(); } }; Dropzone.prototype._errorProcessing = function(files, message, xhr) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.status = Dropzone.ERROR; this.emit("error", file, message, xhr); this.emit("complete", file); } if (this.options.uploadMultiple) { this.emit("errormultiple", files, message, xhr); this.emit("completemultiple", files); } if (this.options.autoProcessQueue) { return this.processQueue(); } }; return Dropzone; })(Emitter); Dropzone.version = "4.3.0"; Dropzone.options = {}; Dropzone.optionsForElement = function(element) { if (element.getAttribute("id")) { return Dropzone.options[camelize(element.getAttribute("id"))]; } else { return void 0; } }; Dropzone.instances = []; Dropzone.forElement = function(element) { if (typeof element === "string") { element = document.querySelector(element); } if ((element != null ? element.dropzone : void 0) == null) { throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone."); } return element.dropzone; }; Dropzone.autoDiscover = true; Dropzone.discover = function() { var checkElements, dropzone, dropzones, _i, _len, _results; if (document.querySelectorAll) { dropzones = document.querySelectorAll(".dropzone"); } else { dropzones = []; checkElements = function(elements) { var el, _i, _len, _results; _results = []; for (_i = 0, _len = elements.length; _i < _len; _i++) { el = elements[_i]; if (/(^| )dropzone($| )/.test(el.className)) { _results.push(dropzones.push(el)); } else { _results.push(void 0); } } return _results; }; checkElements(document.getElementsByTagName("div")); checkElements(document.getElementsByTagName("form")); } _results = []; for (_i = 0, _len = dropzones.length; _i < _len; _i++) { dropzone = dropzones[_i]; if (Dropzone.optionsForElement(dropzone) !== false) { _results.push(new Dropzone(dropzone)); } else { _results.push(void 0); } } return _results; }; Dropzone.blacklistedBrowsers = [/opera.*Macintosh.*version\/12/i]; Dropzone.isBrowserSupported = function() { var capableBrowser, regex, _i, _len, _ref; capableBrowser = true; if (window.File && window.FileReader && window.FileList && window.Blob && window.FormData && document.querySelector) { if (!("classList" in document.createElement("a"))) { capableBrowser = false; } else { _ref = Dropzone.blacklistedBrowsers; for (_i = 0, _len = _ref.length; _i < _len; _i++) { regex = _ref[_i]; if (regex.test(navigator.userAgent)) { capableBrowser = false; continue; } } } } else { capableBrowser = false; } return capableBrowser; }; without = function(list, rejectedItem) { var item, _i, _len, _results; _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) { item = list[_i]; if (item !== rejectedItem) { _results.push(item); } } return _results; }; camelize = function(str) { return str.replace(/[\-_](\w)/g, function(match) { return match.charAt(1).toUpperCase(); }); }; Dropzone.createElement = function(string) { var div; div = document.createElement("div"); div.innerHTML = string; return div.childNodes[0]; }; Dropzone.elementInside = function(element, container) { if (element === container) { return true; } while (element = element.parentNode) { if (element === container) { return true; } } return false; }; Dropzone.getElement = function(el, name) { var element; if (typeof el === "string") { element = document.querySelector(el); } else if (el.nodeType != null) { element = el; } if (element == null) { throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector or a plain HTML element."); } return element; }; Dropzone.getElements = function(els, name) { var e, el, elements, _i, _j, _len, _len1, _ref; if (els instanceof Array) { elements = []; try { for (_i = 0, _len = els.length; _i < _len; _i++) { el = els[_i]; elements.push(this.getElement(el, name)); } } catch (_error) { e = _error; elements = null; } } else if (typeof els === "string") { elements = []; _ref = document.querySelectorAll(els); for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { el = _ref[_j]; elements.push(el); } } else if (els.nodeType != null) { elements = [els]; } if (!((elements != null) && elements.length)) { throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector, a plain HTML element or a list of those."); } return elements; }; Dropzone.confirm = function(question, accepted, rejected) { if (window.confirm(question)) { return accepted(); } else if (rejected != null) { return rejected(); } }; Dropzone.isValidFile = function(file, acceptedFiles) { var baseMimeType, mimeType, validType, _i, _len; if (!acceptedFiles) { return true; } acceptedFiles = acceptedFiles.split(","); mimeType = file.type; baseMimeType = mimeType.replace(/\/.*$/, ""); for (_i = 0, _len = acceptedFiles.length; _i < _len; _i++) { validType = acceptedFiles[_i]; validType = validType.trim(); if (validType.charAt(0) === ".") { if (file.name.toLowerCase().indexOf(validType.toLowerCase(), file.name.length - validType.length) !== -1) { return true; } } else if (/\/\*$/.test(validType)) { if (baseMimeType === validType.replace(/\/.*$/, "")) { return true; } } else { if (mimeType === validType) { return true; } } } return false; }; if (typeof jQuery !== "undefined" && jQuery !== null) { jQuery.fn.dropzone = function(options) { return this.each(function() { return new Dropzone(this, options); }); }; } if (typeof module !== "undefined" && module !== null) { module.exports = Dropzone; } else { window.Dropzone = Dropzone; } Dropzone.ADDED = "added"; Dropzone.QUEUED = "queued"; Dropzone.ACCEPTED = Dropzone.QUEUED; Dropzone.UPLOADING = "uploading"; Dropzone.PROCESSING = Dropzone.UPLOADING; Dropzone.CANCELED = "canceled"; Dropzone.ERROR = "error"; Dropzone.SUCCESS = "success"; /* Bugfix for iOS 6 and 7 Source: http://stackoverflow.com/questions/11929099/html5-canvas-drawimage-ratio-bug-ios based on the work of https://github.com/stomita/ios-imagefile-megapixel */ detectVerticalSquash = function(img) { var alpha, canvas, ctx, data, ey, ih, iw, py, ratio, sy; iw = img.naturalWidth; ih = img.naturalHeight; canvas = document.createElement("canvas"); canvas.width = 1; canvas.height = ih; ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); data = ctx.getImageData(0, 0, 1, ih).data; sy = 0; ey = ih; py = ih; while (py > sy) { alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } ratio = py / ih; if (ratio === 0) { return 1; } else { return ratio; } }; drawImageIOSFix = function(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) { var vertSquashRatio; vertSquashRatio = detectVerticalSquash(img); return ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio); }; /* * contentloaded.js * * Author: Diego Perini (diego.perini at gmail.com) * Summary: cross-browser wrapper for DOMContentLoaded * Updated: 20101020 * License: MIT * Version: 1.2 * * URL: * http://javascript.nwbox.com/ContentLoaded/ * http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE */ contentLoaded = function(win, fn) { var add, doc, done, init, poll, pre, rem, root, top; done = false; top = true; doc = win.document; root = doc.documentElement; add = (doc.addEventListener ? "addEventListener" : "attachEvent"); rem = (doc.addEventListener ? "removeEventListener" : "detachEvent"); pre = (doc.addEventListener ? "" : "on"); init = function(e) { if (e.type === "readystatechange" && doc.readyState !== "complete") { return; } (e.type === "load" ? win : doc)[rem](pre + e.type, init, false); if (!done && (done = true)) { return fn.call(win, e.type || e); } }; poll = function() { var e; try { root.doScroll("left"); } catch (_error) { e = _error; setTimeout(poll, 50); return; } return init("poll"); }; if (doc.readyState !== "complete") { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch (_error) {} if (top) { poll(); } } doc[add](pre + "DOMContentLoaded", init, false); doc[add](pre + "readystatechange", init, false); return win[add](pre + "load", init, false); } }; Dropzone._autoDiscoverFunction = function() { if (Dropzone.autoDiscover) { return Dropzone.discover(); } }; contentLoaded(window, Dropzone._autoDiscoverFunction); }).call(this); },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/ember-browserify/node_modules/buffer/index.js":[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') var isArray = require('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() /* * Export kMaxLength after typed array support is determined. */ exports.kMaxLength = kMaxLength() function typedArraySupport () { try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } function createBuffer (that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length) } that.length = length } return that } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } Buffer.poolSize = 8192 // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype return arr } function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true }) } } function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (that, size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) } function allocUnsafe (that, size) { assertSize(size) that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0 } } return that } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 that = createBuffer(that, length) var actual = that.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual) } return that } function fromArrayLike (that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array) } else if (length === undefined) { array = new Uint8Array(array, byteOffset) } else { array = new Uint8Array(array, byteOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array) } return that } function fromObject (that, obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 that = createBuffer(that, len) if (that.length === 0) { return that } obj.copy(that, 0, 0, len) return that } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '<Buffer ' + str + '>' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end) newBuf.__proto__ = Buffer.prototype } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start] } } return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (val.length === 1) { var code = val.charCodeAt(0) if (code < 256) { val = code } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"base64-js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/base64-js/index.js","ieee754":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/ieee754/index.js","isarray":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/ember-browserify/node_modules/isarray/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/ember-browserify/node_modules/isarray/index.js":[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/events/events.js":[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/fuse.js/src/fuse.js":[function(require,module,exports){ /** * @license * Fuse - Lightweight fuzzy-search * * Copyright (c) 2012-2016 Kirollos Risk <kirollos@gmail.com>. * All Rights Reserved. Apache Software License 2.0 * * 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. */ ;(function (global) { 'use strict' /** @type {function(...*)} */ function log () { console.log.apply(console, arguments) } var defaultOptions = { // The name of the identifier property. If specified, the returned result will be a list // of the items' dentifiers, otherwise it will be a list of the items. id: null, // Indicates whether comparisons should be case sensitive. caseSensitive: false, // An array of values that should be included from the searcher's output. When this array // contains elements, each result in the list will be of the form `{ item: ..., include1: ..., include2: ... }`. // Values you can include are `score`, `matchedLocations` include: [], // Whether to sort the result list, by score shouldSort: true, // The search function to use // Note that the default search function ([[Function]]) must conform to the following API: // // @param pattern The pattern string to search // @param options The search option // [[Function]].constructor = function(pattern, options) // // @param text: the string to search in for the pattern // @return Object in the form of: // - isMatch: boolean // - score: Int // [[Function]].prototype.search = function(text) searchFn: BitapSearcher, // Default sort function sortFn: function (a, b) { return a.score - b.score }, // The get function to use when fetching an object's properties. // The default will search nested paths *ie foo.bar.baz* getFn: deepValue, // List of properties that will be searched. This also supports nested properties. keys: [], // Will print to the console. Useful for debugging. verbose: false, // When true, the search algorithm will search individual words **and** the full string, // computing the final score as a function of both. Note that when `tokenize` is `true`, // the `threshold`, `distance`, and `location` are inconsequential for individual tokens. tokenize: false, // When true, the result set will only include records that match all tokens. Will only work // if `tokenize` is also true. matchAllTokens: false, // Regex used to separate words when searching. Only applicable when `tokenize` is `true`. tokenSeparator: / +/g, // Minimum number of characters that must be matched before a result is considered a match minMatchCharLength: 1, // When true, the algorithm continues searching to the end of the input even if a perfect // match is found before the end of the same input. findAllMatches: false } /** * @constructor * @param {!Array} list * @param {!Object<string, *>} options */ function Fuse (list, options) { var key this.list = list this.options = options = options || {} for (key in defaultOptions) { if (!defaultOptions.hasOwnProperty(key)) { continue; } // Add boolean type options if (typeof defaultOptions[key] === 'boolean') { this.options[key] = key in options ? options[key] : defaultOptions[key]; // Add all other options } else { this.options[key] = options[key] || defaultOptions[key] } } } Fuse.VERSION = '2.7.3' /** * Sets a new list for Fuse to match against. * @param {!Array} list * @return {!Array} The newly set list * @public */ Fuse.prototype.set = function (list) { this.list = list return list } Fuse.prototype.search = function (pattern) { if (this.options.verbose) log('\nSearch term:', pattern, '\n') this.pattern = pattern this.results = [] this.resultMap = {} this._keyMap = null this._prepareSearchers() this._startSearch() this._computeScore() this._sort() var output = this._format() return output } Fuse.prototype._prepareSearchers = function () { var options = this.options var pattern = this.pattern var searchFn = options.searchFn var tokens = pattern.split(options.tokenSeparator) var i = 0 var len = tokens.length if (this.options.tokenize) { this.tokenSearchers = [] for (; i < len; i++) { this.tokenSearchers.push(new searchFn(tokens[i], options)) } } this.fullSeacher = new searchFn(pattern, options) } Fuse.prototype._startSearch = function () { var options = this.options var getFn = options.getFn var list = this.list var listLen = list.length var keys = this.options.keys var keysLen = keys.length var key var weight var item = null var i var j // Check the first item in the list, if it's a string, then we assume // that every item in the list is also a string, and thus it's a flattened array. if (typeof list[0] === 'string') { // Iterate over every item for (i = 0; i < listLen; i++) { this._analyze('', list[i], i, i) } } else { this._keyMap = {} // Otherwise, the first item is an Object (hopefully), and thus the searching // is done on the values of the keys of each item. // Iterate over every item for (i = 0; i < listLen; i++) { item = list[i] // Iterate over every key for (j = 0; j < keysLen; j++) { key = keys[j] if (typeof key !== 'string') { weight = (1 - key.weight) || 1 this._keyMap[key.name] = { weight: weight } if (key.weight <= 0 || key.weight > 1) { throw new Error('Key weight has to be > 0 and <= 1') } key = key.name } else { this._keyMap[key] = { weight: 1 } } this._analyze(key, getFn(item, key, []), item, i) } } } } Fuse.prototype._analyze = function (key, text, entity, index) { var options = this.options var words var scores var exists = false var existingResult var averageScore var finalScore var scoresLen var mainSearchResult var tokenSearcher var termScores var word var tokenSearchResult var hasMatchInText var checkTextMatches var i var j // Check if the text can be searched if (text === undefined || text === null) { return } scores = [] var numTextMatches = 0 if (typeof text === 'string') { words = text.split(options.tokenSeparator) if (options.verbose) log('---------\nKey:', key) if (this.options.tokenize) { for (i = 0; i < this.tokenSearchers.length; i++) { tokenSearcher = this.tokenSearchers[i] if (options.verbose) log('Pattern:', tokenSearcher.pattern) termScores = [] hasMatchInText = false for (j = 0; j < words.length; j++) { word = words[j] tokenSearchResult = tokenSearcher.search(word) var obj = {} if (tokenSearchResult.isMatch) { obj[word] = tokenSearchResult.score exists = true hasMatchInText = true scores.push(tokenSearchResult.score) } else { obj[word] = 1 if (!this.options.matchAllTokens) { scores.push(1) } } termScores.push(obj) } if (hasMatchInText) { numTextMatches++ } if (options.verbose) log('Token scores:', termScores) } averageScore = scores[0] scoresLen = scores.length for (i = 1; i < scoresLen; i++) { averageScore += scores[i] } averageScore = averageScore / scoresLen if (options.verbose) log('Token score average:', averageScore) } mainSearchResult = this.fullSeacher.search(text) if (options.verbose) log('Full text score:', mainSearchResult.score) finalScore = mainSearchResult.score if (averageScore !== undefined) { finalScore = (finalScore + averageScore) / 2 } if (options.verbose) log('Score average:', finalScore) checkTextMatches = (this.options.tokenize && this.options.matchAllTokens) ? numTextMatches >= this.tokenSearchers.length : true if (options.verbose) log('Check Matches', checkTextMatches) // If a match is found, add the item to <rawResults>, including its score if ((exists || mainSearchResult.isMatch) && checkTextMatches) { // Check if the item already exists in our results existingResult = this.resultMap[index] if (existingResult) { // Use the lowest score // existingResult.score, bitapResult.score existingResult.output.push({ key: key, score: finalScore, matchedIndices: mainSearchResult.matchedIndices }) } else { // Add it to the raw result list this.resultMap[index] = { item: entity, output: [{ key: key, score: finalScore, matchedIndices: mainSearchResult.matchedIndices }] } this.results.push(this.resultMap[index]) } } } else if (isArray(text)) { for (i = 0; i < text.length; i++) { this._analyze(key, text[i], entity, index) } } } Fuse.prototype._computeScore = function () { var i var j var keyMap = this._keyMap var totalScore var output var scoreLen var score var weight var results = this.results var bestScore var nScore if (this.options.verbose) log('\n\nComputing score:\n') for (i = 0; i < results.length; i++) { totalScore = 0 output = results[i].output scoreLen = output.length bestScore = 1 for (j = 0; j < scoreLen; j++) { score = output[j].score weight = keyMap ? keyMap[output[j].key].weight : 1 nScore = score * weight if (weight !== 1) { bestScore = Math.min(bestScore, nScore) } else { totalScore += nScore output[j].nScore = nScore } } if (bestScore === 1) { results[i].score = totalScore / scoreLen } else { results[i].score = bestScore } if (this.options.verbose) log(results[i]) } } Fuse.prototype._sort = function () { var options = this.options if (options.shouldSort) { if (options.verbose) log('\n\nSorting....') this.results.sort(options.sortFn) } } Fuse.prototype._format = function () { var options = this.options var getFn = options.getFn var finalOutput = [] var i var len var results = this.results var replaceValue var getItemAtIndex var include = options.include if (options.verbose) log('\n\nOutput:\n\n', results) // Helper function, here for speed-up, which replaces the item with its value, // if the options specifies it, replaceValue = options.id ? function (index) { results[index].item = getFn(results[index].item, options.id, [])[0] } : function () {} getItemAtIndex = function (index) { var record = results[index] var data var j var output var _item var _result // If `include` has values, put the item in the result if (include.length > 0) { data = { item: record.item } if (include.indexOf('matches') !== -1) { output = record.output data.matches = [] for (j = 0; j < output.length; j++) { _item = output[j] _result = { indices: _item.matchedIndices } if (_item.key) { _result.key = _item.key } data.matches.push(_result) } } if (include.indexOf('score') !== -1) { data.score = results[index].score } } else { data = record.item } return data } // From the results, push into a new array only the item identifier (if specified) // of the entire item. This is because we don't want to return the <results>, // since it contains other metadata for (i = 0, len = results.length; i < len; i++) { replaceValue(i) finalOutput.push(getItemAtIndex(i)) } return finalOutput } // Helpers function deepValue (obj, path, list) { var firstSegment var remaining var dotIndex var value var i var len if (!path) { // If there's no path left, we've gotten to the object we care about. list.push(obj) } else { dotIndex = path.indexOf('.') if (dotIndex !== -1) { firstSegment = path.slice(0, dotIndex) remaining = path.slice(dotIndex + 1) } else { firstSegment = path } value = obj[firstSegment] if (value !== null && value !== undefined) { if (!remaining && (typeof value === 'string' || typeof value === 'number')) { list.push(value) } else if (isArray(value)) { // Search each item in the array. for (i = 0, len = value.length; i < len; i++) { deepValue(value[i], remaining, list) } } else if (remaining) { // An object. Recurse further. deepValue(value, remaining, list) } } } return list } function isArray (obj) { return Object.prototype.toString.call(obj) === '[object Array]' } /** * Adapted from "Diff, Match and Patch", by Google * * http://code.google.com/p/google-diff-match-patch/ * * Modified by: Kirollos Risk <kirollos@gmail.com> * ----------------------------------------------- * Details: the algorithm and structure was modified to allow the creation of * <Searcher> instances with a <search> method which does the actual * bitap search. The <pattern> (the string that is searched for) is only defined * once per instance and thus it eliminates redundant re-creation when searching * over a list of strings. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * * @constructor */ function BitapSearcher (pattern, options) { options = options || {} this.options = options this.options.location = options.location || BitapSearcher.defaultOptions.location this.options.distance = 'distance' in options ? options.distance : BitapSearcher.defaultOptions.distance this.options.threshold = 'threshold' in options ? options.threshold : BitapSearcher.defaultOptions.threshold this.options.maxPatternLength = options.maxPatternLength || BitapSearcher.defaultOptions.maxPatternLength this.pattern = options.caseSensitive ? pattern : pattern.toLowerCase() this.patternLen = pattern.length if (this.patternLen <= this.options.maxPatternLength) { this.matchmask = 1 << (this.patternLen - 1) this.patternAlphabet = this._calculatePatternAlphabet() } } BitapSearcher.defaultOptions = { // Approximately where in the text is the pattern expected to be found? location: 0, // Determines how close the match must be to the fuzzy location (specified above). // An exact letter match which is 'distance' characters away from the fuzzy location // would score as a complete mismatch. A distance of '0' requires the match be at // the exact location specified, a threshold of '1000' would require a perfect match // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold. distance: 100, // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match // (of both letters and location), a threshold of '1.0' would match anything. threshold: 0.6, // Machine word size maxPatternLength: 32 } /** * Initialize the alphabet for the Bitap algorithm. * @return {Object} Hash of character locations. * @private */ BitapSearcher.prototype._calculatePatternAlphabet = function () { var mask = {}, i = 0 for (i = 0; i < this.patternLen; i++) { mask[this.pattern.charAt(i)] = 0 } for (i = 0; i < this.patternLen; i++) { mask[this.pattern.charAt(i)] |= 1 << (this.pattern.length - i - 1) } return mask } /** * Compute and return the score for a match with `e` errors and `x` location. * @param {number} errors Number of errors in match. * @param {number} location Location of match. * @return {number} Overall score for match (0.0 = good, 1.0 = bad). * @private */ BitapSearcher.prototype._bitapScore = function (errors, location) { var accuracy = errors / this.patternLen, proximity = Math.abs(this.options.location - location) if (!this.options.distance) { // Dodge divide by zero error. return proximity ? 1.0 : accuracy } return accuracy + (proximity / this.options.distance) } /** * Compute and return the result of the search * @param {string} text The text to search in * @return {{isMatch: boolean, score: number}} Literal containing: * isMatch - Whether the text is a match or not * score - Overall score for the match * @public */ BitapSearcher.prototype.search = function (text) { var options = this.options var i var j var textLen var findAllMatches var location var threshold var bestLoc var binMin var binMid var binMax var start, finish var bitArr var lastBitArr var charMatch var score var locations var matches var isMatched var matchMask var matchedIndices var matchesLen var match text = options.caseSensitive ? text : text.toLowerCase() if (this.pattern === text) { // Exact match return { isMatch: true, score: 0, matchedIndices: [[0, text.length - 1]] } } // When pattern length is greater than the machine word length, just do a a regex comparison if (this.patternLen > options.maxPatternLength) { matches = text.match(new RegExp(this.pattern.replace(options.tokenSeparator, '|'))) isMatched = !!matches if (isMatched) { matchedIndices = [] for (i = 0, matchesLen = matches.length; i < matchesLen; i++) { match = matches[i] matchedIndices.push([text.indexOf(match), match.length - 1]) } } return { isMatch: isMatched, // TODO: revisit this score score: isMatched ? 0.5 : 1, matchedIndices: matchedIndices } } findAllMatches = options.findAllMatches location = options.location // Set starting location at beginning text and initialize the alphabet. textLen = text.length // Highest score beyond which we give up. threshold = options.threshold // Is there a nearby exact match? (speedup) bestLoc = text.indexOf(this.pattern, location) // a mask of the matches matchMask = [] for (i = 0; i < textLen; i++) { matchMask[i] = 0 } if (bestLoc != -1) { threshold = Math.min(this._bitapScore(0, bestLoc), threshold) // What about in the other direction? (speed up) bestLoc = text.lastIndexOf(this.pattern, location + this.patternLen) if (bestLoc != -1) { threshold = Math.min(this._bitapScore(0, bestLoc), threshold) } } bestLoc = -1 score = 1 locations = [] binMax = this.patternLen + textLen for (i = 0; i < this.patternLen; i++) { // Scan for the best match; each iteration allows for one more error. // Run a binary search to determine how far from the match location we can stray // at this error level. binMin = 0 binMid = binMax while (binMin < binMid) { if (this._bitapScore(i, location + binMid) <= threshold) { binMin = binMid } else { binMax = binMid } binMid = Math.floor((binMax - binMin) / 2 + binMin) } // Use the result from this iteration as the maximum for the next. binMax = binMid start = Math.max(1, location - binMid + 1) if (findAllMatches) { finish = textLen; } else { finish = Math.min(location + binMid, textLen) + this.patternLen } // Initialize the bit array bitArr = Array(finish + 2) bitArr[finish + 1] = (1 << i) - 1 for (j = finish; j >= start; j--) { charMatch = this.patternAlphabet[text.charAt(j - 1)] if (charMatch) { matchMask[j - 1] = 1 } bitArr[j] = ((bitArr[j + 1] << 1) | 1) & charMatch if (i !== 0) { // Subsequent passes: fuzzy match. bitArr[j] |= (((lastBitArr[j + 1] | lastBitArr[j]) << 1) | 1) | lastBitArr[j + 1] } if (bitArr[j] & this.matchmask) { score = this._bitapScore(i, j - 1) // This match will almost certainly be better than any existing match. // But check anyway. if (score <= threshold) { // Indeed it is threshold = score bestLoc = j - 1 locations.push(bestLoc) // Already passed loc, downhill from here on in. if (bestLoc <= location) { break } // When passing loc, don't exceed our current distance from loc. start = Math.max(1, 2 * location - bestLoc) } } } // No hope for a (better) match at greater error levels. if (this._bitapScore(i + 1, location) > threshold) { break } lastBitArr = bitArr } matchedIndices = this._getMatchedIndices(matchMask) // Count exact matches (those with a score of 0) to be "almost" exact return { isMatch: bestLoc >= 0, score: score === 0 ? 0.001 : score, matchedIndices: matchedIndices } } BitapSearcher.prototype._getMatchedIndices = function (matchMask) { var matchedIndices = [] var start = -1 var end = -1 var i = 0 var match var len = matchMask.length for (; i < len; i++) { match = matchMask[i] if (match && start === -1) { start = i } else if (!match && start !== -1) { end = i - 1 if ((end - start) + 1 >= this.options.minMatchCharLength) { matchedIndices.push([start, end]) } start = -1 } } if (matchMask[i - 1]) { if ((i-1 - start) + 1 >= this.options.minMatchCharLength) { matchedIndices.push([start, i - 1]) } } return matchedIndices } // Export to Common JS Loader if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = Fuse } else if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(function () { return Fuse }) } else { // Browser globals (root is window) global.Fuse = Fuse } })(this); },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/htmlhint/index.js":[function(require,module,exports){ module.exports = require('./lib/htmlhint'); },{"./lib/htmlhint":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/htmlhint/lib/htmlhint.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/htmlhint/lib/htmlhint.js":[function(require,module,exports){ /*! * HTMLHint v0.9.13 * https://github.com/yaniswang/HTMLHint * * (c) 2014-2016 Yanis Wang <yanis.wang@gmail.com>. * MIT Licensed */ var HTMLHint=function(e){function t(e,t){return Array(e+1).join(t||" ")}var a={};return a.version="0.9.13",a.release="20160501",a.rules={},a.defaultRuleset={"tagname-lowercase":!0,"attr-lowercase":!0,"attr-value-double-quotes":!0,"doctype-first":!0,"tag-pair":!0,"spec-char-escape":!0,"id-unique":!0,"src-not-empty":!0,"attr-no-duplication":!0,"title-require":!0},a.addRule=function(e){a.rules[e.id]=e},a.verify=function(t,n){(n===e||0===Object.keys(n).length)&&(n=a.defaultRuleset),t=t.replace(/^\s*<!--\s*htmlhint\s+([^\r\n]+?)\s*-->/i,function(t,a){return n===e&&(n={}),a.replace(/(?:^|,)\s*([^:,]+)\s*(?:\:\s*([^,\s]+))?/g,function(t,a,r){"false"===r?r=!1:"true"===r&&(r=!0),n[a]=r===e?!0:r}),""});var r,i=new HTMLParser,s=new a.Reporter(t,n),o=a.rules;for(var l in n)r=o[l],r!==e&&n[l]!==!1&&r.init(i,s,n[l]);return i.parse(t),s.messages},a.format=function(e,a){a=a||{};var n=[],r={white:"",grey:"",red:"",reset:""};a.colors&&(r.white="[37m",r.grey="[90m",r.red="[31m",r.reset="[39m");var i=a.indent||0;return e.forEach(function(e){var a=40,s=a+20,o=e.evidence,l=e.line,u=e.col,d=o.length,c=u>a+1?u-a:1,f=o.length>u+s?u+s:d;a+1>u&&(f+=a-u+1),o=o.replace(/\t/g," ").substring(c-1,f),c>1&&(o="..."+o,c-=3),d>f&&(o+="..."),n.push(r.white+t(i)+"L"+l+" |"+r.grey+o+r.reset);var g=u-c,h=o.substring(0,g).match(/[^\u0000-\u00ff]/g);null!==h&&(g+=h.length),n.push(r.white+t(i)+t((l+"").length+3+g)+"^ "+r.red+e.message+" ("+e.rule.id+")"+r.reset)}),n},a}();"object"==typeof exports&&exports&&(exports.HTMLHint=HTMLHint),function(e){var t=function(){var e=this;e._init.apply(e,arguments)};t.prototype={_init:function(e,t){var a=this;a.html=e,a.lines=e.split(/\r?\n/);var n=e.match(/\r?\n/);a.brLen=null!==n?n[0].length:0,a.ruleset=t,a.messages=[]},error:function(e,t,a,n,r){this.report("error",e,t,a,n,r)},warn:function(e,t,a,n,r){this.report("warning",e,t,a,n,r)},info:function(e,t,a,n,r){this.report("info",e,t,a,n,r)},report:function(e,t,a,n,r,i){for(var s,o,l=this,u=l.lines,d=l.brLen,c=a-1,f=u.length;f>c&&(s=u[c],o=s.length,n>o&&f>a);c++)a++,n-=o,1!==n&&(n-=d);l.messages.push({type:e,message:t,raw:i,evidence:s,line:a,col:n,rule:{id:r.id,description:r.description,link:"https://github.com/yaniswang/HTMLHint/wiki/"+r.id}})}},e.Reporter=t}(HTMLHint);var HTMLParser=function(e){var t=function(){var e=this;e._init.apply(e,arguments)};return t.prototype={_init:function(){var e=this;e._listeners={},e._mapCdataTags=e.makeMap("script,style"),e._arrBlocks=[],e.lastEvent=null},makeMap:function(e){for(var t={},a=e.split(","),n=0;a.length>n;n++)t[a[n]]=!0;return t},parse:function(t){function a(t,a,n,r){var i=n-b+1;r===e&&(r={}),r.raw=a,r.pos=n,r.line=w,r.col=i,L.push(r),c.fire(t,r);for(var s;s=m.exec(a);)w++,b=n+m.lastIndex}var n,r,i,s,o,l,u,d,c=this,f=c._mapCdataTags,g=/<(?:\/([^\s>]+)\s*|!--([\s\S]*?)--|!([^>]*?)|([\w\-:]+)((?:\s+[^\s"'>\/=\x00-\x0F\x7F\x80-\x9F]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]*))?)*?)\s*(\/?))>/g,h=/\s*([^\s"'>\/=\x00-\x0F\x7F\x80-\x9F]+)(?:\s*=\s*(?:(")([^"]*)"|(')([^']*)'|([^\s"'>]*)))?/g,m=/\r?\n/g,p=0,v=0,b=0,w=1,L=c._arrBlocks;for(c.fire("start",{pos:0,line:1,col:1});n=g.exec(t);)if(r=n.index,r>p&&(d=t.substring(p,r),o?u.push(d):a("text",d,p)),p=g.lastIndex,!(i=n[1])||(o&&i===o&&(d=u.join(""),a("cdata",d,v,{tagName:o,attrs:l}),o=null,l=null,u=null),o))if(o)u.push(n[0]);else if(i=n[4]){s=[];for(var y,T=n[5],H=0;y=h.exec(T);){var x=y[1],M=y[2]?y[2]:y[4]?y[4]:"",N=y[3]?y[3]:y[5]?y[5]:y[6]?y[6]:"";s.push({name:x,value:N,quote:M,index:y.index,raw:y[0]}),H+=y[0].length}H===T.length?(a("tagstart",n[0],r,{tagName:i,attrs:s,close:n[6]}),f[i]&&(o=i,l=s.concat(),u=[],v=p)):a("text",n[0],r)}else(n[2]||n[3])&&a("comment",n[0],r,{content:n[2]||n[3],"long":n[2]?!0:!1});else a("tagend",n[0],r,{tagName:i});t.length>p&&(d=t.substring(p,t.length),a("text",d,p)),c.fire("end",{pos:p,line:w,col:t.length-b+1})},addListener:function(t,a){for(var n,r=this._listeners,i=t.split(/[,\s]/),s=0,o=i.length;o>s;s++)n=i[s],r[n]===e&&(r[n]=[]),r[n].push(a)},fire:function(t,a){a===e&&(a={}),a.type=t;var n=this,r=[],i=n._listeners[t],s=n._listeners.all;i!==e&&(r=r.concat(i)),s!==e&&(r=r.concat(s));var o=n.lastEvent;null!==o&&(delete o.lastEvent,a.lastEvent=o),n.lastEvent=a;for(var l=0,u=r.length;u>l;l++)r[l].call(n,a)},removeListener:function(t,a){var n=this._listeners[t];if(n!==e)for(var r=0,i=n.length;i>r;r++)if(n[r]===a){n.splice(r,1);break}},fixPos:function(e,t){var a,n=e.raw.substr(0,t),r=n.split(/\r?\n/),i=r.length-1,s=e.line;return i>0?(s+=i,a=r[i].length+1):a=e.col+t,{line:s,col:a}},getMapAttrs:function(e){for(var t,a={},n=0,r=e.length;r>n;n++)t=e[n],a[t.name]=t.value;return a}},t}();"object"==typeof exports&&exports&&(exports.HTMLParser=HTMLParser),HTMLHint.addRule({id:"alt-require",description:"The alt attribute of an <img> element must be present and alt attribute of area[href] and input[type=image] must have a value.",init:function(e,t){var a=this;e.addListener("tagstart",function(n){var r,i=n.tagName.toLowerCase(),s=e.getMapAttrs(n.attrs),o=n.col+i.length+1;"img"!==i||"alt"in s?("area"===i&&"href"in s||"input"===i&&"image"===s.type)&&("alt"in s&&""!==s.alt||(r="area"===i?"area[href]":"input[type=image]",t.warn("The alt attribute of "+r+" must have a value.",n.line,o,a,n.raw))):t.warn("An alt attribute must be present on <img> elements.",n.line,o,a,n.raw)})}}),HTMLHint.addRule({id:"attr-lowercase",description:"All attribute names must be in lowercase.",init:function(e,t,a){var n=this,r=Array.isArray(a)?a:[];e.addListener("tagstart",function(e){for(var a,i=e.attrs,s=e.col+e.tagName.length+1,o=0,l=i.length;l>o;o++){a=i[o];var u=a.name;-1===r.indexOf(u)&&u!==u.toLowerCase()&&t.error("The attribute name of [ "+u+" ] must be in lowercase.",e.line,s+a.index,n,a.raw)}})}}),HTMLHint.addRule({id:"attr-no-duplication",description:"Elements cannot have duplicate attributes.",init:function(e,t){var a=this;e.addListener("tagstart",function(e){for(var n,r,i=e.attrs,s=e.col+e.tagName.length+1,o={},l=0,u=i.length;u>l;l++)n=i[l],r=n.name,o[r]===!0&&t.error("Duplicate of attribute name [ "+n.name+" ] was found.",e.line,s+n.index,a,n.raw),o[r]=!0})}}),HTMLHint.addRule({id:"attr-unsafe-chars",description:"Attribute values cannot contain unsafe chars.",init:function(e,t){var a=this;e.addListener("tagstart",function(e){for(var n,r,i=e.attrs,s=e.col+e.tagName.length+1,o=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/,l=0,u=i.length;u>l;l++)if(n=i[l],r=n.value.match(o),null!==r){var d=escape(r[0]).replace(/%u/,"\\u").replace(/%/,"\\x");t.warn("The value of attribute [ "+n.name+" ] cannot contain an unsafe char [ "+d+" ].",e.line,s+n.index,a,n.raw)}})}}),HTMLHint.addRule({id:"attr-value-double-quotes",description:"Attribute values must be in double quotes.",init:function(e,t){var a=this;e.addListener("tagstart",function(e){for(var n,r=e.attrs,i=e.col+e.tagName.length+1,s=0,o=r.length;o>s;s++)n=r[s],(""!==n.value&&'"'!==n.quote||""===n.value&&"'"===n.quote)&&t.error("The value of attribute [ "+n.name+" ] must be in double quotes.",e.line,i+n.index,a,n.raw)})}}),HTMLHint.addRule({id:"attr-value-not-empty",description:"All attributes must have values.",init:function(e,t){var a=this;e.addListener("tagstart",function(e){for(var n,r=e.attrs,i=e.col+e.tagName.length+1,s=0,o=r.length;o>s;s++)n=r[s],""===n.quote&&""===n.value&&t.warn("The attribute [ "+n.name+" ] must have a value.",e.line,i+n.index,a,n.raw)})}}),HTMLHint.addRule({id:"csslint",description:"Scan css with csslint.",init:function(e,t,a){var n=this;e.addListener("cdata",function(e){if("style"===e.tagName.toLowerCase()){var r;if(r="object"==typeof exports&&require?require("csslint").CSSLint.verify:CSSLint.verify,void 0!==a){var i=e.line-1,s=e.col-1;try{var o=r(e.raw,a).messages;o.forEach(function(e){var a=e.line;t["warning"===e.type?"warn":"error"]("["+e.rule.id+"] "+e.message,i+a,(1===a?s:0)+e.col,n,e.evidence)})}catch(l){}}}})}}),HTMLHint.addRule({id:"doctype-first",description:"Doctype must be declared first.",init:function(e,t){var a=this,n=function(r){"start"===r.type||"text"===r.type&&/^\s*$/.test(r.raw)||(("comment"!==r.type&&r.long===!1||/^DOCTYPE\s+/i.test(r.content)===!1)&&t.error("Doctype must be declared first.",r.line,r.col,a,r.raw),e.removeListener("all",n))};e.addListener("all",n)}}),HTMLHint.addRule({id:"doctype-html5",description:'Invalid doctype. Use: "<!DOCTYPE html>"',init:function(e,t){function a(e){e.long===!1&&"doctype html"!==e.content.toLowerCase()&&t.warn('Invalid doctype. Use: "<!DOCTYPE html>"',e.line,e.col,r,e.raw)}function n(){e.removeListener("comment",a),e.removeListener("tagstart",n)}var r=this;e.addListener("all",a),e.addListener("tagstart",n)}}),HTMLHint.addRule({id:"head-script-disabled",description:"The <script> tag cannot be used in a <head> tag.",init:function(e,t){function a(a){var n=e.getMapAttrs(a.attrs),o=n.type,l=a.tagName.toLowerCase();"head"===l&&(s=!0),s!==!0||"script"!==l||o&&i.test(o)!==!0||t.warn("The <script> tag cannot be used in a <head> tag.",a.line,a.col,r,a.raw)}function n(t){"head"===t.tagName.toLowerCase()&&(e.removeListener("tagstart",a),e.removeListener("tagend",n))}var r=this,i=/^(text\/javascript|application\/javascript)$/i,s=!1;e.addListener("tagstart",a),e.addListener("tagend",n)}}),HTMLHint.addRule({id:"href-abs-or-rel",description:"An href attribute must be either absolute or relative.",init:function(e,t,a){var n=this,r="abs"===a?"absolute":"relative";e.addListener("tagstart",function(e){for(var a,i=e.attrs,s=e.col+e.tagName.length+1,o=0,l=i.length;l>o;o++)if(a=i[o],"href"===a.name){("absolute"===r&&/^\w+?:/.test(a.value)===!1||"relative"===r&&/^https?:\/\//.test(a.value)===!0)&&t.warn("The value of the href attribute [ "+a.value+" ] must be "+r+".",e.line,s+a.index,n,a.raw);break}})}}),HTMLHint.addRule({id:"id-class-ad-disabled",description:"The id and class attributes cannot use the ad keyword, it will be blocked by adblock software.",init:function(e,t){var a=this;e.addListener("tagstart",function(e){for(var n,r,i=e.attrs,s=e.col+e.tagName.length+1,o=0,l=i.length;l>o;o++)n=i[o],r=n.name,/^(id|class)$/i.test(r)&&/(^|[-\_])ad([-\_]|$)/i.test(n.value)&&t.warn("The value of attribute "+r+" cannot use the ad keyword.",e.line,s+n.index,a,n.raw)})}}),HTMLHint.addRule({id:"id-class-value",description:"The id and class attribute values must meet the specified rules.",init:function(e,t,a){var n,r=this,i={underline:{regId:/^[a-z\d]+(_[a-z\d]+)*$/,message:"The id and class attribute values must be in lowercase and split by an underscore."},dash:{regId:/^[a-z\d]+(-[a-z\d]+)*$/,message:"The id and class attribute values must be in lowercase and split by a dash."},hump:{regId:/^[a-z][a-zA-Z\d]*([A-Z][a-zA-Z\d]*)*$/,message:"The id and class attribute values must meet the camelCase style."}};if(n="string"==typeof a?i[a]:a,n&&n.regId){var s=n.regId,o=n.message;e.addListener("tagstart",function(e){for(var a,n=e.attrs,i=e.col+e.tagName.length+1,l=0,u=n.length;u>l;l++)if(a=n[l],"id"===a.name.toLowerCase()&&s.test(a.value)===!1&&t.warn(o,e.line,i+a.index,r,a.raw),"class"===a.name.toLowerCase())for(var d,c=a.value.split(/\s+/g),f=0,g=c.length;g>f;f++)d=c[f],d&&s.test(d)===!1&&t.warn(o,e.line,i+a.index,r,d)})}}}),HTMLHint.addRule({id:"id-unique",description:"The value of id attributes must be unique.",init:function(e,t){var a=this,n={};e.addListener("tagstart",function(e){for(var r,i,s=e.attrs,o=e.col+e.tagName.length+1,l=0,u=s.length;u>l;l++)if(r=s[l],"id"===r.name.toLowerCase()){i=r.value,i&&(void 0===n[i]?n[i]=1:n[i]++,n[i]>1&&t.error("The id value [ "+i+" ] must be unique.",e.line,o+r.index,a,r.raw));break}})}}),HTMLHint.addRule({id:"inline-script-disabled",description:"Inline script cannot be use.",init:function(e,t){var a=this;e.addListener("tagstart",function(e){for(var n,r,i=e.attrs,s=e.col+e.tagName.length+1,o=/^on(unload|message|submit|select|scroll|resize|mouseover|mouseout|mousemove|mouseleave|mouseenter|mousedown|load|keyup|keypress|keydown|focus|dblclick|click|change|blur|error)$/i,l=0,u=i.length;u>l;l++)n=i[l],r=n.name.toLowerCase(),o.test(r)===!0?t.warn("Inline script [ "+n.raw+" ] cannot be use.",e.line,s+n.index,a,n.raw):("src"===r||"href"===r)&&/^\s*javascript:/i.test(n.value)&&t.warn("Inline script [ "+n.raw+" ] cannot be use.",e.line,s+n.index,a,n.raw)})}}),HTMLHint.addRule({id:"inline-style-disabled",description:"Inline style cannot be use.",init:function(e,t){var a=this;e.addListener("tagstart",function(e){for(var n,r=e.attrs,i=e.col+e.tagName.length+1,s=0,o=r.length;o>s;s++)n=r[s],"style"===n.name.toLowerCase()&&t.warn("Inline style [ "+n.raw+" ] cannot be use.",e.line,i+n.index,a,n.raw)})}}),HTMLHint.addRule({id:"jshint",description:"Scan script with jshint.",init:function(e,t,a){var n=this;e.addListener("cdata",function(r){if("script"===r.tagName.toLowerCase()){var i=e.getMapAttrs(r.attrs),s=i.type;if(void 0!==i.src||s&&/^(text\/javascript)$/i.test(s)===!1)return;var o;if(o="object"==typeof exports&&require?require("jshint").JSHINT:JSHINT,void 0!==a){var l=r.line-1,u=r.col-1,d=r.raw.replace(/\t/g," ");try{var c=o(d,a);c===!1&&o.errors.forEach(function(e){var a=e.line;t.warn(e.reason,l+a,(1===a?u:0)+e.character,n,e.evidence)})}catch(f){}}}})}}),HTMLHint.addRule({id:"space-tab-mixed-disabled",description:"Do not mix tabs and spaces for indentation.",init:function(e,t,a){var n=this,r="nomix",i=null;if("string"==typeof a){var s=a.match(/^([a-z]+)(\d+)?/);r=s[1],i=s[2]&&parseInt(s[2],10)}e.addListener("text",function(a){for(var s,o=a.raw,l=/(^|\r?\n)([ \t]+)/g;s=l.exec(o);){var u=e.fixPos(a,s.index+s[1].length);if(1===u.col){var d=s[2];"space"===r?i?(/^ +$/.test(d)===!1||0!==d.length%i)&&t.warn("Please use space for indentation and keep "+i+" length.",u.line,1,n,a.raw):/^ +$/.test(d)===!1&&t.warn("Please use space for indentation.",u.line,1,n,a.raw):"tab"===r&&/^\t+$/.test(d)===!1?t.warn("Please use tab for indentation.",u.line,1,n,a.raw):/ +\t|\t+ /.test(d)===!0&&t.warn("Do not mix tabs and spaces for indentation.",u.line,1,n,a.raw)}}})}}),HTMLHint.addRule({id:"spec-char-escape",description:"Special characters must be escaped.",init:function(e,t){var a=this;e.addListener("text",function(n){for(var r,i=n.raw,s=/[<>]/g;r=s.exec(i);){var o=e.fixPos(n,r.index);t.error("Special characters must be escaped : [ "+r[0]+" ].",o.line,o.col,a,n.raw)}})}}),HTMLHint.addRule({id:"src-not-empty",description:"The src attribute of an img(script,link) must have a value.",init:function(e,t){var a=this;e.addListener("tagstart",function(e){for(var n,r=e.tagName,i=e.attrs,s=e.col+r.length+1,o=0,l=i.length;l>o;o++)n=i[o],(/^(img|script|embed|bgsound|iframe)$/.test(r)===!0&&"src"===n.name||"link"===r&&"href"===n.name||"object"===r&&"data"===n.name)&&""===n.value&&t.error("The attribute [ "+n.name+" ] of the tag [ "+r+" ] must have a value.",e.line,s+n.index,a,n.raw)})}}),HTMLHint.addRule({id:"style-disabled",description:"<style> tags cannot be used.",init:function(e,t){var a=this;e.addListener("tagstart",function(e){"style"===e.tagName.toLowerCase()&&t.warn("The <style> tag cannot be used.",e.line,e.col,a,e.raw)})}}),HTMLHint.addRule({id:"tag-pair",description:"Tag must be paired.",init:function(e,t){var a=this,n=[],r=e.makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed,track,command,source,keygen,wbr");e.addListener("tagstart",function(e){var t=e.tagName.toLowerCase();void 0!==r[t]||e.close||n.push({tagName:t,line:e.line,raw:e.raw})}),e.addListener("tagend",function(e){for(var r=e.tagName.toLowerCase(),i=n.length-1;i>=0&&n[i].tagName!==r;i--);if(i>=0){for(var s=[],o=n.length-1;o>i;o--)s.push("</"+n[o].tagName+">");if(s.length>0){var l=n[n.length-1];t.error("Tag must be paired, missing: [ "+s.join("")+" ], start tag match failed [ "+l.raw+" ] on line "+l.line+".",e.line,e.col,a,e.raw)}n.length=i}else t.error("Tag must be paired, no start tag: [ "+e.raw+" ]",e.line,e.col,a,e.raw)}),e.addListener("end",function(e){for(var r=[],i=n.length-1;i>=0;i--)r.push("</"+n[i].tagName+">");if(r.length>0){var s=n[n.length-1];t.error("Tag must be paired, missing: [ "+r.join("")+" ], open tag match failed [ "+s.raw+" ] on line "+s.line+".",e.line,e.col,a,"")}})}}),HTMLHint.addRule({id:"tag-self-close",description:"Empty tags must be self closed.",init:function(e,t){var a=this,n=e.makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed,track,command,source,keygen,wbr");e.addListener("tagstart",function(e){var r=e.tagName.toLowerCase();void 0!==n[r]&&(e.close||t.warn("The empty tag : [ "+r+" ] must be self closed.",e.line,e.col,a,e.raw))})}}),HTMLHint.addRule({id:"tagname-lowercase",description:"All html element names must be in lowercase.",init:function(e,t){var a=this;e.addListener("tagstart,tagend",function(e){var n=e.tagName;n!==n.toLowerCase()&&t.error("The html element name of [ "+n+" ] must be in lowercase.",e.line,e.col,a,e.raw)})}}),HTMLHint.addRule({id:"title-require",description:"<title> must be present in <head> tag.",init:function(e,t){function a(e){var t=e.tagName.toLowerCase();"head"===t?i=!0:"title"===t&&i&&(s=!0)}function n(i){var o=i.tagName.toLowerCase();if(s&&"title"===o){var l=i.lastEvent;("text"!==l.type||"text"===l.type&&/^\s*$/.test(l.raw)===!0)&&t.error("<title></title> must not be empty.",i.line,i.col,r,i.raw)}else"head"===o&&(s===!1&&t.error("<title> must be present in <head> tag.",i.line,i.col,r,i.raw),e.removeListener("tagstart",a),e.removeListener("tagend",n))}var r=this,i=!1,s=!1;e.addListener("tagstart",a),e.addListener("tagend",n)}}); },{"csslint":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/csslint/lib/csslint-node.js","jshint":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/jshint.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/ieee754/index.js":[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/in-view/dist/in-view.min.js":[function(require,module,exports){ /*! * in-view 0.6.1 - Get notified when a DOM element enters or exits the viewport. * Copyright (c) 2016 Cam Wiegert <cam@camwiegert.com> - https://camwiegert.github.io/in-view * License: MIT */ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.inView=e():t.inView=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return t[r].call(i.exports,i,i.exports,e),i.loaded=!0,i.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}var i=n(2),o=r(i);t.exports=o["default"]},function(t,e){function n(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}t.exports=n},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}Object.defineProperty(e,"__esModule",{value:!0});var i=n(9),o=r(i),u=n(3),f=r(u),s=n(4),c=function(){if("undefined"!=typeof window){var t=100,e=["scroll","resize","load"],n={history:[]},r={offset:{},threshold:0,test:s.inViewport},i=(0,o["default"])(function(){n.history.forEach(function(t){n[t].check()})},t);e.forEach(function(t){return addEventListener(t,i)}),window.MutationObserver&&addEventListener("DOMContentLoaded",function(){new MutationObserver(i).observe(document.body,{attributes:!0,childList:!0,subtree:!0})});var u=function(t){if("string"==typeof t){var e=[].slice.call(document.querySelectorAll(t));return n.history.indexOf(t)>-1?n[t].elements=e:(n[t]=(0,f["default"])(e,r),n.history.push(t)),n[t]}};return u.offset=function(t){if(void 0===t)return r.offset;var e=function(t){return"number"==typeof t};return["top","right","bottom","left"].forEach(e(t)?function(e){return r.offset[e]=t}:function(n){return e(t[n])?r.offset[n]=t[n]:null}),r.offset},u.threshold=function(t){return"number"==typeof t&&t>=0&&t<=1?r.threshold=t:r.threshold},u.test=function(t){return"function"==typeof t?r.test=t:r.test},u.is=function(t){return r.test(t,r)},u.offset(0),u}};e["default"]=c()},function(t,e){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),i=function(){function t(e,r){n(this,t),this.options=r,this.elements=e,this.current=[],this.handlers={enter:[],exit:[]},this.singles={enter:[],exit:[]}}return r(t,[{key:"check",value:function(){var t=this;return this.elements.forEach(function(e){var n=t.options.test(e,t.options),r=t.current.indexOf(e),i=r>-1,o=n&&!i,u=!n&&i;o&&(t.current.push(e),t.emit("enter",e)),u&&(t.current.splice(r,1),t.emit("exit",e))}),this}},{key:"on",value:function(t,e){return this.handlers[t].push(e),this}},{key:"once",value:function(t,e){return this.singles[t].unshift(e),this}},{key:"emit",value:function(t,e){for(;this.singles[t].length;)this.singles[t].pop()(e);for(var n=this.handlers[t].length;--n>-1;)this.handlers[t][n](e);return this}}]),t}();e["default"]=function(t,e){return new i(t,e)}},function(t,e){"use strict";function n(t,e){var n=t.getBoundingClientRect(),r=n.top,i=n.right,o=n.bottom,u=n.left,f=n.width,s=n.height,c={t:o,r:window.innerWidth-u,b:window.innerHeight-r,l:i},a={x:e.threshold*f,y:e.threshold*s};return c.t>e.offset.top+a.y&&c.r>e.offset.right+a.x&&c.b>e.offset.bottom+a.y&&c.l>e.offset.left+a.x}Object.defineProperty(e,"__esModule",{value:!0}),e.inViewport=n},function(t,e){(function(e){var n="object"==typeof e&&e&&e.Object===Object&&e;t.exports=n}).call(e,function(){return this}())},function(t,e,n){var r=n(5),i="object"==typeof self&&self&&self.Object===Object&&self,o=r||i||Function("return this")();t.exports=o},function(t,e,n){function r(t,e,n){function r(e){var n=x,r=m;return x=m=void 0,E=e,w=t.apply(r,n)}function a(t){return E=t,j=setTimeout(h,e),M?r(t):w}function l(t){var n=t-O,r=t-E,i=e-n;return _?c(i,g-r):i}function d(t){var n=t-O,r=t-E;return void 0===O||n>=e||n<0||_&&r>=g}function h(){var t=o();return d(t)?p(t):void(j=setTimeout(h,l(t)))}function p(t){return j=void 0,T&&x?r(t):(x=m=void 0,w)}function v(){void 0!==j&&clearTimeout(j),E=0,x=O=m=j=void 0}function y(){return void 0===j?w:p(o())}function b(){var t=o(),n=d(t);if(x=arguments,m=this,O=t,n){if(void 0===j)return a(O);if(_)return j=setTimeout(h,e),r(O)}return void 0===j&&(j=setTimeout(h,e)),w}var x,m,g,w,j,O,E=0,M=!1,_=!1,T=!0;if("function"!=typeof t)throw new TypeError(f);return e=u(e)||0,i(n)&&(M=!!n.leading,_="maxWait"in n,g=_?s(u(n.maxWait)||0,e):g,T="trailing"in n?!!n.trailing:T),b.cancel=v,b.flush=y,b}var i=n(1),o=n(8),u=n(10),f="Expected a function",s=Math.max,c=Math.min;t.exports=r},function(t,e,n){var r=n(6),i=function(){return r.Date.now()};t.exports=i},function(t,e,n){function r(t,e,n){var r=!0,f=!0;if("function"!=typeof t)throw new TypeError(u);return o(n)&&(r="leading"in n?!!n.leading:r,f="trailing"in n?!!n.trailing:f),i(t,e,{leading:r,maxWait:e,trailing:f})}var i=n(7),o=n(1),u="Expected a function";t.exports=r},function(t,e){function n(t){return t}t.exports=n}])}); },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/js-base64/base64.js":[function(require,module,exports){ /* * $Id: base64.js,v 2.15 2014/04/05 12:58:57 dankogai Exp dankogai $ * * Licensed under the MIT license. * http://opensource.org/licenses/mit-license * * References: * http://en.wikipedia.org/wiki/Base64 */ (function(global) { 'use strict'; // existing version for noConflict() var _Base64 = global.Base64; var version = "2.1.9"; // if node.js, we use Buffer var buffer; if (typeof module !== 'undefined' && module.exports) { try { buffer = require('buffer').Buffer; } catch (err) {} } // constants var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var b64tab = function(bin) { var t = {}; for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i; return t; }(b64chars); var fromCharCode = String.fromCharCode; // encoder stuff var cb_utob = function(c) { if (c.length < 2) { var cc = c.charCodeAt(0); return cc < 0x80 ? c : cc < 0x800 ? (fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f))) : (fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + fromCharCode(0x80 | ( cc & 0x3f))); } else { var cc = 0x10000 + (c.charCodeAt(0) - 0xD800) * 0x400 + (c.charCodeAt(1) - 0xDC00); return (fromCharCode(0xf0 | ((cc >>> 18) & 0x07)) + fromCharCode(0x80 | ((cc >>> 12) & 0x3f)) + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + fromCharCode(0x80 | ( cc & 0x3f))); } }; var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g; var utob = function(u) { return u.replace(re_utob, cb_utob); }; var cb_encode = function(ccc) { var padlen = [0, 2, 1][ccc.length % 3], ord = ccc.charCodeAt(0) << 16 | ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8) | ((ccc.length > 2 ? ccc.charCodeAt(2) : 0)), chars = [ b64chars.charAt( ord >>> 18), b64chars.charAt((ord >>> 12) & 63), padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63), padlen >= 1 ? '=' : b64chars.charAt(ord & 63) ]; return chars.join(''); }; var btoa = global.btoa ? function(b) { return global.btoa(b); } : function(b) { return b.replace(/[\s\S]{1,3}/g, cb_encode); }; var _encode = buffer ? function (u) { return (u.constructor === buffer.constructor ? u : new buffer(u)) .toString('base64') } : function (u) { return btoa(utob(u)) } ; var encode = function(u, urisafe) { return !urisafe ? _encode(String(u)) : _encode(String(u)).replace(/[+\/]/g, function(m0) { return m0 == '+' ? '-' : '_'; }).replace(/=/g, ''); }; var encodeURI = function(u) { return encode(u, true) }; // decoder stuff var re_btou = new RegExp([ '[\xC0-\xDF][\x80-\xBF]', '[\xE0-\xEF][\x80-\xBF]{2}', '[\xF0-\xF7][\x80-\xBF]{3}' ].join('|'), 'g'); var cb_btou = function(cccc) { switch(cccc.length) { case 4: var cp = ((0x07 & cccc.charCodeAt(0)) << 18) | ((0x3f & cccc.charCodeAt(1)) << 12) | ((0x3f & cccc.charCodeAt(2)) << 6) | (0x3f & cccc.charCodeAt(3)), offset = cp - 0x10000; return (fromCharCode((offset >>> 10) + 0xD800) + fromCharCode((offset & 0x3FF) + 0xDC00)); case 3: return fromCharCode( ((0x0f & cccc.charCodeAt(0)) << 12) | ((0x3f & cccc.charCodeAt(1)) << 6) | (0x3f & cccc.charCodeAt(2)) ); default: return fromCharCode( ((0x1f & cccc.charCodeAt(0)) << 6) | (0x3f & cccc.charCodeAt(1)) ); } }; var btou = function(b) { return b.replace(re_btou, cb_btou); }; var cb_decode = function(cccc) { var len = cccc.length, padlen = len % 4, n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0) | (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0) | (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0) | (len > 3 ? b64tab[cccc.charAt(3)] : 0), chars = [ fromCharCode( n >>> 16), fromCharCode((n >>> 8) & 0xff), fromCharCode( n & 0xff) ]; chars.length -= [0, 0, 2, 1][padlen]; return chars.join(''); }; var atob = global.atob ? function(a) { return global.atob(a); } : function(a){ return a.replace(/[\s\S]{1,4}/g, cb_decode); }; var _decode = buffer ? function(a) { return (a.constructor === buffer.constructor ? a : new buffer(a, 'base64')).toString(); } : function(a) { return btou(atob(a)) }; var decode = function(a){ return _decode( String(a).replace(/[-_]/g, function(m0) { return m0 == '-' ? '+' : '/' }) .replace(/[^A-Za-z0-9\+\/]/g, '') ); }; var noConflict = function() { var Base64 = global.Base64; global.Base64 = _Base64; return Base64; }; // export Base64 global.Base64 = { VERSION: version, atob: atob, btoa: btoa, fromBase64: decode, toBase64: encode, utob: utob, encode: encode, encodeURI: encodeURI, btou: btou, decode: decode, noConflict: noConflict }; // if ES5 is available, make Base64.extendString() available if (typeof Object.defineProperty === 'function') { var noEnum = function(v){ return {value:v,enumerable:false,writable:true,configurable:true}; }; global.Base64.extendString = function () { Object.defineProperty( String.prototype, 'fromBase64', noEnum(function () { return decode(this) })); Object.defineProperty( String.prototype, 'toBase64', noEnum(function (urisafe) { return encode(this, urisafe) })); Object.defineProperty( String.prototype, 'toBase64URI', noEnum(function () { return encode(this, true) })); }; } // that's it! if (global['Meteor']) { Base64 = global.Base64; // for normal export in Meteor.js } })(this); },{"buffer":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/ember-browserify/node_modules/buffer/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/data/ascii-identifier-data.js":[function(require,module,exports){ var identifierStartTable = []; for (var i = 0; i < 128; i++) { identifierStartTable[i] = i === 36 || // $ i >= 65 && i <= 90 || // A-Z i === 95 || // _ i >= 97 && i <= 122; // a-z } var identifierPartTable = []; for (var i = 0; i < 128; i++) { identifierPartTable[i] = identifierStartTable[i] || // $, _, A-Z, a-z i >= 48 && i <= 57; // 0-9 } module.exports = { asciiIdentifierStartTable: identifierStartTable, asciiIdentifierPartTable: identifierPartTable }; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/data/non-ascii-identifier-part-only.js":[function(require,module,exports){ var str = '768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,1155,1156,1157,1158,1159,1425,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439,1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1471,1473,1474,1476,1477,1479,1552,1553,1554,1555,1556,1557,1558,1559,1560,1561,1562,1611,1612,1613,1614,1615,1616,1617,1618,1619,1620,1621,1622,1623,1624,1625,1626,1627,1628,1629,1630,1631,1632,1633,1634,1635,1636,1637,1638,1639,1640,1641,1648,1750,1751,1752,1753,1754,1755,1756,1759,1760,1761,1762,1763,1764,1767,1768,1770,1771,1772,1773,1776,1777,1778,1779,1780,1781,1782,1783,1784,1785,1809,1840,1841,1842,1843,1844,1845,1846,1847,1848,1849,1850,1851,1852,1853,1854,1855,1856,1857,1858,1859,1860,1861,1862,1863,1864,1865,1866,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1968,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,2027,2028,2029,2030,2031,2032,2033,2034,2035,2070,2071,2072,2073,2075,2076,2077,2078,2079,2080,2081,2082,2083,2085,2086,2087,2089,2090,2091,2092,2093,2137,2138,2139,2276,2277,2278,2279,2280,2281,2282,2283,2284,2285,2286,2287,2288,2289,2290,2291,2292,2293,2294,2295,2296,2297,2298,2299,2300,2301,2302,2304,2305,2306,2307,2362,2363,2364,2366,2367,2368,2369,2370,2371,2372,2373,2374,2375,2376,2377,2378,2379,2380,2381,2382,2383,2385,2386,2387,2388,2389,2390,2391,2402,2403,2406,2407,2408,2409,2410,2411,2412,2413,2414,2415,2433,2434,2435,2492,2494,2495,2496,2497,2498,2499,2500,2503,2504,2507,2508,2509,2519,2530,2531,2534,2535,2536,2537,2538,2539,2540,2541,2542,2543,2561,2562,2563,2620,2622,2623,2624,2625,2626,2631,2632,2635,2636,2637,2641,2662,2663,2664,2665,2666,2667,2668,2669,2670,2671,2672,2673,2677,2689,2690,2691,2748,2750,2751,2752,2753,2754,2755,2756,2757,2759,2760,2761,2763,2764,2765,2786,2787,2790,2791,2792,2793,2794,2795,2796,2797,2798,2799,2817,2818,2819,2876,2878,2879,2880,2881,2882,2883,2884,2887,2888,2891,2892,2893,2902,2903,2914,2915,2918,2919,2920,2921,2922,2923,2924,2925,2926,2927,2946,3006,3007,3008,3009,3010,3014,3015,3016,3018,3019,3020,3021,3031,3046,3047,3048,3049,3050,3051,3052,3053,3054,3055,3073,3074,3075,3134,3135,3136,3137,3138,3139,3140,3142,3143,3144,3146,3147,3148,3149,3157,3158,3170,3171,3174,3175,3176,3177,3178,3179,3180,3181,3182,3183,3202,3203,3260,3262,3263,3264,3265,3266,3267,3268,3270,3271,3272,3274,3275,3276,3277,3285,3286,3298,3299,3302,3303,3304,3305,3306,3307,3308,3309,3310,3311,3330,3331,3390,3391,3392,3393,3394,3395,3396,3398,3399,3400,3402,3403,3404,3405,3415,3426,3427,3430,3431,3432,3433,3434,3435,3436,3437,3438,3439,3458,3459,3530,3535,3536,3537,3538,3539,3540,3542,3544,3545,3546,3547,3548,3549,3550,3551,3570,3571,3633,3636,3637,3638,3639,3640,3641,3642,3655,3656,3657,3658,3659,3660,3661,3662,3664,3665,3666,3667,3668,3669,3670,3671,3672,3673,3761,3764,3765,3766,3767,3768,3769,3771,3772,3784,3785,3786,3787,3788,3789,3792,3793,3794,3795,3796,3797,3798,3799,3800,3801,3864,3865,3872,3873,3874,3875,3876,3877,3878,3879,3880,3881,3893,3895,3897,3902,3903,3953,3954,3955,3956,3957,3958,3959,3960,3961,3962,3963,3964,3965,3966,3967,3968,3969,3970,3971,3972,3974,3975,3981,3982,3983,3984,3985,3986,3987,3988,3989,3990,3991,3993,3994,3995,3996,3997,3998,3999,4000,4001,4002,4003,4004,4005,4006,4007,4008,4009,4010,4011,4012,4013,4014,4015,4016,4017,4018,4019,4020,4021,4022,4023,4024,4025,4026,4027,4028,4038,4139,4140,4141,4142,4143,4144,4145,4146,4147,4148,4149,4150,4151,4152,4153,4154,4155,4156,4157,4158,4160,4161,4162,4163,4164,4165,4166,4167,4168,4169,4182,4183,4184,4185,4190,4191,4192,4194,4195,4196,4199,4200,4201,4202,4203,4204,4205,4209,4210,4211,4212,4226,4227,4228,4229,4230,4231,4232,4233,4234,4235,4236,4237,4239,4240,4241,4242,4243,4244,4245,4246,4247,4248,4249,4250,4251,4252,4253,4957,4958,4959,5906,5907,5908,5938,5939,5940,5970,5971,6002,6003,6068,6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084,6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6109,6112,6113,6114,6115,6116,6117,6118,6119,6120,6121,6155,6156,6157,6160,6161,6162,6163,6164,6165,6166,6167,6168,6169,6313,6432,6433,6434,6435,6436,6437,6438,6439,6440,6441,6442,6443,6448,6449,6450,6451,6452,6453,6454,6455,6456,6457,6458,6459,6470,6471,6472,6473,6474,6475,6476,6477,6478,6479,6576,6577,6578,6579,6580,6581,6582,6583,6584,6585,6586,6587,6588,6589,6590,6591,6592,6600,6601,6608,6609,6610,6611,6612,6613,6614,6615,6616,6617,6679,6680,6681,6682,6683,6741,6742,6743,6744,6745,6746,6747,6748,6749,6750,6752,6753,6754,6755,6756,6757,6758,6759,6760,6761,6762,6763,6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777,6778,6779,6780,6783,6784,6785,6786,6787,6788,6789,6790,6791,6792,6793,6800,6801,6802,6803,6804,6805,6806,6807,6808,6809,6912,6913,6914,6915,6916,6964,6965,6966,6967,6968,6969,6970,6971,6972,6973,6974,6975,6976,6977,6978,6979,6980,6992,6993,6994,6995,6996,6997,6998,6999,7000,7001,7019,7020,7021,7022,7023,7024,7025,7026,7027,7040,7041,7042,7073,7074,7075,7076,7077,7078,7079,7080,7081,7082,7083,7084,7085,7088,7089,7090,7091,7092,7093,7094,7095,7096,7097,7142,7143,7144,7145,7146,7147,7148,7149,7150,7151,7152,7153,7154,7155,7204,7205,7206,7207,7208,7209,7210,7211,7212,7213,7214,7215,7216,7217,7218,7219,7220,7221,7222,7223,7232,7233,7234,7235,7236,7237,7238,7239,7240,7241,7248,7249,7250,7251,7252,7253,7254,7255,7256,7257,7376,7377,7378,7380,7381,7382,7383,7384,7385,7386,7387,7388,7389,7390,7391,7392,7393,7394,7395,7396,7397,7398,7399,7400,7405,7410,7411,7412,7616,7617,7618,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628,7629,7630,7631,7632,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643,7644,7645,7646,7647,7648,7649,7650,7651,7652,7653,7654,7676,7677,7678,7679,8204,8205,8255,8256,8276,8400,8401,8402,8403,8404,8405,8406,8407,8408,8409,8410,8411,8412,8417,8421,8422,8423,8424,8425,8426,8427,8428,8429,8430,8431,8432,11503,11504,11505,11647,11744,11745,11746,11747,11748,11749,11750,11751,11752,11753,11754,11755,11756,11757,11758,11759,11760,11761,11762,11763,11764,11765,11766,11767,11768,11769,11770,11771,11772,11773,11774,11775,12330,12331,12332,12333,12334,12335,12441,12442,42528,42529,42530,42531,42532,42533,42534,42535,42536,42537,42607,42612,42613,42614,42615,42616,42617,42618,42619,42620,42621,42655,42736,42737,43010,43014,43019,43043,43044,43045,43046,43047,43136,43137,43188,43189,43190,43191,43192,43193,43194,43195,43196,43197,43198,43199,43200,43201,43202,43203,43204,43216,43217,43218,43219,43220,43221,43222,43223,43224,43225,43232,43233,43234,43235,43236,43237,43238,43239,43240,43241,43242,43243,43244,43245,43246,43247,43248,43249,43264,43265,43266,43267,43268,43269,43270,43271,43272,43273,43302,43303,43304,43305,43306,43307,43308,43309,43335,43336,43337,43338,43339,43340,43341,43342,43343,43344,43345,43346,43347,43392,43393,43394,43395,43443,43444,43445,43446,43447,43448,43449,43450,43451,43452,43453,43454,43455,43456,43472,43473,43474,43475,43476,43477,43478,43479,43480,43481,43561,43562,43563,43564,43565,43566,43567,43568,43569,43570,43571,43572,43573,43574,43587,43596,43597,43600,43601,43602,43603,43604,43605,43606,43607,43608,43609,43643,43696,43698,43699,43700,43703,43704,43710,43711,43713,43755,43756,43757,43758,43759,43765,43766,44003,44004,44005,44006,44007,44008,44009,44010,44012,44013,44016,44017,44018,44019,44020,44021,44022,44023,44024,44025,64286,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65056,65057,65058,65059,65060,65061,65062,65075,65076,65101,65102,65103,65296,65297,65298,65299,65300,65301,65302,65303,65304,65305,65343'; var arr = str.split(',').map(function(code) { return parseInt(code, 10); }); module.exports = arr; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/data/non-ascii-identifier-start.js":[function(require,module,exports){ var str = '170,181,186,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,710,711,712,713,714,715,716,717,718,719,720,721,736,737,738,739,740,748,750,880,881,882,883,884,886,887,890,891,892,893,902,904,905,906,908,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999,1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131,1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147,1148,1149,1150,1151,1152,1153,1162,1163,1164,1165,1166,1167,1168,1169,1170,1171,1172,1173,1174,1175,1176,1177,1178,1179,1180,1181,1182,1183,1184,1185,1186,1187,1188,1189,1190,1191,1192,1193,1194,1195,1196,1197,1198,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229,1230,1231,1232,1233,1234,1235,1236,1237,1238,1239,1240,1241,1242,1243,1244,1245,1246,1247,1248,1249,1250,1251,1252,1253,1254,1255,1256,1257,1258,1259,1260,1261,1262,1263,1264,1265,1266,1267,1268,1269,1270,1271,1272,1273,1274,1275,1276,1277,1278,1279,1280,1281,1282,1283,1284,1285,1286,1287,1288,1289,1290,1291,1292,1293,1294,1295,1296,1297,1298,1299,1300,1301,1302,1303,1304,1305,1306,1307,1308,1309,1310,1311,1312,1313,1314,1315,1316,1317,1318,1319,1329,1330,1331,1332,1333,1334,1335,1336,1337,1338,1339,1340,1341,1342,1343,1344,1345,1346,1347,1348,1349,1350,1351,1352,1353,1354,1355,1356,1357,1358,1359,1360,1361,1362,1363,1364,1365,1366,1369,1377,1378,1379,1380,1381,1382,1383,1384,1385,1386,1387,1388,1389,1390,1391,1392,1393,1394,1395,1396,1397,1398,1399,1400,1401,1402,1403,1404,1405,1406,1407,1408,1409,1410,1411,1412,1413,1414,1415,1488,1489,1490,1491,1492,1493,1494,1495,1496,1497,1498,1499,1500,1501,1502,1503,1504,1505,1506,1507,1508,1509,1510,1511,1512,1513,1514,1520,1521,1522,1568,1569,1570,1571,1572,1573,1574,1575,1576,1577,1578,1579,1580,1581,1582,1583,1584,1585,1586,1587,1588,1589,1590,1591,1592,1593,1594,1595,1596,1597,1598,1599,1600,1601,1602,1603,1604,1605,1606,1607,1608,1609,1610,1646,1647,1649,1650,1651,1652,1653,1654,1655,1656,1657,1658,1659,1660,1661,1662,1663,1664,1665,1666,1667,1668,1669,1670,1671,1672,1673,1674,1675,1676,1677,1678,1679,1680,1681,1682,1683,1684,1685,1686,1687,1688,1689,1690,1691,1692,1693,1694,1695,1696,1697,1698,1699,1700,1701,1702,1703,1704,1705,1706,1707,1708,1709,1710,1711,1712,1713,1714,1715,1716,1717,1718,1719,1720,1721,1722,1723,1724,1725,1726,1727,1728,1729,1730,1731,1732,1733,1734,1735,1736,1737,1738,1739,1740,1741,1742,1743,1744,1745,1746,1747,1749,1765,1766,1774,1775,1786,1787,1788,1791,1808,1810,1811,1812,1813,1814,1815,1816,1817,1818,1819,1820,1821,1822,1823,1824,1825,1826,1827,1828,1829,1830,1831,1832,1833,1834,1835,1836,1837,1838,1839,1869,1870,1871,1872,1873,1874,1875,1876,1877,1878,1879,1880,1881,1882,1883,1884,1885,1886,1887,1888,1889,1890,1891,1892,1893,1894,1895,1896,1897,1898,1899,1900,1901,1902,1903,1904,1905,1906,1907,1908,1909,1910,1911,1912,1913,1914,1915,1916,1917,1918,1919,1920,1921,1922,1923,1924,1925,1926,1927,1928,1929,1930,1931,1932,1933,1934,1935,1936,1937,1938,1939,1940,1941,1942,1943,1944,1945,1946,1947,1948,1949,1950,1951,1952,1953,1954,1955,1956,1957,1969,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022,2023,2024,2025,2026,2036,2037,2042,2048,2049,2050,2051,2052,2053,2054,2055,2056,2057,2058,2059,2060,2061,2062,2063,2064,2065,2066,2067,2068,2069,2074,2084,2088,2112,2113,2114,2115,2116,2117,2118,2119,2120,2121,2122,2123,2124,2125,2126,2127,2128,2129,2130,2131,2132,2133,2134,2135,2136,2208,2210,2211,2212,2213,2214,2215,2216,2217,2218,2219,2220,2308,2309,2310,2311,2312,2313,2314,2315,2316,2317,2318,2319,2320,2321,2322,2323,2324,2325,2326,2327,2328,2329,2330,2331,2332,2333,2334,2335,2336,2337,2338,2339,2340,2341,2342,2343,2344,2345,2346,2347,2348,2349,2350,2351,2352,2353,2354,2355,2356,2357,2358,2359,2360,2361,2365,2384,2392,2393,2394,2395,2396,2397,2398,2399,2400,2401,2417,2418,2419,2420,2421,2422,2423,2425,2426,2427,2428,2429,2430,2431,2437,2438,2439,2440,2441,2442,2443,2444,2447,2448,2451,2452,2453,2454,2455,2456,2457,2458,2459,2460,2461,2462,2463,2464,2465,2466,2467,2468,2469,2470,2471,2472,2474,2475,2476,2477,2478,2479,2480,2482,2486,2487,2488,2489,2493,2510,2524,2525,2527,2528,2529,2544,2545,2565,2566,2567,2568,2569,2570,2575,2576,2579,2580,2581,2582,2583,2584,2585,2586,2587,2588,2589,2590,2591,2592,2593,2594,2595,2596,2597,2598,2599,2600,2602,2603,2604,2605,2606,2607,2608,2610,2611,2613,2614,2616,2617,2649,2650,2651,2652,2654,2674,2675,2676,2693,2694,2695,2696,2697,2698,2699,2700,2701,2703,2704,2705,2707,2708,2709,2710,2711,2712,2713,2714,2715,2716,2717,2718,2719,2720,2721,2722,2723,2724,2725,2726,2727,2728,2730,2731,2732,2733,2734,2735,2736,2738,2739,2741,2742,2743,2744,2745,2749,2768,2784,2785,2821,2822,2823,2824,2825,2826,2827,2828,2831,2832,2835,2836,2837,2838,2839,2840,2841,2842,2843,2844,2845,2846,2847,2848,2849,2850,2851,2852,2853,2854,2855,2856,2858,2859,2860,2861,2862,2863,2864,2866,2867,2869,2870,2871,2872,2873,2877,2908,2909,2911,2912,2913,2929,2947,2949,2950,2951,2952,2953,2954,2958,2959,2960,2962,2963,2964,2965,2969,2970,2972,2974,2975,2979,2980,2984,2985,2986,2990,2991,2992,2993,2994,2995,2996,2997,2998,2999,3000,3001,3024,3077,3078,3079,3080,3081,3082,3083,3084,3086,3087,3088,3090,3091,3092,3093,3094,3095,3096,3097,3098,3099,3100,3101,3102,3103,3104,3105,3106,3107,3108,3109,3110,3111,3112,3114,3115,3116,3117,3118,3119,3120,3121,3122,3123,3125,3126,3127,3128,3129,3133,3160,3161,3168,3169,3205,3206,3207,3208,3209,3210,3211,3212,3214,3215,3216,3218,3219,3220,3221,3222,3223,3224,3225,3226,3227,3228,3229,3230,3231,3232,3233,3234,3235,3236,3237,3238,3239,3240,3242,3243,3244,3245,3246,3247,3248,3249,3250,3251,3253,3254,3255,3256,3257,3261,3294,3296,3297,3313,3314,3333,3334,3335,3336,3337,3338,3339,3340,3342,3343,3344,3346,3347,3348,3349,3350,3351,3352,3353,3354,3355,3356,3357,3358,3359,3360,3361,3362,3363,3364,3365,3366,3367,3368,3369,3370,3371,3372,3373,3374,3375,3376,3377,3378,3379,3380,3381,3382,3383,3384,3385,3386,3389,3406,3424,3425,3450,3451,3452,3453,3454,3455,3461,3462,3463,3464,3465,3466,3467,3468,3469,3470,3471,3472,3473,3474,3475,3476,3477,3478,3482,3483,3484,3485,3486,3487,3488,3489,3490,3491,3492,3493,3494,3495,3496,3497,3498,3499,3500,3501,3502,3503,3504,3505,3507,3508,3509,3510,3511,3512,3513,3514,3515,3517,3520,3521,3522,3523,3524,3525,3526,3585,3586,3587,3588,3589,3590,3591,3592,3593,3594,3595,3596,3597,3598,3599,3600,3601,3602,3603,3604,3605,3606,3607,3608,3609,3610,3611,3612,3613,3614,3615,3616,3617,3618,3619,3620,3621,3622,3623,3624,3625,3626,3627,3628,3629,3630,3631,3632,3634,3635,3648,3649,3650,3651,3652,3653,3654,3713,3714,3716,3719,3720,3722,3725,3732,3733,3734,3735,3737,3738,3739,3740,3741,3742,3743,3745,3746,3747,3749,3751,3754,3755,3757,3758,3759,3760,3762,3763,3773,3776,3777,3778,3779,3780,3782,3804,3805,3806,3807,3840,3904,3905,3906,3907,3908,3909,3910,3911,3913,3914,3915,3916,3917,3918,3919,3920,3921,3922,3923,3924,3925,3926,3927,3928,3929,3930,3931,3932,3933,3934,3935,3936,3937,3938,3939,3940,3941,3942,3943,3944,3945,3946,3947,3948,3976,3977,3978,3979,3980,4096,4097,4098,4099,4100,4101,4102,4103,4104,4105,4106,4107,4108,4109,4110,4111,4112,4113,4114,4115,4116,4117,4118,4119,4120,4121,4122,4123,4124,4125,4126,4127,4128,4129,4130,4131,4132,4133,4134,4135,4136,4137,4138,4159,4176,4177,4178,4179,4180,4181,4186,4187,4188,4189,4193,4197,4198,4206,4207,4208,4213,4214,4215,4216,4217,4218,4219,4220,4221,4222,4223,4224,4225,4238,4256,4257,4258,4259,4260,4261,4262,4263,4264,4265,4266,4267,4268,4269,4270,4271,4272,4273,4274,4275,4276,4277,4278,4279,4280,4281,4282,4283,4284,4285,4286,4287,4288,4289,4290,4291,4292,4293,4295,4301,4304,4305,4306,4307,4308,4309,4310,4311,4312,4313,4314,4315,4316,4317,4318,4319,4320,4321,4322,4323,4324,4325,4326,4327,4328,4329,4330,4331,4332,4333,4334,4335,4336,4337,4338,4339,4340,4341,4342,4343,4344,4345,4346,4348,4349,4350,4351,4352,4353,4354,4355,4356,4357,4358,4359,4360,4361,4362,4363,4364,4365,4366,4367,4368,4369,4370,4371,4372,4373,4374,4375,4376,4377,4378,4379,4380,4381,4382,4383,4384,4385,4386,4387,4388,4389,4390,4391,4392,4393,4394,4395,4396,4397,4398,4399,4400,4401,4402,4403,4404,4405,4406,4407,4408,4409,4410,4411,4412,4413,4414,4415,4416,4417,4418,4419,4420,4421,4422,4423,4424,4425,4426,4427,4428,4429,4430,4431,4432,4433,4434,4435,4436,4437,4438,4439,4440,4441,4442,4443,4444,4445,4446,4447,4448,4449,4450,4451,4452,4453,4454,4455,4456,4457,4458,4459,4460,4461,4462,4463,4464,4465,4466,4467,4468,4469,4470,4471,4472,4473,4474,4475,4476,4477,4478,4479,4480,4481,4482,4483,4484,4485,4486,4487,4488,4489,4490,4491,4492,4493,4494,4495,4496,4497,4498,4499,4500,4501,4502,4503,4504,4505,4506,4507,4508,4509,4510,4511,4512,4513,4514,4515,4516,4517,4518,4519,4520,4521,4522,4523,4524,4525,4526,4527,4528,4529,4530,4531,4532,4533,4534,4535,4536,4537,4538,4539,4540,4541,4542,4543,4544,4545,4546,4547,4548,4549,4550,4551,4552,4553,4554,4555,4556,4557,4558,4559,4560,4561,4562,4563,4564,4565,4566,4567,4568,4569,4570,4571,4572,4573,4574,4575,4576,4577,4578,4579,4580,4581,4582,4583,4584,4585,4586,4587,4588,4589,4590,4591,4592,4593,4594,4595,4596,4597,4598,4599,4600,4601,4602,4603,4604,4605,4606,4607,4608,4609,4610,4611,4612,4613,4614,4615,4616,4617,4618,4619,4620,4621,4622,4623,4624,4625,4626,4627,4628,4629,4630,4631,4632,4633,4634,4635,4636,4637,4638,4639,4640,4641,4642,4643,4644,4645,4646,4647,4648,4649,4650,4651,4652,4653,4654,4655,4656,4657,4658,4659,4660,4661,4662,4663,4664,4665,4666,4667,4668,4669,4670,4671,4672,4673,4674,4675,4676,4677,4678,4679,4680,4682,4683,4684,4685,4688,4689,4690,4691,4692,4693,4694,4696,4698,4699,4700,4701,4704,4705,4706,4707,4708,4709,4710,4711,4712,4713,4714,4715,4716,4717,4718,4719,4720,4721,4722,4723,4724,4725,4726,4727,4728,4729,4730,4731,4732,4733,4734,4735,4736,4737,4738,4739,4740,4741,4742,4743,4744,4746,4747,4748,4749,4752,4753,4754,4755,4756,4757,4758,4759,4760,4761,4762,4763,4764,4765,4766,4767,4768,4769,4770,4771,4772,4773,4774,4775,4776,4777,4778,4779,4780,4781,4782,4783,4784,4786,4787,4788,4789,4792,4793,4794,4795,4796,4797,4798,4800,4802,4803,4804,4805,4808,4809,4810,4811,4812,4813,4814,4815,4816,4817,4818,4819,4820,4821,4822,4824,4825,4826,4827,4828,4829,4830,4831,4832,4833,4834,4835,4836,4837,4838,4839,4840,4841,4842,4843,4844,4845,4846,4847,4848,4849,4850,4851,4852,4853,4854,4855,4856,4857,4858,4859,4860,4861,4862,4863,4864,4865,4866,4867,4868,4869,4870,4871,4872,4873,4874,4875,4876,4877,4878,4879,4880,4882,4883,4884,4885,4888,4889,4890,4891,4892,4893,4894,4895,4896,4897,4898,4899,4900,4901,4902,4903,4904,4905,4906,4907,4908,4909,4910,4911,4912,4913,4914,4915,4916,4917,4918,4919,4920,4921,4922,4923,4924,4925,4926,4927,4928,4929,4930,4931,4932,4933,4934,4935,4936,4937,4938,4939,4940,4941,4942,4943,4944,4945,4946,4947,4948,4949,4950,4951,4952,4953,4954,4992,4993,4994,4995,4996,4997,4998,4999,5000,5001,5002,5003,5004,5005,5006,5007,5024,5025,5026,5027,5028,5029,5030,5031,5032,5033,5034,5035,5036,5037,5038,5039,5040,5041,5042,5043,5044,5045,5046,5047,5048,5049,5050,5051,5052,5053,5054,5055,5056,5057,5058,5059,5060,5061,5062,5063,5064,5065,5066,5067,5068,5069,5070,5071,5072,5073,5074,5075,5076,5077,5078,5079,5080,5081,5082,5083,5084,5085,5086,5087,5088,5089,5090,5091,5092,5093,5094,5095,5096,5097,5098,5099,5100,5101,5102,5103,5104,5105,5106,5107,5108,5121,5122,5123,5124,5125,5126,5127,5128,5129,5130,5131,5132,5133,5134,5135,5136,5137,5138,5139,5140,5141,5142,5143,5144,5145,5146,5147,5148,5149,5150,5151,5152,5153,5154,5155,5156,5157,5158,5159,5160,5161,5162,5163,5164,5165,5166,5167,5168,5169,5170,5171,5172,5173,5174,5175,5176,5177,5178,5179,5180,5181,5182,5183,5184,5185,5186,5187,5188,5189,5190,5191,5192,5193,5194,5195,5196,5197,5198,5199,5200,5201,5202,5203,5204,5205,5206,5207,5208,5209,5210,5211,5212,5213,5214,5215,5216,5217,5218,5219,5220,5221,5222,5223,5224,5225,5226,5227,5228,5229,5230,5231,5232,5233,5234,5235,5236,5237,5238,5239,5240,5241,5242,5243,5244,5245,5246,5247,5248,5249,5250,5251,5252,5253,5254,5255,5256,5257,5258,5259,5260,5261,5262,5263,5264,5265,5266,5267,5268,5269,5270,5271,5272,5273,5274,5275,5276,5277,5278,5279,5280,5281,5282,5283,5284,5285,5286,5287,5288,5289,5290,5291,5292,5293,5294,5295,5296,5297,5298,5299,5300,5301,5302,5303,5304,5305,5306,5307,5308,5309,5310,5311,5312,5313,5314,5315,5316,5317,5318,5319,5320,5321,5322,5323,5324,5325,5326,5327,5328,5329,5330,5331,5332,5333,5334,5335,5336,5337,5338,5339,5340,5341,5342,5343,5344,5345,5346,5347,5348,5349,5350,5351,5352,5353,5354,5355,5356,5357,5358,5359,5360,5361,5362,5363,5364,5365,5366,5367,5368,5369,5370,5371,5372,5373,5374,5375,5376,5377,5378,5379,5380,5381,5382,5383,5384,5385,5386,5387,5388,5389,5390,5391,5392,5393,5394,5395,5396,5397,5398,5399,5400,5401,5402,5403,5404,5405,5406,5407,5408,5409,5410,5411,5412,5413,5414,5415,5416,5417,5418,5419,5420,5421,5422,5423,5424,5425,5426,5427,5428,5429,5430,5431,5432,5433,5434,5435,5436,5437,5438,5439,5440,5441,5442,5443,5444,5445,5446,5447,5448,5449,5450,5451,5452,5453,5454,5455,5456,5457,5458,5459,5460,5461,5462,5463,5464,5465,5466,5467,5468,5469,5470,5471,5472,5473,5474,5475,5476,5477,5478,5479,5480,5481,5482,5483,5484,5485,5486,5487,5488,5489,5490,5491,5492,5493,5494,5495,5496,5497,5498,5499,5500,5501,5502,5503,5504,5505,5506,5507,5508,5509,5510,5511,5512,5513,5514,5515,5516,5517,5518,5519,5520,5521,5522,5523,5524,5525,5526,5527,5528,5529,5530,5531,5532,5533,5534,5535,5536,5537,5538,5539,5540,5541,5542,5543,5544,5545,5546,5547,5548,5549,5550,5551,5552,5553,5554,5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568,5569,5570,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584,5585,5586,5587,5588,5589,5590,5591,5592,5593,5594,5595,5596,5597,5598,5599,5600,5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,5615,5616,5617,5618,5619,5620,5621,5622,5623,5624,5625,5626,5627,5628,5629,5630,5631,5632,5633,5634,5635,5636,5637,5638,5639,5640,5641,5642,5643,5644,5645,5646,5647,5648,5649,5650,5651,5652,5653,5654,5655,5656,5657,5658,5659,5660,5661,5662,5663,5664,5665,5666,5667,5668,5669,5670,5671,5672,5673,5674,5675,5676,5677,5678,5679,5680,5681,5682,5683,5684,5685,5686,5687,5688,5689,5690,5691,5692,5693,5694,5695,5696,5697,5698,5699,5700,5701,5702,5703,5704,5705,5706,5707,5708,5709,5710,5711,5712,5713,5714,5715,5716,5717,5718,5719,5720,5721,5722,5723,5724,5725,5726,5727,5728,5729,5730,5731,5732,5733,5734,5735,5736,5737,5738,5739,5740,5743,5744,5745,5746,5747,5748,5749,5750,5751,5752,5753,5754,5755,5756,5757,5758,5759,5761,5762,5763,5764,5765,5766,5767,5768,5769,5770,5771,5772,5773,5774,5775,5776,5777,5778,5779,5780,5781,5782,5783,5784,5785,5786,5792,5793,5794,5795,5796,5797,5798,5799,5800,5801,5802,5803,5804,5805,5806,5807,5808,5809,5810,5811,5812,5813,5814,5815,5816,5817,5818,5819,5820,5821,5822,5823,5824,5825,5826,5827,5828,5829,5830,5831,5832,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,5843,5844,5845,5846,5847,5848,5849,5850,5851,5852,5853,5854,5855,5856,5857,5858,5859,5860,5861,5862,5863,5864,5865,5866,5870,5871,5872,5888,5889,5890,5891,5892,5893,5894,5895,5896,5897,5898,5899,5900,5902,5903,5904,5905,5920,5921,5922,5923,5924,5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,5936,5937,5952,5953,5954,5955,5956,5957,5958,5959,5960,5961,5962,5963,5964,5965,5966,5967,5968,5969,5984,5985,5986,5987,5988,5989,5990,5991,5992,5993,5994,5995,5996,5998,5999,6000,6016,6017,6018,6019,6020,6021,6022,6023,6024,6025,6026,6027,6028,6029,6030,6031,6032,6033,6034,6035,6036,6037,6038,6039,6040,6041,6042,6043,6044,6045,6046,6047,6048,6049,6050,6051,6052,6053,6054,6055,6056,6057,6058,6059,6060,6061,6062,6063,6064,6065,6066,6067,6103,6108,6176,6177,6178,6179,6180,6181,6182,6183,6184,6185,6186,6187,6188,6189,6190,6191,6192,6193,6194,6195,6196,6197,6198,6199,6200,6201,6202,6203,6204,6205,6206,6207,6208,6209,6210,6211,6212,6213,6214,6215,6216,6217,6218,6219,6220,6221,6222,6223,6224,6225,6226,6227,6228,6229,6230,6231,6232,6233,6234,6235,6236,6237,6238,6239,6240,6241,6242,6243,6244,6245,6246,6247,6248,6249,6250,6251,6252,6253,6254,6255,6256,6257,6258,6259,6260,6261,6262,6263,6272,6273,6274,6275,6276,6277,6278,6279,6280,6281,6282,6283,6284,6285,6286,6287,6288,6289,6290,6291,6292,6293,6294,6295,6296,6297,6298,6299,6300,6301,6302,6303,6304,6305,6306,6307,6308,6309,6310,6311,6312,6314,6320,6321,6322,6323,6324,6325,6326,6327,6328,6329,6330,6331,6332,6333,6334,6335,6336,6337,6338,6339,6340,6341,6342,6343,6344,6345,6346,6347,6348,6349,6350,6351,6352,6353,6354,6355,6356,6357,6358,6359,6360,6361,6362,6363,6364,6365,6366,6367,6368,6369,6370,6371,6372,6373,6374,6375,6376,6377,6378,6379,6380,6381,6382,6383,6384,6385,6386,6387,6388,6389,6400,6401,6402,6403,6404,6405,6406,6407,6408,6409,6410,6411,6412,6413,6414,6415,6416,6417,6418,6419,6420,6421,6422,6423,6424,6425,6426,6427,6428,6480,6481,6482,6483,6484,6485,6486,6487,6488,6489,6490,6491,6492,6493,6494,6495,6496,6497,6498,6499,6500,6501,6502,6503,6504,6505,6506,6507,6508,6509,6512,6513,6514,6515,6516,6528,6529,6530,6531,6532,6533,6534,6535,6536,6537,6538,6539,6540,6541,6542,6543,6544,6545,6546,6547,6548,6549,6550,6551,6552,6553,6554,6555,6556,6557,6558,6559,6560,6561,6562,6563,6564,6565,6566,6567,6568,6569,6570,6571,6593,6594,6595,6596,6597,6598,6599,6656,6657,6658,6659,6660,6661,6662,6663,6664,6665,6666,6667,6668,6669,6670,6671,6672,6673,6674,6675,6676,6677,6678,6688,6689,6690,6691,6692,6693,6694,6695,6696,6697,6698,6699,6700,6701,6702,6703,6704,6705,6706,6707,6708,6709,6710,6711,6712,6713,6714,6715,6716,6717,6718,6719,6720,6721,6722,6723,6724,6725,6726,6727,6728,6729,6730,6731,6732,6733,6734,6735,6736,6737,6738,6739,6740,6823,6917,6918,6919,6920,6921,6922,6923,6924,6925,6926,6927,6928,6929,6930,6931,6932,6933,6934,6935,6936,6937,6938,6939,6940,6941,6942,6943,6944,6945,6946,6947,6948,6949,6950,6951,6952,6953,6954,6955,6956,6957,6958,6959,6960,6961,6962,6963,6981,6982,6983,6984,6985,6986,6987,7043,7044,7045,7046,7047,7048,7049,7050,7051,7052,7053,7054,7055,7056,7057,7058,7059,7060,7061,7062,7063,7064,7065,7066,7067,7068,7069,7070,7071,7072,7086,7087,7098,7099,7100,7101,7102,7103,7104,7105,7106,7107,7108,7109,7110,7111,7112,7113,7114,7115,7116,7117,7118,7119,7120,7121,7122,7123,7124,7125,7126,7127,7128,7129,7130,7131,7132,7133,7134,7135,7136,7137,7138,7139,7140,7141,7168,7169,7170,7171,7172,7173,7174,7175,7176,7177,7178,7179,7180,7181,7182,7183,7184,7185,7186,7187,7188,7189,7190,7191,7192,7193,7194,7195,7196,7197,7198,7199,7200,7201,7202,7203,7245,7246,7247,7258,7259,7260,7261,7262,7263,7264,7265,7266,7267,7268,7269,7270,7271,7272,7273,7274,7275,7276,7277,7278,7279,7280,7281,7282,7283,7284,7285,7286,7287,7288,7289,7290,7291,7292,7293,7401,7402,7403,7404,7406,7407,7408,7409,7413,7414,7424,7425,7426,7427,7428,7429,7430,7431,7432,7433,7434,7435,7436,7437,7438,7439,7440,7441,7442,7443,7444,7445,7446,7447,7448,7449,7450,7451,7452,7453,7454,7455,7456,7457,7458,7459,7460,7461,7462,7463,7464,7465,7466,7467,7468,7469,7470,7471,7472,7473,7474,7475,7476,7477,7478,7479,7480,7481,7482,7483,7484,7485,7486,7487,7488,7489,7490,7491,7492,7493,7494,7495,7496,7497,7498,7499,7500,7501,7502,7503,7504,7505,7506,7507,7508,7509,7510,7511,7512,7513,7514,7515,7516,7517,7518,7519,7520,7521,7522,7523,7524,7525,7526,7527,7528,7529,7530,7531,7532,7533,7534,7535,7536,7537,7538,7539,7540,7541,7542,7543,7544,7545,7546,7547,7548,7549,7550,7551,7552,7553,7554,7555,7556,7557,7558,7559,7560,7561,7562,7563,7564,7565,7566,7567,7568,7569,7570,7571,7572,7573,7574,7575,7576,7577,7578,7579,7580,7581,7582,7583,7584,7585,7586,7587,7588,7589,7590,7591,7592,7593,7594,7595,7596,7597,7598,7599,7600,7601,7602,7603,7604,7605,7606,7607,7608,7609,7610,7611,7612,7613,7614,7615,7680,7681,7682,7683,7684,7685,7686,7687,7688,7689,7690,7691,7692,7693,7694,7695,7696,7697,7698,7699,7700,7701,7702,7703,7704,7705,7706,7707,7708,7709,7710,7711,7712,7713,7714,7715,7716,7717,7718,7719,7720,7721,7722,7723,7724,7725,7726,7727,7728,7729,7730,7731,7732,7733,7734,7735,7736,7737,7738,7739,7740,7741,7742,7743,7744,7745,7746,7747,7748,7749,7750,7751,7752,7753,7754,7755,7756,7757,7758,7759,7760,7761,7762,7763,7764,7765,7766,7767,7768,7769,7770,7771,7772,7773,7774,7775,7776,7777,7778,7779,7780,7781,7782,7783,7784,7785,7786,7787,7788,7789,7790,7791,7792,7793,7794,7795,7796,7797,7798,7799,7800,7801,7802,7803,7804,7805,7806,7807,7808,7809,7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823,7824,7825,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839,7840,7841,7842,7843,7844,7845,7846,7847,7848,7849,7850,7851,7852,7853,7854,7855,7856,7857,7858,7859,7860,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870,7871,7872,7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886,7887,7888,7889,7890,7891,7892,7893,7894,7895,7896,7897,7898,7899,7900,7901,7902,7903,7904,7905,7906,7907,7908,7909,7910,7911,7912,7913,7914,7915,7916,7917,7918,7919,7920,7921,7922,7923,7924,7925,7926,7927,7928,7929,7930,7931,7932,7933,7934,7935,7936,7937,7938,7939,7940,7941,7942,7943,7944,7945,7946,7947,7948,7949,7950,7951,7952,7953,7954,7955,7956,7957,7960,7961,7962,7963,7964,7965,7968,7969,7970,7971,7972,7973,7974,7975,7976,7977,7978,7979,7980,7981,7982,7983,7984,7985,7986,7987,7988,7989,7990,7991,7992,7993,7994,7995,7996,7997,7998,7999,8000,8001,8002,8003,8004,8005,8008,8009,8010,8011,8012,8013,8016,8017,8018,8019,8020,8021,8022,8023,8025,8027,8029,8031,8032,8033,8034,8035,8036,8037,8038,8039,8040,8041,8042,8043,8044,8045,8046,8047,8048,8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8064,8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079,8080,8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095,8096,8097,8098,8099,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110,8111,8112,8113,8114,8115,8116,8118,8119,8120,8121,8122,8123,8124,8126,8130,8131,8132,8134,8135,8136,8137,8138,8139,8140,8144,8145,8146,8147,8150,8151,8152,8153,8154,8155,8160,8161,8162,8163,8164,8165,8166,8167,8168,8169,8170,8171,8172,8178,8179,8180,8182,8183,8184,8185,8186,8187,8188,8305,8319,8336,8337,8338,8339,8340,8341,8342,8343,8344,8345,8346,8347,8348,8450,8455,8458,8459,8460,8461,8462,8463,8464,8465,8466,8467,8469,8473,8474,8475,8476,8477,8484,8486,8488,8490,8491,8492,8493,8495,8496,8497,8498,8499,8500,8501,8502,8503,8504,8505,8508,8509,8510,8511,8517,8518,8519,8520,8521,8526,8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,8554,8555,8556,8557,8558,8559,8560,8561,8562,8563,8564,8565,8566,8567,8568,8569,8570,8571,8572,8573,8574,8575,8576,8577,8578,8579,8580,8581,8582,8583,8584,11264,11265,11266,11267,11268,11269,11270,11271,11272,11273,11274,11275,11276,11277,11278,11279,11280,11281,11282,11283,11284,11285,11286,11287,11288,11289,11290,11291,11292,11293,11294,11295,11296,11297,11298,11299,11300,11301,11302,11303,11304,11305,11306,11307,11308,11309,11310,11312,11313,11314,11315,11316,11317,11318,11319,11320,11321,11322,11323,11324,11325,11326,11327,11328,11329,11330,11331,11332,11333,11334,11335,11336,11337,11338,11339,11340,11341,11342,11343,11344,11345,11346,11347,11348,11349,11350,11351,11352,11353,11354,11355,11356,11357,11358,11360,11361,11362,11363,11364,11365,11366,11367,11368,11369,11370,11371,11372,11373,11374,11375,11376,11377,11378,11379,11380,11381,11382,11383,11384,11385,11386,11387,11388,11389,11390,11391,11392,11393,11394,11395,11396,11397,11398,11399,11400,11401,11402,11403,11404,11405,11406,11407,11408,11409,11410,11411,11412,11413,11414,11415,11416,11417,11418,11419,11420,11421,11422,11423,11424,11425,11426,11427,11428,11429,11430,11431,11432,11433,11434,11435,11436,11437,11438,11439,11440,11441,11442,11443,11444,11445,11446,11447,11448,11449,11450,11451,11452,11453,11454,11455,11456,11457,11458,11459,11460,11461,11462,11463,11464,11465,11466,11467,11468,11469,11470,11471,11472,11473,11474,11475,11476,11477,11478,11479,11480,11481,11482,11483,11484,11485,11486,11487,11488,11489,11490,11491,11492,11499,11500,11501,11502,11506,11507,11520,11521,11522,11523,11524,11525,11526,11527,11528,11529,11530,11531,11532,11533,11534,11535,11536,11537,11538,11539,11540,11541,11542,11543,11544,11545,11546,11547,11548,11549,11550,11551,11552,11553,11554,11555,11556,11557,11559,11565,11568,11569,11570,11571,11572,11573,11574,11575,11576,11577,11578,11579,11580,11581,11582,11583,11584,11585,11586,11587,11588,11589,11590,11591,11592,11593,11594,11595,11596,11597,11598,11599,11600,11601,11602,11603,11604,11605,11606,11607,11608,11609,11610,11611,11612,11613,11614,11615,11616,11617,11618,11619,11620,11621,11622,11623,11631,11648,11649,11650,11651,11652,11653,11654,11655,11656,11657,11658,11659,11660,11661,11662,11663,11664,11665,11666,11667,11668,11669,11670,11680,11681,11682,11683,11684,11685,11686,11688,11689,11690,11691,11692,11693,11694,11696,11697,11698,11699,11700,11701,11702,11704,11705,11706,11707,11708,11709,11710,11712,11713,11714,11715,11716,11717,11718,11720,11721,11722,11723,11724,11725,11726,11728,11729,11730,11731,11732,11733,11734,11736,11737,11738,11739,11740,11741,11742,11823,12293,12294,12295,12321,12322,12323,12324,12325,12326,12327,12328,12329,12337,12338,12339,12340,12341,12344,12345,12346,12347,12348,12353,12354,12355,12356,12357,12358,12359,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369,12370,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384,12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400,12401,12402,12403,12404,12405,12406,12407,12408,12409,12410,12411,12412,12413,12414,12415,12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431,12432,12433,12434,12435,12436,12437,12438,12445,12446,12447,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462,12463,12464,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477,12478,12479,12480,12481,12482,12483,12484,12485,12486,12487,12488,12489,12490,12491,12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507,12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523,12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,12535,12536,12537,12538,12540,12541,12542,12543,12549,12550,12551,12552,12553,12554,12555,12556,12557,12558,12559,12560,12561,12562,12563,12564,12565,12566,12567,12568,12569,12570,12571,12572,12573,12574,12575,12576,12577,12578,12579,12580,12581,12582,12583,12584,12585,12586,12587,12588,12589,12593,12594,12595,12596,12597,12598,12599,12600,12601,12602,12603,12604,12605,12606,12607,12608,12609,12610,12611,12612,12613,12614,12615,12616,12617,12618,12619,12620,12621,12622,12623,12624,12625,12626,12627,12628,12629,12630,12631,12632,12633,12634,12635,12636,12637,12638,12639,12640,12641,12642,12643,12644,12645,12646,12647,12648,12649,12650,12651,12652,12653,12654,12655,12656,12657,12658,12659,12660,12661,12662,12663,12664,12665,12666,12667,12668,12669,12670,12671,12672,12673,12674,12675,12676,12677,12678,12679,12680,12681,12682,12683,12684,12685,12686,12704,12705,12706,12707,12708,12709,12710,12711,12712,12713,12714,12715,12716,12717,12718,12719,12720,12721,12722,12723,12724,12725,12726,12727,12728,12729,12730,12784,12785,12786,12787,12788,12789,12790,12791,12792,12793,12794,12795,12796,12797,12798,12799,13312,13313,13314,13315,13316,13317,13318,13319,13320,13321,13322,13323,13324,13325,13326,13327,13328,13329,13330,13331,13332,13333,13334,13335,13336,13337,13338,13339,13340,13341,13342,13343,13344,13345,13346,13347,13348,13349,13350,13351,13352,13353,13354,13355,13356,13357,13358,13359,13360,13361,13362,13363,13364,13365,13366,13367,13368,13369,13370,13371,13372,13373,13374,13375,13376,13377,13378,13379,13380,13381,13382,13383,13384,13385,13386,13387,13388,13389,13390,13391,13392,13393,13394,13395,13396,13397,13398,13399,13400,13401,13402,13403,13404,13405,13406,13407,13408,13409,13410,13411,13412,13413,13414,13415,13416,13417,13418,13419,13420,13421,13422,13423,13424,13425,13426,13427,13428,13429,13430,13431,13432,13433,13434,13435,13436,13437,13438,13439,13440,13441,13442,13443,13444,13445,13446,13447,13448,13449,13450,13451,13452,13453,13454,13455,13456,13457,13458,13459,13460,13461,13462,13463,13464,13465,13466,13467,13468,13469,13470,13471,13472,13473,13474,13475,13476,13477,13478,13479,13480,13481,13482,13483,13484,13485,13486,13487,13488,13489,13490,13491,13492,13493,13494,13495,13496,13497,13498,13499,13500,13501,13502,13503,13504,13505,13506,13507,13508,13509,13510,13511,13512,13513,13514,13515,13516,13517,13518,13519,13520,13521,13522,13523,13524,13525,13526,13527,13528,13529,13530,13531,13532,13533,13534,13535,13536,13537,13538,13539,13540,13541,13542,13543,13544,13545,13546,13547,13548,13549,13550,13551,13552,13553,13554,13555,13556,13557,13558,13559,13560,13561,13562,13563,13564,13565,13566,13567,13568,13569,13570,13571,13572,13573,13574,13575,13576,13577,13578,13579,13580,13581,13582,13583,13584,13585,13586,13587,13588,13589,13590,13591,13592,13593,13594,13595,13596,13597,13598,13599,13600,13601,13602,13603,13604,13605,13606,13607,13608,13609,13610,13611,13612,13613,13614,13615,13616,13617,13618,13619,13620,13621,13622,13623,13624,13625,13626,13627,13628,13629,13630,13631,13632,13633,13634,13635,13636,13637,13638,13639,13640,13641,13642,13643,13644,13645,13646,13647,13648,13649,13650,13651,13652,13653,13654,13655,13656,13657,13658,13659,13660,13661,13662,13663,13664,13665,13666,13667,13668,13669,13670,13671,13672,13673,13674,13675,13676,13677,13678,13679,13680,13681,13682,13683,13684,13685,13686,13687,13688,13689,13690,13691,13692,13693,13694,13695,13696,13697,13698,13699,13700,13701,13702,13703,13704,13705,13706,13707,13708,13709,13710,13711,13712,13713,13714,13715,13716,13717,13718,13719,13720,13721,13722,13723,13724,13725,13726,13727,13728,13729,13730,13731,13732,13733,13734,13735,13736,13737,13738,13739,13740,13741,13742,13743,13744,13745,13746,13747,13748,13749,13750,13751,13752,13753,13754,13755,13756,13757,13758,13759,13760,13761,13762,13763,13764,13765,13766,13767,13768,13769,13770,13771,13772,13773,13774,13775,13776,13777,13778,13779,13780,13781,13782,13783,13784,13785,13786,13787,13788,13789,13790,13791,13792,13793,13794,13795,13796,13797,13798,13799,13800,13801,13802,13803,13804,13805,13806,13807,13808,13809,13810,13811,13812,13813,13814,13815,13816,13817,13818,13819,13820,13821,13822,13823,13824,13825,13826,13827,13828,13829,13830,13831,13832,13833,13834,13835,13836,13837,13838,13839,13840,13841,13842,13843,13844,13845,13846,13847,13848,13849,13850,13851,13852,13853,13854,13855,13856,13857,13858,13859,13860,13861,13862,13863,13864,13865,13866,13867,13868,13869,13870,13871,13872,13873,13874,13875,13876,13877,13878,13879,13880,13881,13882,13883,13884,13885,13886,13887,13888,13889,13890,13891,13892,13893,13894,13895,13896,13897,13898,13899,13900,13901,13902,13903,13904,13905,13906,13907,13908,13909,13910,13911,13912,13913,13914,13915,13916,13917,13918,13919,13920,13921,13922,13923,13924,13925,13926,13927,13928,13929,13930,13931,13932,13933,13934,13935,13936,13937,13938,13939,13940,13941,13942,13943,13944,13945,13946,13947,13948,13949,13950,13951,13952,13953,13954,13955,13956,13957,13958,13959,13960,13961,13962,13963,13964,13965,13966,13967,13968,13969,13970,13971,13972,13973,13974,13975,13976,13977,13978,13979,13980,13981,13982,13983,13984,13985,13986,13987,13988,13989,13990,13991,13992,13993,13994,13995,13996,13997,13998,13999,14000,14001,14002,14003,14004,14005,14006,14007,14008,14009,14010,14011,14012,14013,14014,14015,14016,14017,14018,14019,14020,14021,14022,14023,14024,14025,14026,14027,14028,14029,14030,14031,14032,14033,14034,14035,14036,14037,14038,14039,14040,14041,14042,14043,14044,14045,14046,14047,14048,14049,14050,14051,14052,14053,14054,14055,14056,14057,14058,14059,14060,14061,14062,14063,14064,14065,14066,14067,14068,14069,14070,14071,14072,14073,14074,14075,14076,14077,14078,14079,14080,14081,14082,14083,14084,14085,14086,14087,14088,14089,14090,14091,14092,14093,14094,14095,14096,14097,14098,14099,14100,14101,14102,14103,14104,14105,14106,14107,14108,14109,14110,14111,14112,14113,14114,14115,14116,14117,14118,14119,14120,14121,14122,14123,14124,14125,14126,14127,14128,14129,14130,14131,14132,14133,14134,14135,14136,14137,14138,14139,14140,14141,14142,14143,14144,14145,14146,14147,14148,14149,14150,14151,14152,14153,14154,14155,14156,14157,14158,14159,14160,14161,14162,14163,14164,14165,14166,14167,14168,14169,14170,14171,14172,14173,14174,14175,14176,14177,14178,14179,14180,14181,14182,14183,14184,14185,14186,14187,14188,14189,14190,14191,14192,14193,14194,14195,14196,14197,14198,14199,14200,14201,14202,14203,14204,14205,14206,14207,14208,14209,14210,14211,14212,14213,14214,14215,14216,14217,14218,14219,14220,14221,14222,14223,14224,14225,14226,14227,14228,14229,14230,14231,14232,14233,14234,14235,14236,14237,14238,14239,14240,14241,14242,14243,14244,14245,14246,14247,14248,14249,14250,14251,14252,14253,14254,14255,14256,14257,14258,14259,14260,14261,14262,14263,14264,14265,14266,14267,14268,14269,14270,14271,14272,14273,14274,14275,14276,14277,14278,14279,14280,14281,14282,14283,14284,14285,14286,14287,14288,14289,14290,14291,14292,14293,14294,14295,14296,14297,14298,14299,14300,14301,14302,14303,14304,14305,14306,14307,14308,14309,14310,14311,14312,14313,14314,14315,14316,14317,14318,14319,14320,14321,14322,14323,14324,14325,14326,14327,14328,14329,14330,14331,14332,14333,14334,14335,14336,14337,14338,14339,14340,14341,14342,14343,14344,14345,14346,14347,14348,14349,14350,14351,14352,14353,14354,14355,14356,14357,14358,14359,14360,14361,14362,14363,14364,14365,14366,14367,14368,14369,14370,14371,14372,14373,14374,14375,14376,14377,14378,14379,14380,14381,14382,14383,14384,14385,14386,14387,14388,14389,14390,14391,14392,14393,14394,14395,14396,14397,14398,14399,14400,14401,14402,14403,14404,14405,14406,14407,14408,14409,14410,14411,14412,14413,14414,14415,14416,14417,14418,14419,14420,14421,14422,14423,14424,14425,14426,14427,14428,14429,14430,14431,14432,14433,14434,14435,14436,14437,14438,14439,14440,14441,14442,14443,14444,14445,14446,14447,14448,14449,14450,14451,14452,14453,14454,14455,14456,14457,14458,14459,14460,14461,14462,14463,14464,14465,14466,14467,14468,14469,14470,14471,14472,14473,14474,14475,14476,14477,14478,14479,14480,14481,14482,14483,14484,14485,14486,14487,14488,14489,14490,14491,14492,14493,14494,14495,14496,14497,14498,14499,14500,14501,14502,14503,14504,14505,14506,14507,14508,14509,14510,14511,14512,14513,14514,14515,14516,14517,14518,14519,14520,14521,14522,14523,14524,14525,14526,14527,14528,14529,14530,14531,14532,14533,14534,14535,14536,14537,14538,14539,14540,14541,14542,14543,14544,14545,14546,14547,14548,14549,14550,14551,14552,14553,14554,14555,14556,14557,14558,14559,14560,14561,14562,14563,14564,14565,14566,14567,14568,14569,14570,14571,14572,14573,14574,14575,14576,14577,14578,14579,14580,14581,14582,14583,14584,14585,14586,14587,14588,14589,14590,14591,14592,14593,14594,14595,14596,14597,14598,14599,14600,14601,14602,14603,14604,14605,14606,14607,14608,14609,14610,14611,14612,14613,14614,14615,14616,14617,14618,14619,14620,14621,14622,14623,14624,14625,14626,14627,14628,14629,14630,14631,14632,14633,14634,14635,14636,14637,14638,14639,14640,14641,14642,14643,14644,14645,14646,14647,14648,14649,14650,14651,14652,14653,14654,14655,14656,14657,14658,14659,14660,14661,14662,14663,14664,14665,14666,14667,14668,14669,14670,14671,14672,14673,14674,14675,14676,14677,14678,14679,14680,14681,14682,14683,14684,14685,14686,14687,14688,14689,14690,14691,14692,14693,14694,14695,14696,14697,14698,14699,14700,14701,14702,14703,14704,14705,14706,14707,14708,14709,14710,14711,14712,14713,14714,14715,14716,14717,14718,14719,14720,14721,14722,14723,14724,14725,14726,14727,14728,14729,14730,14731,14732,14733,14734,14735,14736,14737,14738,14739,14740,14741,14742,14743,14744,14745,14746,14747,14748,14749,14750,14751,14752,14753,14754,14755,14756,14757,14758,14759,14760,14761,14762,14763,14764,14765,14766,14767,14768,14769,14770,14771,14772,14773,14774,14775,14776,14777,14778,14779,14780,14781,14782,14783,14784,14785,14786,14787,14788,14789,14790,14791,14792,14793,14794,14795,14796,14797,14798,14799,14800,14801,14802,14803,14804,14805,14806,14807,14808,14809,14810,14811,14812,14813,14814,14815,14816,14817,14818,14819,14820,14821,14822,14823,14824,14825,14826,14827,14828,14829,14830,14831,14832,14833,14834,14835,14836,14837,14838,14839,14840,14841,14842,14843,14844,14845,14846,14847,14848,14849,14850,14851,14852,14853,14854,14855,14856,14857,14858,14859,14860,14861,14862,14863,14864,14865,14866,14867,14868,14869,14870,14871,14872,14873,14874,14875,14876,14877,14878,14879,14880,14881,14882,14883,14884,14885,14886,14887,14888,14889,14890,14891,14892,14893,14894,14895,14896,14897,14898,14899,14900,14901,14902,14903,14904,14905,14906,14907,14908,14909,14910,14911,14912,14913,14914,14915,14916,14917,14918,14919,14920,14921,14922,14923,14924,14925,14926,14927,14928,14929,14930,14931,14932,14933,14934,14935,14936,14937,14938,14939,14940,14941,14942,14943,14944,14945,14946,14947,14948,14949,14950,14951,14952,14953,14954,14955,14956,14957,14958,14959,14960,14961,14962,14963,14964,14965,14966,14967,14968,14969,14970,14971,14972,14973,14974,14975,14976,14977,14978,14979,14980,14981,14982,14983,14984,14985,14986,14987,14988,14989,14990,14991,14992,14993,14994,14995,14996,14997,14998,14999,15000,15001,15002,15003,15004,15005,15006,15007,15008,15009,15010,15011,15012,15013,15014,15015,15016,15017,15018,15019,15020,15021,15022,15023,15024,15025,15026,15027,15028,15029,15030,15031,15032,15033,15034,15035,15036,15037,15038,15039,15040,15041,15042,15043,15044,15045,15046,15047,15048,15049,15050,15051,15052,15053,15054,15055,15056,15057,15058,15059,15060,15061,15062,15063,15064,15065,15066,15067,15068,15069,15070,15071,15072,15073,15074,15075,15076,15077,15078,15079,15080,15081,15082,15083,15084,15085,15086,15087,15088,15089,15090,15091,15092,15093,15094,15095,15096,15097,15098,15099,15100,15101,15102,15103,15104,15105,15106,15107,15108,15109,15110,15111,15112,15113,15114,15115,15116,15117,15118,15119,15120,15121,15122,15123,15124,15125,15126,15127,15128,15129,15130,15131,15132,15133,15134,15135,15136,15137,15138,15139,15140,15141,15142,15143,15144,15145,15146,15147,15148,15149,15150,15151,15152,15153,15154,15155,15156,15157,15158,15159,15160,15161,15162,15163,15164,15165,15166,15167,15168,15169,15170,15171,15172,15173,15174,15175,15176,15177,15178,15179,15180,15181,15182,15183,15184,15185,15186,15187,15188,15189,15190,15191,15192,15193,15194,15195,15196,15197,15198,15199,15200,15201,15202,15203,15204,15205,15206,15207,15208,15209,15210,15211,15212,15213,15214,15215,15216,15217,15218,15219,15220,15221,15222,15223,15224,15225,15226,15227,15228,15229,15230,15231,15232,15233,15234,15235,15236,15237,15238,15239,15240,15241,15242,15243,15244,15245,15246,15247,15248,15249,15250,15251,15252,15253,15254,15255,15256,15257,15258,15259,15260,15261,15262,15263,15264,15265,15266,15267,15268,15269,15270,15271,15272,15273,15274,15275,15276,15277,15278,15279,15280,15281,15282,15283,15284,15285,15286,15287,15288,15289,15290,15291,15292,15293,15294,15295,15296,15297,15298,15299,15300,15301,15302,15303,15304,15305,15306,15307,15308,15309,15310,15311,15312,15313,15314,15315,15316,15317,15318,15319,15320,15321,15322,15323,15324,15325,15326,15327,15328,15329,15330,15331,15332,15333,15334,15335,15336,15337,15338,15339,15340,15341,15342,15343,15344,15345,15346,15347,15348,15349,15350,15351,15352,15353,15354,15355,15356,15357,15358,15359,15360,15361,15362,15363,15364,15365,15366,15367,15368,15369,15370,15371,15372,15373,15374,15375,15376,15377,15378,15379,15380,15381,15382,15383,15384,15385,15386,15387,15388,15389,15390,15391,15392,15393,15394,15395,15396,15397,15398,15399,15400,15401,15402,15403,15404,15405,15406,15407,15408,15409,15410,15411,15412,15413,15414,15415,15416,15417,15418,15419,15420,15421,15422,15423,15424,15425,15426,15427,15428,15429,15430,15431,15432,15433,15434,15435,15436,15437,15438,15439,15440,15441,15442,15443,15444,15445,15446,15447,15448,15449,15450,15451,15452,15453,15454,15455,15456,15457,15458,15459,15460,15461,15462,15463,15464,15465,15466,15467,15468,15469,15470,15471,15472,15473,15474,15475,15476,15477,15478,15479,15480,15481,15482,15483,15484,15485,15486,15487,15488,15489,15490,15491,15492,15493,15494,15495,15496,15497,15498,15499,15500,15501,15502,15503,15504,15505,15506,15507,15508,15509,15510,15511,15512,15513,15514,15515,15516,15517,15518,15519,15520,15521,15522,15523,15524,15525,15526,15527,15528,15529,15530,15531,15532,15533,15534,15535,15536,15537,15538,15539,15540,15541,15542,15543,15544,15545,15546,15547,15548,15549,15550,15551,15552,15553,15554,15555,15556,15557,15558,15559,15560,15561,15562,15563,15564,15565,15566,15567,15568,15569,15570,15571,15572,15573,15574,15575,15576,15577,15578,15579,15580,15581,15582,15583,15584,15585,15586,15587,15588,15589,15590,15591,15592,15593,15594,15595,15596,15597,15598,15599,15600,15601,15602,15603,15604,15605,15606,15607,15608,15609,15610,15611,15612,15613,15614,15615,15616,15617,15618,15619,15620,15621,15622,15623,15624,15625,15626,15627,15628,15629,15630,15631,15632,15633,15634,15635,15636,15637,15638,15639,15640,15641,15642,15643,15644,15645,15646,15647,15648,15649,15650,15651,15652,15653,15654,15655,15656,15657,15658,15659,15660,15661,15662,15663,15664,15665,15666,15667,15668,15669,15670,15671,15672,15673,15674,15675,15676,15677,15678,15679,15680,15681,15682,15683,15684,15685,15686,15687,15688,15689,15690,15691,15692,15693,15694,15695,15696,15697,15698,15699,15700,15701,15702,15703,15704,15705,15706,15707,15708,15709,15710,15711,15712,15713,15714,15715,15716,15717,15718,15719,15720,15721,15722,15723,15724,15725,15726,15727,15728,15729,15730,15731,15732,15733,15734,15735,15736,15737,15738,15739,15740,15741,15742,15743,15744,15745,15746,15747,15748,15749,15750,15751,15752,15753,15754,15755,15756,15757,15758,15759,15760,15761,15762,15763,15764,15765,15766,15767,15768,15769,15770,15771,15772,15773,15774,15775,15776,15777,15778,15779,15780,15781,15782,15783,15784,15785,15786,15787,15788,15789,15790,15791,15792,15793,15794,15795,15796,15797,15798,15799,15800,15801,15802,15803,15804,15805,15806,15807,15808,15809,15810,15811,15812,15813,15814,15815,15816,15817,15818,15819,15820,15821,15822,15823,15824,15825,15826,15827,15828,15829,15830,15831,15832,15833,15834,15835,15836,15837,15838,15839,15840,15841,15842,15843,15844,15845,15846,15847,15848,15849,15850,15851,15852,15853,15854,15855,15856,15857,15858,15859,15860,15861,15862,15863,15864,15865,15866,15867,15868,15869,15870,15871,15872,15873,15874,15875,15876,15877,15878,15879,15880,15881,15882,15883,15884,15885,15886,15887,15888,15889,15890,15891,15892,15893,15894,15895,15896,15897,15898,15899,15900,15901,15902,15903,15904,15905,15906,15907,15908,15909,15910,15911,15912,15913,15914,15915,15916,15917,15918,15919,15920,15921,15922,15923,15924,15925,15926,15927,15928,15929,15930,15931,15932,15933,15934,15935,15936,15937,15938,15939,15940,15941,15942,15943,15944,15945,15946,15947,15948,15949,15950,15951,15952,15953,15954,15955,15956,15957,15958,15959,15960,15961,15962,15963,15964,15965,15966,15967,15968,15969,15970,15971,15972,15973,15974,15975,15976,15977,15978,15979,15980,15981,15982,15983,15984,15985,15986,15987,15988,15989,15990,15991,15992,15993,15994,15995,15996,15997,15998,15999,16000,16001,16002,16003,16004,16005,16006,16007,16008,16009,16010,16011,16012,16013,16014,16015,16016,16017,16018,16019,16020,16021,16022,16023,16024,16025,16026,16027,16028,16029,16030,16031,16032,16033,16034,16035,16036,16037,16038,16039,16040,16041,16042,16043,16044,16045,16046,16047,16048,16049,16050,16051,16052,16053,16054,16055,16056,16057,16058,16059,16060,16061,16062,16063,16064,16065,16066,16067,16068,16069,16070,16071,16072,16073,16074,16075,16076,16077,16078,16079,16080,16081,16082,16083,16084,16085,16086,16087,16088,16089,16090,16091,16092,16093,16094,16095,16096,16097,16098,16099,16100,16101,16102,16103,16104,16105,16106,16107,16108,16109,16110,16111,16112,16113,16114,16115,16116,16117,16118,16119,16120,16121,16122,16123,16124,16125,16126,16127,16128,16129,16130,16131,16132,16133,16134,16135,16136,16137,16138,16139,16140,16141,16142,16143,16144,16145,16146,16147,16148,16149,16150,16151,16152,16153,16154,16155,16156,16157,16158,16159,16160,16161,16162,16163,16164,16165,16166,16167,16168,16169,16170,16171,16172,16173,16174,16175,16176,16177,16178,16179,16180,16181,16182,16183,16184,16185,16186,16187,16188,16189,16190,16191,16192,16193,16194,16195,16196,16197,16198,16199,16200,16201,16202,16203,16204,16205,16206,16207,16208,16209,16210,16211,16212,16213,16214,16215,16216,16217,16218,16219,16220,16221,16222,16223,16224,16225,16226,16227,16228,16229,16230,16231,16232,16233,16234,16235,16236,16237,16238,16239,16240,16241,16242,16243,16244,16245,16246,16247,16248,16249,16250,16251,16252,16253,16254,16255,16256,16257,16258,16259,16260,16261,16262,16263,16264,16265,16266,16267,16268,16269,16270,16271,16272,16273,16274,16275,16276,16277,16278,16279,16280,16281,16282,16283,16284,16285,16286,16287,16288,16289,16290,16291,16292,16293,16294,16295,16296,16297,16298,16299,16300,16301,16302,16303,16304,16305,16306,16307,16308,16309,16310,16311,16312,16313,16314,16315,16316,16317,16318,16319,16320,16321,16322,16323,16324,16325,16326,16327,16328,16329,16330,16331,16332,16333,16334,16335,16336,16337,16338,16339,16340,16341,16342,16343,16344,16345,16346,16347,16348,16349,16350,16351,16352,16353,16354,16355,16356,16357,16358,16359,16360,16361,16362,16363,16364,16365,16366,16367,16368,16369,16370,16371,16372,16373,16374,16375,16376,16377,16378,16379,16380,16381,16382,16383,16384,16385,16386,16387,16388,16389,16390,16391,16392,16393,16394,16395,16396,16397,16398,16399,16400,16401,16402,16403,16404,16405,16406,16407,16408,16409,16410,16411,16412,16413,16414,16415,16416,16417,16418,16419,16420,16421,16422,16423,16424,16425,16426,16427,16428,16429,16430,16431,16432,16433,16434,16435,16436,16437,16438,16439,16440,16441,16442,16443,16444,16445,16446,16447,16448,16449,16450,16451,16452,16453,16454,16455,16456,16457,16458,16459,16460,16461,16462,16463,16464,16465,16466,16467,16468,16469,16470,16471,16472,16473,16474,16475,16476,16477,16478,16479,16480,16481,16482,16483,16484,16485,16486,16487,16488,16489,16490,16491,16492,16493,16494,16495,16496,16497,16498,16499,16500,16501,16502,16503,16504,16505,16506,16507,16508,16509,16510,16511,16512,16513,16514,16515,16516,16517,16518,16519,16520,16521,16522,16523,16524,16525,16526,16527,16528,16529,16530,16531,16532,16533,16534,16535,16536,16537,16538,16539,16540,16541,16542,16543,16544,16545,16546,16547,16548,16549,16550,16551,16552,16553,16554,16555,16556,16557,16558,16559,16560,16561,16562,16563,16564,16565,16566,16567,16568,16569,16570,16571,16572,16573,16574,16575,16576,16577,16578,16579,16580,16581,16582,16583,16584,16585,16586,16587,16588,16589,16590,16591,16592,16593,16594,16595,16596,16597,16598,16599,16600,16601,16602,16603,16604,16605,16606,16607,16608,16609,16610,16611,16612,16613,16614,16615,16616,16617,16618,16619,16620,16621,16622,16623,16624,16625,16626,16627,16628,16629,16630,16631,16632,16633,16634,16635,16636,16637,16638,16639,16640,16641,16642,16643,16644,16645,16646,16647,16648,16649,16650,16651,16652,16653,16654,16655,16656,16657,16658,16659,16660,16661,16662,16663,16664,16665,16666,16667,16668,16669,16670,16671,16672,16673,16674,16675,16676,16677,16678,16679,16680,16681,16682,16683,16684,16685,16686,16687,16688,16689,16690,16691,16692,16693,16694,16695,16696,16697,16698,16699,16700,16701,16702,16703,16704,16705,16706,16707,16708,16709,16710,16711,16712,16713,16714,16715,16716,16717,16718,16719,16720,16721,16722,16723,16724,16725,16726,16727,16728,16729,16730,16731,16732,16733,16734,16735,16736,16737,16738,16739,16740,16741,16742,16743,16744,16745,16746,16747,16748,16749,16750,16751,16752,16753,16754,16755,16756,16757,16758,16759,16760,16761,16762,16763,16764,16765,16766,16767,16768,16769,16770,16771,16772,16773,16774,16775,16776,16777,16778,16779,16780,16781,16782,16783,16784,16785,16786,16787,16788,16789,16790,16791,16792,16793,16794,16795,16796,16797,16798,16799,16800,16801,16802,16803,16804,16805,16806,16807,16808,16809,16810,16811,16812,16813,16814,16815,16816,16817,16818,16819,16820,16821,16822,16823,16824,16825,16826,16827,16828,16829,16830,16831,16832,16833,16834,16835,16836,16837,16838,16839,16840,16841,16842,16843,16844,16845,16846,16847,16848,16849,16850,16851,16852,16853,16854,16855,16856,16857,16858,16859,16860,16861,16862,16863,16864,16865,16866,16867,16868,16869,16870,16871,16872,16873,16874,16875,16876,16877,16878,16879,16880,16881,16882,16883,16884,16885,16886,16887,16888,16889,16890,16891,16892,16893,16894,16895,16896,16897,16898,16899,16900,16901,16902,16903,16904,16905,16906,16907,16908,16909,16910,16911,16912,16913,16914,16915,16916,16917,16918,16919,16920,16921,16922,16923,16924,16925,16926,16927,16928,16929,16930,16931,16932,16933,16934,16935,16936,16937,16938,16939,16940,16941,16942,16943,16944,16945,16946,16947,16948,16949,16950,16951,16952,16953,16954,16955,16956,16957,16958,16959,16960,16961,16962,16963,16964,16965,16966,16967,16968,16969,16970,16971,16972,16973,16974,16975,16976,16977,16978,16979,16980,16981,16982,16983,16984,16985,16986,16987,16988,16989,16990,16991,16992,16993,16994,16995,16996,16997,16998,16999,17000,17001,17002,17003,17004,17005,17006,17007,17008,17009,17010,17011,17012,17013,17014,17015,17016,17017,17018,17019,17020,17021,17022,17023,17024,17025,17026,17027,17028,17029,17030,17031,17032,17033,17034,17035,17036,17037,17038,17039,17040,17041,17042,17043,17044,17045,17046,17047,17048,17049,17050,17051,17052,17053,17054,17055,17056,17057,17058,17059,17060,17061,17062,17063,17064,17065,17066,17067,17068,17069,17070,17071,17072,17073,17074,17075,17076,17077,17078,17079,17080,17081,17082,17083,17084,17085,17086,17087,17088,17089,17090,17091,17092,17093,17094,17095,17096,17097,17098,17099,17100,17101,17102,17103,17104,17105,17106,17107,17108,17109,17110,17111,17112,17113,17114,17115,17116,17117,17118,17119,17120,17121,17122,17123,17124,17125,17126,17127,17128,17129,17130,17131,17132,17133,17134,17135,17136,17137,17138,17139,17140,17141,17142,17143,17144,17145,17146,17147,17148,17149,17150,17151,17152,17153,17154,17155,17156,17157,17158,17159,17160,17161,17162,17163,17164,17165,17166,17167,17168,17169,17170,17171,17172,17173,17174,17175,17176,17177,17178,17179,17180,17181,17182,17183,17184,17185,17186,17187,17188,17189,17190,17191,17192,17193,17194,17195,17196,17197,17198,17199,17200,17201,17202,17203,17204,17205,17206,17207,17208,17209,17210,17211,17212,17213,17214,17215,17216,17217,17218,17219,17220,17221,17222,17223,17224,17225,17226,17227,17228,17229,17230,17231,17232,17233,17234,17235,17236,17237,17238,17239,17240,17241,17242,17243,17244,17245,17246,17247,17248,17249,17250,17251,17252,17253,17254,17255,17256,17257,17258,17259,17260,17261,17262,17263,17264,17265,17266,17267,17268,17269,17270,17271,17272,17273,17274,17275,17276,17277,17278,17279,17280,17281,17282,17283,17284,17285,17286,17287,17288,17289,17290,17291,17292,17293,17294,17295,17296,17297,17298,17299,17300,17301,17302,17303,17304,17305,17306,17307,17308,17309,17310,17311,17312,17313,17314,17315,17316,17317,17318,17319,17320,17321,17322,17323,17324,17325,17326,17327,17328,17329,17330,17331,17332,17333,17334,17335,17336,17337,17338,17339,17340,17341,17342,17343,17344,17345,17346,17347,17348,17349,17350,17351,17352,17353,17354,17355,17356,17357,17358,17359,17360,17361,17362,17363,17364,17365,17366,17367,17368,17369,17370,17371,17372,17373,17374,17375,17376,17377,17378,17379,17380,17381,17382,17383,17384,17385,17386,17387,17388,17389,17390,17391,17392,17393,17394,17395,17396,17397,17398,17399,17400,17401,17402,17403,17404,17405,17406,17407,17408,17409,17410,17411,17412,17413,17414,17415,17416,17417,17418,17419,17420,17421,17422,17423,17424,17425,17426,17427,17428,17429,17430,17431,17432,17433,17434,17435,17436,17437,17438,17439,17440,17441,17442,17443,17444,17445,17446,17447,17448,17449,17450,17451,17452,17453,17454,17455,17456,17457,17458,17459,17460,17461,17462,17463,17464,17465,17466,17467,17468,17469,17470,17471,17472,17473,17474,17475,17476,17477,17478,17479,17480,17481,17482,17483,17484,17485,17486,17487,17488,17489,17490,17491,17492,17493,17494,17495,17496,17497,17498,17499,17500,17501,17502,17503,17504,17505,17506,17507,17508,17509,17510,17511,17512,17513,17514,17515,17516,17517,17518,17519,17520,17521,17522,17523,17524,17525,17526,17527,17528,17529,17530,17531,17532,17533,17534,17535,17536,17537,17538,17539,17540,17541,17542,17543,17544,17545,17546,17547,17548,17549,17550,17551,17552,17553,17554,17555,17556,17557,17558,17559,17560,17561,17562,17563,17564,17565,17566,17567,17568,17569,17570,17571,17572,17573,17574,17575,17576,17577,17578,17579,17580,17581,17582,17583,17584,17585,17586,17587,17588,17589,17590,17591,17592,17593,17594,17595,17596,17597,17598,17599,17600,17601,17602,17603,17604,17605,17606,17607,17608,17609,17610,17611,17612,17613,17614,17615,17616,17617,17618,17619,17620,17621,17622,17623,17624,17625,17626,17627,17628,17629,17630,17631,17632,17633,17634,17635,17636,17637,17638,17639,17640,17641,17642,17643,17644,17645,17646,17647,17648,17649,17650,17651,17652,17653,17654,17655,17656,17657,17658,17659,17660,17661,17662,17663,17664,17665,17666,17667,17668,17669,17670,17671,17672,17673,17674,17675,17676,17677,17678,17679,17680,17681,17682,17683,17684,17685,17686,17687,17688,17689,17690,17691,17692,17693,17694,17695,17696,17697,17698,17699,17700,17701,17702,17703,17704,17705,17706,17707,17708,17709,17710,17711,17712,17713,17714,17715,17716,17717,17718,17719,17720,17721,17722,17723,17724,17725,17726,17727,17728,17729,17730,17731,17732,17733,17734,17735,17736,17737,17738,17739,17740,17741,17742,17743,17744,17745,17746,17747,17748,17749,17750,17751,17752,17753,17754,17755,17756,17757,17758,17759,17760,17761,17762,17763,17764,17765,17766,17767,17768,17769,17770,17771,17772,17773,17774,17775,17776,17777,17778,17779,17780,17781,17782,17783,17784,17785,17786,17787,17788,17789,17790,17791,17792,17793,17794,17795,17796,17797,17798,17799,17800,17801,17802,17803,17804,17805,17806,17807,17808,17809,17810,17811,17812,17813,17814,17815,17816,17817,17818,17819,17820,17821,17822,17823,17824,17825,17826,17827,17828,17829,17830,17831,17832,17833,17834,17835,17836,17837,17838,17839,17840,17841,17842,17843,17844,17845,17846,17847,17848,17849,17850,17851,17852,17853,17854,17855,17856,17857,17858,17859,17860,17861,17862,17863,17864,17865,17866,17867,17868,17869,17870,17871,17872,17873,17874,17875,17876,17877,17878,17879,17880,17881,17882,17883,17884,17885,17886,17887,17888,17889,17890,17891,17892,17893,17894,17895,17896,17897,17898,17899,17900,17901,17902,17903,17904,17905,17906,17907,17908,17909,17910,17911,17912,17913,17914,17915,17916,17917,17918,17919,17920,17921,17922,17923,17924,17925,17926,17927,17928,17929,17930,17931,17932,17933,17934,17935,17936,17937,17938,17939,17940,17941,17942,17943,17944,17945,17946,17947,17948,17949,17950,17951,17952,17953,17954,17955,17956,17957,17958,17959,17960,17961,17962,17963,17964,17965,17966,17967,17968,17969,17970,17971,17972,17973,17974,17975,17976,17977,17978,17979,17980,17981,17982,17983,17984,17985,17986,17987,17988,17989,17990,17991,17992,17993,17994,17995,17996,17997,17998,17999,18000,18001,18002,18003,18004,18005,18006,18007,18008,18009,18010,18011,18012,18013,18014,18015,18016,18017,18018,18019,18020,18021,18022,18023,18024,18025,18026,18027,18028,18029,18030,18031,18032,18033,18034,18035,18036,18037,18038,18039,18040,18041,18042,18043,18044,18045,18046,18047,18048,18049,18050,18051,18052,18053,18054,18055,18056,18057,18058,18059,18060,18061,18062,18063,18064,18065,18066,18067,18068,18069,18070,18071,18072,18073,18074,18075,18076,18077,18078,18079,18080,18081,18082,18083,18084,18085,18086,18087,18088,18089,18090,18091,18092,18093,18094,18095,18096,18097,18098,18099,18100,18101,18102,18103,18104,18105,18106,18107,18108,18109,18110,18111,18112,18113,18114,18115,18116,18117,18118,18119,18120,18121,18122,18123,18124,18125,18126,18127,18128,18129,18130,18131,18132,18133,18134,18135,18136,18137,18138,18139,18140,18141,18142,18143,18144,18145,18146,18147,18148,18149,18150,18151,18152,18153,18154,18155,18156,18157,18158,18159,18160,18161,18162,18163,18164,18165,18166,18167,18168,18169,18170,18171,18172,18173,18174,18175,18176,18177,18178,18179,18180,18181,18182,18183,18184,18185,18186,18187,18188,18189,18190,18191,18192,18193,18194,18195,18196,18197,18198,18199,18200,18201,18202,18203,18204,18205,18206,18207,18208,18209,18210,18211,18212,18213,18214,18215,18216,18217,18218,18219,18220,18221,18222,18223,18224,18225,18226,18227,18228,18229,18230,18231,18232,18233,18234,18235,18236,18237,18238,18239,18240,18241,18242,18243,18244,18245,18246,18247,18248,18249,18250,18251,18252,18253,18254,18255,18256,18257,18258,18259,18260,18261,18262,18263,18264,18265,18266,18267,18268,18269,18270,18271,18272,18273,18274,18275,18276,18277,18278,18279,18280,18281,18282,18283,18284,18285,18286,18287,18288,18289,18290,18291,18292,18293,18294,18295,18296,18297,18298,18299,18300,18301,18302,18303,18304,18305,18306,18307,18308,18309,18310,18311,18312,18313,18314,18315,18316,18317,18318,18319,18320,18321,18322,18323,18324,18325,18326,18327,18328,18329,18330,18331,18332,18333,18334,18335,18336,18337,18338,18339,18340,18341,18342,18343,18344,18345,18346,18347,18348,18349,18350,18351,18352,18353,18354,18355,18356,18357,18358,18359,18360,18361,18362,18363,18364,18365,18366,18367,18368,18369,18370,18371,18372,18373,18374,18375,18376,18377,18378,18379,18380,18381,18382,18383,18384,18385,18386,18387,18388,18389,18390,18391,18392,18393,18394,18395,18396,18397,18398,18399,18400,18401,18402,18403,18404,18405,18406,18407,18408,18409,18410,18411,18412,18413,18414,18415,18416,18417,18418,18419,18420,18421,18422,18423,18424,18425,18426,18427,18428,18429,18430,18431,18432,18433,18434,18435,18436,18437,18438,18439,18440,18441,18442,18443,18444,18445,18446,18447,18448,18449,18450,18451,18452,18453,18454,18455,18456,18457,18458,18459,18460,18461,18462,18463,18464,18465,18466,18467,18468,18469,18470,18471,18472,18473,18474,18475,18476,18477,18478,18479,18480,18481,18482,18483,18484,18485,18486,18487,18488,18489,18490,18491,18492,18493,18494,18495,18496,18497,18498,18499,18500,18501,18502,18503,18504,18505,18506,18507,18508,18509,18510,18511,18512,18513,18514,18515,18516,18517,18518,18519,18520,18521,18522,18523,18524,18525,18526,18527,18528,18529,18530,18531,18532,18533,18534,18535,18536,18537,18538,18539,18540,18541,18542,18543,18544,18545,18546,18547,18548,18549,18550,18551,18552,18553,18554,18555,18556,18557,18558,18559,18560,18561,18562,18563,18564,18565,18566,18567,18568,18569,18570,18571,18572,18573,18574,18575,18576,18577,18578,18579,18580,18581,18582,18583,18584,18585,18586,18587,18588,18589,18590,18591,18592,18593,18594,18595,18596,18597,18598,18599,18600,18601,18602,18603,18604,18605,18606,18607,18608,18609,18610,18611,18612,18613,18614,18615,18616,18617,18618,18619,18620,18621,18622,18623,18624,18625,18626,18627,18628,18629,18630,18631,18632,18633,18634,18635,18636,18637,18638,18639,18640,18641,18642,18643,18644,18645,18646,18647,18648,18649,18650,18651,18652,18653,18654,18655,18656,18657,18658,18659,18660,18661,18662,18663,18664,18665,18666,18667,18668,18669,18670,18671,18672,18673,18674,18675,18676,18677,18678,18679,18680,18681,18682,18683,18684,18685,18686,18687,18688,18689,18690,18691,18692,18693,18694,18695,18696,18697,18698,18699,18700,18701,18702,18703,18704,18705,18706,18707,18708,18709,18710,18711,18712,18713,18714,18715,18716,18717,18718,18719,18720,18721,18722,18723,18724,18725,18726,18727,18728,18729,18730,18731,18732,18733,18734,18735,18736,18737,18738,18739,18740,18741,18742,18743,18744,18745,18746,18747,18748,18749,18750,18751,18752,18753,18754,18755,18756,18757,18758,18759,18760,18761,18762,18763,18764,18765,18766,18767,18768,18769,18770,18771,18772,18773,18774,18775,18776,18777,18778,18779,18780,18781,18782,18783,18784,18785,18786,18787,18788,18789,18790,18791,18792,18793,18794,18795,18796,18797,18798,18799,18800,18801,18802,18803,18804,18805,18806,18807,18808,18809,18810,18811,18812,18813,18814,18815,18816,18817,18818,18819,18820,18821,18822,18823,18824,18825,18826,18827,18828,18829,18830,18831,18832,18833,18834,18835,18836,18837,18838,18839,18840,18841,18842,18843,18844,18845,18846,18847,18848,18849,18850,18851,18852,18853,18854,18855,18856,18857,18858,18859,18860,18861,18862,18863,18864,18865,18866,18867,18868,18869,18870,18871,18872,18873,18874,18875,18876,18877,18878,18879,18880,18881,18882,18883,18884,18885,18886,18887,18888,18889,18890,18891,18892,18893,18894,18895,18896,18897,18898,18899,18900,18901,18902,18903,18904,18905,18906,18907,18908,18909,18910,18911,18912,18913,18914,18915,18916,18917,18918,18919,18920,18921,18922,18923,18924,18925,18926,18927,18928,18929,18930,18931,18932,18933,18934,18935,18936,18937,18938,18939,18940,18941,18942,18943,18944,18945,18946,18947,18948,18949,18950,18951,18952,18953,18954,18955,18956,18957,18958,18959,18960,18961,18962,18963,18964,18965,18966,18967,18968,18969,18970,18971,18972,18973,18974,18975,18976,18977,18978,18979,18980,18981,18982,18983,18984,18985,18986,18987,18988,18989,18990,18991,18992,18993,18994,18995,18996,18997,18998,18999,19000,19001,19002,19003,19004,19005,19006,19007,19008,19009,19010,19011,19012,19013,19014,19015,19016,19017,19018,19019,19020,19021,19022,19023,19024,19025,19026,19027,19028,19029,19030,19031,19032,19033,19034,19035,19036,19037,19038,19039,19040,19041,19042,19043,19044,19045,19046,19047,19048,19049,19050,19051,19052,19053,19054,19055,19056,19057,19058,19059,19060,19061,19062,19063,19064,19065,19066,19067,19068,19069,19070,19071,19072,19073,19074,19075,19076,19077,19078,19079,19080,19081,19082,19083,19084,19085,19086,19087,19088,19089,19090,19091,19092,19093,19094,19095,19096,19097,19098,19099,19100,19101,19102,19103,19104,19105,19106,19107,19108,19109,19110,19111,19112,19113,19114,19115,19116,19117,19118,19119,19120,19121,19122,19123,19124,19125,19126,19127,19128,19129,19130,19131,19132,19133,19134,19135,19136,19137,19138,19139,19140,19141,19142,19143,19144,19145,19146,19147,19148,19149,19150,19151,19152,19153,19154,19155,19156,19157,19158,19159,19160,19161,19162,19163,19164,19165,19166,19167,19168,19169,19170,19171,19172,19173,19174,19175,19176,19177,19178,19179,19180,19181,19182,19183,19184,19185,19186,19187,19188,19189,19190,19191,19192,19193,19194,19195,19196,19197,19198,19199,19200,19201,19202,19203,19204,19205,19206,19207,19208,19209,19210,19211,19212,19213,19214,19215,19216,19217,19218,19219,19220,19221,19222,19223,19224,19225,19226,19227,19228,19229,19230,19231,19232,19233,19234,19235,19236,19237,19238,19239,19240,19241,19242,19243,19244,19245,19246,19247,19248,19249,19250,19251,19252,19253,19254,19255,19256,19257,19258,19259,19260,19261,19262,19263,19264,19265,19266,19267,19268,19269,19270,19271,19272,19273,19274,19275,19276,19277,19278,19279,19280,19281,19282,19283,19284,19285,19286,19287,19288,19289,19290,19291,19292,19293,19294,19295,19296,19297,19298,19299,19300,19301,19302,19303,19304,19305,19306,19307,19308,19309,19310,19311,19312,19313,19314,19315,19316,19317,19318,19319,19320,19321,19322,19323,19324,19325,19326,19327,19328,19329,19330,19331,19332,19333,19334,19335,19336,19337,19338,19339,19340,19341,19342,19343,19344,19345,19346,19347,19348,19349,19350,19351,19352,19353,19354,19355,19356,19357,19358,19359,19360,19361,19362,19363,19364,19365,19366,19367,19368,19369,19370,19371,19372,19373,19374,19375,19376,19377,19378,19379,19380,19381,19382,19383,19384,19385,19386,19387,19388,19389,19390,19391,19392,19393,19394,19395,19396,19397,19398,19399,19400,19401,19402,19403,19404,19405,19406,19407,19408,19409,19410,19411,19412,19413,19414,19415,19416,19417,19418,19419,19420,19421,19422,19423,19424,19425,19426,19427,19428,19429,19430,19431,19432,19433,19434,19435,19436,19437,19438,19439,19440,19441,19442,19443,19444,19445,19446,19447,19448,19449,19450,19451,19452,19453,19454,19455,19456,19457,19458,19459,19460,19461,19462,19463,19464,19465,19466,19467,19468,19469,19470,19471,19472,19473,19474,19475,19476,19477,19478,19479,19480,19481,19482,19483,19484,19485,19486,19487,19488,19489,19490,19491,19492,19493,19494,19495,19496,19497,19498,19499,19500,19501,19502,19503,19504,19505,19506,19507,19508,19509,19510,19511,19512,19513,19514,19515,19516,19517,19518,19519,19520,19521,19522,19523,19524,19525,19526,19527,19528,19529,19530,19531,19532,19533,19534,19535,19536,19537,19538,19539,19540,19541,19542,19543,19544,19545,19546,19547,19548,19549,19550,19551,19552,19553,19554,19555,19556,19557,19558,19559,19560,19561,19562,19563,19564,19565,19566,19567,19568,19569,19570,19571,19572,19573,19574,19575,19576,19577,19578,19579,19580,19581,19582,19583,19584,19585,19586,19587,19588,19589,19590,19591,19592,19593,19594,19595,19596,19597,19598,19599,19600,19601,19602,19603,19604,19605,19606,19607,19608,19609,19610,19611,19612,19613,19614,19615,19616,19617,19618,19619,19620,19621,19622,19623,19624,19625,19626,19627,19628,19629,19630,19631,19632,19633,19634,19635,19636,19637,19638,19639,19640,19641,19642,19643,19644,19645,19646,19647,19648,19649,19650,19651,19652,19653,19654,19655,19656,19657,19658,19659,19660,19661,19662,19663,19664,19665,19666,19667,19668,19669,19670,19671,19672,19673,19674,19675,19676,19677,19678,19679,19680,19681,19682,19683,19684,19685,19686,19687,19688,19689,19690,19691,19692,19693,19694,19695,19696,19697,19698,19699,19700,19701,19702,19703,19704,19705,19706,19707,19708,19709,19710,19711,19712,19713,19714,19715,19716,19717,19718,19719,19720,19721,19722,19723,19724,19725,19726,19727,19728,19729,19730,19731,19732,19733,19734,19735,19736,19737,19738,19739,19740,19741,19742,19743,19744,19745,19746,19747,19748,19749,19750,19751,19752,19753,19754,19755,19756,19757,19758,19759,19760,19761,19762,19763,19764,19765,19766,19767,19768,19769,19770,19771,19772,19773,19774,19775,19776,19777,19778,19779,19780,19781,19782,19783,19784,19785,19786,19787,19788,19789,19790,19791,19792,19793,19794,19795,19796,19797,19798,19799,19800,19801,19802,19803,19804,19805,19806,19807,19808,19809,19810,19811,19812,19813,19814,19815,19816,19817,19818,19819,19820,19821,19822,19823,19824,19825,19826,19827,19828,19829,19830,19831,19832,19833,19834,19835,19836,19837,19838,19839,19840,19841,19842,19843,19844,19845,19846,19847,19848,19849,19850,19851,19852,19853,19854,19855,19856,19857,19858,19859,19860,19861,19862,19863,19864,19865,19866,19867,19868,19869,19870,19871,19872,19873,19874,19875,19876,19877,19878,19879,19880,19881,19882,19883,19884,19885,19886,19887,19888,19889,19890,19891,19892,19893,19968,19969,19970,19971,19972,19973,19974,19975,19976,19977,19978,19979,19980,19981,19982,19983,19984,19985,19986,19987,19988,19989,19990,19991,19992,19993,19994,19995,19996,19997,19998,19999,20000,20001,20002,20003,20004,20005,20006,20007,20008,20009,20010,20011,20012,20013,20014,20015,20016,20017,20018,20019,20020,20021,20022,20023,20024,20025,20026,20027,20028,20029,20030,20031,20032,20033,20034,20035,20036,20037,20038,20039,20040,20041,20042,20043,20044,20045,20046,20047,20048,20049,20050,20051,20052,20053,20054,20055,20056,20057,20058,20059,20060,20061,20062,20063,20064,20065,20066,20067,20068,20069,20070,20071,20072,20073,20074,20075,20076,20077,20078,20079,20080,20081,20082,20083,20084,20085,20086,20087,20088,20089,20090,20091,20092,20093,20094,20095,20096,20097,20098,20099,20100,20101,20102,20103,20104,20105,20106,20107,20108,20109,20110,20111,20112,20113,20114,20115,20116,20117,20118,20119,20120,20121,20122,20123,20124,20125,20126,20127,20128,20129,20130,20131,20132,20133,20134,20135,20136,20137,20138,20139,20140,20141,20142,20143,20144,20145,20146,20147,20148,20149,20150,20151,20152,20153,20154,20155,20156,20157,20158,20159,20160,20161,20162,20163,20164,20165,20166,20167,20168,20169,20170,20171,20172,20173,20174,20175,20176,20177,20178,20179,20180,20181,20182,20183,20184,20185,20186,20187,20188,20189,20190,20191,20192,20193,20194,20195,20196,20197,20198,20199,20200,20201,20202,20203,20204,20205,20206,20207,20208,20209,20210,20211,20212,20213,20214,20215,20216,20217,20218,20219,20220,20221,20222,20223,20224,20225,20226,20227,20228,20229,20230,20231,20232,20233,20234,20235,20236,20237,20238,20239,20240,20241,20242,20243,20244,20245,20246,20247,20248,20249,20250,20251,20252,20253,20254,20255,20256,20257,20258,20259,20260,20261,20262,20263,20264,20265,20266,20267,20268,20269,20270,20271,20272,20273,20274,20275,20276,20277,20278,20279,20280,20281,20282,20283,20284,20285,20286,20287,20288,20289,20290,20291,20292,20293,20294,20295,20296,20297,20298,20299,20300,20301,20302,20303,20304,20305,20306,20307,20308,20309,20310,20311,20312,20313,20314,20315,20316,20317,20318,20319,20320,20321,20322,20323,20324,20325,20326,20327,20328,20329,20330,20331,20332,20333,20334,20335,20336,20337,20338,20339,20340,20341,20342,20343,20344,20345,20346,20347,20348,20349,20350,20351,20352,20353,20354,20355,20356,20357,20358,20359,20360,20361,20362,20363,20364,20365,20366,20367,20368,20369,20370,20371,20372,20373,20374,20375,20376,20377,20378,20379,20380,20381,20382,20383,20384,20385,20386,20387,20388,20389,20390,20391,20392,20393,20394,20395,20396,20397,20398,20399,20400,20401,20402,20403,20404,20405,20406,20407,20408,20409,20410,20411,20412,20413,20414,20415,20416,20417,20418,20419,20420,20421,20422,20423,20424,20425,20426,20427,20428,20429,20430,20431,20432,20433,20434,20435,20436,20437,20438,20439,20440,20441,20442,20443,20444,20445,20446,20447,20448,20449,20450,20451,20452,20453,20454,20455,20456,20457,20458,20459,20460,20461,20462,20463,20464,20465,20466,20467,20468,20469,20470,20471,20472,20473,20474,20475,20476,20477,20478,20479,20480,20481,20482,20483,20484,20485,20486,20487,20488,20489,20490,20491,20492,20493,20494,20495,20496,20497,20498,20499,20500,20501,20502,20503,20504,20505,20506,20507,20508,20509,20510,20511,20512,20513,20514,20515,20516,20517,20518,20519,20520,20521,20522,20523,20524,20525,20526,20527,20528,20529,20530,20531,20532,20533,20534,20535,20536,20537,20538,20539,20540,20541,20542,20543,20544,20545,20546,20547,20548,20549,20550,20551,20552,20553,20554,20555,20556,20557,20558,20559,20560,20561,20562,20563,20564,20565,20566,20567,20568,20569,20570,20571,20572,20573,20574,20575,20576,20577,20578,20579,20580,20581,20582,20583,20584,20585,20586,20587,20588,20589,20590,20591,20592,20593,20594,20595,20596,20597,20598,20599,20600,20601,20602,20603,20604,20605,20606,20607,20608,20609,20610,20611,20612,20613,20614,20615,20616,20617,20618,20619,20620,20621,20622,20623,20624,20625,20626,20627,20628,20629,20630,20631,20632,20633,20634,20635,20636,20637,20638,20639,20640,20641,20642,20643,20644,20645,20646,20647,20648,20649,20650,20651,20652,20653,20654,20655,20656,20657,20658,20659,20660,20661,20662,20663,20664,20665,20666,20667,20668,20669,20670,20671,20672,20673,20674,20675,20676,20677,20678,20679,20680,20681,20682,20683,20684,20685,20686,20687,20688,20689,20690,20691,20692,20693,20694,20695,20696,20697,20698,20699,20700,20701,20702,20703,20704,20705,20706,20707,20708,20709,20710,20711,20712,20713,20714,20715,20716,20717,20718,20719,20720,20721,20722,20723,20724,20725,20726,20727,20728,20729,20730,20731,20732,20733,20734,20735,20736,20737,20738,20739,20740,20741,20742,20743,20744,20745,20746,20747,20748,20749,20750,20751,20752,20753,20754,20755,20756,20757,20758,20759,20760,20761,20762,20763,20764,20765,20766,20767,20768,20769,20770,20771,20772,20773,20774,20775,20776,20777,20778,20779,20780,20781,20782,20783,20784,20785,20786,20787,20788,20789,20790,20791,20792,20793,20794,20795,20796,20797,20798,20799,20800,20801,20802,20803,20804,20805,20806,20807,20808,20809,20810,20811,20812,20813,20814,20815,20816,20817,20818,20819,20820,20821,20822,20823,20824,20825,20826,20827,20828,20829,20830,20831,20832,20833,20834,20835,20836,20837,20838,20839,20840,20841,20842,20843,20844,20845,20846,20847,20848,20849,20850,20851,20852,20853,20854,20855,20856,20857,20858,20859,20860,20861,20862,20863,20864,20865,20866,20867,20868,20869,20870,20871,20872,20873,20874,20875,20876,20877,20878,20879,20880,20881,20882,20883,20884,20885,20886,20887,20888,20889,20890,20891,20892,20893,20894,20895,20896,20897,20898,20899,20900,20901,20902,20903,20904,20905,20906,20907,20908,20909,20910,20911,20912,20913,20914,20915,20916,20917,20918,20919,20920,20921,20922,20923,20924,20925,20926,20927,20928,20929,20930,20931,20932,20933,20934,20935,20936,20937,20938,20939,20940,20941,20942,20943,20944,20945,20946,20947,20948,20949,20950,20951,20952,20953,20954,20955,20956,20957,20958,20959,20960,20961,20962,20963,20964,20965,20966,20967,20968,20969,20970,20971,20972,20973,20974,20975,20976,20977,20978,20979,20980,20981,20982,20983,20984,20985,20986,20987,20988,20989,20990,20991,20992,20993,20994,20995,20996,20997,20998,20999,21000,21001,21002,21003,21004,21005,21006,21007,21008,21009,21010,21011,21012,21013,21014,21015,21016,21017,21018,21019,21020,21021,21022,21023,21024,21025,21026,21027,21028,21029,21030,21031,21032,21033,21034,21035,21036,21037,21038,21039,21040,21041,21042,21043,21044,21045,21046,21047,21048,21049,21050,21051,21052,21053,21054,21055,21056,21057,21058,21059,21060,21061,21062,21063,21064,21065,21066,21067,21068,21069,21070,21071,21072,21073,21074,21075,21076,21077,21078,21079,21080,21081,21082,21083,21084,21085,21086,21087,21088,21089,21090,21091,21092,21093,21094,21095,21096,21097,21098,21099,21100,21101,21102,21103,21104,21105,21106,21107,21108,21109,21110,21111,21112,21113,21114,21115,21116,21117,21118,21119,21120,21121,21122,21123,21124,21125,21126,21127,21128,21129,21130,21131,21132,21133,21134,21135,21136,21137,21138,21139,21140,21141,21142,21143,21144,21145,21146,21147,21148,21149,21150,21151,21152,21153,21154,21155,21156,21157,21158,21159,21160,21161,21162,21163,21164,21165,21166,21167,21168,21169,21170,21171,21172,21173,21174,21175,21176,21177,21178,21179,21180,21181,21182,21183,21184,21185,21186,21187,21188,21189,21190,21191,21192,21193,21194,21195,21196,21197,21198,21199,21200,21201,21202,21203,21204,21205,21206,21207,21208,21209,21210,21211,21212,21213,21214,21215,21216,21217,21218,21219,21220,21221,21222,21223,21224,21225,21226,21227,21228,21229,21230,21231,21232,21233,21234,21235,21236,21237,21238,21239,21240,21241,21242,21243,21244,21245,21246,21247,21248,21249,21250,21251,21252,21253,21254,21255,21256,21257,21258,21259,21260,21261,21262,21263,21264,21265,21266,21267,21268,21269,21270,21271,21272,21273,21274,21275,21276,21277,21278,21279,21280,21281,21282,21283,21284,21285,21286,21287,21288,21289,21290,21291,21292,21293,21294,21295,21296,21297,21298,21299,21300,21301,21302,21303,21304,21305,21306,21307,21308,21309,21310,21311,21312,21313,21314,21315,21316,21317,21318,21319,21320,21321,21322,21323,21324,21325,21326,21327,21328,21329,21330,21331,21332,21333,21334,21335,21336,21337,21338,21339,21340,21341,21342,21343,21344,21345,21346,21347,21348,21349,21350,21351,21352,21353,21354,21355,21356,21357,21358,21359,21360,21361,21362,21363,21364,21365,21366,21367,21368,21369,21370,21371,21372,21373,21374,21375,21376,21377,21378,21379,21380,21381,21382,21383,21384,21385,21386,21387,21388,21389,21390,21391,21392,21393,21394,21395,21396,21397,21398,21399,21400,21401,21402,21403,21404,21405,21406,21407,21408,21409,21410,21411,21412,21413,21414,21415,21416,21417,21418,21419,21420,21421,21422,21423,21424,21425,21426,21427,21428,21429,21430,21431,21432,21433,21434,21435,21436,21437,21438,21439,21440,21441,21442,21443,21444,21445,21446,21447,21448,21449,21450,21451,21452,21453,21454,21455,21456,21457,21458,21459,21460,21461,21462,21463,21464,21465,21466,21467,21468,21469,21470,21471,21472,21473,21474,21475,21476,21477,21478,21479,21480,21481,21482,21483,21484,21485,21486,21487,21488,21489,21490,21491,21492,21493,21494,21495,21496,21497,21498,21499,21500,21501,21502,21503,21504,21505,21506,21507,21508,21509,21510,21511,21512,21513,21514,21515,21516,21517,21518,21519,21520,21521,21522,21523,21524,21525,21526,21527,21528,21529,21530,21531,21532,21533,21534,21535,21536,21537,21538,21539,21540,21541,21542,21543,21544,21545,21546,21547,21548,21549,21550,21551,21552,21553,21554,21555,21556,21557,21558,21559,21560,21561,21562,21563,21564,21565,21566,21567,21568,21569,21570,21571,21572,21573,21574,21575,21576,21577,21578,21579,21580,21581,21582,21583,21584,21585,21586,21587,21588,21589,21590,21591,21592,21593,21594,21595,21596,21597,21598,21599,21600,21601,21602,21603,21604,21605,21606,21607,21608,21609,21610,21611,21612,21613,21614,21615,21616,21617,21618,21619,21620,21621,21622,21623,21624,21625,21626,21627,21628,21629,21630,21631,21632,21633,21634,21635,21636,21637,21638,21639,21640,21641,21642,21643,21644,21645,21646,21647,21648,21649,21650,21651,21652,21653,21654,21655,21656,21657,21658,21659,21660,21661,21662,21663,21664,21665,21666,21667,21668,21669,21670,21671,21672,21673,21674,21675,21676,21677,21678,21679,21680,21681,21682,21683,21684,21685,21686,21687,21688,21689,21690,21691,21692,21693,21694,21695,21696,21697,21698,21699,21700,21701,21702,21703,21704,21705,21706,21707,21708,21709,21710,21711,21712,21713,21714,21715,21716,21717,21718,21719,21720,21721,21722,21723,21724,21725,21726,21727,21728,21729,21730,21731,21732,21733,21734,21735,21736,21737,21738,21739,21740,21741,21742,21743,21744,21745,21746,21747,21748,21749,21750,21751,21752,21753,21754,21755,21756,21757,21758,21759,21760,21761,21762,21763,21764,21765,21766,21767,21768,21769,21770,21771,21772,21773,21774,21775,21776,21777,21778,21779,21780,21781,21782,21783,21784,21785,21786,21787,21788,21789,21790,21791,21792,21793,21794,21795,21796,21797,21798,21799,21800,21801,21802,21803,21804,21805,21806,21807,21808,21809,21810,21811,21812,21813,21814,21815,21816,21817,21818,21819,21820,21821,21822,21823,21824,21825,21826,21827,21828,21829,21830,21831,21832,21833,21834,21835,21836,21837,21838,21839,21840,21841,21842,21843,21844,21845,21846,21847,21848,21849,21850,21851,21852,21853,21854,21855,21856,21857,21858,21859,21860,21861,21862,21863,21864,21865,21866,21867,21868,21869,21870,21871,21872,21873,21874,21875,21876,21877,21878,21879,21880,21881,21882,21883,21884,21885,21886,21887,21888,21889,21890,21891,21892,21893,21894,21895,21896,21897,21898,21899,21900,21901,21902,21903,21904,21905,21906,21907,21908,21909,21910,21911,21912,21913,21914,21915,21916,21917,21918,21919,21920,21921,21922,21923,21924,21925,21926,21927,21928,21929,21930,21931,21932,21933,21934,21935,21936,21937,21938,21939,21940,21941,21942,21943,21944,21945,21946,21947,21948,21949,21950,21951,21952,21953,21954,21955,21956,21957,21958,21959,21960,21961,21962,21963,21964,21965,21966,21967,21968,21969,21970,21971,21972,21973,21974,21975,21976,21977,21978,21979,21980,21981,21982,21983,21984,21985,21986,21987,21988,21989,21990,21991,21992,21993,21994,21995,21996,21997,21998,21999,22000,22001,22002,22003,22004,22005,22006,22007,22008,22009,22010,22011,22012,22013,22014,22015,22016,22017,22018,22019,22020,22021,22022,22023,22024,22025,22026,22027,22028,22029,22030,22031,22032,22033,22034,22035,22036,22037,22038,22039,22040,22041,22042,22043,22044,22045,22046,22047,22048,22049,22050,22051,22052,22053,22054,22055,22056,22057,22058,22059,22060,22061,22062,22063,22064,22065,22066,22067,22068,22069,22070,22071,22072,22073,22074,22075,22076,22077,22078,22079,22080,22081,22082,22083,22084,22085,22086,22087,22088,22089,22090,22091,22092,22093,22094,22095,22096,22097,22098,22099,22100,22101,22102,22103,22104,22105,22106,22107,22108,22109,22110,22111,22112,22113,22114,22115,22116,22117,22118,22119,22120,22121,22122,22123,22124,22125,22126,22127,22128,22129,22130,22131,22132,22133,22134,22135,22136,22137,22138,22139,22140,22141,22142,22143,22144,22145,22146,22147,22148,22149,22150,22151,22152,22153,22154,22155,22156,22157,22158,22159,22160,22161,22162,22163,22164,22165,22166,22167,22168,22169,22170,22171,22172,22173,22174,22175,22176,22177,22178,22179,22180,22181,22182,22183,22184,22185,22186,22187,22188,22189,22190,22191,22192,22193,22194,22195,22196,22197,22198,22199,22200,22201,22202,22203,22204,22205,22206,22207,22208,22209,22210,22211,22212,22213,22214,22215,22216,22217,22218,22219,22220,22221,22222,22223,22224,22225,22226,22227,22228,22229,22230,22231,22232,22233,22234,22235,22236,22237,22238,22239,22240,22241,22242,22243,22244,22245,22246,22247,22248,22249,22250,22251,22252,22253,22254,22255,22256,22257,22258,22259,22260,22261,22262,22263,22264,22265,22266,22267,22268,22269,22270,22271,22272,22273,22274,22275,22276,22277,22278,22279,22280,22281,22282,22283,22284,22285,22286,22287,22288,22289,22290,22291,22292,22293,22294,22295,22296,22297,22298,22299,22300,22301,22302,22303,22304,22305,22306,22307,22308,22309,22310,22311,22312,22313,22314,22315,22316,22317,22318,22319,22320,22321,22322,22323,22324,22325,22326,22327,22328,22329,22330,22331,22332,22333,22334,22335,22336,22337,22338,22339,22340,22341,22342,22343,22344,22345,22346,22347,22348,22349,22350,22351,22352,22353,22354,22355,22356,22357,22358,22359,22360,22361,22362,22363,22364,22365,22366,22367,22368,22369,22370,22371,22372,22373,22374,22375,22376,22377,22378,22379,22380,22381,22382,22383,22384,22385,22386,22387,22388,22389,22390,22391,22392,22393,22394,22395,22396,22397,22398,22399,22400,22401,22402,22403,22404,22405,22406,22407,22408,22409,22410,22411,22412,22413,22414,22415,22416,22417,22418,22419,22420,22421,22422,22423,22424,22425,22426,22427,22428,22429,22430,22431,22432,22433,22434,22435,22436,22437,22438,22439,22440,22441,22442,22443,22444,22445,22446,22447,22448,22449,22450,22451,22452,22453,22454,22455,22456,22457,22458,22459,22460,22461,22462,22463,22464,22465,22466,22467,22468,22469,22470,22471,22472,22473,22474,22475,22476,22477,22478,22479,22480,22481,22482,22483,22484,22485,22486,22487,22488,22489,22490,22491,22492,22493,22494,22495,22496,22497,22498,22499,22500,22501,22502,22503,22504,22505,22506,22507,22508,22509,22510,22511,22512,22513,22514,22515,22516,22517,22518,22519,22520,22521,22522,22523,22524,22525,22526,22527,22528,22529,22530,22531,22532,22533,22534,22535,22536,22537,22538,22539,22540,22541,22542,22543,22544,22545,22546,22547,22548,22549,22550,22551,22552,22553,22554,22555,22556,22557,22558,22559,22560,22561,22562,22563,22564,22565,22566,22567,22568,22569,22570,22571,22572,22573,22574,22575,22576,22577,22578,22579,22580,22581,22582,22583,22584,22585,22586,22587,22588,22589,22590,22591,22592,22593,22594,22595,22596,22597,22598,22599,22600,22601,22602,22603,22604,22605,22606,22607,22608,22609,22610,22611,22612,22613,22614,22615,22616,22617,22618,22619,22620,22621,22622,22623,22624,22625,22626,22627,22628,22629,22630,22631,22632,22633,22634,22635,22636,22637,22638,22639,22640,22641,22642,22643,22644,22645,22646,22647,22648,22649,22650,22651,22652,22653,22654,22655,22656,22657,22658,22659,22660,22661,22662,22663,22664,22665,22666,22667,22668,22669,22670,22671,22672,22673,22674,22675,22676,22677,22678,22679,22680,22681,22682,22683,22684,22685,22686,22687,22688,22689,22690,22691,22692,22693,22694,22695,22696,22697,22698,22699,22700,22701,22702,22703,22704,22705,22706,22707,22708,22709,22710,22711,22712,22713,22714,22715,22716,22717,22718,22719,22720,22721,22722,22723,22724,22725,22726,22727,22728,22729,22730,22731,22732,22733,22734,22735,22736,22737,22738,22739,22740,22741,22742,22743,22744,22745,22746,22747,22748,22749,22750,22751,22752,22753,22754,22755,22756,22757,22758,22759,22760,22761,22762,22763,22764,22765,22766,22767,22768,22769,22770,22771,22772,22773,22774,22775,22776,22777,22778,22779,22780,22781,22782,22783,22784,22785,22786,22787,22788,22789,22790,22791,22792,22793,22794,22795,22796,22797,22798,22799,22800,22801,22802,22803,22804,22805,22806,22807,22808,22809,22810,22811,22812,22813,22814,22815,22816,22817,22818,22819,22820,22821,22822,22823,22824,22825,22826,22827,22828,22829,22830,22831,22832,22833,22834,22835,22836,22837,22838,22839,22840,22841,22842,22843,22844,22845,22846,22847,22848,22849,22850,22851,22852,22853,22854,22855,22856,22857,22858,22859,22860,22861,22862,22863,22864,22865,22866,22867,22868,22869,22870,22871,22872,22873,22874,22875,22876,22877,22878,22879,22880,22881,22882,22883,22884,22885,22886,22887,22888,22889,22890,22891,22892,22893,22894,22895,22896,22897,22898,22899,22900,22901,22902,22903,22904,22905,22906,22907,22908,22909,22910,22911,22912,22913,22914,22915,22916,22917,22918,22919,22920,22921,22922,22923,22924,22925,22926,22927,22928,22929,22930,22931,22932,22933,22934,22935,22936,22937,22938,22939,22940,22941,22942,22943,22944,22945,22946,22947,22948,22949,22950,22951,22952,22953,22954,22955,22956,22957,22958,22959,22960,22961,22962,22963,22964,22965,22966,22967,22968,22969,22970,22971,22972,22973,22974,22975,22976,22977,22978,22979,22980,22981,22982,22983,22984,22985,22986,22987,22988,22989,22990,22991,22992,22993,22994,22995,22996,22997,22998,22999,23000,23001,23002,23003,23004,23005,23006,23007,23008,23009,23010,23011,23012,23013,23014,23015,23016,23017,23018,23019,23020,23021,23022,23023,23024,23025,23026,23027,23028,23029,23030,23031,23032,23033,23034,23035,23036,23037,23038,23039,23040,23041,23042,23043,23044,23045,23046,23047,23048,23049,23050,23051,23052,23053,23054,23055,23056,23057,23058,23059,23060,23061,23062,23063,23064,23065,23066,23067,23068,23069,23070,23071,23072,23073,23074,23075,23076,23077,23078,23079,23080,23081,23082,23083,23084,23085,23086,23087,23088,23089,23090,23091,23092,23093,23094,23095,23096,23097,23098,23099,23100,23101,23102,23103,23104,23105,23106,23107,23108,23109,23110,23111,23112,23113,23114,23115,23116,23117,23118,23119,23120,23121,23122,23123,23124,23125,23126,23127,23128,23129,23130,23131,23132,23133,23134,23135,23136,23137,23138,23139,23140,23141,23142,23143,23144,23145,23146,23147,23148,23149,23150,23151,23152,23153,23154,23155,23156,23157,23158,23159,23160,23161,23162,23163,23164,23165,23166,23167,23168,23169,23170,23171,23172,23173,23174,23175,23176,23177,23178,23179,23180,23181,23182,23183,23184,23185,23186,23187,23188,23189,23190,23191,23192,23193,23194,23195,23196,23197,23198,23199,23200,23201,23202,23203,23204,23205,23206,23207,23208,23209,23210,23211,23212,23213,23214,23215,23216,23217,23218,23219,23220,23221,23222,23223,23224,23225,23226,23227,23228,23229,23230,23231,23232,23233,23234,23235,23236,23237,23238,23239,23240,23241,23242,23243,23244,23245,23246,23247,23248,23249,23250,23251,23252,23253,23254,23255,23256,23257,23258,23259,23260,23261,23262,23263,23264,23265,23266,23267,23268,23269,23270,23271,23272,23273,23274,23275,23276,23277,23278,23279,23280,23281,23282,23283,23284,23285,23286,23287,23288,23289,23290,23291,23292,23293,23294,23295,23296,23297,23298,23299,23300,23301,23302,23303,23304,23305,23306,23307,23308,23309,23310,23311,23312,23313,23314,23315,23316,23317,23318,23319,23320,23321,23322,23323,23324,23325,23326,23327,23328,23329,23330,23331,23332,23333,23334,23335,23336,23337,23338,23339,23340,23341,23342,23343,23344,23345,23346,23347,23348,23349,23350,23351,23352,23353,23354,23355,23356,23357,23358,23359,23360,23361,23362,23363,23364,23365,23366,23367,23368,23369,23370,23371,23372,23373,23374,23375,23376,23377,23378,23379,23380,23381,23382,23383,23384,23385,23386,23387,23388,23389,23390,23391,23392,23393,23394,23395,23396,23397,23398,23399,23400,23401,23402,23403,23404,23405,23406,23407,23408,23409,23410,23411,23412,23413,23414,23415,23416,23417,23418,23419,23420,23421,23422,23423,23424,23425,23426,23427,23428,23429,23430,23431,23432,23433,23434,23435,23436,23437,23438,23439,23440,23441,23442,23443,23444,23445,23446,23447,23448,23449,23450,23451,23452,23453,23454,23455,23456,23457,23458,23459,23460,23461,23462,23463,23464,23465,23466,23467,23468,23469,23470,23471,23472,23473,23474,23475,23476,23477,23478,23479,23480,23481,23482,23483,23484,23485,23486,23487,23488,23489,23490,23491,23492,23493,23494,23495,23496,23497,23498,23499,23500,23501,23502,23503,23504,23505,23506,23507,23508,23509,23510,23511,23512,23513,23514,23515,23516,23517,23518,23519,23520,23521,23522,23523,23524,23525,23526,23527,23528,23529,23530,23531,23532,23533,23534,23535,23536,23537,23538,23539,23540,23541,23542,23543,23544,23545,23546,23547,23548,23549,23550,23551,23552,23553,23554,23555,23556,23557,23558,23559,23560,23561,23562,23563,23564,23565,23566,23567,23568,23569,23570,23571,23572,23573,23574,23575,23576,23577,23578,23579,23580,23581,23582,23583,23584,23585,23586,23587,23588,23589,23590,23591,23592,23593,23594,23595,23596,23597,23598,23599,23600,23601,23602,23603,23604,23605,23606,23607,23608,23609,23610,23611,23612,23613,23614,23615,23616,23617,23618,23619,23620,23621,23622,23623,23624,23625,23626,23627,23628,23629,23630,23631,23632,23633,23634,23635,23636,23637,23638,23639,23640,23641,23642,23643,23644,23645,23646,23647,23648,23649,23650,23651,23652,23653,23654,23655,23656,23657,23658,23659,23660,23661,23662,23663,23664,23665,23666,23667,23668,23669,23670,23671,23672,23673,23674,23675,23676,23677,23678,23679,23680,23681,23682,23683,23684,23685,23686,23687,23688,23689,23690,23691,23692,23693,23694,23695,23696,23697,23698,23699,23700,23701,23702,23703,23704,23705,23706,23707,23708,23709,23710,23711,23712,23713,23714,23715,23716,23717,23718,23719,23720,23721,23722,23723,23724,23725,23726,23727,23728,23729,23730,23731,23732,23733,23734,23735,23736,23737,23738,23739,23740,23741,23742,23743,23744,23745,23746,23747,23748,23749,23750,23751,23752,23753,23754,23755,23756,23757,23758,23759,23760,23761,23762,23763,23764,23765,23766,23767,23768,23769,23770,23771,23772,23773,23774,23775,23776,23777,23778,23779,23780,23781,23782,23783,23784,23785,23786,23787,23788,23789,23790,23791,23792,23793,23794,23795,23796,23797,23798,23799,23800,23801,23802,23803,23804,23805,23806,23807,23808,23809,23810,23811,23812,23813,23814,23815,23816,23817,23818,23819,23820,23821,23822,23823,23824,23825,23826,23827,23828,23829,23830,23831,23832,23833,23834,23835,23836,23837,23838,23839,23840,23841,23842,23843,23844,23845,23846,23847,23848,23849,23850,23851,23852,23853,23854,23855,23856,23857,23858,23859,23860,23861,23862,23863,23864,23865,23866,23867,23868,23869,23870,23871,23872,23873,23874,23875,23876,23877,23878,23879,23880,23881,23882,23883,23884,23885,23886,23887,23888,23889,23890,23891,23892,23893,23894,23895,23896,23897,23898,23899,23900,23901,23902,23903,23904,23905,23906,23907,23908,23909,23910,23911,23912,23913,23914,23915,23916,23917,23918,23919,23920,23921,23922,23923,23924,23925,23926,23927,23928,23929,23930,23931,23932,23933,23934,23935,23936,23937,23938,23939,23940,23941,23942,23943,23944,23945,23946,23947,23948,23949,23950,23951,23952,23953,23954,23955,23956,23957,23958,23959,23960,23961,23962,23963,23964,23965,23966,23967,23968,23969,23970,23971,23972,23973,23974,23975,23976,23977,23978,23979,23980,23981,23982,23983,23984,23985,23986,23987,23988,23989,23990,23991,23992,23993,23994,23995,23996,23997,23998,23999,24000,24001,24002,24003,24004,24005,24006,24007,24008,24009,24010,24011,24012,24013,24014,24015,24016,24017,24018,24019,24020,24021,24022,24023,24024,24025,24026,24027,24028,24029,24030,24031,24032,24033,24034,24035,24036,24037,24038,24039,24040,24041,24042,24043,24044,24045,24046,24047,24048,24049,24050,24051,24052,24053,24054,24055,24056,24057,24058,24059,24060,24061,24062,24063,24064,24065,24066,24067,24068,24069,24070,24071,24072,24073,24074,24075,24076,24077,24078,24079,24080,24081,24082,24083,24084,24085,24086,24087,24088,24089,24090,24091,24092,24093,24094,24095,24096,24097,24098,24099,24100,24101,24102,24103,24104,24105,24106,24107,24108,24109,24110,24111,24112,24113,24114,24115,24116,24117,24118,24119,24120,24121,24122,24123,24124,24125,24126,24127,24128,24129,24130,24131,24132,24133,24134,24135,24136,24137,24138,24139,24140,24141,24142,24143,24144,24145,24146,24147,24148,24149,24150,24151,24152,24153,24154,24155,24156,24157,24158,24159,24160,24161,24162,24163,24164,24165,24166,24167,24168,24169,24170,24171,24172,24173,24174,24175,24176,24177,24178,24179,24180,24181,24182,24183,24184,24185,24186,24187,24188,24189,24190,24191,24192,24193,24194,24195,24196,24197,24198,24199,24200,24201,24202,24203,24204,24205,24206,24207,24208,24209,24210,24211,24212,24213,24214,24215,24216,24217,24218,24219,24220,24221,24222,24223,24224,24225,24226,24227,24228,24229,24230,24231,24232,24233,24234,24235,24236,24237,24238,24239,24240,24241,24242,24243,24244,24245,24246,24247,24248,24249,24250,24251,24252,24253,24254,24255,24256,24257,24258,24259,24260,24261,24262,24263,24264,24265,24266,24267,24268,24269,24270,24271,24272,24273,24274,24275,24276,24277,24278,24279,24280,24281,24282,24283,24284,24285,24286,24287,24288,24289,24290,24291,24292,24293,24294,24295,24296,24297,24298,24299,24300,24301,24302,24303,24304,24305,24306,24307,24308,24309,24310,24311,24312,24313,24314,24315,24316,24317,24318,24319,24320,24321,24322,24323,24324,24325,24326,24327,24328,24329,24330,24331,24332,24333,24334,24335,24336,24337,24338,24339,24340,24341,24342,24343,24344,24345,24346,24347,24348,24349,24350,24351,24352,24353,24354,24355,24356,24357,24358,24359,24360,24361,24362,24363,24364,24365,24366,24367,24368,24369,24370,24371,24372,24373,24374,24375,24376,24377,24378,24379,24380,24381,24382,24383,24384,24385,24386,24387,24388,24389,24390,24391,24392,24393,24394,24395,24396,24397,24398,24399,24400,24401,24402,24403,24404,24405,24406,24407,24408,24409,24410,24411,24412,24413,24414,24415,24416,24417,24418,24419,24420,24421,24422,24423,24424,24425,24426,24427,24428,24429,24430,24431,24432,24433,24434,24435,24436,24437,24438,24439,24440,24441,24442,24443,24444,24445,24446,24447,24448,24449,24450,24451,24452,24453,24454,24455,24456,24457,24458,24459,24460,24461,24462,24463,24464,24465,24466,24467,24468,24469,24470,24471,24472,24473,24474,24475,24476,24477,24478,24479,24480,24481,24482,24483,24484,24485,24486,24487,24488,24489,24490,24491,24492,24493,24494,24495,24496,24497,24498,24499,24500,24501,24502,24503,24504,24505,24506,24507,24508,24509,24510,24511,24512,24513,24514,24515,24516,24517,24518,24519,24520,24521,24522,24523,24524,24525,24526,24527,24528,24529,24530,24531,24532,24533,24534,24535,24536,24537,24538,24539,24540,24541,24542,24543,24544,24545,24546,24547,24548,24549,24550,24551,24552,24553,24554,24555,24556,24557,24558,24559,24560,24561,24562,24563,24564,24565,24566,24567,24568,24569,24570,24571,24572,24573,24574,24575,24576,24577,24578,24579,24580,24581,24582,24583,24584,24585,24586,24587,24588,24589,24590,24591,24592,24593,24594,24595,24596,24597,24598,24599,24600,24601,24602,24603,24604,24605,24606,24607,24608,24609,24610,24611,24612,24613,24614,24615,24616,24617,24618,24619,24620,24621,24622,24623,24624,24625,24626,24627,24628,24629,24630,24631,24632,24633,24634,24635,24636,24637,24638,24639,24640,24641,24642,24643,24644,24645,24646,24647,24648,24649,24650,24651,24652,24653,24654,24655,24656,24657,24658,24659,24660,24661,24662,24663,24664,24665,24666,24667,24668,24669,24670,24671,24672,24673,24674,24675,24676,24677,24678,24679,24680,24681,24682,24683,24684,24685,24686,24687,24688,24689,24690,24691,24692,24693,24694,24695,24696,24697,24698,24699,24700,24701,24702,24703,24704,24705,24706,24707,24708,24709,24710,24711,24712,24713,24714,24715,24716,24717,24718,24719,24720,24721,24722,24723,24724,24725,24726,24727,24728,24729,24730,24731,24732,24733,24734,24735,24736,24737,24738,24739,24740,24741,24742,24743,24744,24745,24746,24747,24748,24749,24750,24751,24752,24753,24754,24755,24756,24757,24758,24759,24760,24761,24762,24763,24764,24765,24766,24767,24768,24769,24770,24771,24772,24773,24774,24775,24776,24777,24778,24779,24780,24781,24782,24783,24784,24785,24786,24787,24788,24789,24790,24791,24792,24793,24794,24795,24796,24797,24798,24799,24800,24801,24802,24803,24804,24805,24806,24807,24808,24809,24810,24811,24812,24813,24814,24815,24816,24817,24818,24819,24820,24821,24822,24823,24824,24825,24826,24827,24828,24829,24830,24831,24832,24833,24834,24835,24836,24837,24838,24839,24840,24841,24842,24843,24844,24845,24846,24847,24848,24849,24850,24851,24852,24853,24854,24855,24856,24857,24858,24859,24860,24861,24862,24863,24864,24865,24866,24867,24868,24869,24870,24871,24872,24873,24874,24875,24876,24877,24878,24879,24880,24881,24882,24883,24884,24885,24886,24887,24888,24889,24890,24891,24892,24893,24894,24895,24896,24897,24898,24899,24900,24901,24902,24903,24904,24905,24906,24907,24908,24909,24910,24911,24912,24913,24914,24915,24916,24917,24918,24919,24920,24921,24922,24923,24924,24925,24926,24927,24928,24929,24930,24931,24932,24933,24934,24935,24936,24937,24938,24939,24940,24941,24942,24943,24944,24945,24946,24947,24948,24949,24950,24951,24952,24953,24954,24955,24956,24957,24958,24959,24960,24961,24962,24963,24964,24965,24966,24967,24968,24969,24970,24971,24972,24973,24974,24975,24976,24977,24978,24979,24980,24981,24982,24983,24984,24985,24986,24987,24988,24989,24990,24991,24992,24993,24994,24995,24996,24997,24998,24999,25000,25001,25002,25003,25004,25005,25006,25007,25008,25009,25010,25011,25012,25013,25014,25015,25016,25017,25018,25019,25020,25021,25022,25023,25024,25025,25026,25027,25028,25029,25030,25031,25032,25033,25034,25035,25036,25037,25038,25039,25040,25041,25042,25043,25044,25045,25046,25047,25048,25049,25050,25051,25052,25053,25054,25055,25056,25057,25058,25059,25060,25061,25062,25063,25064,25065,25066,25067,25068,25069,25070,25071,25072,25073,25074,25075,25076,25077,25078,25079,25080,25081,25082,25083,25084,25085,25086,25087,25088,25089,25090,25091,25092,25093,25094,25095,25096,25097,25098,25099,25100,25101,25102,25103,25104,25105,25106,25107,25108,25109,25110,25111,25112,25113,25114,25115,25116,25117,25118,25119,25120,25121,25122,25123,25124,25125,25126,25127,25128,25129,25130,25131,25132,25133,25134,25135,25136,25137,25138,25139,25140,25141,25142,25143,25144,25145,25146,25147,25148,25149,25150,25151,25152,25153,25154,25155,25156,25157,25158,25159,25160,25161,25162,25163,25164,25165,25166,25167,25168,25169,25170,25171,25172,25173,25174,25175,25176,25177,25178,25179,25180,25181,25182,25183,25184,25185,25186,25187,25188,25189,25190,25191,25192,25193,25194,25195,25196,25197,25198,25199,25200,25201,25202,25203,25204,25205,25206,25207,25208,25209,25210,25211,25212,25213,25214,25215,25216,25217,25218,25219,25220,25221,25222,25223,25224,25225,25226,25227,25228,25229,25230,25231,25232,25233,25234,25235,25236,25237,25238,25239,25240,25241,25242,25243,25244,25245,25246,25247,25248,25249,25250,25251,25252,25253,25254,25255,25256,25257,25258,25259,25260,25261,25262,25263,25264,25265,25266,25267,25268,25269,25270,25271,25272,25273,25274,25275,25276,25277,25278,25279,25280,25281,25282,25283,25284,25285,25286,25287,25288,25289,25290,25291,25292,25293,25294,25295,25296,25297,25298,25299,25300,25301,25302,25303,25304,25305,25306,25307,25308,25309,25310,25311,25312,25313,25314,25315,25316,25317,25318,25319,25320,25321,25322,25323,25324,25325,25326,25327,25328,25329,25330,25331,25332,25333,25334,25335,25336,25337,25338,25339,25340,25341,25342,25343,25344,25345,25346,25347,25348,25349,25350,25351,25352,25353,25354,25355,25356,25357,25358,25359,25360,25361,25362,25363,25364,25365,25366,25367,25368,25369,25370,25371,25372,25373,25374,25375,25376,25377,25378,25379,25380,25381,25382,25383,25384,25385,25386,25387,25388,25389,25390,25391,25392,25393,25394,25395,25396,25397,25398,25399,25400,25401,25402,25403,25404,25405,25406,25407,25408,25409,25410,25411,25412,25413,25414,25415,25416,25417,25418,25419,25420,25421,25422,25423,25424,25425,25426,25427,25428,25429,25430,25431,25432,25433,25434,25435,25436,25437,25438,25439,25440,25441,25442,25443,25444,25445,25446,25447,25448,25449,25450,25451,25452,25453,25454,25455,25456,25457,25458,25459,25460,25461,25462,25463,25464,25465,25466,25467,25468,25469,25470,25471,25472,25473,25474,25475,25476,25477,25478,25479,25480,25481,25482,25483,25484,25485,25486,25487,25488,25489,25490,25491,25492,25493,25494,25495,25496,25497,25498,25499,25500,25501,25502,25503,25504,25505,25506,25507,25508,25509,25510,25511,25512,25513,25514,25515,25516,25517,25518,25519,25520,25521,25522,25523,25524,25525,25526,25527,25528,25529,25530,25531,25532,25533,25534,25535,25536,25537,25538,25539,25540,25541,25542,25543,25544,25545,25546,25547,25548,25549,25550,25551,25552,25553,25554,25555,25556,25557,25558,25559,25560,25561,25562,25563,25564,25565,25566,25567,25568,25569,25570,25571,25572,25573,25574,25575,25576,25577,25578,25579,25580,25581,25582,25583,25584,25585,25586,25587,25588,25589,25590,25591,25592,25593,25594,25595,25596,25597,25598,25599,25600,25601,25602,25603,25604,25605,25606,25607,25608,25609,25610,25611,25612,25613,25614,25615,25616,25617,25618,25619,25620,25621,25622,25623,25624,25625,25626,25627,25628,25629,25630,25631,25632,25633,25634,25635,25636,25637,25638,25639,25640,25641,25642,25643,25644,25645,25646,25647,25648,25649,25650,25651,25652,25653,25654,25655,25656,25657,25658,25659,25660,25661,25662,25663,25664,25665,25666,25667,25668,25669,25670,25671,25672,25673,25674,25675,25676,25677,25678,25679,25680,25681,25682,25683,25684,25685,25686,25687,25688,25689,25690,25691,25692,25693,25694,25695,25696,25697,25698,25699,25700,25701,25702,25703,25704,25705,25706,25707,25708,25709,25710,25711,25712,25713,25714,25715,25716,25717,25718,25719,25720,25721,25722,25723,25724,25725,25726,25727,25728,25729,25730,25731,25732,25733,25734,25735,25736,25737,25738,25739,25740,25741,25742,25743,25744,25745,25746,25747,25748,25749,25750,25751,25752,25753,25754,25755,25756,25757,25758,25759,25760,25761,25762,25763,25764,25765,25766,25767,25768,25769,25770,25771,25772,25773,25774,25775,25776,25777,25778,25779,25780,25781,25782,25783,25784,25785,25786,25787,25788,25789,25790,25791,25792,25793,25794,25795,25796,25797,25798,25799,25800,25801,25802,25803,25804,25805,25806,25807,25808,25809,25810,25811,25812,25813,25814,25815,25816,25817,25818,25819,25820,25821,25822,25823,25824,25825,25826,25827,25828,25829,25830,25831,25832,25833,25834,25835,25836,25837,25838,25839,25840,25841,25842,25843,25844,25845,25846,25847,25848,25849,25850,25851,25852,25853,25854,25855,25856,25857,25858,25859,25860,25861,25862,25863,25864,25865,25866,25867,25868,25869,25870,25871,25872,25873,25874,25875,25876,25877,25878,25879,25880,25881,25882,25883,25884,25885,25886,25887,25888,25889,25890,25891,25892,25893,25894,25895,25896,25897,25898,25899,25900,25901,25902,25903,25904,25905,25906,25907,25908,25909,25910,25911,25912,25913,25914,25915,25916,25917,25918,25919,25920,25921,25922,25923,25924,25925,25926,25927,25928,25929,25930,25931,25932,25933,25934,25935,25936,25937,25938,25939,25940,25941,25942,25943,25944,25945,25946,25947,25948,25949,25950,25951,25952,25953,25954,25955,25956,25957,25958,25959,25960,25961,25962,25963,25964,25965,25966,25967,25968,25969,25970,25971,25972,25973,25974,25975,25976,25977,25978,25979,25980,25981,25982,25983,25984,25985,25986,25987,25988,25989,25990,25991,25992,25993,25994,25995,25996,25997,25998,25999,26000,26001,26002,26003,26004,26005,26006,26007,26008,26009,26010,26011,26012,26013,26014,26015,26016,26017,26018,26019,26020,26021,26022,26023,26024,26025,26026,26027,26028,26029,26030,26031,26032,26033,26034,26035,26036,26037,26038,26039,26040,26041,26042,26043,26044,26045,26046,26047,26048,26049,26050,26051,26052,26053,26054,26055,26056,26057,26058,26059,26060,26061,26062,26063,26064,26065,26066,26067,26068,26069,26070,26071,26072,26073,26074,26075,26076,26077,26078,26079,26080,26081,26082,26083,26084,26085,26086,26087,26088,26089,26090,26091,26092,26093,26094,26095,26096,26097,26098,26099,26100,26101,26102,26103,26104,26105,26106,26107,26108,26109,26110,26111,26112,26113,26114,26115,26116,26117,26118,26119,26120,26121,26122,26123,26124,26125,26126,26127,26128,26129,26130,26131,26132,26133,26134,26135,26136,26137,26138,26139,26140,26141,26142,26143,26144,26145,26146,26147,26148,26149,26150,26151,26152,26153,26154,26155,26156,26157,26158,26159,26160,26161,26162,26163,26164,26165,26166,26167,26168,26169,26170,26171,26172,26173,26174,26175,26176,26177,26178,26179,26180,26181,26182,26183,26184,26185,26186,26187,26188,26189,26190,26191,26192,26193,26194,26195,26196,26197,26198,26199,26200,26201,26202,26203,26204,26205,26206,26207,26208,26209,26210,26211,26212,26213,26214,26215,26216,26217,26218,26219,26220,26221,26222,26223,26224,26225,26226,26227,26228,26229,26230,26231,26232,26233,26234,26235,26236,26237,26238,26239,26240,26241,26242,26243,26244,26245,26246,26247,26248,26249,26250,26251,26252,26253,26254,26255,26256,26257,26258,26259,26260,26261,26262,26263,26264,26265,26266,26267,26268,26269,26270,26271,26272,26273,26274,26275,26276,26277,26278,26279,26280,26281,26282,26283,26284,26285,26286,26287,26288,26289,26290,26291,26292,26293,26294,26295,26296,26297,26298,26299,26300,26301,26302,26303,26304,26305,26306,26307,26308,26309,26310,26311,26312,26313,26314,26315,26316,26317,26318,26319,26320,26321,26322,26323,26324,26325,26326,26327,26328,26329,26330,26331,26332,26333,26334,26335,26336,26337,26338,26339,26340,26341,26342,26343,26344,26345,26346,26347,26348,26349,26350,26351,26352,26353,26354,26355,26356,26357,26358,26359,26360,26361,26362,26363,26364,26365,26366,26367,26368,26369,26370,26371,26372,26373,26374,26375,26376,26377,26378,26379,26380,26381,26382,26383,26384,26385,26386,26387,26388,26389,26390,26391,26392,26393,26394,26395,26396,26397,26398,26399,26400,26401,26402,26403,26404,26405,26406,26407,26408,26409,26410,26411,26412,26413,26414,26415,26416,26417,26418,26419,26420,26421,26422,26423,26424,26425,26426,26427,26428,26429,26430,26431,26432,26433,26434,26435,26436,26437,26438,26439,26440,26441,26442,26443,26444,26445,26446,26447,26448,26449,26450,26451,26452,26453,26454,26455,26456,26457,26458,26459,26460,26461,26462,26463,26464,26465,26466,26467,26468,26469,26470,26471,26472,26473,26474,26475,26476,26477,26478,26479,26480,26481,26482,26483,26484,26485,26486,26487,26488,26489,26490,26491,26492,26493,26494,26495,26496,26497,26498,26499,26500,26501,26502,26503,26504,26505,26506,26507,26508,26509,26510,26511,26512,26513,26514,26515,26516,26517,26518,26519,26520,26521,26522,26523,26524,26525,26526,26527,26528,26529,26530,26531,26532,26533,26534,26535,26536,26537,26538,26539,26540,26541,26542,26543,26544,26545,26546,26547,26548,26549,26550,26551,26552,26553,26554,26555,26556,26557,26558,26559,26560,26561,26562,26563,26564,26565,26566,26567,26568,26569,26570,26571,26572,26573,26574,26575,26576,26577,26578,26579,26580,26581,26582,26583,26584,26585,26586,26587,26588,26589,26590,26591,26592,26593,26594,26595,26596,26597,26598,26599,26600,26601,26602,26603,26604,26605,26606,26607,26608,26609,26610,26611,26612,26613,26614,26615,26616,26617,26618,26619,26620,26621,26622,26623,26624,26625,26626,26627,26628,26629,26630,26631,26632,26633,26634,26635,26636,26637,26638,26639,26640,26641,26642,26643,26644,26645,26646,26647,26648,26649,26650,26651,26652,26653,26654,26655,26656,26657,26658,26659,26660,26661,26662,26663,26664,26665,26666,26667,26668,26669,26670,26671,26672,26673,26674,26675,26676,26677,26678,26679,26680,26681,26682,26683,26684,26685,26686,26687,26688,26689,26690,26691,26692,26693,26694,26695,26696,26697,26698,26699,26700,26701,26702,26703,26704,26705,26706,26707,26708,26709,26710,26711,26712,26713,26714,26715,26716,26717,26718,26719,26720,26721,26722,26723,26724,26725,26726,26727,26728,26729,26730,26731,26732,26733,26734,26735,26736,26737,26738,26739,26740,26741,26742,26743,26744,26745,26746,26747,26748,26749,26750,26751,26752,26753,26754,26755,26756,26757,26758,26759,26760,26761,26762,26763,26764,26765,26766,26767,26768,26769,26770,26771,26772,26773,26774,26775,26776,26777,26778,26779,26780,26781,26782,26783,26784,26785,26786,26787,26788,26789,26790,26791,26792,26793,26794,26795,26796,26797,26798,26799,26800,26801,26802,26803,26804,26805,26806,26807,26808,26809,26810,26811,26812,26813,26814,26815,26816,26817,26818,26819,26820,26821,26822,26823,26824,26825,26826,26827,26828,26829,26830,26831,26832,26833,26834,26835,26836,26837,26838,26839,26840,26841,26842,26843,26844,26845,26846,26847,26848,26849,26850,26851,26852,26853,26854,26855,26856,26857,26858,26859,26860,26861,26862,26863,26864,26865,26866,26867,26868,26869,26870,26871,26872,26873,26874,26875,26876,26877,26878,26879,26880,26881,26882,26883,26884,26885,26886,26887,26888,26889,26890,26891,26892,26893,26894,26895,26896,26897,26898,26899,26900,26901,26902,26903,26904,26905,26906,26907,26908,26909,26910,26911,26912,26913,26914,26915,26916,26917,26918,26919,26920,26921,26922,26923,26924,26925,26926,26927,26928,26929,26930,26931,26932,26933,26934,26935,26936,26937,26938,26939,26940,26941,26942,26943,26944,26945,26946,26947,26948,26949,26950,26951,26952,26953,26954,26955,26956,26957,26958,26959,26960,26961,26962,26963,26964,26965,26966,26967,26968,26969,26970,26971,26972,26973,26974,26975,26976,26977,26978,26979,26980,26981,26982,26983,26984,26985,26986,26987,26988,26989,26990,26991,26992,26993,26994,26995,26996,26997,26998,26999,27000,27001,27002,27003,27004,27005,27006,27007,27008,27009,27010,27011,27012,27013,27014,27015,27016,27017,27018,27019,27020,27021,27022,27023,27024,27025,27026,27027,27028,27029,27030,27031,27032,27033,27034,27035,27036,27037,27038,27039,27040,27041,27042,27043,27044,27045,27046,27047,27048,27049,27050,27051,27052,27053,27054,27055,27056,27057,27058,27059,27060,27061,27062,27063,27064,27065,27066,27067,27068,27069,27070,27071,27072,27073,27074,27075,27076,27077,27078,27079,27080,27081,27082,27083,27084,27085,27086,27087,27088,27089,27090,27091,27092,27093,27094,27095,27096,27097,27098,27099,27100,27101,27102,27103,27104,27105,27106,27107,27108,27109,27110,27111,27112,27113,27114,27115,27116,27117,27118,27119,27120,27121,27122,27123,27124,27125,27126,27127,27128,27129,27130,27131,27132,27133,27134,27135,27136,27137,27138,27139,27140,27141,27142,27143,27144,27145,27146,27147,27148,27149,27150,27151,27152,27153,27154,27155,27156,27157,27158,27159,27160,27161,27162,27163,27164,27165,27166,27167,27168,27169,27170,27171,27172,27173,27174,27175,27176,27177,27178,27179,27180,27181,27182,27183,27184,27185,27186,27187,27188,27189,27190,27191,27192,27193,27194,27195,27196,27197,27198,27199,27200,27201,27202,27203,27204,27205,27206,27207,27208,27209,27210,27211,27212,27213,27214,27215,27216,27217,27218,27219,27220,27221,27222,27223,27224,27225,27226,27227,27228,27229,27230,27231,27232,27233,27234,27235,27236,27237,27238,27239,27240,27241,27242,27243,27244,27245,27246,27247,27248,27249,27250,27251,27252,27253,27254,27255,27256,27257,27258,27259,27260,27261,27262,27263,27264,27265,27266,27267,27268,27269,27270,27271,27272,27273,27274,27275,27276,27277,27278,27279,27280,27281,27282,27283,27284,27285,27286,27287,27288,27289,27290,27291,27292,27293,27294,27295,27296,27297,27298,27299,27300,27301,27302,27303,27304,27305,27306,27307,27308,27309,27310,27311,27312,27313,27314,27315,27316,27317,27318,27319,27320,27321,27322,27323,27324,27325,27326,27327,27328,27329,27330,27331,27332,27333,27334,27335,27336,27337,27338,27339,27340,27341,27342,27343,27344,27345,27346,27347,27348,27349,27350,27351,27352,27353,27354,27355,27356,27357,27358,27359,27360,27361,27362,27363,27364,27365,27366,27367,27368,27369,27370,27371,27372,27373,27374,27375,27376,27377,27378,27379,27380,27381,27382,27383,27384,27385,27386,27387,27388,27389,27390,27391,27392,27393,27394,27395,27396,27397,27398,27399,27400,27401,27402,27403,27404,27405,27406,27407,27408,27409,27410,27411,27412,27413,27414,27415,27416,27417,27418,27419,27420,27421,27422,27423,27424,27425,27426,27427,27428,27429,27430,27431,27432,27433,27434,27435,27436,27437,27438,27439,27440,27441,27442,27443,27444,27445,27446,27447,27448,27449,27450,27451,27452,27453,27454,27455,27456,27457,27458,27459,27460,27461,27462,27463,27464,27465,27466,27467,27468,27469,27470,27471,27472,27473,27474,27475,27476,27477,27478,27479,27480,27481,27482,27483,27484,27485,27486,27487,27488,27489,27490,27491,27492,27493,27494,27495,27496,27497,27498,27499,27500,27501,27502,27503,27504,27505,27506,27507,27508,27509,27510,27511,27512,27513,27514,27515,27516,27517,27518,27519,27520,27521,27522,27523,27524,27525,27526,27527,27528,27529,27530,27531,27532,27533,27534,27535,27536,27537,27538,27539,27540,27541,27542,27543,27544,27545,27546,27547,27548,27549,27550,27551,27552,27553,27554,27555,27556,27557,27558,27559,27560,27561,27562,27563,27564,27565,27566,27567,27568,27569,27570,27571,27572,27573,27574,27575,27576,27577,27578,27579,27580,27581,27582,27583,27584,27585,27586,27587,27588,27589,27590,27591,27592,27593,27594,27595,27596,27597,27598,27599,27600,27601,27602,27603,27604,27605,27606,27607,27608,27609,27610,27611,27612,27613,27614,27615,27616,27617,27618,27619,27620,27621,27622,27623,27624,27625,27626,27627,27628,27629,27630,27631,27632,27633,27634,27635,27636,27637,27638,27639,27640,27641,27642,27643,27644,27645,27646,27647,27648,27649,27650,27651,27652,27653,27654,27655,27656,27657,27658,27659,27660,27661,27662,27663,27664,27665,27666,27667,27668,27669,27670,27671,27672,27673,27674,27675,27676,27677,27678,27679,27680,27681,27682,27683,27684,27685,27686,27687,27688,27689,27690,27691,27692,27693,27694,27695,27696,27697,27698,27699,27700,27701,27702,27703,27704,27705,27706,27707,27708,27709,27710,27711,27712,27713,27714,27715,27716,27717,27718,27719,27720,27721,27722,27723,27724,27725,27726,27727,27728,27729,27730,27731,27732,27733,27734,27735,27736,27737,27738,27739,27740,27741,27742,27743,27744,27745,27746,27747,27748,27749,27750,27751,27752,27753,27754,27755,27756,27757,27758,27759,27760,27761,27762,27763,27764,27765,27766,27767,27768,27769,27770,27771,27772,27773,27774,27775,27776,27777,27778,27779,27780,27781,27782,27783,27784,27785,27786,27787,27788,27789,27790,27791,27792,27793,27794,27795,27796,27797,27798,27799,27800,27801,27802,27803,27804,27805,27806,27807,27808,27809,27810,27811,27812,27813,27814,27815,27816,27817,27818,27819,27820,27821,27822,27823,27824,27825,27826,27827,27828,27829,27830,27831,27832,27833,27834,27835,27836,27837,27838,27839,27840,27841,27842,27843,27844,27845,27846,27847,27848,27849,27850,27851,27852,27853,27854,27855,27856,27857,27858,27859,27860,27861,27862,27863,27864,27865,27866,27867,27868,27869,27870,27871,27872,27873,27874,27875,27876,27877,27878,27879,27880,27881,27882,27883,27884,27885,27886,27887,27888,27889,27890,27891,27892,27893,27894,27895,27896,27897,27898,27899,27900,27901,27902,27903,27904,27905,27906,27907,27908,27909,27910,27911,27912,27913,27914,27915,27916,27917,27918,27919,27920,27921,27922,27923,27924,27925,27926,27927,27928,27929,27930,27931,27932,27933,27934,27935,27936,27937,27938,27939,27940,27941,27942,27943,27944,27945,27946,27947,27948,27949,27950,27951,27952,27953,27954,27955,27956,27957,27958,27959,27960,27961,27962,27963,27964,27965,27966,27967,27968,27969,27970,27971,27972,27973,27974,27975,27976,27977,27978,27979,27980,27981,27982,27983,27984,27985,27986,27987,27988,27989,27990,27991,27992,27993,27994,27995,27996,27997,27998,27999,28000,28001,28002,28003,28004,28005,28006,28007,28008,28009,28010,28011,28012,28013,28014,28015,28016,28017,28018,28019,28020,28021,28022,28023,28024,28025,28026,28027,28028,28029,28030,28031,28032,28033,28034,28035,28036,28037,28038,28039,28040,28041,28042,28043,28044,28045,28046,28047,28048,28049,28050,28051,28052,28053,28054,28055,28056,28057,28058,28059,28060,28061,28062,28063,28064,28065,28066,28067,28068,28069,28070,28071,28072,28073,28074,28075,28076,28077,28078,28079,28080,28081,28082,28083,28084,28085,28086,28087,28088,28089,28090,28091,28092,28093,28094,28095,28096,28097,28098,28099,28100,28101,28102,28103,28104,28105,28106,28107,28108,28109,28110,28111,28112,28113,28114,28115,28116,28117,28118,28119,28120,28121,28122,28123,28124,28125,28126,28127,28128,28129,28130,28131,28132,28133,28134,28135,28136,28137,28138,28139,28140,28141,28142,28143,28144,28145,28146,28147,28148,28149,28150,28151,28152,28153,28154,28155,28156,28157,28158,28159,28160,28161,28162,28163,28164,28165,28166,28167,28168,28169,28170,28171,28172,28173,28174,28175,28176,28177,28178,28179,28180,28181,28182,28183,28184,28185,28186,28187,28188,28189,28190,28191,28192,28193,28194,28195,28196,28197,28198,28199,28200,28201,28202,28203,28204,28205,28206,28207,28208,28209,28210,28211,28212,28213,28214,28215,28216,28217,28218,28219,28220,28221,28222,28223,28224,28225,28226,28227,28228,28229,28230,28231,28232,28233,28234,28235,28236,28237,28238,28239,28240,28241,28242,28243,28244,28245,28246,28247,28248,28249,28250,28251,28252,28253,28254,28255,28256,28257,28258,28259,28260,28261,28262,28263,28264,28265,28266,28267,28268,28269,28270,28271,28272,28273,28274,28275,28276,28277,28278,28279,28280,28281,28282,28283,28284,28285,28286,28287,28288,28289,28290,28291,28292,28293,28294,28295,28296,28297,28298,28299,28300,28301,28302,28303,28304,28305,28306,28307,28308,28309,28310,28311,28312,28313,28314,28315,28316,28317,28318,28319,28320,28321,28322,28323,28324,28325,28326,28327,28328,28329,28330,28331,28332,28333,28334,28335,28336,28337,28338,28339,28340,28341,28342,28343,28344,28345,28346,28347,28348,28349,28350,28351,28352,28353,28354,28355,28356,28357,28358,28359,28360,28361,28362,28363,28364,28365,28366,28367,28368,28369,28370,28371,28372,28373,28374,28375,28376,28377,28378,28379,28380,28381,28382,28383,28384,28385,28386,28387,28388,28389,28390,28391,28392,28393,28394,28395,28396,28397,28398,28399,28400,28401,28402,28403,28404,28405,28406,28407,28408,28409,28410,28411,28412,28413,28414,28415,28416,28417,28418,28419,28420,28421,28422,28423,28424,28425,28426,28427,28428,28429,28430,28431,28432,28433,28434,28435,28436,28437,28438,28439,28440,28441,28442,28443,28444,28445,28446,28447,28448,28449,28450,28451,28452,28453,28454,28455,28456,28457,28458,28459,28460,28461,28462,28463,28464,28465,28466,28467,28468,28469,28470,28471,28472,28473,28474,28475,28476,28477,28478,28479,28480,28481,28482,28483,28484,28485,28486,28487,28488,28489,28490,28491,28492,28493,28494,28495,28496,28497,28498,28499,28500,28501,28502,28503,28504,28505,28506,28507,28508,28509,28510,28511,28512,28513,28514,28515,28516,28517,28518,28519,28520,28521,28522,28523,28524,28525,28526,28527,28528,28529,28530,28531,28532,28533,28534,28535,28536,28537,28538,28539,28540,28541,28542,28543,28544,28545,28546,28547,28548,28549,28550,28551,28552,28553,28554,28555,28556,28557,28558,28559,28560,28561,28562,28563,28564,28565,28566,28567,28568,28569,28570,28571,28572,28573,28574,28575,28576,28577,28578,28579,28580,28581,28582,28583,28584,28585,28586,28587,28588,28589,28590,28591,28592,28593,28594,28595,28596,28597,28598,28599,28600,28601,28602,28603,28604,28605,28606,28607,28608,28609,28610,28611,28612,28613,28614,28615,28616,28617,28618,28619,28620,28621,28622,28623,28624,28625,28626,28627,28628,28629,28630,28631,28632,28633,28634,28635,28636,28637,28638,28639,28640,28641,28642,28643,28644,28645,28646,28647,28648,28649,28650,28651,28652,28653,28654,28655,28656,28657,28658,28659,28660,28661,28662,28663,28664,28665,28666,28667,28668,28669,28670,28671,28672,28673,28674,28675,28676,28677,28678,28679,28680,28681,28682,28683,28684,28685,28686,28687,28688,28689,28690,28691,28692,28693,28694,28695,28696,28697,28698,28699,28700,28701,28702,28703,28704,28705,28706,28707,28708,28709,28710,28711,28712,28713,28714,28715,28716,28717,28718,28719,28720,28721,28722,28723,28724,28725,28726,28727,28728,28729,28730,28731,28732,28733,28734,28735,28736,28737,28738,28739,28740,28741,28742,28743,28744,28745,28746,28747,28748,28749,28750,28751,28752,28753,28754,28755,28756,28757,28758,28759,28760,28761,28762,28763,28764,28765,28766,28767,28768,28769,28770,28771,28772,28773,28774,28775,28776,28777,28778,28779,28780,28781,28782,28783,28784,28785,28786,28787,28788,28789,28790,28791,28792,28793,28794,28795,28796,28797,28798,28799,28800,28801,28802,28803,28804,28805,28806,28807,28808,28809,28810,28811,28812,28813,28814,28815,28816,28817,28818,28819,28820,28821,28822,28823,28824,28825,28826,28827,28828,28829,28830,28831,28832,28833,28834,28835,28836,28837,28838,28839,28840,28841,28842,28843,28844,28845,28846,28847,28848,28849,28850,28851,28852,28853,28854,28855,28856,28857,28858,28859,28860,28861,28862,28863,28864,28865,28866,28867,28868,28869,28870,28871,28872,28873,28874,28875,28876,28877,28878,28879,28880,28881,28882,28883,28884,28885,28886,28887,28888,28889,28890,28891,28892,28893,28894,28895,28896,28897,28898,28899,28900,28901,28902,28903,28904,28905,28906,28907,28908,28909,28910,28911,28912,28913,28914,28915,28916,28917,28918,28919,28920,28921,28922,28923,28924,28925,28926,28927,28928,28929,28930,28931,28932,28933,28934,28935,28936,28937,28938,28939,28940,28941,28942,28943,28944,28945,28946,28947,28948,28949,28950,28951,28952,28953,28954,28955,28956,28957,28958,28959,28960,28961,28962,28963,28964,28965,28966,28967,28968,28969,28970,28971,28972,28973,28974,28975,28976,28977,28978,28979,28980,28981,28982,28983,28984,28985,28986,28987,28988,28989,28990,28991,28992,28993,28994,28995,28996,28997,28998,28999,29000,29001,29002,29003,29004,29005,29006,29007,29008,29009,29010,29011,29012,29013,29014,29015,29016,29017,29018,29019,29020,29021,29022,29023,29024,29025,29026,29027,29028,29029,29030,29031,29032,29033,29034,29035,29036,29037,29038,29039,29040,29041,29042,29043,29044,29045,29046,29047,29048,29049,29050,29051,29052,29053,29054,29055,29056,29057,29058,29059,29060,29061,29062,29063,29064,29065,29066,29067,29068,29069,29070,29071,29072,29073,29074,29075,29076,29077,29078,29079,29080,29081,29082,29083,29084,29085,29086,29087,29088,29089,29090,29091,29092,29093,29094,29095,29096,29097,29098,29099,29100,29101,29102,29103,29104,29105,29106,29107,29108,29109,29110,29111,29112,29113,29114,29115,29116,29117,29118,29119,29120,29121,29122,29123,29124,29125,29126,29127,29128,29129,29130,29131,29132,29133,29134,29135,29136,29137,29138,29139,29140,29141,29142,29143,29144,29145,29146,29147,29148,29149,29150,29151,29152,29153,29154,29155,29156,29157,29158,29159,29160,29161,29162,29163,29164,29165,29166,29167,29168,29169,29170,29171,29172,29173,29174,29175,29176,29177,29178,29179,29180,29181,29182,29183,29184,29185,29186,29187,29188,29189,29190,29191,29192,29193,29194,29195,29196,29197,29198,29199,29200,29201,29202,29203,29204,29205,29206,29207,29208,29209,29210,29211,29212,29213,29214,29215,29216,29217,29218,29219,29220,29221,29222,29223,29224,29225,29226,29227,29228,29229,29230,29231,29232,29233,29234,29235,29236,29237,29238,29239,29240,29241,29242,29243,29244,29245,29246,29247,29248,29249,29250,29251,29252,29253,29254,29255,29256,29257,29258,29259,29260,29261,29262,29263,29264,29265,29266,29267,29268,29269,29270,29271,29272,29273,29274,29275,29276,29277,29278,29279,29280,29281,29282,29283,29284,29285,29286,29287,29288,29289,29290,29291,29292,29293,29294,29295,29296,29297,29298,29299,29300,29301,29302,29303,29304,29305,29306,29307,29308,29309,29310,29311,29312,29313,29314,29315,29316,29317,29318,29319,29320,29321,29322,29323,29324,29325,29326,29327,29328,29329,29330,29331,29332,29333,29334,29335,29336,29337,29338,29339,29340,29341,29342,29343,29344,29345,29346,29347,29348,29349,29350,29351,29352,29353,29354,29355,29356,29357,29358,29359,29360,29361,29362,29363,29364,29365,29366,29367,29368,29369,29370,29371,29372,29373,29374,29375,29376,29377,29378,29379,29380,29381,29382,29383,29384,29385,29386,29387,29388,29389,29390,29391,29392,29393,29394,29395,29396,29397,29398,29399,29400,29401,29402,29403,29404,29405,29406,29407,29408,29409,29410,29411,29412,29413,29414,29415,29416,29417,29418,29419,29420,29421,29422,29423,29424,29425,29426,29427,29428,29429,29430,29431,29432,29433,29434,29435,29436,29437,29438,29439,29440,29441,29442,29443,29444,29445,29446,29447,29448,29449,29450,29451,29452,29453,29454,29455,29456,29457,29458,29459,29460,29461,29462,29463,29464,29465,29466,29467,29468,29469,29470,29471,29472,29473,29474,29475,29476,29477,29478,29479,29480,29481,29482,29483,29484,29485,29486,29487,29488,29489,29490,29491,29492,29493,29494,29495,29496,29497,29498,29499,29500,29501,29502,29503,29504,29505,29506,29507,29508,29509,29510,29511,29512,29513,29514,29515,29516,29517,29518,29519,29520,29521,29522,29523,29524,29525,29526,29527,29528,29529,29530,29531,29532,29533,29534,29535,29536,29537,29538,29539,29540,29541,29542,29543,29544,29545,29546,29547,29548,29549,29550,29551,29552,29553,29554,29555,29556,29557,29558,29559,29560,29561,29562,29563,29564,29565,29566,29567,29568,29569,29570,29571,29572,29573,29574,29575,29576,29577,29578,29579,29580,29581,29582,29583,29584,29585,29586,29587,29588,29589,29590,29591,29592,29593,29594,29595,29596,29597,29598,29599,29600,29601,29602,29603,29604,29605,29606,29607,29608,29609,29610,29611,29612,29613,29614,29615,29616,29617,29618,29619,29620,29621,29622,29623,29624,29625,29626,29627,29628,29629,29630,29631,29632,29633,29634,29635,29636,29637,29638,29639,29640,29641,29642,29643,29644,29645,29646,29647,29648,29649,29650,29651,29652,29653,29654,29655,29656,29657,29658,29659,29660,29661,29662,29663,29664,29665,29666,29667,29668,29669,29670,29671,29672,29673,29674,29675,29676,29677,29678,29679,29680,29681,29682,29683,29684,29685,29686,29687,29688,29689,29690,29691,29692,29693,29694,29695,29696,29697,29698,29699,29700,29701,29702,29703,29704,29705,29706,29707,29708,29709,29710,29711,29712,29713,29714,29715,29716,29717,29718,29719,29720,29721,29722,29723,29724,29725,29726,29727,29728,29729,29730,29731,29732,29733,29734,29735,29736,29737,29738,29739,29740,29741,29742,29743,29744,29745,29746,29747,29748,29749,29750,29751,29752,29753,29754,29755,29756,29757,29758,29759,29760,29761,29762,29763,29764,29765,29766,29767,29768,29769,29770,29771,29772,29773,29774,29775,29776,29777,29778,29779,29780,29781,29782,29783,29784,29785,29786,29787,29788,29789,29790,29791,29792,29793,29794,29795,29796,29797,29798,29799,29800,29801,29802,29803,29804,29805,29806,29807,29808,29809,29810,29811,29812,29813,29814,29815,29816,29817,29818,29819,29820,29821,29822,29823,29824,29825,29826,29827,29828,29829,29830,29831,29832,29833,29834,29835,29836,29837,29838,29839,29840,29841,29842,29843,29844,29845,29846,29847,29848,29849,29850,29851,29852,29853,29854,29855,29856,29857,29858,29859,29860,29861,29862,29863,29864,29865,29866,29867,29868,29869,29870,29871,29872,29873,29874,29875,29876,29877,29878,29879,29880,29881,29882,29883,29884,29885,29886,29887,29888,29889,29890,29891,29892,29893,29894,29895,29896,29897,29898,29899,29900,29901,29902,29903,29904,29905,29906,29907,29908,29909,29910,29911,29912,29913,29914,29915,29916,29917,29918,29919,29920,29921,29922,29923,29924,29925,29926,29927,29928,29929,29930,29931,29932,29933,29934,29935,29936,29937,29938,29939,29940,29941,29942,29943,29944,29945,29946,29947,29948,29949,29950,29951,29952,29953,29954,29955,29956,29957,29958,29959,29960,29961,29962,29963,29964,29965,29966,29967,29968,29969,29970,29971,29972,29973,29974,29975,29976,29977,29978,29979,29980,29981,29982,29983,29984,29985,29986,29987,29988,29989,29990,29991,29992,29993,29994,29995,29996,29997,29998,29999,30000,30001,30002,30003,30004,30005,30006,30007,30008,30009,30010,30011,30012,30013,30014,30015,30016,30017,30018,30019,30020,30021,30022,30023,30024,30025,30026,30027,30028,30029,30030,30031,30032,30033,30034,30035,30036,30037,30038,30039,30040,30041,30042,30043,30044,30045,30046,30047,30048,30049,30050,30051,30052,30053,30054,30055,30056,30057,30058,30059,30060,30061,30062,30063,30064,30065,30066,30067,30068,30069,30070,30071,30072,30073,30074,30075,30076,30077,30078,30079,30080,30081,30082,30083,30084,30085,30086,30087,30088,30089,30090,30091,30092,30093,30094,30095,30096,30097,30098,30099,30100,30101,30102,30103,30104,30105,30106,30107,30108,30109,30110,30111,30112,30113,30114,30115,30116,30117,30118,30119,30120,30121,30122,30123,30124,30125,30126,30127,30128,30129,30130,30131,30132,30133,30134,30135,30136,30137,30138,30139,30140,30141,30142,30143,30144,30145,30146,30147,30148,30149,30150,30151,30152,30153,30154,30155,30156,30157,30158,30159,30160,30161,30162,30163,30164,30165,30166,30167,30168,30169,30170,30171,30172,30173,30174,30175,30176,30177,30178,30179,30180,30181,30182,30183,30184,30185,30186,30187,30188,30189,30190,30191,30192,30193,30194,30195,30196,30197,30198,30199,30200,30201,30202,30203,30204,30205,30206,30207,30208,30209,30210,30211,30212,30213,30214,30215,30216,30217,30218,30219,30220,30221,30222,30223,30224,30225,30226,30227,30228,30229,30230,30231,30232,30233,30234,30235,30236,30237,30238,30239,30240,30241,30242,30243,30244,30245,30246,30247,30248,30249,30250,30251,30252,30253,30254,30255,30256,30257,30258,30259,30260,30261,30262,30263,30264,30265,30266,30267,30268,30269,30270,30271,30272,30273,30274,30275,30276,30277,30278,30279,30280,30281,30282,30283,30284,30285,30286,30287,30288,30289,30290,30291,30292,30293,30294,30295,30296,30297,30298,30299,30300,30301,30302,30303,30304,30305,30306,30307,30308,30309,30310,30311,30312,30313,30314,30315,30316,30317,30318,30319,30320,30321,30322,30323,30324,30325,30326,30327,30328,30329,30330,30331,30332,30333,30334,30335,30336,30337,30338,30339,30340,30341,30342,30343,30344,30345,30346,30347,30348,30349,30350,30351,30352,30353,30354,30355,30356,30357,30358,30359,30360,30361,30362,30363,30364,30365,30366,30367,30368,30369,30370,30371,30372,30373,30374,30375,30376,30377,30378,30379,30380,30381,30382,30383,30384,30385,30386,30387,30388,30389,30390,30391,30392,30393,30394,30395,30396,30397,30398,30399,30400,30401,30402,30403,30404,30405,30406,30407,30408,30409,30410,30411,30412,30413,30414,30415,30416,30417,30418,30419,30420,30421,30422,30423,30424,30425,30426,30427,30428,30429,30430,30431,30432,30433,30434,30435,30436,30437,30438,30439,30440,30441,30442,30443,30444,30445,30446,30447,30448,30449,30450,30451,30452,30453,30454,30455,30456,30457,30458,30459,30460,30461,30462,30463,30464,30465,30466,30467,30468,30469,30470,30471,30472,30473,30474,30475,30476,30477,30478,30479,30480,30481,30482,30483,30484,30485,30486,30487,30488,30489,30490,30491,30492,30493,30494,30495,30496,30497,30498,30499,30500,30501,30502,30503,30504,30505,30506,30507,30508,30509,30510,30511,30512,30513,30514,30515,30516,30517,30518,30519,30520,30521,30522,30523,30524,30525,30526,30527,30528,30529,30530,30531,30532,30533,30534,30535,30536,30537,30538,30539,30540,30541,30542,30543,30544,30545,30546,30547,30548,30549,30550,30551,30552,30553,30554,30555,30556,30557,30558,30559,30560,30561,30562,30563,30564,30565,30566,30567,30568,30569,30570,30571,30572,30573,30574,30575,30576,30577,30578,30579,30580,30581,30582,30583,30584,30585,30586,30587,30588,30589,30590,30591,30592,30593,30594,30595,30596,30597,30598,30599,30600,30601,30602,30603,30604,30605,30606,30607,30608,30609,30610,30611,30612,30613,30614,30615,30616,30617,30618,30619,30620,30621,30622,30623,30624,30625,30626,30627,30628,30629,30630,30631,30632,30633,30634,30635,30636,30637,30638,30639,30640,30641,30642,30643,30644,30645,30646,30647,30648,30649,30650,30651,30652,30653,30654,30655,30656,30657,30658,30659,30660,30661,30662,30663,30664,30665,30666,30667,30668,30669,30670,30671,30672,30673,30674,30675,30676,30677,30678,30679,30680,30681,30682,30683,30684,30685,30686,30687,30688,30689,30690,30691,30692,30693,30694,30695,30696,30697,30698,30699,30700,30701,30702,30703,30704,30705,30706,30707,30708,30709,30710,30711,30712,30713,30714,30715,30716,30717,30718,30719,30720,30721,30722,30723,30724,30725,30726,30727,30728,30729,30730,30731,30732,30733,30734,30735,30736,30737,30738,30739,30740,30741,30742,30743,30744,30745,30746,30747,30748,30749,30750,30751,30752,30753,30754,30755,30756,30757,30758,30759,30760,30761,30762,30763,30764,30765,30766,30767,30768,30769,30770,30771,30772,30773,30774,30775,30776,30777,30778,30779,30780,30781,30782,30783,30784,30785,30786,30787,30788,30789,30790,30791,30792,30793,30794,30795,30796,30797,30798,30799,30800,30801,30802,30803,30804,30805,30806,30807,30808,30809,30810,30811,30812,30813,30814,30815,30816,30817,30818,30819,30820,30821,30822,30823,30824,30825,30826,30827,30828,30829,30830,30831,30832,30833,30834,30835,30836,30837,30838,30839,30840,30841,30842,30843,30844,30845,30846,30847,30848,30849,30850,30851,30852,30853,30854,30855,30856,30857,30858,30859,30860,30861,30862,30863,30864,30865,30866,30867,30868,30869,30870,30871,30872,30873,30874,30875,30876,30877,30878,30879,30880,30881,30882,30883,30884,30885,30886,30887,30888,30889,30890,30891,30892,30893,30894,30895,30896,30897,30898,30899,30900,30901,30902,30903,30904,30905,30906,30907,30908,30909,30910,30911,30912,30913,30914,30915,30916,30917,30918,30919,30920,30921,30922,30923,30924,30925,30926,30927,30928,30929,30930,30931,30932,30933,30934,30935,30936,30937,30938,30939,30940,30941,30942,30943,30944,30945,30946,30947,30948,30949,30950,30951,30952,30953,30954,30955,30956,30957,30958,30959,30960,30961,30962,30963,30964,30965,30966,30967,30968,30969,30970,30971,30972,30973,30974,30975,30976,30977,30978,30979,30980,30981,30982,30983,30984,30985,30986,30987,30988,30989,30990,30991,30992,30993,30994,30995,30996,30997,30998,30999,31000,31001,31002,31003,31004,31005,31006,31007,31008,31009,31010,31011,31012,31013,31014,31015,31016,31017,31018,31019,31020,31021,31022,31023,31024,31025,31026,31027,31028,31029,31030,31031,31032,31033,31034,31035,31036,31037,31038,31039,31040,31041,31042,31043,31044,31045,31046,31047,31048,31049,31050,31051,31052,31053,31054,31055,31056,31057,31058,31059,31060,31061,31062,31063,31064,31065,31066,31067,31068,31069,31070,31071,31072,31073,31074,31075,31076,31077,31078,31079,31080,31081,31082,31083,31084,31085,31086,31087,31088,31089,31090,31091,31092,31093,31094,31095,31096,31097,31098,31099,31100,31101,31102,31103,31104,31105,31106,31107,31108,31109,31110,31111,31112,31113,31114,31115,31116,31117,31118,31119,31120,31121,31122,31123,31124,31125,31126,31127,31128,31129,31130,31131,31132,31133,31134,31135,31136,31137,31138,31139,31140,31141,31142,31143,31144,31145,31146,31147,31148,31149,31150,31151,31152,31153,31154,31155,31156,31157,31158,31159,31160,31161,31162,31163,31164,31165,31166,31167,31168,31169,31170,31171,31172,31173,31174,31175,31176,31177,31178,31179,31180,31181,31182,31183,31184,31185,31186,31187,31188,31189,31190,31191,31192,31193,31194,31195,31196,31197,31198,31199,31200,31201,31202,31203,31204,31205,31206,31207,31208,31209,31210,31211,31212,31213,31214,31215,31216,31217,31218,31219,31220,31221,31222,31223,31224,31225,31226,31227,31228,31229,31230,31231,31232,31233,31234,31235,31236,31237,31238,31239,31240,31241,31242,31243,31244,31245,31246,31247,31248,31249,31250,31251,31252,31253,31254,31255,31256,31257,31258,31259,31260,31261,31262,31263,31264,31265,31266,31267,31268,31269,31270,31271,31272,31273,31274,31275,31276,31277,31278,31279,31280,31281,31282,31283,31284,31285,31286,31287,31288,31289,31290,31291,31292,31293,31294,31295,31296,31297,31298,31299,31300,31301,31302,31303,31304,31305,31306,31307,31308,31309,31310,31311,31312,31313,31314,31315,31316,31317,31318,31319,31320,31321,31322,31323,31324,31325,31326,31327,31328,31329,31330,31331,31332,31333,31334,31335,31336,31337,31338,31339,31340,31341,31342,31343,31344,31345,31346,31347,31348,31349,31350,31351,31352,31353,31354,31355,31356,31357,31358,31359,31360,31361,31362,31363,31364,31365,31366,31367,31368,31369,31370,31371,31372,31373,31374,31375,31376,31377,31378,31379,31380,31381,31382,31383,31384,31385,31386,31387,31388,31389,31390,31391,31392,31393,31394,31395,31396,31397,31398,31399,31400,31401,31402,31403,31404,31405,31406,31407,31408,31409,31410,31411,31412,31413,31414,31415,31416,31417,31418,31419,31420,31421,31422,31423,31424,31425,31426,31427,31428,31429,31430,31431,31432,31433,31434,31435,31436,31437,31438,31439,31440,31441,31442,31443,31444,31445,31446,31447,31448,31449,31450,31451,31452,31453,31454,31455,31456,31457,31458,31459,31460,31461,31462,31463,31464,31465,31466,31467,31468,31469,31470,31471,31472,31473,31474,31475,31476,31477,31478,31479,31480,31481,31482,31483,31484,31485,31486,31487,31488,31489,31490,31491,31492,31493,31494,31495,31496,31497,31498,31499,31500,31501,31502,31503,31504,31505,31506,31507,31508,31509,31510,31511,31512,31513,31514,31515,31516,31517,31518,31519,31520,31521,31522,31523,31524,31525,31526,31527,31528,31529,31530,31531,31532,31533,31534,31535,31536,31537,31538,31539,31540,31541,31542,31543,31544,31545,31546,31547,31548,31549,31550,31551,31552,31553,31554,31555,31556,31557,31558,31559,31560,31561,31562,31563,31564,31565,31566,31567,31568,31569,31570,31571,31572,31573,31574,31575,31576,31577,31578,31579,31580,31581,31582,31583,31584,31585,31586,31587,31588,31589,31590,31591,31592,31593,31594,31595,31596,31597,31598,31599,31600,31601,31602,31603,31604,31605,31606,31607,31608,31609,31610,31611,31612,31613,31614,31615,31616,31617,31618,31619,31620,31621,31622,31623,31624,31625,31626,31627,31628,31629,31630,31631,31632,31633,31634,31635,31636,31637,31638,31639,31640,31641,31642,31643,31644,31645,31646,31647,31648,31649,31650,31651,31652,31653,31654,31655,31656,31657,31658,31659,31660,31661,31662,31663,31664,31665,31666,31667,31668,31669,31670,31671,31672,31673,31674,31675,31676,31677,31678,31679,31680,31681,31682,31683,31684,31685,31686,31687,31688,31689,31690,31691,31692,31693,31694,31695,31696,31697,31698,31699,31700,31701,31702,31703,31704,31705,31706,31707,31708,31709,31710,31711,31712,31713,31714,31715,31716,31717,31718,31719,31720,31721,31722,31723,31724,31725,31726,31727,31728,31729,31730,31731,31732,31733,31734,31735,31736,31737,31738,31739,31740,31741,31742,31743,31744,31745,31746,31747,31748,31749,31750,31751,31752,31753,31754,31755,31756,31757,31758,31759,31760,31761,31762,31763,31764,31765,31766,31767,31768,31769,31770,31771,31772,31773,31774,31775,31776,31777,31778,31779,31780,31781,31782,31783,31784,31785,31786,31787,31788,31789,31790,31791,31792,31793,31794,31795,31796,31797,31798,31799,31800,31801,31802,31803,31804,31805,31806,31807,31808,31809,31810,31811,31812,31813,31814,31815,31816,31817,31818,31819,31820,31821,31822,31823,31824,31825,31826,31827,31828,31829,31830,31831,31832,31833,31834,31835,31836,31837,31838,31839,31840,31841,31842,31843,31844,31845,31846,31847,31848,31849,31850,31851,31852,31853,31854,31855,31856,31857,31858,31859,31860,31861,31862,31863,31864,31865,31866,31867,31868,31869,31870,31871,31872,31873,31874,31875,31876,31877,31878,31879,31880,31881,31882,31883,31884,31885,31886,31887,31888,31889,31890,31891,31892,31893,31894,31895,31896,31897,31898,31899,31900,31901,31902,31903,31904,31905,31906,31907,31908,31909,31910,31911,31912,31913,31914,31915,31916,31917,31918,31919,31920,31921,31922,31923,31924,31925,31926,31927,31928,31929,31930,31931,31932,31933,31934,31935,31936,31937,31938,31939,31940,31941,31942,31943,31944,31945,31946,31947,31948,31949,31950,31951,31952,31953,31954,31955,31956,31957,31958,31959,31960,31961,31962,31963,31964,31965,31966,31967,31968,31969,31970,31971,31972,31973,31974,31975,31976,31977,31978,31979,31980,31981,31982,31983,31984,31985,31986,31987,31988,31989,31990,31991,31992,31993,31994,31995,31996,31997,31998,31999,32000,32001,32002,32003,32004,32005,32006,32007,32008,32009,32010,32011,32012,32013,32014,32015,32016,32017,32018,32019,32020,32021,32022,32023,32024,32025,32026,32027,32028,32029,32030,32031,32032,32033,32034,32035,32036,32037,32038,32039,32040,32041,32042,32043,32044,32045,32046,32047,32048,32049,32050,32051,32052,32053,32054,32055,32056,32057,32058,32059,32060,32061,32062,32063,32064,32065,32066,32067,32068,32069,32070,32071,32072,32073,32074,32075,32076,32077,32078,32079,32080,32081,32082,32083,32084,32085,32086,32087,32088,32089,32090,32091,32092,32093,32094,32095,32096,32097,32098,32099,32100,32101,32102,32103,32104,32105,32106,32107,32108,32109,32110,32111,32112,32113,32114,32115,32116,32117,32118,32119,32120,32121,32122,32123,32124,32125,32126,32127,32128,32129,32130,32131,32132,32133,32134,32135,32136,32137,32138,32139,32140,32141,32142,32143,32144,32145,32146,32147,32148,32149,32150,32151,32152,32153,32154,32155,32156,32157,32158,32159,32160,32161,32162,32163,32164,32165,32166,32167,32168,32169,32170,32171,32172,32173,32174,32175,32176,32177,32178,32179,32180,32181,32182,32183,32184,32185,32186,32187,32188,32189,32190,32191,32192,32193,32194,32195,32196,32197,32198,32199,32200,32201,32202,32203,32204,32205,32206,32207,32208,32209,32210,32211,32212,32213,32214,32215,32216,32217,32218,32219,32220,32221,32222,32223,32224,32225,32226,32227,32228,32229,32230,32231,32232,32233,32234,32235,32236,32237,32238,32239,32240,32241,32242,32243,32244,32245,32246,32247,32248,32249,32250,32251,32252,32253,32254,32255,32256,32257,32258,32259,32260,32261,32262,32263,32264,32265,32266,32267,32268,32269,32270,32271,32272,32273,32274,32275,32276,32277,32278,32279,32280,32281,32282,32283,32284,32285,32286,32287,32288,32289,32290,32291,32292,32293,32294,32295,32296,32297,32298,32299,32300,32301,32302,32303,32304,32305,32306,32307,32308,32309,32310,32311,32312,32313,32314,32315,32316,32317,32318,32319,32320,32321,32322,32323,32324,32325,32326,32327,32328,32329,32330,32331,32332,32333,32334,32335,32336,32337,32338,32339,32340,32341,32342,32343,32344,32345,32346,32347,32348,32349,32350,32351,32352,32353,32354,32355,32356,32357,32358,32359,32360,32361,32362,32363,32364,32365,32366,32367,32368,32369,32370,32371,32372,32373,32374,32375,32376,32377,32378,32379,32380,32381,32382,32383,32384,32385,32386,32387,32388,32389,32390,32391,32392,32393,32394,32395,32396,32397,32398,32399,32400,32401,32402,32403,32404,32405,32406,32407,32408,32409,32410,32411,32412,32413,32414,32415,32416,32417,32418,32419,32420,32421,32422,32423,32424,32425,32426,32427,32428,32429,32430,32431,32432,32433,32434,32435,32436,32437,32438,32439,32440,32441,32442,32443,32444,32445,32446,32447,32448,32449,32450,32451,32452,32453,32454,32455,32456,32457,32458,32459,32460,32461,32462,32463,32464,32465,32466,32467,32468,32469,32470,32471,32472,32473,32474,32475,32476,32477,32478,32479,32480,32481,32482,32483,32484,32485,32486,32487,32488,32489,32490,32491,32492,32493,32494,32495,32496,32497,32498,32499,32500,32501,32502,32503,32504,32505,32506,32507,32508,32509,32510,32511,32512,32513,32514,32515,32516,32517,32518,32519,32520,32521,32522,32523,32524,32525,32526,32527,32528,32529,32530,32531,32532,32533,32534,32535,32536,32537,32538,32539,32540,32541,32542,32543,32544,32545,32546,32547,32548,32549,32550,32551,32552,32553,32554,32555,32556,32557,32558,32559,32560,32561,32562,32563,32564,32565,32566,32567,32568,32569,32570,32571,32572,32573,32574,32575,32576,32577,32578,32579,32580,32581,32582,32583,32584,32585,32586,32587,32588,32589,32590,32591,32592,32593,32594,32595,32596,32597,32598,32599,32600,32601,32602,32603,32604,32605,32606,32607,32608,32609,32610,32611,32612,32613,32614,32615,32616,32617,32618,32619,32620,32621,32622,32623,32624,32625,32626,32627,32628,32629,32630,32631,32632,32633,32634,32635,32636,32637,32638,32639,32640,32641,32642,32643,32644,32645,32646,32647,32648,32649,32650,32651,32652,32653,32654,32655,32656,32657,32658,32659,32660,32661,32662,32663,32664,32665,32666,32667,32668,32669,32670,32671,32672,32673,32674,32675,32676,32677,32678,32679,32680,32681,32682,32683,32684,32685,32686,32687,32688,32689,32690,32691,32692,32693,32694,32695,32696,32697,32698,32699,32700,32701,32702,32703,32704,32705,32706,32707,32708,32709,32710,32711,32712,32713,32714,32715,32716,32717,32718,32719,32720,32721,32722,32723,32724,32725,32726,32727,32728,32729,32730,32731,32732,32733,32734,32735,32736,32737,32738,32739,32740,32741,32742,32743,32744,32745,32746,32747,32748,32749,32750,32751,32752,32753,32754,32755,32756,32757,32758,32759,32760,32761,32762,32763,32764,32765,32766,32767,32768,32769,32770,32771,32772,32773,32774,32775,32776,32777,32778,32779,32780,32781,32782,32783,32784,32785,32786,32787,32788,32789,32790,32791,32792,32793,32794,32795,32796,32797,32798,32799,32800,32801,32802,32803,32804,32805,32806,32807,32808,32809,32810,32811,32812,32813,32814,32815,32816,32817,32818,32819,32820,32821,32822,32823,32824,32825,32826,32827,32828,32829,32830,32831,32832,32833,32834,32835,32836,32837,32838,32839,32840,32841,32842,32843,32844,32845,32846,32847,32848,32849,32850,32851,32852,32853,32854,32855,32856,32857,32858,32859,32860,32861,32862,32863,32864,32865,32866,32867,32868,32869,32870,32871,32872,32873,32874,32875,32876,32877,32878,32879,32880,32881,32882,32883,32884,32885,32886,32887,32888,32889,32890,32891,32892,32893,32894,32895,32896,32897,32898,32899,32900,32901,32902,32903,32904,32905,32906,32907,32908,32909,32910,32911,32912,32913,32914,32915,32916,32917,32918,32919,32920,32921,32922,32923,32924,32925,32926,32927,32928,32929,32930,32931,32932,32933,32934,32935,32936,32937,32938,32939,32940,32941,32942,32943,32944,32945,32946,32947,32948,32949,32950,32951,32952,32953,32954,32955,32956,32957,32958,32959,32960,32961,32962,32963,32964,32965,32966,32967,32968,32969,32970,32971,32972,32973,32974,32975,32976,32977,32978,32979,32980,32981,32982,32983,32984,32985,32986,32987,32988,32989,32990,32991,32992,32993,32994,32995,32996,32997,32998,32999,33000,33001,33002,33003,33004,33005,33006,33007,33008,33009,33010,33011,33012,33013,33014,33015,33016,33017,33018,33019,33020,33021,33022,33023,33024,33025,33026,33027,33028,33029,33030,33031,33032,33033,33034,33035,33036,33037,33038,33039,33040,33041,33042,33043,33044,33045,33046,33047,33048,33049,33050,33051,33052,33053,33054,33055,33056,33057,33058,33059,33060,33061,33062,33063,33064,33065,33066,33067,33068,33069,33070,33071,33072,33073,33074,33075,33076,33077,33078,33079,33080,33081,33082,33083,33084,33085,33086,33087,33088,33089,33090,33091,33092,33093,33094,33095,33096,33097,33098,33099,33100,33101,33102,33103,33104,33105,33106,33107,33108,33109,33110,33111,33112,33113,33114,33115,33116,33117,33118,33119,33120,33121,33122,33123,33124,33125,33126,33127,33128,33129,33130,33131,33132,33133,33134,33135,33136,33137,33138,33139,33140,33141,33142,33143,33144,33145,33146,33147,33148,33149,33150,33151,33152,33153,33154,33155,33156,33157,33158,33159,33160,33161,33162,33163,33164,33165,33166,33167,33168,33169,33170,33171,33172,33173,33174,33175,33176,33177,33178,33179,33180,33181,33182,33183,33184,33185,33186,33187,33188,33189,33190,33191,33192,33193,33194,33195,33196,33197,33198,33199,33200,33201,33202,33203,33204,33205,33206,33207,33208,33209,33210,33211,33212,33213,33214,33215,33216,33217,33218,33219,33220,33221,33222,33223,33224,33225,33226,33227,33228,33229,33230,33231,33232,33233,33234,33235,33236,33237,33238,33239,33240,33241,33242,33243,33244,33245,33246,33247,33248,33249,33250,33251,33252,33253,33254,33255,33256,33257,33258,33259,33260,33261,33262,33263,33264,33265,33266,33267,33268,33269,33270,33271,33272,33273,33274,33275,33276,33277,33278,33279,33280,33281,33282,33283,33284,33285,33286,33287,33288,33289,33290,33291,33292,33293,33294,33295,33296,33297,33298,33299,33300,33301,33302,33303,33304,33305,33306,33307,33308,33309,33310,33311,33312,33313,33314,33315,33316,33317,33318,33319,33320,33321,33322,33323,33324,33325,33326,33327,33328,33329,33330,33331,33332,33333,33334,33335,33336,33337,33338,33339,33340,33341,33342,33343,33344,33345,33346,33347,33348,33349,33350,33351,33352,33353,33354,33355,33356,33357,33358,33359,33360,33361,33362,33363,33364,33365,33366,33367,33368,33369,33370,33371,33372,33373,33374,33375,33376,33377,33378,33379,33380,33381,33382,33383,33384,33385,33386,33387,33388,33389,33390,33391,33392,33393,33394,33395,33396,33397,33398,33399,33400,33401,33402,33403,33404,33405,33406,33407,33408,33409,33410,33411,33412,33413,33414,33415,33416,33417,33418,33419,33420,33421,33422,33423,33424,33425,33426,33427,33428,33429,33430,33431,33432,33433,33434,33435,33436,33437,33438,33439,33440,33441,33442,33443,33444,33445,33446,33447,33448,33449,33450,33451,33452,33453,33454,33455,33456,33457,33458,33459,33460,33461,33462,33463,33464,33465,33466,33467,33468,33469,33470,33471,33472,33473,33474,33475,33476,33477,33478,33479,33480,33481,33482,33483,33484,33485,33486,33487,33488,33489,33490,33491,33492,33493,33494,33495,33496,33497,33498,33499,33500,33501,33502,33503,33504,33505,33506,33507,33508,33509,33510,33511,33512,33513,33514,33515,33516,33517,33518,33519,33520,33521,33522,33523,33524,33525,33526,33527,33528,33529,33530,33531,33532,33533,33534,33535,33536,33537,33538,33539,33540,33541,33542,33543,33544,33545,33546,33547,33548,33549,33550,33551,33552,33553,33554,33555,33556,33557,33558,33559,33560,33561,33562,33563,33564,33565,33566,33567,33568,33569,33570,33571,33572,33573,33574,33575,33576,33577,33578,33579,33580,33581,33582,33583,33584,33585,33586,33587,33588,33589,33590,33591,33592,33593,33594,33595,33596,33597,33598,33599,33600,33601,33602,33603,33604,33605,33606,33607,33608,33609,33610,33611,33612,33613,33614,33615,33616,33617,33618,33619,33620,33621,33622,33623,33624,33625,33626,33627,33628,33629,33630,33631,33632,33633,33634,33635,33636,33637,33638,33639,33640,33641,33642,33643,33644,33645,33646,33647,33648,33649,33650,33651,33652,33653,33654,33655,33656,33657,33658,33659,33660,33661,33662,33663,33664,33665,33666,33667,33668,33669,33670,33671,33672,33673,33674,33675,33676,33677,33678,33679,33680,33681,33682,33683,33684,33685,33686,33687,33688,33689,33690,33691,33692,33693,33694,33695,33696,33697,33698,33699,33700,33701,33702,33703,33704,33705,33706,33707,33708,33709,33710,33711,33712,33713,33714,33715,33716,33717,33718,33719,33720,33721,33722,33723,33724,33725,33726,33727,33728,33729,33730,33731,33732,33733,33734,33735,33736,33737,33738,33739,33740,33741,33742,33743,33744,33745,33746,33747,33748,33749,33750,33751,33752,33753,33754,33755,33756,33757,33758,33759,33760,33761,33762,33763,33764,33765,33766,33767,33768,33769,33770,33771,33772,33773,33774,33775,33776,33777,33778,33779,33780,33781,33782,33783,33784,33785,33786,33787,33788,33789,33790,33791,33792,33793,33794,33795,33796,33797,33798,33799,33800,33801,33802,33803,33804,33805,33806,33807,33808,33809,33810,33811,33812,33813,33814,33815,33816,33817,33818,33819,33820,33821,33822,33823,33824,33825,33826,33827,33828,33829,33830,33831,33832,33833,33834,33835,33836,33837,33838,33839,33840,33841,33842,33843,33844,33845,33846,33847,33848,33849,33850,33851,33852,33853,33854,33855,33856,33857,33858,33859,33860,33861,33862,33863,33864,33865,33866,33867,33868,33869,33870,33871,33872,33873,33874,33875,33876,33877,33878,33879,33880,33881,33882,33883,33884,33885,33886,33887,33888,33889,33890,33891,33892,33893,33894,33895,33896,33897,33898,33899,33900,33901,33902,33903,33904,33905,33906,33907,33908,33909,33910,33911,33912,33913,33914,33915,33916,33917,33918,33919,33920,33921,33922,33923,33924,33925,33926,33927,33928,33929,33930,33931,33932,33933,33934,33935,33936,33937,33938,33939,33940,33941,33942,33943,33944,33945,33946,33947,33948,33949,33950,33951,33952,33953,33954,33955,33956,33957,33958,33959,33960,33961,33962,33963,33964,33965,33966,33967,33968,33969,33970,33971,33972,33973,33974,33975,33976,33977,33978,33979,33980,33981,33982,33983,33984,33985,33986,33987,33988,33989,33990,33991,33992,33993,33994,33995,33996,33997,33998,33999,34000,34001,34002,34003,34004,34005,34006,34007,34008,34009,34010,34011,34012,34013,34014,34015,34016,34017,34018,34019,34020,34021,34022,34023,34024,34025,34026,34027,34028,34029,34030,34031,34032,34033,34034,34035,34036,34037,34038,34039,34040,34041,34042,34043,34044,34045,34046,34047,34048,34049,34050,34051,34052,34053,34054,34055,34056,34057,34058,34059,34060,34061,34062,34063,34064,34065,34066,34067,34068,34069,34070,34071,34072,34073,34074,34075,34076,34077,34078,34079,34080,34081,34082,34083,34084,34085,34086,34087,34088,34089,34090,34091,34092,34093,34094,34095,34096,34097,34098,34099,34100,34101,34102,34103,34104,34105,34106,34107,34108,34109,34110,34111,34112,34113,34114,34115,34116,34117,34118,34119,34120,34121,34122,34123,34124,34125,34126,34127,34128,34129,34130,34131,34132,34133,34134,34135,34136,34137,34138,34139,34140,34141,34142,34143,34144,34145,34146,34147,34148,34149,34150,34151,34152,34153,34154,34155,34156,34157,34158,34159,34160,34161,34162,34163,34164,34165,34166,34167,34168,34169,34170,34171,34172,34173,34174,34175,34176,34177,34178,34179,34180,34181,34182,34183,34184,34185,34186,34187,34188,34189,34190,34191,34192,34193,34194,34195,34196,34197,34198,34199,34200,34201,34202,34203,34204,34205,34206,34207,34208,34209,34210,34211,34212,34213,34214,34215,34216,34217,34218,34219,34220,34221,34222,34223,34224,34225,34226,34227,34228,34229,34230,34231,34232,34233,34234,34235,34236,34237,34238,34239,34240,34241,34242,34243,34244,34245,34246,34247,34248,34249,34250,34251,34252,34253,34254,34255,34256,34257,34258,34259,34260,34261,34262,34263,34264,34265,34266,34267,34268,34269,34270,34271,34272,34273,34274,34275,34276,34277,34278,34279,34280,34281,34282,34283,34284,34285,34286,34287,34288,34289,34290,34291,34292,34293,34294,34295,34296,34297,34298,34299,34300,34301,34302,34303,34304,34305,34306,34307,34308,34309,34310,34311,34312,34313,34314,34315,34316,34317,34318,34319,34320,34321,34322,34323,34324,34325,34326,34327,34328,34329,34330,34331,34332,34333,34334,34335,34336,34337,34338,34339,34340,34341,34342,34343,34344,34345,34346,34347,34348,34349,34350,34351,34352,34353,34354,34355,34356,34357,34358,34359,34360,34361,34362,34363,34364,34365,34366,34367,34368,34369,34370,34371,34372,34373,34374,34375,34376,34377,34378,34379,34380,34381,34382,34383,34384,34385,34386,34387,34388,34389,34390,34391,34392,34393,34394,34395,34396,34397,34398,34399,34400,34401,34402,34403,34404,34405,34406,34407,34408,34409,34410,34411,34412,34413,34414,34415,34416,34417,34418,34419,34420,34421,34422,34423,34424,34425,34426,34427,34428,34429,34430,34431,34432,34433,34434,34435,34436,34437,34438,34439,34440,34441,34442,34443,34444,34445,34446,34447,34448,34449,34450,34451,34452,34453,34454,34455,34456,34457,34458,34459,34460,34461,34462,34463,34464,34465,34466,34467,34468,34469,34470,34471,34472,34473,34474,34475,34476,34477,34478,34479,34480,34481,34482,34483,34484,34485,34486,34487,34488,34489,34490,34491,34492,34493,34494,34495,34496,34497,34498,34499,34500,34501,34502,34503,34504,34505,34506,34507,34508,34509,34510,34511,34512,34513,34514,34515,34516,34517,34518,34519,34520,34521,34522,34523,34524,34525,34526,34527,34528,34529,34530,34531,34532,34533,34534,34535,34536,34537,34538,34539,34540,34541,34542,34543,34544,34545,34546,34547,34548,34549,34550,34551,34552,34553,34554,34555,34556,34557,34558,34559,34560,34561,34562,34563,34564,34565,34566,34567,34568,34569,34570,34571,34572,34573,34574,34575,34576,34577,34578,34579,34580,34581,34582,34583,34584,34585,34586,34587,34588,34589,34590,34591,34592,34593,34594,34595,34596,34597,34598,34599,34600,34601,34602,34603,34604,34605,34606,34607,34608,34609,34610,34611,34612,34613,34614,34615,34616,34617,34618,34619,34620,34621,34622,34623,34624,34625,34626,34627,34628,34629,34630,34631,34632,34633,34634,34635,34636,34637,34638,34639,34640,34641,34642,34643,34644,34645,34646,34647,34648,34649,34650,34651,34652,34653,34654,34655,34656,34657,34658,34659,34660,34661,34662,34663,34664,34665,34666,34667,34668,34669,34670,34671,34672,34673,34674,34675,34676,34677,34678,34679,34680,34681,34682,34683,34684,34685,34686,34687,34688,34689,34690,34691,34692,34693,34694,34695,34696,34697,34698,34699,34700,34701,34702,34703,34704,34705,34706,34707,34708,34709,34710,34711,34712,34713,34714,34715,34716,34717,34718,34719,34720,34721,34722,34723,34724,34725,34726,34727,34728,34729,34730,34731,34732,34733,34734,34735,34736,34737,34738,34739,34740,34741,34742,34743,34744,34745,34746,34747,34748,34749,34750,34751,34752,34753,34754,34755,34756,34757,34758,34759,34760,34761,34762,34763,34764,34765,34766,34767,34768,34769,34770,34771,34772,34773,34774,34775,34776,34777,34778,34779,34780,34781,34782,34783,34784,34785,34786,34787,34788,34789,34790,34791,34792,34793,34794,34795,34796,34797,34798,34799,34800,34801,34802,34803,34804,34805,34806,34807,34808,34809,34810,34811,34812,34813,34814,34815,34816,34817,34818,34819,34820,34821,34822,34823,34824,34825,34826,34827,34828,34829,34830,34831,34832,34833,34834,34835,34836,34837,34838,34839,34840,34841,34842,34843,34844,34845,34846,34847,34848,34849,34850,34851,34852,34853,34854,34855,34856,34857,34858,34859,34860,34861,34862,34863,34864,34865,34866,34867,34868,34869,34870,34871,34872,34873,34874,34875,34876,34877,34878,34879,34880,34881,34882,34883,34884,34885,34886,34887,34888,34889,34890,34891,34892,34893,34894,34895,34896,34897,34898,34899,34900,34901,34902,34903,34904,34905,34906,34907,34908,34909,34910,34911,34912,34913,34914,34915,34916,34917,34918,34919,34920,34921,34922,34923,34924,34925,34926,34927,34928,34929,34930,34931,34932,34933,34934,34935,34936,34937,34938,34939,34940,34941,34942,34943,34944,34945,34946,34947,34948,34949,34950,34951,34952,34953,34954,34955,34956,34957,34958,34959,34960,34961,34962,34963,34964,34965,34966,34967,34968,34969,34970,34971,34972,34973,34974,34975,34976,34977,34978,34979,34980,34981,34982,34983,34984,34985,34986,34987,34988,34989,34990,34991,34992,34993,34994,34995,34996,34997,34998,34999,35000,35001,35002,35003,35004,35005,35006,35007,35008,35009,35010,35011,35012,35013,35014,35015,35016,35017,35018,35019,35020,35021,35022,35023,35024,35025,35026,35027,35028,35029,35030,35031,35032,35033,35034,35035,35036,35037,35038,35039,35040,35041,35042,35043,35044,35045,35046,35047,35048,35049,35050,35051,35052,35053,35054,35055,35056,35057,35058,35059,35060,35061,35062,35063,35064,35065,35066,35067,35068,35069,35070,35071,35072,35073,35074,35075,35076,35077,35078,35079,35080,35081,35082,35083,35084,35085,35086,35087,35088,35089,35090,35091,35092,35093,35094,35095,35096,35097,35098,35099,35100,35101,35102,35103,35104,35105,35106,35107,35108,35109,35110,35111,35112,35113,35114,35115,35116,35117,35118,35119,35120,35121,35122,35123,35124,35125,35126,35127,35128,35129,35130,35131,35132,35133,35134,35135,35136,35137,35138,35139,35140,35141,35142,35143,35144,35145,35146,35147,35148,35149,35150,35151,35152,35153,35154,35155,35156,35157,35158,35159,35160,35161,35162,35163,35164,35165,35166,35167,35168,35169,35170,35171,35172,35173,35174,35175,35176,35177,35178,35179,35180,35181,35182,35183,35184,35185,35186,35187,35188,35189,35190,35191,35192,35193,35194,35195,35196,35197,35198,35199,35200,35201,35202,35203,35204,35205,35206,35207,35208,35209,35210,35211,35212,35213,35214,35215,35216,35217,35218,35219,35220,35221,35222,35223,35224,35225,35226,35227,35228,35229,35230,35231,35232,35233,35234,35235,35236,35237,35238,35239,35240,35241,35242,35243,35244,35245,35246,35247,35248,35249,35250,35251,35252,35253,35254,35255,35256,35257,35258,35259,35260,35261,35262,35263,35264,35265,35266,35267,35268,35269,35270,35271,35272,35273,35274,35275,35276,35277,35278,35279,35280,35281,35282,35283,35284,35285,35286,35287,35288,35289,35290,35291,35292,35293,35294,35295,35296,35297,35298,35299,35300,35301,35302,35303,35304,35305,35306,35307,35308,35309,35310,35311,35312,35313,35314,35315,35316,35317,35318,35319,35320,35321,35322,35323,35324,35325,35326,35327,35328,35329,35330,35331,35332,35333,35334,35335,35336,35337,35338,35339,35340,35341,35342,35343,35344,35345,35346,35347,35348,35349,35350,35351,35352,35353,35354,35355,35356,35357,35358,35359,35360,35361,35362,35363,35364,35365,35366,35367,35368,35369,35370,35371,35372,35373,35374,35375,35376,35377,35378,35379,35380,35381,35382,35383,35384,35385,35386,35387,35388,35389,35390,35391,35392,35393,35394,35395,35396,35397,35398,35399,35400,35401,35402,35403,35404,35405,35406,35407,35408,35409,35410,35411,35412,35413,35414,35415,35416,35417,35418,35419,35420,35421,35422,35423,35424,35425,35426,35427,35428,35429,35430,35431,35432,35433,35434,35435,35436,35437,35438,35439,35440,35441,35442,35443,35444,35445,35446,35447,35448,35449,35450,35451,35452,35453,35454,35455,35456,35457,35458,35459,35460,35461,35462,35463,35464,35465,35466,35467,35468,35469,35470,35471,35472,35473,35474,35475,35476,35477,35478,35479,35480,35481,35482,35483,35484,35485,35486,35487,35488,35489,35490,35491,35492,35493,35494,35495,35496,35497,35498,35499,35500,35501,35502,35503,35504,35505,35506,35507,35508,35509,35510,35511,35512,35513,35514,35515,35516,35517,35518,35519,35520,35521,35522,35523,35524,35525,35526,35527,35528,35529,35530,35531,35532,35533,35534,35535,35536,35537,35538,35539,35540,35541,35542,35543,35544,35545,35546,35547,35548,35549,35550,35551,35552,35553,35554,35555,35556,35557,35558,35559,35560,35561,35562,35563,35564,35565,35566,35567,35568,35569,35570,35571,35572,35573,35574,35575,35576,35577,35578,35579,35580,35581,35582,35583,35584,35585,35586,35587,35588,35589,35590,35591,35592,35593,35594,35595,35596,35597,35598,35599,35600,35601,35602,35603,35604,35605,35606,35607,35608,35609,35610,35611,35612,35613,35614,35615,35616,35617,35618,35619,35620,35621,35622,35623,35624,35625,35626,35627,35628,35629,35630,35631,35632,35633,35634,35635,35636,35637,35638,35639,35640,35641,35642,35643,35644,35645,35646,35647,35648,35649,35650,35651,35652,35653,35654,35655,35656,35657,35658,35659,35660,35661,35662,35663,35664,35665,35666,35667,35668,35669,35670,35671,35672,35673,35674,35675,35676,35677,35678,35679,35680,35681,35682,35683,35684,35685,35686,35687,35688,35689,35690,35691,35692,35693,35694,35695,35696,35697,35698,35699,35700,35701,35702,35703,35704,35705,35706,35707,35708,35709,35710,35711,35712,35713,35714,35715,35716,35717,35718,35719,35720,35721,35722,35723,35724,35725,35726,35727,35728,35729,35730,35731,35732,35733,35734,35735,35736,35737,35738,35739,35740,35741,35742,35743,35744,35745,35746,35747,35748,35749,35750,35751,35752,35753,35754,35755,35756,35757,35758,35759,35760,35761,35762,35763,35764,35765,35766,35767,35768,35769,35770,35771,35772,35773,35774,35775,35776,35777,35778,35779,35780,35781,35782,35783,35784,35785,35786,35787,35788,35789,35790,35791,35792,35793,35794,35795,35796,35797,35798,35799,35800,35801,35802,35803,35804,35805,35806,35807,35808,35809,35810,35811,35812,35813,35814,35815,35816,35817,35818,35819,35820,35821,35822,35823,35824,35825,35826,35827,35828,35829,35830,35831,35832,35833,35834,35835,35836,35837,35838,35839,35840,35841,35842,35843,35844,35845,35846,35847,35848,35849,35850,35851,35852,35853,35854,35855,35856,35857,35858,35859,35860,35861,35862,35863,35864,35865,35866,35867,35868,35869,35870,35871,35872,35873,35874,35875,35876,35877,35878,35879,35880,35881,35882,35883,35884,35885,35886,35887,35888,35889,35890,35891,35892,35893,35894,35895,35896,35897,35898,35899,35900,35901,35902,35903,35904,35905,35906,35907,35908,35909,35910,35911,35912,35913,35914,35915,35916,35917,35918,35919,35920,35921,35922,35923,35924,35925,35926,35927,35928,35929,35930,35931,35932,35933,35934,35935,35936,35937,35938,35939,35940,35941,35942,35943,35944,35945,35946,35947,35948,35949,35950,35951,35952,35953,35954,35955,35956,35957,35958,35959,35960,35961,35962,35963,35964,35965,35966,35967,35968,35969,35970,35971,35972,35973,35974,35975,35976,35977,35978,35979,35980,35981,35982,35983,35984,35985,35986,35987,35988,35989,35990,35991,35992,35993,35994,35995,35996,35997,35998,35999,36000,36001,36002,36003,36004,36005,36006,36007,36008,36009,36010,36011,36012,36013,36014,36015,36016,36017,36018,36019,36020,36021,36022,36023,36024,36025,36026,36027,36028,36029,36030,36031,36032,36033,36034,36035,36036,36037,36038,36039,36040,36041,36042,36043,36044,36045,36046,36047,36048,36049,36050,36051,36052,36053,36054,36055,36056,36057,36058,36059,36060,36061,36062,36063,36064,36065,36066,36067,36068,36069,36070,36071,36072,36073,36074,36075,36076,36077,36078,36079,36080,36081,36082,36083,36084,36085,36086,36087,36088,36089,36090,36091,36092,36093,36094,36095,36096,36097,36098,36099,36100,36101,36102,36103,36104,36105,36106,36107,36108,36109,36110,36111,36112,36113,36114,36115,36116,36117,36118,36119,36120,36121,36122,36123,36124,36125,36126,36127,36128,36129,36130,36131,36132,36133,36134,36135,36136,36137,36138,36139,36140,36141,36142,36143,36144,36145,36146,36147,36148,36149,36150,36151,36152,36153,36154,36155,36156,36157,36158,36159,36160,36161,36162,36163,36164,36165,36166,36167,36168,36169,36170,36171,36172,36173,36174,36175,36176,36177,36178,36179,36180,36181,36182,36183,36184,36185,36186,36187,36188,36189,36190,36191,36192,36193,36194,36195,36196,36197,36198,36199,36200,36201,36202,36203,36204,36205,36206,36207,36208,36209,36210,36211,36212,36213,36214,36215,36216,36217,36218,36219,36220,36221,36222,36223,36224,36225,36226,36227,36228,36229,36230,36231,36232,36233,36234,36235,36236,36237,36238,36239,36240,36241,36242,36243,36244,36245,36246,36247,36248,36249,36250,36251,36252,36253,36254,36255,36256,36257,36258,36259,36260,36261,36262,36263,36264,36265,36266,36267,36268,36269,36270,36271,36272,36273,36274,36275,36276,36277,36278,36279,36280,36281,36282,36283,36284,36285,36286,36287,36288,36289,36290,36291,36292,36293,36294,36295,36296,36297,36298,36299,36300,36301,36302,36303,36304,36305,36306,36307,36308,36309,36310,36311,36312,36313,36314,36315,36316,36317,36318,36319,36320,36321,36322,36323,36324,36325,36326,36327,36328,36329,36330,36331,36332,36333,36334,36335,36336,36337,36338,36339,36340,36341,36342,36343,36344,36345,36346,36347,36348,36349,36350,36351,36352,36353,36354,36355,36356,36357,36358,36359,36360,36361,36362,36363,36364,36365,36366,36367,36368,36369,36370,36371,36372,36373,36374,36375,36376,36377,36378,36379,36380,36381,36382,36383,36384,36385,36386,36387,36388,36389,36390,36391,36392,36393,36394,36395,36396,36397,36398,36399,36400,36401,36402,36403,36404,36405,36406,36407,36408,36409,36410,36411,36412,36413,36414,36415,36416,36417,36418,36419,36420,36421,36422,36423,36424,36425,36426,36427,36428,36429,36430,36431,36432,36433,36434,36435,36436,36437,36438,36439,36440,36441,36442,36443,36444,36445,36446,36447,36448,36449,36450,36451,36452,36453,36454,36455,36456,36457,36458,36459,36460,36461,36462,36463,36464,36465,36466,36467,36468,36469,36470,36471,36472,36473,36474,36475,36476,36477,36478,36479,36480,36481,36482,36483,36484,36485,36486,36487,36488,36489,36490,36491,36492,36493,36494,36495,36496,36497,36498,36499,36500,36501,36502,36503,36504,36505,36506,36507,36508,36509,36510,36511,36512,36513,36514,36515,36516,36517,36518,36519,36520,36521,36522,36523,36524,36525,36526,36527,36528,36529,36530,36531,36532,36533,36534,36535,36536,36537,36538,36539,36540,36541,36542,36543,36544,36545,36546,36547,36548,36549,36550,36551,36552,36553,36554,36555,36556,36557,36558,36559,36560,36561,36562,36563,36564,36565,36566,36567,36568,36569,36570,36571,36572,36573,36574,36575,36576,36577,36578,36579,36580,36581,36582,36583,36584,36585,36586,36587,36588,36589,36590,36591,36592,36593,36594,36595,36596,36597,36598,36599,36600,36601,36602,36603,36604,36605,36606,36607,36608,36609,36610,36611,36612,36613,36614,36615,36616,36617,36618,36619,36620,36621,36622,36623,36624,36625,36626,36627,36628,36629,36630,36631,36632,36633,36634,36635,36636,36637,36638,36639,36640,36641,36642,36643,36644,36645,36646,36647,36648,36649,36650,36651,36652,36653,36654,36655,36656,36657,36658,36659,36660,36661,36662,36663,36664,36665,36666,36667,36668,36669,36670,36671,36672,36673,36674,36675,36676,36677,36678,36679,36680,36681,36682,36683,36684,36685,36686,36687,36688,36689,36690,36691,36692,36693,36694,36695,36696,36697,36698,36699,36700,36701,36702,36703,36704,36705,36706,36707,36708,36709,36710,36711,36712,36713,36714,36715,36716,36717,36718,36719,36720,36721,36722,36723,36724,36725,36726,36727,36728,36729,36730,36731,36732,36733,36734,36735,36736,36737,36738,36739,36740,36741,36742,36743,36744,36745,36746,36747,36748,36749,36750,36751,36752,36753,36754,36755,36756,36757,36758,36759,36760,36761,36762,36763,36764,36765,36766,36767,36768,36769,36770,36771,36772,36773,36774,36775,36776,36777,36778,36779,36780,36781,36782,36783,36784,36785,36786,36787,36788,36789,36790,36791,36792,36793,36794,36795,36796,36797,36798,36799,36800,36801,36802,36803,36804,36805,36806,36807,36808,36809,36810,36811,36812,36813,36814,36815,36816,36817,36818,36819,36820,36821,36822,36823,36824,36825,36826,36827,36828,36829,36830,36831,36832,36833,36834,36835,36836,36837,36838,36839,36840,36841,36842,36843,36844,36845,36846,36847,36848,36849,36850,36851,36852,36853,36854,36855,36856,36857,36858,36859,36860,36861,36862,36863,36864,36865,36866,36867,36868,36869,36870,36871,36872,36873,36874,36875,36876,36877,36878,36879,36880,36881,36882,36883,36884,36885,36886,36887,36888,36889,36890,36891,36892,36893,36894,36895,36896,36897,36898,36899,36900,36901,36902,36903,36904,36905,36906,36907,36908,36909,36910,36911,36912,36913,36914,36915,36916,36917,36918,36919,36920,36921,36922,36923,36924,36925,36926,36927,36928,36929,36930,36931,36932,36933,36934,36935,36936,36937,36938,36939,36940,36941,36942,36943,36944,36945,36946,36947,36948,36949,36950,36951,36952,36953,36954,36955,36956,36957,36958,36959,36960,36961,36962,36963,36964,36965,36966,36967,36968,36969,36970,36971,36972,36973,36974,36975,36976,36977,36978,36979,36980,36981,36982,36983,36984,36985,36986,36987,36988,36989,36990,36991,36992,36993,36994,36995,36996,36997,36998,36999,37000,37001,37002,37003,37004,37005,37006,37007,37008,37009,37010,37011,37012,37013,37014,37015,37016,37017,37018,37019,37020,37021,37022,37023,37024,37025,37026,37027,37028,37029,37030,37031,37032,37033,37034,37035,37036,37037,37038,37039,37040,37041,37042,37043,37044,37045,37046,37047,37048,37049,37050,37051,37052,37053,37054,37055,37056,37057,37058,37059,37060,37061,37062,37063,37064,37065,37066,37067,37068,37069,37070,37071,37072,37073,37074,37075,37076,37077,37078,37079,37080,37081,37082,37083,37084,37085,37086,37087,37088,37089,37090,37091,37092,37093,37094,37095,37096,37097,37098,37099,37100,37101,37102,37103,37104,37105,37106,37107,37108,37109,37110,37111,37112,37113,37114,37115,37116,37117,37118,37119,37120,37121,37122,37123,37124,37125,37126,37127,37128,37129,37130,37131,37132,37133,37134,37135,37136,37137,37138,37139,37140,37141,37142,37143,37144,37145,37146,37147,37148,37149,37150,37151,37152,37153,37154,37155,37156,37157,37158,37159,37160,37161,37162,37163,37164,37165,37166,37167,37168,37169,37170,37171,37172,37173,37174,37175,37176,37177,37178,37179,37180,37181,37182,37183,37184,37185,37186,37187,37188,37189,37190,37191,37192,37193,37194,37195,37196,37197,37198,37199,37200,37201,37202,37203,37204,37205,37206,37207,37208,37209,37210,37211,37212,37213,37214,37215,37216,37217,37218,37219,37220,37221,37222,37223,37224,37225,37226,37227,37228,37229,37230,37231,37232,37233,37234,37235,37236,37237,37238,37239,37240,37241,37242,37243,37244,37245,37246,37247,37248,37249,37250,37251,37252,37253,37254,37255,37256,37257,37258,37259,37260,37261,37262,37263,37264,37265,37266,37267,37268,37269,37270,37271,37272,37273,37274,37275,37276,37277,37278,37279,37280,37281,37282,37283,37284,37285,37286,37287,37288,37289,37290,37291,37292,37293,37294,37295,37296,37297,37298,37299,37300,37301,37302,37303,37304,37305,37306,37307,37308,37309,37310,37311,37312,37313,37314,37315,37316,37317,37318,37319,37320,37321,37322,37323,37324,37325,37326,37327,37328,37329,37330,37331,37332,37333,37334,37335,37336,37337,37338,37339,37340,37341,37342,37343,37344,37345,37346,37347,37348,37349,37350,37351,37352,37353,37354,37355,37356,37357,37358,37359,37360,37361,37362,37363,37364,37365,37366,37367,37368,37369,37370,37371,37372,37373,37374,37375,37376,37377,37378,37379,37380,37381,37382,37383,37384,37385,37386,37387,37388,37389,37390,37391,37392,37393,37394,37395,37396,37397,37398,37399,37400,37401,37402,37403,37404,37405,37406,37407,37408,37409,37410,37411,37412,37413,37414,37415,37416,37417,37418,37419,37420,37421,37422,37423,37424,37425,37426,37427,37428,37429,37430,37431,37432,37433,37434,37435,37436,37437,37438,37439,37440,37441,37442,37443,37444,37445,37446,37447,37448,37449,37450,37451,37452,37453,37454,37455,37456,37457,37458,37459,37460,37461,37462,37463,37464,37465,37466,37467,37468,37469,37470,37471,37472,37473,37474,37475,37476,37477,37478,37479,37480,37481,37482,37483,37484,37485,37486,37487,37488,37489,37490,37491,37492,37493,37494,37495,37496,37497,37498,37499,37500,37501,37502,37503,37504,37505,37506,37507,37508,37509,37510,37511,37512,37513,37514,37515,37516,37517,37518,37519,37520,37521,37522,37523,37524,37525,37526,37527,37528,37529,37530,37531,37532,37533,37534,37535,37536,37537,37538,37539,37540,37541,37542,37543,37544,37545,37546,37547,37548,37549,37550,37551,37552,37553,37554,37555,37556,37557,37558,37559,37560,37561,37562,37563,37564,37565,37566,37567,37568,37569,37570,37571,37572,37573,37574,37575,37576,37577,37578,37579,37580,37581,37582,37583,37584,37585,37586,37587,37588,37589,37590,37591,37592,37593,37594,37595,37596,37597,37598,37599,37600,37601,37602,37603,37604,37605,37606,37607,37608,37609,37610,37611,37612,37613,37614,37615,37616,37617,37618,37619,37620,37621,37622,37623,37624,37625,37626,37627,37628,37629,37630,37631,37632,37633,37634,37635,37636,37637,37638,37639,37640,37641,37642,37643,37644,37645,37646,37647,37648,37649,37650,37651,37652,37653,37654,37655,37656,37657,37658,37659,37660,37661,37662,37663,37664,37665,37666,37667,37668,37669,37670,37671,37672,37673,37674,37675,37676,37677,37678,37679,37680,37681,37682,37683,37684,37685,37686,37687,37688,37689,37690,37691,37692,37693,37694,37695,37696,37697,37698,37699,37700,37701,37702,37703,37704,37705,37706,37707,37708,37709,37710,37711,37712,37713,37714,37715,37716,37717,37718,37719,37720,37721,37722,37723,37724,37725,37726,37727,37728,37729,37730,37731,37732,37733,37734,37735,37736,37737,37738,37739,37740,37741,37742,37743,37744,37745,37746,37747,37748,37749,37750,37751,37752,37753,37754,37755,37756,37757,37758,37759,37760,37761,37762,37763,37764,37765,37766,37767,37768,37769,37770,37771,37772,37773,37774,37775,37776,37777,37778,37779,37780,37781,37782,37783,37784,37785,37786,37787,37788,37789,37790,37791,37792,37793,37794,37795,37796,37797,37798,37799,37800,37801,37802,37803,37804,37805,37806,37807,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,37822,37823,37824,37825,37826,37827,37828,37829,37830,37831,37832,37833,37834,37835,37836,37837,37838,37839,37840,37841,37842,37843,37844,37845,37846,37847,37848,37849,37850,37851,37852,37853,37854,37855,37856,37857,37858,37859,37860,37861,37862,37863,37864,37865,37866,37867,37868,37869,37870,37871,37872,37873,37874,37875,37876,37877,37878,37879,37880,37881,37882,37883,37884,37885,37886,37887,37888,37889,37890,37891,37892,37893,37894,37895,37896,37897,37898,37899,37900,37901,37902,37903,37904,37905,37906,37907,37908,37909,37910,37911,37912,37913,37914,37915,37916,37917,37918,37919,37920,37921,37922,37923,37924,37925,37926,37927,37928,37929,37930,37931,37932,37933,37934,37935,37936,37937,37938,37939,37940,37941,37942,37943,37944,37945,37946,37947,37948,37949,37950,37951,37952,37953,37954,37955,37956,37957,37958,37959,37960,37961,37962,37963,37964,37965,37966,37967,37968,37969,37970,37971,37972,37973,37974,37975,37976,37977,37978,37979,37980,37981,37982,37983,37984,37985,37986,37987,37988,37989,37990,37991,37992,37993,37994,37995,37996,37997,37998,37999,38000,38001,38002,38003,38004,38005,38006,38007,38008,38009,38010,38011,38012,38013,38014,38015,38016,38017,38018,38019,38020,38021,38022,38023,38024,38025,38026,38027,38028,38029,38030,38031,38032,38033,38034,38035,38036,38037,38038,38039,38040,38041,38042,38043,38044,38045,38046,38047,38048,38049,38050,38051,38052,38053,38054,38055,38056,38057,38058,38059,38060,38061,38062,38063,38064,38065,38066,38067,38068,38069,38070,38071,38072,38073,38074,38075,38076,38077,38078,38079,38080,38081,38082,38083,38084,38085,38086,38087,38088,38089,38090,38091,38092,38093,38094,38095,38096,38097,38098,38099,38100,38101,38102,38103,38104,38105,38106,38107,38108,38109,38110,38111,38112,38113,38114,38115,38116,38117,38118,38119,38120,38121,38122,38123,38124,38125,38126,38127,38128,38129,38130,38131,38132,38133,38134,38135,38136,38137,38138,38139,38140,38141,38142,38143,38144,38145,38146,38147,38148,38149,38150,38151,38152,38153,38154,38155,38156,38157,38158,38159,38160,38161,38162,38163,38164,38165,38166,38167,38168,38169,38170,38171,38172,38173,38174,38175,38176,38177,38178,38179,38180,38181,38182,38183,38184,38185,38186,38187,38188,38189,38190,38191,38192,38193,38194,38195,38196,38197,38198,38199,38200,38201,38202,38203,38204,38205,38206,38207,38208,38209,38210,38211,38212,38213,38214,38215,38216,38217,38218,38219,38220,38221,38222,38223,38224,38225,38226,38227,38228,38229,38230,38231,38232,38233,38234,38235,38236,38237,38238,38239,38240,38241,38242,38243,38244,38245,38246,38247,38248,38249,38250,38251,38252,38253,38254,38255,38256,38257,38258,38259,38260,38261,38262,38263,38264,38265,38266,38267,38268,38269,38270,38271,38272,38273,38274,38275,38276,38277,38278,38279,38280,38281,38282,38283,38284,38285,38286,38287,38288,38289,38290,38291,38292,38293,38294,38295,38296,38297,38298,38299,38300,38301,38302,38303,38304,38305,38306,38307,38308,38309,38310,38311,38312,38313,38314,38315,38316,38317,38318,38319,38320,38321,38322,38323,38324,38325,38326,38327,38328,38329,38330,38331,38332,38333,38334,38335,38336,38337,38338,38339,38340,38341,38342,38343,38344,38345,38346,38347,38348,38349,38350,38351,38352,38353,38354,38355,38356,38357,38358,38359,38360,38361,38362,38363,38364,38365,38366,38367,38368,38369,38370,38371,38372,38373,38374,38375,38376,38377,38378,38379,38380,38381,38382,38383,38384,38385,38386,38387,38388,38389,38390,38391,38392,38393,38394,38395,38396,38397,38398,38399,38400,38401,38402,38403,38404,38405,38406,38407,38408,38409,38410,38411,38412,38413,38414,38415,38416,38417,38418,38419,38420,38421,38422,38423,38424,38425,38426,38427,38428,38429,38430,38431,38432,38433,38434,38435,38436,38437,38438,38439,38440,38441,38442,38443,38444,38445,38446,38447,38448,38449,38450,38451,38452,38453,38454,38455,38456,38457,38458,38459,38460,38461,38462,38463,38464,38465,38466,38467,38468,38469,38470,38471,38472,38473,38474,38475,38476,38477,38478,38479,38480,38481,38482,38483,38484,38485,38486,38487,38488,38489,38490,38491,38492,38493,38494,38495,38496,38497,38498,38499,38500,38501,38502,38503,38504,38505,38506,38507,38508,38509,38510,38511,38512,38513,38514,38515,38516,38517,38518,38519,38520,38521,38522,38523,38524,38525,38526,38527,38528,38529,38530,38531,38532,38533,38534,38535,38536,38537,38538,38539,38540,38541,38542,38543,38544,38545,38546,38547,38548,38549,38550,38551,38552,38553,38554,38555,38556,38557,38558,38559,38560,38561,38562,38563,38564,38565,38566,38567,38568,38569,38570,38571,38572,38573,38574,38575,38576,38577,38578,38579,38580,38581,38582,38583,38584,38585,38586,38587,38588,38589,38590,38591,38592,38593,38594,38595,38596,38597,38598,38599,38600,38601,38602,38603,38604,38605,38606,38607,38608,38609,38610,38611,38612,38613,38614,38615,38616,38617,38618,38619,38620,38621,38622,38623,38624,38625,38626,38627,38628,38629,38630,38631,38632,38633,38634,38635,38636,38637,38638,38639,38640,38641,38642,38643,38644,38645,38646,38647,38648,38649,38650,38651,38652,38653,38654,38655,38656,38657,38658,38659,38660,38661,38662,38663,38664,38665,38666,38667,38668,38669,38670,38671,38672,38673,38674,38675,38676,38677,38678,38679,38680,38681,38682,38683,38684,38685,38686,38687,38688,38689,38690,38691,38692,38693,38694,38695,38696,38697,38698,38699,38700,38701,38702,38703,38704,38705,38706,38707,38708,38709,38710,38711,38712,38713,38714,38715,38716,38717,38718,38719,38720,38721,38722,38723,38724,38725,38726,38727,38728,38729,38730,38731,38732,38733,38734,38735,38736,38737,38738,38739,38740,38741,38742,38743,38744,38745,38746,38747,38748,38749,38750,38751,38752,38753,38754,38755,38756,38757,38758,38759,38760,38761,38762,38763,38764,38765,38766,38767,38768,38769,38770,38771,38772,38773,38774,38775,38776,38777,38778,38779,38780,38781,38782,38783,38784,38785,38786,38787,38788,38789,38790,38791,38792,38793,38794,38795,38796,38797,38798,38799,38800,38801,38802,38803,38804,38805,38806,38807,38808,38809,38810,38811,38812,38813,38814,38815,38816,38817,38818,38819,38820,38821,38822,38823,38824,38825,38826,38827,38828,38829,38830,38831,38832,38833,38834,38835,38836,38837,38838,38839,38840,38841,38842,38843,38844,38845,38846,38847,38848,38849,38850,38851,38852,38853,38854,38855,38856,38857,38858,38859,38860,38861,38862,38863,38864,38865,38866,38867,38868,38869,38870,38871,38872,38873,38874,38875,38876,38877,38878,38879,38880,38881,38882,38883,38884,38885,38886,38887,38888,38889,38890,38891,38892,38893,38894,38895,38896,38897,38898,38899,38900,38901,38902,38903,38904,38905,38906,38907,38908,38909,38910,38911,38912,38913,38914,38915,38916,38917,38918,38919,38920,38921,38922,38923,38924,38925,38926,38927,38928,38929,38930,38931,38932,38933,38934,38935,38936,38937,38938,38939,38940,38941,38942,38943,38944,38945,38946,38947,38948,38949,38950,38951,38952,38953,38954,38955,38956,38957,38958,38959,38960,38961,38962,38963,38964,38965,38966,38967,38968,38969,38970,38971,38972,38973,38974,38975,38976,38977,38978,38979,38980,38981,38982,38983,38984,38985,38986,38987,38988,38989,38990,38991,38992,38993,38994,38995,38996,38997,38998,38999,39000,39001,39002,39003,39004,39005,39006,39007,39008,39009,39010,39011,39012,39013,39014,39015,39016,39017,39018,39019,39020,39021,39022,39023,39024,39025,39026,39027,39028,39029,39030,39031,39032,39033,39034,39035,39036,39037,39038,39039,39040,39041,39042,39043,39044,39045,39046,39047,39048,39049,39050,39051,39052,39053,39054,39055,39056,39057,39058,39059,39060,39061,39062,39063,39064,39065,39066,39067,39068,39069,39070,39071,39072,39073,39074,39075,39076,39077,39078,39079,39080,39081,39082,39083,39084,39085,39086,39087,39088,39089,39090,39091,39092,39093,39094,39095,39096,39097,39098,39099,39100,39101,39102,39103,39104,39105,39106,39107,39108,39109,39110,39111,39112,39113,39114,39115,39116,39117,39118,39119,39120,39121,39122,39123,39124,39125,39126,39127,39128,39129,39130,39131,39132,39133,39134,39135,39136,39137,39138,39139,39140,39141,39142,39143,39144,39145,39146,39147,39148,39149,39150,39151,39152,39153,39154,39155,39156,39157,39158,39159,39160,39161,39162,39163,39164,39165,39166,39167,39168,39169,39170,39171,39172,39173,39174,39175,39176,39177,39178,39179,39180,39181,39182,39183,39184,39185,39186,39187,39188,39189,39190,39191,39192,39193,39194,39195,39196,39197,39198,39199,39200,39201,39202,39203,39204,39205,39206,39207,39208,39209,39210,39211,39212,39213,39214,39215,39216,39217,39218,39219,39220,39221,39222,39223,39224,39225,39226,39227,39228,39229,39230,39231,39232,39233,39234,39235,39236,39237,39238,39239,39240,39241,39242,39243,39244,39245,39246,39247,39248,39249,39250,39251,39252,39253,39254,39255,39256,39257,39258,39259,39260,39261,39262,39263,39264,39265,39266,39267,39268,39269,39270,39271,39272,39273,39274,39275,39276,39277,39278,39279,39280,39281,39282,39283,39284,39285,39286,39287,39288,39289,39290,39291,39292,39293,39294,39295,39296,39297,39298,39299,39300,39301,39302,39303,39304,39305,39306,39307,39308,39309,39310,39311,39312,39313,39314,39315,39316,39317,39318,39319,39320,39321,39322,39323,39324,39325,39326,39327,39328,39329,39330,39331,39332,39333,39334,39335,39336,39337,39338,39339,39340,39341,39342,39343,39344,39345,39346,39347,39348,39349,39350,39351,39352,39353,39354,39355,39356,39357,39358,39359,39360,39361,39362,39363,39364,39365,39366,39367,39368,39369,39370,39371,39372,39373,39374,39375,39376,39377,39378,39379,39380,39381,39382,39383,39384,39385,39386,39387,39388,39389,39390,39391,39392,39393,39394,39395,39396,39397,39398,39399,39400,39401,39402,39403,39404,39405,39406,39407,39408,39409,39410,39411,39412,39413,39414,39415,39416,39417,39418,39419,39420,39421,39422,39423,39424,39425,39426,39427,39428,39429,39430,39431,39432,39433,39434,39435,39436,39437,39438,39439,39440,39441,39442,39443,39444,39445,39446,39447,39448,39449,39450,39451,39452,39453,39454,39455,39456,39457,39458,39459,39460,39461,39462,39463,39464,39465,39466,39467,39468,39469,39470,39471,39472,39473,39474,39475,39476,39477,39478,39479,39480,39481,39482,39483,39484,39485,39486,39487,39488,39489,39490,39491,39492,39493,39494,39495,39496,39497,39498,39499,39500,39501,39502,39503,39504,39505,39506,39507,39508,39509,39510,39511,39512,39513,39514,39515,39516,39517,39518,39519,39520,39521,39522,39523,39524,39525,39526,39527,39528,39529,39530,39531,39532,39533,39534,39535,39536,39537,39538,39539,39540,39541,39542,39543,39544,39545,39546,39547,39548,39549,39550,39551,39552,39553,39554,39555,39556,39557,39558,39559,39560,39561,39562,39563,39564,39565,39566,39567,39568,39569,39570,39571,39572,39573,39574,39575,39576,39577,39578,39579,39580,39581,39582,39583,39584,39585,39586,39587,39588,39589,39590,39591,39592,39593,39594,39595,39596,39597,39598,39599,39600,39601,39602,39603,39604,39605,39606,39607,39608,39609,39610,39611,39612,39613,39614,39615,39616,39617,39618,39619,39620,39621,39622,39623,39624,39625,39626,39627,39628,39629,39630,39631,39632,39633,39634,39635,39636,39637,39638,39639,39640,39641,39642,39643,39644,39645,39646,39647,39648,39649,39650,39651,39652,39653,39654,39655,39656,39657,39658,39659,39660,39661,39662,39663,39664,39665,39666,39667,39668,39669,39670,39671,39672,39673,39674,39675,39676,39677,39678,39679,39680,39681,39682,39683,39684,39685,39686,39687,39688,39689,39690,39691,39692,39693,39694,39695,39696,39697,39698,39699,39700,39701,39702,39703,39704,39705,39706,39707,39708,39709,39710,39711,39712,39713,39714,39715,39716,39717,39718,39719,39720,39721,39722,39723,39724,39725,39726,39727,39728,39729,39730,39731,39732,39733,39734,39735,39736,39737,39738,39739,39740,39741,39742,39743,39744,39745,39746,39747,39748,39749,39750,39751,39752,39753,39754,39755,39756,39757,39758,39759,39760,39761,39762,39763,39764,39765,39766,39767,39768,39769,39770,39771,39772,39773,39774,39775,39776,39777,39778,39779,39780,39781,39782,39783,39784,39785,39786,39787,39788,39789,39790,39791,39792,39793,39794,39795,39796,39797,39798,39799,39800,39801,39802,39803,39804,39805,39806,39807,39808,39809,39810,39811,39812,39813,39814,39815,39816,39817,39818,39819,39820,39821,39822,39823,39824,39825,39826,39827,39828,39829,39830,39831,39832,39833,39834,39835,39836,39837,39838,39839,39840,39841,39842,39843,39844,39845,39846,39847,39848,39849,39850,39851,39852,39853,39854,39855,39856,39857,39858,39859,39860,39861,39862,39863,39864,39865,39866,39867,39868,39869,39870,39871,39872,39873,39874,39875,39876,39877,39878,39879,39880,39881,39882,39883,39884,39885,39886,39887,39888,39889,39890,39891,39892,39893,39894,39895,39896,39897,39898,39899,39900,39901,39902,39903,39904,39905,39906,39907,39908,39909,39910,39911,39912,39913,39914,39915,39916,39917,39918,39919,39920,39921,39922,39923,39924,39925,39926,39927,39928,39929,39930,39931,39932,39933,39934,39935,39936,39937,39938,39939,39940,39941,39942,39943,39944,39945,39946,39947,39948,39949,39950,39951,39952,39953,39954,39955,39956,39957,39958,39959,39960,39961,39962,39963,39964,39965,39966,39967,39968,39969,39970,39971,39972,39973,39974,39975,39976,39977,39978,39979,39980,39981,39982,39983,39984,39985,39986,39987,39988,39989,39990,39991,39992,39993,39994,39995,39996,39997,39998,39999,40000,40001,40002,40003,40004,40005,40006,40007,40008,40009,40010,40011,40012,40013,40014,40015,40016,40017,40018,40019,40020,40021,40022,40023,40024,40025,40026,40027,40028,40029,40030,40031,40032,40033,40034,40035,40036,40037,40038,40039,40040,40041,40042,40043,40044,40045,40046,40047,40048,40049,40050,40051,40052,40053,40054,40055,40056,40057,40058,40059,40060,40061,40062,40063,40064,40065,40066,40067,40068,40069,40070,40071,40072,40073,40074,40075,40076,40077,40078,40079,40080,40081,40082,40083,40084,40085,40086,40087,40088,40089,40090,40091,40092,40093,40094,40095,40096,40097,40098,40099,40100,40101,40102,40103,40104,40105,40106,40107,40108,40109,40110,40111,40112,40113,40114,40115,40116,40117,40118,40119,40120,40121,40122,40123,40124,40125,40126,40127,40128,40129,40130,40131,40132,40133,40134,40135,40136,40137,40138,40139,40140,40141,40142,40143,40144,40145,40146,40147,40148,40149,40150,40151,40152,40153,40154,40155,40156,40157,40158,40159,40160,40161,40162,40163,40164,40165,40166,40167,40168,40169,40170,40171,40172,40173,40174,40175,40176,40177,40178,40179,40180,40181,40182,40183,40184,40185,40186,40187,40188,40189,40190,40191,40192,40193,40194,40195,40196,40197,40198,40199,40200,40201,40202,40203,40204,40205,40206,40207,40208,40209,40210,40211,40212,40213,40214,40215,40216,40217,40218,40219,40220,40221,40222,40223,40224,40225,40226,40227,40228,40229,40230,40231,40232,40233,40234,40235,40236,40237,40238,40239,40240,40241,40242,40243,40244,40245,40246,40247,40248,40249,40250,40251,40252,40253,40254,40255,40256,40257,40258,40259,40260,40261,40262,40263,40264,40265,40266,40267,40268,40269,40270,40271,40272,40273,40274,40275,40276,40277,40278,40279,40280,40281,40282,40283,40284,40285,40286,40287,40288,40289,40290,40291,40292,40293,40294,40295,40296,40297,40298,40299,40300,40301,40302,40303,40304,40305,40306,40307,40308,40309,40310,40311,40312,40313,40314,40315,40316,40317,40318,40319,40320,40321,40322,40323,40324,40325,40326,40327,40328,40329,40330,40331,40332,40333,40334,40335,40336,40337,40338,40339,40340,40341,40342,40343,40344,40345,40346,40347,40348,40349,40350,40351,40352,40353,40354,40355,40356,40357,40358,40359,40360,40361,40362,40363,40364,40365,40366,40367,40368,40369,40370,40371,40372,40373,40374,40375,40376,40377,40378,40379,40380,40381,40382,40383,40384,40385,40386,40387,40388,40389,40390,40391,40392,40393,40394,40395,40396,40397,40398,40399,40400,40401,40402,40403,40404,40405,40406,40407,40408,40409,40410,40411,40412,40413,40414,40415,40416,40417,40418,40419,40420,40421,40422,40423,40424,40425,40426,40427,40428,40429,40430,40431,40432,40433,40434,40435,40436,40437,40438,40439,40440,40441,40442,40443,40444,40445,40446,40447,40448,40449,40450,40451,40452,40453,40454,40455,40456,40457,40458,40459,40460,40461,40462,40463,40464,40465,40466,40467,40468,40469,40470,40471,40472,40473,40474,40475,40476,40477,40478,40479,40480,40481,40482,40483,40484,40485,40486,40487,40488,40489,40490,40491,40492,40493,40494,40495,40496,40497,40498,40499,40500,40501,40502,40503,40504,40505,40506,40507,40508,40509,40510,40511,40512,40513,40514,40515,40516,40517,40518,40519,40520,40521,40522,40523,40524,40525,40526,40527,40528,40529,40530,40531,40532,40533,40534,40535,40536,40537,40538,40539,40540,40541,40542,40543,40544,40545,40546,40547,40548,40549,40550,40551,40552,40553,40554,40555,40556,40557,40558,40559,40560,40561,40562,40563,40564,40565,40566,40567,40568,40569,40570,40571,40572,40573,40574,40575,40576,40577,40578,40579,40580,40581,40582,40583,40584,40585,40586,40587,40588,40589,40590,40591,40592,40593,40594,40595,40596,40597,40598,40599,40600,40601,40602,40603,40604,40605,40606,40607,40608,40609,40610,40611,40612,40613,40614,40615,40616,40617,40618,40619,40620,40621,40622,40623,40624,40625,40626,40627,40628,40629,40630,40631,40632,40633,40634,40635,40636,40637,40638,40639,40640,40641,40642,40643,40644,40645,40646,40647,40648,40649,40650,40651,40652,40653,40654,40655,40656,40657,40658,40659,40660,40661,40662,40663,40664,40665,40666,40667,40668,40669,40670,40671,40672,40673,40674,40675,40676,40677,40678,40679,40680,40681,40682,40683,40684,40685,40686,40687,40688,40689,40690,40691,40692,40693,40694,40695,40696,40697,40698,40699,40700,40701,40702,40703,40704,40705,40706,40707,40708,40709,40710,40711,40712,40713,40714,40715,40716,40717,40718,40719,40720,40721,40722,40723,40724,40725,40726,40727,40728,40729,40730,40731,40732,40733,40734,40735,40736,40737,40738,40739,40740,40741,40742,40743,40744,40745,40746,40747,40748,40749,40750,40751,40752,40753,40754,40755,40756,40757,40758,40759,40760,40761,40762,40763,40764,40765,40766,40767,40768,40769,40770,40771,40772,40773,40774,40775,40776,40777,40778,40779,40780,40781,40782,40783,40784,40785,40786,40787,40788,40789,40790,40791,40792,40793,40794,40795,40796,40797,40798,40799,40800,40801,40802,40803,40804,40805,40806,40807,40808,40809,40810,40811,40812,40813,40814,40815,40816,40817,40818,40819,40820,40821,40822,40823,40824,40825,40826,40827,40828,40829,40830,40831,40832,40833,40834,40835,40836,40837,40838,40839,40840,40841,40842,40843,40844,40845,40846,40847,40848,40849,40850,40851,40852,40853,40854,40855,40856,40857,40858,40859,40860,40861,40862,40863,40864,40865,40866,40867,40868,40869,40870,40871,40872,40873,40874,40875,40876,40877,40878,40879,40880,40881,40882,40883,40884,40885,40886,40887,40888,40889,40890,40891,40892,40893,40894,40895,40896,40897,40898,40899,40900,40901,40902,40903,40904,40905,40906,40907,40908,40960,40961,40962,40963,40964,40965,40966,40967,40968,40969,40970,40971,40972,40973,40974,40975,40976,40977,40978,40979,40980,40981,40982,40983,40984,40985,40986,40987,40988,40989,40990,40991,40992,40993,40994,40995,40996,40997,40998,40999,41000,41001,41002,41003,41004,41005,41006,41007,41008,41009,41010,41011,41012,41013,41014,41015,41016,41017,41018,41019,41020,41021,41022,41023,41024,41025,41026,41027,41028,41029,41030,41031,41032,41033,41034,41035,41036,41037,41038,41039,41040,41041,41042,41043,41044,41045,41046,41047,41048,41049,41050,41051,41052,41053,41054,41055,41056,41057,41058,41059,41060,41061,41062,41063,41064,41065,41066,41067,41068,41069,41070,41071,41072,41073,41074,41075,41076,41077,41078,41079,41080,41081,41082,41083,41084,41085,41086,41087,41088,41089,41090,41091,41092,41093,41094,41095,41096,41097,41098,41099,41100,41101,41102,41103,41104,41105,41106,41107,41108,41109,41110,41111,41112,41113,41114,41115,41116,41117,41118,41119,41120,41121,41122,41123,41124,41125,41126,41127,41128,41129,41130,41131,41132,41133,41134,41135,41136,41137,41138,41139,41140,41141,41142,41143,41144,41145,41146,41147,41148,41149,41150,41151,41152,41153,41154,41155,41156,41157,41158,41159,41160,41161,41162,41163,41164,41165,41166,41167,41168,41169,41170,41171,41172,41173,41174,41175,41176,41177,41178,41179,41180,41181,41182,41183,41184,41185,41186,41187,41188,41189,41190,41191,41192,41193,41194,41195,41196,41197,41198,41199,41200,41201,41202,41203,41204,41205,41206,41207,41208,41209,41210,41211,41212,41213,41214,41215,41216,41217,41218,41219,41220,41221,41222,41223,41224,41225,41226,41227,41228,41229,41230,41231,41232,41233,41234,41235,41236,41237,41238,41239,41240,41241,41242,41243,41244,41245,41246,41247,41248,41249,41250,41251,41252,41253,41254,41255,41256,41257,41258,41259,41260,41261,41262,41263,41264,41265,41266,41267,41268,41269,41270,41271,41272,41273,41274,41275,41276,41277,41278,41279,41280,41281,41282,41283,41284,41285,41286,41287,41288,41289,41290,41291,41292,41293,41294,41295,41296,41297,41298,41299,41300,41301,41302,41303,41304,41305,41306,41307,41308,41309,41310,41311,41312,41313,41314,41315,41316,41317,41318,41319,41320,41321,41322,41323,41324,41325,41326,41327,41328,41329,41330,41331,41332,41333,41334,41335,41336,41337,41338,41339,41340,41341,41342,41343,41344,41345,41346,41347,41348,41349,41350,41351,41352,41353,41354,41355,41356,41357,41358,41359,41360,41361,41362,41363,41364,41365,41366,41367,41368,41369,41370,41371,41372,41373,41374,41375,41376,41377,41378,41379,41380,41381,41382,41383,41384,41385,41386,41387,41388,41389,41390,41391,41392,41393,41394,41395,41396,41397,41398,41399,41400,41401,41402,41403,41404,41405,41406,41407,41408,41409,41410,41411,41412,41413,41414,41415,41416,41417,41418,41419,41420,41421,41422,41423,41424,41425,41426,41427,41428,41429,41430,41431,41432,41433,41434,41435,41436,41437,41438,41439,41440,41441,41442,41443,41444,41445,41446,41447,41448,41449,41450,41451,41452,41453,41454,41455,41456,41457,41458,41459,41460,41461,41462,41463,41464,41465,41466,41467,41468,41469,41470,41471,41472,41473,41474,41475,41476,41477,41478,41479,41480,41481,41482,41483,41484,41485,41486,41487,41488,41489,41490,41491,41492,41493,41494,41495,41496,41497,41498,41499,41500,41501,41502,41503,41504,41505,41506,41507,41508,41509,41510,41511,41512,41513,41514,41515,41516,41517,41518,41519,41520,41521,41522,41523,41524,41525,41526,41527,41528,41529,41530,41531,41532,41533,41534,41535,41536,41537,41538,41539,41540,41541,41542,41543,41544,41545,41546,41547,41548,41549,41550,41551,41552,41553,41554,41555,41556,41557,41558,41559,41560,41561,41562,41563,41564,41565,41566,41567,41568,41569,41570,41571,41572,41573,41574,41575,41576,41577,41578,41579,41580,41581,41582,41583,41584,41585,41586,41587,41588,41589,41590,41591,41592,41593,41594,41595,41596,41597,41598,41599,41600,41601,41602,41603,41604,41605,41606,41607,41608,41609,41610,41611,41612,41613,41614,41615,41616,41617,41618,41619,41620,41621,41622,41623,41624,41625,41626,41627,41628,41629,41630,41631,41632,41633,41634,41635,41636,41637,41638,41639,41640,41641,41642,41643,41644,41645,41646,41647,41648,41649,41650,41651,41652,41653,41654,41655,41656,41657,41658,41659,41660,41661,41662,41663,41664,41665,41666,41667,41668,41669,41670,41671,41672,41673,41674,41675,41676,41677,41678,41679,41680,41681,41682,41683,41684,41685,41686,41687,41688,41689,41690,41691,41692,41693,41694,41695,41696,41697,41698,41699,41700,41701,41702,41703,41704,41705,41706,41707,41708,41709,41710,41711,41712,41713,41714,41715,41716,41717,41718,41719,41720,41721,41722,41723,41724,41725,41726,41727,41728,41729,41730,41731,41732,41733,41734,41735,41736,41737,41738,41739,41740,41741,41742,41743,41744,41745,41746,41747,41748,41749,41750,41751,41752,41753,41754,41755,41756,41757,41758,41759,41760,41761,41762,41763,41764,41765,41766,41767,41768,41769,41770,41771,41772,41773,41774,41775,41776,41777,41778,41779,41780,41781,41782,41783,41784,41785,41786,41787,41788,41789,41790,41791,41792,41793,41794,41795,41796,41797,41798,41799,41800,41801,41802,41803,41804,41805,41806,41807,41808,41809,41810,41811,41812,41813,41814,41815,41816,41817,41818,41819,41820,41821,41822,41823,41824,41825,41826,41827,41828,41829,41830,41831,41832,41833,41834,41835,41836,41837,41838,41839,41840,41841,41842,41843,41844,41845,41846,41847,41848,41849,41850,41851,41852,41853,41854,41855,41856,41857,41858,41859,41860,41861,41862,41863,41864,41865,41866,41867,41868,41869,41870,41871,41872,41873,41874,41875,41876,41877,41878,41879,41880,41881,41882,41883,41884,41885,41886,41887,41888,41889,41890,41891,41892,41893,41894,41895,41896,41897,41898,41899,41900,41901,41902,41903,41904,41905,41906,41907,41908,41909,41910,41911,41912,41913,41914,41915,41916,41917,41918,41919,41920,41921,41922,41923,41924,41925,41926,41927,41928,41929,41930,41931,41932,41933,41934,41935,41936,41937,41938,41939,41940,41941,41942,41943,41944,41945,41946,41947,41948,41949,41950,41951,41952,41953,41954,41955,41956,41957,41958,41959,41960,41961,41962,41963,41964,41965,41966,41967,41968,41969,41970,41971,41972,41973,41974,41975,41976,41977,41978,41979,41980,41981,41982,41983,41984,41985,41986,41987,41988,41989,41990,41991,41992,41993,41994,41995,41996,41997,41998,41999,42000,42001,42002,42003,42004,42005,42006,42007,42008,42009,42010,42011,42012,42013,42014,42015,42016,42017,42018,42019,42020,42021,42022,42023,42024,42025,42026,42027,42028,42029,42030,42031,42032,42033,42034,42035,42036,42037,42038,42039,42040,42041,42042,42043,42044,42045,42046,42047,42048,42049,42050,42051,42052,42053,42054,42055,42056,42057,42058,42059,42060,42061,42062,42063,42064,42065,42066,42067,42068,42069,42070,42071,42072,42073,42074,42075,42076,42077,42078,42079,42080,42081,42082,42083,42084,42085,42086,42087,42088,42089,42090,42091,42092,42093,42094,42095,42096,42097,42098,42099,42100,42101,42102,42103,42104,42105,42106,42107,42108,42109,42110,42111,42112,42113,42114,42115,42116,42117,42118,42119,42120,42121,42122,42123,42124,42192,42193,42194,42195,42196,42197,42198,42199,42200,42201,42202,42203,42204,42205,42206,42207,42208,42209,42210,42211,42212,42213,42214,42215,42216,42217,42218,42219,42220,42221,42222,42223,42224,42225,42226,42227,42228,42229,42230,42231,42232,42233,42234,42235,42236,42237,42240,42241,42242,42243,42244,42245,42246,42247,42248,42249,42250,42251,42252,42253,42254,42255,42256,42257,42258,42259,42260,42261,42262,42263,42264,42265,42266,42267,42268,42269,42270,42271,42272,42273,42274,42275,42276,42277,42278,42279,42280,42281,42282,42283,42284,42285,42286,42287,42288,42289,42290,42291,42292,42293,42294,42295,42296,42297,42298,42299,42300,42301,42302,42303,42304,42305,42306,42307,42308,42309,42310,42311,42312,42313,42314,42315,42316,42317,42318,42319,42320,42321,42322,42323,42324,42325,42326,42327,42328,42329,42330,42331,42332,42333,42334,42335,42336,42337,42338,42339,42340,42341,42342,42343,42344,42345,42346,42347,42348,42349,42350,42351,42352,42353,42354,42355,42356,42357,42358,42359,42360,42361,42362,42363,42364,42365,42366,42367,42368,42369,42370,42371,42372,42373,42374,42375,42376,42377,42378,42379,42380,42381,42382,42383,42384,42385,42386,42387,42388,42389,42390,42391,42392,42393,42394,42395,42396,42397,42398,42399,42400,42401,42402,42403,42404,42405,42406,42407,42408,42409,42410,42411,42412,42413,42414,42415,42416,42417,42418,42419,42420,42421,42422,42423,42424,42425,42426,42427,42428,42429,42430,42431,42432,42433,42434,42435,42436,42437,42438,42439,42440,42441,42442,42443,42444,42445,42446,42447,42448,42449,42450,42451,42452,42453,42454,42455,42456,42457,42458,42459,42460,42461,42462,42463,42464,42465,42466,42467,42468,42469,42470,42471,42472,42473,42474,42475,42476,42477,42478,42479,42480,42481,42482,42483,42484,42485,42486,42487,42488,42489,42490,42491,42492,42493,42494,42495,42496,42497,42498,42499,42500,42501,42502,42503,42504,42505,42506,42507,42508,42512,42513,42514,42515,42516,42517,42518,42519,42520,42521,42522,42523,42524,42525,42526,42527,42538,42539,42560,42561,42562,42563,42564,42565,42566,42567,42568,42569,42570,42571,42572,42573,42574,42575,42576,42577,42578,42579,42580,42581,42582,42583,42584,42585,42586,42587,42588,42589,42590,42591,42592,42593,42594,42595,42596,42597,42598,42599,42600,42601,42602,42603,42604,42605,42606,42623,42624,42625,42626,42627,42628,42629,42630,42631,42632,42633,42634,42635,42636,42637,42638,42639,42640,42641,42642,42643,42644,42645,42646,42647,42656,42657,42658,42659,42660,42661,42662,42663,42664,42665,42666,42667,42668,42669,42670,42671,42672,42673,42674,42675,42676,42677,42678,42679,42680,42681,42682,42683,42684,42685,42686,42687,42688,42689,42690,42691,42692,42693,42694,42695,42696,42697,42698,42699,42700,42701,42702,42703,42704,42705,42706,42707,42708,42709,42710,42711,42712,42713,42714,42715,42716,42717,42718,42719,42720,42721,42722,42723,42724,42725,42726,42727,42728,42729,42730,42731,42732,42733,42734,42735,42775,42776,42777,42778,42779,42780,42781,42782,42783,42786,42787,42788,42789,42790,42791,42792,42793,42794,42795,42796,42797,42798,42799,42800,42801,42802,42803,42804,42805,42806,42807,42808,42809,42810,42811,42812,42813,42814,42815,42816,42817,42818,42819,42820,42821,42822,42823,42824,42825,42826,42827,42828,42829,42830,42831,42832,42833,42834,42835,42836,42837,42838,42839,42840,42841,42842,42843,42844,42845,42846,42847,42848,42849,42850,42851,42852,42853,42854,42855,42856,42857,42858,42859,42860,42861,42862,42863,42864,42865,42866,42867,42868,42869,42870,42871,42872,42873,42874,42875,42876,42877,42878,42879,42880,42881,42882,42883,42884,42885,42886,42887,42888,42891,42892,42893,42894,42896,42897,42898,42899,42912,42913,42914,42915,42916,42917,42918,42919,42920,42921,42922,43000,43001,43002,43003,43004,43005,43006,43007,43008,43009,43011,43012,43013,43015,43016,43017,43018,43020,43021,43022,43023,43024,43025,43026,43027,43028,43029,43030,43031,43032,43033,43034,43035,43036,43037,43038,43039,43040,43041,43042,43072,43073,43074,43075,43076,43077,43078,43079,43080,43081,43082,43083,43084,43085,43086,43087,43088,43089,43090,43091,43092,43093,43094,43095,43096,43097,43098,43099,43100,43101,43102,43103,43104,43105,43106,43107,43108,43109,43110,43111,43112,43113,43114,43115,43116,43117,43118,43119,43120,43121,43122,43123,43138,43139,43140,43141,43142,43143,43144,43145,43146,43147,43148,43149,43150,43151,43152,43153,43154,43155,43156,43157,43158,43159,43160,43161,43162,43163,43164,43165,43166,43167,43168,43169,43170,43171,43172,43173,43174,43175,43176,43177,43178,43179,43180,43181,43182,43183,43184,43185,43186,43187,43250,43251,43252,43253,43254,43255,43259,43274,43275,43276,43277,43278,43279,43280,43281,43282,43283,43284,43285,43286,43287,43288,43289,43290,43291,43292,43293,43294,43295,43296,43297,43298,43299,43300,43301,43312,43313,43314,43315,43316,43317,43318,43319,43320,43321,43322,43323,43324,43325,43326,43327,43328,43329,43330,43331,43332,43333,43334,43360,43361,43362,43363,43364,43365,43366,43367,43368,43369,43370,43371,43372,43373,43374,43375,43376,43377,43378,43379,43380,43381,43382,43383,43384,43385,43386,43387,43388,43396,43397,43398,43399,43400,43401,43402,43403,43404,43405,43406,43407,43408,43409,43410,43411,43412,43413,43414,43415,43416,43417,43418,43419,43420,43421,43422,43423,43424,43425,43426,43427,43428,43429,43430,43431,43432,43433,43434,43435,43436,43437,43438,43439,43440,43441,43442,43471,43520,43521,43522,43523,43524,43525,43526,43527,43528,43529,43530,43531,43532,43533,43534,43535,43536,43537,43538,43539,43540,43541,43542,43543,43544,43545,43546,43547,43548,43549,43550,43551,43552,43553,43554,43555,43556,43557,43558,43559,43560,43584,43585,43586,43588,43589,43590,43591,43592,43593,43594,43595,43616,43617,43618,43619,43620,43621,43622,43623,43624,43625,43626,43627,43628,43629,43630,43631,43632,43633,43634,43635,43636,43637,43638,43642,43648,43649,43650,43651,43652,43653,43654,43655,43656,43657,43658,43659,43660,43661,43662,43663,43664,43665,43666,43667,43668,43669,43670,43671,43672,43673,43674,43675,43676,43677,43678,43679,43680,43681,43682,43683,43684,43685,43686,43687,43688,43689,43690,43691,43692,43693,43694,43695,43697,43701,43702,43705,43706,43707,43708,43709,43712,43714,43739,43740,43741,43744,43745,43746,43747,43748,43749,43750,43751,43752,43753,43754,43762,43763,43764,43777,43778,43779,43780,43781,43782,43785,43786,43787,43788,43789,43790,43793,43794,43795,43796,43797,43798,43808,43809,43810,43811,43812,43813,43814,43816,43817,43818,43819,43820,43821,43822,43968,43969,43970,43971,43972,43973,43974,43975,43976,43977,43978,43979,43980,43981,43982,43983,43984,43985,43986,43987,43988,43989,43990,43991,43992,43993,43994,43995,43996,43997,43998,43999,44000,44001,44002,44032,44033,44034,44035,44036,44037,44038,44039,44040,44041,44042,44043,44044,44045,44046,44047,44048,44049,44050,44051,44052,44053,44054,44055,44056,44057,44058,44059,44060,44061,44062,44063,44064,44065,44066,44067,44068,44069,44070,44071,44072,44073,44074,44075,44076,44077,44078,44079,44080,44081,44082,44083,44084,44085,44086,44087,44088,44089,44090,44091,44092,44093,44094,44095,44096,44097,44098,44099,44100,44101,44102,44103,44104,44105,44106,44107,44108,44109,44110,44111,44112,44113,44114,44115,44116,44117,44118,44119,44120,44121,44122,44123,44124,44125,44126,44127,44128,44129,44130,44131,44132,44133,44134,44135,44136,44137,44138,44139,44140,44141,44142,44143,44144,44145,44146,44147,44148,44149,44150,44151,44152,44153,44154,44155,44156,44157,44158,44159,44160,44161,44162,44163,44164,44165,44166,44167,44168,44169,44170,44171,44172,44173,44174,44175,44176,44177,44178,44179,44180,44181,44182,44183,44184,44185,44186,44187,44188,44189,44190,44191,44192,44193,44194,44195,44196,44197,44198,44199,44200,44201,44202,44203,44204,44205,44206,44207,44208,44209,44210,44211,44212,44213,44214,44215,44216,44217,44218,44219,44220,44221,44222,44223,44224,44225,44226,44227,44228,44229,44230,44231,44232,44233,44234,44235,44236,44237,44238,44239,44240,44241,44242,44243,44244,44245,44246,44247,44248,44249,44250,44251,44252,44253,44254,44255,44256,44257,44258,44259,44260,44261,44262,44263,44264,44265,44266,44267,44268,44269,44270,44271,44272,44273,44274,44275,44276,44277,44278,44279,44280,44281,44282,44283,44284,44285,44286,44287,44288,44289,44290,44291,44292,44293,44294,44295,44296,44297,44298,44299,44300,44301,44302,44303,44304,44305,44306,44307,44308,44309,44310,44311,44312,44313,44314,44315,44316,44317,44318,44319,44320,44321,44322,44323,44324,44325,44326,44327,44328,44329,44330,44331,44332,44333,44334,44335,44336,44337,44338,44339,44340,44341,44342,44343,44344,44345,44346,44347,44348,44349,44350,44351,44352,44353,44354,44355,44356,44357,44358,44359,44360,44361,44362,44363,44364,44365,44366,44367,44368,44369,44370,44371,44372,44373,44374,44375,44376,44377,44378,44379,44380,44381,44382,44383,44384,44385,44386,44387,44388,44389,44390,44391,44392,44393,44394,44395,44396,44397,44398,44399,44400,44401,44402,44403,44404,44405,44406,44407,44408,44409,44410,44411,44412,44413,44414,44415,44416,44417,44418,44419,44420,44421,44422,44423,44424,44425,44426,44427,44428,44429,44430,44431,44432,44433,44434,44435,44436,44437,44438,44439,44440,44441,44442,44443,44444,44445,44446,44447,44448,44449,44450,44451,44452,44453,44454,44455,44456,44457,44458,44459,44460,44461,44462,44463,44464,44465,44466,44467,44468,44469,44470,44471,44472,44473,44474,44475,44476,44477,44478,44479,44480,44481,44482,44483,44484,44485,44486,44487,44488,44489,44490,44491,44492,44493,44494,44495,44496,44497,44498,44499,44500,44501,44502,44503,44504,44505,44506,44507,44508,44509,44510,44511,44512,44513,44514,44515,44516,44517,44518,44519,44520,44521,44522,44523,44524,44525,44526,44527,44528,44529,44530,44531,44532,44533,44534,44535,44536,44537,44538,44539,44540,44541,44542,44543,44544,44545,44546,44547,44548,44549,44550,44551,44552,44553,44554,44555,44556,44557,44558,44559,44560,44561,44562,44563,44564,44565,44566,44567,44568,44569,44570,44571,44572,44573,44574,44575,44576,44577,44578,44579,44580,44581,44582,44583,44584,44585,44586,44587,44588,44589,44590,44591,44592,44593,44594,44595,44596,44597,44598,44599,44600,44601,44602,44603,44604,44605,44606,44607,44608,44609,44610,44611,44612,44613,44614,44615,44616,44617,44618,44619,44620,44621,44622,44623,44624,44625,44626,44627,44628,44629,44630,44631,44632,44633,44634,44635,44636,44637,44638,44639,44640,44641,44642,44643,44644,44645,44646,44647,44648,44649,44650,44651,44652,44653,44654,44655,44656,44657,44658,44659,44660,44661,44662,44663,44664,44665,44666,44667,44668,44669,44670,44671,44672,44673,44674,44675,44676,44677,44678,44679,44680,44681,44682,44683,44684,44685,44686,44687,44688,44689,44690,44691,44692,44693,44694,44695,44696,44697,44698,44699,44700,44701,44702,44703,44704,44705,44706,44707,44708,44709,44710,44711,44712,44713,44714,44715,44716,44717,44718,44719,44720,44721,44722,44723,44724,44725,44726,44727,44728,44729,44730,44731,44732,44733,44734,44735,44736,44737,44738,44739,44740,44741,44742,44743,44744,44745,44746,44747,44748,44749,44750,44751,44752,44753,44754,44755,44756,44757,44758,44759,44760,44761,44762,44763,44764,44765,44766,44767,44768,44769,44770,44771,44772,44773,44774,44775,44776,44777,44778,44779,44780,44781,44782,44783,44784,44785,44786,44787,44788,44789,44790,44791,44792,44793,44794,44795,44796,44797,44798,44799,44800,44801,44802,44803,44804,44805,44806,44807,44808,44809,44810,44811,44812,44813,44814,44815,44816,44817,44818,44819,44820,44821,44822,44823,44824,44825,44826,44827,44828,44829,44830,44831,44832,44833,44834,44835,44836,44837,44838,44839,44840,44841,44842,44843,44844,44845,44846,44847,44848,44849,44850,44851,44852,44853,44854,44855,44856,44857,44858,44859,44860,44861,44862,44863,44864,44865,44866,44867,44868,44869,44870,44871,44872,44873,44874,44875,44876,44877,44878,44879,44880,44881,44882,44883,44884,44885,44886,44887,44888,44889,44890,44891,44892,44893,44894,44895,44896,44897,44898,44899,44900,44901,44902,44903,44904,44905,44906,44907,44908,44909,44910,44911,44912,44913,44914,44915,44916,44917,44918,44919,44920,44921,44922,44923,44924,44925,44926,44927,44928,44929,44930,44931,44932,44933,44934,44935,44936,44937,44938,44939,44940,44941,44942,44943,44944,44945,44946,44947,44948,44949,44950,44951,44952,44953,44954,44955,44956,44957,44958,44959,44960,44961,44962,44963,44964,44965,44966,44967,44968,44969,44970,44971,44972,44973,44974,44975,44976,44977,44978,44979,44980,44981,44982,44983,44984,44985,44986,44987,44988,44989,44990,44991,44992,44993,44994,44995,44996,44997,44998,44999,45000,45001,45002,45003,45004,45005,45006,45007,45008,45009,45010,45011,45012,45013,45014,45015,45016,45017,45018,45019,45020,45021,45022,45023,45024,45025,45026,45027,45028,45029,45030,45031,45032,45033,45034,45035,45036,45037,45038,45039,45040,45041,45042,45043,45044,45045,45046,45047,45048,45049,45050,45051,45052,45053,45054,45055,45056,45057,45058,45059,45060,45061,45062,45063,45064,45065,45066,45067,45068,45069,45070,45071,45072,45073,45074,45075,45076,45077,45078,45079,45080,45081,45082,45083,45084,45085,45086,45087,45088,45089,45090,45091,45092,45093,45094,45095,45096,45097,45098,45099,45100,45101,45102,45103,45104,45105,45106,45107,45108,45109,45110,45111,45112,45113,45114,45115,45116,45117,45118,45119,45120,45121,45122,45123,45124,45125,45126,45127,45128,45129,45130,45131,45132,45133,45134,45135,45136,45137,45138,45139,45140,45141,45142,45143,45144,45145,45146,45147,45148,45149,45150,45151,45152,45153,45154,45155,45156,45157,45158,45159,45160,45161,45162,45163,45164,45165,45166,45167,45168,45169,45170,45171,45172,45173,45174,45175,45176,45177,45178,45179,45180,45181,45182,45183,45184,45185,45186,45187,45188,45189,45190,45191,45192,45193,45194,45195,45196,45197,45198,45199,45200,45201,45202,45203,45204,45205,45206,45207,45208,45209,45210,45211,45212,45213,45214,45215,45216,45217,45218,45219,45220,45221,45222,45223,45224,45225,45226,45227,45228,45229,45230,45231,45232,45233,45234,45235,45236,45237,45238,45239,45240,45241,45242,45243,45244,45245,45246,45247,45248,45249,45250,45251,45252,45253,45254,45255,45256,45257,45258,45259,45260,45261,45262,45263,45264,45265,45266,45267,45268,45269,45270,45271,45272,45273,45274,45275,45276,45277,45278,45279,45280,45281,45282,45283,45284,45285,45286,45287,45288,45289,45290,45291,45292,45293,45294,45295,45296,45297,45298,45299,45300,45301,45302,45303,45304,45305,45306,45307,45308,45309,45310,45311,45312,45313,45314,45315,45316,45317,45318,45319,45320,45321,45322,45323,45324,45325,45326,45327,45328,45329,45330,45331,45332,45333,45334,45335,45336,45337,45338,45339,45340,45341,45342,45343,45344,45345,45346,45347,45348,45349,45350,45351,45352,45353,45354,45355,45356,45357,45358,45359,45360,45361,45362,45363,45364,45365,45366,45367,45368,45369,45370,45371,45372,45373,45374,45375,45376,45377,45378,45379,45380,45381,45382,45383,45384,45385,45386,45387,45388,45389,45390,45391,45392,45393,45394,45395,45396,45397,45398,45399,45400,45401,45402,45403,45404,45405,45406,45407,45408,45409,45410,45411,45412,45413,45414,45415,45416,45417,45418,45419,45420,45421,45422,45423,45424,45425,45426,45427,45428,45429,45430,45431,45432,45433,45434,45435,45436,45437,45438,45439,45440,45441,45442,45443,45444,45445,45446,45447,45448,45449,45450,45451,45452,45453,45454,45455,45456,45457,45458,45459,45460,45461,45462,45463,45464,45465,45466,45467,45468,45469,45470,45471,45472,45473,45474,45475,45476,45477,45478,45479,45480,45481,45482,45483,45484,45485,45486,45487,45488,45489,45490,45491,45492,45493,45494,45495,45496,45497,45498,45499,45500,45501,45502,45503,45504,45505,45506,45507,45508,45509,45510,45511,45512,45513,45514,45515,45516,45517,45518,45519,45520,45521,45522,45523,45524,45525,45526,45527,45528,45529,45530,45531,45532,45533,45534,45535,45536,45537,45538,45539,45540,45541,45542,45543,45544,45545,45546,45547,45548,45549,45550,45551,45552,45553,45554,45555,45556,45557,45558,45559,45560,45561,45562,45563,45564,45565,45566,45567,45568,45569,45570,45571,45572,45573,45574,45575,45576,45577,45578,45579,45580,45581,45582,45583,45584,45585,45586,45587,45588,45589,45590,45591,45592,45593,45594,45595,45596,45597,45598,45599,45600,45601,45602,45603,45604,45605,45606,45607,45608,45609,45610,45611,45612,45613,45614,45615,45616,45617,45618,45619,45620,45621,45622,45623,45624,45625,45626,45627,45628,45629,45630,45631,45632,45633,45634,45635,45636,45637,45638,45639,45640,45641,45642,45643,45644,45645,45646,45647,45648,45649,45650,45651,45652,45653,45654,45655,45656,45657,45658,45659,45660,45661,45662,45663,45664,45665,45666,45667,45668,45669,45670,45671,45672,45673,45674,45675,45676,45677,45678,45679,45680,45681,45682,45683,45684,45685,45686,45687,45688,45689,45690,45691,45692,45693,45694,45695,45696,45697,45698,45699,45700,45701,45702,45703,45704,45705,45706,45707,45708,45709,45710,45711,45712,45713,45714,45715,45716,45717,45718,45719,45720,45721,45722,45723,45724,45725,45726,45727,45728,45729,45730,45731,45732,45733,45734,45735,45736,45737,45738,45739,45740,45741,45742,45743,45744,45745,45746,45747,45748,45749,45750,45751,45752,45753,45754,45755,45756,45757,45758,45759,45760,45761,45762,45763,45764,45765,45766,45767,45768,45769,45770,45771,45772,45773,45774,45775,45776,45777,45778,45779,45780,45781,45782,45783,45784,45785,45786,45787,45788,45789,45790,45791,45792,45793,45794,45795,45796,45797,45798,45799,45800,45801,45802,45803,45804,45805,45806,45807,45808,45809,45810,45811,45812,45813,45814,45815,45816,45817,45818,45819,45820,45821,45822,45823,45824,45825,45826,45827,45828,45829,45830,45831,45832,45833,45834,45835,45836,45837,45838,45839,45840,45841,45842,45843,45844,45845,45846,45847,45848,45849,45850,45851,45852,45853,45854,45855,45856,45857,45858,45859,45860,45861,45862,45863,45864,45865,45866,45867,45868,45869,45870,45871,45872,45873,45874,45875,45876,45877,45878,45879,45880,45881,45882,45883,45884,45885,45886,45887,45888,45889,45890,45891,45892,45893,45894,45895,45896,45897,45898,45899,45900,45901,45902,45903,45904,45905,45906,45907,45908,45909,45910,45911,45912,45913,45914,45915,45916,45917,45918,45919,45920,45921,45922,45923,45924,45925,45926,45927,45928,45929,45930,45931,45932,45933,45934,45935,45936,45937,45938,45939,45940,45941,45942,45943,45944,45945,45946,45947,45948,45949,45950,45951,45952,45953,45954,45955,45956,45957,45958,45959,45960,45961,45962,45963,45964,45965,45966,45967,45968,45969,45970,45971,45972,45973,45974,45975,45976,45977,45978,45979,45980,45981,45982,45983,45984,45985,45986,45987,45988,45989,45990,45991,45992,45993,45994,45995,45996,45997,45998,45999,46000,46001,46002,46003,46004,46005,46006,46007,46008,46009,46010,46011,46012,46013,46014,46015,46016,46017,46018,46019,46020,46021,46022,46023,46024,46025,46026,46027,46028,46029,46030,46031,46032,46033,46034,46035,46036,46037,46038,46039,46040,46041,46042,46043,46044,46045,46046,46047,46048,46049,46050,46051,46052,46053,46054,46055,46056,46057,46058,46059,46060,46061,46062,46063,46064,46065,46066,46067,46068,46069,46070,46071,46072,46073,46074,46075,46076,46077,46078,46079,46080,46081,46082,46083,46084,46085,46086,46087,46088,46089,46090,46091,46092,46093,46094,46095,46096,46097,46098,46099,46100,46101,46102,46103,46104,46105,46106,46107,46108,46109,46110,46111,46112,46113,46114,46115,46116,46117,46118,46119,46120,46121,46122,46123,46124,46125,46126,46127,46128,46129,46130,46131,46132,46133,46134,46135,46136,46137,46138,46139,46140,46141,46142,46143,46144,46145,46146,46147,46148,46149,46150,46151,46152,46153,46154,46155,46156,46157,46158,46159,46160,46161,46162,46163,46164,46165,46166,46167,46168,46169,46170,46171,46172,46173,46174,46175,46176,46177,46178,46179,46180,46181,46182,46183,46184,46185,46186,46187,46188,46189,46190,46191,46192,46193,46194,46195,46196,46197,46198,46199,46200,46201,46202,46203,46204,46205,46206,46207,46208,46209,46210,46211,46212,46213,46214,46215,46216,46217,46218,46219,46220,46221,46222,46223,46224,46225,46226,46227,46228,46229,46230,46231,46232,46233,46234,46235,46236,46237,46238,46239,46240,46241,46242,46243,46244,46245,46246,46247,46248,46249,46250,46251,46252,46253,46254,46255,46256,46257,46258,46259,46260,46261,46262,46263,46264,46265,46266,46267,46268,46269,46270,46271,46272,46273,46274,46275,46276,46277,46278,46279,46280,46281,46282,46283,46284,46285,46286,46287,46288,46289,46290,46291,46292,46293,46294,46295,46296,46297,46298,46299,46300,46301,46302,46303,46304,46305,46306,46307,46308,46309,46310,46311,46312,46313,46314,46315,46316,46317,46318,46319,46320,46321,46322,46323,46324,46325,46326,46327,46328,46329,46330,46331,46332,46333,46334,46335,46336,46337,46338,46339,46340,46341,46342,46343,46344,46345,46346,46347,46348,46349,46350,46351,46352,46353,46354,46355,46356,46357,46358,46359,46360,46361,46362,46363,46364,46365,46366,46367,46368,46369,46370,46371,46372,46373,46374,46375,46376,46377,46378,46379,46380,46381,46382,46383,46384,46385,46386,46387,46388,46389,46390,46391,46392,46393,46394,46395,46396,46397,46398,46399,46400,46401,46402,46403,46404,46405,46406,46407,46408,46409,46410,46411,46412,46413,46414,46415,46416,46417,46418,46419,46420,46421,46422,46423,46424,46425,46426,46427,46428,46429,46430,46431,46432,46433,46434,46435,46436,46437,46438,46439,46440,46441,46442,46443,46444,46445,46446,46447,46448,46449,46450,46451,46452,46453,46454,46455,46456,46457,46458,46459,46460,46461,46462,46463,46464,46465,46466,46467,46468,46469,46470,46471,46472,46473,46474,46475,46476,46477,46478,46479,46480,46481,46482,46483,46484,46485,46486,46487,46488,46489,46490,46491,46492,46493,46494,46495,46496,46497,46498,46499,46500,46501,46502,46503,46504,46505,46506,46507,46508,46509,46510,46511,46512,46513,46514,46515,46516,46517,46518,46519,46520,46521,46522,46523,46524,46525,46526,46527,46528,46529,46530,46531,46532,46533,46534,46535,46536,46537,46538,46539,46540,46541,46542,46543,46544,46545,46546,46547,46548,46549,46550,46551,46552,46553,46554,46555,46556,46557,46558,46559,46560,46561,46562,46563,46564,46565,46566,46567,46568,46569,46570,46571,46572,46573,46574,46575,46576,46577,46578,46579,46580,46581,46582,46583,46584,46585,46586,46587,46588,46589,46590,46591,46592,46593,46594,46595,46596,46597,46598,46599,46600,46601,46602,46603,46604,46605,46606,46607,46608,46609,46610,46611,46612,46613,46614,46615,46616,46617,46618,46619,46620,46621,46622,46623,46624,46625,46626,46627,46628,46629,46630,46631,46632,46633,46634,46635,46636,46637,46638,46639,46640,46641,46642,46643,46644,46645,46646,46647,46648,46649,46650,46651,46652,46653,46654,46655,46656,46657,46658,46659,46660,46661,46662,46663,46664,46665,46666,46667,46668,46669,46670,46671,46672,46673,46674,46675,46676,46677,46678,46679,46680,46681,46682,46683,46684,46685,46686,46687,46688,46689,46690,46691,46692,46693,46694,46695,46696,46697,46698,46699,46700,46701,46702,46703,46704,46705,46706,46707,46708,46709,46710,46711,46712,46713,46714,46715,46716,46717,46718,46719,46720,46721,46722,46723,46724,46725,46726,46727,46728,46729,46730,46731,46732,46733,46734,46735,46736,46737,46738,46739,46740,46741,46742,46743,46744,46745,46746,46747,46748,46749,46750,46751,46752,46753,46754,46755,46756,46757,46758,46759,46760,46761,46762,46763,46764,46765,46766,46767,46768,46769,46770,46771,46772,46773,46774,46775,46776,46777,46778,46779,46780,46781,46782,46783,46784,46785,46786,46787,46788,46789,46790,46791,46792,46793,46794,46795,46796,46797,46798,46799,46800,46801,46802,46803,46804,46805,46806,46807,46808,46809,46810,46811,46812,46813,46814,46815,46816,46817,46818,46819,46820,46821,46822,46823,46824,46825,46826,46827,46828,46829,46830,46831,46832,46833,46834,46835,46836,46837,46838,46839,46840,46841,46842,46843,46844,46845,46846,46847,46848,46849,46850,46851,46852,46853,46854,46855,46856,46857,46858,46859,46860,46861,46862,46863,46864,46865,46866,46867,46868,46869,46870,46871,46872,46873,46874,46875,46876,46877,46878,46879,46880,46881,46882,46883,46884,46885,46886,46887,46888,46889,46890,46891,46892,46893,46894,46895,46896,46897,46898,46899,46900,46901,46902,46903,46904,46905,46906,46907,46908,46909,46910,46911,46912,46913,46914,46915,46916,46917,46918,46919,46920,46921,46922,46923,46924,46925,46926,46927,46928,46929,46930,46931,46932,46933,46934,46935,46936,46937,46938,46939,46940,46941,46942,46943,46944,46945,46946,46947,46948,46949,46950,46951,46952,46953,46954,46955,46956,46957,46958,46959,46960,46961,46962,46963,46964,46965,46966,46967,46968,46969,46970,46971,46972,46973,46974,46975,46976,46977,46978,46979,46980,46981,46982,46983,46984,46985,46986,46987,46988,46989,46990,46991,46992,46993,46994,46995,46996,46997,46998,46999,47000,47001,47002,47003,47004,47005,47006,47007,47008,47009,47010,47011,47012,47013,47014,47015,47016,47017,47018,47019,47020,47021,47022,47023,47024,47025,47026,47027,47028,47029,47030,47031,47032,47033,47034,47035,47036,47037,47038,47039,47040,47041,47042,47043,47044,47045,47046,47047,47048,47049,47050,47051,47052,47053,47054,47055,47056,47057,47058,47059,47060,47061,47062,47063,47064,47065,47066,47067,47068,47069,47070,47071,47072,47073,47074,47075,47076,47077,47078,47079,47080,47081,47082,47083,47084,47085,47086,47087,47088,47089,47090,47091,47092,47093,47094,47095,47096,47097,47098,47099,47100,47101,47102,47103,47104,47105,47106,47107,47108,47109,47110,47111,47112,47113,47114,47115,47116,47117,47118,47119,47120,47121,47122,47123,47124,47125,47126,47127,47128,47129,47130,47131,47132,47133,47134,47135,47136,47137,47138,47139,47140,47141,47142,47143,47144,47145,47146,47147,47148,47149,47150,47151,47152,47153,47154,47155,47156,47157,47158,47159,47160,47161,47162,47163,47164,47165,47166,47167,47168,47169,47170,47171,47172,47173,47174,47175,47176,47177,47178,47179,47180,47181,47182,47183,47184,47185,47186,47187,47188,47189,47190,47191,47192,47193,47194,47195,47196,47197,47198,47199,47200,47201,47202,47203,47204,47205,47206,47207,47208,47209,47210,47211,47212,47213,47214,47215,47216,47217,47218,47219,47220,47221,47222,47223,47224,47225,47226,47227,47228,47229,47230,47231,47232,47233,47234,47235,47236,47237,47238,47239,47240,47241,47242,47243,47244,47245,47246,47247,47248,47249,47250,47251,47252,47253,47254,47255,47256,47257,47258,47259,47260,47261,47262,47263,47264,47265,47266,47267,47268,47269,47270,47271,47272,47273,47274,47275,47276,47277,47278,47279,47280,47281,47282,47283,47284,47285,47286,47287,47288,47289,47290,47291,47292,47293,47294,47295,47296,47297,47298,47299,47300,47301,47302,47303,47304,47305,47306,47307,47308,47309,47310,47311,47312,47313,47314,47315,47316,47317,47318,47319,47320,47321,47322,47323,47324,47325,47326,47327,47328,47329,47330,47331,47332,47333,47334,47335,47336,47337,47338,47339,47340,47341,47342,47343,47344,47345,47346,47347,47348,47349,47350,47351,47352,47353,47354,47355,47356,47357,47358,47359,47360,47361,47362,47363,47364,47365,47366,47367,47368,47369,47370,47371,47372,47373,47374,47375,47376,47377,47378,47379,47380,47381,47382,47383,47384,47385,47386,47387,47388,47389,47390,47391,47392,47393,47394,47395,47396,47397,47398,47399,47400,47401,47402,47403,47404,47405,47406,47407,47408,47409,47410,47411,47412,47413,47414,47415,47416,47417,47418,47419,47420,47421,47422,47423,47424,47425,47426,47427,47428,47429,47430,47431,47432,47433,47434,47435,47436,47437,47438,47439,47440,47441,47442,47443,47444,47445,47446,47447,47448,47449,47450,47451,47452,47453,47454,47455,47456,47457,47458,47459,47460,47461,47462,47463,47464,47465,47466,47467,47468,47469,47470,47471,47472,47473,47474,47475,47476,47477,47478,47479,47480,47481,47482,47483,47484,47485,47486,47487,47488,47489,47490,47491,47492,47493,47494,47495,47496,47497,47498,47499,47500,47501,47502,47503,47504,47505,47506,47507,47508,47509,47510,47511,47512,47513,47514,47515,47516,47517,47518,47519,47520,47521,47522,47523,47524,47525,47526,47527,47528,47529,47530,47531,47532,47533,47534,47535,47536,47537,47538,47539,47540,47541,47542,47543,47544,47545,47546,47547,47548,47549,47550,47551,47552,47553,47554,47555,47556,47557,47558,47559,47560,47561,47562,47563,47564,47565,47566,47567,47568,47569,47570,47571,47572,47573,47574,47575,47576,47577,47578,47579,47580,47581,47582,47583,47584,47585,47586,47587,47588,47589,47590,47591,47592,47593,47594,47595,47596,47597,47598,47599,47600,47601,47602,47603,47604,47605,47606,47607,47608,47609,47610,47611,47612,47613,47614,47615,47616,47617,47618,47619,47620,47621,47622,47623,47624,47625,47626,47627,47628,47629,47630,47631,47632,47633,47634,47635,47636,47637,47638,47639,47640,47641,47642,47643,47644,47645,47646,47647,47648,47649,47650,47651,47652,47653,47654,47655,47656,47657,47658,47659,47660,47661,47662,47663,47664,47665,47666,47667,47668,47669,47670,47671,47672,47673,47674,47675,47676,47677,47678,47679,47680,47681,47682,47683,47684,47685,47686,47687,47688,47689,47690,47691,47692,47693,47694,47695,47696,47697,47698,47699,47700,47701,47702,47703,47704,47705,47706,47707,47708,47709,47710,47711,47712,47713,47714,47715,47716,47717,47718,47719,47720,47721,47722,47723,47724,47725,47726,47727,47728,47729,47730,47731,47732,47733,47734,47735,47736,47737,47738,47739,47740,47741,47742,47743,47744,47745,47746,47747,47748,47749,47750,47751,47752,47753,47754,47755,47756,47757,47758,47759,47760,47761,47762,47763,47764,47765,47766,47767,47768,47769,47770,47771,47772,47773,47774,47775,47776,47777,47778,47779,47780,47781,47782,47783,47784,47785,47786,47787,47788,47789,47790,47791,47792,47793,47794,47795,47796,47797,47798,47799,47800,47801,47802,47803,47804,47805,47806,47807,47808,47809,47810,47811,47812,47813,47814,47815,47816,47817,47818,47819,47820,47821,47822,47823,47824,47825,47826,47827,47828,47829,47830,47831,47832,47833,47834,47835,47836,47837,47838,47839,47840,47841,47842,47843,47844,47845,47846,47847,47848,47849,47850,47851,47852,47853,47854,47855,47856,47857,47858,47859,47860,47861,47862,47863,47864,47865,47866,47867,47868,47869,47870,47871,47872,47873,47874,47875,47876,47877,47878,47879,47880,47881,47882,47883,47884,47885,47886,47887,47888,47889,47890,47891,47892,47893,47894,47895,47896,47897,47898,47899,47900,47901,47902,47903,47904,47905,47906,47907,47908,47909,47910,47911,47912,47913,47914,47915,47916,47917,47918,47919,47920,47921,47922,47923,47924,47925,47926,47927,47928,47929,47930,47931,47932,47933,47934,47935,47936,47937,47938,47939,47940,47941,47942,47943,47944,47945,47946,47947,47948,47949,47950,47951,47952,47953,47954,47955,47956,47957,47958,47959,47960,47961,47962,47963,47964,47965,47966,47967,47968,47969,47970,47971,47972,47973,47974,47975,47976,47977,47978,47979,47980,47981,47982,47983,47984,47985,47986,47987,47988,47989,47990,47991,47992,47993,47994,47995,47996,47997,47998,47999,48000,48001,48002,48003,48004,48005,48006,48007,48008,48009,48010,48011,48012,48013,48014,48015,48016,48017,48018,48019,48020,48021,48022,48023,48024,48025,48026,48027,48028,48029,48030,48031,48032,48033,48034,48035,48036,48037,48038,48039,48040,48041,48042,48043,48044,48045,48046,48047,48048,48049,48050,48051,48052,48053,48054,48055,48056,48057,48058,48059,48060,48061,48062,48063,48064,48065,48066,48067,48068,48069,48070,48071,48072,48073,48074,48075,48076,48077,48078,48079,48080,48081,48082,48083,48084,48085,48086,48087,48088,48089,48090,48091,48092,48093,48094,48095,48096,48097,48098,48099,48100,48101,48102,48103,48104,48105,48106,48107,48108,48109,48110,48111,48112,48113,48114,48115,48116,48117,48118,48119,48120,48121,48122,48123,48124,48125,48126,48127,48128,48129,48130,48131,48132,48133,48134,48135,48136,48137,48138,48139,48140,48141,48142,48143,48144,48145,48146,48147,48148,48149,48150,48151,48152,48153,48154,48155,48156,48157,48158,48159,48160,48161,48162,48163,48164,48165,48166,48167,48168,48169,48170,48171,48172,48173,48174,48175,48176,48177,48178,48179,48180,48181,48182,48183,48184,48185,48186,48187,48188,48189,48190,48191,48192,48193,48194,48195,48196,48197,48198,48199,48200,48201,48202,48203,48204,48205,48206,48207,48208,48209,48210,48211,48212,48213,48214,48215,48216,48217,48218,48219,48220,48221,48222,48223,48224,48225,48226,48227,48228,48229,48230,48231,48232,48233,48234,48235,48236,48237,48238,48239,48240,48241,48242,48243,48244,48245,48246,48247,48248,48249,48250,48251,48252,48253,48254,48255,48256,48257,48258,48259,48260,48261,48262,48263,48264,48265,48266,48267,48268,48269,48270,48271,48272,48273,48274,48275,48276,48277,48278,48279,48280,48281,48282,48283,48284,48285,48286,48287,48288,48289,48290,48291,48292,48293,48294,48295,48296,48297,48298,48299,48300,48301,48302,48303,48304,48305,48306,48307,48308,48309,48310,48311,48312,48313,48314,48315,48316,48317,48318,48319,48320,48321,48322,48323,48324,48325,48326,48327,48328,48329,48330,48331,48332,48333,48334,48335,48336,48337,48338,48339,48340,48341,48342,48343,48344,48345,48346,48347,48348,48349,48350,48351,48352,48353,48354,48355,48356,48357,48358,48359,48360,48361,48362,48363,48364,48365,48366,48367,48368,48369,48370,48371,48372,48373,48374,48375,48376,48377,48378,48379,48380,48381,48382,48383,48384,48385,48386,48387,48388,48389,48390,48391,48392,48393,48394,48395,48396,48397,48398,48399,48400,48401,48402,48403,48404,48405,48406,48407,48408,48409,48410,48411,48412,48413,48414,48415,48416,48417,48418,48419,48420,48421,48422,48423,48424,48425,48426,48427,48428,48429,48430,48431,48432,48433,48434,48435,48436,48437,48438,48439,48440,48441,48442,48443,48444,48445,48446,48447,48448,48449,48450,48451,48452,48453,48454,48455,48456,48457,48458,48459,48460,48461,48462,48463,48464,48465,48466,48467,48468,48469,48470,48471,48472,48473,48474,48475,48476,48477,48478,48479,48480,48481,48482,48483,48484,48485,48486,48487,48488,48489,48490,48491,48492,48493,48494,48495,48496,48497,48498,48499,48500,48501,48502,48503,48504,48505,48506,48507,48508,48509,48510,48511,48512,48513,48514,48515,48516,48517,48518,48519,48520,48521,48522,48523,48524,48525,48526,48527,48528,48529,48530,48531,48532,48533,48534,48535,48536,48537,48538,48539,48540,48541,48542,48543,48544,48545,48546,48547,48548,48549,48550,48551,48552,48553,48554,48555,48556,48557,48558,48559,48560,48561,48562,48563,48564,48565,48566,48567,48568,48569,48570,48571,48572,48573,48574,48575,48576,48577,48578,48579,48580,48581,48582,48583,48584,48585,48586,48587,48588,48589,48590,48591,48592,48593,48594,48595,48596,48597,48598,48599,48600,48601,48602,48603,48604,48605,48606,48607,48608,48609,48610,48611,48612,48613,48614,48615,48616,48617,48618,48619,48620,48621,48622,48623,48624,48625,48626,48627,48628,48629,48630,48631,48632,48633,48634,48635,48636,48637,48638,48639,48640,48641,48642,48643,48644,48645,48646,48647,48648,48649,48650,48651,48652,48653,48654,48655,48656,48657,48658,48659,48660,48661,48662,48663,48664,48665,48666,48667,48668,48669,48670,48671,48672,48673,48674,48675,48676,48677,48678,48679,48680,48681,48682,48683,48684,48685,48686,48687,48688,48689,48690,48691,48692,48693,48694,48695,48696,48697,48698,48699,48700,48701,48702,48703,48704,48705,48706,48707,48708,48709,48710,48711,48712,48713,48714,48715,48716,48717,48718,48719,48720,48721,48722,48723,48724,48725,48726,48727,48728,48729,48730,48731,48732,48733,48734,48735,48736,48737,48738,48739,48740,48741,48742,48743,48744,48745,48746,48747,48748,48749,48750,48751,48752,48753,48754,48755,48756,48757,48758,48759,48760,48761,48762,48763,48764,48765,48766,48767,48768,48769,48770,48771,48772,48773,48774,48775,48776,48777,48778,48779,48780,48781,48782,48783,48784,48785,48786,48787,48788,48789,48790,48791,48792,48793,48794,48795,48796,48797,48798,48799,48800,48801,48802,48803,48804,48805,48806,48807,48808,48809,48810,48811,48812,48813,48814,48815,48816,48817,48818,48819,48820,48821,48822,48823,48824,48825,48826,48827,48828,48829,48830,48831,48832,48833,48834,48835,48836,48837,48838,48839,48840,48841,48842,48843,48844,48845,48846,48847,48848,48849,48850,48851,48852,48853,48854,48855,48856,48857,48858,48859,48860,48861,48862,48863,48864,48865,48866,48867,48868,48869,48870,48871,48872,48873,48874,48875,48876,48877,48878,48879,48880,48881,48882,48883,48884,48885,48886,48887,48888,48889,48890,48891,48892,48893,48894,48895,48896,48897,48898,48899,48900,48901,48902,48903,48904,48905,48906,48907,48908,48909,48910,48911,48912,48913,48914,48915,48916,48917,48918,48919,48920,48921,48922,48923,48924,48925,48926,48927,48928,48929,48930,48931,48932,48933,48934,48935,48936,48937,48938,48939,48940,48941,48942,48943,48944,48945,48946,48947,48948,48949,48950,48951,48952,48953,48954,48955,48956,48957,48958,48959,48960,48961,48962,48963,48964,48965,48966,48967,48968,48969,48970,48971,48972,48973,48974,48975,48976,48977,48978,48979,48980,48981,48982,48983,48984,48985,48986,48987,48988,48989,48990,48991,48992,48993,48994,48995,48996,48997,48998,48999,49000,49001,49002,49003,49004,49005,49006,49007,49008,49009,49010,49011,49012,49013,49014,49015,49016,49017,49018,49019,49020,49021,49022,49023,49024,49025,49026,49027,49028,49029,49030,49031,49032,49033,49034,49035,49036,49037,49038,49039,49040,49041,49042,49043,49044,49045,49046,49047,49048,49049,49050,49051,49052,49053,49054,49055,49056,49057,49058,49059,49060,49061,49062,49063,49064,49065,49066,49067,49068,49069,49070,49071,49072,49073,49074,49075,49076,49077,49078,49079,49080,49081,49082,49083,49084,49085,49086,49087,49088,49089,49090,49091,49092,49093,49094,49095,49096,49097,49098,49099,49100,49101,49102,49103,49104,49105,49106,49107,49108,49109,49110,49111,49112,49113,49114,49115,49116,49117,49118,49119,49120,49121,49122,49123,49124,49125,49126,49127,49128,49129,49130,49131,49132,49133,49134,49135,49136,49137,49138,49139,49140,49141,49142,49143,49144,49145,49146,49147,49148,49149,49150,49151,49152,49153,49154,49155,49156,49157,49158,49159,49160,49161,49162,49163,49164,49165,49166,49167,49168,49169,49170,49171,49172,49173,49174,49175,49176,49177,49178,49179,49180,49181,49182,49183,49184,49185,49186,49187,49188,49189,49190,49191,49192,49193,49194,49195,49196,49197,49198,49199,49200,49201,49202,49203,49204,49205,49206,49207,49208,49209,49210,49211,49212,49213,49214,49215,49216,49217,49218,49219,49220,49221,49222,49223,49224,49225,49226,49227,49228,49229,49230,49231,49232,49233,49234,49235,49236,49237,49238,49239,49240,49241,49242,49243,49244,49245,49246,49247,49248,49249,49250,49251,49252,49253,49254,49255,49256,49257,49258,49259,49260,49261,49262,49263,49264,49265,49266,49267,49268,49269,49270,49271,49272,49273,49274,49275,49276,49277,49278,49279,49280,49281,49282,49283,49284,49285,49286,49287,49288,49289,49290,49291,49292,49293,49294,49295,49296,49297,49298,49299,49300,49301,49302,49303,49304,49305,49306,49307,49308,49309,49310,49311,49312,49313,49314,49315,49316,49317,49318,49319,49320,49321,49322,49323,49324,49325,49326,49327,49328,49329,49330,49331,49332,49333,49334,49335,49336,49337,49338,49339,49340,49341,49342,49343,49344,49345,49346,49347,49348,49349,49350,49351,49352,49353,49354,49355,49356,49357,49358,49359,49360,49361,49362,49363,49364,49365,49366,49367,49368,49369,49370,49371,49372,49373,49374,49375,49376,49377,49378,49379,49380,49381,49382,49383,49384,49385,49386,49387,49388,49389,49390,49391,49392,49393,49394,49395,49396,49397,49398,49399,49400,49401,49402,49403,49404,49405,49406,49407,49408,49409,49410,49411,49412,49413,49414,49415,49416,49417,49418,49419,49420,49421,49422,49423,49424,49425,49426,49427,49428,49429,49430,49431,49432,49433,49434,49435,49436,49437,49438,49439,49440,49441,49442,49443,49444,49445,49446,49447,49448,49449,49450,49451,49452,49453,49454,49455,49456,49457,49458,49459,49460,49461,49462,49463,49464,49465,49466,49467,49468,49469,49470,49471,49472,49473,49474,49475,49476,49477,49478,49479,49480,49481,49482,49483,49484,49485,49486,49487,49488,49489,49490,49491,49492,49493,49494,49495,49496,49497,49498,49499,49500,49501,49502,49503,49504,49505,49506,49507,49508,49509,49510,49511,49512,49513,49514,49515,49516,49517,49518,49519,49520,49521,49522,49523,49524,49525,49526,49527,49528,49529,49530,49531,49532,49533,49534,49535,49536,49537,49538,49539,49540,49541,49542,49543,49544,49545,49546,49547,49548,49549,49550,49551,49552,49553,49554,49555,49556,49557,49558,49559,49560,49561,49562,49563,49564,49565,49566,49567,49568,49569,49570,49571,49572,49573,49574,49575,49576,49577,49578,49579,49580,49581,49582,49583,49584,49585,49586,49587,49588,49589,49590,49591,49592,49593,49594,49595,49596,49597,49598,49599,49600,49601,49602,49603,49604,49605,49606,49607,49608,49609,49610,49611,49612,49613,49614,49615,49616,49617,49618,49619,49620,49621,49622,49623,49624,49625,49626,49627,49628,49629,49630,49631,49632,49633,49634,49635,49636,49637,49638,49639,49640,49641,49642,49643,49644,49645,49646,49647,49648,49649,49650,49651,49652,49653,49654,49655,49656,49657,49658,49659,49660,49661,49662,49663,49664,49665,49666,49667,49668,49669,49670,49671,49672,49673,49674,49675,49676,49677,49678,49679,49680,49681,49682,49683,49684,49685,49686,49687,49688,49689,49690,49691,49692,49693,49694,49695,49696,49697,49698,49699,49700,49701,49702,49703,49704,49705,49706,49707,49708,49709,49710,49711,49712,49713,49714,49715,49716,49717,49718,49719,49720,49721,49722,49723,49724,49725,49726,49727,49728,49729,49730,49731,49732,49733,49734,49735,49736,49737,49738,49739,49740,49741,49742,49743,49744,49745,49746,49747,49748,49749,49750,49751,49752,49753,49754,49755,49756,49757,49758,49759,49760,49761,49762,49763,49764,49765,49766,49767,49768,49769,49770,49771,49772,49773,49774,49775,49776,49777,49778,49779,49780,49781,49782,49783,49784,49785,49786,49787,49788,49789,49790,49791,49792,49793,49794,49795,49796,49797,49798,49799,49800,49801,49802,49803,49804,49805,49806,49807,49808,49809,49810,49811,49812,49813,49814,49815,49816,49817,49818,49819,49820,49821,49822,49823,49824,49825,49826,49827,49828,49829,49830,49831,49832,49833,49834,49835,49836,49837,49838,49839,49840,49841,49842,49843,49844,49845,49846,49847,49848,49849,49850,49851,49852,49853,49854,49855,49856,49857,49858,49859,49860,49861,49862,49863,49864,49865,49866,49867,49868,49869,49870,49871,49872,49873,49874,49875,49876,49877,49878,49879,49880,49881,49882,49883,49884,49885,49886,49887,49888,49889,49890,49891,49892,49893,49894,49895,49896,49897,49898,49899,49900,49901,49902,49903,49904,49905,49906,49907,49908,49909,49910,49911,49912,49913,49914,49915,49916,49917,49918,49919,49920,49921,49922,49923,49924,49925,49926,49927,49928,49929,49930,49931,49932,49933,49934,49935,49936,49937,49938,49939,49940,49941,49942,49943,49944,49945,49946,49947,49948,49949,49950,49951,49952,49953,49954,49955,49956,49957,49958,49959,49960,49961,49962,49963,49964,49965,49966,49967,49968,49969,49970,49971,49972,49973,49974,49975,49976,49977,49978,49979,49980,49981,49982,49983,49984,49985,49986,49987,49988,49989,49990,49991,49992,49993,49994,49995,49996,49997,49998,49999,50000,50001,50002,50003,50004,50005,50006,50007,50008,50009,50010,50011,50012,50013,50014,50015,50016,50017,50018,50019,50020,50021,50022,50023,50024,50025,50026,50027,50028,50029,50030,50031,50032,50033,50034,50035,50036,50037,50038,50039,50040,50041,50042,50043,50044,50045,50046,50047,50048,50049,50050,50051,50052,50053,50054,50055,50056,50057,50058,50059,50060,50061,50062,50063,50064,50065,50066,50067,50068,50069,50070,50071,50072,50073,50074,50075,50076,50077,50078,50079,50080,50081,50082,50083,50084,50085,50086,50087,50088,50089,50090,50091,50092,50093,50094,50095,50096,50097,50098,50099,50100,50101,50102,50103,50104,50105,50106,50107,50108,50109,50110,50111,50112,50113,50114,50115,50116,50117,50118,50119,50120,50121,50122,50123,50124,50125,50126,50127,50128,50129,50130,50131,50132,50133,50134,50135,50136,50137,50138,50139,50140,50141,50142,50143,50144,50145,50146,50147,50148,50149,50150,50151,50152,50153,50154,50155,50156,50157,50158,50159,50160,50161,50162,50163,50164,50165,50166,50167,50168,50169,50170,50171,50172,50173,50174,50175,50176,50177,50178,50179,50180,50181,50182,50183,50184,50185,50186,50187,50188,50189,50190,50191,50192,50193,50194,50195,50196,50197,50198,50199,50200,50201,50202,50203,50204,50205,50206,50207,50208,50209,50210,50211,50212,50213,50214,50215,50216,50217,50218,50219,50220,50221,50222,50223,50224,50225,50226,50227,50228,50229,50230,50231,50232,50233,50234,50235,50236,50237,50238,50239,50240,50241,50242,50243,50244,50245,50246,50247,50248,50249,50250,50251,50252,50253,50254,50255,50256,50257,50258,50259,50260,50261,50262,50263,50264,50265,50266,50267,50268,50269,50270,50271,50272,50273,50274,50275,50276,50277,50278,50279,50280,50281,50282,50283,50284,50285,50286,50287,50288,50289,50290,50291,50292,50293,50294,50295,50296,50297,50298,50299,50300,50301,50302,50303,50304,50305,50306,50307,50308,50309,50310,50311,50312,50313,50314,50315,50316,50317,50318,50319,50320,50321,50322,50323,50324,50325,50326,50327,50328,50329,50330,50331,50332,50333,50334,50335,50336,50337,50338,50339,50340,50341,50342,50343,50344,50345,50346,50347,50348,50349,50350,50351,50352,50353,50354,50355,50356,50357,50358,50359,50360,50361,50362,50363,50364,50365,50366,50367,50368,50369,50370,50371,50372,50373,50374,50375,50376,50377,50378,50379,50380,50381,50382,50383,50384,50385,50386,50387,50388,50389,50390,50391,50392,50393,50394,50395,50396,50397,50398,50399,50400,50401,50402,50403,50404,50405,50406,50407,50408,50409,50410,50411,50412,50413,50414,50415,50416,50417,50418,50419,50420,50421,50422,50423,50424,50425,50426,50427,50428,50429,50430,50431,50432,50433,50434,50435,50436,50437,50438,50439,50440,50441,50442,50443,50444,50445,50446,50447,50448,50449,50450,50451,50452,50453,50454,50455,50456,50457,50458,50459,50460,50461,50462,50463,50464,50465,50466,50467,50468,50469,50470,50471,50472,50473,50474,50475,50476,50477,50478,50479,50480,50481,50482,50483,50484,50485,50486,50487,50488,50489,50490,50491,50492,50493,50494,50495,50496,50497,50498,50499,50500,50501,50502,50503,50504,50505,50506,50507,50508,50509,50510,50511,50512,50513,50514,50515,50516,50517,50518,50519,50520,50521,50522,50523,50524,50525,50526,50527,50528,50529,50530,50531,50532,50533,50534,50535,50536,50537,50538,50539,50540,50541,50542,50543,50544,50545,50546,50547,50548,50549,50550,50551,50552,50553,50554,50555,50556,50557,50558,50559,50560,50561,50562,50563,50564,50565,50566,50567,50568,50569,50570,50571,50572,50573,50574,50575,50576,50577,50578,50579,50580,50581,50582,50583,50584,50585,50586,50587,50588,50589,50590,50591,50592,50593,50594,50595,50596,50597,50598,50599,50600,50601,50602,50603,50604,50605,50606,50607,50608,50609,50610,50611,50612,50613,50614,50615,50616,50617,50618,50619,50620,50621,50622,50623,50624,50625,50626,50627,50628,50629,50630,50631,50632,50633,50634,50635,50636,50637,50638,50639,50640,50641,50642,50643,50644,50645,50646,50647,50648,50649,50650,50651,50652,50653,50654,50655,50656,50657,50658,50659,50660,50661,50662,50663,50664,50665,50666,50667,50668,50669,50670,50671,50672,50673,50674,50675,50676,50677,50678,50679,50680,50681,50682,50683,50684,50685,50686,50687,50688,50689,50690,50691,50692,50693,50694,50695,50696,50697,50698,50699,50700,50701,50702,50703,50704,50705,50706,50707,50708,50709,50710,50711,50712,50713,50714,50715,50716,50717,50718,50719,50720,50721,50722,50723,50724,50725,50726,50727,50728,50729,50730,50731,50732,50733,50734,50735,50736,50737,50738,50739,50740,50741,50742,50743,50744,50745,50746,50747,50748,50749,50750,50751,50752,50753,50754,50755,50756,50757,50758,50759,50760,50761,50762,50763,50764,50765,50766,50767,50768,50769,50770,50771,50772,50773,50774,50775,50776,50777,50778,50779,50780,50781,50782,50783,50784,50785,50786,50787,50788,50789,50790,50791,50792,50793,50794,50795,50796,50797,50798,50799,50800,50801,50802,50803,50804,50805,50806,50807,50808,50809,50810,50811,50812,50813,50814,50815,50816,50817,50818,50819,50820,50821,50822,50823,50824,50825,50826,50827,50828,50829,50830,50831,50832,50833,50834,50835,50836,50837,50838,50839,50840,50841,50842,50843,50844,50845,50846,50847,50848,50849,50850,50851,50852,50853,50854,50855,50856,50857,50858,50859,50860,50861,50862,50863,50864,50865,50866,50867,50868,50869,50870,50871,50872,50873,50874,50875,50876,50877,50878,50879,50880,50881,50882,50883,50884,50885,50886,50887,50888,50889,50890,50891,50892,50893,50894,50895,50896,50897,50898,50899,50900,50901,50902,50903,50904,50905,50906,50907,50908,50909,50910,50911,50912,50913,50914,50915,50916,50917,50918,50919,50920,50921,50922,50923,50924,50925,50926,50927,50928,50929,50930,50931,50932,50933,50934,50935,50936,50937,50938,50939,50940,50941,50942,50943,50944,50945,50946,50947,50948,50949,50950,50951,50952,50953,50954,50955,50956,50957,50958,50959,50960,50961,50962,50963,50964,50965,50966,50967,50968,50969,50970,50971,50972,50973,50974,50975,50976,50977,50978,50979,50980,50981,50982,50983,50984,50985,50986,50987,50988,50989,50990,50991,50992,50993,50994,50995,50996,50997,50998,50999,51000,51001,51002,51003,51004,51005,51006,51007,51008,51009,51010,51011,51012,51013,51014,51015,51016,51017,51018,51019,51020,51021,51022,51023,51024,51025,51026,51027,51028,51029,51030,51031,51032,51033,51034,51035,51036,51037,51038,51039,51040,51041,51042,51043,51044,51045,51046,51047,51048,51049,51050,51051,51052,51053,51054,51055,51056,51057,51058,51059,51060,51061,51062,51063,51064,51065,51066,51067,51068,51069,51070,51071,51072,51073,51074,51075,51076,51077,51078,51079,51080,51081,51082,51083,51084,51085,51086,51087,51088,51089,51090,51091,51092,51093,51094,51095,51096,51097,51098,51099,51100,51101,51102,51103,51104,51105,51106,51107,51108,51109,51110,51111,51112,51113,51114,51115,51116,51117,51118,51119,51120,51121,51122,51123,51124,51125,51126,51127,51128,51129,51130,51131,51132,51133,51134,51135,51136,51137,51138,51139,51140,51141,51142,51143,51144,51145,51146,51147,51148,51149,51150,51151,51152,51153,51154,51155,51156,51157,51158,51159,51160,51161,51162,51163,51164,51165,51166,51167,51168,51169,51170,51171,51172,51173,51174,51175,51176,51177,51178,51179,51180,51181,51182,51183,51184,51185,51186,51187,51188,51189,51190,51191,51192,51193,51194,51195,51196,51197,51198,51199,51200,51201,51202,51203,51204,51205,51206,51207,51208,51209,51210,51211,51212,51213,51214,51215,51216,51217,51218,51219,51220,51221,51222,51223,51224,51225,51226,51227,51228,51229,51230,51231,51232,51233,51234,51235,51236,51237,51238,51239,51240,51241,51242,51243,51244,51245,51246,51247,51248,51249,51250,51251,51252,51253,51254,51255,51256,51257,51258,51259,51260,51261,51262,51263,51264,51265,51266,51267,51268,51269,51270,51271,51272,51273,51274,51275,51276,51277,51278,51279,51280,51281,51282,51283,51284,51285,51286,51287,51288,51289,51290,51291,51292,51293,51294,51295,51296,51297,51298,51299,51300,51301,51302,51303,51304,51305,51306,51307,51308,51309,51310,51311,51312,51313,51314,51315,51316,51317,51318,51319,51320,51321,51322,51323,51324,51325,51326,51327,51328,51329,51330,51331,51332,51333,51334,51335,51336,51337,51338,51339,51340,51341,51342,51343,51344,51345,51346,51347,51348,51349,51350,51351,51352,51353,51354,51355,51356,51357,51358,51359,51360,51361,51362,51363,51364,51365,51366,51367,51368,51369,51370,51371,51372,51373,51374,51375,51376,51377,51378,51379,51380,51381,51382,51383,51384,51385,51386,51387,51388,51389,51390,51391,51392,51393,51394,51395,51396,51397,51398,51399,51400,51401,51402,51403,51404,51405,51406,51407,51408,51409,51410,51411,51412,51413,51414,51415,51416,51417,51418,51419,51420,51421,51422,51423,51424,51425,51426,51427,51428,51429,51430,51431,51432,51433,51434,51435,51436,51437,51438,51439,51440,51441,51442,51443,51444,51445,51446,51447,51448,51449,51450,51451,51452,51453,51454,51455,51456,51457,51458,51459,51460,51461,51462,51463,51464,51465,51466,51467,51468,51469,51470,51471,51472,51473,51474,51475,51476,51477,51478,51479,51480,51481,51482,51483,51484,51485,51486,51487,51488,51489,51490,51491,51492,51493,51494,51495,51496,51497,51498,51499,51500,51501,51502,51503,51504,51505,51506,51507,51508,51509,51510,51511,51512,51513,51514,51515,51516,51517,51518,51519,51520,51521,51522,51523,51524,51525,51526,51527,51528,51529,51530,51531,51532,51533,51534,51535,51536,51537,51538,51539,51540,51541,51542,51543,51544,51545,51546,51547,51548,51549,51550,51551,51552,51553,51554,51555,51556,51557,51558,51559,51560,51561,51562,51563,51564,51565,51566,51567,51568,51569,51570,51571,51572,51573,51574,51575,51576,51577,51578,51579,51580,51581,51582,51583,51584,51585,51586,51587,51588,51589,51590,51591,51592,51593,51594,51595,51596,51597,51598,51599,51600,51601,51602,51603,51604,51605,51606,51607,51608,51609,51610,51611,51612,51613,51614,51615,51616,51617,51618,51619,51620,51621,51622,51623,51624,51625,51626,51627,51628,51629,51630,51631,51632,51633,51634,51635,51636,51637,51638,51639,51640,51641,51642,51643,51644,51645,51646,51647,51648,51649,51650,51651,51652,51653,51654,51655,51656,51657,51658,51659,51660,51661,51662,51663,51664,51665,51666,51667,51668,51669,51670,51671,51672,51673,51674,51675,51676,51677,51678,51679,51680,51681,51682,51683,51684,51685,51686,51687,51688,51689,51690,51691,51692,51693,51694,51695,51696,51697,51698,51699,51700,51701,51702,51703,51704,51705,51706,51707,51708,51709,51710,51711,51712,51713,51714,51715,51716,51717,51718,51719,51720,51721,51722,51723,51724,51725,51726,51727,51728,51729,51730,51731,51732,51733,51734,51735,51736,51737,51738,51739,51740,51741,51742,51743,51744,51745,51746,51747,51748,51749,51750,51751,51752,51753,51754,51755,51756,51757,51758,51759,51760,51761,51762,51763,51764,51765,51766,51767,51768,51769,51770,51771,51772,51773,51774,51775,51776,51777,51778,51779,51780,51781,51782,51783,51784,51785,51786,51787,51788,51789,51790,51791,51792,51793,51794,51795,51796,51797,51798,51799,51800,51801,51802,51803,51804,51805,51806,51807,51808,51809,51810,51811,51812,51813,51814,51815,51816,51817,51818,51819,51820,51821,51822,51823,51824,51825,51826,51827,51828,51829,51830,51831,51832,51833,51834,51835,51836,51837,51838,51839,51840,51841,51842,51843,51844,51845,51846,51847,51848,51849,51850,51851,51852,51853,51854,51855,51856,51857,51858,51859,51860,51861,51862,51863,51864,51865,51866,51867,51868,51869,51870,51871,51872,51873,51874,51875,51876,51877,51878,51879,51880,51881,51882,51883,51884,51885,51886,51887,51888,51889,51890,51891,51892,51893,51894,51895,51896,51897,51898,51899,51900,51901,51902,51903,51904,51905,51906,51907,51908,51909,51910,51911,51912,51913,51914,51915,51916,51917,51918,51919,51920,51921,51922,51923,51924,51925,51926,51927,51928,51929,51930,51931,51932,51933,51934,51935,51936,51937,51938,51939,51940,51941,51942,51943,51944,51945,51946,51947,51948,51949,51950,51951,51952,51953,51954,51955,51956,51957,51958,51959,51960,51961,51962,51963,51964,51965,51966,51967,51968,51969,51970,51971,51972,51973,51974,51975,51976,51977,51978,51979,51980,51981,51982,51983,51984,51985,51986,51987,51988,51989,51990,51991,51992,51993,51994,51995,51996,51997,51998,51999,52000,52001,52002,52003,52004,52005,52006,52007,52008,52009,52010,52011,52012,52013,52014,52015,52016,52017,52018,52019,52020,52021,52022,52023,52024,52025,52026,52027,52028,52029,52030,52031,52032,52033,52034,52035,52036,52037,52038,52039,52040,52041,52042,52043,52044,52045,52046,52047,52048,52049,52050,52051,52052,52053,52054,52055,52056,52057,52058,52059,52060,52061,52062,52063,52064,52065,52066,52067,52068,52069,52070,52071,52072,52073,52074,52075,52076,52077,52078,52079,52080,52081,52082,52083,52084,52085,52086,52087,52088,52089,52090,52091,52092,52093,52094,52095,52096,52097,52098,52099,52100,52101,52102,52103,52104,52105,52106,52107,52108,52109,52110,52111,52112,52113,52114,52115,52116,52117,52118,52119,52120,52121,52122,52123,52124,52125,52126,52127,52128,52129,52130,52131,52132,52133,52134,52135,52136,52137,52138,52139,52140,52141,52142,52143,52144,52145,52146,52147,52148,52149,52150,52151,52152,52153,52154,52155,52156,52157,52158,52159,52160,52161,52162,52163,52164,52165,52166,52167,52168,52169,52170,52171,52172,52173,52174,52175,52176,52177,52178,52179,52180,52181,52182,52183,52184,52185,52186,52187,52188,52189,52190,52191,52192,52193,52194,52195,52196,52197,52198,52199,52200,52201,52202,52203,52204,52205,52206,52207,52208,52209,52210,52211,52212,52213,52214,52215,52216,52217,52218,52219,52220,52221,52222,52223,52224,52225,52226,52227,52228,52229,52230,52231,52232,52233,52234,52235,52236,52237,52238,52239,52240,52241,52242,52243,52244,52245,52246,52247,52248,52249,52250,52251,52252,52253,52254,52255,52256,52257,52258,52259,52260,52261,52262,52263,52264,52265,52266,52267,52268,52269,52270,52271,52272,52273,52274,52275,52276,52277,52278,52279,52280,52281,52282,52283,52284,52285,52286,52287,52288,52289,52290,52291,52292,52293,52294,52295,52296,52297,52298,52299,52300,52301,52302,52303,52304,52305,52306,52307,52308,52309,52310,52311,52312,52313,52314,52315,52316,52317,52318,52319,52320,52321,52322,52323,52324,52325,52326,52327,52328,52329,52330,52331,52332,52333,52334,52335,52336,52337,52338,52339,52340,52341,52342,52343,52344,52345,52346,52347,52348,52349,52350,52351,52352,52353,52354,52355,52356,52357,52358,52359,52360,52361,52362,52363,52364,52365,52366,52367,52368,52369,52370,52371,52372,52373,52374,52375,52376,52377,52378,52379,52380,52381,52382,52383,52384,52385,52386,52387,52388,52389,52390,52391,52392,52393,52394,52395,52396,52397,52398,52399,52400,52401,52402,52403,52404,52405,52406,52407,52408,52409,52410,52411,52412,52413,52414,52415,52416,52417,52418,52419,52420,52421,52422,52423,52424,52425,52426,52427,52428,52429,52430,52431,52432,52433,52434,52435,52436,52437,52438,52439,52440,52441,52442,52443,52444,52445,52446,52447,52448,52449,52450,52451,52452,52453,52454,52455,52456,52457,52458,52459,52460,52461,52462,52463,52464,52465,52466,52467,52468,52469,52470,52471,52472,52473,52474,52475,52476,52477,52478,52479,52480,52481,52482,52483,52484,52485,52486,52487,52488,52489,52490,52491,52492,52493,52494,52495,52496,52497,52498,52499,52500,52501,52502,52503,52504,52505,52506,52507,52508,52509,52510,52511,52512,52513,52514,52515,52516,52517,52518,52519,52520,52521,52522,52523,52524,52525,52526,52527,52528,52529,52530,52531,52532,52533,52534,52535,52536,52537,52538,52539,52540,52541,52542,52543,52544,52545,52546,52547,52548,52549,52550,52551,52552,52553,52554,52555,52556,52557,52558,52559,52560,52561,52562,52563,52564,52565,52566,52567,52568,52569,52570,52571,52572,52573,52574,52575,52576,52577,52578,52579,52580,52581,52582,52583,52584,52585,52586,52587,52588,52589,52590,52591,52592,52593,52594,52595,52596,52597,52598,52599,52600,52601,52602,52603,52604,52605,52606,52607,52608,52609,52610,52611,52612,52613,52614,52615,52616,52617,52618,52619,52620,52621,52622,52623,52624,52625,52626,52627,52628,52629,52630,52631,52632,52633,52634,52635,52636,52637,52638,52639,52640,52641,52642,52643,52644,52645,52646,52647,52648,52649,52650,52651,52652,52653,52654,52655,52656,52657,52658,52659,52660,52661,52662,52663,52664,52665,52666,52667,52668,52669,52670,52671,52672,52673,52674,52675,52676,52677,52678,52679,52680,52681,52682,52683,52684,52685,52686,52687,52688,52689,52690,52691,52692,52693,52694,52695,52696,52697,52698,52699,52700,52701,52702,52703,52704,52705,52706,52707,52708,52709,52710,52711,52712,52713,52714,52715,52716,52717,52718,52719,52720,52721,52722,52723,52724,52725,52726,52727,52728,52729,52730,52731,52732,52733,52734,52735,52736,52737,52738,52739,52740,52741,52742,52743,52744,52745,52746,52747,52748,52749,52750,52751,52752,52753,52754,52755,52756,52757,52758,52759,52760,52761,52762,52763,52764,52765,52766,52767,52768,52769,52770,52771,52772,52773,52774,52775,52776,52777,52778,52779,52780,52781,52782,52783,52784,52785,52786,52787,52788,52789,52790,52791,52792,52793,52794,52795,52796,52797,52798,52799,52800,52801,52802,52803,52804,52805,52806,52807,52808,52809,52810,52811,52812,52813,52814,52815,52816,52817,52818,52819,52820,52821,52822,52823,52824,52825,52826,52827,52828,52829,52830,52831,52832,52833,52834,52835,52836,52837,52838,52839,52840,52841,52842,52843,52844,52845,52846,52847,52848,52849,52850,52851,52852,52853,52854,52855,52856,52857,52858,52859,52860,52861,52862,52863,52864,52865,52866,52867,52868,52869,52870,52871,52872,52873,52874,52875,52876,52877,52878,52879,52880,52881,52882,52883,52884,52885,52886,52887,52888,52889,52890,52891,52892,52893,52894,52895,52896,52897,52898,52899,52900,52901,52902,52903,52904,52905,52906,52907,52908,52909,52910,52911,52912,52913,52914,52915,52916,52917,52918,52919,52920,52921,52922,52923,52924,52925,52926,52927,52928,52929,52930,52931,52932,52933,52934,52935,52936,52937,52938,52939,52940,52941,52942,52943,52944,52945,52946,52947,52948,52949,52950,52951,52952,52953,52954,52955,52956,52957,52958,52959,52960,52961,52962,52963,52964,52965,52966,52967,52968,52969,52970,52971,52972,52973,52974,52975,52976,52977,52978,52979,52980,52981,52982,52983,52984,52985,52986,52987,52988,52989,52990,52991,52992,52993,52994,52995,52996,52997,52998,52999,53000,53001,53002,53003,53004,53005,53006,53007,53008,53009,53010,53011,53012,53013,53014,53015,53016,53017,53018,53019,53020,53021,53022,53023,53024,53025,53026,53027,53028,53029,53030,53031,53032,53033,53034,53035,53036,53037,53038,53039,53040,53041,53042,53043,53044,53045,53046,53047,53048,53049,53050,53051,53052,53053,53054,53055,53056,53057,53058,53059,53060,53061,53062,53063,53064,53065,53066,53067,53068,53069,53070,53071,53072,53073,53074,53075,53076,53077,53078,53079,53080,53081,53082,53083,53084,53085,53086,53087,53088,53089,53090,53091,53092,53093,53094,53095,53096,53097,53098,53099,53100,53101,53102,53103,53104,53105,53106,53107,53108,53109,53110,53111,53112,53113,53114,53115,53116,53117,53118,53119,53120,53121,53122,53123,53124,53125,53126,53127,53128,53129,53130,53131,53132,53133,53134,53135,53136,53137,53138,53139,53140,53141,53142,53143,53144,53145,53146,53147,53148,53149,53150,53151,53152,53153,53154,53155,53156,53157,53158,53159,53160,53161,53162,53163,53164,53165,53166,53167,53168,53169,53170,53171,53172,53173,53174,53175,53176,53177,53178,53179,53180,53181,53182,53183,53184,53185,53186,53187,53188,53189,53190,53191,53192,53193,53194,53195,53196,53197,53198,53199,53200,53201,53202,53203,53204,53205,53206,53207,53208,53209,53210,53211,53212,53213,53214,53215,53216,53217,53218,53219,53220,53221,53222,53223,53224,53225,53226,53227,53228,53229,53230,53231,53232,53233,53234,53235,53236,53237,53238,53239,53240,53241,53242,53243,53244,53245,53246,53247,53248,53249,53250,53251,53252,53253,53254,53255,53256,53257,53258,53259,53260,53261,53262,53263,53264,53265,53266,53267,53268,53269,53270,53271,53272,53273,53274,53275,53276,53277,53278,53279,53280,53281,53282,53283,53284,53285,53286,53287,53288,53289,53290,53291,53292,53293,53294,53295,53296,53297,53298,53299,53300,53301,53302,53303,53304,53305,53306,53307,53308,53309,53310,53311,53312,53313,53314,53315,53316,53317,53318,53319,53320,53321,53322,53323,53324,53325,53326,53327,53328,53329,53330,53331,53332,53333,53334,53335,53336,53337,53338,53339,53340,53341,53342,53343,53344,53345,53346,53347,53348,53349,53350,53351,53352,53353,53354,53355,53356,53357,53358,53359,53360,53361,53362,53363,53364,53365,53366,53367,53368,53369,53370,53371,53372,53373,53374,53375,53376,53377,53378,53379,53380,53381,53382,53383,53384,53385,53386,53387,53388,53389,53390,53391,53392,53393,53394,53395,53396,53397,53398,53399,53400,53401,53402,53403,53404,53405,53406,53407,53408,53409,53410,53411,53412,53413,53414,53415,53416,53417,53418,53419,53420,53421,53422,53423,53424,53425,53426,53427,53428,53429,53430,53431,53432,53433,53434,53435,53436,53437,53438,53439,53440,53441,53442,53443,53444,53445,53446,53447,53448,53449,53450,53451,53452,53453,53454,53455,53456,53457,53458,53459,53460,53461,53462,53463,53464,53465,53466,53467,53468,53469,53470,53471,53472,53473,53474,53475,53476,53477,53478,53479,53480,53481,53482,53483,53484,53485,53486,53487,53488,53489,53490,53491,53492,53493,53494,53495,53496,53497,53498,53499,53500,53501,53502,53503,53504,53505,53506,53507,53508,53509,53510,53511,53512,53513,53514,53515,53516,53517,53518,53519,53520,53521,53522,53523,53524,53525,53526,53527,53528,53529,53530,53531,53532,53533,53534,53535,53536,53537,53538,53539,53540,53541,53542,53543,53544,53545,53546,53547,53548,53549,53550,53551,53552,53553,53554,53555,53556,53557,53558,53559,53560,53561,53562,53563,53564,53565,53566,53567,53568,53569,53570,53571,53572,53573,53574,53575,53576,53577,53578,53579,53580,53581,53582,53583,53584,53585,53586,53587,53588,53589,53590,53591,53592,53593,53594,53595,53596,53597,53598,53599,53600,53601,53602,53603,53604,53605,53606,53607,53608,53609,53610,53611,53612,53613,53614,53615,53616,53617,53618,53619,53620,53621,53622,53623,53624,53625,53626,53627,53628,53629,53630,53631,53632,53633,53634,53635,53636,53637,53638,53639,53640,53641,53642,53643,53644,53645,53646,53647,53648,53649,53650,53651,53652,53653,53654,53655,53656,53657,53658,53659,53660,53661,53662,53663,53664,53665,53666,53667,53668,53669,53670,53671,53672,53673,53674,53675,53676,53677,53678,53679,53680,53681,53682,53683,53684,53685,53686,53687,53688,53689,53690,53691,53692,53693,53694,53695,53696,53697,53698,53699,53700,53701,53702,53703,53704,53705,53706,53707,53708,53709,53710,53711,53712,53713,53714,53715,53716,53717,53718,53719,53720,53721,53722,53723,53724,53725,53726,53727,53728,53729,53730,53731,53732,53733,53734,53735,53736,53737,53738,53739,53740,53741,53742,53743,53744,53745,53746,53747,53748,53749,53750,53751,53752,53753,53754,53755,53756,53757,53758,53759,53760,53761,53762,53763,53764,53765,53766,53767,53768,53769,53770,53771,53772,53773,53774,53775,53776,53777,53778,53779,53780,53781,53782,53783,53784,53785,53786,53787,53788,53789,53790,53791,53792,53793,53794,53795,53796,53797,53798,53799,53800,53801,53802,53803,53804,53805,53806,53807,53808,53809,53810,53811,53812,53813,53814,53815,53816,53817,53818,53819,53820,53821,53822,53823,53824,53825,53826,53827,53828,53829,53830,53831,53832,53833,53834,53835,53836,53837,53838,53839,53840,53841,53842,53843,53844,53845,53846,53847,53848,53849,53850,53851,53852,53853,53854,53855,53856,53857,53858,53859,53860,53861,53862,53863,53864,53865,53866,53867,53868,53869,53870,53871,53872,53873,53874,53875,53876,53877,53878,53879,53880,53881,53882,53883,53884,53885,53886,53887,53888,53889,53890,53891,53892,53893,53894,53895,53896,53897,53898,53899,53900,53901,53902,53903,53904,53905,53906,53907,53908,53909,53910,53911,53912,53913,53914,53915,53916,53917,53918,53919,53920,53921,53922,53923,53924,53925,53926,53927,53928,53929,53930,53931,53932,53933,53934,53935,53936,53937,53938,53939,53940,53941,53942,53943,53944,53945,53946,53947,53948,53949,53950,53951,53952,53953,53954,53955,53956,53957,53958,53959,53960,53961,53962,53963,53964,53965,53966,53967,53968,53969,53970,53971,53972,53973,53974,53975,53976,53977,53978,53979,53980,53981,53982,53983,53984,53985,53986,53987,53988,53989,53990,53991,53992,53993,53994,53995,53996,53997,53998,53999,54000,54001,54002,54003,54004,54005,54006,54007,54008,54009,54010,54011,54012,54013,54014,54015,54016,54017,54018,54019,54020,54021,54022,54023,54024,54025,54026,54027,54028,54029,54030,54031,54032,54033,54034,54035,54036,54037,54038,54039,54040,54041,54042,54043,54044,54045,54046,54047,54048,54049,54050,54051,54052,54053,54054,54055,54056,54057,54058,54059,54060,54061,54062,54063,54064,54065,54066,54067,54068,54069,54070,54071,54072,54073,54074,54075,54076,54077,54078,54079,54080,54081,54082,54083,54084,54085,54086,54087,54088,54089,54090,54091,54092,54093,54094,54095,54096,54097,54098,54099,54100,54101,54102,54103,54104,54105,54106,54107,54108,54109,54110,54111,54112,54113,54114,54115,54116,54117,54118,54119,54120,54121,54122,54123,54124,54125,54126,54127,54128,54129,54130,54131,54132,54133,54134,54135,54136,54137,54138,54139,54140,54141,54142,54143,54144,54145,54146,54147,54148,54149,54150,54151,54152,54153,54154,54155,54156,54157,54158,54159,54160,54161,54162,54163,54164,54165,54166,54167,54168,54169,54170,54171,54172,54173,54174,54175,54176,54177,54178,54179,54180,54181,54182,54183,54184,54185,54186,54187,54188,54189,54190,54191,54192,54193,54194,54195,54196,54197,54198,54199,54200,54201,54202,54203,54204,54205,54206,54207,54208,54209,54210,54211,54212,54213,54214,54215,54216,54217,54218,54219,54220,54221,54222,54223,54224,54225,54226,54227,54228,54229,54230,54231,54232,54233,54234,54235,54236,54237,54238,54239,54240,54241,54242,54243,54244,54245,54246,54247,54248,54249,54250,54251,54252,54253,54254,54255,54256,54257,54258,54259,54260,54261,54262,54263,54264,54265,54266,54267,54268,54269,54270,54271,54272,54273,54274,54275,54276,54277,54278,54279,54280,54281,54282,54283,54284,54285,54286,54287,54288,54289,54290,54291,54292,54293,54294,54295,54296,54297,54298,54299,54300,54301,54302,54303,54304,54305,54306,54307,54308,54309,54310,54311,54312,54313,54314,54315,54316,54317,54318,54319,54320,54321,54322,54323,54324,54325,54326,54327,54328,54329,54330,54331,54332,54333,54334,54335,54336,54337,54338,54339,54340,54341,54342,54343,54344,54345,54346,54347,54348,54349,54350,54351,54352,54353,54354,54355,54356,54357,54358,54359,54360,54361,54362,54363,54364,54365,54366,54367,54368,54369,54370,54371,54372,54373,54374,54375,54376,54377,54378,54379,54380,54381,54382,54383,54384,54385,54386,54387,54388,54389,54390,54391,54392,54393,54394,54395,54396,54397,54398,54399,54400,54401,54402,54403,54404,54405,54406,54407,54408,54409,54410,54411,54412,54413,54414,54415,54416,54417,54418,54419,54420,54421,54422,54423,54424,54425,54426,54427,54428,54429,54430,54431,54432,54433,54434,54435,54436,54437,54438,54439,54440,54441,54442,54443,54444,54445,54446,54447,54448,54449,54450,54451,54452,54453,54454,54455,54456,54457,54458,54459,54460,54461,54462,54463,54464,54465,54466,54467,54468,54469,54470,54471,54472,54473,54474,54475,54476,54477,54478,54479,54480,54481,54482,54483,54484,54485,54486,54487,54488,54489,54490,54491,54492,54493,54494,54495,54496,54497,54498,54499,54500,54501,54502,54503,54504,54505,54506,54507,54508,54509,54510,54511,54512,54513,54514,54515,54516,54517,54518,54519,54520,54521,54522,54523,54524,54525,54526,54527,54528,54529,54530,54531,54532,54533,54534,54535,54536,54537,54538,54539,54540,54541,54542,54543,54544,54545,54546,54547,54548,54549,54550,54551,54552,54553,54554,54555,54556,54557,54558,54559,54560,54561,54562,54563,54564,54565,54566,54567,54568,54569,54570,54571,54572,54573,54574,54575,54576,54577,54578,54579,54580,54581,54582,54583,54584,54585,54586,54587,54588,54589,54590,54591,54592,54593,54594,54595,54596,54597,54598,54599,54600,54601,54602,54603,54604,54605,54606,54607,54608,54609,54610,54611,54612,54613,54614,54615,54616,54617,54618,54619,54620,54621,54622,54623,54624,54625,54626,54627,54628,54629,54630,54631,54632,54633,54634,54635,54636,54637,54638,54639,54640,54641,54642,54643,54644,54645,54646,54647,54648,54649,54650,54651,54652,54653,54654,54655,54656,54657,54658,54659,54660,54661,54662,54663,54664,54665,54666,54667,54668,54669,54670,54671,54672,54673,54674,54675,54676,54677,54678,54679,54680,54681,54682,54683,54684,54685,54686,54687,54688,54689,54690,54691,54692,54693,54694,54695,54696,54697,54698,54699,54700,54701,54702,54703,54704,54705,54706,54707,54708,54709,54710,54711,54712,54713,54714,54715,54716,54717,54718,54719,54720,54721,54722,54723,54724,54725,54726,54727,54728,54729,54730,54731,54732,54733,54734,54735,54736,54737,54738,54739,54740,54741,54742,54743,54744,54745,54746,54747,54748,54749,54750,54751,54752,54753,54754,54755,54756,54757,54758,54759,54760,54761,54762,54763,54764,54765,54766,54767,54768,54769,54770,54771,54772,54773,54774,54775,54776,54777,54778,54779,54780,54781,54782,54783,54784,54785,54786,54787,54788,54789,54790,54791,54792,54793,54794,54795,54796,54797,54798,54799,54800,54801,54802,54803,54804,54805,54806,54807,54808,54809,54810,54811,54812,54813,54814,54815,54816,54817,54818,54819,54820,54821,54822,54823,54824,54825,54826,54827,54828,54829,54830,54831,54832,54833,54834,54835,54836,54837,54838,54839,54840,54841,54842,54843,54844,54845,54846,54847,54848,54849,54850,54851,54852,54853,54854,54855,54856,54857,54858,54859,54860,54861,54862,54863,54864,54865,54866,54867,54868,54869,54870,54871,54872,54873,54874,54875,54876,54877,54878,54879,54880,54881,54882,54883,54884,54885,54886,54887,54888,54889,54890,54891,54892,54893,54894,54895,54896,54897,54898,54899,54900,54901,54902,54903,54904,54905,54906,54907,54908,54909,54910,54911,54912,54913,54914,54915,54916,54917,54918,54919,54920,54921,54922,54923,54924,54925,54926,54927,54928,54929,54930,54931,54932,54933,54934,54935,54936,54937,54938,54939,54940,54941,54942,54943,54944,54945,54946,54947,54948,54949,54950,54951,54952,54953,54954,54955,54956,54957,54958,54959,54960,54961,54962,54963,54964,54965,54966,54967,54968,54969,54970,54971,54972,54973,54974,54975,54976,54977,54978,54979,54980,54981,54982,54983,54984,54985,54986,54987,54988,54989,54990,54991,54992,54993,54994,54995,54996,54997,54998,54999,55000,55001,55002,55003,55004,55005,55006,55007,55008,55009,55010,55011,55012,55013,55014,55015,55016,55017,55018,55019,55020,55021,55022,55023,55024,55025,55026,55027,55028,55029,55030,55031,55032,55033,55034,55035,55036,55037,55038,55039,55040,55041,55042,55043,55044,55045,55046,55047,55048,55049,55050,55051,55052,55053,55054,55055,55056,55057,55058,55059,55060,55061,55062,55063,55064,55065,55066,55067,55068,55069,55070,55071,55072,55073,55074,55075,55076,55077,55078,55079,55080,55081,55082,55083,55084,55085,55086,55087,55088,55089,55090,55091,55092,55093,55094,55095,55096,55097,55098,55099,55100,55101,55102,55103,55104,55105,55106,55107,55108,55109,55110,55111,55112,55113,55114,55115,55116,55117,55118,55119,55120,55121,55122,55123,55124,55125,55126,55127,55128,55129,55130,55131,55132,55133,55134,55135,55136,55137,55138,55139,55140,55141,55142,55143,55144,55145,55146,55147,55148,55149,55150,55151,55152,55153,55154,55155,55156,55157,55158,55159,55160,55161,55162,55163,55164,55165,55166,55167,55168,55169,55170,55171,55172,55173,55174,55175,55176,55177,55178,55179,55180,55181,55182,55183,55184,55185,55186,55187,55188,55189,55190,55191,55192,55193,55194,55195,55196,55197,55198,55199,55200,55201,55202,55203,55216,55217,55218,55219,55220,55221,55222,55223,55224,55225,55226,55227,55228,55229,55230,55231,55232,55233,55234,55235,55236,55237,55238,55243,55244,55245,55246,55247,55248,55249,55250,55251,55252,55253,55254,55255,55256,55257,55258,55259,55260,55261,55262,55263,55264,55265,55266,55267,55268,55269,55270,55271,55272,55273,55274,55275,55276,55277,55278,55279,55280,55281,55282,55283,55284,55285,55286,55287,55288,55289,55290,55291,63744,63745,63746,63747,63748,63749,63750,63751,63752,63753,63754,63755,63756,63757,63758,63759,63760,63761,63762,63763,63764,63765,63766,63767,63768,63769,63770,63771,63772,63773,63774,63775,63776,63777,63778,63779,63780,63781,63782,63783,63784,63785,63786,63787,63788,63789,63790,63791,63792,63793,63794,63795,63796,63797,63798,63799,63800,63801,63802,63803,63804,63805,63806,63807,63808,63809,63810,63811,63812,63813,63814,63815,63816,63817,63818,63819,63820,63821,63822,63823,63824,63825,63826,63827,63828,63829,63830,63831,63832,63833,63834,63835,63836,63837,63838,63839,63840,63841,63842,63843,63844,63845,63846,63847,63848,63849,63850,63851,63852,63853,63854,63855,63856,63857,63858,63859,63860,63861,63862,63863,63864,63865,63866,63867,63868,63869,63870,63871,63872,63873,63874,63875,63876,63877,63878,63879,63880,63881,63882,63883,63884,63885,63886,63887,63888,63889,63890,63891,63892,63893,63894,63895,63896,63897,63898,63899,63900,63901,63902,63903,63904,63905,63906,63907,63908,63909,63910,63911,63912,63913,63914,63915,63916,63917,63918,63919,63920,63921,63922,63923,63924,63925,63926,63927,63928,63929,63930,63931,63932,63933,63934,63935,63936,63937,63938,63939,63940,63941,63942,63943,63944,63945,63946,63947,63948,63949,63950,63951,63952,63953,63954,63955,63956,63957,63958,63959,63960,63961,63962,63963,63964,63965,63966,63967,63968,63969,63970,63971,63972,63973,63974,63975,63976,63977,63978,63979,63980,63981,63982,63983,63984,63985,63986,63987,63988,63989,63990,63991,63992,63993,63994,63995,63996,63997,63998,63999,64000,64001,64002,64003,64004,64005,64006,64007,64008,64009,64010,64011,64012,64013,64014,64015,64016,64017,64018,64019,64020,64021,64022,64023,64024,64025,64026,64027,64028,64029,64030,64031,64032,64033,64034,64035,64036,64037,64038,64039,64040,64041,64042,64043,64044,64045,64046,64047,64048,64049,64050,64051,64052,64053,64054,64055,64056,64057,64058,64059,64060,64061,64062,64063,64064,64065,64066,64067,64068,64069,64070,64071,64072,64073,64074,64075,64076,64077,64078,64079,64080,64081,64082,64083,64084,64085,64086,64087,64088,64089,64090,64091,64092,64093,64094,64095,64096,64097,64098,64099,64100,64101,64102,64103,64104,64105,64106,64107,64108,64109,64112,64113,64114,64115,64116,64117,64118,64119,64120,64121,64122,64123,64124,64125,64126,64127,64128,64129,64130,64131,64132,64133,64134,64135,64136,64137,64138,64139,64140,64141,64142,64143,64144,64145,64146,64147,64148,64149,64150,64151,64152,64153,64154,64155,64156,64157,64158,64159,64160,64161,64162,64163,64164,64165,64166,64167,64168,64169,64170,64171,64172,64173,64174,64175,64176,64177,64178,64179,64180,64181,64182,64183,64184,64185,64186,64187,64188,64189,64190,64191,64192,64193,64194,64195,64196,64197,64198,64199,64200,64201,64202,64203,64204,64205,64206,64207,64208,64209,64210,64211,64212,64213,64214,64215,64216,64217,64256,64257,64258,64259,64260,64261,64262,64275,64276,64277,64278,64279,64285,64287,64288,64289,64290,64291,64292,64293,64294,64295,64296,64298,64299,64300,64301,64302,64303,64304,64305,64306,64307,64308,64309,64310,64312,64313,64314,64315,64316,64318,64320,64321,64323,64324,64326,64327,64328,64329,64330,64331,64332,64333,64334,64335,64336,64337,64338,64339,64340,64341,64342,64343,64344,64345,64346,64347,64348,64349,64350,64351,64352,64353,64354,64355,64356,64357,64358,64359,64360,64361,64362,64363,64364,64365,64366,64367,64368,64369,64370,64371,64372,64373,64374,64375,64376,64377,64378,64379,64380,64381,64382,64383,64384,64385,64386,64387,64388,64389,64390,64391,64392,64393,64394,64395,64396,64397,64398,64399,64400,64401,64402,64403,64404,64405,64406,64407,64408,64409,64410,64411,64412,64413,64414,64415,64416,64417,64418,64419,64420,64421,64422,64423,64424,64425,64426,64427,64428,64429,64430,64431,64432,64433,64467,64468,64469,64470,64471,64472,64473,64474,64475,64476,64477,64478,64479,64480,64481,64482,64483,64484,64485,64486,64487,64488,64489,64490,64491,64492,64493,64494,64495,64496,64497,64498,64499,64500,64501,64502,64503,64504,64505,64506,64507,64508,64509,64510,64511,64512,64513,64514,64515,64516,64517,64518,64519,64520,64521,64522,64523,64524,64525,64526,64527,64528,64529,64530,64531,64532,64533,64534,64535,64536,64537,64538,64539,64540,64541,64542,64543,64544,64545,64546,64547,64548,64549,64550,64551,64552,64553,64554,64555,64556,64557,64558,64559,64560,64561,64562,64563,64564,64565,64566,64567,64568,64569,64570,64571,64572,64573,64574,64575,64576,64577,64578,64579,64580,64581,64582,64583,64584,64585,64586,64587,64588,64589,64590,64591,64592,64593,64594,64595,64596,64597,64598,64599,64600,64601,64602,64603,64604,64605,64606,64607,64608,64609,64610,64611,64612,64613,64614,64615,64616,64617,64618,64619,64620,64621,64622,64623,64624,64625,64626,64627,64628,64629,64630,64631,64632,64633,64634,64635,64636,64637,64638,64639,64640,64641,64642,64643,64644,64645,64646,64647,64648,64649,64650,64651,64652,64653,64654,64655,64656,64657,64658,64659,64660,64661,64662,64663,64664,64665,64666,64667,64668,64669,64670,64671,64672,64673,64674,64675,64676,64677,64678,64679,64680,64681,64682,64683,64684,64685,64686,64687,64688,64689,64690,64691,64692,64693,64694,64695,64696,64697,64698,64699,64700,64701,64702,64703,64704,64705,64706,64707,64708,64709,64710,64711,64712,64713,64714,64715,64716,64717,64718,64719,64720,64721,64722,64723,64724,64725,64726,64727,64728,64729,64730,64731,64732,64733,64734,64735,64736,64737,64738,64739,64740,64741,64742,64743,64744,64745,64746,64747,64748,64749,64750,64751,64752,64753,64754,64755,64756,64757,64758,64759,64760,64761,64762,64763,64764,64765,64766,64767,64768,64769,64770,64771,64772,64773,64774,64775,64776,64777,64778,64779,64780,64781,64782,64783,64784,64785,64786,64787,64788,64789,64790,64791,64792,64793,64794,64795,64796,64797,64798,64799,64800,64801,64802,64803,64804,64805,64806,64807,64808,64809,64810,64811,64812,64813,64814,64815,64816,64817,64818,64819,64820,64821,64822,64823,64824,64825,64826,64827,64828,64829,64848,64849,64850,64851,64852,64853,64854,64855,64856,64857,64858,64859,64860,64861,64862,64863,64864,64865,64866,64867,64868,64869,64870,64871,64872,64873,64874,64875,64876,64877,64878,64879,64880,64881,64882,64883,64884,64885,64886,64887,64888,64889,64890,64891,64892,64893,64894,64895,64896,64897,64898,64899,64900,64901,64902,64903,64904,64905,64906,64907,64908,64909,64910,64911,64914,64915,64916,64917,64918,64919,64920,64921,64922,64923,64924,64925,64926,64927,64928,64929,64930,64931,64932,64933,64934,64935,64936,64937,64938,64939,64940,64941,64942,64943,64944,64945,64946,64947,64948,64949,64950,64951,64952,64953,64954,64955,64956,64957,64958,64959,64960,64961,64962,64963,64964,64965,64966,64967,65008,65009,65010,65011,65012,65013,65014,65015,65016,65017,65018,65019,65136,65137,65138,65139,65140,65142,65143,65144,65145,65146,65147,65148,65149,65150,65151,65152,65153,65154,65155,65156,65157,65158,65159,65160,65161,65162,65163,65164,65165,65166,65167,65168,65169,65170,65171,65172,65173,65174,65175,65176,65177,65178,65179,65180,65181,65182,65183,65184,65185,65186,65187,65188,65189,65190,65191,65192,65193,65194,65195,65196,65197,65198,65199,65200,65201,65202,65203,65204,65205,65206,65207,65208,65209,65210,65211,65212,65213,65214,65215,65216,65217,65218,65219,65220,65221,65222,65223,65224,65225,65226,65227,65228,65229,65230,65231,65232,65233,65234,65235,65236,65237,65238,65239,65240,65241,65242,65243,65244,65245,65246,65247,65248,65249,65250,65251,65252,65253,65254,65255,65256,65257,65258,65259,65260,65261,65262,65263,65264,65265,65266,65267,65268,65269,65270,65271,65272,65273,65274,65275,65276,65313,65314,65315,65316,65317,65318,65319,65320,65321,65322,65323,65324,65325,65326,65327,65328,65329,65330,65331,65332,65333,65334,65335,65336,65337,65338,65345,65346,65347,65348,65349,65350,65351,65352,65353,65354,65355,65356,65357,65358,65359,65360,65361,65362,65363,65364,65365,65366,65367,65368,65369,65370,65382,65383,65384,65385,65386,65387,65388,65389,65390,65391,65392,65393,65394,65395,65396,65397,65398,65399,65400,65401,65402,65403,65404,65405,65406,65407,65408,65409,65410,65411,65412,65413,65414,65415,65416,65417,65418,65419,65420,65421,65422,65423,65424,65425,65426,65427,65428,65429,65430,65431,65432,65433,65434,65435,65436,65437,65438,65439,65440,65441,65442,65443,65444,65445,65446,65447,65448,65449,65450,65451,65452,65453,65454,65455,65456,65457,65458,65459,65460,65461,65462,65463,65464,65465,65466,65467,65468,65469,65470,65474,65475,65476,65477,65478,65479,65482,65483,65484,65485,65486,65487,65490,65491,65492,65493,65494,65495,65498,65499,65500'; var arr = str.split(',').map(function(code) { return parseInt(code, 10); }); module.exports = arr; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/jshint.js":[function(require,module,exports){ /*! * JSHint, by JSHint Community. * * This file (and this file only) is licensed under the same slightly modified * MIT license that JSLint is. It stops evil-doers everywhere: * * Copyright (c) 2002 Douglas Crockford (www.JSLint.com) * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * The Software shall be used for Good, not Evil. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jshint quotmark:double */ /*global console:true */ /*exported console */ var _ = require("lodash"); var events = require("events"); var vars = require("./vars.js"); var messages = require("./messages.js"); var Lexer = require("./lex.js").Lexer; var reg = require("./reg.js"); var state = require("./state.js").state; var style = require("./style.js"); var options = require("./options.js"); // We need this module here because environments such as IE and Rhino // don't necessarilly expose the 'console' API and browserify uses // it to log things. It's a sad state of affair, really. var console = require("console-browserify"); // We build the application inside a function so that we produce only a singleton // variable. That function will be invoked immediately, and its return value is // the JSHINT function itself. var JSHINT = (function() { "use strict"; var api, // Extension API // These are operators that should not be used with the ! operator. bang = { "<" : true, "<=" : true, "==" : true, "===": true, "!==": true, "!=" : true, ">" : true, ">=" : true, "+" : true, "-" : true, "*" : true, "/" : true, "%" : true }, declared, // Globals that were declared using /*global ... */ syntax. exported, // Variables that are used outside of the current file. functionicity = [ "closure", "exception", "global", "label", "outer", "unused", "var" ], funct, // The current function functions, // All of the functions global, // The global scope implied, // Implied globals inblock, indent, lookahead, lex, member, membersOnly, predefined, // Global variables defined by option scope, // The current scope stack, unuseds, urls, extraModules = [], emitter = new events.EventEmitter(); function checkOption(name, t) { name = name.trim(); if (/^[+-]W\d{3}$/g.test(name)) { return true; } if (options.validNames.indexOf(name) === -1) { if (t.type !== "jslint" && !_.has(options.removed, name)) { error("E001", t, name); return false; } } return true; } function isString(obj) { return Object.prototype.toString.call(obj) === "[object String]"; } function isIdentifier(tkn, value) { if (!tkn) return false; if (!tkn.identifier || tkn.value !== value) return false; return true; } function isReserved(token) { if (!token.reserved) { return false; } var meta = token.meta; if (meta && meta.isFutureReservedWord && state.inES5()) { // ES3 FutureReservedWord in an ES5 environment. if (!meta.es5) { return false; } // Some ES5 FutureReservedWord identifiers are active only // within a strict mode environment. if (meta.strictOnly) { if (!state.option.strict && !state.isStrict()) { return false; } } if (token.isProperty) { return false; } } return true; } function supplant(str, data) { return str.replace(/\{([^{}]*)\}/g, function(a, b) { var r = data[b]; return typeof r === "string" || typeof r === "number" ? r : a; }); } function combine(dest, src) { Object.keys(src).forEach(function(name) { if (_.has(JSHINT.blacklist, name)) return; dest[name] = src[name]; }); } function processenforceall() { if (state.option.enforceall) { for (var enforceopt in options.bool.enforcing) { if (state.option[enforceopt] === undefined && !options.noenforceall[enforceopt]) { state.option[enforceopt] = true; } } for (var relaxopt in options.bool.relaxing) { if (state.option[relaxopt] === undefined) { state.option[relaxopt] = false; } } } } function assume() { processenforceall(); if (!state.option.es3) { combine(predefined, vars.ecmaIdentifiers[5]); } if (state.option.esnext) { combine(predefined, vars.ecmaIdentifiers[6]); } if (state.option.module) { /** * TODO: Extend this restriction to *all* "environmental" options. */ if (!hasParsedCode(funct)) { error("E055", state.tokens.next, "module"); } /** * TODO: Extend this restriction to *all* ES6-specific options. */ if (!state.inESNext()) { warning("W134", state.tokens.next, "module", 6); } } if (state.option.couch) { combine(predefined, vars.couch); } if (state.option.qunit) { combine(predefined, vars.qunit); } if (state.option.rhino) { combine(predefined, vars.rhino); } if (state.option.shelljs) { combine(predefined, vars.shelljs); combine(predefined, vars.node); } if (state.option.typed) { combine(predefined, vars.typed); } if (state.option.phantom) { combine(predefined, vars.phantom); } if (state.option.prototypejs) { combine(predefined, vars.prototypejs); } if (state.option.node) { combine(predefined, vars.node); combine(predefined, vars.typed); } if (state.option.devel) { combine(predefined, vars.devel); } if (state.option.dojo) { combine(predefined, vars.dojo); } if (state.option.browser) { combine(predefined, vars.browser); combine(predefined, vars.typed); } if (state.option.browserify) { combine(predefined, vars.browser); combine(predefined, vars.typed); combine(predefined, vars.browserify); } if (state.option.nonstandard) { combine(predefined, vars.nonstandard); } if (state.option.jasmine) { combine(predefined, vars.jasmine); } if (state.option.jquery) { combine(predefined, vars.jquery); } if (state.option.mootools) { combine(predefined, vars.mootools); } if (state.option.worker) { combine(predefined, vars.worker); } if (state.option.wsh) { combine(predefined, vars.wsh); } if (state.option.globalstrict && state.option.strict !== false) { state.option.strict = true; } if (state.option.yui) { combine(predefined, vars.yui); } if (state.option.mocha) { combine(predefined, vars.mocha); } } // Produce an error warning. function quit(code, line, chr) { var percentage = Math.floor((line / state.lines.length) * 100); var message = messages.errors[code].desc; throw { name: "JSHintError", line: line, character: chr, message: message + " (" + percentage + "% scanned).", raw: message, code: code }; } function isundef(scope, code, token, a) { if (!state.ignored[code] && state.option.undef !== false) { JSHINT.undefs.push([scope, code, token, a]); } } function removeIgnoredMessages() { var ignored = state.ignoredLines; if (_.isEmpty(ignored)) return; JSHINT.errors = _.reject(JSHINT.errors, function(err) { return ignored[err.line] }); } function warning(code, t, a, b, c, d) { var ch, l, w, msg; if (/^W\d{3}$/.test(code)) { if (state.ignored[code]) return; msg = messages.warnings[code]; } else if (/E\d{3}/.test(code)) { msg = messages.errors[code]; } else if (/I\d{3}/.test(code)) { msg = messages.info[code]; } t = t || state.tokens.next || {}; if (t.id === "(end)") { // `~ t = state.tokens.curr; } l = t.line || 0; ch = t.from || 0; w = { id: "(error)", raw: msg.desc, code: msg.code, evidence: state.lines[l - 1] || "", line: l, character: ch, scope: JSHINT.scope, a: a, b: b, c: c, d: d }; w.reason = supplant(msg.desc, w); JSHINT.errors.push(w); removeIgnoredMessages(); if (JSHINT.errors.length >= state.option.maxerr) quit("E043", l, ch); return w; } function warningAt(m, l, ch, a, b, c, d) { return warning(m, { line: l, from: ch }, a, b, c, d); } function error(m, t, a, b, c, d) { warning(m, t, a, b, c, d); } function errorAt(m, l, ch, a, b, c, d) { return error(m, { line: l, from: ch }, a, b, c, d); } // Tracking of "internal" scripts, like eval containing a static string function addInternalSrc(elem, src) { var i; i = { id: "(internal)", elem: elem, value: src }; JSHINT.internals.push(i); return i; } // adds an indentifier to the relevant current scope and creates warnings/errors as necessary // name: string // opts: { type: string, token: token, isblockscoped: bool } function addlabel(name, opts) { var type = opts.type; var token = opts.token; var isblockscoped = opts.isblockscoped; // Define label in the current function in the current scope. if (type === "exception") { if (_.has(funct["(context)"], name)) { if (funct[name] !== true && !state.option.node) { warning("W002", state.tokens.next, name); } } } if (_.has(funct, name) && !funct["(global)"]) { if (funct[name] === true) { if (state.option.latedef) { if ((state.option.latedef === true && _.contains([funct[name], type], "unction")) || !_.contains([funct[name], type], "unction")) { warning("W003", state.tokens.next, name); } } } else { if ((!state.option.shadow || _.contains([ "inner", "outer" ], state.option.shadow)) && type !== "exception" || funct["(blockscope)"].getlabel(name)) { warning("W004", state.tokens.next, name); } } } if (funct["(context)"] && _.has(funct["(context)"], name) && type !== "function") { if (state.option.shadow === "outer") { warning("W123", state.tokens.next, name); } } // if the identifier is blockscoped (a let or a const), add it only to the current blockscope if (isblockscoped) { funct["(blockscope)"].current.add(name, type, state.tokens.curr); if (funct["(blockscope)"].atTop() && exported[name]) { state.tokens.curr.exported = true; } } else { funct["(blockscope)"].shadow(name); funct[name] = type; if (token) { funct["(tokens)"][name] = token; } if (funct["(global)"]) { global[name] = funct; if (_.has(implied, name)) { if (state.option.latedef) { if ((state.option.latedef === true && _.contains([funct[name], type], "unction")) || !_.contains([funct[name], type], "unction")) { warning("W003", state.tokens.next, name); } } delete implied[name]; } } else { scope[name] = funct; } } } function doOption() { var nt = state.tokens.next; var body = nt.body.split(",").map(function(s) { return s.trim(); }); var predef = {}; if (nt.type === "globals") { body.forEach(function(g) { g = g.split(":"); var key = (g[0] || "").trim(); var val = (g[1] || "").trim(); if (key.charAt(0) === "-") { key = key.slice(1); val = false; JSHINT.blacklist[key] = key; delete predefined[key]; } else { predef[key] = (val === "true"); } }); combine(predefined, predef); for (var key in predef) { if (_.has(predef, key)) { declared[key] = nt; } } } if (nt.type === "exported") { body.forEach(function(e) { exported[e] = true; }); } if (nt.type === "members") { membersOnly = membersOnly || {}; body.forEach(function(m) { var ch1 = m.charAt(0); var ch2 = m.charAt(m.length - 1); if (ch1 === ch2 && (ch1 === "\"" || ch1 === "'")) { m = m .substr(1, m.length - 2) .replace("\\\"", "\""); } membersOnly[m] = false; }); } var numvals = [ "maxstatements", "maxparams", "maxdepth", "maxcomplexity", "maxerr", "maxlen", "indent" ]; if (nt.type === "jshint" || nt.type === "jslint") { body.forEach(function(g) { g = g.split(":"); var key = (g[0] || "").trim(); var val = (g[1] || "").trim(); if (!checkOption(key, nt)) { return; } if (numvals.indexOf(key) >= 0) { // GH988 - numeric options can be disabled by setting them to `false` if (val !== "false") { val = +val; if (typeof val !== "number" || !isFinite(val) || val <= 0 || Math.floor(val) !== val) { error("E032", nt, g[1].trim()); return; } state.option[key] = val; } else { state.option[key] = key === "indent" ? 4 : false; } return; } if (key === "es5") { if (val === "true" && state.option.es5) { warning("I003"); } } if (key === "validthis") { // `validthis` is valid only within a function scope. if (funct["(global)"]) return void error("E009"); if (val !== "true" && val !== "false") return void error("E002", nt); state.option.validthis = (val === "true"); return; } if (key === "quotmark") { switch (val) { case "true": case "false": state.option.quotmark = (val === "true"); break; case "double": case "single": state.option.quotmark = val; break; default: error("E002", nt); } return; } if (key === "shadow") { switch (val) { case "true": state.option.shadow = true; break; case "outer": state.option.shadow = "outer"; break; case "false": case "inner": state.option.shadow = "inner"; break; default: error("E002", nt); } return; } if (key === "unused") { switch (val) { case "true": state.option.unused = true; break; case "false": state.option.unused = false; break; case "vars": case "strict": state.option.unused = val; break; default: error("E002", nt); } return; } if (key === "latedef") { switch (val) { case "true": state.option.latedef = true; break; case "false": state.option.latedef = false; break; case "nofunc": state.option.latedef = "nofunc"; break; default: error("E002", nt); } return; } if (key === "ignore") { switch (val) { case "start": state.ignoreLinterErrors = true; break; case "end": state.ignoreLinterErrors = false; break; case "line": state.ignoredLines[nt.line] = true; removeIgnoredMessages(); break; default: error("E002", nt); } return; } var match = /^([+-])(W\d{3})$/g.exec(key); if (match) { // ignore for -W..., unignore for +W... state.ignored[match[2]] = (match[1] === "-"); return; } var tn; if (val === "true" || val === "false") { if (nt.type === "jslint") { tn = options.renamed[key] || key; state.option[tn] = (val === "true"); if (options.inverted[tn] !== undefined) { state.option[tn] = !state.option[tn]; } } else { state.option[key] = (val === "true"); } if (key === "newcap") { state.option["(explicitNewcap)"] = true; } return; } error("E002", nt); }); assume(); } } // We need a peek function. If it has an argument, it peeks that much farther // ahead. It is used to distinguish // for ( var i in ... // from // for ( var i = ... function peek(p) { var i = p || 0, j = 0, t; while (j <= i) { t = lookahead[j]; if (!t) { t = lookahead[j] = lex.token(); } j += 1; } // Peeking past the end of the program should produce the "(end)" token. if (!t && state.tokens.next.id === "(end)") { return state.tokens.next; } return t; } function peekIgnoreEOL() { var i = 0; var t; do { t = peek(i++); } while (t.id === "(endline)"); return t; } // Produce the next token. It looks for programming errors. function advance(id, t) { switch (state.tokens.curr.id) { case "(number)": if (state.tokens.next.id === ".") { warning("W005", state.tokens.curr); } break; case "-": if (state.tokens.next.id === "-" || state.tokens.next.id === "--") { warning("W006"); } break; case "+": if (state.tokens.next.id === "+" || state.tokens.next.id === "++") { warning("W007"); } break; } if (id && state.tokens.next.id !== id) { if (t) { if (state.tokens.next.id === "(end)") { error("E019", t, t.id); } else { error("E020", state.tokens.next, id, t.id, t.line, state.tokens.next.value); } } else if (state.tokens.next.type !== "(identifier)" || state.tokens.next.value !== id) { warning("W116", state.tokens.next, id, state.tokens.next.value); } } state.tokens.prev = state.tokens.curr; state.tokens.curr = state.tokens.next; for (;;) { state.tokens.next = lookahead.shift() || lex.token(); if (!state.tokens.next) { // No more tokens left, give up quit("E041", state.tokens.curr.line); } if (state.tokens.next.id === "(end)" || state.tokens.next.id === "(error)") { return; } if (state.tokens.next.check) { state.tokens.next.check(); } if (state.tokens.next.isSpecial) { doOption(); } else { if (state.tokens.next.id !== "(endline)") { break; } } } } function isInfix(token) { return token.infix || (!token.identifier && !token.template && !!token.led); } function isEndOfExpr() { var curr = state.tokens.curr; var next = state.tokens.next; if (next.id === ";" || next.id === "}" || next.id === ":") { return true; } if (isInfix(next) === isInfix(curr) || (curr.id === "yield" && state.inMoz())) { return curr.line !== startLine(next); } return false; } function isBeginOfExpr(prev) { return !prev.left && prev.arity !== "unary"; } // This is the heart of JSHINT, the Pratt parser. In addition to parsing, it // is looking for ad hoc lint patterns. We add .fud to Pratt's model, which is // like .nud except that it is only used on the first token of a statement. // Having .fud makes it much easier to define statement-oriented languages like // JavaScript. I retained Pratt's nomenclature. // .nud Null denotation // .fud First null denotation // .led Left denotation // lbp Left binding power // rbp Right binding power // They are elements of the parsing method called Top Down Operator Precedence. function expression(rbp, initial) { var left, isArray = false, isObject = false, isLetExpr = false; state.nameStack.push(); // if current expression is a let expression if (!initial && state.tokens.next.value === "let" && peek(0).value === "(") { if (!state.inMoz()) { warning("W118", state.tokens.next, "let expressions"); } isLetExpr = true; // create a new block scope we use only for the current expression funct["(blockscope)"].stack(); advance("let"); advance("("); state.tokens.prev.fud(); advance(")"); } if (state.tokens.next.id === "(end)") error("E006", state.tokens.curr); var isDangerous = state.option.asi && state.tokens.prev.line !== startLine(state.tokens.curr) && _.contains(["]", ")"], state.tokens.prev.id) && _.contains(["[", "("], state.tokens.curr.id); if (isDangerous) warning("W014", state.tokens.curr, state.tokens.curr.id); advance(); if (initial) { funct["(verb)"] = state.tokens.curr.value; state.tokens.curr.beginsStmt = true; } if (initial === true && state.tokens.curr.fud) { left = state.tokens.curr.fud(); } else { if (state.tokens.curr.nud) { left = state.tokens.curr.nud(); } else { error("E030", state.tokens.curr, state.tokens.curr.id); } // TODO: use pratt mechanics rather than special casing template tokens while ((rbp < state.tokens.next.lbp || state.tokens.next.type === "(template)") && !isEndOfExpr()) { isArray = state.tokens.curr.value === "Array"; isObject = state.tokens.curr.value === "Object"; // #527, new Foo.Array(), Foo.Array(), new Foo.Object(), Foo.Object() // Line breaks in IfStatement heads exist to satisfy the checkJSHint // "Line too long." error. if (left && (left.value || (left.first && left.first.value))) { // If the left.value is not "new", or the left.first.value is a "." // then safely assume that this is not "new Array()" and possibly // not "new Object()"... if (left.value !== "new" || (left.first && left.first.value && left.first.value === ".")) { isArray = false; // ...In the case of Object, if the left.value and state.tokens.curr.value // are not equal, then safely assume that this not "new Object()" if (left.value !== state.tokens.curr.value) { isObject = false; } } } advance(); if (isArray && state.tokens.curr.id === "(" && state.tokens.next.id === ")") { warning("W009", state.tokens.curr); } if (isObject && state.tokens.curr.id === "(" && state.tokens.next.id === ")") { warning("W010", state.tokens.curr); } if (left && state.tokens.curr.led) { left = state.tokens.curr.led(left); } else { error("E033", state.tokens.curr, state.tokens.curr.id); } } } if (isLetExpr) { funct["(blockscope)"].unstack(); } state.nameStack.pop(); return left; } // Functions for conformance of style. function startLine(token) { return token.startLine || token.line; } function nobreaknonadjacent(left, right) { left = left || state.tokens.curr; right = right || state.tokens.next; if (!state.option.laxbreak && left.line !== startLine(right)) { warning("W014", right, right.value); } } function nolinebreak(t) { t = t || state.tokens.curr; if (t.line !== startLine(state.tokens.next)) { warning("E022", t, t.value); } } function nobreakcomma(left, right) { if (left.line !== startLine(right)) { if (!state.option.laxcomma) { if (comma.first) { warning("I001"); comma.first = false; } warning("W014", left, right.value); } } } function comma(opts) { opts = opts || {}; if (!opts.peek) { nobreakcomma(state.tokens.curr, state.tokens.next); advance(","); } else { nobreakcomma(state.tokens.prev, state.tokens.curr); } if (state.tokens.next.identifier && !(opts.property && state.inES5())) { // Keywords that cannot follow a comma operator. switch (state.tokens.next.value) { case "break": case "case": case "catch": case "continue": case "default": case "do": case "else": case "finally": case "for": case "if": case "in": case "instanceof": case "return": case "switch": case "throw": case "try": case "var": case "let": case "while": case "with": error("E024", state.tokens.next, state.tokens.next.value); return false; } } if (state.tokens.next.type === "(punctuator)") { switch (state.tokens.next.value) { case "}": case "]": case ",": if (opts.allowTrailing) { return true; } /* falls through */ case ")": error("E024", state.tokens.next, state.tokens.next.value); return false; } } return true; } // Functional constructors for making the symbols that will be inherited by // tokens. function symbol(s, p) { var x = state.syntax[s]; if (!x || typeof x !== "object") { state.syntax[s] = x = { id: s, lbp: p, value: s }; } return x; } function delim(s) { var x = symbol(s, 0); x.delim = true; return x; } function stmt(s, f) { var x = delim(s); x.identifier = x.reserved = true; x.fud = f; return x; } function blockstmt(s, f) { var x = stmt(s, f); x.block = true; return x; } function reserveName(x) { var c = x.id.charAt(0); if ((c >= "a" && c <= "z") || (c >= "A" && c <= "Z")) { x.identifier = x.reserved = true; } return x; } function prefix(s, f) { var x = symbol(s, 150); reserveName(x); x.nud = (typeof f === "function") ? f : function() { this.arity = "unary"; this.right = expression(150); if (this.id === "++" || this.id === "--") { if (state.option.plusplus) { warning("W016", this, this.id); } else if (this.right && (!this.right.identifier || isReserved(this.right)) && this.right.id !== "." && this.right.id !== "[") { warning("W017", this); } // detect increment/decrement of a const // in the case of a.b, right will be the "." punctuator if (this.right && this.right.identifier) { if (funct["(blockscope)"].labeltype(this.right.value) === "const") { error("E013", this, this.right.value); } } } return this; }; return x; } function type(s, f) { var x = delim(s); x.type = s; x.nud = f; return x; } function reserve(name, func) { var x = type(name, func); x.identifier = true; x.reserved = true; return x; } function FutureReservedWord(name, meta) { var x = type(name, (meta && meta.nud) || function() { return this; }); meta = meta || {}; meta.isFutureReservedWord = true; x.value = name; x.identifier = true; x.reserved = true; x.meta = meta; return x; } function reservevar(s, v) { return reserve(s, function() { if (typeof v === "function") { v(this); } return this; }); } function infix(s, f, p, w) { var x = symbol(s, p); reserveName(x); x.infix = true; x.led = function(left) { if (!w) { nobreaknonadjacent(state.tokens.prev, state.tokens.curr); } if ((s === "in" || s === "instanceof") && left.id === "!") { warning("W018", left, "!"); } if (typeof f === "function") { return f(left, this); } else { this.left = left; this.right = expression(p); return this; } }; return x; } function application(s) { var x = symbol(s, 42); x.led = function(left) { nobreaknonadjacent(state.tokens.prev, state.tokens.curr); this.left = left; this.right = doFunction({ type: "arrow", loneArg: left }); return this; }; return x; } function relation(s, f) { var x = symbol(s, 100); x.led = function(left) { nobreaknonadjacent(state.tokens.prev, state.tokens.curr); this.left = left; var right = this.right = expression(100); if (isIdentifier(left, "NaN") || isIdentifier(right, "NaN")) { warning("W019", this); } else if (f) { f.apply(this, [left, right]); } if (!left || !right) { quit("E041", state.tokens.curr.line); } if (left.id === "!") { warning("W018", left, "!"); } if (right.id === "!") { warning("W018", right, "!"); } return this; }; return x; } function isPoorRelation(node) { return node && ((node.type === "(number)" && +node.value === 0) || (node.type === "(string)" && node.value === "") || (node.type === "null" && !state.option.eqnull) || node.type === "true" || node.type === "false" || node.type === "undefined"); } var typeofValues = {}; typeofValues.legacy = [ // E4X extended the `typeof` operator to return "xml" for the XML and // XMLList types it introduced. // Ref: 11.3.2 The typeof Operator // http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-357.pdf "xml", // IE<9 reports "unknown" when the `typeof` operator is applied to an // object existing across a COM+ bridge. In lieu of official documentation // (which does not exist), see: // http://robertnyman.com/2005/12/21/what-is-typeof-unknown/ "unknown" ]; typeofValues.es3 = [ "undefined", "boolean", "number", "string", "function", "object", ]; typeofValues.es3 = typeofValues.es3.concat(typeofValues.legacy); typeofValues.es6 = typeofValues.es3.concat("symbol"); // Checks whether the 'typeof' operator is used with the correct // value. For docs on 'typeof' see: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof function isTypoTypeof(left, right, state) { var values; if (state.option.notypeof) return false; if (!left || !right) return false; values = state.inESNext() ? typeofValues.es6 : typeofValues.es3; if (right.type === "(identifier)" && right.value === "typeof" && left.type === "(string)") return !_.contains(values, left.value); return false; } function isGlobalEval(left, state, funct) { var isGlobal = false; // permit methods to refer to an "eval" key in their own context if (left.type === "this" && funct["(context)"] === null) { isGlobal = true; } // permit use of "eval" members of objects else if (left.type === "(identifier)") { if (state.option.node && left.value === "global") { isGlobal = true; } else if (state.option.browser && (left.value === "window" || left.value === "document")) { isGlobal = true; } } return isGlobal; } function findNativePrototype(left) { var natives = [ "Array", "ArrayBuffer", "Boolean", "Collator", "DataView", "Date", "DateTimeFormat", "Error", "EvalError", "Float32Array", "Float64Array", "Function", "Infinity", "Intl", "Int16Array", "Int32Array", "Int8Array", "Iterator", "Number", "NumberFormat", "Object", "RangeError", "ReferenceError", "RegExp", "StopIteration", "String", "SyntaxError", "TypeError", "Uint16Array", "Uint32Array", "Uint8Array", "Uint8ClampedArray", "URIError" ]; function walkPrototype(obj) { if (typeof obj !== "object") return; return obj.right === "prototype" ? obj : walkPrototype(obj.left); } function walkNative(obj) { while (!obj.identifier && typeof obj.left === "object") obj = obj.left; if (obj.identifier && natives.indexOf(obj.value) >= 0) return obj.value; } var prototype = walkPrototype(left); if (prototype) return walkNative(prototype); } function assignop(s, f, p) { var x = infix(s, typeof f === "function" ? f : function(left, that) { that.left = left; if (left) { if (state.option.freeze) { var nativeObject = findNativePrototype(left); if (nativeObject) warning("W121", left, nativeObject); } if (predefined[left.value] === false && scope[left.value]["(global)"] === true) { warning("W020", left); } else if (left["function"]) { warning("W021", left, left.value); } if (funct["(blockscope)"].labeltype(left.value) === "const") { error("E013", left, left.value); } if (left.id === ".") { if (!left.left) { warning("E031", that); } else if (left.left.value === "arguments" && !state.isStrict()) { warning("E031", that); } state.nameStack.set(state.tokens.prev); that.right = expression(10); return that; } else if (left.id === "[") { if (state.tokens.curr.left.first) { state.tokens.curr.left.first.forEach(function(t) { if (t && funct[t.value] === "const") { error("E013", t, t.value); } }); } else if (!left.left) { warning("E031", that); } else if (left.left.value === "arguments" && !state.isStrict()) { warning("E031", that); } state.nameStack.set(left.right); that.right = expression(10); return that; } else if (left.identifier && !isReserved(left)) { if (funct[left.value] === "exception") { warning("W022", left); } state.nameStack.set(left); that.right = expression(10); return that; } if (left === state.syntax["function"]) { warning("W023", state.tokens.curr); } } error("E031", that); }, p); x.exps = true; x.assign = true; return x; } function bitwise(s, f, p) { var x = symbol(s, p); reserveName(x); x.led = (typeof f === "function") ? f : function(left) { if (state.option.bitwise) { warning("W016", this, this.id); } this.left = left; this.right = expression(p); return this; }; return x; } function bitwiseassignop(s) { return assignop(s, function(left, that) { if (state.option.bitwise) { warning("W016", that, that.id); } if (left) { if (left.id === "." || left.id === "[" || (left.identifier && !isReserved(left))) { expression(10); return that; } if (left === state.syntax["function"]) { warning("W023", state.tokens.curr); } return that; } error("E031", that); }, 20); } function suffix(s) { var x = symbol(s, 150); x.led = function(left) { // this = suffix e.g. "++" punctuator // left = symbol operated e.g. "a" identifier or "a.b" punctuator if (state.option.plusplus) { warning("W016", this, this.id); } else if ((!left.identifier || isReserved(left)) && left.id !== "." && left.id !== "[") { warning("W017", this); } // detect increment/decrement of a const // in the case of a.b, left will be the "." punctuator if (left && left.identifier) { if (funct["(blockscope)"].labeltype(left.value) === "const") { error("E013", this, left.value); } } this.left = left; return this; }; return x; } // fnparam means that this identifier is being defined as a function // argument (see identifier()) // prop means that this identifier is that of an object property function optionalidentifier(fnparam, prop, preserve) { if (!state.tokens.next.identifier) { return; } if (!preserve) { advance(); } var curr = state.tokens.curr; var val = state.tokens.curr.value; if (!isReserved(curr)) { return val; } if (prop) { if (state.inES5()) { return val; } } if (fnparam && val === "undefined") { return val; } warning("W024", state.tokens.curr, state.tokens.curr.id); return val; } // fnparam means that this identifier is being defined as a function // argument // prop means that this identifier is that of an object property function identifier(fnparam, prop) { var i = optionalidentifier(fnparam, prop, false); if (i) { return i; } // parameter destructuring with rest operator if (state.tokens.next.value === "...") { if (!state.option.esnext) { warning("W119", state.tokens.next, "spread/rest operator"); } advance(); if (checkPunctuators(state.tokens.next, ["..."])) { warning("E024", state.tokens.next, "..."); while (checkPunctuators(state.tokens.next, ["..."])) { advance(); } } if (!state.tokens.next.identifier) { warning("E024", state.tokens.curr, "..."); return; } return identifier(fnparam, prop); } else { error("E030", state.tokens.next, state.tokens.next.value); // The token should be consumed after a warning is issued so the parser // can continue as though an identifier were found. The semicolon token // should not be consumed in this way so that the parser interprets it as // a statement delimeter; if (state.tokens.next.id !== ";") { advance(); } } } function reachable(controlToken) { var i = 0, t; if (state.tokens.next.id !== ";" || controlToken.inBracelessBlock) { return; } for (;;) { do { t = peek(i); i += 1; } while (t.id !== "(end)" && t.id === "(comment)"); if (t.reach) { return; } if (t.id !== "(endline)") { if (t.id === "function") { if (state.option.latedef === true) { warning("W026", t); } break; } warning("W027", t, t.value, controlToken.value); break; } } } function parseFinalSemicolon() { if (state.tokens.next.id !== ";") { // don't complain about unclosed templates / strings if (state.tokens.next.isUnclosed) return advance(); if (!state.option.asi) { // If this is the last statement in a block that ends on // the same line *and* option lastsemic is on, ignore the warning. // Otherwise, complain about missing semicolon. if (!state.option.lastsemic || state.tokens.next.id !== "}" || startLine(state.tokens.next) !== state.tokens.curr.line) { warningAt("W033", state.tokens.curr.line, state.tokens.curr.character); } } } else { advance(";"); } } function statement() { var i = indent, r, s = scope, t = state.tokens.next; if (t.id === ";") { advance(";"); return; } // Is this a labelled statement? var res = isReserved(t); // We're being more tolerant here: if someone uses // a FutureReservedWord as a label, we warn but proceed // anyway. if (res && t.meta && t.meta.isFutureReservedWord && peek().id === ":") { warning("W024", t, t.id); res = false; } // detect a module import declaration if (t.value === "module" && t.type === "(identifier)") { if (peek().type === "(identifier)") { if (!state.inESNext()) { warning("W119", state.tokens.curr, "module"); } advance("module"); var name = identifier(); addlabel(name, { type: "unused", token: state.tokens.curr }); advance("from"); advance("(string)"); parseFinalSemicolon(); return; } } if (t.identifier && !res && peek().id === ":") { advance(); advance(":"); scope = Object.create(s); addlabel(t.value, { type: "label" }); if (!state.tokens.next.labelled && state.tokens.next.value !== "{") { warning("W028", state.tokens.next, t.value, state.tokens.next.value); } state.tokens.next.label = t.value; t = state.tokens.next; } // Is it a lonely block? if (t.id === "{") { // Is it a switch case block? // // switch (foo) { // case bar: { <= here. // ... // } // } var iscase = (funct["(verb)"] === "case" && state.tokens.curr.value === ":"); block(true, true, false, false, iscase); return; } // Parse the statement. r = expression(0, true); if (r && (!r.identifier || r.value !== "function") && (r.type !== "(punctuator)")) { if (!state.isStrict() && state.option.globalstrict && state.option.strict) { warning("E007"); } } // Look for the final semicolon. if (!t.block) { if (!state.option.expr && (!r || !r.exps)) { warning("W030", state.tokens.curr); } else if (state.option.nonew && r && r.left && r.id === "(" && r.left.id === "new") { warning("W031", t); } parseFinalSemicolon(); } // Restore the indentation. indent = i; scope = s; return r; } function statements() { var a = [], p; while (!state.tokens.next.reach && state.tokens.next.id !== "(end)") { if (state.tokens.next.id === ";") { p = peek(); if (!p || (p.id !== "(" && p.id !== "[")) { warning("W032"); } advance(";"); } else { a.push(statement()); } } return a; } /* * read all directives * recognizes a simple form of asi, but always * warns, if it is used */ function directives() { var i, p, pn; while (state.tokens.next.id === "(string)") { p = peek(0); if (p.id === "(endline)") { i = 1; do { pn = peek(i++); } while (pn.id === "(endline)"); if (pn.id === ";") { p = pn; } else if (pn.value === "[" || pn.value === ".") { // string -> [ | . is a valid production return; } else if (!state.option.asi || pn.value === "(") { // string -> ( is not a valid production warning("W033", state.tokens.next); } } else if (p.id === "." || p.id === "[") { return; } else if (p.id !== ";") { warning("W033", p); } advance(); if (state.directive[state.tokens.curr.value]) { warning("W034", state.tokens.curr, state.tokens.curr.value); } if (state.tokens.curr.value === "use strict") { if (!state.option["(explicitNewcap)"]) { state.option.newcap = true; } state.option.undef = true; } // there's no directive negation, so always set to true state.directive[state.tokens.curr.value] = true; if (p.id === ";") { advance(";"); } } } /* * Parses a single block. A block is a sequence of statements wrapped in * braces. * * ordinary - true for everything but function bodies and try blocks. * stmt - true if block can be a single statement (e.g. in if/for/while). * isfunc - true if block is a function body * isfatarrow - true if its a body of a fat arrow function * iscase - true if block is a switch case block */ function block(ordinary, stmt, isfunc, isfatarrow, iscase) { var a, b = inblock, old_indent = indent, m, s = scope, t, line, d; inblock = ordinary; if (!ordinary || !state.option.funcscope) scope = Object.create(scope); t = state.tokens.next; var metrics = funct["(metrics)"]; metrics.nestedBlockDepth += 1; metrics.verifyMaxNestedBlockDepthPerFunction(); if (state.tokens.next.id === "{") { advance("{"); // create a new block scope funct["(blockscope)"].stack(); line = state.tokens.curr.line; if (state.tokens.next.id !== "}") { indent += state.option.indent; while (!ordinary && state.tokens.next.from > indent) { indent += state.option.indent; } if (isfunc) { m = {}; for (d in state.directive) { if (_.has(state.directive, d)) { m[d] = state.directive[d]; } } directives(); if (state.option.strict && funct["(context)"]["(global)"]) { if (!m["use strict"] && !state.isStrict()) { warning("E007"); } } } a = statements(); metrics.statementCount += a.length; if (isfunc) { state.directive = m; } indent -= state.option.indent; } advance("}", t); funct["(blockscope)"].unstack(); indent = old_indent; } else if (!ordinary) { if (isfunc) { m = {}; if (stmt && !isfatarrow && !state.inMoz()) { error("W118", state.tokens.curr, "function closure expressions"); } if (!stmt) { for (d in state.directive) { if (_.has(state.directive, d)) { m[d] = state.directive[d]; } } } expression(10); if (state.option.strict && funct["(context)"]["(global)"]) { if (!m["use strict"] && !state.isStrict()) { warning("E007"); } } } else { error("E021", state.tokens.next, "{", state.tokens.next.value); } } else { // check to avoid let declaration not within a block funct["(noblockscopedvar)"] = true; if (!stmt || state.option.curly) { warning("W116", state.tokens.next, "{", state.tokens.next.value); } state.tokens.next.inBracelessBlock = true; indent += state.option.indent; // test indentation only if statement is in new line a = [statement()]; indent -= state.option.indent; delete funct["(noblockscopedvar)"]; } // Don't clear and let it propagate out if it is "break", "return" or similar in switch case switch (funct["(verb)"]) { case "break": case "continue": case "return": case "throw": if (iscase) { break; } /* falls through */ default: funct["(verb)"] = null; } if (!ordinary || !state.option.funcscope) scope = s; inblock = b; if (ordinary && state.option.noempty && (!a || a.length === 0)) { warning("W035", state.tokens.prev); } metrics.nestedBlockDepth -= 1; return a; } function countMember(m) { if (membersOnly && typeof membersOnly[m] !== "boolean") { warning("W036", state.tokens.curr, m); } if (typeof member[m] === "number") { member[m] += 1; } else { member[m] = 1; } } function note_implied(tkn) { var name = tkn.value; var desc = Object.getOwnPropertyDescriptor(implied, name); if (!desc) implied[name] = [tkn.line]; else desc.value.push(tkn.line); } // Build the syntax table by declaring the syntactic elements of the language. type("(number)", function() { return this; }); type("(string)", function() { return this; }); state.syntax["(identifier)"] = { type: "(identifier)", lbp: 0, identifier: true, nud: function() { var v = this.value; // s will be either the function object 'funct' that the identifier points at // or it will be a boolean if it is a predefined variable var s = scope[v]; var f; var block; // If this identifier is the lone parameter to a shorthand "fat arrow" // function definition, i.e. // // x => x; // // ...it should not be considered as a variable in the current scope. It // will be added to the scope of the new function when the next token is // parsed, so it can be safely ignored for now. if (state.tokens.next.id === "=>") { return this; } block = funct["(blockscope)"].getlabel(v); if (typeof s === "function") { // Protection against accidental inheritance. s = undefined; } else if (!block && typeof s === "boolean") { f = funct; funct = functions[0]; addlabel(v, { type: "var" }); s = funct; funct = f; } // The name is in scope and defined in the current function or it exists in the blockscope. if (funct === s || block) { // Change 'unused' to 'var', and reject labels. // the name is in a block scope. switch (block ? block[v]["(type)"] : funct[v]) { case "unused": if (block) block[v]["(type)"] = "var"; else funct[v] = "var"; break; case "unction": if (block) block[v]["(type)"] = "function"; else funct[v] = "function"; this["function"] = true; break; case "const": // consts can only exist inside block // because they are never added to the scope, s block[v]["(unused)"] = false; break; case "function": this["function"] = true; break; case "label": warning("W037", state.tokens.curr, v); break; } } else { // If the name is already defined in the current // function, but not as outer, then there is a scope error. switch (funct[v]) { case "closure": case "function": case "var": case "unused": warning("W038", state.tokens.curr, v); break; case "label": warning("W037", state.tokens.curr, v); break; case "outer": case "global": break; default: // If the name is defined in an outer function, make an outer entry, // and if it was unused, make it var. if (s === true) { funct[v] = true; } else if (s === null) { warning("W039", state.tokens.curr, v); note_implied(state.tokens.curr); } else if (typeof s !== "object") { // if we're in a list comprehension, variables are declared // locally and used before being defined. So we check // the presence of the given variable in the comp array // before declaring it undefined. if (!funct["(comparray)"].check(v)) { isundef(funct, "W117", state.tokens.curr, v); } // Explicitly mark the variable as used within function scopes if (!funct["(global)"]) { funct[v] = true; } note_implied(state.tokens.curr); } else { switch (s[v]) { case "function": case "unction": this["function"] = true; s[v] = "closure"; funct[v] = s["(global)"] ? "global" : "outer"; break; case "var": case "unused": s[v] = "closure"; funct[v] = s["(global)"] ? "global" : "outer"; break; case "closure": funct[v] = s["(global)"] ? "global" : "outer"; break; case "label": warning("W037", state.tokens.curr, v); } } } } return this; }, led: function() { error("E033", state.tokens.next, state.tokens.next.value); } }; var baseTemplateSyntax = { lbp: 0, identifier: false, template: true, }; state.syntax["(template)"] = _.extend({ type: "(template)", nud: doTemplateLiteral, led: doTemplateLiteral, noSubst: false }, baseTemplateSyntax); state.syntax["(template middle)"] = _.extend({ type: "(template middle)", middle: true, noSubst: false }, baseTemplateSyntax); state.syntax["(template tail)"] = _.extend({ type: "(template tail)", tail: true, noSubst: false }, baseTemplateSyntax); state.syntax["(no subst template)"] = _.extend({ type: "(template)", nud: doTemplateLiteral, led: doTemplateLiteral, noSubst: true, tail: true // mark as tail, since it's always the last component }, baseTemplateSyntax); type("(regexp)", function() { return this; }); // ECMAScript parser delim("(endline)"); delim("(begin)"); delim("(end)").reach = true; delim("(error)").reach = true; delim("}").reach = true; delim(")"); delim("]"); delim("\"").reach = true; delim("'").reach = true; delim(";"); delim(":").reach = true; delim("#"); reserve("else"); reserve("case").reach = true; reserve("catch"); reserve("default").reach = true; reserve("finally"); reservevar("arguments", function(x) { if (state.isStrict() && funct["(global)"]) { warning("E008", x); } }); reservevar("eval"); reservevar("false"); reservevar("Infinity"); reservevar("null"); reservevar("this", function(x) { if (state.isStrict() && !isMethod() && !state.option.validthis && ((funct["(statement)"] && funct["(name)"].charAt(0) > "Z") || funct["(global)"])) { warning("W040", x); } }); reservevar("true"); reservevar("undefined"); assignop("=", "assign", 20); assignop("+=", "assignadd", 20); assignop("-=", "assignsub", 20); assignop("*=", "assignmult", 20); assignop("/=", "assigndiv", 20).nud = function() { error("E014"); }; assignop("%=", "assignmod", 20); bitwiseassignop("&="); bitwiseassignop("|="); bitwiseassignop("^="); bitwiseassignop("<<="); bitwiseassignop(">>="); bitwiseassignop(">>>="); infix(",", function(left, that) { var expr; that.exprs = [left]; if (state.option.nocomma) { warning("W127"); } if (!comma({ peek: true })) { return that; } while (true) { if (!(expr = expression(10))) { break; } that.exprs.push(expr); if (state.tokens.next.value !== "," || !comma()) { break; } } return that; }, 10, true); infix("?", function(left, that) { increaseComplexityCount(); that.left = left; that.right = expression(10); advance(":"); that["else"] = expression(10); return that; }, 30); var orPrecendence = 40; infix("||", function(left, that) { increaseComplexityCount(); that.left = left; that.right = expression(orPrecendence); return that; }, orPrecendence); infix("&&", "and", 50); bitwise("|", "bitor", 70); bitwise("^", "bitxor", 80); bitwise("&", "bitand", 90); relation("==", function(left, right) { var eqnull = state.option.eqnull && (left.value === "null" || right.value === "null"); switch (true) { case !eqnull && state.option.eqeqeq: this.from = this.character; warning("W116", this, "===", "=="); break; case isPoorRelation(left): warning("W041", this, "===", left.value); break; case isPoorRelation(right): warning("W041", this, "===", right.value); break; case isTypoTypeof(right, left, state): warning("W122", this, right.value); break; case isTypoTypeof(left, right, state): warning("W122", this, left.value); break; } return this; }); relation("===", function(left, right) { if (isTypoTypeof(right, left, state)) { warning("W122", this, right.value); } else if (isTypoTypeof(left, right, state)) { warning("W122", this, left.value); } return this; }); relation("!=", function(left, right) { var eqnull = state.option.eqnull && (left.value === "null" || right.value === "null"); if (!eqnull && state.option.eqeqeq) { this.from = this.character; warning("W116", this, "!==", "!="); } else if (isPoorRelation(left)) { warning("W041", this, "!==", left.value); } else if (isPoorRelation(right)) { warning("W041", this, "!==", right.value); } else if (isTypoTypeof(right, left, state)) { warning("W122", this, right.value); } else if (isTypoTypeof(left, right, state)) { warning("W122", this, left.value); } return this; }); relation("!==", function(left, right) { if (isTypoTypeof(right, left, state)) { warning("W122", this, right.value); } else if (isTypoTypeof(left, right, state)) { warning("W122", this, left.value); } return this; }); relation("<"); relation(">"); relation("<="); relation(">="); bitwise("<<", "shiftleft", 120); bitwise(">>", "shiftright", 120); bitwise(">>>", "shiftrightunsigned", 120); infix("in", "in", 120); infix("instanceof", "instanceof", 120); infix("+", function(left, that) { var right; that.left = left; that.right = right = expression(130); if (left && right && left.id === "(string)" && right.id === "(string)") { left.value += right.value; left.character = right.character; if (!state.option.scripturl && reg.javascriptURL.test(left.value)) { warning("W050", left); } return left; } return that; }, 130); prefix("+", "num"); prefix("+++", function() { warning("W007"); this.arity = "unary"; this.right = expression(150); return this; }); infix("+++", function(left) { warning("W007"); this.left = left; this.right = expression(130); return this; }, 130); infix("-", "sub", 130); prefix("-", "neg"); prefix("---", function() { warning("W006"); this.arity = "unary"; this.right = expression(150); return this; }); infix("---", function(left) { warning("W006"); this.left = left; this.right = expression(130); return this; }, 130); infix("*", "mult", 140); infix("/", "div", 140); infix("%", "mod", 140); suffix("++"); prefix("++", "preinc"); state.syntax["++"].exps = true; suffix("--"); prefix("--", "predec"); state.syntax["--"].exps = true; prefix("delete", function() { var p = expression(10); if (!p) { return this; } if (p.id !== "." && p.id !== "[") { warning("W051"); } this.first = p; // The `delete` operator accepts unresolvable references when not in strict // mode, so the operand may be undefined. if (p.identifier && !state.isStrict()) { p.forgiveUndef = true; } return this; }).exps = true; prefix("~", function() { if (state.option.bitwise) { warning("W016", this, "~"); } this.arity = "unary"; expression(150); return this; }); prefix("...", function() { if (!state.option.esnext) { warning("W119", this, "spread/rest operator"); } // TODO: Allow all AssignmentExpression // once parsing permits. // // How to handle eg. number, boolean when the built-in // prototype of may have an @@iterator definition? // // Number.prototype[Symbol.iterator] = function * () { // yield this.valueOf(); // }; // // var a = [ ...1 ]; // console.log(a); // [1]; // // for (let n of [...10]) { // console.log(n); // } // // 10 // // // Boolean.prototype[Symbol.iterator] = function * () { // yield this.valueOf(); // }; // // var a = [ ...true ]; // console.log(a); // [true]; // // for (let n of [...false]) { // console.log(n); // } // // false // if (!state.tokens.next.identifier && state.tokens.next.type !== "(string)" && !checkPunctuators(state.tokens.next, ["[", "("])) { error("E030", state.tokens.next, state.tokens.next.value); } expression(150); return this; }); prefix("!", function() { this.arity = "unary"; this.right = expression(150); if (!this.right) { // '!' followed by nothing? Give up. quit("E041", this.line || 0); } if (bang[this.right.id] === true) { warning("W018", this, "!"); } return this; }); prefix("typeof", (function() { var p = expression(150); this.first = p; // The `typeof` operator accepts unresolvable references, so the operand // may be undefined. if (p.identifier) { p.forgiveUndef = true; } return this; })); prefix("new", function() { var c = expression(155), i; if (c && c.id !== "function") { if (c.identifier) { c["new"] = true; switch (c.value) { case "Number": case "String": case "Boolean": case "Math": case "JSON": warning("W053", state.tokens.prev, c.value); break; case "Symbol": if (state.option.esnext) { warning("W053", state.tokens.prev, c.value); } break; case "Function": if (!state.option.evil) { warning("W054"); } break; case "Date": case "RegExp": case "this": break; default: if (c.id !== "function") { i = c.value.substr(0, 1); if (state.option.newcap && (i < "A" || i > "Z") && !_.has(global, c.value)) { warning("W055", state.tokens.curr); } } } } else { if (c.id !== "." && c.id !== "[" && c.id !== "(") { warning("W056", state.tokens.curr); } } } else { if (!state.option.supernew) warning("W057", this); } if (state.tokens.next.id !== "(" && !state.option.supernew) { warning("W058", state.tokens.curr, state.tokens.curr.value); } this.first = c; return this; }); state.syntax["new"].exps = true; prefix("void").exps = true; infix(".", function(left, that) { var m = identifier(false, true); if (typeof m === "string") { countMember(m); } that.left = left; that.right = m; if (m && m === "hasOwnProperty" && state.tokens.next.value === "=") { warning("W001"); } if (left && left.value === "arguments" && (m === "callee" || m === "caller")) { if (state.option.noarg) warning("W059", left, m); else if (state.isStrict()) error("E008"); } else if (!state.option.evil && left && left.value === "document" && (m === "write" || m === "writeln")) { warning("W060", left); } if (!state.option.evil && (m === "eval" || m === "execScript")) { if (isGlobalEval(left, state, funct)) { warning("W061"); } } return that; }, 160, true); infix("(", function(left, that) { if (state.option.immed && left && !left.immed && left.id === "function") { warning("W062"); } var n = 0; var p = []; if (left) { if (left.type === "(identifier)") { if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) { if ("Number String Boolean Date Object Error Symbol".indexOf(left.value) === -1) { if (left.value === "Math") { warning("W063", left); } else if (state.option.newcap) { warning("W064", left); } } } } } if (state.tokens.next.id !== ")") { for (;;) { p[p.length] = expression(10); n += 1; if (state.tokens.next.id !== ",") { break; } comma(); } } advance(")"); if (typeof left === "object") { if (state.inES3() && left.value === "parseInt" && n === 1) { warning("W065", state.tokens.curr); } if (!state.option.evil) { if (left.value === "eval" || left.value === "Function" || left.value === "execScript") { warning("W061", left); if (p[0] && [0].id === "(string)") { addInternalSrc(left, p[0].value); } } else if (p[0] && p[0].id === "(string)" && (left.value === "setTimeout" || left.value === "setInterval")) { warning("W066", left); addInternalSrc(left, p[0].value); // window.setTimeout/setInterval } else if (p[0] && p[0].id === "(string)" && left.value === "." && left.left.value === "window" && (left.right === "setTimeout" || left.right === "setInterval")) { warning("W066", left); addInternalSrc(left, p[0].value); } } if (!left.identifier && left.id !== "." && left.id !== "[" && left.id !== "(" && left.id !== "&&" && left.id !== "||" && left.id !== "?" && !(state.option.esnext && left["(name)"])) { warning("W067", that); } } that.left = left; return that; }, 155, true).exps = true; prefix("(", function() { var pn = state.tokens.next, pn1, i = -1; var ret, triggerFnExpr, first, last; var parens = 1; var opening = state.tokens.curr; var preceeding = state.tokens.prev; var isNecessary = !state.option.singleGroups; do { if (pn.value === "(") { parens += 1; } else if (pn.value === ")") { parens -= 1; } i += 1; pn1 = pn; pn = peek(i); } while (!(parens === 0 && pn1.value === ")") && pn.value !== ";" && pn.type !== "(end)"); if (state.tokens.next.id === "function") { triggerFnExpr = state.tokens.next.immed = true; } // If the balanced grouping operator is followed by a "fat arrow", the // current token marks the beginning of a "fat arrow" function and parsing // should proceed accordingly. if (pn.value === "=>") { return doFunction({ type: "arrow", parsedOpening: true }); } var exprs = []; if (state.tokens.next.id !== ")") { for (;;) { exprs.push(expression(10)); if (state.tokens.next.id !== ",") { break; } if (state.option.nocomma) { warning("W127"); } comma(); } } advance(")", this); if (state.option.immed && exprs[0] && exprs[0].id === "function") { if (state.tokens.next.id !== "(" && state.tokens.next.id !== "." && state.tokens.next.id !== "[") { warning("W068", this); } } if (!exprs.length) { return; } if (exprs.length > 1) { ret = Object.create(state.syntax[","]); ret.exprs = exprs; first = exprs[0]; last = exprs[exprs.length - 1]; if (!isNecessary) { isNecessary = preceeding.assign || preceeding.delim; } } else { ret = first = last = exprs[0]; if (!isNecessary) { isNecessary = // Used to distinguish from an ExpressionStatement which may not // begin with the `{` and `function` tokens (opening.beginsStmt && (ret.id === "{" || triggerFnExpr || isFunctor(ret))) || // Used to signal that a function expression is being supplied to // some other operator. (triggerFnExpr && // For parenthesis wrapping a function expression to be considered // necessary, the grouping operator should be the left-hand-side of // some other operator--either within the parenthesis or directly // following them. (!isEndOfExpr() || state.tokens.prev.id !== "}")) || // Used to demarcate an arrow function as the left-hand side of some // operator. (isFunctor(ret) && !isEndOfExpr()) || // Used as the return value of a single-statement arrow function (ret.id === "{" && preceeding.id === "=>"); } } if (ret) { // The operator may be necessary to override the default binding power of // neighboring operators (whenever there is an operator in use within the // first expression *or* the current group contains multiple expressions) if (!isNecessary && (first.left || ret.exprs)) { isNecessary = (!isBeginOfExpr(preceeding) && first.lbp <= preceeding.lbp) || (!isEndOfExpr() && last.lbp < state.tokens.next.lbp); } if (!isNecessary) { warning("W126", opening); } ret.paren = true; } return ret; }); application("=>"); infix("[", function(left, that) { var e = expression(10), s; if (e && e.type === "(string)") { if (!state.option.evil && (e.value === "eval" || e.value === "execScript")) { if (isGlobalEval(left, state, funct)) { warning("W061"); } } countMember(e.value); if (!state.option.sub && reg.identifier.test(e.value)) { s = state.syntax[e.value]; if (!s || !isReserved(s)) { warning("W069", state.tokens.prev, e.value); } } } advance("]", that); if (e && e.value === "hasOwnProperty" && state.tokens.next.value === "=") { warning("W001"); } that.left = left; that.right = e; return that; }, 160, true); function comprehensiveArrayExpression() { var res = {}; res.exps = true; funct["(comparray)"].stack(); // Handle reversed for expressions, used in spidermonkey var reversed = false; if (state.tokens.next.value !== "for") { reversed = true; if (!state.inMoz()) { warning("W116", state.tokens.next, "for", state.tokens.next.value); } funct["(comparray)"].setState("use"); res.right = expression(10); } advance("for"); if (state.tokens.next.value === "each") { advance("each"); if (!state.inMoz()) { warning("W118", state.tokens.curr, "for each"); } } advance("("); funct["(comparray)"].setState("define"); res.left = expression(130); if (_.contains(["in", "of"], state.tokens.next.value)) { advance(); } else { error("E045", state.tokens.curr); } funct["(comparray)"].setState("generate"); expression(10); advance(")"); if (state.tokens.next.value === "if") { advance("if"); advance("("); funct["(comparray)"].setState("filter"); res.filter = expression(10); advance(")"); } if (!reversed) { funct["(comparray)"].setState("use"); res.right = expression(10); } advance("]"); funct["(comparray)"].unstack(); return res; } prefix("[", function() { var blocktype = lookupBlockType(); if (blocktype.isCompArray) { if (!state.inESNext()) { warning("W119", state.tokens.curr, "array comprehension"); } return comprehensiveArrayExpression(); } else if (blocktype.isDestAssign && !state.inESNext()) { warning("W104", state.tokens.curr, "destructuring assignment"); } var b = state.tokens.curr.line !== startLine(state.tokens.next); this.first = []; if (b) { indent += state.option.indent; if (state.tokens.next.from === indent + state.option.indent) { indent += state.option.indent; } } while (state.tokens.next.id !== "(end)") { while (state.tokens.next.id === ",") { if (!state.option.elision) { if (!state.inES5()) { // Maintain compat with old options --- ES5 mode without // elision=true will warn once per comma warning("W070"); } else { warning("W128"); do { advance(","); } while (state.tokens.next.id === ","); continue; } } advance(","); } if (state.tokens.next.id === "]") { break; } this.first.push(expression(10)); if (state.tokens.next.id === ",") { comma({ allowTrailing: true }); if (state.tokens.next.id === "]" && !state.inES5(true)) { warning("W070", state.tokens.curr); break; } } else { break; } } if (b) { indent -= state.option.indent; } advance("]", this); return this; }); function isMethod() { return funct["(statement)"] && funct["(statement)"].type === "class" || funct["(context)"] && funct["(context)"]["(verb)"] === "class"; } function isPropertyName(token) { return token.identifier || token.id === "(string)" || token.id === "(number)"; } function propertyName(preserveOrToken) { var id; var preserve = true; if (typeof preserveOrToken === "object") { id = preserveOrToken; } else { preserve = preserveOrToken; id = optionalidentifier(false, true, preserve); } if (!id) { if (state.tokens.next.id === "(string)") { id = state.tokens.next.value; if (!preserve) { advance(); } } else if (state.tokens.next.id === "(number)") { id = state.tokens.next.value.toString(); if (!preserve) { advance(); } } } else if (typeof id === "object") { if (id.id === "(string)" || id.id === "(identifier)") id = id.value; else if (id.id === "(number)") id = id.value.toString(); } if (id === "hasOwnProperty") { warning("W001"); } return id; } /** * @param {Object} [options] * @param {token} [options.loneArg] The argument to the function in cases * where it was defined using the * single-argument shorthand. * @param {bool} [options.parsedOpening] Whether the opening parenthesis has * already been parsed. */ function functionparams(options) { var next; var params = []; var ident; var tokens = []; var t; var pastDefault = false; var pastRest = false; var loneArg = options && options.loneArg; if (loneArg && loneArg.identifier === true) { addlabel(loneArg.value, { type: "unused", token: loneArg }); return [loneArg.value]; } next = state.tokens.next; if (!options || !options.parsedOpening) { advance("("); } if (state.tokens.next.id === ")") { advance(")"); return; } for (;;) { if (_.contains(["{", "["], state.tokens.next.id)) { tokens = destructuringExpression(); for (t in tokens) { t = tokens[t]; if (t.id) { params.push(t.id); addlabel(t.id, { type: "unused", token: t.token }); } } } else { if (checkPunctuators(state.tokens.next, ["..."])) pastRest = true; ident = identifier(true); if (ident) { params.push(ident); addlabel(ident, { type: "unused", token: state.tokens.curr }); } else { // Skip invalid parameter. while (!checkPunctuators(state.tokens.next, [",", ")"])) advance(); } } // it is a syntax error to have a regular argument after a default argument if (pastDefault) { if (state.tokens.next.id !== "=") { error("E051", state.tokens.current); } } if (state.tokens.next.id === "=") { if (!state.inESNext()) { warning("W119", state.tokens.next, "default parameters"); } advance("="); pastDefault = true; expression(10); } if (state.tokens.next.id === ",") { if (pastRest) { warning("W131", state.tokens.next); } comma(); } else { advance(")", next); return params; } } } function functor(name, token, scope, overwrites) { var funct = { "(name)" : name, "(breakage)" : 0, "(loopage)" : 0, "(scope)" : scope, "(tokens)" : {}, "(properties)": {}, "(catch)" : false, "(global)" : false, "(line)" : null, "(character)" : null, "(metrics)" : null, "(statement)" : null, "(context)" : null, "(blockscope)": null, "(comparray)" : null, "(generator)" : null, "(params)" : null }; if (token) { _.extend(funct, { "(line)" : token.line, "(character)": token.character, "(metrics)" : createMetrics(token) }); } _.extend(funct, overwrites); if (funct["(context)"]) { funct["(blockscope)"] = funct["(context)"]["(blockscope)"]; funct["(comparray)"] = funct["(context)"]["(comparray)"]; } return funct; } function isFunctor(token) { return "(scope)" in token; } /** * Determine if the parser has begun parsing executable code. * * @param {Token} funct - The current "functor" token * * @returns {boolean} */ function hasParsedCode(funct) { return funct["(global)"] && !funct["(verb)"]; } function doTemplateLiteral(left) { // ASSERT: this.type === "(template)" // jshint validthis: true var ctx = this.context; var noSubst = this.noSubst; var depth = this.depth; if (!noSubst) { while (!end()) { if (!state.tokens.next.template || state.tokens.next.depth > depth) { expression(0); // should probably have different rbp? } else { // skip template start / middle advance(); } } } return { id: "(template)", type: "(template)", tag: left }; function end() { if (state.tokens.curr.template && state.tokens.curr.tail && state.tokens.curr.context === ctx) return true; var complete = (state.tokens.next.template && state.tokens.next.tail && state.tokens.next.context === ctx); if (complete) advance(); return complete || state.tokens.next.isUnclosed; } } /** * @param {Object} [options] * @param {token} [options.name] The identifier belonging to the function (if * any) * @param {boolean} [options.statement] The statement that triggered creation * of the current function. * @param {string} [options.type] If specified, either "generator" or "arrow" * @param {token} [options.loneArg] The argument to the function in cases * where it was defined using the * single-argument shorthand * @param {bool} [options.parsedOpening] Whether the opening parenthesis has * already been parsed * @param {token} [options.classExprBinding] Define a function with this * identifier in the new function's * scope, mimicking the bahavior of * class expression names within * the body of member functions. */ function doFunction(options) { var f, name, statement, classExprBinding, isGenerator, isArrow; var oldOption = state.option; var oldIgnored = state.ignored; var oldScope = scope; if (options) { name = options.name; statement = options.statement; classExprBinding = options.classExprBinding; isGenerator = options.type === "generator"; isArrow = options.type === "arrow"; } state.option = Object.create(state.option); state.ignored = Object.create(state.ignored); scope = Object.create(scope); funct = functor(name || state.nameStack.infer(), state.tokens.next, scope, { "(statement)": statement, "(context)": funct, "(generator)": isGenerator }); f = funct; state.tokens.curr.funct = funct; functions.push(funct); if (name) { addlabel(name, { type: "function" }); } if (classExprBinding) { addlabel(classExprBinding, { type: "function" }); } funct["(params)"] = functionparams(options); funct["(metrics)"].verifyMaxParametersPerFunction(funct["(params)"]); if (isArrow) { if (!state.option.esnext) { warning("W119", state.tokens.curr, "arrow function syntax (=>)"); } if (!options.loneArg) { advance("=>"); } } block(false, true, true, isArrow); if (!state.option.noyield && isGenerator && funct["(generator)"] !== "yielded") { warning("W124", state.tokens.curr); } funct["(metrics)"].verifyMaxStatementsPerFunction(); funct["(metrics)"].verifyMaxComplexityPerFunction(); funct["(unusedOption)"] = state.option.unused; scope = oldScope; state.option = oldOption; state.ignored = oldIgnored; funct["(last)"] = state.tokens.curr.line; funct["(lastcharacter)"] = state.tokens.curr.character; _.map(Object.keys(funct), function(key) { if (key[0] === "(") return; funct["(blockscope)"].unshadow(key); }); funct = funct["(context)"]; return f; } function createMetrics(functionStartToken) { return { statementCount: 0, nestedBlockDepth: -1, ComplexityCount: 1, verifyMaxStatementsPerFunction: function() { if (state.option.maxstatements && this.statementCount > state.option.maxstatements) { warning("W071", functionStartToken, this.statementCount); } }, verifyMaxParametersPerFunction: function(params) { params = params || []; if (_.isNumber(state.option.maxparams) && params.length > state.option.maxparams) { warning("W072", functionStartToken, params.length); } }, verifyMaxNestedBlockDepthPerFunction: function() { if (state.option.maxdepth && this.nestedBlockDepth > 0 && this.nestedBlockDepth === state.option.maxdepth + 1) { warning("W073", null, this.nestedBlockDepth); } }, verifyMaxComplexityPerFunction: function() { var max = state.option.maxcomplexity; var cc = this.ComplexityCount; if (max && cc > max) { warning("W074", functionStartToken, cc); } } }; } function increaseComplexityCount() { funct["(metrics)"].ComplexityCount += 1; } // Parse assignments that were found instead of conditionals. // For example: if (a = 1) { ... } function checkCondAssignment(expr) { var id, paren; if (expr) { id = expr.id; paren = expr.paren; if (id === "," && (expr = expr.exprs[expr.exprs.length - 1])) { id = expr.id; paren = paren || expr.paren; } } switch (id) { case "=": case "+=": case "-=": case "*=": case "%=": case "&=": case "|=": case "^=": case "/=": if (!paren && !state.option.boss) { warning("W084"); } } } /** * @param {object} props Collection of property descriptors for a given * object. */ function checkProperties(props) { // Check for lonely setters if in the ES5 mode. if (state.inES5()) { for (var name in props) { if (_.has(props, name) && props[name].setterToken && !props[name].getterToken) { warning("W078", props[name].setterToken); } } } } (function(x) { x.nud = function() { var b, f, i, p, t, isGeneratorMethod = false, nextVal; var props = {}; // All properties, including accessors b = state.tokens.curr.line !== startLine(state.tokens.next); if (b) { indent += state.option.indent; if (state.tokens.next.from === indent + state.option.indent) { indent += state.option.indent; } } for (;;) { if (state.tokens.next.id === "}") { break; } nextVal = state.tokens.next.value; if (state.tokens.next.identifier && (peekIgnoreEOL().id === "," || peekIgnoreEOL().id === "}")) { if (!state.inESNext()) { warning("W104", state.tokens.next, "object short notation"); } i = propertyName(true); saveProperty(props, i, state.tokens.next); expression(10); } else if (peek().id !== ":" && (nextVal === "get" || nextVal === "set")) { advance(nextVal); if (!state.inES5()) { error("E034"); } i = propertyName(); // ES6 allows for get() {...} and set() {...} method // definition shorthand syntax, so we don't produce an error // if the esnext option is enabled. if (!i && !state.inESNext()) { error("E035"); } // We don't want to save this getter unless it's an actual getter // and not an ES6 concise method if (i) { saveAccessor(nextVal, props, i, state.tokens.curr); } t = state.tokens.next; f = doFunction(); p = f["(params)"]; // Don't warn about getter/setter pairs if this is an ES6 concise method if (nextVal === "get" && i && p) { warning("W076", t, p[0], i); } else if (nextVal === "set" && i && (!p || p.length !== 1)) { warning("W077", t, i); } } else { if (state.tokens.next.value === "*" && state.tokens.next.type === "(punctuator)") { if (!state.inESNext()) { warning("W104", state.tokens.next, "generator functions"); } advance("*"); isGeneratorMethod = true; } else { isGeneratorMethod = false; } if (state.tokens.next.id === "[") { i = computedPropertyName(); state.nameStack.set(i); } else { state.nameStack.set(state.tokens.next); i = propertyName(); saveProperty(props, i, state.tokens.next); if (typeof i !== "string") { break; } } if (state.tokens.next.value === "(") { if (!state.inESNext()) { warning("W104", state.tokens.curr, "concise methods"); } doFunction({ type: isGeneratorMethod ? "generator" : null }); } else { advance(":"); expression(10); } } countMember(i); if (state.tokens.next.id === ",") { comma({ allowTrailing: true, property: true }); if (state.tokens.next.id === ",") { warning("W070", state.tokens.curr); } else if (state.tokens.next.id === "}" && !state.inES5(true)) { warning("W070", state.tokens.curr); } } else { break; } } if (b) { indent -= state.option.indent; } advance("}", this); checkProperties(props); return this; }; x.fud = function() { error("E036", state.tokens.curr); }; }(delim("{"))); function destructuringExpression() { var id, ids; var identifiers = []; if (!state.inESNext()) { warning("W104", state.tokens.curr, "destructuring expression"); } var nextInnerDE = function() { var ident; if (checkPunctuators(state.tokens.next, ["[", "{"])) { ids = destructuringExpression(); for (var id in ids) { id = ids[id]; identifiers.push({ id: id.id, token: id.token }); } } else if (checkPunctuators(state.tokens.next, [","])) { identifiers.push({ id: null, token: state.tokens.curr }); } else if (checkPunctuators(state.tokens.next, ["("])) { advance("("); nextInnerDE(); advance(")"); } else { var is_rest = checkPunctuators(state.tokens.next, ["..."]); ident = identifier(); if (ident) identifiers.push({ id: ident, token: state.tokens.curr }); return is_rest; } return false; }; if (checkPunctuators(state.tokens.next, ["["])) { advance("["); var element_after_rest = false; if (nextInnerDE() && checkPunctuators(state.tokens.next, [","]) && !element_after_rest) { warning("W130", state.tokens.next); element_after_rest = true; } while (!checkPunctuators(state.tokens.next, ["]"])) { advance(","); if (checkPunctuators(state.tokens.next, ["]"])) { // Trailing comma break; } if (nextInnerDE() && checkPunctuators(state.tokens.next, [","]) && !element_after_rest) { warning("W130", state.tokens.next); element_after_rest = true; } } advance("]"); } else if (checkPunctuators(state.tokens.next, ["{"])) { advance("{"); id = identifier(); if (checkPunctuators(state.tokens.next, [":"])) { advance(":"); nextInnerDE(); } else { identifiers.push({ id: id, token: state.tokens.curr }); } while (!checkPunctuators(state.tokens.next, ["}"])) { advance(","); if (checkPunctuators(state.tokens.next, ["}"])) { // Trailing comma // ObjectBindingPattern: { BindingPropertyList , } break; } id = identifier(); if (checkPunctuators(state.tokens.next, [":"])) { advance(":"); nextInnerDE(); } else { identifiers.push({ id: id, token: state.tokens.curr }); } } advance("}"); } return identifiers; } function destructuringExpressionMatch(tokens, value) { var first = value.first; if (!first) return; _.zip(tokens, Array.isArray(first) ? first : [ first ]).forEach(function(val) { var token = val[0]; var value = val[1]; if (token && value) token.first = value; else if (token && token.first && !value) warning("W080", token.first, token.first.value); }); } function blockVariableStatement(type, statement, context) { // used for both let and const statements var prefix = context && context.prefix; var inexport = context && context.inexport; var isLet = type === "let"; var isConst = type === "const"; var tokens, lone, value, letblock; if (!state.inESNext()) { warning("W104", state.tokens.curr, type); } if (isLet && state.tokens.next.value === "(") { if (!state.inMoz()) { warning("W118", state.tokens.next, "let block"); } advance("("); funct["(blockscope)"].stack(); letblock = true; } else if (funct["(noblockscopedvar)"]) { error("E048", state.tokens.curr, isConst ? "Const" : "Let"); } statement.first = []; for (;;) { var names = []; if (_.contains(["{", "["], state.tokens.next.value)) { tokens = destructuringExpression(); lone = false; } else { tokens = [ { id: identifier(), token: state.tokens.curr } ]; lone = true; if (inexport) { exported[state.tokens.curr.value] = true; state.tokens.curr.exported = true; } } for (var t in tokens) { if (tokens.hasOwnProperty(t)) { t = tokens[t]; if (state.inESNext()) { // only look in the latest scope because we can shadow if (funct["(blockscope)"].current.labeltype(t.id) === "const") { warning("E011", null, t.id); } } if (funct["(global)"]) { if (predefined[t.id] === false) { warning("W079", t.token, t.id); } } if (t.id && !funct["(noblockscopedvar)"]) { addlabel(t.id, { type: isConst ? "const" : "unused", token: t.token, isblockscoped: true }); names.push(t.token); } } } statement.first = statement.first.concat(names); if (!prefix && isConst && state.tokens.next.id !== "=") { warning("E012", state.tokens.curr, state.tokens.curr.value); } if (state.tokens.next.id === "=") { advance("="); if (!prefix && state.tokens.next.id === "undefined") { warning("W080", state.tokens.prev, state.tokens.prev.value); } if (!prefix && peek(0).id === "=" && state.tokens.next.identifier) { warning("W120", state.tokens.next, state.tokens.next.value); } // don't accept `in` in expression if prefix is used for ForIn/Of loop. value = expression(prefix ? 120 : 10); if (lone) { tokens[0].first = value; } else { destructuringExpressionMatch(names, value); } } if (state.tokens.next.id !== ",") { break; } comma(); } if (letblock) { advance(")"); block(true, true); statement.block = true; funct["(blockscope)"].unstack(); } return statement; } var conststatement = stmt("const", function(context) { return blockVariableStatement("const", this, context); }); conststatement.exps = true; var letstatement = stmt("let", function(context) { return blockVariableStatement("let", this, context); }); letstatement.exps = true; var varstatement = stmt("var", function(context) { var prefix = context && context.prefix; var inexport = context && context.inexport; var tokens, lone, value; // If the `implied` option is set, bindings are set differently. var implied = context && context.implied; var report = !(context && context.ignore); this.first = []; for (;;) { var names = []; if (_.contains(["{", "["], state.tokens.next.value)) { tokens = destructuringExpression(); lone = false; } else { tokens = [ { id: identifier(), token: state.tokens.curr } ]; lone = true; if (inexport) { exported[state.tokens.curr.value] = true; state.tokens.curr.exported = true; } } for (var t in tokens) { if (tokens.hasOwnProperty(t)) { t = tokens[t]; if (state.inESNext()) { // because var is function scoped, look in the whole function if (funct["(blockscope)"].labeltype(t.id) === "const") { warning("E011", null, t.id); } } if (!implied && funct["(global)"]) { if (predefined[t.id] === false) { warning("W079", t.token, t.id); } else if (state.option.futurehostile === false) { if ((!state.inES5() && vars.ecmaIdentifiers[5][t.id] === false) || (!state.inESNext() && vars.ecmaIdentifiers[6][t.id] === false)) { warning("W129", t.token, t.id); } } } if (t.id) { if (implied === "for") { var ident = t.token.value; switch (funct[ident]) { case "unused": funct[ident] = "var"; break; case "var": break; default: if (!funct["(blockscope)"].getlabel(ident) && !(scope[ident] || {})[ident]) { if (report) warning("W088", t.token, ident); } } } else { addlabel(t.id, { type: "unused", token: t.token }); } names.push(t.token); } } } if (!prefix && report && state.option.varstmt) { warning("W132", this); } this.first = this.first.concat(names); if (state.tokens.next.id === "=") { state.nameStack.set(state.tokens.curr); advance("="); if (!prefix && report && state.tokens.next.id === "undefined") { warning("W080", state.tokens.prev, state.tokens.prev.value); } if (peek(0).id === "=" && state.tokens.next.identifier) { if (!prefix && report && !funct["(params)"] || funct["(params)"].indexOf(state.tokens.next.value) === -1) { warning("W120", state.tokens.next, state.tokens.next.value); } } // don't accept `in` in expression if prefix is used for ForIn/Of loop. value = expression(prefix ? 120 : 10); if (lone) { tokens[0].first = value; } else { destructuringExpressionMatch(names, value); } } if (state.tokens.next.id !== ",") { break; } comma(); } return this; }); varstatement.exps = true; blockstmt("class", function() { return classdef.call(this, true); }); function classdef(isStatement) { /*jshint validthis:true */ if (!state.inESNext()) { warning("W104", state.tokens.curr, "class"); } if (isStatement) { // BindingIdentifier this.name = identifier(); addlabel(this.name, { type: "unused", token: state.tokens.curr }); } else if (state.tokens.next.identifier && state.tokens.next.value !== "extends") { // BindingIdentifier(opt) this.name = identifier(); this.namedExpr = true; } else { this.name = state.nameStack.infer(); } classtail(this); return this; } function classtail(c) { var wasInClassBody = state.inClassBody; // ClassHeritage(opt) if (state.tokens.next.value === "extends") { advance("extends"); c.heritage = expression(10); } state.inClassBody = true; advance("{"); // ClassBody(opt) c.body = classbody(c); advance("}"); state.inClassBody = wasInClassBody; } function classbody(c) { var name; var isStatic; var isGenerator; var getset; var props = {}; var staticProps = {}; var computed; for (var i = 0; state.tokens.next.id !== "}"; ++i) { name = state.tokens.next; isStatic = false; isGenerator = false; getset = null; // The ES6 grammar for ClassElement includes the `;` token, but it is // defined only as a placeholder to facilitate future language // extensions. In ES6 code, it serves no purpose. if (name.id === ";") { warning("W032"); advance(";"); continue; } if (name.id === "*") { isGenerator = true; advance("*"); name = state.tokens.next; } if (name.id === "[") { name = computedPropertyName(); computed = true; } else if (isPropertyName(name)) { // Non-Computed PropertyName advance(); computed = false; if (name.identifier && name.value === "static") { if (checkPunctuators(state.tokens.next, ["*"])) { isGenerator = true; advance("*"); } if (isPropertyName(state.tokens.next) || state.tokens.next.id === "[") { computed = state.tokens.next.id === "["; isStatic = true; name = state.tokens.next; if (state.tokens.next.id === "[") { name = computedPropertyName(); } else advance(); } } if (name.identifier && (name.value === "get" || name.value === "set")) { if (isPropertyName(state.tokens.next) || state.tokens.next.id === "[") { computed = state.tokens.next.id === "["; getset = name; name = state.tokens.next; if (state.tokens.next.id === "[") { name = computedPropertyName(); } else advance(); } } } else { warning("W052", state.tokens.next, state.tokens.next.value || state.tokens.next.type); advance(); continue; } if (!checkPunctuators(state.tokens.next, ["("])) { // error --- class properties must be methods error("E054", state.tokens.next, state.tokens.next.value); while (state.tokens.next.id !== "}" && !checkPunctuators(state.tokens.next, ["("])) { advance(); } if (state.tokens.next.value !== "(") { doFunction({ statement: c }); } } if (!computed) { // We don't know how to determine if we have duplicate computed property names :( if (getset) { saveAccessor( getset.value, isStatic ? staticProps : props, name.value, name, true, isStatic); } else { if (name.value === "constructor") { state.nameStack.set(c); } else { state.nameStack.set(name); } saveProperty(isStatic ? staticProps : props, name.value, name, true, isStatic); } } if (getset && name.value === "constructor") { var propDesc = getset.value === "get" ? "class getter method" : "class setter method"; error("E049", name, propDesc, "constructor"); } else if (name.value === "prototype") { error("E049", name, "class method", "prototype"); } propertyName(name); doFunction({ statement: c, type: isGenerator ? "generator" : null, classExprBinding: c.namedExpr ? c.name : null }); } checkProperties(props); } blockstmt("function", function() { var generator = false; if (state.tokens.next.value === "*") { advance("*"); if (state.inESNext({ strict: true })) { generator = true; } else { warning("W119", state.tokens.curr, "function*"); } } if (inblock) { warning("W082", state.tokens.curr); } var i = optionalidentifier(); if (i === undefined) { warning("W025"); } // check if a identifier with the same name is already defined // in the blockscope as a const if (funct["(blockscope)"].labeltype(i) === "const") { warning("E011", null, i); } addlabel(i, { type: "unction", token: state.tokens.curr }); doFunction({ name: i, statement: this, type: generator ? "generator" : null }); if (state.tokens.next.id === "(" && state.tokens.next.line === state.tokens.curr.line) { error("E039"); } return this; }); prefix("function", function() { var generator = false; if (state.tokens.next.value === "*") { if (!state.inESNext()) { warning("W119", state.tokens.curr, "function*"); } advance("*"); generator = true; } var i = optionalidentifier(); var fn = doFunction({ name: i, type: generator ? "generator" : null }); function isVariable(name) { return name[0] !== "("; } function isLocal(name) { return fn[name] === "var"; } if (!state.option.loopfunc && funct["(loopage)"]) { // If the function we just parsed accesses any non-local variables // trigger a warning. Otherwise, the function is safe even within // a loop. if (_.some(fn, function(val, name) { return isVariable(name) && !isLocal(name); })) { warning("W083"); } } return this; }); blockstmt("if", function() { var t = state.tokens.next; increaseComplexityCount(); state.condition = true; advance("("); var expr = expression(0); checkCondAssignment(expr); // When the if is within a for-in loop, check if the condition // starts with a negation operator var forinifcheck = null; if (state.option.forin && state.forinifcheckneeded) { state.forinifcheckneeded = false; // We only need to analyze the first if inside the loop forinifcheck = state.forinifchecks[state.forinifchecks.length - 1]; if (expr.type === "(punctuator)" && expr.value === "!") { forinifcheck.type = "(negative)"; } else { forinifcheck.type = "(positive)"; } } advance(")", t); state.condition = false; var s = block(true, true); // When the if is within a for-in loop and the condition has a negative form, // check if the body contains nothing but a continue statement if (forinifcheck && forinifcheck.type === "(negative)") { if (s && s.length === 1 && s[0].type === "(identifier)" && s[0].value === "continue") { forinifcheck.type = "(negative-with-continue)"; } } if (state.tokens.next.id === "else") { advance("else"); if (state.tokens.next.id === "if" || state.tokens.next.id === "switch") { statement(); } else { block(true, true); } } return this; }); blockstmt("try", function() { var b; function doCatch() { var oldScope = scope; var e; advance("catch"); advance("("); scope = Object.create(oldScope); e = state.tokens.next.value; if (state.tokens.next.type !== "(identifier)") { e = null; warning("E030", state.tokens.next, e); } advance(); funct = functor("(catch)", state.tokens.next, scope, { "(context)" : funct, "(breakage)" : funct["(breakage)"], "(loopage)" : funct["(loopage)"], "(statement)": false, "(catch)" : true }); if (e) { addlabel(e, { type: "exception" }); } if (state.tokens.next.value === "if") { if (!state.inMoz()) { warning("W118", state.tokens.curr, "catch filter"); } advance("if"); expression(0); } advance(")"); state.tokens.curr.funct = funct; functions.push(funct); block(false); scope = oldScope; funct["(last)"] = state.tokens.curr.line; funct["(lastcharacter)"] = state.tokens.curr.character; funct = funct["(context)"]; } block(true); while (state.tokens.next.id === "catch") { increaseComplexityCount(); if (b && (!state.inMoz())) { warning("W118", state.tokens.next, "multiple catch blocks"); } doCatch(); b = true; } if (state.tokens.next.id === "finally") { advance("finally"); block(true); return; } if (!b) { error("E021", state.tokens.next, "catch", state.tokens.next.value); } return this; }); blockstmt("while", function() { var t = state.tokens.next; funct["(breakage)"] += 1; funct["(loopage)"] += 1; increaseComplexityCount(); advance("("); checkCondAssignment(expression(0)); advance(")", t); block(true, true); funct["(breakage)"] -= 1; funct["(loopage)"] -= 1; return this; }).labelled = true; blockstmt("with", function() { var t = state.tokens.next; if (state.isStrict()) { error("E010", state.tokens.curr); } else if (!state.option.withstmt) { warning("W085", state.tokens.curr); } advance("("); expression(0); advance(")", t); block(true, true); return this; }); blockstmt("switch", function() { var t = state.tokens.next; var g = false; var noindent = false; funct["(breakage)"] += 1; advance("("); checkCondAssignment(expression(0)); advance(")", t); t = state.tokens.next; advance("{"); if (state.tokens.next.from === indent) noindent = true; if (!noindent) indent += state.option.indent; this.cases = []; for (;;) { switch (state.tokens.next.id) { case "case": switch (funct["(verb)"]) { case "yield": case "break": case "case": case "continue": case "return": case "switch": case "throw": break; default: // You can tell JSHint that you don't use break intentionally by // adding a comment /* falls through */ on a line just before // the next `case`. if (!reg.fallsThrough.test(state.lines[state.tokens.next.line - 2])) { warning("W086", state.tokens.curr, "case"); } } advance("case"); this.cases.push(expression(0)); increaseComplexityCount(); g = true; advance(":"); funct["(verb)"] = "case"; break; case "default": switch (funct["(verb)"]) { case "yield": case "break": case "continue": case "return": case "throw": break; default: // Do not display a warning if 'default' is the first statement or if // there is a special /* falls through */ comment. if (this.cases.length) { if (!reg.fallsThrough.test(state.lines[state.tokens.next.line - 2])) { warning("W086", state.tokens.curr, "default"); } } } advance("default"); g = true; advance(":"); break; case "}": if (!noindent) indent -= state.option.indent; advance("}", t); funct["(breakage)"] -= 1; funct["(verb)"] = undefined; return; case "(end)": error("E023", state.tokens.next, "}"); return; default: indent += state.option.indent; if (g) { switch (state.tokens.curr.id) { case ",": error("E040"); return; case ":": g = false; statements(); break; default: error("E025", state.tokens.curr); return; } } else { if (state.tokens.curr.id === ":") { advance(":"); error("E024", state.tokens.curr, ":"); statements(); } else { error("E021", state.tokens.next, "case", state.tokens.next.value); return; } } indent -= state.option.indent; } } }).labelled = true; stmt("debugger", function() { if (!state.option.debug) { warning("W087", this); } return this; }).exps = true; (function() { var x = stmt("do", function() { funct["(breakage)"] += 1; funct["(loopage)"] += 1; increaseComplexityCount(); this.first = block(true, true); advance("while"); var t = state.tokens.next; advance("("); checkCondAssignment(expression(0)); advance(")", t); funct["(breakage)"] -= 1; funct["(loopage)"] -= 1; return this; }); x.labelled = true; x.exps = true; }()); blockstmt("for", function() { var s, t = state.tokens.next; var letscope = false; var foreachtok = null; if (t.value === "each") { foreachtok = t; advance("each"); if (!state.inMoz()) { warning("W118", state.tokens.curr, "for each"); } } funct["(breakage)"] += 1; funct["(loopage)"] += 1; increaseComplexityCount(); advance("("); // what kind of for(…) statement it is? for(…of…)? for(…in…)? for(…;…;…)? var nextop; // contains the token of the "in" or "of" operator var i = 0; var inof = ["in", "of"]; var level = 0; // BindingPattern "level" --- level 0 === no BindingPattern var comma; // First comma punctuator at level 0 var initializer; // First initializer at level 0 // If initial token is a BindingPattern, count it as such. if (checkPunctuators(state.tokens.next, ["{", "["])) ++level; do { nextop = peek(i); ++i; if (checkPunctuators(nextop, ["{", "["])) ++level; else if (checkPunctuators(nextop, ["}", "]"])) --level; if (level < 0) break; if (level === 0) { if (!comma && checkPunctuators(nextop, [","])) comma = nextop; else if (!initializer && checkPunctuators(nextop, ["="])) initializer = nextop; } } while (level > 0 || !_.contains(inof, nextop.value) && nextop.value !== ";" && nextop.type !== "(end)"); // Is this a JSCS bug? This looks really weird. // if we're in a for (… in|of …) statement if (_.contains(inof, nextop.value)) { if (!state.inESNext() && nextop.value === "of") { error("W104", nextop, "for of"); } var ok = !(initializer || comma); if (initializer) { error("W133", comma, nextop.value, "initializer is forbidden"); } if (comma) { error("W133", comma, nextop.value, "more than one ForBinding"); } if (state.tokens.next.id === "var") { advance("var"); state.tokens.curr.fud({ prefix: true }); } else if (state.tokens.next.id === "let" || state.tokens.next.id === "const") { advance(state.tokens.next.id); // create a new block scope letscope = true; funct["(blockscope)"].stack(); state.tokens.curr.fud({ prefix: true }); } else { // Parse as a var statement, with implied bindings. Ignore errors if an error // was already reported Object.create(varstatement).fud({ prefix: true, implied: "for", ignore: !ok }); } advance(nextop.value); expression(20); advance(")", t); if (nextop.value === "in" && state.option.forin) { state.forinifcheckneeded = true; if (state.forinifchecks === undefined) { state.forinifchecks = []; } // Push a new for-in-if check onto the stack. The type will be modified // when the loop's body is parsed and a suitable if statement exists. state.forinifchecks.push({ type: "(none)" }); } s = block(true, true); if (nextop.value === "in" && state.option.forin) { if (state.forinifchecks && state.forinifchecks.length > 0) { var check = state.forinifchecks.pop(); if (// No if statement or not the first statement in loop body s && s.length > 0 && (typeof s[0] !== "object" || s[0].value !== "if") || // Positive if statement is not the only one in loop body check.type === "(positive)" && s.length > 1 || // Negative if statement but no continue check.type === "(negative)") { warning("W089", this); } } // Reset the flag in case no if statement was contained in the loop body state.forinifcheckneeded = false; } funct["(breakage)"] -= 1; funct["(loopage)"] -= 1; } else { if (foreachtok) { error("E045", foreachtok); } if (state.tokens.next.id !== ";") { if (state.tokens.next.id === "var") { advance("var"); state.tokens.curr.fud(); } else if (state.tokens.next.id === "let") { advance("let"); // create a new block scope letscope = true; funct["(blockscope)"].stack(); state.tokens.curr.fud(); } else { for (;;) { expression(0, "for"); if (state.tokens.next.id !== ",") { break; } comma(); } } } nolinebreak(state.tokens.curr); advance(";"); if (state.tokens.next.id !== ";") { checkCondAssignment(expression(0)); } nolinebreak(state.tokens.curr); advance(";"); if (state.tokens.next.id === ";") { error("E021", state.tokens.next, ")", ";"); } if (state.tokens.next.id !== ")") { for (;;) { expression(0, "for"); if (state.tokens.next.id !== ",") { break; } comma(); } } advance(")", t); block(true, true); funct["(breakage)"] -= 1; funct["(loopage)"] -= 1; } // unstack loop blockscope if (letscope) { funct["(blockscope)"].unstack(); } return this; }).labelled = true; stmt("break", function() { var v = state.tokens.next.value; if (funct["(breakage)"] === 0) warning("W052", state.tokens.next, this.value); if (!state.option.asi) nolinebreak(this); if (state.tokens.next.id !== ";" && !state.tokens.next.reach) { if (state.tokens.curr.line === startLine(state.tokens.next)) { if (funct[v] !== "label") { warning("W090", state.tokens.next, v); } else if (scope[v] !== funct) { warning("W091", state.tokens.next, v); } this.first = state.tokens.next; advance(); } } reachable(this); return this; }).exps = true; stmt("continue", function() { var v = state.tokens.next.value; if (funct["(breakage)"] === 0) warning("W052", state.tokens.next, this.value); if (!state.option.asi) nolinebreak(this); if (state.tokens.next.id !== ";" && !state.tokens.next.reach) { if (state.tokens.curr.line === startLine(state.tokens.next)) { if (funct[v] !== "label") { warning("W090", state.tokens.next, v); } else if (scope[v] !== funct) { warning("W091", state.tokens.next, v); } this.first = state.tokens.next; advance(); } } else if (!funct["(loopage)"]) { warning("W052", state.tokens.next, this.value); } reachable(this); return this; }).exps = true; stmt("return", function() { if (this.line === startLine(state.tokens.next)) { if (state.tokens.next.id !== ";" && !state.tokens.next.reach) { this.first = expression(0); if (this.first && this.first.type === "(punctuator)" && this.first.value === "=" && !this.first.paren && !state.option.boss) { warningAt("W093", this.first.line, this.first.character); } } } else { if (state.tokens.next.type === "(punctuator)" && ["[", "{", "+", "-"].indexOf(state.tokens.next.value) > -1) { nolinebreak(this); // always warn (Line breaking error) } } reachable(this); return this; }).exps = true; (function(x) { x.exps = true; x.lbp = 25; }(prefix("yield", function() { var prev = state.tokens.prev; if (state.inESNext(true) && !funct["(generator)"]) { // If it's a yield within a catch clause inside a generator then that's ok if (!("(catch)" === funct["(name)"] && funct["(context)"]["(generator)"])) { error("E046", state.tokens.curr, "yield"); } } else if (!state.inESNext()) { warning("W104", state.tokens.curr, "yield"); } funct["(generator)"] = "yielded"; var delegatingYield = false; if (state.tokens.next.value === "*") { delegatingYield = true; advance("*"); } if (this.line === startLine(state.tokens.next) || !state.inMoz()) { if (delegatingYield || (state.tokens.next.id !== ";" && !state.tokens.next.reach && state.tokens.next.nud)) { nobreaknonadjacent(state.tokens.curr, state.tokens.next); this.first = expression(10); if (this.first.type === "(punctuator)" && this.first.value === "=" && !this.first.paren && !state.option.boss) { warningAt("W093", this.first.line, this.first.character); } } if (state.inMoz() && state.tokens.next.id !== ")" && (prev.lbp > 30 || (!prev.assign && !isEndOfExpr()) || prev.id === "yield")) { error("E050", this); } } else if (!state.option.asi) { nolinebreak(this); // always warn (Line breaking error) } return this; }))); stmt("throw", function() { nolinebreak(this); this.first = expression(20); reachable(this); return this; }).exps = true; stmt("import", function() { if (!state.inESNext()) { warning("W119", state.tokens.curr, "import"); } if (state.tokens.next.type === "(string)") { // ModuleSpecifier :: StringLiteral advance("(string)"); return this; } if (state.tokens.next.identifier) { // ImportClause :: ImportedDefaultBinding this.name = identifier(); addlabel(this.name, { type: "unused", token: state.tokens.curr }); if (state.tokens.next.value === ",") { // ImportClause :: ImportedDefaultBinding , NameSpaceImport // ImportClause :: ImportedDefaultBinding , NamedImports advance(","); // At this point, we intentionally fall through to continue matching // either NameSpaceImport or NamedImports. // Discussion: // https://github.com/jshint/jshint/pull/2144#discussion_r23978406 } else { advance("from"); advance("(string)"); return this; } } if (state.tokens.next.id === "*") { // ImportClause :: NameSpaceImport advance("*"); advance("as"); if (state.tokens.next.identifier) { this.name = identifier(); addlabel(this.name, { type: "unused", token: state.tokens.curr }); } } else { // ImportClause :: NamedImports advance("{"); for (;;) { if (state.tokens.next.value === "}") { advance("}"); break; } var importName; if (state.tokens.next.type === "default") { importName = "default"; advance("default"); } else { importName = identifier(); } if (state.tokens.next.value === "as") { advance("as"); importName = identifier(); } addlabel(importName, { type: "unused", token: state.tokens.curr }); if (state.tokens.next.value === ",") { advance(","); } else if (state.tokens.next.value === "}") { advance("}"); break; } else { error("E024", state.tokens.next, state.tokens.next.value); break; } } } // FromClause advance("from"); advance("(string)"); return this; }).exps = true; stmt("export", function() { var ok = true; var token; var identifier; if (!state.inESNext()) { warning("W119", state.tokens.curr, "export"); ok = false; } if (!funct["(global)"] || !funct["(blockscope)"].atTop()) { error("E053", state.tokens.curr); ok = false; } if (state.tokens.next.value === "*") { // ExportDeclaration :: export * FromClause advance("*"); advance("from"); advance("(string)"); return this; } if (state.tokens.next.type === "default") { // ExportDeclaration :: export default HoistableDeclaration // ExportDeclaration :: export default ClassDeclaration state.nameStack.set(state.tokens.next); advance("default"); if (state.tokens.next.id === "function" || state.tokens.next.id === "class") { this.block = true; } token = peek(); expression(10); if (state.tokens.next.id === "class") { identifier = token.name; } else { identifier = token.value; } addlabel(identifier, { type: "function", token: token }); return this; } if (state.tokens.next.value === "{") { // ExportDeclaration :: export ExportClause advance("{"); var exportedTokens = []; for (;;) { if (!state.tokens.next.identifier) { error("E030", state.tokens.next, state.tokens.next.value); } advance(); state.tokens.curr.exported = ok; exportedTokens.push(state.tokens.curr); if (state.tokens.next.value === "as") { advance("as"); if (!state.tokens.next.identifier) { error("E030", state.tokens.next, state.tokens.next.value); } advance(); } if (state.tokens.next.value === ",") { advance(","); } else if (state.tokens.next.value === "}") { advance("}"); break; } else { error("E024", state.tokens.next, state.tokens.next.value); break; } } if (state.tokens.next.value === "from") { // ExportDeclaration :: export ExportClause FromClause advance("from"); advance("(string)"); } else if (ok) { exportedTokens.forEach(function(token) { if (!funct[token.value]) { isundef(funct, "W117", token, token.value); } exported[token.value] = true; funct["(blockscope)"].setExported(token.value); }); } return this; } if (state.tokens.next.id === "var") { // ExportDeclaration :: export VariableStatement advance("var"); state.tokens.curr.fud({ inexport:true }); } else if (state.tokens.next.id === "let") { // ExportDeclaration :: export VariableStatement advance("let"); state.tokens.curr.fud({ inexport:true }); } else if (state.tokens.next.id === "const") { // ExportDeclaration :: export VariableStatement advance("const"); state.tokens.curr.fud({ inexport:true }); } else if (state.tokens.next.id === "function") { // ExportDeclaration :: export Declaration this.block = true; advance("function"); exported[state.tokens.next.value] = ok; state.tokens.next.exported = true; state.syntax["function"].fud(); } else if (state.tokens.next.id === "class") { // ExportDeclaration :: export Declaration this.block = true; advance("class"); exported[state.tokens.next.value] = ok; state.tokens.next.exported = true; state.syntax["class"].fud(); } else { error("E024", state.tokens.next, state.tokens.next.value); } return this; }).exps = true; // Future Reserved Words FutureReservedWord("abstract"); FutureReservedWord("boolean"); FutureReservedWord("byte"); FutureReservedWord("char"); FutureReservedWord("class", { es5: true, nud: classdef }); FutureReservedWord("double"); FutureReservedWord("enum", { es5: true }); FutureReservedWord("export", { es5: true }); FutureReservedWord("extends", { es5: true }); FutureReservedWord("final"); FutureReservedWord("float"); FutureReservedWord("goto"); FutureReservedWord("implements", { es5: true, strictOnly: true }); FutureReservedWord("import", { es5: true }); FutureReservedWord("int"); FutureReservedWord("interface", { es5: true, strictOnly: true }); FutureReservedWord("long"); FutureReservedWord("native"); FutureReservedWord("package", { es5: true, strictOnly: true }); FutureReservedWord("private", { es5: true, strictOnly: true }); FutureReservedWord("protected", { es5: true, strictOnly: true }); FutureReservedWord("public", { es5: true, strictOnly: true }); FutureReservedWord("short"); FutureReservedWord("static", { es5: true, strictOnly: true }); FutureReservedWord("super", { es5: true }); FutureReservedWord("synchronized"); FutureReservedWord("transient"); FutureReservedWord("volatile"); // this function is used to determine whether a squarebracket or a curlybracket // expression is a comprehension array, destructuring assignment or a json value. var lookupBlockType = function() { var pn, pn1; var i = -1; var bracketStack = 0; var ret = {}; if (checkPunctuators(state.tokens.curr, ["[", "{"])) bracketStack += 1; do { pn = (i === -1) ? state.tokens.next : peek(i); pn1 = peek(i + 1); i = i + 1; if (checkPunctuators(pn, ["[", "{"])) { bracketStack += 1; } else if (checkPunctuators(pn, ["]", "}"])) { bracketStack -= 1; } if (pn.identifier && pn.value === "for" && bracketStack === 1) { ret.isCompArray = true; ret.notJson = true; break; } if (checkPunctuators(pn, ["}", "]"]) && bracketStack === 0) { if (pn1.value === "=") { ret.isDestAssign = true; ret.notJson = true; break; } else if (pn1.value === ".") { ret.notJson = true; break; } } if (pn.value === ";") { ret.isBlock = true; ret.notJson = true; } } while (bracketStack > 0 && pn.id !== "(end)"); return ret; }; function saveProperty(props, name, tkn, isClass, isStatic) { var msg = ["key", "class method", "static class method"]; msg = msg[(isClass || false) + (isStatic || false)]; if (tkn.identifier) { name = tkn.value; } if (props[name] && _.has(props, name)) { warning("W075", state.tokens.next, msg, name); } else { props[name] = {}; } props[name].basic = true; props[name].basictkn = tkn; } /** * @param {string} accessorType - Either "get" or "set" * @param {object} props - a collection of all properties of the object to * which the current accessor is being assigned * @param {object} tkn - the identifier token representing the accessor name * @param {boolean} isClass - whether the accessor is part of an ES6 Class * definition * @param {boolean} isStatic - whether the accessor is a static method */ function saveAccessor(accessorType, props, name, tkn, isClass, isStatic) { var flagName = accessorType === "get" ? "getterToken" : "setterToken"; var msg = ""; if (isClass) { if (isStatic) { msg += "static "; } msg += accessorType + "ter method"; } else { msg = "key"; } state.tokens.curr.accessorType = accessorType; state.nameStack.set(tkn); if (props[name] && _.has(props, name)) { if (props[name].basic || props[name][flagName]) { warning("W075", state.tokens.next, msg, name); } } else { props[name] = {}; } props[name][flagName] = tkn; } function computedPropertyName() { advance("["); if (!state.option.esnext) { warning("W119", state.tokens.curr, "computed property names"); } var value = expression(10); advance("]"); return value; } // Test whether a given token is a punctuator matching one of the specified values function checkPunctuators(token, values) { return token.type === "(punctuator)" && _.contains(values, token.value); } // Check whether this function has been reached for a destructuring assign with undeclared values function destructuringAssignOrJsonValue() { // lookup for the assignment (esnext only) // if it has semicolons, it is a block, so go parse it as a block // or it's not a block, but there are assignments, check for undeclared variables var block = lookupBlockType(); if (block.notJson) { if (!state.inESNext() && block.isDestAssign) { warning("W104", state.tokens.curr, "destructuring assignment"); } statements(); // otherwise parse json value } else { state.option.laxbreak = true; state.jsonMode = true; jsonValue(); } } // array comprehension parsing function // parses and defines the three states of the list comprehension in order // to avoid defining global variables, but keeping them to the list comprehension scope // only. The order of the states are as follows: // * "use" which will be the returned iterative part of the list comprehension // * "define" which will define the variables local to the list comprehension // * "filter" which will help filter out values var arrayComprehension = function() { var CompArray = function() { this.mode = "use"; this.variables = []; }; var _carrays = []; var _current; function declare(v) { var l = _current.variables.filter(function(elt) { // if it has, change its undef state if (elt.value === v) { elt.undef = false; return v; } }).length; return l !== 0; } function use(v) { var l = _current.variables.filter(function(elt) { // and if it has been defined if (elt.value === v && !elt.undef) { if (elt.unused === true) { elt.unused = false; } return v; } }).length; // otherwise we warn about it return (l === 0); } return { stack: function() { _current = new CompArray(); _carrays.push(_current); }, unstack: function() { _current.variables.filter(function(v) { if (v.unused) warning("W098", v.token, v.raw_text || v.value); if (v.undef) isundef(v.funct, "W117", v.token, v.value); }); _carrays.splice(-1, 1); _current = _carrays[_carrays.length - 1]; }, setState: function(s) { if (_.contains(["use", "define", "generate", "filter"], s)) _current.mode = s; }, check: function(v) { if (!_current) { return; } // When we are in "use" state of the list comp, we enqueue that var if (_current && _current.mode === "use") { if (use(v)) { _current.variables.push({ funct: funct, token: state.tokens.curr, value: v, undef: true, unused: false }); } return true; // When we are in "define" state of the list comp, } else if (_current && _current.mode === "define") { // check if the variable has been used previously if (!declare(v)) { _current.variables.push({ funct: funct, token: state.tokens.curr, value: v, undef: false, unused: true }); } return true; // When we are in the "generate" state of the list comp, } else if (_current && _current.mode === "generate") { isundef(funct, "W117", state.tokens.curr, v); return true; // When we are in "filter" state, } else if (_current && _current.mode === "filter") { // we check whether current variable has been declared if (use(v)) { // if not we warn about it isundef(funct, "W117", state.tokens.curr, v); } return true; } return false; } }; }; // Parse JSON function jsonValue() { function jsonObject() { var o = {}, t = state.tokens.next; advance("{"); if (state.tokens.next.id !== "}") { for (;;) { if (state.tokens.next.id === "(end)") { error("E026", state.tokens.next, t.line); } else if (state.tokens.next.id === "}") { warning("W094", state.tokens.curr); break; } else if (state.tokens.next.id === ",") { error("E028", state.tokens.next); } else if (state.tokens.next.id !== "(string)") { warning("W095", state.tokens.next, state.tokens.next.value); } if (o[state.tokens.next.value] === true) { warning("W075", state.tokens.next, "key", state.tokens.next.value); } else if ((state.tokens.next.value === "__proto__" && !state.option.proto) || (state.tokens.next.value === "__iterator__" && !state.option.iterator)) { warning("W096", state.tokens.next, state.tokens.next.value); } else { o[state.tokens.next.value] = true; } advance(); advance(":"); jsonValue(); if (state.tokens.next.id !== ",") { break; } advance(","); } } advance("}"); } function jsonArray() { var t = state.tokens.next; advance("["); if (state.tokens.next.id !== "]") { for (;;) { if (state.tokens.next.id === "(end)") { error("E027", state.tokens.next, t.line); } else if (state.tokens.next.id === "]") { warning("W094", state.tokens.curr); break; } else if (state.tokens.next.id === ",") { error("E028", state.tokens.next); } jsonValue(); if (state.tokens.next.id !== ",") { break; } advance(","); } } advance("]"); } switch (state.tokens.next.id) { case "{": jsonObject(); break; case "[": jsonArray(); break; case "true": case "false": case "null": case "(number)": case "(string)": advance(); break; case "-": advance("-"); advance("(number)"); break; default: error("E003", state.tokens.next); } } var warnUnused = function(name, tkn, type, unused_opt) { var line = tkn.line; var chr = tkn.from; var raw_name = tkn.raw_text || name; if (unused_opt === undefined) { unused_opt = state.option.unused; } if (unused_opt === true) { unused_opt = "last-param"; } var warnable_types = { "vars": ["var"], "last-param": ["var", "param"], "strict": ["var", "param", "last-param"] }; if (unused_opt) { if (warnable_types[unused_opt] && warnable_types[unused_opt].indexOf(type) !== -1) { if (!tkn.exported) { warningAt("W098", line, chr, raw_name); } } } unuseds.push({ name: name, line: line, character: chr }); }; var blockScope = function() { var _current = {}; var _variables = [_current]; function _checkBlockLabels() { for (var t in _current) { var label = _current[t], labelType = label["(type)"]; if (labelType === "unused" || (labelType === "const" && label["(unused)"])) { if (state.option.unused) { var tkn = _current[t]["(token)"]; // Don't report exported labels as unused if (tkn.exported) { continue; } warnUnused(t, tkn, "var"); } } } } function _getLabel(l) { for (var i = _variables.length - 1 ; i >= 0; --i) { if (_.has(_variables[i], l) && !_variables[i][l]["(shadowed)"]) { return _variables[i]; } } } return { stack: function() { _current = {}; _variables.push(_current); }, unstack: function() { _checkBlockLabels(); _variables.splice(_variables.length - 1, 1); _current = _.last(_variables); }, getlabel: _getLabel, labeltype: function(l) { // returns a labels type or null if not present var block = _getLabel(l); if (block) { return block[l]["(type)"]; } return null; }, shadow: function(name) { for (var i = _variables.length - 1; i >= 0; i--) { if (_.has(_variables[i], name)) { _variables[i][name]["(shadowed)"] = true; } } }, unshadow: function(name) { for (var i = _variables.length - 1; i >= 0; i--) { if (_.has(_variables[i], name)) { _variables[i][name]["(shadowed)"] = false; } } }, atTop: function() { return _variables.length === 1; }, setExported: function(id) { if (funct["(blockscope)"].atTop()) { var item = _current[id]; if (item && item["(token)"]) { item["(token)"].exported = true; } } }, current: { labeltype: function(t) { if (_current[t]) { return _current[t]["(type)"]; } return null; }, has: function(t) { return _.has(_current, t); }, add: function(t, type, tok) { _current[t] = { "(type)" : type, "(token)": tok, "(shadowed)": false, "(unused)": true }; } } }; }; var escapeRegex = function(str) { return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); }; // The actual JSHINT function itself. var itself = function(s, o, g) { var i, k, x, reIgnoreStr, reIgnore; var optionKeys; var newOptionObj = {}; var newIgnoredObj = {}; o = _.clone(o); state.reset(); if (o && o.scope) { JSHINT.scope = o.scope; } else { JSHINT.errors = []; JSHINT.undefs = []; JSHINT.internals = []; JSHINT.blacklist = {}; JSHINT.scope = "(main)"; } predefined = Object.create(null); combine(predefined, vars.ecmaIdentifiers[3]); combine(predefined, vars.reservedVars); combine(predefined, g || {}); declared = Object.create(null); exported = Object.create(null); function each(obj, cb) { if (!obj) return; if (!Array.isArray(obj) && typeof obj === "object") obj = Object.keys(obj); obj.forEach(cb); } if (o) { each(o.predef || null, function(item) { var slice, prop; if (item[0] === "-") { slice = item.slice(1); JSHINT.blacklist[slice] = slice; // remove from predefined if there delete predefined[slice]; } else { prop = Object.getOwnPropertyDescriptor(o.predef, item); predefined[item] = prop ? prop.value : false; } }); each(o.exported || null, function(item) { exported[item] = true; }); delete o.predef; delete o.exported; optionKeys = Object.keys(o); for (x = 0; x < optionKeys.length; x++) { if (/^-W\d{3}$/g.test(optionKeys[x])) { newIgnoredObj[optionKeys[x].slice(1)] = true; } else { var optionKey = optionKeys[x]; newOptionObj[optionKey] = o[optionKey]; if (optionKey === "es5") { if (o[optionKey]) { warning("I003"); } } if (optionKeys[x] === "newcap" && o[optionKey] === false) newOptionObj["(explicitNewcap)"] = true; } } } state.option = newOptionObj; state.ignored = newIgnoredObj; state.option.indent = state.option.indent || 4; state.option.maxerr = state.option.maxerr || 50; indent = 1; global = Object.create(predefined); scope = global; funct = functor("(global)", null, scope, { "(global)" : true, "(blockscope)": blockScope(), "(comparray)" : arrayComprehension(), "(metrics)" : createMetrics(state.tokens.next) }); functions = [funct]; urls = []; stack = null; member = {}; membersOnly = null; implied = {}; inblock = false; lookahead = []; unuseds = []; if (!isString(s) && !Array.isArray(s)) { errorAt("E004", 0); return false; } api = { get isJSON() { return state.jsonMode; }, getOption: function(name) { return state.option[name] || null; }, getCache: function(name) { return state.cache[name]; }, setCache: function(name, value) { state.cache[name] = value; }, warn: function(code, data) { warningAt.apply(null, [ code, data.line, data.char ].concat(data.data)); }, on: function(names, listener) { names.split(" ").forEach(function(name) { emitter.on(name, listener); }.bind(this)); } }; emitter.removeAllListeners(); (extraModules || []).forEach(function(func) { func(api); }); state.tokens.prev = state.tokens.curr = state.tokens.next = state.syntax["(begin)"]; if (o && o.ignoreDelimiters) { if (!Array.isArray(o.ignoreDelimiters)) { o.ignoreDelimiters = [o.ignoreDelimiters]; } o.ignoreDelimiters.forEach(function(delimiterPair) { if (!delimiterPair.start || !delimiterPair.end) return; reIgnoreStr = escapeRegex(delimiterPair.start) + "[\\s\\S]*?" + escapeRegex(delimiterPair.end); reIgnore = new RegExp(reIgnoreStr, "ig"); s = s.replace(reIgnore, function(match) { return match.replace(/./g, " "); }); }); } lex = new Lexer(s); lex.on("warning", function(ev) { warningAt.apply(null, [ ev.code, ev.line, ev.character].concat(ev.data)); }); lex.on("error", function(ev) { errorAt.apply(null, [ ev.code, ev.line, ev.character ].concat(ev.data)); }); lex.on("fatal", function(ev) { quit("E041", ev.line, ev.from); }); lex.on("Identifier", function(ev) { emitter.emit("Identifier", ev); }); lex.on("String", function(ev) { emitter.emit("String", ev); }); lex.on("Number", function(ev) { emitter.emit("Number", ev); }); lex.start(); // Check options for (var name in o) { if (_.has(o, name)) { checkOption(name, state.tokens.curr); } } assume(); // combine the passed globals after we've assumed all our options combine(predefined, g || {}); //reset values comma.first = true; try { advance(); switch (state.tokens.next.id) { case "{": case "[": destructuringAssignOrJsonValue(); break; default: directives(); if (state.isStrict()) { if (!state.option.globalstrict) { if (!(state.option.module || state.option.node || state.option.phantom || state.option.browserify)) { warning("W097", state.tokens.prev); } } } statements(); } if (state.tokens.next.id !== "(end)") { quit("E041", state.tokens.curr.line); } funct["(blockscope)"].unstack(); var markDefined = function(name, context) { do { if (typeof context[name] === "string") { // JSHINT marks unused variables as 'unused' and // unused function declaration as 'unction'. This // code changes such instances back 'var' and // 'closure' so that the code in JSHINT.data() // doesn't think they're unused. if (context[name] === "unused") context[name] = "var"; else if (context[name] === "unction") context[name] = "closure"; return true; } context = context["(context)"]; } while (context); return false; }; var clearImplied = function(name, line) { if (!implied[name]) return; var newImplied = []; for (var i = 0; i < implied[name].length; i += 1) { if (implied[name][i] !== line) newImplied.push(implied[name][i]); } if (newImplied.length === 0) delete implied[name]; else implied[name] = newImplied; }; var checkUnused = function(func, key) { var type = func[key]; var tkn = func["(tokens)"][key]; if (key.charAt(0) === "(") return; if (type !== "unused" && type !== "unction") return; // Params are checked separately from other variables. if (func["(params)"] && func["(params)"].indexOf(key) !== -1) return; // Variable is in global scope and defined as exported. if (func["(global)"] && _.has(exported, key)) return; warnUnused(key, tkn, "var"); }; // Check queued 'x is not defined' instances to see if they're still undefined. for (i = 0; i < JSHINT.undefs.length; i += 1) { k = JSHINT.undefs[i].slice(0); if (markDefined(k[2].value, k[0]) || k[2].forgiveUndef) { clearImplied(k[2].value, k[2].line); } else if (state.option.undef) { warning.apply(warning, k.slice(1)); } } functions.forEach(function(func) { if (func["(unusedOption)"] === false) { return; } for (var key in func) { if (_.has(func, key)) { checkUnused(func, key); } } if (!func["(params)"]) return; var params = func["(params)"].slice(); var param = params.pop(); var type, unused_opt; while (param) { type = func[param]; unused_opt = func["(unusedOption)"] || state.option.unused; unused_opt = unused_opt === true ? "last-param" : unused_opt; // 'undefined' is a special case for (function(window, undefined) { ... })(); // patterns. if (param === "undefined") return; if (type === "unused" || type === "unction") { warnUnused(param, func["(tokens)"][param], "param", func["(unusedOption)"]); } else if (unused_opt === "last-param") { return; } param = params.pop(); } }); for (var key in declared) { if (_.has(declared, key) && !_.has(global, key) && !_.has(exported, key)) { warnUnused(key, declared[key], "var"); } } } catch (err) { if (err && err.name === "JSHintError") { var nt = state.tokens.next || {}; JSHINT.errors.push({ scope : "(main)", raw : err.raw, code : err.code, reason : err.message, line : err.line || nt.line, character : err.character || nt.from }, null); } else { throw err; } } // Loop over the listed "internals", and check them as well. if (JSHINT.scope === "(main)") { o = o || {}; for (i = 0; i < JSHINT.internals.length; i += 1) { k = JSHINT.internals[i]; o.scope = k.elem; itself(k.value, o, g); } } return JSHINT.errors.length === 0; }; // Modules. itself.addModule = function(func) { extraModules.push(func); }; itself.addModule(style.register); // Data summary. itself.data = function() { var data = { functions: [], options: state.option }; var implieds = []; var members = []; var fu, f, i, j, n, globals; if (itself.errors.length) { data.errors = itself.errors; } if (state.jsonMode) { data.json = true; } for (n in implied) { if (_.has(implied, n)) { implieds.push({ name: n, line: implied[n] }); } } if (implieds.length > 0) { data.implieds = implieds; } if (urls.length > 0) { data.urls = urls; } globals = Object.keys(scope); if (globals.length > 0) { data.globals = globals; } for (i = 1; i < functions.length; i += 1) { f = functions[i]; fu = {}; for (j = 0; j < functionicity.length; j += 1) { fu[functionicity[j]] = []; } for (j = 0; j < functionicity.length; j += 1) { if (fu[functionicity[j]].length === 0) { delete fu[functionicity[j]]; } } fu.name = f["(name)"]; fu.param = f["(params)"]; fu.line = f["(line)"]; fu.character = f["(character)"]; fu.last = f["(last)"]; fu.lastcharacter = f["(lastcharacter)"]; fu.metrics = { complexity: f["(metrics)"].ComplexityCount, parameters: (f["(params)"] || []).length, statements: f["(metrics)"].statementCount }; data.functions.push(fu); } if (unuseds.length > 0) { data.unused = unuseds; } members = []; for (n in member) { if (typeof member[n] === "number") { data.member = member; break; } } return data; }; itself.jshint = itself; return itself; }()); // Make JSHINT a Node module, if possible. if (typeof exports === "object" && exports) { exports.JSHINT = JSHINT; } },{"./lex.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/lex.js","./messages.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/messages.js","./options.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/options.js","./reg.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/reg.js","./state.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/state.js","./style.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/style.js","./vars.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/vars.js","console-browserify":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/console-browserify/index.js","events":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/events/events.js","lodash":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/lodash/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/lex.js":[function(require,module,exports){ /* * Lexical analysis and token construction. */ "use strict"; var _ = require("lodash"); var events = require("events"); var reg = require("./reg.js"); var state = require("./state.js").state; var unicodeData = require("../data/ascii-identifier-data.js"); var asciiIdentifierStartTable = unicodeData.asciiIdentifierStartTable; var asciiIdentifierPartTable = unicodeData.asciiIdentifierPartTable; var nonAsciiIdentifierStartTable = require("../data/non-ascii-identifier-start.js"); var nonAsciiIdentifierPartTable = require("../data/non-ascii-identifier-part-only.js"); // Some of these token types are from JavaScript Parser API // while others are specific to JSHint parser. // JS Parser API: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API var Token = { Identifier: 1, Punctuator: 2, NumericLiteral: 3, StringLiteral: 4, Comment: 5, Keyword: 6, NullLiteral: 7, BooleanLiteral: 8, RegExp: 9, TemplateHead: 10, TemplateMiddle: 11, TemplateTail: 12, NoSubstTemplate: 13 }; var Context = { Block: 1, Template: 2 }; // Object that handles postponed lexing verifications that checks the parsed // environment state. function asyncTrigger() { var _checks = []; return { push: function(fn) { _checks.push(fn); }, check: function() { for (var check = 0; check < _checks.length; ++check) { _checks[check](); } _checks.splice(0, _checks.length); } }; } /* * Lexer for JSHint. * * This object does a char-by-char scan of the provided source code * and produces a sequence of tokens. * * var lex = new Lexer("var i = 0;"); * lex.start(); * lex.token(); // returns the next token * * You have to use the token() method to move the lexer forward * but you don't have to use its return value to get tokens. In addition * to token() method returning the next token, the Lexer object also * emits events. * * lex.on("Identifier", function(data) { * if (data.name.indexOf("_") >= 0) { * // Produce a warning. * } * }); * * Note that the token() method returns tokens in a JSLint-compatible * format while the event emitter uses a slightly modified version of * Mozilla's JavaScript Parser API. Eventually, we will move away from * JSLint format. */ function Lexer(source) { var lines = source; if (typeof lines === "string") { lines = lines .replace(/\r\n/g, "\n") .replace(/\r/g, "\n") .split("\n"); } // If the first line is a shebang (#!), make it a blank and move on. // Shebangs are used by Node scripts. if (lines[0] && lines[0].substr(0, 2) === "#!") { if (lines[0].indexOf("node") !== -1) { state.option.node = true; } lines[0] = ""; } this.emitter = new events.EventEmitter(); this.source = source; this.setLines(lines); this.prereg = true; this.line = 0; this.char = 1; this.from = 1; this.input = ""; this.inComment = false; this.context = []; this.templateStarts = []; for (var i = 0; i < state.option.indent; i += 1) { state.tab += " "; } } Lexer.prototype = { _lines: [], inContext: function(ctxType) { return this.context.length > 0 && this.context[this.context.length - 1].type === ctxType; }, pushContext: function(ctxType) { this.context.push({ type: ctxType }); }, popContext: function() { return this.context.pop(); }, isContext: function(context) { return this.context.length > 0 && this.context[this.context.length - 1] === context; }, currentContext: function() { return this.context.length > 0 && this.context[this.context.length - 1]; }, getLines: function() { this._lines = state.lines; return this._lines; }, setLines: function(val) { this._lines = val; state.lines = this._lines; }, /* * Return the next i character without actually moving the * char pointer. */ peek: function(i) { return this.input.charAt(i || 0); }, /* * Move the char pointer forward i times. */ skip: function(i) { i = i || 1; this.char += i; this.input = this.input.slice(i); }, /* * Subscribe to a token event. The API for this method is similar * Underscore.js i.e. you can subscribe to multiple events with * one call: * * lex.on("Identifier Number", function(data) { * // ... * }); */ on: function(names, listener) { names.split(" ").forEach(function(name) { this.emitter.on(name, listener); }.bind(this)); }, /* * Trigger a token event. All arguments will be passed to each * listener. */ trigger: function() { this.emitter.emit.apply(this.emitter, Array.prototype.slice.call(arguments)); }, /* * Postpone a token event. the checking condition is set as * last parameter, and the trigger function is called in a * stored callback. To be later called using the check() function * by the parser. This avoids parser's peek() to give the lexer * a false context. */ triggerAsync: function(type, args, checks, fn) { checks.push(function() { if (fn()) { this.trigger(type, args); } }.bind(this)); }, /* * Extract a punctuator out of the next sequence of characters * or return 'null' if its not possible. * * This method's implementation was heavily influenced by the * scanPunctuator function in the Esprima parser's source code. */ scanPunctuator: function() { var ch1 = this.peek(); var ch2, ch3, ch4; switch (ch1) { // Most common single-character punctuators case ".": if ((/^[0-9]$/).test(this.peek(1))) { return null; } if (this.peek(1) === "." && this.peek(2) === ".") { return { type: Token.Punctuator, value: "..." }; } /* falls through */ case "(": case ")": case ";": case ",": case "[": case "]": case ":": case "~": case "?": return { type: Token.Punctuator, value: ch1 }; // A block/object opener case "{": this.pushContext(Context.Block); return { type: Token.Punctuator, value: ch1 }; // A block/object closer case "}": if (this.inContext(Context.Block)) { this.popContext(); } return { type: Token.Punctuator, value: ch1 }; // A pound sign (for Node shebangs) case "#": return { type: Token.Punctuator, value: ch1 }; // We're at the end of input case "": return null; } // Peek more characters ch2 = this.peek(1); ch3 = this.peek(2); ch4 = this.peek(3); // 4-character punctuator: >>>= if (ch1 === ">" && ch2 === ">" && ch3 === ">" && ch4 === "=") { return { type: Token.Punctuator, value: ">>>=" }; } // 3-character punctuators: === !== >>> <<= >>= if (ch1 === "=" && ch2 === "=" && ch3 === "=") { return { type: Token.Punctuator, value: "===" }; } if (ch1 === "!" && ch2 === "=" && ch3 === "=") { return { type: Token.Punctuator, value: "!==" }; } if (ch1 === ">" && ch2 === ">" && ch3 === ">") { return { type: Token.Punctuator, value: ">>>" }; } if (ch1 === "<" && ch2 === "<" && ch3 === "=") { return { type: Token.Punctuator, value: "<<=" }; } if (ch1 === ">" && ch2 === ">" && ch3 === "=") { return { type: Token.Punctuator, value: ">>=" }; } // Fat arrow punctuator if (ch1 === "=" && ch2 === ">") { return { type: Token.Punctuator, value: ch1 + ch2 }; } // 2-character punctuators: <= >= == != ++ -- << >> && || // += -= *= %= &= |= ^= (but not /=, see below) if (ch1 === ch2 && ("+-<>&|".indexOf(ch1) >= 0)) { return { type: Token.Punctuator, value: ch1 + ch2 }; } if ("<>=!+-*%&|^".indexOf(ch1) >= 0) { if (ch2 === "=") { return { type: Token.Punctuator, value: ch1 + ch2 }; } return { type: Token.Punctuator, value: ch1 }; } // Special case: /=. if (ch1 === "/") { if (ch2 === "=") { return { type: Token.Punctuator, value: "/=" }; } return { type: Token.Punctuator, value: "/" }; } return null; }, /* * Extract a comment out of the next sequence of characters and/or * lines or return 'null' if its not possible. Since comments can * span across multiple lines this method has to move the char * pointer. * * In addition to normal JavaScript comments (// and /*) this method * also recognizes JSHint- and JSLint-specific comments such as * /*jshint, /*jslint, /*globals and so on. */ scanComments: function() { var ch1 = this.peek(); var ch2 = this.peek(1); var rest = this.input.substr(2); var startLine = this.line; var startChar = this.char; // Create a comment token object and make sure it // has all the data JSHint needs to work with special // comments. function commentToken(label, body, opt) { var special = ["jshint", "jslint", "members", "member", "globals", "global", "exported"]; var isSpecial = false; var value = label + body; var commentType = "plain"; opt = opt || {}; if (opt.isMultiline) { value += "*/"; } body = body.replace(/\n/g, " "); special.forEach(function(str) { if (isSpecial) { return; } // Don't recognize any special comments other than jshint for single-line // comments. This introduced many problems with legit comments. if (label === "//" && str !== "jshint") { return; } if (body.charAt(str.length) === " " && body.substr(0, str.length) === str) { isSpecial = true; label = label + str; body = body.substr(str.length); } if (!isSpecial && body.charAt(0) === " " && body.charAt(str.length + 1) === " " && body.substr(1, str.length) === str) { isSpecial = true; label = label + " " + str; body = body.substr(str.length + 1); } if (!isSpecial) { return; } switch (str) { case "member": commentType = "members"; break; case "global": commentType = "globals"; break; default: commentType = str; } }); return { type: Token.Comment, commentType: commentType, value: value, body: body, isSpecial: isSpecial, isMultiline: opt.isMultiline || false, isMalformed: opt.isMalformed || false }; } // End of unbegun comment. Raise an error and skip that input. if (ch1 === "*" && ch2 === "/") { this.trigger("error", { code: "E018", line: startLine, character: startChar }); this.skip(2); return null; } // Comments must start either with // or /* if (ch1 !== "/" || (ch2 !== "*" && ch2 !== "/")) { return null; } // One-line comment if (ch2 === "/") { this.skip(this.input.length); // Skip to the EOL. return commentToken("//", rest); } var body = ""; /* Multi-line comment */ if (ch2 === "*") { this.inComment = true; this.skip(2); while (this.peek() !== "*" || this.peek(1) !== "/") { if (this.peek() === "") { // End of Line body += "\n"; // If we hit EOF and our comment is still unclosed, // trigger an error and end the comment implicitly. if (!this.nextLine()) { this.trigger("error", { code: "E017", line: startLine, character: startChar }); this.inComment = false; return commentToken("/*", body, { isMultiline: true, isMalformed: true }); } } else { body += this.peek(); this.skip(); } } this.skip(2); this.inComment = false; return commentToken("/*", body, { isMultiline: true }); } }, /* * Extract a keyword out of the next sequence of characters or * return 'null' if its not possible. */ scanKeyword: function() { var result = /^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input); var keywords = [ "if", "in", "do", "var", "for", "new", "try", "let", "this", "else", "case", "void", "with", "enum", "while", "break", "catch", "throw", "const", "yield", "class", "super", "return", "typeof", "delete", "switch", "export", "import", "default", "finally", "extends", "function", "continue", "debugger", "instanceof" ]; if (result && keywords.indexOf(result[0]) >= 0) { return { type: Token.Keyword, value: result[0] }; } return null; }, /* * Extract a JavaScript identifier out of the next sequence of * characters or return 'null' if its not possible. In addition, * to Identifier this method can also produce BooleanLiteral * (true/false) and NullLiteral (null). */ scanIdentifier: function() { var id = ""; var index = 0; var type, char; function isNonAsciiIdentifierStart(code) { return nonAsciiIdentifierStartTable.indexOf(code) > -1; } function isNonAsciiIdentifierPart(code) { return isNonAsciiIdentifierStart(code) || nonAsciiIdentifierPartTable.indexOf(code) > -1; } function isHexDigit(str) { return (/^[0-9a-fA-F]$/).test(str); } var readUnicodeEscapeSequence = function() { /*jshint validthis:true */ index += 1; if (this.peek(index) !== "u") { return null; } var ch1 = this.peek(index + 1); var ch2 = this.peek(index + 2); var ch3 = this.peek(index + 3); var ch4 = this.peek(index + 4); var code; if (isHexDigit(ch1) && isHexDigit(ch2) && isHexDigit(ch3) && isHexDigit(ch4)) { code = parseInt(ch1 + ch2 + ch3 + ch4, 16); if (asciiIdentifierPartTable[code] || isNonAsciiIdentifierPart(code)) { index += 5; return "\\u" + ch1 + ch2 + ch3 + ch4; } return null; } return null; }.bind(this); var getIdentifierStart = function() { /*jshint validthis:true */ var chr = this.peek(index); var code = chr.charCodeAt(0); if (code === 92) { return readUnicodeEscapeSequence(); } if (code < 128) { if (asciiIdentifierStartTable[code]) { index += 1; return chr; } return null; } if (isNonAsciiIdentifierStart(code)) { index += 1; return chr; } return null; }.bind(this); var getIdentifierPart = function() { /*jshint validthis:true */ var chr = this.peek(index); var code = chr.charCodeAt(0); if (code === 92) { return readUnicodeEscapeSequence(); } if (code < 128) { if (asciiIdentifierPartTable[code]) { index += 1; return chr; } return null; } if (isNonAsciiIdentifierPart(code)) { index += 1; return chr; } return null; }.bind(this); function removeEscapeSequences(id) { return id.replace(/\\u([0-9a-fA-F]{4})/g, function(m0, codepoint) { return String.fromCharCode(parseInt(codepoint, 16)); }); } char = getIdentifierStart(); if (char === null) { return null; } id = char; for (;;) { char = getIdentifierPart(); if (char === null) { break; } id += char; } switch (id) { case "true": case "false": type = Token.BooleanLiteral; break; case "null": type = Token.NullLiteral; break; default: type = Token.Identifier; } return { type: type, value: removeEscapeSequences(id), text: id, tokenLength: id.length }; }, /* * Extract a numeric literal out of the next sequence of * characters or return 'null' if its not possible. This method * supports all numeric literals described in section 7.8.3 * of the EcmaScript 5 specification. * * This method's implementation was heavily influenced by the * scanNumericLiteral function in the Esprima parser's source code. */ scanNumericLiteral: function() { var index = 0; var value = ""; var length = this.input.length; var char = this.peek(index); var bad; var isAllowedDigit = isDecimalDigit; var base = 10; var isLegacy = false; function isDecimalDigit(str) { return (/^[0-9]$/).test(str); } function isOctalDigit(str) { return (/^[0-7]$/).test(str); } function isBinaryDigit(str) { return (/^[01]$/).test(str); } function isHexDigit(str) { return (/^[0-9a-fA-F]$/).test(str); } function isIdentifierStart(ch) { return (ch === "$") || (ch === "_") || (ch === "\\") || (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z"); } // Numbers must start either with a decimal digit or a point. if (char !== "." && !isDecimalDigit(char)) { return null; } if (char !== ".") { value = this.peek(index); index += 1; char = this.peek(index); if (value === "0") { // Base-16 numbers. if (char === "x" || char === "X") { isAllowedDigit = isHexDigit; base = 16; index += 1; value += char; } // Base-8 numbers. if (char === "o" || char === "O") { isAllowedDigit = isOctalDigit; base = 8; if (!state.option.esnext) { this.trigger("warning", { code: "W119", line: this.line, character: this.char, data: [ "Octal integer literal" ] }); } index += 1; value += char; } // Base-2 numbers. if (char === "b" || char === "B") { isAllowedDigit = isBinaryDigit; base = 2; if (!state.option.esnext) { this.trigger("warning", { code: "W119", line: this.line, character: this.char, data: [ "Binary integer literal" ] }); } index += 1; value += char; } // Legacy base-8 numbers. if (isOctalDigit(char)) { isAllowedDigit = isOctalDigit; base = 8; isLegacy = true; bad = false; index += 1; value += char; } // Decimal numbers that start with '0' such as '09' are illegal // but we still parse them and return as malformed. if (!isOctalDigit(char) && isDecimalDigit(char)) { index += 1; value += char; } } while (index < length) { char = this.peek(index); if (isLegacy && isDecimalDigit(char)) { // Numbers like '019' (note the 9) are not valid octals // but we still parse them and mark as malformed. bad = true; } else if (!isAllowedDigit(char)) { break; } value += char; index += 1; } if (isAllowedDigit !== isDecimalDigit) { if (!isLegacy && value.length <= 2) { // 0x return { type: Token.NumericLiteral, value: value, isMalformed: true }; } if (index < length) { char = this.peek(index); if (isIdentifierStart(char)) { return null; } } return { type: Token.NumericLiteral, value: value, base: base, isLegacy: isLegacy, isMalformed: false }; } } // Decimal digits. if (char === ".") { value += char; index += 1; while (index < length) { char = this.peek(index); if (!isDecimalDigit(char)) { break; } value += char; index += 1; } } // Exponent part. if (char === "e" || char === "E") { value += char; index += 1; char = this.peek(index); if (char === "+" || char === "-") { value += this.peek(index); index += 1; } char = this.peek(index); if (isDecimalDigit(char)) { value += char; index += 1; while (index < length) { char = this.peek(index); if (!isDecimalDigit(char)) { break; } value += char; index += 1; } } else { return null; } } if (index < length) { char = this.peek(index); if (isIdentifierStart(char)) { return null; } } return { type: Token.NumericLiteral, value: value, base: base, isMalformed: !isFinite(value) }; }, // Assumes previously parsed character was \ (=== '\\') and was not skipped. scanEscapeSequence: function(checks) { var allowNewLine = false; var jump = 1; this.skip(); var char = this.peek(); switch (char) { case "'": this.triggerAsync("warning", { code: "W114", line: this.line, character: this.char, data: [ "\\'" ] }, checks, function() {return state.jsonMode; }); break; case "b": char = "\\b"; break; case "f": char = "\\f"; break; case "n": char = "\\n"; break; case "r": char = "\\r"; break; case "t": char = "\\t"; break; case "0": char = "\\0"; // Octal literals fail in strict mode. // Check if the number is between 00 and 07. var n = parseInt(this.peek(1), 10); this.triggerAsync("warning", { code: "W115", line: this.line, character: this.char }, checks, function() { return n >= 0 && n <= 7 && state.isStrict(); }); break; case "u": var hexCode = this.input.substr(1, 4); var code = parseInt(hexCode, 16); if (isNaN(code)) { this.trigger("warning", { code: "W052", line: this.line, character: this.char, data: [ "u" + hexCode ] }); } char = String.fromCharCode(code); jump = 5; break; case "v": this.triggerAsync("warning", { code: "W114", line: this.line, character: this.char, data: [ "\\v" ] }, checks, function() { return state.jsonMode; }); char = "\v"; break; case "x": var x = parseInt(this.input.substr(1, 2), 16); this.triggerAsync("warning", { code: "W114", line: this.line, character: this.char, data: [ "\\x-" ] }, checks, function() { return state.jsonMode; }); char = String.fromCharCode(x); jump = 3; break; case "\\": char = "\\\\"; break; case "\"": char = "\\\""; break; case "/": break; case "": allowNewLine = true; char = ""; break; } return { char: char, jump: jump, allowNewLine: allowNewLine }; }, /* * Extract a template literal out of the next sequence of characters * and/or lines or return 'null' if its not possible. Since template * literals can span across multiple lines, this method has to move * the char pointer. */ scanTemplateLiteral: function(checks) { var tokenType; var value = ""; var ch; var startLine = this.line; var startChar = this.char; var depth = this.templateStarts.length; if (!state.option.esnext) { // Only lex template strings in ESNext mode. return null; } else if (this.peek() === "`") { // Template must start with a backtick. tokenType = Token.TemplateHead; this.templateStarts.push({ line: this.line, char: this.char }); depth = this.templateStarts.length; this.skip(1); this.pushContext(Context.Template); } else if (this.inContext(Context.Template) && this.peek() === "}") { // If we're in a template context, and we have a '}', lex a TemplateMiddle. tokenType = Token.TemplateMiddle; } else { // Go lex something else. return null; } while (this.peek() !== "`") { while ((ch = this.peek()) === "") { value += "\n"; if (!this.nextLine()) { // Unclosed template literal --- point to the starting "`" var startPos = this.templateStarts.pop(); this.trigger("error", { code: "E052", line: startPos.line, character: startPos.char }); return { type: tokenType, value: value, startLine: startLine, startChar: startChar, isUnclosed: true, depth: depth, context: this.popContext() }; } } if (ch === '$' && this.peek(1) === '{') { value += '${'; this.skip(2); return { type: tokenType, value: value, startLine: startLine, startChar: startChar, isUnclosed: false, depth: depth, context: this.currentContext() }; } else if (ch === '\\') { var escape = this.scanEscapeSequence(checks); value += escape.char; this.skip(escape.jump); } else if (ch !== '`') { // Otherwise, append the value and continue. value += ch; this.skip(1); } } // Final value is either NoSubstTemplate or TemplateTail tokenType = tokenType === Token.TemplateHead ? Token.NoSubstTemplate : Token.TemplateTail; this.skip(1); this.templateStarts.pop(); return { type: tokenType, value: value, startLine: startLine, startChar: startChar, isUnclosed: false, depth: depth, context: this.popContext() }; }, /* * Extract a string out of the next sequence of characters and/or * lines or return 'null' if its not possible. Since strings can * span across multiple lines this method has to move the char * pointer. * * This method recognizes pseudo-multiline JavaScript strings: * * var str = "hello\ * world"; */ scanStringLiteral: function(checks) { /*jshint loopfunc:true */ var quote = this.peek(); // String must start with a quote. if (quote !== "\"" && quote !== "'") { return null; } // In JSON strings must always use double quotes. this.triggerAsync("warning", { code: "W108", line: this.line, character: this.char // +1? }, checks, function() { return state.jsonMode && quote !== "\""; }); var value = ""; var startLine = this.line; var startChar = this.char; var allowNewLine = false; this.skip(); while (this.peek() !== quote) { if (this.peek() === "") { // End Of Line // If an EOL is not preceded by a backslash, show a warning // and proceed like it was a legit multi-line string where // author simply forgot to escape the newline symbol. // // Another approach is to implicitly close a string on EOL // but it generates too many false positives. if (!allowNewLine) { this.trigger("warning", { code: "W112", line: this.line, character: this.char }); } else { allowNewLine = false; // Otherwise show a warning if multistr option was not set. // For JSON, show warning no matter what. this.triggerAsync("warning", { code: "W043", line: this.line, character: this.char }, checks, function() { return !state.option.multistr; }); this.triggerAsync("warning", { code: "W042", line: this.line, character: this.char }, checks, function() { return state.jsonMode && state.option.multistr; }); } // If we get an EOF inside of an unclosed string, show an // error and implicitly close it at the EOF point. if (!this.nextLine()) { this.trigger("error", { code: "E029", line: startLine, character: startChar }); return { type: Token.StringLiteral, value: value, startLine: startLine, startChar: startChar, isUnclosed: true, quote: quote }; } } else { // Any character other than End Of Line allowNewLine = false; var char = this.peek(); var jump = 1; // A length of a jump, after we're done // parsing this character. if (char < " ") { // Warn about a control character in a string. this.trigger("warning", { code: "W113", line: this.line, character: this.char, data: [ "<non-printable>" ] }); } // Special treatment for some escaped characters. if (char === "\\") { var parsed = this.scanEscapeSequence(checks); char = parsed.char; jump = parsed.jump; allowNewLine = parsed.allowNewLine; } value += char; this.skip(jump); } } this.skip(); return { type: Token.StringLiteral, value: value, startLine: startLine, startChar: startChar, isUnclosed: false, quote: quote }; }, /* * Extract a regular expression out of the next sequence of * characters and/or lines or return 'null' if its not possible. * * This method is platform dependent: it accepts almost any * regular expression values but then tries to compile and run * them using system's RegExp object. This means that there are * rare edge cases where one JavaScript engine complains about * your regular expression while others don't. */ scanRegExp: function() { var index = 0; var length = this.input.length; var char = this.peek(); var value = char; var body = ""; var flags = []; var malformed = false; var isCharSet = false; var terminated; var scanUnexpectedChars = function() { // Unexpected control character if (char < " ") { malformed = true; this.trigger("warning", { code: "W048", line: this.line, character: this.char }); } // Unexpected escaped character if (char === "<") { malformed = true; this.trigger("warning", { code: "W049", line: this.line, character: this.char, data: [ char ] }); } }.bind(this); // Regular expressions must start with '/' if (!this.prereg || char !== "/") { return null; } index += 1; terminated = false; // Try to get everything in between slashes. A couple of // cases aside (see scanUnexpectedChars) we don't really // care whether the resulting expression is valid or not. // We will check that later using the RegExp object. while (index < length) { char = this.peek(index); value += char; body += char; if (isCharSet) { if (char === "]") { if (this.peek(index - 1) !== "\\" || this.peek(index - 2) === "\\") { isCharSet = false; } } if (char === "\\") { index += 1; char = this.peek(index); body += char; value += char; scanUnexpectedChars(); } index += 1; continue; } if (char === "\\") { index += 1; char = this.peek(index); body += char; value += char; scanUnexpectedChars(); if (char === "/") { index += 1; continue; } if (char === "[") { index += 1; continue; } } if (char === "[") { isCharSet = true; index += 1; continue; } if (char === "/") { body = body.substr(0, body.length - 1); terminated = true; index += 1; break; } index += 1; } // A regular expression that was never closed is an // error from which we cannot recover. if (!terminated) { this.trigger("error", { code: "E015", line: this.line, character: this.from }); return void this.trigger("fatal", { line: this.line, from: this.from }); } // Parse flags (if any). while (index < length) { char = this.peek(index); if (!/[gim]/.test(char)) { break; } flags.push(char); value += char; index += 1; } // Check regular expression for correctness. try { new RegExp(body, flags.join("")); } catch (err) { malformed = true; this.trigger("error", { code: "E016", line: this.line, character: this.char, data: [ err.message ] // Platform dependent! }); } return { type: Token.RegExp, value: value, flags: flags, isMalformed: malformed }; }, /* * Scan for any occurrence of non-breaking spaces. Non-breaking spaces * can be mistakenly typed on OS X with option-space. Non UTF-8 web * pages with non-breaking pages produce syntax errors. */ scanNonBreakingSpaces: function() { return state.option.nonbsp ? this.input.search(/(\u00A0)/) : -1; }, /* * Scan for characters that get silently deleted by one or more browsers. */ scanUnsafeChars: function() { return this.input.search(reg.unsafeChars); }, /* * Produce the next raw token or return 'null' if no tokens can be matched. * This method skips over all space characters. */ next: function(checks) { this.from = this.char; // Move to the next non-space character. var start; if (/\s/.test(this.peek())) { start = this.char; while (/\s/.test(this.peek())) { this.from += 1; this.skip(); } } // Methods that work with multi-line structures and move the // character pointer. var match = this.scanComments() || this.scanStringLiteral(checks) || this.scanTemplateLiteral(checks); if (match) { return match; } // Methods that don't move the character pointer. match = this.scanRegExp() || this.scanPunctuator() || this.scanKeyword() || this.scanIdentifier() || this.scanNumericLiteral(); if (match) { this.skip(match.tokenLength || match.value.length); return match; } // No token could be matched, give up. return null; }, /* * Switch to the next line and reset all char pointers. Once * switched, this method also checks for other minor warnings. */ nextLine: function() { var char; if (this.line >= this.getLines().length) { return false; } this.input = this.getLines()[this.line]; this.line += 1; this.char = 1; this.from = 1; var inputTrimmed = this.input.trim(); var startsWith = function() { return _.some(arguments, function(prefix) { return inputTrimmed.indexOf(prefix) === 0; }); }; var endsWith = function() { return _.some(arguments, function(suffix) { return inputTrimmed.indexOf(suffix, inputTrimmed.length - suffix.length) !== -1; }); }; // If we are ignoring linter errors, replace the input with empty string // if it doesn't already at least start or end a multi-line comment if (state.ignoreLinterErrors === true) { if (!startsWith("/*", "//") && !(this.inComment && endsWith("*/"))) { this.input = ""; } } char = this.scanNonBreakingSpaces(); if (char >= 0) { this.trigger("warning", { code: "W125", line: this.line, character: char + 1 }); } this.input = this.input.replace(/\t/g, state.tab); char = this.scanUnsafeChars(); if (char >= 0) { this.trigger("warning", { code: "W100", line: this.line, character: char }); } // If there is a limit on line length, warn when lines get too // long. if (state.option.maxlen && state.option.maxlen < this.input.length) { var inComment = this.inComment || startsWith.call(inputTrimmed, "//") || startsWith.call(inputTrimmed, "/*"); var shouldTriggerError = !inComment || !reg.maxlenException.test(inputTrimmed); if (shouldTriggerError) { this.trigger("warning", { code: "W101", line: this.line, character: this.input.length }); } } return true; }, /* * This is simply a synonym for nextLine() method with a friendlier * public name. */ start: function() { this.nextLine(); }, /* * Produce the next token. This function is called by advance() to get * the next token. It returns a token in a JSLint-compatible format. */ token: function() { /*jshint loopfunc:true */ var checks = asyncTrigger(); var token; function isReserved(token, isProperty) { if (!token.reserved) { return false; } var meta = token.meta; if (meta && meta.isFutureReservedWord && state.inES5()) { // ES3 FutureReservedWord in an ES5 environment. if (!meta.es5) { return false; } // Some ES5 FutureReservedWord identifiers are active only // within a strict mode environment. if (meta.strictOnly) { if (!state.option.strict && !state.isStrict()) { return false; } } if (isProperty) { return false; } } return true; } // Produce a token object. var create = function(type, value, isProperty, token) { /*jshint validthis:true */ var obj; if (type !== "(endline)" && type !== "(end)") { this.prereg = false; } if (type === "(punctuator)") { switch (value) { case ".": case ")": case "~": case "#": case "]": case "++": case "--": this.prereg = false; break; default: this.prereg = true; } obj = Object.create(state.syntax[value] || state.syntax["(error)"]); } if (type === "(identifier)") { if (value === "return" || value === "case" || value === "typeof") { this.prereg = true; } if (_.has(state.syntax, value)) { obj = Object.create(state.syntax[value] || state.syntax["(error)"]); // If this can't be a reserved keyword, reset the object. if (!isReserved(obj, isProperty && type === "(identifier)")) { obj = null; } } } if (!obj) { obj = Object.create(state.syntax[type]); } obj.identifier = (type === "(identifier)"); obj.type = obj.type || type; obj.value = value; obj.line = this.line; obj.character = this.char; obj.from = this.from; if (obj.identifier && token) obj.raw_text = token.text || token.value; if (token && token.startLine && token.startLine !== this.line) { obj.startLine = token.startLine; } if (token && token.context) { // Context of current token obj.context = token.context; } if (token && token.depth) { // Nested template depth obj.depth = token.depth; } if (token && token.isUnclosed) { // Mark token as unclosed string / template literal obj.isUnclosed = token.isUnclosed; } if (isProperty && obj.identifier) { obj.isProperty = isProperty; } obj.check = checks.check; return obj; }.bind(this); for (;;) { if (!this.input.length) { if (this.nextLine()) { return create("(endline)", ""); } if (this.exhausted) { return null; } this.exhausted = true; return create("(end)", ""); } token = this.next(checks); if (!token) { if (this.input.length) { // Unexpected character. this.trigger("error", { code: "E024", line: this.line, character: this.char, data: [ this.peek() ] }); this.input = ""; } continue; } switch (token.type) { case Token.StringLiteral: this.triggerAsync("String", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value, quote: token.quote }, checks, function() { return true; }); return create("(string)", token.value, null, token); case Token.TemplateHead: this.trigger("TemplateHead", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value }); return create("(template)", token.value, null, token); case Token.TemplateMiddle: this.trigger("TemplateMiddle", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value }); return create("(template middle)", token.value, null, token); case Token.TemplateTail: this.trigger("TemplateTail", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value }); return create("(template tail)", token.value, null, token); case Token.NoSubstTemplate: this.trigger("NoSubstTemplate", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value }); return create("(no subst template)", token.value, null, token); case Token.Identifier: this.trigger("Identifier", { line: this.line, char: this.char, from: this.form, name: token.value, raw_name: token.text, isProperty: state.tokens.curr.id === "." }); /* falls through */ case Token.Keyword: case Token.NullLiteral: case Token.BooleanLiteral: return create("(identifier)", token.value, state.tokens.curr.id === ".", token); case Token.NumericLiteral: if (token.isMalformed) { this.trigger("warning", { code: "W045", line: this.line, character: this.char, data: [ token.value ] }); } this.triggerAsync("warning", { code: "W114", line: this.line, character: this.char, data: [ "0x-" ] }, checks, function() { return token.base === 16 && state.jsonMode; }); this.triggerAsync("warning", { code: "W115", line: this.line, character: this.char }, checks, function() { return state.isStrict() && token.base === 8 && token.isLegacy; }); this.trigger("Number", { line: this.line, char: this.char, from: this.from, value: token.value, base: token.base, isMalformed: token.malformed }); return create("(number)", token.value); case Token.RegExp: return create("(regexp)", token.value); case Token.Comment: state.tokens.curr.comment = true; if (token.isSpecial) { return { id: '(comment)', value: token.value, body: token.body, type: token.commentType, isSpecial: token.isSpecial, line: this.line, character: this.char, from: this.from }; } break; case "": break; default: return create("(punctuator)", token.value); } } } }; exports.Lexer = Lexer; exports.Context = Context; },{"../data/ascii-identifier-data.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/data/ascii-identifier-data.js","../data/non-ascii-identifier-part-only.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/data/non-ascii-identifier-part-only.js","../data/non-ascii-identifier-start.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/data/non-ascii-identifier-start.js","./reg.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/reg.js","./state.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/state.js","events":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/events/events.js","lodash":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/lodash/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/messages.js":[function(require,module,exports){ "use strict"; var _ = require("lodash"); var errors = { // JSHint options E001: "Bad option: '{a}'.", E002: "Bad option value.", // JSHint input E003: "Expected a JSON value.", E004: "Input is neither a string nor an array of strings.", E005: "Input is empty.", E006: "Unexpected early end of program.", // Strict mode E007: "Missing \"use strict\" statement.", E008: "Strict violation.", E009: "Option 'validthis' can't be used in a global scope.", E010: "'with' is not allowed in strict mode.", // Constants E011: "const '{a}' has already been declared.", E012: "const '{a}' is initialized to 'undefined'.", E013: "Attempting to override '{a}' which is a constant.", // Regular expressions E014: "A regular expression literal can be confused with '/='.", E015: "Unclosed regular expression.", E016: "Invalid regular expression.", // Tokens E017: "Unclosed comment.", E018: "Unbegun comment.", E019: "Unmatched '{a}'.", E020: "Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.", E021: "Expected '{a}' and instead saw '{b}'.", E022: "Line breaking error '{a}'.", E023: "Missing '{a}'.", E024: "Unexpected '{a}'.", E025: "Missing ':' on a case clause.", E026: "Missing '}' to match '{' from line {a}.", E027: "Missing ']' to match '[' from line {a}.", E028: "Illegal comma.", E029: "Unclosed string.", // Everything else E030: "Expected an identifier and instead saw '{a}'.", E031: "Bad assignment.", // FIXME: Rephrase E032: "Expected a small integer or 'false' and instead saw '{a}'.", E033: "Expected an operator and instead saw '{a}'.", E034: "get/set are ES5 features.", E035: "Missing property name.", E036: "Expected to see a statement and instead saw a block.", E037: null, E038: null, E039: "Function declarations are not invocable. Wrap the whole function invocation in parens.", E040: "Each value should have its own case label.", E041: "Unrecoverable syntax error.", E042: "Stopping.", E043: "Too many errors.", E044: null, E045: "Invalid for each loop.", E046: "A yield statement shall be within a generator function (with syntax: `function*`)", E047: null, // Vacant E048: "{a} declaration not directly within block.", E049: "A {a} cannot be named '{b}'.", E050: "Mozilla requires the yield expression to be parenthesized here.", E051: "Regular parameters cannot come after default parameters.", E052: "Unclosed template literal.", E053: "Export declaration must be in global scope.", E054: "Class properties must be methods. Expected '(' but instead saw '{a}'.", E055: "The '{a}' option cannot be set after any executable code." }; var warnings = { W001: "'hasOwnProperty' is a really bad name.", W002: "Value of '{a}' may be overwritten in IE 8 and earlier.", W003: "'{a}' was used before it was defined.", W004: "'{a}' is already defined.", W005: "A dot following a number can be confused with a decimal point.", W006: "Confusing minuses.", W007: "Confusing plusses.", W008: "A leading decimal point can be confused with a dot: '{a}'.", W009: "The array literal notation [] is preferable.", W010: "The object literal notation {} is preferable.", W011: null, W012: null, W013: null, W014: "Bad line breaking before '{a}'.", W015: null, W016: "Unexpected use of '{a}'.", W017: "Bad operand.", W018: "Confusing use of '{a}'.", W019: "Use the isNaN function to compare with NaN.", W020: "Read only.", W021: "'{a}' is a function.", W022: "Do not assign to the exception parameter.", W023: "Expected an identifier in an assignment and instead saw a function invocation.", W024: "Expected an identifier and instead saw '{a}' (a reserved word).", W025: "Missing name in function declaration.", W026: "Inner functions should be listed at the top of the outer function.", W027: "Unreachable '{a}' after '{b}'.", W028: "Label '{a}' on {b} statement.", W030: "Expected an assignment or function call and instead saw an expression.", W031: "Do not use 'new' for side effects.", W032: "Unnecessary semicolon.", W033: "Missing semicolon.", W034: "Unnecessary directive \"{a}\".", W035: "Empty block.", W036: "Unexpected /*member '{a}'.", W037: "'{a}' is a statement label.", W038: "'{a}' used out of scope.", W039: "'{a}' is not allowed.", W040: "Possible strict violation.", W041: "Use '{a}' to compare with '{b}'.", W042: "Avoid EOL escaping.", W043: "Bad escaping of EOL. Use option multistr if needed.", W044: "Bad or unnecessary escaping.", /* TODO(caitp): remove W044 */ W045: "Bad number '{a}'.", W046: "Don't use extra leading zeros '{a}'.", W047: "A trailing decimal point can be confused with a dot: '{a}'.", W048: "Unexpected control character in regular expression.", W049: "Unexpected escaped character '{a}' in regular expression.", W050: "JavaScript URL.", W051: "Variables should not be deleted.", W052: "Unexpected '{a}'.", W053: "Do not use {a} as a constructor.", W054: "The Function constructor is a form of eval.", W055: "A constructor name should start with an uppercase letter.", W056: "Bad constructor.", W057: "Weird construction. Is 'new' necessary?", W058: "Missing '()' invoking a constructor.", W059: "Avoid arguments.{a}.", W060: "document.write can be a form of eval.", W061: "eval can be harmful.", W062: "Wrap an immediate function invocation in parens " + "to assist the reader in understanding that the expression " + "is the result of a function, and not the function itself.", W063: "Math is not a function.", W064: "Missing 'new' prefix when invoking a constructor.", W065: "Missing radix parameter.", W066: "Implied eval. Consider passing a function instead of a string.", W067: "Bad invocation.", W068: "Wrapping non-IIFE function literals in parens is unnecessary.", W069: "['{a}'] is better written in dot notation.", W070: "Extra comma. (it breaks older versions of IE)", W071: "This function has too many statements. ({a})", W072: "This function has too many parameters. ({a})", W073: "Blocks are nested too deeply. ({a})", W074: "This function's cyclomatic complexity is too high. ({a})", W075: "Duplicate {a} '{b}'.", W076: "Unexpected parameter '{a}' in get {b} function.", W077: "Expected a single parameter in set {a} function.", W078: "Setter is defined without getter.", W079: "Redefinition of '{a}'.", W080: "It's not necessary to initialize '{a}' to 'undefined'.", W081: null, W082: "Function declarations should not be placed in blocks. " + "Use a function expression or move the statement to the top of " + "the outer function.", W083: "Don't make functions within a loop.", W084: "Expected a conditional expression and instead saw an assignment.", W085: "Don't use 'with'.", W086: "Expected a 'break' statement before '{a}'.", W087: "Forgotten 'debugger' statement?", W088: "Creating global 'for' variable. Should be 'for (var {a} ...'.", W089: "The body of a for in should be wrapped in an if statement to filter " + "unwanted properties from the prototype.", W090: "'{a}' is not a statement label.", W091: "'{a}' is out of scope.", W093: "Did you mean to return a conditional instead of an assignment?", W094: "Unexpected comma.", W095: "Expected a string and instead saw {a}.", W096: "The '{a}' key may produce unexpected results.", W097: "Use the function form of \"use strict\".", W098: "'{a}' is defined but never used.", W099: null, W100: "This character may get silently deleted by one or more browsers.", W101: "Line is too long.", W102: null, W103: "The '{a}' property is deprecated.", W104: "'{a}' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).", W105: "Unexpected {a} in '{b}'.", W106: "Identifier '{a}' is not in camel case.", W107: "Script URL.", W108: "Strings must use doublequote.", W109: "Strings must use singlequote.", W110: "Mixed double and single quotes.", W112: "Unclosed string.", W113: "Control character in string: {a}.", W114: "Avoid {a}.", W115: "Octal literals are not allowed in strict mode.", W116: "Expected '{a}' and instead saw '{b}'.", W117: "'{a}' is not defined.", W118: "'{a}' is only available in Mozilla JavaScript extensions (use moz option).", W119: "'{a}' is only available in ES6 (use esnext option).", W120: "You might be leaking a variable ({a}) here.", W121: "Extending prototype of native object: '{a}'.", W122: "Invalid typeof value '{a}'", W123: "'{a}' is already defined in outer scope.", W124: "A generator function shall contain a yield statement.", W125: "This line contains non-breaking spaces: http://jshint.com/doc/options/#nonbsp", W126: "Unnecessary grouping operator.", W127: "Unexpected use of a comma operator.", W128: "Empty array elements require elision=true.", W129: "'{a}' is defined in a future version of JavaScript. Use a " + "different variable name to avoid migration issues.", W130: "Invalid element after rest element.", W131: "Invalid parameter after rest parameter.", W132: "`var` declarations are forbidden. Use `let` or `const` instead.", W133: "Invalid for-{a} loop left-hand-side: {b}.", W134: "The '{a}' option is only available when linting ECMAScript {b} code." }; var info = { I001: "Comma warnings can be turned off with 'laxcomma'.", I002: null, I003: "ES5 option is now set per default" }; exports.errors = {}; exports.warnings = {}; exports.info = {}; _.each(errors, function(desc, code) { exports.errors[code] = { code: code, desc: desc }; }); _.each(warnings, function(desc, code) { exports.warnings[code] = { code: code, desc: desc }; }); _.each(info, function(desc, code) { exports.info[code] = { code: code, desc: desc }; }); },{"lodash":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/lodash/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/name-stack.js":[function(require,module,exports){ "use strict"; function NameStack() { this._stack = []; } Object.defineProperty(NameStack.prototype, "length", { get: function() { return this._stack.length; } }); /** * Create a new entry in the stack. Useful for tracking names across * expressions. */ NameStack.prototype.push = function() { this._stack.push(null); }; /** * Discard the most recently-created name on the stack. */ NameStack.prototype.pop = function() { this._stack.pop(); }; /** * Update the most recent name on the top of the stack. * * @param {object} token The token to consider as the source for the most * recent name. */ NameStack.prototype.set = function(token) { this._stack[this.length - 1] = token; }; /** * Generate a string representation of the most recent name. * * @returns {string} */ NameStack.prototype.infer = function() { var nameToken = this._stack[this.length - 1]; var prefix = ""; var type; // During expected operation, the topmost entry on the stack will only // reflect the current function's name when the function is declared without // the `function` keyword (i.e. for in-line accessor methods). In other // cases, the `function` expression itself will introduce an empty entry on // the top of the stack, and this should be ignored. if (!nameToken || nameToken.type === "class") { nameToken = this._stack[this.length - 2]; } if (!nameToken) { return "(empty)"; } type = nameToken.type; if (type !== "(string)" && type !== "(number)" && type !== "(identifier)" && type !== "default") { return "(expression)"; } if (nameToken.accessorType) { prefix = nameToken.accessorType + " "; } return prefix + nameToken.value; }; module.exports = NameStack; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/options.js":[function(require,module,exports){ "use strict"; // These are the JSHint boolean options. exports.bool = { enforcing: { /** * This option prohibits the use of bitwise operators such as `^` (XOR), * `|` (OR) and others. Bitwise operators are very rare in JavaScript * programs and quite often `&` is simply a mistyped `&&`. */ bitwise : true, /** * * This options prohibits overwriting prototypes of native objects such as * `Array`, `Date` and so on. * * // jshint freeze:true * Array.prototype.count = function (value) { return 4; }; * // -> Warning: Extending prototype of native object: 'Array'. */ freeze : true, /** * This option allows you to force all variable names to use either * camelCase style or UPPER_CASE with underscores. * * @deprecated JSHint is limiting its scope to issues of code correctness. * If you would like to enforce rules relating to code style, * check out [the JSCS * project](https://github.com/jscs-dev/node-jscs). */ camelcase : true, /** * This option requires you to always put curly braces around blocks in * loops and conditionals. JavaScript allows you to omit curly braces when * the block consists of only one statement, for example: * * while (day) * shuffle(); * * However, in some circumstances, it can lead to bugs (you'd think that * `sleep()` is a part of the loop while in reality it is not): * * while (day) * shuffle(); * sleep(); */ curly : true, /** * This options prohibits the use of `==` and `!=` in favor of `===` and * `!==`. The former try to coerce values before comparing them which can * lead to some unexpected results. The latter don't do any coercion so * they are generally safer. If you would like to learn more about type * coercion in JavaScript, we recommend [Truth, Equality and * JavaScript](http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/) * by Angus Croll. */ eqeqeq : true, /** * This option enables warnings about the use of identifiers which are * defined in future versions of JavaScript. Although overwriting them has * no effect in contexts where they are not implemented, this practice can * cause issues when migrating codebases to newer versions of the language. */ futurehostile: true, /** * This option suppresses warnings about invalid `typeof` operator values. * This operator has only [a limited set of possible return * values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof). * By default, JSHint warns when you compare its result with an invalid * value which often can be a typo. * * // 'fuction' instead of 'function' * if (typeof a == "fuction") { // Invalid typeof value 'fuction' * // ... * } * * Do not use this option unless you're absolutely sure you don't want * these checks. */ notypeof : true, /** * This option tells JSHint that your code needs to adhere to ECMAScript 3 * specification. Use this option if you need your program to be executable * in older browsers—such as Internet Explorer 6/7/8/9—and other legacy * JavaScript environments. */ es3 : true, /** * This option enables syntax first defined in [the ECMAScript 5.1 * specification](http://es5.github.io/). This includes allowing reserved * keywords as object properties. */ es5 : true, /** * This option requires all `for in` loops to filter object's items. The * for in statement allows for looping through the names of all of the * properties of an object including those inherited through the prototype * chain. This behavior can lead to unexpected items in your object so it * is generally safer to always filter inherited properties out as shown in * the example: * * for (key in obj) { * if (obj.hasOwnProperty(key)) { * // We are sure that obj[key] belongs to the object and was not inherited. * } * } * * For more in-depth understanding of `for in` loops in JavaScript, read * [Exploring JavaScript for-in * loops](http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/) * by Angus Croll. */ forin : true, /** * This option suppresses warnings about declaring variables inside of * control * structures while accessing them later from the outside. Even though * JavaScript has only two real scopes—global and function—such practice * leads to confusion among people new to the language and hard-to-debug * bugs. This is why, by default, JSHint warns about variables that are * used outside of their intended scope. * * function test() { * if (true) { * var x = 0; * } * * x += 1; // Default: 'x' used out of scope. * // No warning when funcscope:true * } */ funcscope : true, /** * This option prohibits the use of immediate function invocations without * wrapping them in parentheses. Wrapping parentheses assists readers of * your code in understanding that the expression is the result of a * function, and not the function itself. * * @deprecated JSHint is limiting its scope to issues of code correctness. * If you would like to enforce rules relating to code style, * check out [the JSCS * project](https://github.com/jscs-dev/node-jscs). */ immed : true, /** * This option suppresses warnings about the `__iterator__` property. This * property is not supported by all browsers so use it carefully. */ iterator : true, /** * This option requires you to capitalize names of constructor functions. * Capitalizing functions that are intended to be used with `new` operator * is just a convention that helps programmers to visually distinguish * constructor functions from other types of functions to help spot * mistakes when using `this`. * * Not doing so won't break your code in any browsers or environments but * it will be a bit harder to figure out—by reading the code—if the * function was supposed to be used with or without new. And this is * important because when the function that was intended to be used with * `new` is used without it, `this` will point to the global object instead * of a new object. * * @deprecated JSHint is limiting its scope to issues of code correctness. * If you would like to enforce rules relating to code style, * check out [the JSCS * project](https://github.com/jscs-dev/node-jscs). */ newcap : true, /** * This option prohibits the use of `arguments.caller` and * `arguments.callee`. Both `.caller` and `.callee` make quite a few * optimizations impossible so they were deprecated in future versions of * JavaScript. In fact, ECMAScript 5 forbids the use of `arguments.callee` * in strict mode. */ noarg : true, /** * This option prohibits the use of the comma operator. When misused, the * comma operator can obscure the value of a statement and promote * incorrect code. */ nocomma : true, /** * This option warns when you have an empty block in your code. JSLint was * originally warning for all empty blocks and we simply made it optional. * There were no studies reporting that empty blocks in JavaScript break * your code in any way. * * @deprecated JSHint is limiting its scope to issues of code correctness. * If you would like to enforce rules relating to code style, * check out [the JSCS * project](https://github.com/jscs-dev/node-jscs). */ noempty : true, /** * This option warns about "non-breaking whitespace" characters. These * characters can be entered with option-space on Mac computers and have a * potential of breaking non-UTF8 web pages. */ nonbsp : true, /** * This option prohibits the use of constructor functions for side-effects. * Some people like to call constructor functions without assigning its * result to any variable: * * new MyConstructor(); * * There is no advantage in this approach over simply calling * `MyConstructor` since the object that the operator `new` creates isn't * used anywhere so you should generally avoid constructors like this one. */ nonew : true, /** * This option prohibits the use of explicitly undeclared variables. This * option is very useful for spotting leaking and mistyped variables. * * // jshint undef:true * * function test() { * var myVar = 'Hello, World'; * console.log(myvar); // Oops, typoed here. JSHint with undef will complain * } * * If your variable is defined in another file, you can use the `global` * directive to tell JSHint about it. */ undef : true, /** * This option prohibits the use of the grouping operator when it is not * strictly required. Such usage commonly reflects a misunderstanding of * unary operators, for example: * * // jshint singleGroups: true * * delete(obj.attr); // Warning: Unnecessary grouping operator. */ singleGroups: false, /** * This option requires all functions to run in ECMAScript 5's strict mode. * [Strict mode](https://developer.mozilla.org/en/JavaScript/Strict_mode) * is a way to opt in to a restricted variant of JavaScript. Strict mode * eliminates some JavaScript pitfalls that didn't cause errors by changing * them to produce errors. It also fixes mistakes that made it difficult * for the JavaScript engines to perform certain optimizations. * * *Note:* This option enables strict mode for function scope only. It * *prohibits* the global scoped strict mode because it might break * third-party widgets on your page. If you really want to use global * strict mode, see the *globalstrict* option. */ strict : true, /** * When set to true, the use of VariableStatements are forbidden. * For example: * * // jshint varstmt: true * * var a; // Warning: `var` declarations are forbidden. Use `let` or `const` instead. */ varstmt: false, /** * This option is a short hand for the most strict JSHint configuration as * available in JSHint version 2.6.3. It enables all enforcing options and * disables all relaxing options that were defined in that release. * * @deprecated The option cannot be maintained without automatically opting * users in to new features. This can lead to unexpected * warnings/errors in when upgrading between minor versions of * JSHint. */ enforceall : false }, relaxing: { /** * This option suppresses warnings about missing semicolons. There is a lot * of FUD about semicolon spread by quite a few people in the community. * The common myths are that semicolons are required all the time (they are * not) and that they are unreliable. JavaScript has rules about semicolons * which are followed by *all* browsers so it is up to you to decide * whether you should or should not use semicolons in your code. * * For more information about semicolons in JavaScript read [An Open Letter * to JavaScript Leaders Regarding * Semicolons](http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding) * by Isaac Schlueter and [JavaScript Semicolon * Insertion](http://inimino.org/~inimino/blog/javascript_semicolons). */ asi : true, /** * This option suppresses warnings about multi-line strings. Multi-line * strings can be dangerous in JavaScript because all hell breaks loose if * you accidentally put a whitespace in between the escape character (`\`) * and a new line. * * Note that even though this option allows correct multi-line strings, it * still warns about multi-line strings without escape characters or with * anything in between the escape character and a whitespace. * * // jshint multistr:true * * var text = "Hello\ * World"; // All good. * * text = "Hello * World"; // Warning, no escape character. * * text = "Hello\ * World"; // Warning, there is a space after \ * * @deprecated JSHint is limiting its scope to issues of code correctness. * If you would like to enforce rules relating to code style, * check out [the JSCS * project](https://github.com/jscs-dev/node-jscs). */ multistr : true, /** * This option suppresses warnings about the `debugger` statements in your * code. */ debug : true, /** * This option suppresses warnings about the use of assignments in cases * where comparisons are expected. More often than not, code like `if (a = * 10) {}` is a typo. However, it can be useful in cases like this one: * * for (var i = 0, person; person = people[i]; i++) {} * * You can silence this error on a per-use basis by surrounding the assignment * with parenthesis, such as: * * for (var i = 0, person; (person = people[i]); i++) {} */ boss : true, /** * This option suppresses warnings about the use of `eval`. The use of * `eval` is discouraged because it can make your code vulnerable to * various injection attacks and it makes it hard for JavaScript * interpreter to do certain optimizations. */ evil : true, /** * This option suppresses warnings about the use of global strict mode. * Global strict mode can break third-party widgets so it is not * recommended. * * For more info about strict mode see the `strict` option. */ globalstrict: true, /** * This option prohibits the use of unary increment and decrement * operators. Some people think that `++` and `--` reduces the quality of * their coding styles and there are programming languages—such as * Python—that go completely without these operators. */ plusplus : true, /** * This option suppresses warnings about the `__proto__` property. */ proto : true, /** * This option suppresses warnings about the use of script-targeted * URLs—such as `javascript:...`. */ scripturl : true, /** * This option suppresses warnings about using `[]` notation when it can be * expressed in dot notation: `person['name']` vs. `person.name`. * * @deprecated JSHint is limiting its scope to issues of code correctness. * If you would like to enforce rules relating to code style, * check out [the JSCS * project](https://github.com/jscs-dev/node-jscs). */ sub : true, /** * This option suppresses warnings about "weird" constructions like * `new function () { ... }` and `new Object;`. Such constructions are * sometimes used to produce singletons in JavaScript: * * var singleton = new function() { * var privateVar; * * this.publicMethod = function () {} * this.publicMethod2 = function () {} * }; */ supernew : true, /** * This option suppresses most of the warnings about possibly unsafe line * breakings in your code. It doesn't suppress warnings about comma-first * coding style. To suppress those you have to use `laxcomma` (see below). * * @deprecated JSHint is limiting its scope to issues of code correctness. * If you would like to enforce rules relating to code style, * check out [the JSCS * project](https://github.com/jscs-dev/node-jscs). */ laxbreak : true, /** * This option suppresses warnings about comma-first coding style: * * var obj = { * name: 'Anton' * , handle: 'valueof' * , role: 'SW Engineer' * }; * * @deprecated JSHint is limiting its scope to issues of code correctness. * If you would like to enforce rules relating to code style, * check out [the JSCS * project](https://github.com/jscs-dev/node-jscs). */ laxcomma : true, /** * This option suppresses warnings about possible strict violations when * the code is running in strict mode and you use `this` in a * non-constructor function. You should use this option—in a function scope * only—when you are positive that your use of `this` is valid in the * strict mode (for example, if you call your function using * `Function.call`). * * **Note:** This option can be used only inside of a function scope. * JSHint will fail with an error if you will try to set this option * globally. */ validthis : true, /** * This option suppresses warnings about the use of the `with` statement. * The semantics of the `with` statement can cause confusion among * developers and accidental definition of global variables. * * More info: * * * [with Statement Considered * Harmful](http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/) */ withstmt : true, /** * This options tells JSHint that your code uses Mozilla JavaScript * extensions. Unless you develop specifically for the Firefox web browser * you don't need this option. * * More info: * * * [New in JavaScript * 1.7](https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7) */ moz : true, /** * This option suppresses warnings about generator functions with no * `yield` statement in them. */ noyield : true, /** * This option suppresses warnings about `== null` comparisons. Such * comparisons are often useful when you want to check if a variable is * `null` or `undefined`. */ eqnull : true, /** * This option suppresses warnings about missing semicolons, but only when * the semicolon is omitted for the last statement in a one-line block: * * var name = (function() { return 'Anton' }()); * * This is a very niche use case that is useful only when you use automatic * JavaScript code generators. */ lastsemic : true, /** * This option suppresses warnings about functions inside of loops. * Defining functions inside of loops can lead to bugs such as this one: * * var nums = []; * * for (var i = 0; i < 10; i++) { * nums[i] = function (j) { * return i + j; * }; * } * * nums[0](2); // Prints 12 instead of 2 * * To fix the code above you need to copy the value of `i`: * * var nums = []; * * for (var i = 0; i < 10; i++) { * (function (i) { * nums[i] = function (j) { * return i + j; * }; * }(i)); * } */ loopfunc : true, /** * This option suppresses warnings about the use of expressions where * normally you would expect to see assignments or function calls. Most of * the time, such code is a typo. However, it is not forbidden by the spec * and that's why this warning is optional. */ expr : true, /** * This option tells JSHint that your code uses ECMAScript 6 specific * syntax. Note that these features are not finalized yet and not all * browsers implement them. * * More info: * * * [Draft Specification for ES.next (ECMA-262 Ed. * 6)](http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts) */ esnext : true, /** * This option tells JSHint that your code uses ES3 array elision elements, * or empty elements (for example, `[1, , , 4, , , 7]`). */ elision : true, }, // Third party globals environments: { /** * This option defines globals exposed by the * [MooTools](http://mootools.net/) JavaScript framework. */ mootools : true, /** * This option defines globals exposed by * [CouchDB](http://couchdb.apache.org/). CouchDB is a document-oriented * database that can be queried and indexed in a MapReduce fashion using * JavaScript. */ couch : true, /** * This option defines globals exposed by [the Jasmine unit testing * framework](https://jasmine.github.io/). */ jasmine : true, /** * This option defines globals exposed by the [jQuery](http://jquery.com/) * JavaScript library. */ jquery : true, /** * This option defines globals available when your code is running inside * of the Node runtime environment. [Node.js](http://nodejs.org/) is a * server-side JavaScript environment that uses an asynchronous * event-driven model. This option also skips some warnings that make sense * in the browser environments but don't make sense in Node such as * file-level `use strict` pragmas and `console.log` statements. */ node : true, /** * This option defines globals exposed by [the QUnit unit testing * framework](http://qunitjs.com/). */ qunit : true, /** * This option defines globals available when your code is running inside * of the Rhino runtime environment. [Rhino](http://www.mozilla.org/rhino/) * is an open-source implementation of JavaScript written entirely in Java. */ rhino : true, /** * This option defines globals exposed by [the ShellJS * library](http://documentup.com/arturadib/shelljs). */ shelljs : true, /** * This option defines globals exposed by the * [Prototype](http://www.prototypejs.org/) JavaScript framework. */ prototypejs : true, /** * This option defines globals exposed by the [YUI](http://yuilibrary.com/) * JavaScript framework. */ yui : true, /** * This option defines globals exposed by the "BDD" and "TDD" UIs of the * [Mocha unit testing framework](http://mochajs.org/). */ mocha : true, /** * This option informs JSHint that the input code describes an ECMAScript 6 * module. All module code is interpreted as strict mode code. */ module : true, /** * This option defines globals available when your code is running as a * script for the [Windows Script * Host](http://en.wikipedia.org/wiki/Windows_Script_Host). */ wsh : true, /** * This option defines globals available when your code is running inside * of a Web Worker. [Web * Workers](https://developer.mozilla.org/en/Using_web_workers) provide a * simple means for web content to run scripts in background threads. */ worker : true, /** * This option defines non-standard but widely adopted globals such as * `escape` and `unescape`. */ nonstandard : true, /** * This option defines globals exposed by modern browsers: all the way from * good old `document` and `navigator` to the HTML5 `FileReader` and other * new developments in the browser world. * * **Note:** This option doesn't expose variables like `alert` or * `console`. See option `devel` for more information. */ browser : true, /** * This option defines globals available when using [the Browserify * tool](http://browserify.org/) to build a project. */ browserify : true, /** * This option defines globals that are usually used for logging poor-man's * debugging: `console`, `alert`, etc. It is usually a good idea to not * ship them in production because, for example, `console.log` breaks in * legacy versions of Internet Explorer. */ devel : true, /** * This option defines globals exposed by the [Dojo * Toolkit](http://dojotoolkit.org/). */ dojo : true, /** * This option defines globals for typed array constructors. * * More info: * * * [JavaScript typed * arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) */ typed : true, /** * This option defines globals available when your core is running inside * of the PhantomJS runtime environment. [PhantomJS](http://phantomjs.org/) * is a headless WebKit scriptable with a JavaScript API. It has fast and * native support for various web standards: DOM handling, CSS selector, * JSON, Canvas, and SVG. */ phantom : true }, // Obsolete options obsolete: { onecase : true, // if one case switch statements should be allowed regexp : true, // if the . should not be allowed in regexp literals regexdash : true // if unescaped first/last dash (-) inside brackets // should be tolerated } }; // These are the JSHint options that can take any value // (we use this object to detect invalid options) exports.val = { /** * This option lets you set the maximum length of a line. * * @deprecated JSHint is limiting its scope to issues of code correctness. If * you would like to enforce rules relating to code style, check * out [the JSCS project](https://github.com/jscs-dev/node-jscs). */ maxlen : false, /** * This option sets a specific tab width for your code. * * @deprecated JSHint is limiting its scope to issues of code correctness. If * you would like to enforce rules relating to code style, check * out [the JSCS project](https://github.com/jscs-dev/node-jscs). */ indent : false, /** * This options allows you to set the maximum amount of warnings JSHint will * produce before giving up. Default is 50. */ maxerr : false, predef : false, // predef is deprecated and being replaced by globals /** * This option can be used to specify a white list of global variables that * are not formally defined in the source code. This is most useful when * combined with the `undef` option in order to suppress warnings for * project-specific global variables. * * Setting an entry to `true` enables reading and writing to that variable. * Setting it to `false` will trigger JSHint to consider that variable * read-only. * * See also the "environment" options: a set of options to be used as short * hand for enabling global variables defined in common JavaScript * environments. */ globals : false, /** * This option enforces the consistency of quotation marks used throughout * your code. It accepts three values: `true` if you don't want to enforce * one particular style but want some consistency, `"single"` if you want to * allow only single quotes and `"double"` if you want to allow only double * quotes. * * @deprecated JSHint is limiting its scope to issues of code correctness. If * you would like to enforce rules relating to code style, check * out [the JSCS project](https://github.com/jscs-dev/node-jscs). */ quotmark : false, scope : false, /** * This option lets you set the max number of statements allowed per function: * * // jshint maxstatements:4 * * function main() { * var i = 0; * var j = 0; * * // Function declarations count as one statement. Their bodies * // don't get taken into account for the outer function. * function inner() { * var i2 = 1; * var j2 = 1; * * return i2 + j2; * } * * j = i + j; * return j; // JSHint: Too many statements per function. (5) * } */ maxstatements: false, /** * This option lets you control how nested do you want your blocks to be: * * // jshint maxdepth:2 * * function main(meaning) { * var day = true; * * if (meaning === 42) { * while (day) { * shuffle(); * * if (tired) { // JSHint: Blocks are nested too deeply (3). * sleep(); * } * } * } * } */ maxdepth : false, /** * This option lets you set the max number of formal parameters allowed per * function: * * // jshint maxparams:3 * * function login(request, onSuccess) { * // ... * } * * // JSHint: Too many parameters per function (4). * function logout(request, isManual, whereAmI, onSuccess) { * // ... * } */ maxparams : false, /** * This option lets you control cyclomatic complexity throughout your code. * Cyclomatic complexity measures the number of linearly independent paths * through a program's source code. Read more about [cyclomatic complexity on * Wikipedia](http://en.wikipedia.org/wiki/Cyclomatic_complexity). */ maxcomplexity: false, /** * This option suppresses warnings about variable shadowing i.e. declaring a * variable that had been already declared somewhere in the outer scope. * * - "inner" - check for variables defined in the same scope only * - "outer" - check for variables defined in outer scopes as well * - false - same as inner * - true - allow variable shadowing */ shadow : false, /** * This option warns when you define and never use your variables. It is very * useful for general code cleanup, especially when used in addition to * `undef`. * * // jshint unused:true * * function test(a, b) { * var c, d = 2; * * return a + d; * } * * test(1, 2); * * // Line 3: 'b' was defined but never used. * // Line 4: 'c' was defined but never used. * * In addition to that, this option will warn you about unused global * variables declared via the `global` directive. * * This can be set to `vars` to only check for variables, not function * parameters, or `strict` to check all variables and parameters. The * default (true) behavior is to allow unused parameters that are followed by * a used parameter. */ unused : true, /** * This option prohibits the use of a variable before it was defined. * JavaScript has function scope only and, in addition to that, all variables * are always moved—or hoisted— to the top of the function. This behavior can * lead to some very nasty bugs and that's why it is safer to always use * variable only after they have been explicitly defined. * * Setting this option to "nofunc" will allow function declarations to be * ignored. * * For more in-depth understanding of scoping and hoisting in JavaScript, * read [JavaScript Scoping and * Hoisting](http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting) * by Ben Cherry. */ latedef : false, ignore : false, // start/end ignoring lines of code, bypassing the lexer // start - start ignoring lines, including the current line // end - stop ignoring lines, starting on the next line // line - ignore warnings / errors for just a single line // (this option does not bypass the lexer) ignoreDelimiters: false // array of start/end delimiters used to ignore // certain chunks from code }; // These are JSHint boolean options which are shared with JSLint // where the definition in JSHint is opposite JSLint exports.inverted = { bitwise : true, forin : true, newcap : true, plusplus: true, regexp : true, undef : true, // Inverted and renamed, use JSHint name here eqeqeq : true, strict : true }; exports.validNames = Object.keys(exports.val) .concat(Object.keys(exports.bool.relaxing)) .concat(Object.keys(exports.bool.enforcing)) .concat(Object.keys(exports.bool.obsolete)) .concat(Object.keys(exports.bool.environments)); // These are JSHint boolean options which are shared with JSLint // where the name has been changed but the effect is unchanged exports.renamed = { eqeq : "eqeqeq", windows: "wsh", sloppy : "strict" }; exports.removed = { nomen: true, onevar: true, passfail: true, white: true, gcl: true, smarttabs: true, trailing: true }; // Add options here which should not be automatically enforced by // `enforceall`. exports.noenforceall = { varstmt: true, strict: true }; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/reg.js":[function(require,module,exports){ /* * Regular expressions. Some of these are stupidly long. */ /*jshint maxlen:1000 */ "use strict"; // Unsafe comment or string (ax) exports.unsafeString = /@cc|<\/?|script|\]\s*\]|<\s*!|</i; // Unsafe characters that are silently deleted by one or more browsers (cx) exports.unsafeChars = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; // Characters in strings that need escaping (nx and nxg) exports.needEsc = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; exports.needEscGlobal = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // Star slash (lx) exports.starSlash = /\*\//; // Identifier (ix) exports.identifier = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/; // JavaScript URL (jx) exports.javascriptURL = /^(?:javascript|jscript|ecmascript|vbscript|livescript)\s*:/i; // Catches /* falls through */ comments (ft) exports.fallsThrough = /^\s*\/\*\s*falls?\sthrough\s*\*\/\s*$/; // very conservative rule (eg: only one space between the start of the comment and the first character) // to relax the maxlen option exports.maxlenException = /^(?:(?:\/\/|\/\*|\*) ?)?[^ ]+$/; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/state.js":[function(require,module,exports){ "use strict"; var NameStack = require("./name-stack.js"); var state = { syntax: {}, /** * Determine if the code currently being linted is strict mode code. * * @returns {boolean} */ isStrict: function() { return this.directive["use strict"] || this.inClassBody || this.option.module; }, // Assumption: chronologically ES3 < ES5 < ES6/ESNext < Moz inMoz: function() { return this.option.moz && !this.option.esnext; }, /** * @param {object} options * @param {boolean} options.strict - When `true`, only consider ESNext when * in "esnext" code and *not* in "moz". */ inESNext: function(strict) { if (strict) { return !this.option.moz && this.option.esnext; } return this.option.moz || this.option.esnext; }, inES5: function() { return !this.option.es3; }, inES3: function() { return this.option.es3; }, reset: function() { this.tokens = { prev: null, next: null, curr: null }; this.option = {}; this.ignored = {}; this.directive = {}; this.jsonMode = false; this.jsonWarnings = []; this.lines = []; this.tab = ""; this.cache = {}; // Node.JS doesn't have Map. Sniff. this.ignoredLines = {}; this.forinifcheckneeded = false; this.nameStack = new NameStack(); this.inClassBody = false; // Blank out non-multi-line-commented lines when ignoring linter errors this.ignoreLinterErrors = false; } }; exports.state = state; },{"./name-stack.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/name-stack.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/style.js":[function(require,module,exports){ "use strict"; exports.register = function(linter) { // Check for properties named __proto__. This special property was // deprecated and then re-introduced for ES6. linter.on("Identifier", function style_scanProto(data) { if (linter.getOption("proto")) { return; } if (data.name === "__proto__") { linter.warn("W103", { line: data.line, char: data.char, data: [ data.name ] }); } }); // Check for properties named __iterator__. This is a special property // available only in browsers with JavaScript 1.7 implementation. linter.on("Identifier", function style_scanIterator(data) { if (linter.getOption("iterator")) { return; } if (data.name === "__iterator__") { linter.warn("W104", { line: data.line, char: data.char, data: [ data.name ] }); } }); // Check that all identifiers are using camelCase notation. // Exceptions: names like MY_VAR and _myVar. linter.on("Identifier", function style_scanCamelCase(data) { if (!linter.getOption("camelcase")) { return; } if (data.name.replace(/^_+|_+$/g, "").indexOf("_") > -1 && !data.name.match(/^[A-Z0-9_]*$/)) { linter.warn("W106", { line: data.line, char: data.from, data: [ data.name ] }); } }); // Enforce consistency in style of quoting. linter.on("String", function style_scanQuotes(data) { var quotmark = linter.getOption("quotmark"); var code; if (!quotmark) { return; } // If quotmark is set to 'single' warn about all double-quotes. if (quotmark === "single" && data.quote !== "'") { code = "W109"; } // If quotmark is set to 'double' warn about all single-quotes. if (quotmark === "double" && data.quote !== "\"") { code = "W108"; } // If quotmark is set to true, remember the first quotation style // and then warn about all others. if (quotmark === true) { if (!linter.getCache("quotmark")) { linter.setCache("quotmark", data.quote); } if (linter.getCache("quotmark") !== data.quote) { code = "W110"; } } if (code) { linter.warn(code, { line: data.line, char: data.char, }); } }); linter.on("Number", function style_scanNumbers(data) { if (data.value.charAt(0) === ".") { // Warn about a leading decimal point. linter.warn("W008", { line: data.line, char: data.char, data: [ data.value ] }); } if (data.value.substr(data.value.length - 1) === ".") { // Warn about a trailing decimal point. linter.warn("W047", { line: data.line, char: data.char, data: [ data.value ] }); } if (/^00+/.test(data.value)) { // Multiple leading zeroes. linter.warn("W046", { line: data.line, char: data.char, data: [ data.value ] }); } }); // Warn about script URLs. linter.on("String", function style_scanJavaScriptURLs(data) { var re = /^(?:javascript|jscript|ecmascript|vbscript|livescript)\s*:/i; if (linter.getOption("scripturl")) { return; } if (re.test(data.value)) { linter.warn("W107", { line: data.line, char: data.char }); } }); }; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/jshint/src/vars.js":[function(require,module,exports){ // jshint -W001 "use strict"; // Identifiers provided by the ECMAScript standard. exports.reservedVars = { arguments : false, NaN : false }; exports.ecmaIdentifiers = { 3: { Array : false, Boolean : false, Date : false, decodeURI : false, decodeURIComponent : false, encodeURI : false, encodeURIComponent : false, Error : false, "eval" : false, EvalError : false, Function : false, hasOwnProperty : false, isFinite : false, isNaN : false, Math : false, Number : false, Object : false, parseInt : false, parseFloat : false, RangeError : false, ReferenceError : false, RegExp : false, String : false, SyntaxError : false, TypeError : false, URIError : false }, 5: { JSON : false }, 6: { Map : false, Promise : false, Proxy : false, Reflect : false, Set : false, Symbol : false, WeakMap : false, WeakSet : false } }; // Global variables commonly provided by a web browser environment. exports.browser = { Audio : false, Blob : false, addEventListener : false, applicationCache : false, atob : false, blur : false, btoa : false, cancelAnimationFrame : false, CanvasGradient : false, CanvasPattern : false, CanvasRenderingContext2D: false, CSS : false, clearInterval : false, clearTimeout : false, close : false, closed : false, Comment : false, CustomEvent : false, DOMParser : false, defaultStatus : false, Document : false, document : false, DocumentFragment : false, Element : false, ElementTimeControl : false, Event : false, event : false, fetch : false, FileReader : false, FormData : false, focus : false, frames : false, getComputedStyle : false, HTMLElement : false, HTMLAnchorElement : false, HTMLBaseElement : false, HTMLBlockquoteElement: false, HTMLBodyElement : false, HTMLBRElement : false, HTMLButtonElement : false, HTMLCanvasElement : false, HTMLDirectoryElement : false, HTMLDivElement : false, HTMLDListElement : false, HTMLFieldSetElement : false, HTMLFontElement : false, HTMLFormElement : false, HTMLFrameElement : false, HTMLFrameSetElement : false, HTMLHeadElement : false, HTMLHeadingElement : false, HTMLHRElement : false, HTMLHtmlElement : false, HTMLIFrameElement : false, HTMLImageElement : false, HTMLInputElement : false, HTMLIsIndexElement : false, HTMLLabelElement : false, HTMLLayerElement : false, HTMLLegendElement : false, HTMLLIElement : false, HTMLLinkElement : false, HTMLMapElement : false, HTMLMenuElement : false, HTMLMetaElement : false, HTMLModElement : false, HTMLObjectElement : false, HTMLOListElement : false, HTMLOptGroupElement : false, HTMLOptionElement : false, HTMLParagraphElement : false, HTMLParamElement : false, HTMLPreElement : false, HTMLQuoteElement : false, HTMLScriptElement : false, HTMLSelectElement : false, HTMLStyleElement : false, HTMLTableCaptionElement: false, HTMLTableCellElement : false, HTMLTableColElement : false, HTMLTableElement : false, HTMLTableRowElement : false, HTMLTableSectionElement: false, HTMLTemplateElement : false, HTMLTextAreaElement : false, HTMLTitleElement : false, HTMLUListElement : false, HTMLVideoElement : false, history : false, Image : false, Intl : false, length : false, localStorage : false, location : false, matchMedia : false, MessageChannel : false, MessageEvent : false, MessagePort : false, MouseEvent : false, moveBy : false, moveTo : false, MutationObserver : false, name : false, Node : false, NodeFilter : false, NodeList : false, Notification : false, navigator : false, onbeforeunload : true, onblur : true, onerror : true, onfocus : true, onload : true, onresize : true, onunload : true, open : false, openDatabase : false, opener : false, Option : false, parent : false, print : false, Range : false, requestAnimationFrame : false, removeEventListener : false, resizeBy : false, resizeTo : false, screen : false, scroll : false, scrollBy : false, scrollTo : false, sessionStorage : false, setInterval : false, setTimeout : false, SharedWorker : false, status : false, SVGAElement : false, SVGAltGlyphDefElement: false, SVGAltGlyphElement : false, SVGAltGlyphItemElement: false, SVGAngle : false, SVGAnimateColorElement: false, SVGAnimateElement : false, SVGAnimateMotionElement: false, SVGAnimateTransformElement: false, SVGAnimatedAngle : false, SVGAnimatedBoolean : false, SVGAnimatedEnumeration: false, SVGAnimatedInteger : false, SVGAnimatedLength : false, SVGAnimatedLengthList: false, SVGAnimatedNumber : false, SVGAnimatedNumberList: false, SVGAnimatedPathData : false, SVGAnimatedPoints : false, SVGAnimatedPreserveAspectRatio: false, SVGAnimatedRect : false, SVGAnimatedString : false, SVGAnimatedTransformList: false, SVGAnimationElement : false, SVGCSSRule : false, SVGCircleElement : false, SVGClipPathElement : false, SVGColor : false, SVGColorProfileElement: false, SVGColorProfileRule : false, SVGComponentTransferFunctionElement: false, SVGCursorElement : false, SVGDefsElement : false, SVGDescElement : false, SVGDocument : false, SVGElement : false, SVGElementInstance : false, SVGElementInstanceList: false, SVGEllipseElement : false, SVGExternalResourcesRequired: false, SVGFEBlendElement : false, SVGFEColorMatrixElement: false, SVGFEComponentTransferElement: false, SVGFECompositeElement: false, SVGFEConvolveMatrixElement: false, SVGFEDiffuseLightingElement: false, SVGFEDisplacementMapElement: false, SVGFEDistantLightElement: false, SVGFEFloodElement : false, SVGFEFuncAElement : false, SVGFEFuncBElement : false, SVGFEFuncGElement : false, SVGFEFuncRElement : false, SVGFEGaussianBlurElement: false, SVGFEImageElement : false, SVGFEMergeElement : false, SVGFEMergeNodeElement: false, SVGFEMorphologyElement: false, SVGFEOffsetElement : false, SVGFEPointLightElement: false, SVGFESpecularLightingElement: false, SVGFESpotLightElement: false, SVGFETileElement : false, SVGFETurbulenceElement: false, SVGFilterElement : false, SVGFilterPrimitiveStandardAttributes: false, SVGFitToViewBox : false, SVGFontElement : false, SVGFontFaceElement : false, SVGFontFaceFormatElement: false, SVGFontFaceNameElement: false, SVGFontFaceSrcElement: false, SVGFontFaceUriElement: false, SVGForeignObjectElement: false, SVGGElement : false, SVGGlyphElement : false, SVGGlyphRefElement : false, SVGGradientElement : false, SVGHKernElement : false, SVGICCColor : false, SVGImageElement : false, SVGLangSpace : false, SVGLength : false, SVGLengthList : false, SVGLineElement : false, SVGLinearGradientElement: false, SVGLocatable : false, SVGMPathElement : false, SVGMarkerElement : false, SVGMaskElement : false, SVGMatrix : false, SVGMetadataElement : false, SVGMissingGlyphElement: false, SVGNumber : false, SVGNumberList : false, SVGPaint : false, SVGPathElement : false, SVGPathSeg : false, SVGPathSegArcAbs : false, SVGPathSegArcRel : false, SVGPathSegClosePath : false, SVGPathSegCurvetoCubicAbs: false, SVGPathSegCurvetoCubicRel: false, SVGPathSegCurvetoCubicSmoothAbs: false, SVGPathSegCurvetoCubicSmoothRel: false, SVGPathSegCurvetoQuadraticAbs: false, SVGPathSegCurvetoQuadraticRel: false, SVGPathSegCurvetoQuadraticSmoothAbs: false, SVGPathSegCurvetoQuadraticSmoothRel: false, SVGPathSegLinetoAbs : false, SVGPathSegLinetoHorizontalAbs: false, SVGPathSegLinetoHorizontalRel: false, SVGPathSegLinetoRel : false, SVGPathSegLinetoVerticalAbs: false, SVGPathSegLinetoVerticalRel: false, SVGPathSegList : false, SVGPathSegMovetoAbs : false, SVGPathSegMovetoRel : false, SVGPatternElement : false, SVGPoint : false, SVGPointList : false, SVGPolygonElement : false, SVGPolylineElement : false, SVGPreserveAspectRatio: false, SVGRadialGradientElement: false, SVGRect : false, SVGRectElement : false, SVGRenderingIntent : false, SVGSVGElement : false, SVGScriptElement : false, SVGSetElement : false, SVGStopElement : false, SVGStringList : false, SVGStylable : false, SVGStyleElement : false, SVGSwitchElement : false, SVGSymbolElement : false, SVGTRefElement : false, SVGTSpanElement : false, SVGTests : false, SVGTextContentElement: false, SVGTextElement : false, SVGTextPathElement : false, SVGTextPositioningElement: false, SVGTitleElement : false, SVGTransform : false, SVGTransformList : false, SVGTransformable : false, SVGURIReference : false, SVGUnitTypes : false, SVGUseElement : false, SVGVKernElement : false, SVGViewElement : false, SVGViewSpec : false, SVGZoomAndPan : false, Text : false, TextDecoder : false, TextEncoder : false, TimeEvent : false, top : false, URL : false, WebGLActiveInfo : false, WebGLBuffer : false, WebGLContextEvent : false, WebGLFramebuffer : false, WebGLProgram : false, WebGLRenderbuffer : false, WebGLRenderingContext: false, WebGLShader : false, WebGLShaderPrecisionFormat: false, WebGLTexture : false, WebGLUniformLocation : false, WebSocket : false, window : false, Worker : false, XDomainRequest : false, XMLHttpRequest : false, XMLSerializer : false, XPathEvaluator : false, XPathException : false, XPathExpression : false, XPathNamespace : false, XPathNSResolver : false, XPathResult : false }; exports.devel = { alert : false, confirm: false, console: false, Debug : false, opera : false, prompt : false }; exports.worker = { importScripts : true, postMessage : true, self : true, FileReaderSync : true }; // Widely adopted global names that are not part of ECMAScript standard exports.nonstandard = { escape : false, unescape: false }; // Globals provided by popular JavaScript environments. exports.couch = { "require" : false, respond : false, getRow : false, emit : false, send : false, start : false, sum : false, log : false, exports : false, module : false, provides : false }; exports.node = { __filename : false, __dirname : false, GLOBAL : false, global : false, module : false, require : false, // These globals are writeable because Node allows the following // usage pattern: var Buffer = require("buffer").Buffer; Buffer : true, console : true, exports : true, process : true, setTimeout : true, clearTimeout : true, setInterval : true, clearInterval : true, setImmediate : true, // v0.9.1+ clearImmediate: true // v0.9.1+ }; exports.browserify = { __filename : false, __dirname : false, global : false, module : false, require : false, Buffer : true, exports : true, process : true }; exports.phantom = { phantom : true, require : true, WebPage : true, console : true, // in examples, but undocumented exports : true // v1.7+ }; exports.qunit = { asyncTest : false, deepEqual : false, equal : false, expect : false, module : false, notDeepEqual : false, notEqual : false, notPropEqual : false, notStrictEqual : false, ok : false, propEqual : false, QUnit : false, raises : false, start : false, stop : false, strictEqual : false, test : false, "throws" : false }; exports.rhino = { defineClass : false, deserialize : false, gc : false, help : false, importClass : false, importPackage: false, "java" : false, load : false, loadClass : false, Packages : false, print : false, quit : false, readFile : false, readUrl : false, runCommand : false, seal : false, serialize : false, spawn : false, sync : false, toint32 : false, version : false }; exports.shelljs = { target : false, echo : false, exit : false, cd : false, pwd : false, ls : false, find : false, cp : false, rm : false, mv : false, mkdir : false, test : false, cat : false, sed : false, grep : false, which : false, dirs : false, pushd : false, popd : false, env : false, exec : false, chmod : false, config : false, error : false, tempdir : false }; exports.typed = { ArrayBuffer : false, ArrayBufferView : false, DataView : false, Float32Array : false, Float64Array : false, Int16Array : false, Int32Array : false, Int8Array : false, Uint16Array : false, Uint32Array : false, Uint8Array : false, Uint8ClampedArray : false }; exports.wsh = { ActiveXObject : true, Enumerator : true, GetObject : true, ScriptEngine : true, ScriptEngineBuildVersion : true, ScriptEngineMajorVersion : true, ScriptEngineMinorVersion : true, VBArray : true, WSH : true, WScript : true, XDomainRequest : true }; // Globals provided by popular JavaScript libraries. exports.dojo = { dojo : false, dijit : false, dojox : false, define : false, "require": false }; exports.jquery = { "$" : false, jQuery : false }; exports.mootools = { "$" : false, "$$" : false, Asset : false, Browser : false, Chain : false, Class : false, Color : false, Cookie : false, Core : false, Document : false, DomReady : false, DOMEvent : false, DOMReady : false, Drag : false, Element : false, Elements : false, Event : false, Events : false, Fx : false, Group : false, Hash : false, HtmlTable : false, IFrame : false, IframeShim : false, InputValidator: false, instanceOf : false, Keyboard : false, Locale : false, Mask : false, MooTools : false, Native : false, Options : false, OverText : false, Request : false, Scroller : false, Slick : false, Slider : false, Sortables : false, Spinner : false, Swiff : false, Tips : false, Type : false, typeOf : false, URI : false, Window : false }; exports.prototypejs = { "$" : false, "$$" : false, "$A" : false, "$F" : false, "$H" : false, "$R" : false, "$break" : false, "$continue" : false, "$w" : false, Abstract : false, Ajax : false, Class : false, Enumerable : false, Element : false, Event : false, Field : false, Form : false, Hash : false, Insertion : false, ObjectRange : false, PeriodicalExecuter: false, Position : false, Prototype : false, Selector : false, Template : false, Toggle : false, Try : false, Autocompleter : false, Builder : false, Control : false, Draggable : false, Draggables : false, Droppables : false, Effect : false, Sortable : false, SortableObserver : false, Sound : false, Scriptaculous : false }; exports.yui = { YUI : false, Y : false, YUI_config: false }; exports.mocha = { // BDD describe : false, xdescribe : false, it : false, xit : false, context : false, xcontext : false, before : false, after : false, beforeEach : false, afterEach : false, // TDD suite : false, test : false, setup : false, teardown : false, suiteSetup : false, suiteTeardown : false }; exports.jasmine = { jasmine : false, describe : false, xdescribe : false, it : false, xit : false, beforeEach : false, afterEach : false, setFixtures : false, loadFixtures: false, spyOn : false, expect : false, // Jasmine 1.3 runs : false, waitsFor : false, waits : false, // Jasmine 2.1 beforeAll : false, afterAll : false, fail : false, fdescribe : false, fit : false }; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/lodash/index.js":[function(require,module,exports){ (function (global){ /** * @license * lodash 3.7.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern -d -o ./index.js` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '3.7.0'; /** Used to compose bitmasks for wrapper metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, CURRY_RIGHT_FLAG = 16, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FLAG = 64, ARY_FLAG = 128, REARG_FLAG = 256; /** Used as default options for `_.trunc`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect when a function becomes hot. */ var HOT_COUNT = 150, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_DROP_WHILE_FLAG = 0, LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2; /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g, reUnescapedHtml = /[&<>"'`]/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]+|(["'])(?:(?!\1)[^\n\\]|\\.)*?)\1\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). * In addition to special characters the forward slash is escaped to allow for * easier `eval` use and `Function` compilation. */ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */ var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** Used to match [ES template delimiters](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect hexadecimal string values. */ var reHasHexPrefix = /^0[xX]/; /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to match latin-1 supplementary letters (excluding mathematical operators). */ var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to match words to create compound words. */ var reWords = (function() { var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]', lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+'; return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g'); }()); /** Used to detect and test for whitespace. */ var whitespace = ( // Basic whitespace characters. ' \t\x0b\f\xa0\ufeff' + // Line terminators. '\n\r\u2028\u2029' + // Unicode category "Zs" space separators. '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000' ); /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number', 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'document', 'isFinite', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', 'window' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[stringTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[mapTag] = cloneableTags[setTag] = cloneableTags[weakMapTag] = false; /** Used as an internal `_.debounce` options object by `_.throttle`. */ var debounceOptions = { 'leading': false, 'maxWait': 0, 'trailing': false }; /** Used to map latin-1 supplementary letters to basic latin letters. */ var deburredLetters = { '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'", '`': '`' }; /** Used to determine if values are of the language type `Object`. */ var objectTypes = { 'function': true, 'object': true }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Detect free variable `exports`. */ var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; /** Detect free variable `global` from Node.js. */ var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global; /** Detect free variable `self`. */ var freeSelf = objectTypes[typeof self] && self && self.Object && self; /** Detect free variable `window`. */ var freeWindow = objectTypes[typeof window] && window && window.Object && window; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; /** * Used as a reference to the global object. * * The `this` value is used if it is the global object to avoid Greasemonkey's * restricted `window` object, otherwise the `window` object is used. */ var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this; /*--------------------------------------------------------------------------*/ /** * The base implementation of `compareAscending` which compares values and * sorts them in ascending order without guaranteeing a stable sort. * * @private * @param {*} value The value to compare to `other`. * @param {*} other The value to compare to `value`. * @returns {number} Returns the sort order indicator for `value`. */ function baseCompareAscending(value, other) { if (value !== other) { var valIsReflexive = value === value, othIsReflexive = other === other; if (value > other || !valIsReflexive || (value === undefined && othIsReflexive)) { return 1; } if (value < other || !othIsReflexive || (other === undefined && valIsReflexive)) { return -1; } } return 0; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for callback shorthands and `this` binding. * * @private * @param {Array} array The array to search. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without support for binary searches. * * @private * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { if (value !== value) { return indexOfNaN(array, fromIndex); } var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * The base implementation of `_.isFunction` without support for environments * with incorrect `typeof` results. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. */ function baseIsFunction(value) { // Avoid a Chakra JIT bug in compatibility modes of IE 11. // See https://github.com/jashkenas/underscore/issues/1621 for more details. return typeof value == 'function' || false; } /** * Converts `value` to a string if it is not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } /** * Used by `_.max` and `_.min` as the default callback for string values. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the code unit of the first character of the string. */ function charAtCallback(string) { return string.charCodeAt(0); } /** * Used by `_.trim` and `_.trimLeft` to get the index of the first character * of `string` that is not found in `chars`. * * @private * @param {string} string The string to inspect. * @param {string} chars The characters to find. * @returns {number} Returns the index of the first character not found in `chars`. */ function charsLeftIndex(string, chars) { var index = -1, length = string.length; while (++index < length && chars.indexOf(string.charAt(index)) > -1) {} return index; } /** * Used by `_.trim` and `_.trimRight` to get the index of the last character * of `string` that is not found in `chars`. * * @private * @param {string} string The string to inspect. * @param {string} chars The characters to find. * @returns {number} Returns the index of the last character not found in `chars`. */ function charsRightIndex(string, chars) { var index = string.length; while (index-- && chars.indexOf(string.charAt(index)) > -1) {} return index; } /** * Used by `_.sortBy` to compare transformed elements of a collection and stable * sort them in ascending order. * * @private * @param {Object} object The object to compare to `other`. * @param {Object} other The object to compare to `object`. * @returns {number} Returns the sort order indicator for `object`. */ function compareAscending(object, other) { return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index); } /** * Used by `_.sortByOrder` to compare multiple properties of each element * in a collection and stable sort them in the following order: * * If `orders` is unspecified, sort in ascending order for all properties. * Otherwise, for each property, sort in ascending order if its corresponding value in * orders is true, and descending order if false. * * @private * @param {Object} object The object to compare to `other`. * @param {Object} other The object to compare to `object`. * @param {boolean[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = baseCompareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } return result * (orders[index] ? 1 : -1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://code.google.com/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ function deburrLetter(letter) { return deburredLetters[letter]; } /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeHtmlChar(chr) { return htmlEscapes[chr]; } /** * Used by `_.template` to escape characters for inclusion in compiled * string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the index at which the first occurrence of `NaN` is found in `array`. * * @private * @param {Array} array The array to search. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched `NaN`, else `-1`. */ function indexOfNaN(array, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 0 : -1); while ((fromRight ? index-- : ++index < length)) { var other = array[index]; if (other !== other) { return index; } } return -1; } /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a * character code is whitespace. * * @private * @param {number} charCode The character code to inspect. * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`. */ function isSpace(charCode) { return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 || (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279))); } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { if (array[index] === placeholder) { array[index] = PLACEHOLDER; result[++resIndex] = index; } } return result; } /** * An implementation of `_.uniq` optimized for sorted arrays without support * for callback shorthands and `this` binding. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The function invoked per iteration. * @returns {Array} Returns the new duplicate-value-free array. */ function sortedUniq(array, iteratee) { var seen, index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value, index, array) : value; if (!index || seen !== computed) { seen = computed; result[++resIndex] = value; } } return result; } /** * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace * character of `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the index of the first non-whitespace character. */ function trimmedLeftIndex(string) { var index = -1, length = string.length; while (++index < length && isSpace(string.charCodeAt(index))) {} return index; } /** * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace * character of `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the index of the last non-whitespace character. */ function trimmedRightIndex(string) { var index = string.length; while (index-- && isSpace(string.charCodeAt(index))) {} return index; } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ function unescapeHtmlChar(chr) { return htmlUnescapes[chr]; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the given `context` object. * * @static * @memberOf _ * @category Utility * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // using `context` to mock `Date#getTime` use in `_.now` * var mock = _.runInContext({ * 'Date': function() { * return { 'getTime': getTimeMock }; * } * }); * * // or creating a suped-up `defer` in Node.js * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ function runInContext(context) { // Avoid issues with some ES3 environments that attempt to use values, named // after built-in constructors like `Object`, for the creation of literals. // ES5 clears this up by stating that literals must use built-in constructors. // See https://es5.github.io/#x11.1.5 for more details. context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; /** Native constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Number = context.Number, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for native method references. */ var arrayProto = Array.prototype, objectProto = Object.prototype, stringProto = String.prototype; /** Used to detect DOM support. */ var document = (document = context.window) && document.document; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = context._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + escapeRegExp(objToString) .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Native method references. */ var ArrayBuffer = isNative(ArrayBuffer = context.ArrayBuffer) && ArrayBuffer, bufferSlice = isNative(bufferSlice = ArrayBuffer && new ArrayBuffer(0).slice) && bufferSlice, ceil = Math.ceil, clearTimeout = context.clearTimeout, floor = Math.floor, getOwnPropertySymbols = isNative(getOwnPropertySymbols = Object.getOwnPropertySymbols) && getOwnPropertySymbols, getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, push = arrayProto.push, preventExtensions = isNative(Object.preventExtensions = Object.preventExtensions) && preventExtensions, propertyIsEnumerable = objectProto.propertyIsEnumerable, Set = isNative(Set = context.Set) && Set, setTimeout = context.setTimeout, splice = arrayProto.splice, Uint8Array = isNative(Uint8Array = context.Uint8Array) && Uint8Array, WeakMap = isNative(WeakMap = context.WeakMap) && WeakMap; /** Used to clone array buffers. */ var Float64Array = (function() { // Safari 5 errors when using an array buffer to initialize a typed array // where the array buffer's `byteLength` is not a multiple of the typed // array's `BYTES_PER_ELEMENT`. try { var func = isNative(func = context.Float64Array) && func, result = new func(new ArrayBuffer(10), 0, 1) && func; } catch(e) {} return result; }()); /** Used as `baseAssign`. */ var nativeAssign = (function() { // Avoid `Object.assign` in Firefox 34-37 which have an early implementation // with a now defunct try/catch behavior. See https://bugzilla.mozilla.org/show_bug.cgi?id=1103344 // for more details. // // Use `Object.preventExtensions` on a plain object instead of simply using // `Object('x')` because Chrome and IE fail to throw an error when attempting // to assign values to readonly indexes of strings in strict mode. var object = { '1': 0 }, func = preventExtensions && isNative(func = Object.assign) && func; try { func(preventExtensions(object), 'xo'); } catch(e) {} return !object[1] && func; }()); /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, nativeIsFinite = context.isFinite, nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, nativeMax = Math.max, nativeMin = Math.min, nativeNow = isNative(nativeNow = Date.now) && nativeNow, nativeNumIsFinite = isNative(nativeNumIsFinite = Number.isFinite) && nativeNumIsFinite, nativeParseInt = context.parseInt, nativeRandom = Math.random; /** Used as references for `-Infinity` and `Infinity`. */ var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY, POSITIVE_INFINITY = Number.POSITIVE_INFINITY; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used as the size, in bytes, of each `Float64Array` element. */ var FLOAT64_BYTES_PER_ELEMENT = Float64Array ? Float64Array.BYTES_PER_ELEMENT : 0; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit chaining. * Methods that operate on and return arrays, collections, and functions can * be chained together. Methods that return a boolean or single value will * automatically end the chain returning the unwrapped value. Explicit chaining * may be enabled using `_.chain`. The execution of chained methods is lazy, * that is, execution is deferred until `_#value` is implicitly or explicitly * called. * * Lazy evaluation allows several methods to support shortcut fusion. Shortcut * fusion is an optimization that merges iteratees to avoid creating intermediate * arrays and reduce the number of iteratee executions. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, * `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`, * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`, * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`, * and `where` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`, * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`, * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defer`, `delay`, * `difference`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `fill`, * `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, `forEach`, * `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`, * `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`, * `keysIn`, `map`, `mapValues`, `matches`, `matchesProperty`, `memoize`, * `merge`, `mixin`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`, * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`, * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `reverse`, * `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, `sortByOrder`, `splice`, * `spread`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `tap`, * `throttle`, `thru`, `times`, `toArray`, `toPlainObject`, `transform`, * `union`, `uniq`, `unshift`, `unzip`, `values`, `valuesIn`, `where`, * `without`, `wrap`, `xor`, `zip`, and `zipObject` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `clone`, `cloneDeep`, `deburr`, * `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, * `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, `has`, * `identity`, `includes`, `indexOf`, `inRange`, `isArguments`, `isArray`, * `isBoolean`, `isDate`, `isElement`, `isEmpty`, `isEqual`, `isError`, `isFinite` * `isFunction`, `isMatch`, `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, * `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, * `join`, `kebabCase`, `last`, `lastIndexOf`, `max`, `min`, `noConflict`, * `noop`, `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, * `reduce`, `reduceRight`, `repeat`, `result`, `runInContext`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`, `startsWith`, * `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`, `unescape`, * `uniqueId`, `value`, and `words` * * The wrapper method `sample` will return a wrapped value when `n` is provided, * otherwise an unwrapped value is returned. * * @name _ * @constructor * @category Chain * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var wrapped = _([1, 2, 3]); * * // returns an unwrapped value * wrapped.reduce(function(total, n) { * return total + n; * }); * // => 6 * * // returns a wrapped value * var squares = wrapped.map(function(n) { * return n * n; * }); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The function whose prototype all chaining wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable chaining for all wrapper methods. * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value. */ function LodashWrapper(value, chainAll, actions) { this.__wrapped__ = value; this.__actions__ = actions || []; this.__chain__ = !!chainAll; } /** * An object environment feature flags. * * @static * @memberOf _ * @type Object */ var support = lodash.support = {}; (function(x) { var Ctor = function() { this.x = x; }, object = { '0': x, 'length': x }, props = []; Ctor.prototype = { 'valueOf': x, 'y': x }; for (var key in new Ctor) { props.push(key); } /** * Detect if functions can be decompiled by `Function#toString` * (all but Firefox OS certified apps, older Opera mobile browsers, and * the PlayStation 3; forced `false` for Windows 8 apps). * * @memberOf _.support * @type boolean */ support.funcDecomp = /\bthis\b/.test(function() { return this; }); /** * Detect if `Function#name` is supported (all but IE). * * @memberOf _.support * @type boolean */ support.funcNames = typeof Function.name == 'string'; /** * Detect if the DOM is supported. * * @memberOf _.support * @type boolean */ try { support.dom = document.createDocumentFragment().nodeType === 11; } catch(e) { support.dom = false; } /** * Detect if `arguments` object indexes are non-enumerable. * * In Firefox < 4, IE < 9, PhantomJS, and Safari < 5.1 `arguments` object * indexes are non-enumerable. Chrome < 25 and Node.js < 0.11.0 treat * `arguments` object indexes as non-enumerable and fail `hasOwnProperty` * checks for indexes that exceed the number of function parameters and * whose associated argument values are `0`. * * @memberOf _.support * @type boolean */ try { support.nonEnumArgs = !propertyIsEnumerable.call(arguments, 1); } catch(e) { support.nonEnumArgs = true; } }(1, 0)); /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB). Change the following template settings to use * alternative delimiters. * * @static * @memberOf _ * @type Object */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type RegExp */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type RegExp */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type RegExp */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type string */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type Object */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type Function */ '_': lodash } }; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = null; this.__dir__ = 1; this.__dropCount__ = 0; this.__filtered__ = false; this.__iteratees__ = null; this.__takeCount__ = POSITIVE_INFINITY; this.__views__ = null; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var actions = this.__actions__, iteratees = this.__iteratees__, views = this.__views__, result = new LazyWrapper(this.__wrapped__); result.__actions__ = actions ? arrayCopy(actions) : null; result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = iteratees ? arrayCopy(iteratees) : null; result.__takeCount__ = this.__takeCount__; result.__views__ = views ? arrayCopy(views) : null; return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(); if (!isArray(array)) { return baseWrapperValue(array, this.__actions__); } var dir = this.__dir__, isRight = dir < 0, view = getView(0, array.length, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), takeCount = nativeMin(length, this.__takeCount__), iteratees = this.__iteratees__, iterLength = iteratees ? iteratees.length : 0, resIndex = 0, result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type; if (type == LAZY_DROP_WHILE_FLAG) { if (data.done && (isRight ? (index > data.index) : (index < data.index))) { data.count = 0; data.done = false; } data.index = index; if (!data.done) { var limit = data.limit; if (!(data.done = limit > -1 ? (data.count++ >= limit) : !iteratee(value))) { continue outer; } } } else { var computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } } result[resIndex++] = value; } return result; } /*------------------------------------------------------------------------*/ /** * Creates a cache object to store key/value pairs. * * @private * @static * @name Cache * @memberOf _.memoize */ function MapCache() { this.__data__ = {}; } /** * Removes `key` and its value from the cache. * * @private * @name delete * @memberOf _.memoize.Cache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`. */ function mapDelete(key) { return this.has(key) && delete this.__data__[key]; } /** * Gets the cached value for `key`. * * @private * @name get * @memberOf _.memoize.Cache * @param {string} key The key of the value to get. * @returns {*} Returns the cached value. */ function mapGet(key) { return key == '__proto__' ? undefined : this.__data__[key]; } /** * Checks if a cached value for `key` exists. * * @private * @name has * @memberOf _.memoize.Cache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapHas(key) { return key != '__proto__' && hasOwnProperty.call(this.__data__, key); } /** * Sets `value` to `key` of the cache. * * @private * @name set * @memberOf _.memoize.Cache * @param {string} key The key of the value to cache. * @param {*} value The value to cache. * @returns {Object} Returns the cache object. */ function mapSet(key, value) { if (key != '__proto__') { this.__data__[key] = value; } return this; } /*------------------------------------------------------------------------*/ /** * * Creates a cache object to store unique values. * * @private * @param {Array} [values] The values to cache. */ function SetCache(values) { var length = values ? values.length : 0; this.data = { 'hash': nativeCreate(null), 'set': new Set }; while (length--) { this.push(values[length]); } } /** * Checks if `value` is in `cache` mimicking the return signature of * `_.indexOf` by returning `0` if the value is found, else `-1`. * * @private * @param {Object} cache The cache to search. * @param {*} value The value to search for. * @returns {number} Returns `0` if `value` is found, else `-1`. */ function cacheIndexOf(cache, value) { var data = cache.data, result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value]; return result ? 0 : -1; } /** * Adds `value` to the cache. * * @private * @name push * @memberOf SetCache * @param {*} value The value to cache. */ function cachePush(value) { var data = this.data; if (typeof value == 'string' || isObject(value)) { data.set.add(value); } else { data.hash[value] = true; } } /*------------------------------------------------------------------------*/ /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * A specialized version of `_.forEach` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * callback shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[++resIndex] = value; } } return result; } /** * A specialized version of `_.map` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * A specialized version of `_.max` for arrays without support for iteratees. * * @private * @param {Array} array The array to iterate over. * @returns {*} Returns the maximum value. */ function arrayMax(array) { var index = -1, length = array.length, result = NEGATIVE_INFINITY; while (++index < length) { var value = array[index]; if (value > result) { result = value; } } return result; } /** * A specialized version of `_.min` for arrays without support for iteratees. * * @private * @param {Array} array The array to iterate over. * @returns {*} Returns the minimum value. */ function arrayMin(array) { var index = -1, length = array.length, result = POSITIVE_INFINITY; while (++index < length) { var value = array[index]; if (value < result) { result = value; } } return result; } /** * A specialized version of `_.reduce` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initFromArray] Specify using the first element of `array` * as the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initFromArray) { var index = -1, length = array.length; if (initFromArray && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * callback shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initFromArray] Specify using the last element of `array` * as the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initFromArray) { var length = array.length; if (initFromArray && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * A specialized version of `_.sum` for arrays without support for iteratees. * * @private * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. */ function arraySum(array) { var length = array.length, result = 0; while (length--) { result += +array[length] || 0; } return result; } /** * Used by `_.defaults` to customize its `_.assign` use. * * @private * @param {*} objectValue The destination object property value. * @param {*} sourceValue The source object property value. * @returns {*} Returns the value to assign to the destination object. */ function assignDefaults(objectValue, sourceValue) { return objectValue === undefined ? sourceValue : objectValue; } /** * Used by `_.template` to customize its `_.assign` use. * * **Note:** This function is like `assignDefaults` except that it ignores * inherited property values when checking if a property is `undefined`. * * @private * @param {*} objectValue The destination object property value. * @param {*} sourceValue The source object property value. * @param {string} key The key associated with the object and source values. * @param {Object} object The destination object. * @returns {*} Returns the value to assign to the destination object. */ function assignOwnDefaults(objectValue, sourceValue, key, object) { return (objectValue === undefined || !hasOwnProperty.call(object, key)) ? sourceValue : objectValue; } /** * A specialized version of `_.assign` for customizing assigned values without * support for argument juggling, multiple sources, and `this` binding `customizer` * functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. */ function assignWith(object, source, customizer) { var props = keys(source); push.apply(props, getSymbols(source)); var index = -1, length = props.length; while (++index < length) { var key = props[index], value = object[key], result = customizer(value, source[key], key, object, source); if ((result === result ? (result !== value) : (value === value)) || (value === undefined && !(key in object))) { object[key] = result; } } return object; } /** * The base implementation of `_.assign` without support for argument juggling, * multiple sources, and `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ var baseAssign = nativeAssign || function(object, source) { return source == null ? object : baseCopy(source, getSymbols(source), baseCopy(source, keys(source), object)); }; /** * The base implementation of `_.at` without support for string collections * and individual key arguments. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {number[]|string[]} props The property names or indexes of elements to pick. * @returns {Array} Returns the new array of picked elements. */ function baseAt(collection, props) { var index = -1, length = collection.length, isArr = isLength(length), propsLength = props.length, result = Array(propsLength); while(++index < propsLength) { var key = props[index]; if (isArr) { result[index] = isIndex(key, length) ? collection[key] : undefined; } else { result[index] = collection[key]; } } return result; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property names to copy. * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ function baseCopy(source, props, object) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; object[key] = source[key]; } return object; } /** * The base implementation of `_.callback` which supports specifying the * number of arguments to provide to `func`. * * @private * @param {*} [func=_.identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function baseCallback(func, thisArg, argCount) { var type = typeof func; if (type == 'function') { return thisArg === undefined ? func : bindCallback(func, thisArg, argCount); } if (func == null) { return identity; } if (type == 'object') { return baseMatches(func); } return thisArg === undefined ? property(func) : baseMatchesProperty(func, thisArg); } /** * The base implementation of `_.clone` without support for argument juggling * and `this` binding `customizer` functions. * * @private * @param {*} value The value to clone. * @param {boolean} [isDeep] Specify a deep clone. * @param {Function} [customizer] The function to customize cloning values. * @param {string} [key] The key of `value`. * @param {Object} [object] The object `value` belongs to. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates clones with source counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, isDeep, customizer, key, object, stackA, stackB) { var result; if (customizer) { result = object ? customizer(value, key, object) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return arrayCopy(value, result); } } else { var tag = objToString.call(value), isFunc = tag == funcTag; if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = initCloneObject(isFunc ? {} : value); if (!isDeep) { return baseAssign(result, value); } } else { return cloneableTags[tag] ? initCloneByTag(value, tag, isDeep) : (object ? value : {}); } } // Check for circular references and return corresponding clone. stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == value) { return stackB[length]; } } // Add the source value to the stack of traversed objects and associate it with its clone. stackA.push(value); stackB.push(result); // Recursively populate clone (susceptible to call stack limits). (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) { result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB); }); return result; } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} prototype The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function Object() {} return function(prototype) { if (isObject(prototype)) { Object.prototype = prototype; var result = new Object; Object.prototype = null; } return result || context.Object(); }; }()); /** * The base implementation of `_.delay` and `_.defer` which accepts an index * of where to slice the arguments to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Object} args The arguments provide to `func`. * @returns {number} Returns the timer id. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of `_.difference` which accepts a single array * of values to exclude. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values) { var length = array ? array.length : 0, result = []; if (!length) { return result; } var index = -1, indexOf = getIndexOf(), isCommon = indexOf == baseIndexOf, cache = (isCommon && values.length >= 200) ? createCache(values) : null, valuesLength = values.length; if (cache) { indexOf = cacheIndexOf; isCommon = false; values = cache; } outer: while (++index < length) { var value = array[index]; if (isCommon && value === value) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === value) { continue outer; } } result.push(value); } else if (indexOf(values, value, 0) < 0) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object|string} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object|string} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = start == null ? 0 : (+start || 0); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } length = start > end ? 0 : (end >>> 0); start >>>= 0; while (start < length) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`, * without support for callback shorthands and `this` binding, which iterates * over `collection` using the provided `eachFunc`. * * @private * @param {Array|Object|string} collection The collection to search. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @param {boolean} [retKey] Specify returning the key of the found element * instead of the element itself. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFind(collection, predicate, eachFunc, retKey) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = retKey ? key : value; return false; } }); return result; } /** * The base implementation of `_.flatten` with added support for restricting * flattening and specifying the start index. * * @private * @param {Array} array The array to flatten. * @param {boolean} isDeep Specify a deep flatten. * @param {boolean} isStrict Restrict flattening to arrays and `arguments` objects. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, isDeep, isStrict) { var index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { var value = array[index]; if (isObjectLike(value) && isLength(value.length) && (isArray(value) || isArguments(value))) { if (isDeep) { // Recursively flatten arrays (susceptible to call stack limits). value = baseFlatten(value, isDeep, isStrict); } var valIndex = -1, valLength = value.length; result.length += valLength; while (++valIndex < valLength) { result[++resIndex] = value[valIndex]; } } else if (!isStrict) { result[++resIndex] = value; } } return result; } /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forIn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForIn(object, iteratee) { return baseFor(object, iteratee, keysIn); } /** * The base implementation of `_.forOwn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from those provided. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the new array of filtered property names. */ function baseFunctions(object, props) { var index = -1, length = props.length, resIndex = -1, result = []; while (++index < length) { var key = props[index]; if (isFunction(object[key])) { result[++resIndex] = key; } } return result; } /** * The base implementation of `get` without support for string paths * and default values. * * @private * @param {Object} object The object to query. * @param {Array} path The path of the property to get. * @param {string} [pathKey] The key representation of path. * @returns {*} Returns the resolved value. */ function baseGet(object, path, pathKey) { if (object == null) { return; } if (pathKey !== undefined && pathKey in toObject(object)) { path = [pathKey]; } var index = -1, length = path.length; while (object != null && ++index < length) { var result = object = object[path[index]]; } return result; } /** * The base implementation of `_.isEqual` without support for `this` binding * `customizer` functions. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { // Exit early for identical values. if (value === other) { // Treat `+0` vs. `-0` as not equal. return value !== 0 || (1 / value == 1 / other); } var valType = typeof value, othType = typeof other; // Exit early for unlike primitive values. if ((valType != 'function' && valType != 'object' && othType != 'function' && othType != 'object') || value == null || other == null) { // Return `false` unless both values are `NaN`. return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing objects. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA=[]] Tracks traversed `value` objects. * @param {Array} [stackB=[]] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = objToString.call(object); if (objTag == argsTag) { objTag = objectTag; } else if (objTag != objectTag) { objIsArr = isTypedArray(object); } } if (!othIsArr) { othTag = objToString.call(other); if (othTag == argsTag) { othTag = objectTag; } else if (othTag != objectTag) { othIsArr = isTypedArray(other); } } var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && !(objIsArr || objIsObj)) { return equalByTag(object, other, objTag); } if (!isLoose) { var valWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (valWrapped || othWrapped) { return equalFunc(valWrapped ? object.value() : object, othWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); } } if (!isSameTag) { return false; } // Assume cyclic values are equal. // For more information on detecting circular references see https://es5.github.io/#JO. stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == object) { return stackB[length] == other; } } // Add `object` and `other` to the stack of traversed objects. stackA.push(object); stackB.push(other); var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); stackA.pop(); stackB.pop(); return result; } /** * The base implementation of `_.isMatch` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to inspect. * @param {Array} props The source property names to match. * @param {Array} values The source values to match. * @param {Array} strictCompareFlags Strict comparison flags for source values. * @param {Function} [customizer] The function to customize comparing objects. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, props, values, strictCompareFlags, customizer) { var index = -1, length = props.length, noCustomizer = !customizer; while (++index < length) { if ((noCustomizer && strictCompareFlags[index]) ? values[index] !== object[props[index]] : !(props[index] in object) ) { return false; } } index = -1; while (++index < length) { var key = props[index], objValue = object[key], srcValue = values[index]; if (noCustomizer && strictCompareFlags[index]) { var result = objValue !== undefined || (key in object); } else { result = customizer ? customizer(objValue, srcValue, key) : undefined; if (result === undefined) { result = baseIsEqual(srcValue, objValue, customizer, true); } } if (!result) { return false; } } return true; } /** * The base implementation of `_.map` without support for callback shorthands * and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, length = getLength(collection), result = isLength(length) ? Array(length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which does not clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new function. */ function baseMatches(source) { var props = keys(source), length = props.length; if (!length) { return constant(true); } if (length == 1) { var key = props[0], value = source[key]; if (isStrictComparable(value)) { return function(object) { if (object == null) { return false; } return object[key] === value && (value !== undefined || (key in toObject(object))); }; } } var values = Array(length), strictCompareFlags = Array(length); while (length--) { value = source[props[length]]; values[length] = value; strictCompareFlags[length] = isStrictComparable(value); } return function(object) { return object != null && baseIsMatch(toObject(object), props, values, strictCompareFlags); }; } /** * The base implementation of `_.matchesProperty` which does not which does * not clone `value`. * * @private * @param {string} path The path of the property to get. * @param {*} value The value to compare. * @returns {Function} Returns the new function. */ function baseMatchesProperty(path, value) { var isArr = isArray(path), isCommon = isKey(path) && isStrictComparable(value), pathKey = (path + ''); path = toPath(path); return function(object) { if (object == null) { return false; } var key = pathKey; object = toObject(object); if ((isArr || !isCommon) && !(key in object)) { object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } key = last(path); object = toObject(object); } return object[key] === value ? (value !== undefined || (key in object)) : baseIsEqual(value, object[key], null, true); }; } /** * The base implementation of `_.merge` without support for argument juggling, * multiple sources, and `this` binding `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} [customizer] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {Object} Returns `object`. */ function baseMerge(object, source, customizer, stackA, stackB) { if (!isObject(object)) { return object; } var isSrcArr = isLength(source.length) && (isArray(source) || isTypedArray(source)); if (!isSrcArr) { var props = keys(source); push.apply(props, getSymbols(source)); } arrayEach(props || source, function(srcValue, key) { if (props) { key = srcValue; srcValue = source[key]; } if (isObjectLike(srcValue)) { stackA || (stackA = []); stackB || (stackB = []); baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); } else { var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; } if ((isSrcArr || result !== undefined) && (isCommon || (result === result ? (result !== value) : (value === value)))) { object[key] = result; } } }); return object; } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { var length = stackA.length, srcValue = source[key]; while (length--) { if (stackA[length] == srcValue) { object[key] = stackB[length]; return; } } var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; if (isLength(srcValue.length) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value : (getLength(value) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) ? toPlainObject(value) : (isPlainObject(value) ? value : {}); } else { isCommon = false; } } // Add the source value to the stack of traversed objects and associate // it with its merged value. stackA.push(srcValue); stackB.push(result); if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); } else if (result === result ? (result !== value) : (value === value)) { object[key] = result; } } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. */ function basePropertyDeep(path) { var pathKey = (path + ''); path = toPath(path); return function(object) { return baseGet(object, path, pathKey); }; } /** * The base implementation of `_.pullAt` without support for individual * index arguments and capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = indexes.length; while (length--) { var index = parseFloat(indexes[length]); if (index != previous && isIndex(index)) { var previous = index; splice.call(array, index, 1); } } return array; } /** * The base implementation of `_.random` without support for argument juggling * and returning floating-point numbers. * * @private * @param {number} min The minimum possible value. * @param {number} max The maximum possible value. * @returns {number} Returns the random number. */ function baseRandom(min, max) { return min + floor(nativeRandom() * (max - min + 1)); } /** * The base implementation of `_.reduce` and `_.reduceRight` without support * for callback shorthands and `this` binding, which iterates over `collection` * using the provided `eachFunc`. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initFromCollection Specify using the first or last element * of `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initFromCollection ? (initFromCollection = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `setData` without support for hot loop detection. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; start = start == null ? 0 : (+start || 0); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for callback shorthands * and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortBy` which uses `comparer` to define * the sort order of `array` and replaces criteria objects with their * corresponding values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sortByOrder` without param guards. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {boolean[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseSortByOrder(collection, iteratees, orders) { var callback = getCallback(), index = -1; iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); }); var result = baseMap(collection, function(value) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.sum` without support for callback shorthands * and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(collection, iteratee) { var result = 0; baseEach(collection, function(value, index, collection) { result += +iteratee(value, index, collection) || 0; }); return result; } /** * The base implementation of `_.uniq` without support for callback shorthands * and `this` binding. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The function invoked per iteration. * @returns {Array} Returns the new duplicate-value-free array. */ function baseUniq(array, iteratee) { var index = -1, indexOf = getIndexOf(), length = array.length, isCommon = indexOf == baseIndexOf, isLarge = isCommon && length >= 200, seen = isLarge ? createCache() : null, result = []; if (seen) { indexOf = cacheIndexOf; isCommon = false; } else { isLarge = false; seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value, index, array) : value; if (isCommon && value === value) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (indexOf(seen, computed, 0) < 0) { if (iteratee || isLarge) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { var index = -1, length = props.length, result = Array(length); while (++index < length) { result[index] = object[props[index]]; } return result; } /** * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`, * and `_.takeWhile` without support for callback shorthands and `this` binding. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to peform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } var index = -1, length = actions.length; while (++index < length) { var args = [result], action = actions[index]; push.apply(args, action.args); result = action.func.apply(action.thisArg, args); } return result; } /** * Performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function binaryIndex(array, value, retHighest) { var low = 0, high = array ? array.length : low; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (retHighest ? (computed <= value) : (computed < value)) { low = mid + 1; } else { high = mid; } } return high; } return binaryIndexBy(array, value, identity, retHighest); } /** * This function is like `binaryIndex` except that it invokes `iteratee` for * `value` and each element of `array` to compute their sort ranking. The * iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The function invoked per iteration. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function binaryIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array ? array.length : 0, valIsNaN = value !== value, valIsUndef = value === undefined; while (low < high) { var mid = floor((low + high) / 2), computed = iteratee(array[mid]), isReflexive = computed === computed; if (valIsNaN) { var setLow = isReflexive || retHighest; } else if (valIsUndef) { setLow = isReflexive && (retHighest || computed !== undefined); } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } /** * Creates a clone of the given array buffer. * * @private * @param {ArrayBuffer} buffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function bufferClone(buffer) { return bufferSlice.call(buffer, 0); } if (!bufferSlice) { // PhantomJS has `ArrayBuffer` and `Uint8Array` but not `Float64Array`. bufferClone = !(ArrayBuffer && Uint8Array) ? constant(null) : function(buffer) { var byteLength = buffer.byteLength, floatLength = Float64Array ? floor(byteLength / FLOAT64_BYTES_PER_ELEMENT) : 0, offset = floatLength * FLOAT64_BYTES_PER_ELEMENT, result = new ArrayBuffer(byteLength); if (floatLength) { var view = new Float64Array(result, 0, floatLength); view.set(new Float64Array(buffer, 0, floatLength)); } if (byteLength != offset) { view = new Uint8Array(result, offset); view.set(new Uint8Array(buffer, offset)); } return result; }; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array|Object} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders) { var holdersLength = holders.length, argsIndex = -1, argsLength = nativeMax(args.length - holdersLength, 0), leftIndex = -1, leftLength = partials.length, result = Array(argsLength + leftLength); while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { result[holders[argsIndex]] = args[argsIndex]; } while (argsLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array|Object} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders) { var holdersIndex = -1, holdersLength = holders.length, argsIndex = -1, argsLength = nativeMax(args.length - holdersLength, 0), rightIndex = -1, rightLength = partials.length, result = Array(argsLength + rightLength); while (++argsIndex < argsLength) { result[argsIndex] = args[argsIndex]; } var pad = argsIndex; while (++rightIndex < rightLength) { result[pad + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { result[pad + holders[holdersIndex]] = args[argsIndex++]; } return result; } /** * Creates a function that aggregates a collection, creating an accumulator * object composed from the results of running each element in the collection * through an iteratee. * * **Note:** This function is used to create `_.countBy`, `_.groupBy`, `_.indexBy`, * and `_.partition`. * * @private * @param {Function} setter The function to set keys and values of the accumulator object. * @param {Function} [initializer] The function to initialize the accumulator object. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee, thisArg) { var result = initializer ? initializer() : {}; iteratee = getCallback(iteratee, thisArg, 3); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; setter(result, value, iteratee(value, index, collection), collection); } } else { baseEach(collection, function(value, key, collection) { setter(result, value, iteratee(value, key, collection), collection); }); } return result; }; } /** * Creates a function that assigns properties of source object(s) to a given * destination object. * * **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return restParam(function(object, sources) { var index = -1, length = object == null ? 0 : sources.length, customizer = length > 2 && sources[length - 2], guard = length > 2 && sources[2], thisArg = length > 1 && sources[length - 1]; if (typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { customizer = typeof thisArg == 'function' ? thisArg : null; length -= (customizer ? 1 : 0); } if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? null : customizer; length = 1; } while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } var index = fromRight ? length : -1, iterable = toObject(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` and invokes it with the `this` * binding of `thisArg`. * * @private * @param {Function} func The function to bind. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new bound function. */ function createBindWrapper(func, thisArg) { var Ctor = createCtorWrapper(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(thisArg, arguments); } return wrapper; } /** * Creates a `Set` cache object to optimize linear searches of large arrays. * * @private * @param {Array} [values] The values to cache. * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`. */ var createCache = !(nativeCreate && Set) ? constant(null) : function(values) { return new SetCache(values); }; /** * Creates a function that produces compound words out of the words in a * given string. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { var index = -1, array = words(deburr(string)), length = array.length, result = ''; while (++index < length) { result = callback(result, array[index], index); } return result; }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtorWrapper(Ctor) { return function() { var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, arguments); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a `_.curry` or `_.curryRight` function. * * @private * @param {boolean} flag The curry bit flag. * @returns {Function} Returns the new curry function. */ function createCurry(flag) { function curryFunc(func, arity, guard) { if (guard && isIterateeCall(func, arity, guard)) { arity = null; } var result = createWrapper(func, flag, null, null, null, null, null, arity); result.placeholder = curryFunc.placeholder; return result; } return curryFunc; } /** * Creates a `_.max` or `_.min` function. * * @private * @param {Function} arrayFunc The function to get the extremum value from an array. * @param {boolean} [isMin] Specify returning the minimum, instead of the maximum, * extremum value. * @returns {Function} Returns the new extremum function. */ function createExtremum(arrayFunc, isMin) { return function(collection, iteratee, thisArg) { if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { iteratee = null; } var func = getCallback(), noIteratee = iteratee == null; if (!(func === baseCallback && noIteratee)) { noIteratee = false; iteratee = func(iteratee, thisArg, 3); } if (noIteratee) { var isArr = isArray(collection); if (!isArr && isString(collection)) { iteratee = charAtCallback; } else { return arrayFunc(isArr ? collection : toIterable(collection)); } } return extremumBy(collection, iteratee, isMin); }; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new find function. */ function createFind(eachFunc, fromRight) { return function(collection, predicate, thisArg) { predicate = getCallback(predicate, thisArg, 3); if (isArray(collection)) { var index = baseFindIndex(collection, predicate, fromRight); return index > -1 ? collection[index] : undefined; } return baseFind(collection, predicate, eachFunc); } } /** * Creates a `_.findIndex` or `_.findLastIndex` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new find function. */ function createFindIndex(fromRight) { return function(array, predicate, thisArg) { if (!(array && array.length)) { return -1; } predicate = getCallback(predicate, thisArg, 3); return baseFindIndex(array, predicate, fromRight); }; } /** * Creates a `_.findKey` or `_.findLastKey` function. * * @private * @param {Function} objectFunc The function to iterate over an object. * @returns {Function} Returns the new find function. */ function createFindKey(objectFunc) { return function(object, predicate, thisArg) { predicate = getCallback(predicate, thisArg, 3); return baseFind(object, predicate, objectFunc, true); }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return function() { var length = arguments.length; if (!length) { return function() { return arguments[0]; }; } var wrapper, index = fromRight ? length : -1, leftIndex = 0, funcs = Array(length); while ((fromRight ? index-- : ++index < length)) { var func = funcs[leftIndex++] = arguments[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var funcName = wrapper ? '' : getFuncName(func); wrapper = funcName == 'wrapper' ? new LodashWrapper([]) : wrapper; } index = wrapper ? -1 : length; while (++index < length) { func = funcs[index]; funcName = getFuncName(func); var data = funcName == 'wrapper' ? getData(func) : null; if (data && isLaziable(data[0])) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments; if (wrapper && args.length == 1 && isArray(args[0])) { return wrapper.plant(args[0]).value(); } var index = 0, result = funcs[index].apply(this, args); while (++index < length) { result = funcs[index].call(this, result); } return result; }; }; } /** * Creates a function for `_.forEach` or `_.forEachRight`. * * @private * @param {Function} arrayFunc The function to iterate over an array. * @param {Function} eachFunc The function to iterate over a collection. * @returns {Function} Returns the new each function. */ function createForEach(arrayFunc, eachFunc) { return function(collection, iteratee, thisArg) { return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) ? arrayFunc(collection, iteratee) : eachFunc(collection, bindCallback(iteratee, thisArg, 3)); }; } /** * Creates a function for `_.forIn` or `_.forInRight`. * * @private * @param {Function} objectFunc The function to iterate over an object. * @returns {Function} Returns the new each function. */ function createForIn(objectFunc) { return function(object, iteratee, thisArg) { if (typeof iteratee != 'function' || thisArg !== undefined) { iteratee = bindCallback(iteratee, thisArg, 3); } return objectFunc(object, iteratee, keysIn); }; } /** * Creates a function for `_.forOwn` or `_.forOwnRight`. * * @private * @param {Function} objectFunc The function to iterate over an object. * @returns {Function} Returns the new each function. */ function createForOwn(objectFunc) { return function(object, iteratee, thisArg) { if (typeof iteratee != 'function' || thisArg !== undefined) { iteratee = bindCallback(iteratee, thisArg, 3); } return objectFunc(object, iteratee); }; } /** * Creates a function for `_.padLeft` or `_.padRight`. * * @private * @param {boolean} [fromRight] Specify padding from the right. * @returns {Function} Returns the new pad function. */ function createPadDir(fromRight) { return function(string, length, chars) { string = baseToString(string); return string && ((fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string)); }; } /** * Creates a `_.partial` or `_.partialRight` function. * * @private * @param {boolean} flag The partial bit flag. * @returns {Function} Returns the new partial function. */ function createPartial(flag) { var partialFunc = restParam(function(func, partials) { var holders = replaceHolders(partials, partialFunc.placeholder); return createWrapper(func, flag, null, partials, holders); }); return partialFunc; } /** * Creates a function for `_.reduce` or `_.reduceRight`. * * @private * @param {Function} arrayFunc The function to iterate over an array. * @param {Function} eachFunc The function to iterate over a collection. * @returns {Function} Returns the new each function. */ function createReduce(arrayFunc, eachFunc) { return function(collection, iteratee, accumulator, thisArg) { var initFromArray = arguments.length < 3; return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) ? arrayFunc(collection, iteratee, accumulator, initFromArray) : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc); }; } /** * Creates a function that wraps `func` and invokes it with optional `this` * binding of, partial application, and currying. * * @private * @param {Function|string} func The function or method name to reference. * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & ARY_FLAG, isBind = bitmask & BIND_FLAG, isBindKey = bitmask & BIND_KEY_FLAG, isCurry = bitmask & CURRY_FLAG, isCurryBound = bitmask & CURRY_BOUND_FLAG, isCurryRight = bitmask & CURRY_RIGHT_FLAG; var Ctor = !isBindKey && createCtorWrapper(func), key = func; function wrapper() { // Avoid `arguments` object use disqualifying optimizations by // converting it to an array before providing it to other functions. var length = arguments.length, index = length, args = Array(length); while (index--) { args[index] = arguments[index]; } if (partials) { args = composeArgs(args, partials, holders); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight); } if (isCurry || isCurryRight) { var placeholder = wrapper.placeholder, argsHolders = replaceHolders(args, placeholder); length -= argsHolders.length; if (length < arity) { var newArgPos = argPos ? arrayCopy(argPos) : null, newArity = nativeMax(arity - length, 0), newsHolders = isCurry ? argsHolders : null, newHoldersRight = isCurry ? null : argsHolders, newPartials = isCurry ? args : null, newPartialsRight = isCurry ? null : args; bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); if (!isCurryBound) { bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); } var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity], result = createHybridWrapper.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return result; } } var thisBinding = isBind ? thisArg : this; if (isBindKey) { func = thisBinding[key]; } if (argPos) { args = reorder(args, argPos); } if (isAry && ary < args.length) { args.length = ary; } var fn = (this && this !== root && this instanceof wrapper) ? (Ctor || createCtorWrapper(func)) : func; return fn.apply(thisBinding, args); } return wrapper; } /** * Creates the padding required for `string` based on the given `length`. * The `chars` string is truncated if the number of characters exceeds `length`. * * @private * @param {string} string The string to create padding for. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the pad for `string`. */ function createPadding(string, length, chars) { var strLength = string.length; length = +length; if (strLength >= length || !nativeIsFinite(length)) { return ''; } var padLength = length - strLength; chars = chars == null ? ' ' : (chars + ''); return repeat(chars, ceil(padLength / chars.length)).slice(0, padLength); } /** * Creates a function that wraps `func` and invokes it with the optional `this` * binding of `thisArg` and the `partials` prepended to those provided to * the wrapper. * * @private * @param {Function} func The function to partially apply arguments to. * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to the new function. * @returns {Function} Returns the new bound function. */ function createPartialWrapper(func, bitmask, thisArg, partials) { var isBind = bitmask & BIND_FLAG, Ctor = createCtorWrapper(func); function wrapper() { // Avoid `arguments` object use disqualifying optimizations by // converting it to an array before providing it `func`. var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(argsLength + leftLength); while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.sortedIndex` or `_.sortedLastIndex` function. * * @private * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {Function} Returns the new index function. */ function createSortedIndex(retHighest) { return function(array, value, iteratee, thisArg) { var func = getCallback(iteratee); return (func === baseCallback && iteratee == null) ? binaryIndex(array, value, retHighest) : binaryIndexBy(array, value, func(iteratee, thisArg, 1), retHighest); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to reference. * @param {number} bitmask The bitmask of flags. * The bitmask may be composed of the following flags: * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); partials = holders = null; } length -= (holders ? holders.length : 0); if (bitmask & PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = null; } var data = isBindKey ? null : getData(func), newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity]; if (data) { mergeData(newData, data); bitmask = newData[1]; arity = newData[9]; } newData[9] = arity == null ? (isBindKey ? 0 : func.length) : (nativeMax(arity - length, 0) || 0); if (bitmask == BIND_FLAG) { var result = createBindWrapper(newData[0], newData[2]); } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) { result = createPartialWrapper.apply(undefined, newData); } else { result = createHybridWrapper.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setter(result, newData); } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing arrays. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { var index = -1, arrLength = array.length, othLength = other.length, result = true; if (arrLength != othLength && !(isLoose && othLength > arrLength)) { return false; } // Deep compare the contents, ignoring non-numeric properties. while (result && ++index < arrLength) { var arrValue = array[index], othValue = other[index]; result = undefined; if (customizer) { result = isLoose ? customizer(othValue, arrValue, index) : customizer(arrValue, othValue, index); } if (result === undefined) { // Recursively compare arrays (susceptible to call stack limits). if (isLoose) { var othIndex = othLength; while (othIndex--) { othValue = other[othIndex]; result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); if (result) { break; } } } else { result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); } } } return !!result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} value The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag) { switch (tag) { case boolTag: case dateTag: // Coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal. return +object == +other; case errorTag: return object.name == other.name && object.message == other.message; case numberTag: // Treat `NaN` vs. `NaN` as equal. return (object != +object) ? other != +other // But, treat `-0` vs. `+0` as not equal. : (object == 0 ? ((1 / object) == (1 / other)) : object == +other); case regexpTag: case stringTag: // Coerce regexes to strings and treat strings primitives and string // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. return object == (other + ''); } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isLoose) { return false; } var skipCtor = isLoose, index = -1; while (++index < objLength) { var key = objProps[index], result = isLoose ? key in other : hasOwnProperty.call(other, key); if (result) { var objValue = object[key], othValue = other[key]; result = undefined; if (customizer) { result = isLoose ? customizer(othValue, objValue, key) : customizer(objValue, othValue, key); } if (result === undefined) { // Recursively compare objects (susceptible to call stack limits). result = (objValue && objValue === othValue) || equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB); } } if (!result) { return false; } skipCtor || (skipCtor = key == 'constructor'); } if (!skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { return false; } } return true; } /** * Gets the extremum value of `collection` invoking `iteratee` for each value * in `collection` to generate the criterion by which the value is ranked. * The `iteratee` is invoked with three arguments: (value, index, collection). * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {boolean} [isMin] Specify returning the minimum, instead of the * maximum, extremum value. * @returns {*} Returns the extremum value. */ function extremumBy(collection, iteratee, isMin) { var exValue = isMin ? POSITIVE_INFINITY : NEGATIVE_INFINITY, computed = exValue, result = computed; baseEach(collection, function(value, index, collection) { var current = iteratee(value, index, collection); if ((isMin ? (current < computed) : (current > computed)) || (current === exValue && current === result)) { computed = current; result = value; } }); return result; } /** * Gets the appropriate "callback" function. If the `_.callback` method is * customized this function returns the custom method, otherwise it returns * the `baseCallback` function. If arguments are provided the chosen function * is invoked with them and its result is returned. * * @private * @returns {Function} Returns the chosen function or its result. */ function getCallback(func, thisArg, argCount) { var result = lodash.callback || callback; result = result === callback ? baseCallback : result; return argCount ? result(func, thisArg, argCount) : result; } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ var getFuncName = (function() { if (!support.funcNames) { return constant(''); } if (constant.name == 'constant') { return baseProperty('name'); } return function(func) { var result = func.name, array = realNames[result], length = array ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; }; }()); /** * Gets the appropriate "indexOf" function. If the `_.indexOf` method is * customized this function returns the custom method, otherwise it returns * the `baseIndexOf` function. If arguments are provided the chosen function * is invoked with them and its result is returned. * * @private * @returns {Function|number} Returns the chosen function or its result. */ function getIndexOf(collection, target, fromIndex) { var result = lodash.indexOf || indexOf; result = result === indexOf ? baseIndexOf : result; return collection ? result(collection, target, fromIndex) : result; } /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * in Safari on iOS 8.1 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); /** * Creates an array of the own symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !getOwnPropertySymbols ? constant([]) : function(object) { return getOwnPropertySymbols(toObject(object)); }; /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} [transforms] The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms ? transforms.length : 0; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add array properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { var Ctor = object.constructor; if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) { Ctor = Object; } return new Ctor; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return bufferClone(object); case boolTag: case dateTag: return new Ctor(+object); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: var buffer = object.buffer; return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length); case numberTag: case stringTag: return new Ctor(object); case regexpTag: var result = new Ctor(object.source, reFlags.exec(object)); result.lastIndex = object.lastIndex; } return result; } /** * Invokes the method at `path` on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function invokePath(object, path, args) { if (object != null && !isKey(path, object)) { path = toPath(path); object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); path = last(path); } var func = object == null ? object : object[path]; return func == null ? undefined : func.apply(object, args); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = +value; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } /** * Checks if the provided arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number') { var length = getLength(object), prereq = isLength(length) && isIndex(index, length); } else { prereq = type == 'string' && index in object; } if (prereq) { var other = object[index]; return value === value ? (value === other) : (other !== other); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { var type = typeof value; if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { return true; } if (isArray(value)) { return false; } var result = !reIsDeepProp.test(value); return result || (object != null && value in toObject(object)); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`. */ function isLaziable(func) { var funcName = getFuncName(func); return !!funcName && func === lodash[funcName] && funcName in LazyWrapper.prototype; } /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && (value === 0 ? ((1 / value) > 0) : !isObject(value)); } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers required to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg` * augment function arguments, making the order in which they are executed important, * preventing the merging of metadata. However, we make an exception for a safe * common case where curried functions have `_.ary` and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < ARY_FLAG; var isCombo = (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) || (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) || (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value); data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]); } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value); data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]); } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = arrayCopy(value); } // Use source `ary` if it's smaller. if (srcBitmask & ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * A specialized version of `_.pick` that picks `object` properties specified * by `props`. * * @private * @param {Object} object The source object. * @param {string[]} props The property names to pick. * @returns {Object} Returns the new object. */ function pickByArray(object, props) { object = toObject(object); var index = -1, length = props.length, result = {}; while (++index < length) { var key = props[index]; if (key in object) { result[key] = object[key]; } } return result; } /** * A specialized version of `_.pick` that picks `object` properties `predicate` * returns truthy for. * * @private * @param {Object} object The source object. * @param {Function} predicate The function invoked per iteration. * @returns {Object} Returns the new object. */ function pickByCallback(object, predicate) { var result = {}; baseForIn(object, function(value, key, object) { if (predicate(value, key, object)) { result[key] = value; } }); return result; } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = arrayCopy(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity function * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = (function() { var count = 0, lastCalled = 0; return function(key, value) { var stamp = now(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return key; } } else { count = 0; } return baseSetData(key, value); }; }()); /** * A fallback implementation of `_.isPlainObject` which checks if `value` * is an object created by the `Object` constructor or has a `[[Prototype]]` * of `null`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. */ function shimIsPlainObject(value) { var Ctor, support = lodash.support; // Exit early for non `Object` objects. if (!(isObjectLike(value) && objToString.call(value) == objectTag) || (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { return false; } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. var result; // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. baseForIn(value, function(subValue, key) { result = key; }); return result === undefined || hasOwnProperty.call(value, result); } /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length, support = lodash.support; var allowIndexes = length && isLength(length) && (isArray(object) || (support.nonEnumArgs && isArguments(object))); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } /** * Converts `value` to an array-like object if it is not one. * * @private * @param {*} value The value to process. * @returns {Array|Object} Returns the array-like object. */ function toIterable(value) { if (value == null) { return []; } if (!isLength(getLength(value))) { return values(value); } return isObject(value) ? value : Object(value); } /** * Converts `value` to an object if it is not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { return isObject(value) ? value : Object(value); } /** * Converts `value` to property path array if it is not one. * * @private * @param {*} value The value to process. * @returns {Array} Returns the property path array. */ function toPath(value) { if (isArray(value)) { return value; } var result = []; baseToString(value).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { return wrapper instanceof LazyWrapper ? wrapper.clone() : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__)); } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `collection` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the new array containing chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if (guard ? isIterateeCall(array, size, guard) : size == null) { size = 1; } else { size = nativeMax(+size || 1, 1); } var index = 0, length = array ? array.length : 0, resIndex = -1, result = Array(ceil(length / size)); while (index < length) { result[++resIndex] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array ? array.length : 0, resIndex = -1, result = []; while (++index < length) { var value = array[index]; if (value) { result[++resIndex] = value; } } return result; } /** * Creates an array excluding all values of the provided arrays using * `SameValueZero` for equality comparisons. * * **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * comparisons are like strict equality comparisons, e.g. `===`, except that * `NaN` matches `NaN`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The arrays of values to exclude. * @returns {Array} Returns the new array of filtered values. * @example * * _.difference([1, 2, 3], [4, 2]); * // => [1, 3] */ var difference = restParam(function(array, values) { return (isArray(array) || isArguments(array)) ? baseDifference(array, baseFlatten(values, false, true)) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } if (guard ? isIterateeCall(array, n, guard) : n == null) { n = 1; } return baseSlice(array, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } if (guard ? isIterateeCall(array, n, guard) : n == null) { n = 1; } n = length - (+n || 0); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * bound to `thisArg` and invoked with three arguments: (value, index, array). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that match the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRightWhile([1, 2, 3], function(n) { * return n > 1; * }); * // => [1] * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); * // => ['barney', 'fred'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.dropRightWhile(users, 'active', false), 'user'); * // => ['barney'] * * // using the `_.property` callback shorthand * _.pluck(_.dropRightWhile(users, 'active'), 'user'); * // => ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate, thisArg) { return (array && array.length) ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * bound to `thisArg` and invoked with three arguments: (value, index, array). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropWhile([1, 2, 3], function(n) { * return n < 3; * }); * // => [3] * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user'); * // => ['fred', 'pebbles'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.dropWhile(users, 'active', false), 'user'); * // => ['pebbles'] * * // using the `_.property` callback shorthand * _.pluck(_.dropWhile(users, 'active'), 'user'); * // => ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate, thisArg) { return (array && array.length) ? baseWhile(array, getCallback(predicate, thisArg, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8], '*', 1, 2); * // => [4, '*', 8] */ function fill(array, value, start, end) { var length = array ? array.length : 0; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(chr) { * return chr.user == 'barney'; * }); * // => 0 * * // using the `_.matches` callback shorthand * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // using the `_.matchesProperty` callback shorthand * _.findIndex(users, 'active', false); * // => 0 * * // using the `_.property` callback shorthand * _.findIndex(users, 'active'); * // => 2 */ var findIndex = createFindIndex(); /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(chr) { * return chr.user == 'pebbles'; * }); * // => 2 * * // using the `_.matches` callback shorthand * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // using the `_.matchesProperty` callback shorthand * _.findLastIndex(users, 'active', false); * // => 2 * * // using the `_.property` callback shorthand * _.findLastIndex(users, 'active'); * // => 0 */ var findLastIndex = createFindIndex(true); /** * Gets the first element of `array`. * * @static * @memberOf _ * @alias head * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.first([1, 2, 3]); * // => 1 * * _.first([]); * // => undefined */ function first(array) { return array ? array[0] : undefined; } /** * Flattens a nested array. If `isDeep` is `true` the array is recursively * flattened, otherwise it is only flattened a single level. * * @static * @memberOf _ * @category Array * @param {Array} array The array to flatten. * @param {boolean} [isDeep] Specify a deep flatten. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, 3, [4]]]); * // => [1, 2, 3, [4]] * * // using `isDeep` * _.flatten([1, [2, 3, [4]]], true); * // => [1, 2, 3, 4] */ function flatten(array, isDeep, guard) { var length = array ? array.length : 0; if (guard && isIterateeCall(array, isDeep, guard)) { isDeep = false; } return length ? baseFlatten(array, isDeep) : []; } /** * Recursively flattens a nested array. * * @static * @memberOf _ * @category Array * @param {Array} array The array to recursively flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, 3, [4]]]); * // => [1, 2, 3, 4] */ function flattenDeep(array) { var length = array ? array.length : 0; return length ? baseFlatten(array, true) : []; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using `SameValueZero` for equality comparisons. If `fromIndex` is negative, * it is used as the offset from the end of `array`. If `array` is sorted * providing `true` for `fromIndex` performs a faster binary search. * * **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * comparisons are like strict equality comparisons, e.g. `===`, except that * `NaN` matches `NaN`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {boolean|number} [fromIndex=0] The index to search from or `true` * to perform a binary search on a sorted array. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // using `fromIndex` * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 * * // performing a binary search * _.indexOf([1, 1, 2, 2], 2, true); * // => 2 */ function indexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } if (typeof fromIndex == 'number') { fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; } else if (fromIndex) { var index = binaryIndex(array, value), other = array[index]; if (value === value ? (value === other) : (other !== other)) { return index; } return -1; } return baseIndexOf(array, value, fromIndex || 0); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { return dropRight(array, 1); } /** * Creates an array of unique values in all provided arrays using `SameValueZero` * for equality comparisons. * * **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * comparisons are like strict equality comparisons, e.g. `===`, except that * `NaN` matches `NaN`. * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of shared values. * @example * _.intersection([1, 2], [4, 2], [2, 1]); * // => [2] */ function intersection() { var args = [], argsIndex = -1, argsLength = arguments.length, caches = [], indexOf = getIndexOf(), isCommon = indexOf == baseIndexOf, result = []; while (++argsIndex < argsLength) { var value = arguments[argsIndex]; if (isArray(value) || isArguments(value)) { args.push(value); caches.push((isCommon && value.length >= 120) ? createCache(argsIndex && value) : null); } } argsLength = args.length; if (argsLength < 2) { return result; } var array = args[0], index = -1, length = array ? array.length : 0, seen = caches[0]; outer: while (++index < length) { value = array[index]; if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) { argsIndex = argsLength; while (--argsIndex) { var cache = caches[argsIndex]; if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value, 0)) < 0) { continue outer; } } if (seen) { seen.push(value); } result.push(value); } } return result; } /** * Gets the last element of `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @category Array * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {boolean|number} [fromIndex=array.length-1] The index to search from * or `true` to perform a binary search on a sorted array. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // using `fromIndex` * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 * * // performing a binary search * _.lastIndexOf([1, 1, 2, 2], 2, true); * // => 3 */ function lastIndexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } var index = length; if (typeof fromIndex == 'number') { index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1; } else if (fromIndex) { index = binaryIndex(array, value, true) - 1; var other = array[index]; if (value === value ? (value === other) : (other !== other)) { return index; } return -1; } if (value !== value) { return indexOfNaN(array, index, true); } while (index--) { if (array[index] === value) { return index; } } return -1; } /** * Removes all provided values from `array` using `SameValueZero` for equality * comparisons. * * **Notes:** * - Unlike `_.without`, this method mutates `array` * - [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * comparisons are like strict equality comparisons, e.g. `===`, except * that `NaN` matches `NaN` * * @static * @memberOf _ * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3, 1, 2, 3]; * * _.pull(array, 2, 3); * console.log(array); * // => [1, 1] */ function pull() { var args = arguments, array = args[0]; if (!(array && array.length)) { return array; } var index = 0, indexOf = getIndexOf(), length = args.length; while (++index < length) { var fromIndex = 0, value = args[index]; while ((fromIndex = indexOf(array, value, fromIndex)) > -1) { splice.call(array, fromIndex, 1); } } return array; } /** * Removes elements from `array` corresponding to the given indexes and returns * an array of the removed elements. Indexes may be specified as an array of * indexes or as individual arguments. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove, * specified as individual indexes or arrays of indexes. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [5, 10, 15, 20]; * var evens = _.pullAt(array, 1, 3); * * console.log(array); * // => [5, 15] * * console.log(evens); * // => [10, 20] */ var pullAt = restParam(function(array, indexes) { array || (array = []); indexes = baseFlatten(indexes); var result = baseAt(array, indexes); basePullAt(array, indexes.sort(baseCompareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is bound to * `thisArg` and invoked with three arguments: (value, index, array). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * **Note:** Unlike `_.filter`, this method mutates `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to modify. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate, thisArg) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getCallback(predicate, thisArg, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @alias tail * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.rest([1, 2, 3]); * // => [2, 3] */ function rest(array) { return drop(array, 1); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of `Array#slice` to support node * lists in IE < 9 and to ensure dense arrays are returned. * * @static * @memberOf _ * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array ? array.length : 0; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` should * be inserted into `array` in order to maintain its sort order. If an iteratee * function is provided it is invoked for `value` and each element of `array` * to compute their sort ranking. The iteratee is bound to `thisArg` and * invoked with one argument; (value). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 * * _.sortedIndex([4, 4, 5, 5], 5); * // => 2 * * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } }; * * // using an iteratee function * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) { * return this.data[word]; * }, dict); * // => 1 * * // using the `_.property` callback shorthand * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); * // => 1 */ var sortedIndex = createSortedIndex(); /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 4, 5, 5], 5); * // => 4 */ var sortedLastIndex = createSortedIndex(true); /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } if (guard ? isIterateeCall(array, n, guard) : n == null) { n = 1; } return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } if (guard ? isIterateeCall(array, n, guard) : n == null) { n = 1; } n = length - (+n || 0); return baseSlice(array, n < 0 ? 0 : n); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is bound to `thisArg` * and invoked with three arguments: (value, index, array). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRightWhile([1, 2, 3], function(n) { * return n > 1; * }); * // => [2, 3] * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); * // => ['pebbles'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.takeRightWhile(users, 'active', false), 'user'); * // => ['fred', 'pebbles'] * * // using the `_.property` callback shorthand * _.pluck(_.takeRightWhile(users, 'active'), 'user'); * // => [] */ function takeRightWhile(array, predicate, thisArg) { return (array && array.length) ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is bound to * `thisArg` and invoked with three arguments: (value, index, array). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeWhile([1, 2, 3], function(n) { * return n < 3; * }); * // => [1, 2] * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false}, * { 'user': 'pebbles', 'active': true } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user'); * // => ['barney'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.takeWhile(users, 'active', false), 'user'); * // => ['barney', 'fred'] * * // using the `_.property` callback shorthand * _.pluck(_.takeWhile(users, 'active'), 'user'); * // => [] */ function takeWhile(array, predicate, thisArg) { return (array && array.length) ? baseWhile(array, getCallback(predicate, thisArg, 3)) : []; } /** * Creates an array of unique values, in order, of the provided arrays using * `SameValueZero` for equality comparisons. * * **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * comparisons are like strict equality comparisons, e.g. `===`, except that * `NaN` matches `NaN`. * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([1, 2], [4, 2], [2, 1]); * // => [1, 2, 4] */ var union = restParam(function(arrays) { return baseUniq(baseFlatten(arrays, false, true)); }); /** * Creates a duplicate-free version of an array, using `SameValueZero` for * equality comparisons, in which only the first occurence of each element * is kept. Providing `true` for `isSorted` performs a faster search algorithm * for sorted arrays. If an iteratee function is provided it is invoked for * each element in the array to generate the criterion by which uniqueness * is computed. The `iteratee` is bound to `thisArg` and invoked with three * arguments: (value, index, array). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * comparisons are like strict equality comparisons, e.g. `===`, except that * `NaN` matches `NaN`. * * @static * @memberOf _ * @alias unique * @category Array * @param {Array} array The array to inspect. * @param {boolean} [isSorted] Specify the array is sorted. * @param {Function|Object|string} [iteratee] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new duplicate-value-free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] * * // using `isSorted` * _.uniq([1, 1, 2], true); * // => [1, 2] * * // using an iteratee function * _.uniq([1, 2.5, 1.5, 2], function(n) { * return this.floor(n); * }, Math); * // => [1, 2.5] * * // using the `_.property` callback shorthand * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniq(array, isSorted, iteratee, thisArg) { var length = array ? array.length : 0; if (!length) { return []; } if (isSorted != null && typeof isSorted != 'boolean') { thisArg = iteratee; iteratee = isIterateeCall(array, isSorted, thisArg) ? null : isSorted; isSorted = false; } var func = getCallback(); if (!(func === baseCallback && iteratee == null)) { iteratee = func(iteratee, thisArg, 3); } return (isSorted && getIndexOf() == baseIndexOf) ? sortedUniq(array, iteratee) : baseUniq(array, iteratee); } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-`_.zip` * configuration. * * @static * @memberOf _ * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]); * // => [['fred', 30, true], ['barney', 40, false]] * * _.unzip(zipped); * // => [['fred', 'barney'], [30, 40], [true, false]] */ function unzip(array) { var index = -1, length = (array && array.length && arrayMax(arrayMap(array, getLength))) >>> 0, result = Array(length); while (++index < length) { result[index] = arrayMap(array, baseProperty(index)); } return result; } /** * Creates an array excluding all provided values using `SameValueZero` for * equality comparisons. * * **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * comparisons are like strict equality comparisons, e.g. `===`, except that * `NaN` matches `NaN`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to filter. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @example * * _.without([1, 2, 1, 3], 1, 2); * // => [3] */ var without = restParam(function(array, values) { return (isArray(array) || isArguments(array)) ? baseDifference(array, values) : []; }); /** * Creates an array that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the provided arrays. * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of values. * @example * * _.xor([1, 2], [4, 2]); * // => [1, 4] */ function xor() { var index = -1, length = arguments.length; while (++index < length) { var array = arguments[index]; if (isArray(array) || isArguments(array)) { var result = result ? baseDifference(result, array).concat(baseDifference(array, result)) : array; } } return result ? baseUniq(result) : []; } /** * Creates an array of grouped elements, the first of which contains the first * elements of the given arrays, the second of which contains the second elements * of the given arrays, and so on. * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['fred', 'barney'], [30, 40], [true, false]); * // => [['fred', 30, true], ['barney', 40, false]] */ var zip = restParam(unzip); /** * The inverse of `_.pairs`; this method returns an object composed from arrays * of property names and values. Provide either a single two dimensional array, * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names * and one of corresponding values. * * @static * @memberOf _ * @alias object * @category Array * @param {Array} props The property names. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject([['fred', 30], ['barney', 40]]); * // => { 'fred': 30, 'barney': 40 } * * _.zipObject(['fred', 'barney'], [30, 40]); * // => { 'fred': 30, 'barney': 40 } */ function zipObject(props, values) { var index = -1, length = props ? props.length : 0, result = {}; if (length && !values && !isArray(props[0])) { values = []; } while (++index < length) { var key = props[index]; if (values) { result[key] = values[index]; } else if (key) { result[key[0]] = key[1]; } } return result; } /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object that wraps `value` with explicit method * chaining enabled. * * @static * @memberOf _ * @category Chain * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _.chain(users) * .sortBy('age') * .map(function(chr) { * return chr.user + ' is ' + chr.age; * }) * .first() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor is * bound to `thisArg` and invoked with one argument; (value). The purpose of * this method is to "tap into" a method chain in order to perform operations * on intermediate results within the chain. * * @static * @memberOf _ * @category Chain * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @param {*} [thisArg] The `this` binding of `interceptor`. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor, thisArg) { interceptor.call(thisArg, value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * * @static * @memberOf _ * @category Chain * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @param {*} [thisArg] The `this` binding of `interceptor`. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor, thisArg) { return interceptor.call(thisArg, value); } /** * Enables explicit method chaining on the wrapper object. * * @name chain * @memberOf _ * @category Chain * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // without explicit chaining * _(users).first(); * // => { 'user': 'barney', 'age': 36 } * * // with explicit chaining * _(users).chain() * .first() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chained sequence and returns the wrapped result. * * @name commit * @memberOf _ * @category Chain * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapper = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapper = wrapper.commit(); * console.log(array); * // => [1, 2, 3] * * wrapper.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Creates a clone of the chained sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @category Chain * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapper = _(array).map(function(value) { * return Math.pow(value, 2); * }); * * var other = [3, 4]; * var otherWrapper = wrapper.plant(other); * * otherWrapper.value(); * // => [9, 16] * * wrapper.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * Reverses the wrapped array so the first element becomes the last, the * second element becomes the second to last, and so on. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @category Chain * @returns {Object} Returns the new reversed `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { if (this.__actions__.length) { value = new LazyWrapper(this); } return new LodashWrapper(value.reverse(), this.__chain__); } return this.thru(function(value) { return value.reverse(); }); } /** * Produces the result of coercing the unwrapped value to a string. * * @name toString * @memberOf _ * @category Chain * @returns {string} Returns the coerced string value. * @example * * _([1, 2, 3]).toString(); * // => '1,2,3' */ function wrapperToString() { return (this.value() + ''); } /** * Executes the chained sequence to extract the unwrapped value. * * @name value * @memberOf _ * @alias run, toJSON, valueOf * @category Chain * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an array of elements corresponding to the given keys, or indexes, * of `collection`. Keys may be specified as individual arguments or as arrays * of keys. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {...(number|number[]|string|string[])} [props] The property names * or indexes of elements to pick, specified individually or in arrays. * @returns {Array} Returns the new array of picked elements. * @example * * _.at(['a', 'b', 'c'], [0, 2]); * // => ['a', 'c'] * * _.at(['barney', 'fred', 'pebbles'], 0, 2); * // => ['barney', 'pebbles'] */ var at = restParam(function(collection, props) { var length = collection ? getLength(collection) : 0; if (isLength(length)) { collection = toIterable(collection); } return baseAt(collection, baseFlatten(props)); }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` through `iteratee`. The corresponding value * of each key is the number of times the key was returned by `iteratee`. * The `iteratee` is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([4.3, 6.1, 6.4], function(n) { * return Math.floor(n); * }); * // => { '4': 1, '6': 2 } * * _.countBy([4.3, 6.1, 6.4], function(n) { * return this.floor(n); * }, Math); * // => { '4': 1, '6': 2 } * * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1); }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * The predicate is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias all * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false } * ]; * * // using the `_.matches` callback shorthand * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // using the `_.matchesProperty` callback shorthand * _.every(users, 'active', false); * // => true * * // using the `_.property` callback shorthand * _.every(users, 'active'); * // => false */ function every(collection, predicate, thisArg) { var func = isArray(collection) ? arrayEvery : baseEvery; if (thisArg && isIterateeCall(collection, predicate, thisArg)) { predicate = null; } if (typeof predicate != 'function' || thisArg !== undefined) { predicate = getCallback(predicate, thisArg, 3); } return func(collection, predicate); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is bound to `thisArg` and * invoked with three arguments: (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias select * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the new filtered array. * @example * * _.filter([4, 5, 6], function(n) { * return n % 2 == 0; * }); * // => [4, 6] * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user'); * // => ['barney'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.filter(users, 'active', false), 'user'); * // => ['fred'] * * // using the `_.property` callback shorthand * _.pluck(_.filter(users, 'active'), 'user'); * // => ['barney'] */ function filter(collection, predicate, thisArg) { var func = isArray(collection) ? arrayFilter : baseFilter; predicate = getCallback(predicate, thisArg, 3); return func(collection, predicate); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is bound to `thisArg` and * invoked with three arguments: (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias detect * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.result(_.find(users, function(chr) { * return chr.age < 40; * }), 'user'); * // => 'barney' * * // using the `_.matches` callback shorthand * _.result(_.find(users, { 'age': 1, 'active': true }), 'user'); * // => 'pebbles' * * // using the `_.matchesProperty` callback shorthand * _.result(_.find(users, 'active', false), 'user'); * // => 'fred' * * // using the `_.property` callback shorthand * _.result(_.find(users, 'active'), 'user'); * // => 'barney' */ var find = createFind(baseEach); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(baseEachRight, true); /** * Performs a deep comparison between each element in `collection` and the * source object, returning the first element that has equivalent property * values. * * **Note:** This method supports comparing arrays, booleans, `Date` objects, * numbers, `Object` objects, regexes, and strings. Objects are compared by * their own, not inherited, enumerable properties. For comparing a single * own or inherited property value see `_.matchesProperty`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {Object} source The object of property values to match. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user'); * // => 'barney' * * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user'); * // => 'fred' */ function findWhere(collection, source) { return find(collection, baseMatches(source)); } /** * Iterates over elements of `collection` invoking `iteratee` for each element. * The `iteratee` is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). Iteratee functions may exit iteration early * by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" property * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` * may be used for object iteration. * * @static * @memberOf _ * @alias each * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2]).forEach(function(n) { * console.log(n); * }).value(); * // => logs each value from left to right and returns the array * * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) { * console.log(n, key); * }); * // => logs each value-key pair and returns the object (iteration order is not guaranteed) */ var forEach = createForEach(arrayEach, baseEach); /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @alias eachRight * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2]).forEachRight(function(n) { * console.log(n); * }).value(); * // => logs each value from right to left and returns the array */ var forEachRight = createForEach(arrayEachRight, baseEachRight); /** * Creates an object composed of keys generated from the results of running * each element of `collection` through `iteratee`. The corresponding value * of each key is an array of the elements responsible for generating the key. * The `iteratee` is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([4.2, 6.1, 6.4], function(n) { * return Math.floor(n); * }); * // => { '4': [4.2], '6': [6.1, 6.4] } * * _.groupBy([4.2, 6.1, 6.4], function(n) { * return this.floor(n); * }, Math); * // => { '4': [4.2], '6': [6.1, 6.4] } * * // using the `_.property` callback shorthand * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { result[key] = [value]; } }); /** * Checks if `value` is in `collection` using `SameValueZero` for equality * comparisons. If `fromIndex` is negative, it is used as the offset from * the end of `collection`. * * **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) * comparisons are like strict equality comparisons, e.g. `===`, except that * `NaN` matches `NaN`. * * @static * @memberOf _ * @alias contains, include * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {*} target The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. * @returns {boolean} Returns `true` if a matching element is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'user': 'fred', 'age': 40 }, 'fred'); * // => true * * _.includes('pebbles', 'eb'); * // => true */ function includes(collection, target, fromIndex, guard) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { collection = values(collection); length = collection.length; } if (!length) { return false; } if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) { fromIndex = 0; } else { fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0); } return (typeof collection == 'string' || !isArray(collection) && isString(collection)) ? (fromIndex < length && collection.indexOf(target, fromIndex) > -1) : (getIndexOf(collection, target, fromIndex) > -1); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` through `iteratee`. The corresponding value * of each key is the last element responsible for generating the key. The * iteratee function is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns the composed aggregate object. * @example * * var keyData = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.indexBy(keyData, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } * * _.indexBy(keyData, function(object) { * return String.fromCharCode(object.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.indexBy(keyData, function(object) { * return this.fromCharCode(object.code); * }, String); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } */ var indexBy = createAggregator(function(result, value, key) { result[key] = value; }); /** * Invokes the method at `path` on each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `methodName` is a function it is * invoked for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke the method with. * @returns {Array} Returns the array of results. * @example * * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invoke([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invoke = restParam(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', isProp = isKey(path), length = getLength(collection), result = isLength(length) ? Array(length) : []; baseEach(collection, function(value) { var func = isFunc ? path : (isProp && value != null && value[path]); result[++index] = func ? func.apply(value, args) : invokePath(value, path, args); }); return result; }); /** * Creates an array of values by running each element in `collection` through * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three * arguments: (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * Many lodash methods are guarded to work as interatees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, `drop`, * `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`, `parseInt`, * `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`, `trimLeft`, * `trimRight`, `trunc`, `random`, `range`, `sample`, `some`, `uniq`, and `words` * * @static * @memberOf _ * @alias collect * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new mapped array. * @example * * function timesThree(n) { * return n * 3; * } * * _.map([1, 2], timesThree); * // => [3, 6] * * _.map({ 'a': 1, 'b': 2 }, timesThree); * // => [3, 6] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // using the `_.property` callback shorthand * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee, thisArg) { var func = isArray(collection) ? arrayMap : baseMap; iteratee = getCallback(iteratee, thisArg, 3); return func(collection, iteratee); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, while the second of which * contains elements `predicate` returns falsey for. The predicate is bound * to `thisArg` and invoked with three arguments: (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the array of grouped elements. * @example * * _.partition([1, 2, 3], function(n) { * return n % 2; * }); * // => [[1, 3], [2]] * * _.partition([1.2, 2.3, 3.4], function(n) { * return this.floor(n) % 2; * }, Math); * // => [[1.2, 3.4], [2.3]] * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * var mapper = function(array) { * return _.pluck(array, 'user'); * }; * * // using the `_.matches` callback shorthand * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper); * // => [['pebbles'], ['barney', 'fred']] * * // using the `_.matchesProperty` callback shorthand * _.map(_.partition(users, 'active', false), mapper); * // => [['barney', 'pebbles'], ['fred']] * * // using the `_.property` callback shorthand * _.map(_.partition(users, 'active'), mapper); * // => [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Gets the property value of `path` from all elements in `collection`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Array|string} path The path of the property to pluck. * @returns {Array} Returns the property values. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * _.pluck(users, 'user'); * // => ['barney', 'fred'] * * var userIndex = _.indexBy(users, 'user'); * _.pluck(userIndex, 'age'); * // => [36, 40] (iteration order is not guaranteed) */ function pluck(collection, path) { return map(collection, property(path)); } /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` through `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not provided the first element of `collection` is used as the initial * value. The `iteratee` is bound to `thisArg` and invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as interatees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `includes`, `merge`, `sortByAll`, and `sortByOrder` * * @static * @memberOf _ * @alias foldl, inject * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {*} Returns the accumulated value. * @example * * _.reduce([1, 2], function(total, n) { * return total + n; * }); * // => 3 * * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) { * result[key] = n * 3; * return result; * }, {}); * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed) */ var reduce = createReduce(arrayReduce, baseEach); /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @alias foldr * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {*} Returns the accumulated value. * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ var reduceRight = createReduce(arrayReduceRight, baseEachRight); /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Array} Returns the new filtered array. * @example * * _.reject([1, 2, 3, 4], function(n) { * return n % 2 == 0; * }); * // => [1, 3] * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * // using the `_.matches` callback shorthand * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user'); * // => ['barney'] * * // using the `_.matchesProperty` callback shorthand * _.pluck(_.reject(users, 'active', false), 'user'); * // => ['fred'] * * // using the `_.property` callback shorthand * _.pluck(_.reject(users, 'active'), 'user'); * // => ['barney'] */ function reject(collection, predicate, thisArg) { var func = isArray(collection) ? arrayFilter : baseFilter; predicate = getCallback(predicate, thisArg, 3); return func(collection, function(value, index, collection) { return !predicate(value, index, collection); }); } /** * Gets a random element or `n` random elements from a collection. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to sample. * @param {number} [n] The number of elements to sample. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {*} Returns the random sample(s). * @example * * _.sample([1, 2, 3, 4]); * // => 2 * * _.sample([1, 2, 3, 4], 2); * // => [3, 1] */ function sample(collection, n, guard) { if (guard ? isIterateeCall(collection, n, guard) : n == null) { collection = toIterable(collection); var length = collection.length; return length > 0 ? collection[baseRandom(0, length - 1)] : undefined; } var result = shuffle(collection); result.length = nativeMin(n < 0 ? 0 : (+n || 0), result.length); return result; } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { collection = toIterable(collection); var index = -1, length = collection.length, result = Array(length); while (++index < length) { var rand = baseRandom(0, index); if (index != rand) { result[index] = result[rand]; } result[rand] = collection[index]; } return result; } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable properties for objects. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the size of `collection`. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { var length = collection ? getLength(collection) : 0; return isLength(length) ? length : keys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * The function returns as soon as it finds a passing value and does not iterate * over the entire collection. The predicate is bound to `thisArg` and invoked * with three arguments: (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias any * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // using the `_.matches` callback shorthand * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // using the `_.matchesProperty` callback shorthand * _.some(users, 'active', false); * // => true * * // using the `_.property` callback shorthand * _.some(users, 'active'); * // => true */ function some(collection, predicate, thisArg) { var func = isArray(collection) ? arraySome : baseSome; if (thisArg && isIterateeCall(collection, predicate, thisArg)) { predicate = null; } if (typeof predicate != 'function' || thisArg !== undefined) { predicate = getCallback(predicate, thisArg, 3); } return func(collection, predicate); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection through `iteratee`. This method performs * a stable sort, that is, it preserves the original sort order of equal elements. * The `iteratee` is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the new sorted array. * @example * * _.sortBy([1, 2, 3], function(n) { * return Math.sin(n); * }); * // => [3, 1, 2] * * _.sortBy([1, 2, 3], function(n) { * return this.sin(n); * }, Math); * // => [3, 1, 2] * * var users = [ * { 'user': 'fred' }, * { 'user': 'pebbles' }, * { 'user': 'barney' } * ]; * * // using the `_.property` callback shorthand * _.pluck(_.sortBy(users, 'user'), 'user'); * // => ['barney', 'fred', 'pebbles'] */ function sortBy(collection, iteratee, thisArg) { if (collection == null) { return []; } if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { iteratee = null; } var index = -1; iteratee = getCallback(iteratee, thisArg, 3); var result = baseMap(collection, function(value, key, collection) { return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value }; }); return baseSortBy(result, compareAscending); } /** * This method is like `_.sortBy` except that it can sort by multiple iteratees * or property names. * * If a property name is provided for an iteratee the created `_.property` * style callback returns the property value of the given element. * * If an object is provided for an iteratee the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees * The iteratees to sort by, specified as individual values or arrays of values. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 42 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.map(_.sortByAll(users, ['user', 'age']), _.values); * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] * * _.map(_.sortByAll(users, 'user', function(chr) { * return Math.floor(chr.age / 10); * }), _.values); * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] */ var sortByAll = restParam(function(collection, iteratees) { if (collection == null) { return []; } var guard = iteratees[2]; if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) { iteratees.length = 1; } return baseSortByOrder(collection, baseFlatten(iteratees), []); }); /** * This method is like `_.sortByAll` except that it allows specifying the * sort orders of the iteratees to sort by. A truthy value in `orders` will * sort the corresponding property name in ascending order while a falsey * value will sort it in descending order. * * If a property name is provided for an iteratee the created `_.property` * style callback returns the property value of the given element. * * If an object is provided for an iteratee the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {boolean[]} orders The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 42 }, * { 'user': 'barney', 'age': 36 } * ]; * * // sort by `user` in ascending order and by `age` in descending order * _.map(_.sortByOrder(users, ['user', 'age'], [true, false]), _.values); * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] */ function sortByOrder(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (guard && isIterateeCall(iteratees, orders, guard)) { orders = null; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseSortByOrder(collection, iteratees, orders); } /** * Performs a deep comparison between each element in `collection` and the * source object, returning an array of all elements that have equivalent * property values. * * **Note:** This method supports comparing arrays, booleans, `Date` objects, * numbers, `Object` objects, regexes, and strings. Objects are compared by * their own, not inherited, enumerable properties. For comparing a single * own or inherited property value see `_.matchesProperty`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {Object} source The object of property values to match. * @returns {Array} Returns the new filtered array. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] }, * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] } * ]; * * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user'); * // => ['barney'] * * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user'); * // => ['fred'] */ function where(collection, source) { return filter(collection, baseMatches(source)); } /*------------------------------------------------------------------------*/ /** * Gets the number of milliseconds that have elapsed since the Unix epoch * (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @category Date * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => logs the number of milliseconds it took for the deferred function to be invoked */ var now = nativeNow || function() { return new Date().getTime(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it is called `n` or more times. * * @static * @memberOf _ * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => logs 'done saving!' after the two async saves have completed */ function after(n, func) { if (typeof func != 'function') { if (typeof n == 'function') { var temp = n; n = func; func = temp; } else { throw new TypeError(FUNC_ERROR_TEXT); } } n = nativeIsFinite(n = +n) ? n : 0; return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that accepts up to `n` arguments ignoring any * additional arguments. * * @static * @memberOf _ * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Function} Returns the new function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { if (guard && isIterateeCall(func, n, guard)) { n = null; } n = (func && n == null) ? func.length : nativeMax(+n || 0, 0); return createWrapper(func, ARY_FLAG, null, null, null, null, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it is called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery('#add').on('click', _.before(5, addContactToList)); * // => allows adding up to 4 contacts to the list */ function before(n, func) { var result; if (typeof func != 'function') { if (typeof n == 'function') { var temp = n; n = func; func = temp; } else { throw new TypeError(FUNC_ERROR_TEXT); } } return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = null; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and prepends any additional `_.bind` arguments to those provided to the * bound function. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind` this method does not set the "length" * property of bound functions. * * @static * @memberOf _ * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var greet = function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * }; * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // using placeholders * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = restParam(function(func, thisArg, partials) { var bitmask = BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, bind.placeholder); bitmask |= PARTIAL_FLAG; } return createWrapper(func, bitmask, thisArg, partials, holders); }); /** * Binds methods of an object to the object itself, overwriting the existing * method. Method names may be specified as individual arguments or as arrays * of method names. If no method names are provided all enumerable function * properties, own and inherited, of `object` are bound. * * **Note:** This method does not set the "length" property of bound functions. * * @static * @memberOf _ * @category Function * @param {Object} object The object to bind and assign the bound methods to. * @param {...(string|string[])} [methodNames] The object method names to bind, * specified as individual method names or arrays of method names. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'onClick': function() { * console.log('clicked ' + this.label); * } * }; * * _.bindAll(view); * jQuery('#docs').on('click', view.onClick); * // => logs 'clicked docs' when the element is clicked */ var bindAll = restParam(function(object, methodNames) { methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object); var index = -1, length = methodNames.length; while (++index < length) { var key = methodNames[index]; object[key] = createWrapper(object[key], BIND_FLAG, object); } return object; }); /** * Creates a function that invokes the method at `object[key]` and prepends * any additional `_.bindKey` arguments to those provided to the bound function. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @category Function * @param {Object} object The object the method belongs to. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // using placeholders * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = restParam(function(object, key, partials) { var bitmask = BIND_FLAG | BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, bindKey.placeholder); bitmask |= PARTIAL_FLAG; } return createWrapper(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts one or more arguments of `func` that when * called either invokes `func` returning its result, if all `func` arguments * have been provided, or returns a function that accepts one or more of the * remaining `func` arguments, and so on. The arity of `func` may be specified * if `func.length` is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method does not set the "length" property of curried functions. * * @static * @memberOf _ * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // using placeholders * curried(1)(_, 3)(2); * // => [1, 2, 3] */ var curry = createCurry(CURRY_FLAG); /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method does not set the "length" property of curried functions. * * @static * @memberOf _ * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // using placeholders * curried(3)(1, _)(2); * // => [1, 2, 3] */ var curryRight = createCurry(CURRY_RIGHT_FLAG); /** * Creates a function that delays invoking `func` until after `wait` milliseconds * have elapsed since the last time it was invoked. The created function comes * with a `cancel` method to cancel delayed invocations. Provide an options * object to indicate that `func` should be invoked on the leading and/or * trailing edge of the `wait` timeout. Subsequent calls to the debounced * function return the result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked * on the trailing edge of the timeout only if the the debounced function is * invoked more than once during the `wait` timeout. * * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options] The options object. * @param {boolean} [options.leading=false] Specify invoking on the leading * edge of the timeout. * @param {number} [options.maxWait] The maximum time `func` is allowed to be * delayed before it is invoked. * @param {boolean} [options.trailing=true] Specify invoking on the trailing * edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // avoid costly calculations while the window size is in flux * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // invoke `sendMail` when the click event is fired, debouncing subsequent calls * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // ensure `batchLog` is invoked once after 1 second of debounced calls * var source = new EventSource('/stream'); * jQuery(source).on('message', _.debounce(batchLog, 250, { * 'maxWait': 1000 * })); * * // cancel a debounced call * var todoChanges = _.debounce(batchLog, 1000); * Object.observe(models.todo, todoChanges); * * Object.observe(models, function(changes) { * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) { * todoChanges.cancel(); * } * }, ['delete']); * * // ...at some point `models.todo` is changed * models.todo.completed = true; * * // ...before 1 second has passed `models.todo` is deleted * // which cancels the debounced `todoChanges` call * delete models.todo; */ function debounce(func, wait, options) { var args, maxTimeoutId, result, stamp, thisArg, timeoutId, trailingCall, lastCalled = 0, maxWait = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = wait < 0 ? 0 : (+wait || 0); if (options === true) { var leading = true; trailing = false; } else if (isObject(options)) { leading = options.leading; maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait); trailing = 'trailing' in options ? options.trailing : trailing; } function cancel() { if (timeoutId) { clearTimeout(timeoutId); } if (maxTimeoutId) { clearTimeout(maxTimeoutId); } maxTimeoutId = timeoutId = trailingCall = undefined; } function delayed() { var remaining = wait - (now() - stamp); if (remaining <= 0 || remaining > wait) { if (maxTimeoutId) { clearTimeout(maxTimeoutId); } var isCalled = trailingCall; maxTimeoutId = timeoutId = trailingCall = undefined; if (isCalled) { lastCalled = now(); result = func.apply(thisArg, args); if (!timeoutId && !maxTimeoutId) { args = thisArg = null; } } } else { timeoutId = setTimeout(delayed, remaining); } } function maxDelayed() { if (timeoutId) { clearTimeout(timeoutId); } maxTimeoutId = timeoutId = trailingCall = undefined; if (trailing || (maxWait !== wait)) { lastCalled = now(); result = func.apply(thisArg, args); if (!timeoutId && !maxTimeoutId) { args = thisArg = null; } } } function debounced() { args = arguments; stamp = now(); thisArg = this; trailingCall = trailing && (timeoutId || !leading); if (maxWait === false) { var leadingCall = leading && !timeoutId; } else { if (!maxTimeoutId && !leading) { lastCalled = stamp; } var remaining = maxWait - (stamp - lastCalled), isCalled = remaining <= 0 || remaining > maxWait; if (isCalled) { if (maxTimeoutId) { maxTimeoutId = clearTimeout(maxTimeoutId); } lastCalled = stamp; result = func.apply(thisArg, args); } else if (!maxTimeoutId) { maxTimeoutId = setTimeout(maxDelayed, remaining); } } if (isCalled && timeoutId) { timeoutId = clearTimeout(timeoutId); } else if (!timeoutId && wait !== maxWait) { timeoutId = setTimeout(delayed, wait); } if (leadingCall) { isCalled = true; result = func.apply(thisArg, args); } if (isCalled && !timeoutId && !maxTimeoutId) { args = thisArg = null; } return result; } debounced.cancel = cancel; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it is invoked. * * @static * @memberOf _ * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke the function with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // logs 'deferred' after one or more milliseconds */ var defer = restParam(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it is invoked. * * @static * @memberOf _ * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke the function with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => logs 'later' after one second */ var delay = restParam(function(func, wait, args) { return baseDelay(func, wait, args); }); /** * Creates a function that returns the result of invoking the provided * functions with the `this` binding of the created function, where each * successive invocation is supplied the return value of the previous. * * @static * @memberOf _ * @category Function * @param {...Function} [funcs] Functions to invoke. * @returns {Function} Returns the new function. * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flow(_.add, square); * addSquare(1, 2); * // => 9 */ var flow = createFlow(); /** * This method is like `_.flow` except that it creates a function that * invokes the provided functions from right to left. * * @static * @memberOf _ * @alias backflow, compose * @category Function * @param {...Function} [funcs] Functions to invoke. * @returns {Function} Returns the new function. * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight(square, _.add); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is coerced to a string and used as the * cache key. The `func` is invoked with the `this` binding of the memoized * function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the [`Map`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-map-prototype-object) * method interface of `get`, `has`, and `set`. * * @static * @memberOf _ * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoizing function. * @example * * var upperCase = _.memoize(function(string) { * return string.toUpperCase(); * }); * * upperCase('fred'); * // => 'FRED' * * // modifying the result cache * upperCase.cache.set('fred', 'BARNEY'); * upperCase('fred'); * // => 'BARNEY' * * // replacing `_.memoize.Cache` * var object = { 'user': 'fred' }; * var other = { 'user': 'barney' }; * var identity = _.memoize(_.identity); * * identity(object); * // => { 'user': 'fred' } * identity(other); * // => { 'user': 'fred' } * * _.memoize.Cache = WeakMap; * var identity = _.memoize(_.identity); * * identity(object); * // => { 'user': 'fred' } * identity(other); * // => { 'user': 'barney' } */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, cache = memoized.cache, key = resolver ? resolver.apply(this, args) : args[0]; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); cache.set(key, result); return result; }; memoized.cache = new memoize.Cache; return memoized; } /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { return !predicate.apply(this, arguments); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first call. The `func` is invoked * with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // `initialize` invokes `createApplication` once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with `partial` arguments prepended * to those provided to the new function. This method is like `_.bind` except * it does **not** alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method does not set the "length" property of partially * applied functions. * * @static * @memberOf _ * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { * return greeting + ' ' + name; * }; * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // using placeholders * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = createPartial(PARTIAL_FLAG); /** * This method is like `_.partial` except that partially applied arguments * are appended to those provided to the new function. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method does not set the "length" property of partially * applied functions. * * @static * @memberOf _ * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { * return greeting + ' ' + name; * }; * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // using placeholders * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = createPartial(PARTIAL_RIGHT_FLAG); /** * Creates a function that invokes `func` with arguments arranged according * to the specified indexes where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes, * specified as individual indexes or arrays of indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, 2, 0, 1); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] * * var map = _.rearg(_.map, [1, 0]); * map(function(n) { * return n * 3; * }, [1, 2, 3]); * // => [3, 6, 9] */ var rearg = restParam(function(func, indexes) { return createWrapper(func, REARG_FLAG, null, null, null, baseFlatten(indexes)); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters). * * @static * @memberOf _ * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.restParam(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } /** * Creates a function that invokes `func` with the `this` binding of the created * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3). * * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). * * @static * @memberOf _ * @category Function * @param {Function} func The function to spread arguments over. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * // with a Promise * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function(array) { return func.apply(this, array); }; } /** * Creates a function that only invokes `func` at most once per every `wait` * milliseconds. The created function comes with a `cancel` method to cancel * delayed invocations. Provide an options object to indicate that `func` * should be invoked on the leading and/or trailing edge of the `wait` timeout. * Subsequent calls to the throttled function return the result of the last * `func` call. * * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked * on the trailing edge of the timeout only if the the throttled function is * invoked more than once during the `wait` timeout. * * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options] The options object. * @param {boolean} [options.leading=true] Specify invoking on the leading * edge of the timeout. * @param {boolean} [options.trailing=true] Specify invoking on the trailing * edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // avoid excessively updating the position while scrolling * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { * 'trailing': false * })); * * // cancel a trailing throttled call * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (options === false) { leading = false; } else if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } debounceOptions.leading = leading; debounceOptions.maxWait = +wait; debounceOptions.trailing = trailing; return debounce(func, wait, debounceOptions); } /** * Creates a function that provides `value` to the wrapper function as its * first argument. Any additional arguments provided to the function are * appended to those provided to the wrapper function. The wrapper is invoked * with the `this` binding of the created function. * * @static * @memberOf _ * @category Function * @param {*} value The value to wrap. * @param {Function} wrapper The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('fred, barney, & pebbles'); * // => '<p>fred, barney, & pebbles</p>' */ function wrap(value, wrapper) { wrapper = wrapper == null ? identity : wrapper; return createWrapper(wrapper, PARTIAL_FLAG, null, [value], []); } /*------------------------------------------------------------------------*/ /** * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned, * otherwise they are assigned by reference. If `customizer` is provided it is * invoked to produce the cloned values. If `customizer` returns `undefined` * cloning is handled by the method instead. The `customizer` is bound to * `thisArg` and invoked with two argument; (value [, index|key, object]). * * **Note:** This method is loosely based on the * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). * The enumerable properties of `arguments` objects and objects created by * constructors other than `Object` are cloned to plain `Object` objects. An * empty object is returned for uncloneable values such as functions, DOM nodes, * Maps, Sets, and WeakMaps. * * @static * @memberOf _ * @category Lang * @param {*} value The value to clone. * @param {boolean} [isDeep] Specify a deep clone. * @param {Function} [customizer] The function to customize cloning values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {*} Returns the cloned value. * @example * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * var shallow = _.clone(users); * shallow[0] === users[0]; * // => true * * var deep = _.clone(users, true); * deep[0] === users[0]; * // => false * * // using a customizer callback * var el = _.clone(document.body, function(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * }); * * el === document.body * // => false * el.nodeName * // => BODY * el.childNodes.length; * // => 0 */ function clone(value, isDeep, customizer, thisArg) { if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) { isDeep = false; } else if (typeof isDeep == 'function') { thisArg = customizer; customizer = isDeep; isDeep = false; } customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 1); return baseClone(value, isDeep, customizer); } /** * Creates a deep clone of `value`. If `customizer` is provided it is invoked * to produce the cloned values. If `customizer` returns `undefined` cloning * is handled by the method instead. The `customizer` is bound to `thisArg` * and invoked with two argument; (value [, index|key, object]). * * **Note:** This method is loosely based on the * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). * The enumerable properties of `arguments` objects and objects created by * constructors other than `Object` are cloned to plain `Object` objects. An * empty object is returned for uncloneable values such as functions, DOM nodes, * Maps, Sets, and WeakMaps. * * @static * @memberOf _ * @category Lang * @param {*} value The value to deep clone. * @param {Function} [customizer] The function to customize cloning values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {*} Returns the deep cloned value. * @example * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * var deep = _.cloneDeep(users); * deep[0] === users[0]; * // => false * * // using a customizer callback * var el = _.cloneDeep(document.body, function(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * }); * * el === document.body * // => false * el.nodeName * // => BODY * el.childNodes.length; * // => 20 */ function cloneDeep(value, customizer, thisArg) { customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 1); return baseClone(value, true, customizer); } /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { var length = isObjectLike(value) ? value.length : undefined; return isLength(length) && objToString.call(value) == argsTag; } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag); } /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ function isDate(value) { return isObjectLike(value) && objToString.call(value) == dateTag; } /** * Checks if `value` is a DOM element. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement('<body>'); * // => false */ function isElement(value) { return !!value && value.nodeType === 1 && isObjectLike(value) && (objToString.call(value).indexOf('Element') > -1); } // Fallback for environments without DOM support. if (!support.dom) { isElement = function(value) { return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value); }; } /** * Checks if `value` is empty. A value is considered empty unless it is an * `arguments` object, array, string, or jQuery-like collection with a length * greater than `0` or an object with own enumerable properties. * * @static * @memberOf _ * @category Lang * @param {Array|Object|string} value The value to inspect. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } var length = getLength(value); if (isLength(length) && (isArray(value) || isString(value) || isArguments(value) || (isObjectLike(value) && isFunction(value.splice)))) { return !length; } return !keys(value).length; } /** * Performs a deep comparison between two values to determine if they are * equivalent. If `customizer` is provided it is invoked to compare values. * If `customizer` returns `undefined` comparisons are handled by the method * instead. The `customizer` is bound to `thisArg` and invoked with three * arguments: (value, other [, index|key]). * * **Note:** This method supports comparing arrays, booleans, `Date` objects, * numbers, `Object` objects, regexes, and strings. Objects are compared by * their own, not inherited, enumerable properties. Functions and DOM nodes * are **not** supported. Provide a customizer function to extend support * for comparing other values. * * @static * @memberOf _ * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize value comparisons. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * object == other; * // => false * * _.isEqual(object, other); * // => true * * // using a customizer callback * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqual(array, other, function(value, other) { * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) { * return true; * } * }); * // => true */ function isEqual(value, other, customizer, thisArg) { customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3); if (!customizer && isStrictComparable(value) && isStrictComparable(other)) { return value === other; } var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag; } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on [`Number.isFinite`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isfinite). * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(10); * // => true * * _.isFinite('10'); * // => false * * _.isFinite(true); * // => false * * _.isFinite(Object(10)); * // => false * * _.isFinite(Infinity); * // => false */ var isFinite = nativeNumIsFinite || function(value) { return typeof value == 'number' && nativeIsFinite(value); }; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ var isFunction = !(baseIsFunction(/x/) || (Uint8Array && !baseIsFunction(Uint8Array))) ? baseIsFunction : function(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 equivalents which return 'object' for typed array constructors. return objToString.call(value) == funcTag; }; /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return type == 'function' || (!!value && type == 'object'); } /** * Performs a deep comparison between `object` and `source` to determine if * `object` contains equivalent property values. If `customizer` is provided * it is invoked to compare values. If `customizer` returns `undefined` * comparisons are handled by the method instead. The `customizer` is bound * to `thisArg` and invoked with three arguments: (value, other, index|key). * * **Note:** This method supports comparing properties of arrays, booleans, * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions * and DOM nodes are **not** supported. Provide a customizer function to extend * support for comparing other values. * * @static * @memberOf _ * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize value comparisons. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'user': 'fred', 'age': 40 }; * * _.isMatch(object, { 'age': 40 }); * // => true * * _.isMatch(object, { 'age': 36 }); * // => false * * // using a customizer callback * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatch(object, source, function(value, other) { * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined; * }); * // => true */ function isMatch(object, source, customizer, thisArg) { var props = keys(source), length = props.length; if (!length) { return true; } if (object == null) { return false; } customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3); object = toObject(object); if (!customizer && length == 1) { var key = props[0], value = source[key]; if (isStrictComparable(value)) { return value === object[key] && (value !== undefined || (key in object)); } } var values = Array(length), strictCompareFlags = Array(length); while (length--) { value = values[length] = source[props[length]]; strictCompareFlags[length] = isStrictComparable(value); } return baseIsMatch(object, props, values, strictCompareFlags, customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4) * which returns `true` for `undefined` and other non-numeric values. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some host objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified * as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isNumber(8.4); * // => true * * _.isNumber(NaN); * // => true * * _.isNumber('8.4'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * **Note:** This method assumes objects created by the `Object` constructor * have no inherited enumerable properties. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { if (!(value && objToString.call(value) == objectTag)) { return false; } var valueOf = value.valueOf, objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); return objProto ? (value == objProto || getPrototypeOf(value) == objProto) : shimIsPlainObject(value); }; /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ function isRegExp(value) { return (isObjectLike(value) && objToString.call(value) == regexpTag) || false; } /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } /** * Checks if `value` is `undefined`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Converts `value` to an array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * (function() { * return _.toArray(arguments).slice(1); * }(1, 2, 3)); * // => [2, 3] */ function toArray(value) { var length = value ? getLength(value) : 0; if (!isLength(length)) { return values(value); } if (!length) { return []; } return arrayCopy(value); } /** * Converts `value` to a plain object flattening inherited enumerable * properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return baseCopy(value, keysIn(value)); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable properties of source object(s) to the destination * object. Subsequent sources overwrite property assignments of previous sources. * If `customizer` is provided it is invoked to produce the assigned values. * The `customizer` is bound to `thisArg` and invoked with five arguments: * (objectValue, sourceValue, key, object, source). * * **Note:** This method mutates `object` and is based on * [`Object.assign`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign). * * * @static * @memberOf _ * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' }); * // => { 'user': 'fred', 'age': 40 } * * // using a customizer callback * var defaults = _.partialRight(_.assign, function(value, other) { * return _.isUndefined(value) ? other : value; * }); * * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); * // => { 'user': 'barney', 'age': 36 } */ var assign = createAssigner(function(object, source, customizer) { return customizer ? assignWith(object, source, customizer) : baseAssign(object, source); }); /** * Creates an object that inherits from the given `prototype` object. If a * `properties` object is provided its own enumerable properties are assigned * to the created object. * * @static * @memberOf _ * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties, guard) { var result = baseCreate(prototype); if (guard && isIterateeCall(prototype, properties, guard)) { properties = null; } return properties ? baseAssign(result, properties) : result; } /** * Assigns own enumerable properties of source object(s) to the destination * object for all destination properties that resolve to `undefined`. Once a * property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); * // => { 'user': 'barney', 'age': 36 } */ var defaults = restParam(function(args) { var object = args[0]; if (object == null) { return object; } args.push(assignDefaults); return assign.apply(undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {string|undefined} Returns the key of the matched element, else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(chr) { * return chr.age < 40; * }); * // => 'barney' (iteration order is not guaranteed) * * // using the `_.matches` callback shorthand * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // using the `_.matchesProperty` callback shorthand * _.findKey(users, 'active', false); * // => 'fred' * * // using the `_.property` callback shorthand * _.findKey(users, 'active'); * // => 'barney' */ var findKey = createFindKey(baseForOwn); /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {string|undefined} Returns the key of the matched element, else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(chr) { * return chr.age < 40; * }); * // => returns `pebbles` assuming `_.findKey` returns `barney` * * // using the `_.matches` callback shorthand * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // using the `_.matchesProperty` callback shorthand * _.findLastKey(users, 'active', false); * // => 'fred' * * // using the `_.property` callback shorthand * _.findLastKey(users, 'active'); * // => 'pebbles' */ var findLastKey = createFindKey(baseForOwnRight); /** * Iterates over own and inherited enumerable properties of an object invoking * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed) */ var forIn = createForIn(baseFor); /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c' */ var forInRight = createForIn(baseForRight); /** * Iterates over own enumerable properties of an object invoking `iteratee` * for each property. The `iteratee` is bound to `thisArg` and invoked with * three arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => logs 'a' and 'b' (iteration order is not guaranteed) */ var forOwn = createForOwn(baseForOwn); /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b' */ var forOwnRight = createForOwn(baseForOwnRight); /** * Creates an array of function property names from all enumerable properties, * own and inherited, of `object`. * * @static * @memberOf _ * @alias methods * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the new array of property names. * @example * * _.functions(_); * // => ['after', 'ary', 'assign', ...] */ function functions(object) { return baseFunctions(object, keysIn(object)); } /** * Gets the property value of `path` on `object`. If the resolved value is * `undefined` the `defaultValue` is used in its place. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, toPath(path), path + ''); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` is a direct property, else `false`. * @example * * var object = { 'a': { 'b': { 'c': 3 } } }; * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b.c'); * // => true * * _.has(object, ['a', 'b', 'c']); * // => true */ function has(object, path) { if (object == null) { return false; } var result = hasOwnProperty.call(object, path); if (!result && !isKey(path)) { path = toPath(path); object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); path = last(path); result = object != null && hasOwnProperty.call(object, path); } return result; } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite property * assignments of previous values unless `multiValue` is `true`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to invert. * @param {boolean} [multiValue] Allow multiple values per key. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } * * // with `multiValue` * _.invert(object, true); * // => { '1': ['a', 'c'], '2': ['b'] } */ function invert(object, multiValue, guard) { if (guard && isIterateeCall(object, multiValue, guard)) { multiValue = null; } var index = -1, props = keys(object), length = props.length, result = {}; while (++index < length) { var key = props[index], value = object[key]; if (multiValue) { if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } } else { result[value] = key; } } return result; } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { if (object) { var Ctor = object.constructor, length = object.length; } if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object != 'function' && isLength(length))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || (support.nonEnumArgs && isArguments(object))) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * Creates an object with the same keys as `object` and values generated by * running each own enumerable property of `object` through `iteratee`. The * iteratee function is bound to `thisArg` and invoked with three arguments: * (value, key, object). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns the new mapped object. * @example * * _.mapValues({ 'a': 1, 'b': 2 }, function(n) { * return n * 3; * }); * // => { 'a': 3, 'b': 6 } * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * // using the `_.property` callback shorthand * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee, thisArg) { var result = {}; iteratee = getCallback(iteratee, thisArg, 3); baseForOwn(object, function(value, key, object) { result[key] = iteratee(value, key, object); }); return result; } /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined` into the destination object. Subsequent sources * overwrite property assignments of previous sources. If `customizer` is * provided it is invoked to produce the merged values of the destination and * source properties. If `customizer` returns `undefined` merging is handled * by the method instead. The `customizer` is bound to `thisArg` and invoked * with five arguments: (objectValue, sourceValue, key, object, source). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * var users = { * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] * }; * * var ages = { * 'data': [{ 'age': 36 }, { 'age': 40 }] * }; * * _.merge(users, ages); * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } * * // using a customizer callback * var object = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var other = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(object, other, function(a, b) { * if (_.isArray(a)) { * return a.concat(b); * } * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } */ var merge = createAssigner(baseMerge); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable properties of `object` that are not omitted. * Property names may be specified as individual arguments or as arrays of * property names. If `predicate` is provided it is invoked for each property * of `object` omitting the properties `predicate` returns truthy for. The * predicate is bound to `thisArg` and invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {Function|...(string|string[])} [predicate] The function invoked per * iteration or property names to omit, specified as individual property * names or arrays of property names. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Object} Returns the new object. * @example * * var object = { 'user': 'fred', 'age': 40 }; * * _.omit(object, 'age'); * // => { 'user': 'fred' } * * _.omit(object, _.isNumber); * // => { 'user': 'fred' } */ var omit = restParam(function(object, props) { if (object == null) { return {}; } if (typeof props[0] != 'function') { var props = arrayMap(baseFlatten(props), String); return pickByArray(object, baseDifference(keysIn(object), props)); } var predicate = bindCallback(props[0], props[1], 3); return pickByCallback(object, function(value, key, object) { return !predicate(value, key, object); }); }); /** * Creates a two dimensional array of the key-value pairs for `object`, * e.g. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the new array of key-value pairs. * @example * * _.pairs({ 'barney': 36, 'fred': 40 }); * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) */ function pairs(object) { var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } /** * Creates an object composed of the picked `object` properties. Property * names may be specified as individual arguments or as arrays of property * names. If `predicate` is provided it is invoked for each property of `object` * picking the properties `predicate` returns truthy for. The predicate is * bound to `thisArg` and invoked with three arguments: (value, key, object). * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {Function|...(string|string[])} [predicate] The function invoked per * iteration or property names to pick, specified as individual property * names or arrays of property names. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Object} Returns the new object. * @example * * var object = { 'user': 'fred', 'age': 40 }; * * _.pick(object, 'user'); * // => { 'user': 'fred' } * * _.pick(object, _.isString); * // => { 'user': 'fred' } */ var pick = restParam(function(object, props) { if (object == null) { return {}; } return typeof props[0] == 'function' ? pickByCallback(object, bindCallback(props[0], props[1], 3)) : pickByArray(object, baseFlatten(props)); }); /** * This method is like `_.get` except that if the resolved value is a function * it is invoked with the `this` binding of its parent object and its result * is returned. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a.b.c', 'default'); * // => 'default' * * _.result(object, 'a.b.c', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { var result = object == null ? undefined : object[path]; if (result === undefined) { if (object != null && !isKey(path, object)) { path = toPath(path); object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); result = object == null ? undefined : object[last(path)]; } result = result === undefined ? defaultValue : result; } return isFunction(result) ? result.call(object) : result; } /** * Sets the property value of `path` on `object`. If a portion of `path` * does not exist it is created. * * @static * @memberOf _ * @category Object * @param {Object} object The object to augment. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, 'x[0].y.z', 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { if (object == null) { return object; } var pathKey = (path + ''); path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path); var index = -1, length = path.length, endIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = path[index]; if (isObject(nested)) { if (index == endIndex) { nested[key] = value; } else if (nested[key] == null) { nested[key] = isIndex(path[index + 1]) ? [] : {}; } } nested = nested[key]; } return object; } /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own enumerable * properties through `iteratee`, with each invocation potentially mutating * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked * with four arguments: (accumulator, value, key, object). Iteratee functions * may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @category Object * @param {Array|Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) { * result[key] = n * 3; * }); * // => { 'a': 3, 'b': 6 } */ function transform(object, iteratee, accumulator, thisArg) { var isArr = isArray(object) || isTypedArray(object); iteratee = getCallback(iteratee, thisArg, 4); if (accumulator == null) { if (isArr || isObject(object)) { var Ctor = object.constructor; if (isArr) { accumulator = isArray(object) ? new Ctor : []; } else { accumulator = baseCreate(isFunction(Ctor) && Ctor.prototype); } } else { accumulator = {}; } } (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Creates an array of the own enumerable property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable property values * of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Checks if `n` is between `start` and up to but not including, `end`. If * `end` is not specified it is set to `start` with `start` then set to `0`. * * @static * @memberOf _ * @category Number * @param {number} n The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `n` is in the range, else `false`. * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false */ function inRange(value, start, end) { start = +start || 0; if (typeof end === 'undefined') { end = start; start = 0; } else { end = +end || 0; } return value >= nativeMin(start, end) && value < nativeMax(start, end); } /** * Produces a random number between `min` and `max` (inclusive). If only one * argument is provided a number between `0` and the given number is returned. * If `floating` is `true`, or either `min` or `max` are floats, a floating-point * number is returned instead of an integer. * * @static * @memberOf _ * @category Number * @param {number} [min=0] The minimum possible value. * @param {number} [max=1] The maximum possible value. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(min, max, floating) { if (floating && isIterateeCall(min, max, floating)) { max = floating = null; } var noMin = min == null, noMax = max == null; if (floating == null) { if (noMax && typeof min == 'boolean') { floating = min; min = 1; } else if (typeof max == 'boolean') { floating = max; noMax = true; } } if (noMin && noMax) { max = 1; noMax = false; } min = +min || 0; if (noMax) { max = min; min = 0; } else { max = +max || 0; } if (floating || min % 1 || max % 1) { var rand = nativeRandom(); return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max); } return baseRandom(min, max); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar'); * // => 'fooBar' * * _.camelCase('__foo_bar__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word); }); /** * Capitalizes the first character of `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('fred'); * // => 'Fred' */ function capitalize(string) { string = baseToString(string); return string && (string.charAt(0).toUpperCase() + string.slice(1)); } /** * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = baseToString(string); return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to search. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search from. * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = baseToString(string); target = (target + ''); var length = string.length; position = position === undefined ? length : nativeMin(position < 0 ? 0 : (+position || 0), length); position -= target.length; return position >= 0 && string.indexOf(target, position) == position; } /** * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to * their corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional characters * use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't require escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * Backticks are escaped because in Internet Explorer < 9, they can break out * of attribute values or HTML comments. See [#59](https://html5sec.org/#59), * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/) * for more details. * * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping) * to reduce XSS vectors. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, & pebbles' */ function escape(string) { // Reset `lastIndex` because in IE < 9 `String#replace` does not. string = baseToString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' */ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } /** * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__foo_bar__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Pads `string` on the left and right sides if it is shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = baseToString(string); length = +length; var strLength = string.length; if (strLength >= length || !nativeIsFinite(length)) { return string; } var mid = (length - strLength) / 2, leftLength = floor(mid), rightLength = ceil(mid); chars = createPadding('', rightLength, chars); return chars.slice(0, leftLength) + string + chars; } /** * Pads `string` on the left side if it is shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padLeft('abc', 6); * // => ' abc' * * _.padLeft('abc', 6, '_-'); * // => '_-_abc' * * _.padLeft('abc', 3); * // => 'abc' */ var padLeft = createPadDir(); /** * Pads `string` on the right side if it is shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padRight('abc', 6); * // => 'abc ' * * _.padRight('abc', 6, '_-'); * // => 'abc_-_' * * _.padRight('abc', 3); * // => 'abc' */ var padRight = createPadDir(true); /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal, * in which case a `radix` of `16` is used. * * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E) * of `parseInt`. * * @static * @memberOf _ * @category String * @param {string} string The string to convert. * @param {number} [radix] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard && isIterateeCall(string, radix, guard)) { radix = 0; } return nativeParseInt(string, radix); } // Fallback for environments with pre-ES5 implementations. if (nativeParseInt(whitespace + '08') != 8) { parseInt = function(string, radix, guard) { // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`. // Chrome fails to trim leading <BOM> whitespace characters. // See https://code.google.com/p/v8/issues/detail?id=3109 for more details. if (guard ? isIterateeCall(string, radix, guard) : radix == null) { radix = 0; } else if (radix) { radix = +radix; } string = trim(string); return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10)); }; } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=0] The number of times to repeat the string. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n) { var result = ''; string = baseToString(string); n = +n; if (n < 1 || !string || !nativeIsFinite(n)) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = floor(n / 2); string += string; } while (n); return result; } /** * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--foo-bar'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__foo_bar__'); * // => 'Foo Bar' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1)); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to search. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = baseToString(string); position = position == null ? 0 : nativeMin(position < 0 ? 0 : (+position || 0), string.length); return string.lastIndexOf(target, position) == position; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is provided it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options] The options object. * @param {RegExp} [options.escape] The HTML "escape" delimiter. * @param {RegExp} [options.evaluate] The "evaluate" delimiter. * @param {Object} [options.imports] An object to import into the template as free variables. * @param {RegExp} [options.interpolate] The "interpolate" delimiter. * @param {string} [options.sourceURL] The sourceURL of the template's compiled source. * @param {string} [options.variable] The data object variable name. * @param- {Object} [otherOptions] Enables the legacy `options` param signature. * @returns {Function} Returns the compiled template function. * @example * * // using the "interpolate" delimiter to create a compiled template * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // using the HTML "escape" delimiter to escape data property values * var compiled = _.template('<b><%- value %></b>'); * compiled({ 'value': '<script>' }); * // => '<b><script></b>' * * // using the "evaluate" delimiter to execute JavaScript and generate HTML * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // using the internal `print` function in "evaluate" delimiters * var compiled = _.template('<% print("hello " + user); %>!'); * compiled({ 'user': 'barney' }); * // => 'hello barney!' * * // using the ES delimiter as an alternative to the default "interpolate" delimiter * var compiled = _.template('hello ${ user }!'); * compiled({ 'user': 'pebbles' }); * // => 'hello pebbles!' * * // using custom template delimiters * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; * var compiled = _.template('hello {{ user }}!'); * compiled({ 'user': 'mustache' }); * // => 'hello mustache!' * * // using backslashes to treat delimiters as plain text * var compiled = _.template('<%= "\\<%- value %\\>" %>'); * compiled({ 'value': 'ignored' }); * // => '<%- value %>' * * // using the `imports` option to import `jQuery` as `jq` * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // using the `sourceURL` option to specify a custom sourceURL for the template * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector * * // using the `variable` option to ensure a with-statement isn't used in the compiled template * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); * compiled.source; * // => function(data) { * // var __t, __p = ''; * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; * // return __p; * // } * * // using the `source` property to inline compiled templates for meaningful * // line numbers in error messages and a stack trace * fs.writeFileSync(path.join(cwd, 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(string, options, otherOptions) { // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (otherOptions && isIterateeCall(string, options, otherOptions)) { options = otherOptions = null; } string = baseToString(string); options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults); var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. var sourceURL = '//# sourceURL=' + ('sourceURL' in options ? options.sourceURL : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products requires returning the `match` // string in order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; } /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { var value = string; string = baseToString(string); if (!string) { return string; } if (guard ? isIterateeCall(value, chars, guard) : chars == null) { return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1); } chars = (chars + ''); return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1); } /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimLeft(' abc '); * // => 'abc ' * * _.trimLeft('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimLeft(string, chars, guard) { var value = string; string = baseToString(string); if (!string) { return string; } if (guard ? isIterateeCall(value, chars, guard) : chars == null) { return string.slice(trimmedLeftIndex(string)); } return string.slice(charsLeftIndex(string, (chars + ''))); } /** * Removes trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimRight(' abc '); * // => ' abc' * * _.trimRight('-_-abc-_-', '_-'); * // => '-_-abc' */ function trimRight(string, chars, guard) { var value = string; string = baseToString(string); if (!string) { return string; } if (guard ? isIterateeCall(value, chars, guard) : chars == null) { return string.slice(0, trimmedRightIndex(string) + 1); } return string.slice(0, charsRightIndex(string, (chars + '')) + 1); } /** * Truncates `string` if it is longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to truncate. * @param {Object|number} [options] The options object or maximum string length. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {string} Returns the truncated string. * @example * * _.trunc('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.trunc('hi-diddly-ho there, neighborino', 24); * // => 'hi-diddly-ho there, n...' * * _.trunc('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.trunc('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.trunc('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function trunc(string, options, guard) { if (guard && isIterateeCall(string, options, guard)) { options = null; } var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (options != null) { if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? (+options.length || 0) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } else { length = +options || 0; } } string = baseToString(string); if (length >= string.length) { return string; } var end = length - omission.length; if (end < 1) { return omission; } var result = string.slice(0, end); if (separator == null) { return result + omission; } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, newEnd, substring = string.slice(0, end); if (!separator.global) { separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g'); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { newEnd = match.index; } result = result.slice(0, newEnd == null ? end : newEnd); } } else if (string.indexOf(separator, end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } /** * The inverse of `_.escape`; this method converts the HTML entities * `&`, `<`, `>`, `"`, `'`, and ``` in `string` to their * corresponding characters. * * **Note:** No other HTML entities are unescaped. To unescape additional HTML * entities use a third-party library like [_he_](https://mths.be/he). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('fred, barney, & pebbles'); * // => 'fred, barney, & pebbles' */ function unescape(string) { string = baseToString(string); return (string && reHasEscapedHtml.test(string)) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { if (guard && isIterateeCall(string, pattern, guard)) { pattern = null; } string = baseToString(string); return string.match(pattern || reWords) || []; } /*------------------------------------------------------------------------*/ /** * Attempts to invoke `func`, returning either the result or the caught error * object. Any additional arguments are provided to `func` when it is invoked. * * @static * @memberOf _ * @category Utility * @param {Function} func The function to attempt. * @returns {*} Returns the `func` result or error object. * @example * * // avoid throwing errors for invalid selectors * var elements = _.attempt(function(selector) { * return document.querySelectorAll(selector); * }, '>_>'); * * if (_.isError(elements)) { * elements = []; * } */ var attempt = restParam(function(func, args) { try { return func.apply(undefined, args); } catch(e) { return isError(e) ? e : new Error(e); } }); /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and arguments of the created function. If `func` is a property name the * created callback returns the property value for a given element. If `func` * is an object the created callback returns `true` for elements that contain * the equivalent object properties, otherwise it returns `false`. * * @static * @memberOf _ * @alias iteratee * @category Utility * @param {*} [func=_.identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of `func`. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // wrap to create custom callback shorthands * _.callback = _.wrap(_.callback, function(callback, func, thisArg) { * var match = /^(.+?)__([gl]t)(.+)$/.exec(func); * if (!match) { * return callback(func, thisArg); * } * return function(object) { * return match[2] == 'gt' * ? object[match[1]] > match[3] * : object[match[1]] < match[3]; * }; * }); * * _.filter(users, 'age__gt36'); * // => [{ 'user': 'fred', 'age': 40 }] */ function callback(func, thisArg, guard) { if (guard && isIterateeCall(func, thisArg, guard)) { thisArg = null; } return baseCallback(func, thisArg); } /** * Creates a function that returns `value`. * * @static * @memberOf _ * @category Utility * @param {*} value The value to return from the new function. * @returns {Function} Returns the new function. * @example * * var object = { 'user': 'fred' }; * var getter = _.constant(object); * * getter() === object; * // => true */ function constant(value) { return function() { return value; }; } /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } /** * Creates a function which performs a deep comparison between a given object * and `source`, returning `true` if the given object has equivalent property * values, else `false`. * * **Note:** This method supports comparing arrays, booleans, `Date` objects, * numbers, `Object` objects, regexes, and strings. Objects are compared by * their own, not inherited, enumerable properties. For comparing a single * own or inherited property value see `_.matchesProperty`. * * @static * @memberOf _ * @category Utility * @param {Object} source The object of property values to match. * @returns {Function} Returns the new function. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, _.matches({ 'age': 40, 'active': false })); * // => [{ 'user': 'fred', 'age': 40, 'active': false }] */ function matches(source) { return baseMatches(baseClone(source, true)); } /** * Creates a function which compares the property value of `path` on a given * object to `value`. * * **Note:** This method supports comparing arrays, booleans, `Date` objects, * numbers, `Object` objects, regexes, and strings. Objects are compared by * their own, not inherited, enumerable properties. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the property to get. * @param {*} value The value to compare. * @returns {Function} Returns the new function. * @example * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * _.find(users, _.matchesProperty('user', 'fred')); * // => { 'user': 'fred' } */ function matchesProperty(path, value) { return baseMatchesProperty(path, baseClone(value, true)); } /** * Creates a function which invokes the method at `path` on a given object. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the method to invoke. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': _.constant(2) } } }, * { 'a': { 'b': { 'c': _.constant(1) } } } * ]; * * _.map(objects, _.method('a.b.c')); * // => [2, 1] * * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ var method = restParam(function(path, args) { return function(object) { return invokePath(object, path, args); } }); /** * The opposite of `_.method`; this method creates a function which invokes * the method at a given path on `object`. * * @static * @memberOf _ * @category Utility * @param {Object} object The object to query. * @returns {Function} Returns the new function. * @example * * var array = _.times(3, _.constant), * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.methodOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); * // => [2, 0] */ var methodOf = restParam(function(object, args) { return function(path) { return invokePath(object, path, args); }; }); /** * Adds all own enumerable function properties of a source object to the * destination object. If `object` is a function then methods are added to * its prototype as well. * * **Note:** Use `_.runInContext` to create a pristine `lodash` function to * avoid conflicts caused by modifying the original. * * @static * @memberOf _ * @category Utility * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options] The options object. * @param {boolean} [options.chain=true] Specify whether the functions added * are chainable. * @returns {Function|Object} Returns `object`. * @example * * function vowels(string) { * return _.filter(string, function(v) { * return /[aeiou]/i.test(v); * }); * } * * // use `_.runInContext` to avoid conflicts (esp. in Node.js) * var _ = require('lodash').runInContext(); * * _.mixin({ 'vowels': vowels }); * _.vowels('fred'); * // => ['e'] * * _('fred').vowels().value(); * // => ['e'] * * _.mixin({ 'vowels': vowels }, { 'chain': false }); * _('fred').vowels(); * // => ['e'] */ function mixin(object, source, options) { if (options == null) { var isObj = isObject(source), props = isObj && keys(source), methodNames = props && props.length && baseFunctions(source, props); if (!(methodNames ? methodNames.length : isObj)) { methodNames = false; options = source; source = object; object = this; } } if (!methodNames) { methodNames = baseFunctions(source, keys(source)); } var chain = true, index = -1, isFunc = isFunction(object), length = methodNames.length; if (options === false) { chain = false; } else if (isObject(options) && 'chain' in options) { chain = options.chain; } while (++index < length) { var methodName = methodNames[index], func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = (function(func) { return function() { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = arrayCopy(this.__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } var args = [this.value()]; push.apply(args, arguments); return func.apply(object, args); }; }(func)); } } return object; } /** * Reverts the `_` variable to its previous value and returns a reference to * the `lodash` function. * * @static * @memberOf _ * @category Utility * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { context._ = oldDash; return this; } /** * A no-operation function which returns `undefined` regardless of the * arguments it receives. * * @static * @memberOf _ * @category Utility * @example * * var object = { 'user': 'fred' }; * * _.noop(object) === undefined; * // => true */ function noop() { // No operation performed. } /** * Creates a function which returns the property value at `path` on a * given object. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': 2 } } }, * { 'a': { 'b': { 'c': 1 } } } * ]; * * _.map(objects, _.property('a.b.c')); * // => [2, 1] * * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function which returns * the property value at a given path on `object`. * * @static * @memberOf _ * @category Utility * @param {Object} object The object to query. * @returns {Function} Returns the new function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function(path) { return baseGet(object, toPath(path), path + ''); }; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. If `end` is not specified it is * set to `start` with `start` then set to `0`. If `end` is less than `start` * a zero-length range is created unless a negative `step` is specified. * * @static * @memberOf _ * @category Utility * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the new array of numbers. * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ function range(start, end, step) { if (step && isIterateeCall(start, end, step)) { end = step = null; } start = +start || 0; step = step == null ? 1 : (+step || 0); if (end == null) { end = start; start = 0; } else { end = +end || 0; } // Use `Array(length)` so engines like Chakra and V8 avoid slower modes. // See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details. var index = -1, length = nativeMax(ceil((end - start) / (step || 1)), 0), result = Array(length); while (++index < length) { result[index] = start; start += step; } return result; } /** * Invokes the iteratee function `n` times, returning an array of the results * of each invocation. The `iteratee` is bound to `thisArg` and invoked with * one argument; (index). * * @static * @memberOf _ * @category Utility * @param {number} n The number of times to invoke `iteratee`. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array} Returns the array of results. * @example * * var diceRolls = _.times(3, _.partial(_.random, 1, 6, false)); * // => [3, 6, 4] * * _.times(3, function(n) { * mage.castSpell(n); * }); * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2` * * _.times(3, function(n) { * this.cast(n); * }, mage); * // => also invokes `mage.castSpell(n)` three times */ function times(n, iteratee, thisArg) { n = floor(n); // Exit early to avoid a JSC JIT bug in Safari 8 // where `Array(0)` is treated as `Array(1)`. if (n < 1 || !nativeIsFinite(n)) { return []; } var index = -1, result = Array(nativeMin(n, MAX_ARRAY_LENGTH)); iteratee = bindCallback(iteratee, thisArg, 1); while (++index < n) { if (index < MAX_ARRAY_LENGTH) { result[index] = iteratee(index); } else { iteratee(index); } } return result; } /** * Generates a unique ID. If `prefix` is provided the ID is appended to it. * * @static * @memberOf _ * @category Utility * @param {string} [prefix] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return baseToString(prefix) + id; } /*------------------------------------------------------------------------*/ /** * Adds two numbers. * * @static * @memberOf _ * @category Math * @param {number} augend The first number to add. * @param {number} addend The second number to add. * @returns {number} Returns the sum. * @example * * _.add(6, 4); * // => 10 */ function add(augend, addend) { return (+augend || 0) + (+addend || 0); } /** * Gets the maximum value of `collection`. If `collection` is empty or falsey * `-Infinity` is returned. If an iteratee function is provided it is invoked * for each value in `collection` to generate the criterion by which the value * is ranked. The `iteratee` is bound to `thisArg` and invoked with three * arguments: (value, index, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Math * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * _.max([]); * // => -Infinity * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * _.max(users, function(chr) { * return chr.age; * }); * // => { 'user': 'fred', 'age': 40 } * * // using the `_.property` callback shorthand * _.max(users, 'age'); * // => { 'user': 'fred', 'age': 40 } */ var max = createExtremum(arrayMax); /** * Gets the minimum value of `collection`. If `collection` is empty or falsey * `Infinity` is returned. If an iteratee function is provided it is invoked * for each value in `collection` to generate the criterion by which the value * is ranked. The `iteratee` is bound to `thisArg` and invoked with three * arguments: (value, index, collection). * * If a property name is provided for `iteratee` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `iteratee` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @category Math * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * _.min([]); * // => Infinity * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * _.min(users, function(chr) { * return chr.age; * }); * // => { 'user': 'barney', 'age': 36 } * * // using the `_.property` callback shorthand * _.min(users, 'age'); * // => { 'user': 'barney', 'age': 36 } */ var min = createExtremum(arrayMin, true); /** * Gets the sum of the values in `collection`. * * @static * @memberOf _ * @category Math * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [iteratee] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {number} Returns the sum. * @example * * _.sum([4, 6]); * // => 10 * * _.sum({ 'a': 4, 'b': 6 }); * // => 10 * * var objects = [ * { 'n': 4 }, * { 'n': 6 } * ]; * * _.sum(objects, function(object) { * return object.n; * }); * // => 10 * * // using the `_.property` callback shorthand * _.sum(objects, 'n'); * // => 10 */ function sum(collection, iteratee, thisArg) { if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { iteratee = null; } var func = getCallback(), noIteratee = iteratee == null; if (!(func === baseCallback && noIteratee)) { noIteratee = false; iteratee = func(iteratee, thisArg, 3); } return noIteratee ? arraySum(isArray(collection) ? collection : toIterable(collection)) : baseSum(collection, iteratee); } /*------------------------------------------------------------------------*/ // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; // Add functions to the `Map` cache. MapCache.prototype['delete'] = mapDelete; MapCache.prototype.get = mapGet; MapCache.prototype.has = mapHas; MapCache.prototype.set = mapSet; // Add functions to the `Set` cache. SetCache.prototype.push = cachePush; // Assign cache to `_.memoize`. memoize.Cache = MapCache; // Add functions that return wrapped values when chaining. lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.callback = callback; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flow = flow; lodash.flowRight = flowRight; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.functions = functions; lodash.groupBy = groupBy; lodash.indexBy = indexBy; lodash.initial = initial; lodash.intersection = intersection; lodash.invert = invert; lodash.invoke = invoke; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.omit = omit; lodash.once = once; lodash.pairs = pairs; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pluck = pluck; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAt = pullAt; lodash.range = range; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.restParam = restParam; lodash.set = set; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortByAll = sortByAll; lodash.sortByOrder = sortByOrder; lodash.spread = spread; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.times = times; lodash.toArray = toArray; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.union = union; lodash.uniq = uniq; lodash.unzip = unzip; lodash.values = values; lodash.valuesIn = valuesIn; lodash.where = where; lodash.without = without; lodash.wrap = wrap; lodash.xor = xor; lodash.zip = zip; lodash.zipObject = zipObject; // Add aliases. lodash.backflow = flowRight; lodash.collect = map; lodash.compose = flowRight; lodash.each = forEach; lodash.eachRight = forEachRight; lodash.extend = assign; lodash.iteratee = callback; lodash.methods = functions; lodash.object = zipObject; lodash.select = filter; lodash.tail = rest; lodash.unique = uniq; // Add functions to `lodash.prototype`. mixin(lodash, lodash); /*------------------------------------------------------------------------*/ // Add functions that return unwrapped values when chaining. lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.deburr = deburr; lodash.endsWith = endsWith; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.findWhere = findWhere; lodash.first = first; lodash.get = get; lodash.has = has; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isBoolean = isBoolean; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isMatch = isMatch; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isString = isString; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.max = max; lodash.min = min; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padLeft = padLeft; lodash.padRight = padRight; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.result = result; lodash.runInContext = runInContext; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedLastIndex = sortedLastIndex; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.sum = sum; lodash.template = template; lodash.trim = trim; lodash.trimLeft = trimLeft; lodash.trimRight = trimRight; lodash.trunc = trunc; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.words = words; // Add aliases. lodash.all = every; lodash.any = some; lodash.contains = includes; lodash.detect = find; lodash.foldl = reduce; lodash.foldr = reduceRight; lodash.head = first; lodash.include = includes; lodash.inject = reduce; mixin(lodash, (function() { var source = {}; baseForOwn(lodash, function(func, methodName) { if (!lodash.prototype[methodName]) { source[methodName] = func; } }); return source; }()), false); /*------------------------------------------------------------------------*/ // Add functions capable of returning wrapped and unwrapped values when chaining. lodash.sample = sample; lodash.prototype.sample = function(n) { if (!this.__chain__ && n == null) { return sample(this.value()); } return this.thru(function(value) { return sample(value, n); }); }; /*------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type string */ lodash.VERSION = VERSION; // Assign default placeholders. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { lodash[methodName].placeholder = lodash; }); // Add `LazyWrapper` methods that accept an `iteratee` value. arrayEach(['dropWhile', 'filter', 'map', 'takeWhile'], function(methodName, type) { var isFilter = type != LAZY_MAP_FLAG, isDropWhile = type == LAZY_DROP_WHILE_FLAG; LazyWrapper.prototype[methodName] = function(iteratee, thisArg) { var filtered = this.__filtered__, result = (filtered && isDropWhile) ? new LazyWrapper(this) : this.clone(), iteratees = result.__iteratees__ || (result.__iteratees__ = []); iteratees.push({ 'done': false, 'count': 0, 'index': 0, 'iteratee': getCallback(iteratee, thisArg, 1), 'limit': -1, 'type': type }); result.__filtered__ = filtered || isFilter; return result; }; }); // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. arrayEach(['drop', 'take'], function(methodName, index) { var whileName = methodName + 'While'; LazyWrapper.prototype[methodName] = function(n) { var filtered = this.__filtered__, result = (filtered && !index) ? this.dropWhile() : this.clone(); n = n == null ? 1 : nativeMax(floor(n) || 0, 0); if (filtered) { if (index) { result.__takeCount__ = nativeMin(result.__takeCount__, n); } else { last(result.__iteratees__).limit = n; } } else { var views = result.__views__ || (result.__views__ = []); views.push({ 'size': n, 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') }); } return result; }; LazyWrapper.prototype[methodName + 'Right'] = function(n) { return this.reverse()[methodName](n).reverse(); }; LazyWrapper.prototype[methodName + 'RightWhile'] = function(predicate, thisArg) { return this.reverse()[whileName](predicate, thisArg).reverse(); }; }); // Add `LazyWrapper` methods for `_.first` and `_.last`. arrayEach(['first', 'last'], function(methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); LazyWrapper.prototype[methodName] = function() { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.rest`. arrayEach(['initial', 'rest'], function(methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); LazyWrapper.prototype[methodName] = function() { return this[dropName](1); }; }); // Add `LazyWrapper` methods for `_.pluck` and `_.where`. arrayEach(['pluck', 'where'], function(methodName, index) { var operationName = index ? 'filter' : 'map', createCallback = index ? baseMatches : property; LazyWrapper.prototype[methodName] = function(value) { return this[operationName](createCallback(value)); }; }); LazyWrapper.prototype.compact = function() { return this.filter(identity); }; LazyWrapper.prototype.reject = function(predicate, thisArg) { predicate = getCallback(predicate, thisArg, 1); return this.filter(function(value) { return !predicate(value); }); }; LazyWrapper.prototype.slice = function(start, end) { start = start == null ? 0 : (+start || 0); var result = start < 0 ? this.takeRight(-start) : this.drop(start); if (end !== undefined) { end = (+end || 0); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } return result; }; LazyWrapper.prototype.toArray = function() { return this.drop(0); }; // Add `LazyWrapper` methods to `lodash.prototype`. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (!lodashFunc) { return; } var checkIteratee = /^(?:filter|map|reject)|While$/.test(methodName), retUnwrapped = /^(?:first|last)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments, length = args.length, chainAll = this.__chain__, value = this.__wrapped__, isHybrid = !!this.__actions__.length, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { // avoid lazy use if the iteratee has a "length" value other than `1` isLazy = useLazy = false; } var onlyLazy = isLazy && !isHybrid; if (retUnwrapped && !chainAll) { return onlyLazy ? func.call(value) : lodashFunc.call(lodash, this.value()); } var interceptor = function(value) { var otherArgs = [value]; push.apply(otherArgs, args); return lodashFunc.apply(lodash, otherArgs); }; if (useLazy) { var wrapper = onlyLazy ? value : new LazyWrapper(this), result = func.apply(wrapper, args); if (!retUnwrapped && (isHybrid || result.__actions__)) { var actions = result.__actions__ || (result.__actions__ = []); actions.push({ 'func': thru, 'args': [interceptor], 'thisArg': lodash }); } return new LodashWrapper(result, chainAll); } return this.thru(interceptor); }; }); // Add `Array` and `String` methods to `lodash.prototype`. arrayEach(['concat', 'join', 'pop', 'push', 'replace', 'shift', 'sort', 'splice', 'split', 'unshift'], function(methodName) { var func = (/^(?:replace|split)$/.test(methodName) ? stringProto : arrayProto)[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:join|pop|replace|shift)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments; if (retUnwrapped && !this.__chain__) { return func.apply(this.value(), args); } return this[chainName](function(value) { return func.apply(value, args); }); }; }); // Map minified function names to their real names. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = lodashFunc.name, names = realNames[key] || (realNames[key] = []); names.push({ 'name': methodName, 'func': lodashFunc }); } }); realNames[createHybridWrapper(null, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': null }]; // Add functions to the lazy wrapper. LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; // Add chaining functions to the `lodash` wrapper. lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toString = wrapperToString; lodash.prototype.run = lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; // Add function aliases to the `lodash` wrapper. lodash.prototype.collect = lodash.prototype.map; lodash.prototype.head = lodash.prototype.first; lodash.prototype.select = lodash.prototype.filter; lodash.prototype.tail = lodash.prototype.rest; return lodash; } /*--------------------------------------------------------------------------*/ // Export lodash. var _ = runInContext(); // Some AMD build optimizers like r.js check for condition patterns like the following: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // Expose lodash to the global object when an AMD loader is present to avoid // errors in cases where lodash is loaded by a script tag and not intended // as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for // more details. root._ = _; // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. define(function() { return _; }); } // Check for `exports` after `define` in case a build optimizer adds an `exports` object. else if (freeExports && freeModule) { // Export for Node.js or RingoJS. if (moduleExports) { (freeModule.exports = _)._ = _; } // Export for Narwhal or Rhino -require. else { freeExports._ = _; } } else { // Export for a browser or Rhino. root._ = _; } }.call(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/nouislider/distribute/nouislider.js":[function(require,module,exports){ /*! nouislider - 8.5.1 - 2016-04-24 16:00:29 */ (function (factory) { if ( typeof define === 'function' && define.amd ) { // AMD. Register as an anonymous module. define([], factory); } else if ( typeof exports === 'object' ) { // Node/CommonJS module.exports = factory(); } else { // Browser globals window.noUiSlider = factory(); } }(function( ){ 'use strict'; // Removes duplicates from an array. function unique(array) { return array.filter(function(a){ return !this[a] ? this[a] = true : false; }, {}); } // Round a value to the closest 'to'. function closest ( value, to ) { return Math.round(value / to) * to; } // Current position of an element relative to the document. function offset ( elem ) { var rect = elem.getBoundingClientRect(), doc = elem.ownerDocument, docElem = doc.documentElement, pageOffset = getPageOffset(); // getBoundingClientRect contains left scroll in Chrome on Android. // I haven't found a feature detection that proves this. Worst case // scenario on mis-match: the 'tap' feature on horizontal sliders breaks. if ( /webkit.*Chrome.*Mobile/i.test(navigator.userAgent) ) { pageOffset.x = 0; } return { top: rect.top + pageOffset.y - docElem.clientTop, left: rect.left + pageOffset.x - docElem.clientLeft }; } // Checks whether a value is numerical. function isNumeric ( a ) { return typeof a === 'number' && !isNaN( a ) && isFinite( a ); } // Sets a class and removes it after [duration] ms. function addClassFor ( element, className, duration ) { addClass(element, className); setTimeout(function(){ removeClass(element, className); }, duration); } // Limits a value to 0 - 100 function limit ( a ) { return Math.max(Math.min(a, 100), 0); } // Wraps a variable as an array, if it isn't one yet. function asArray ( a ) { return Array.isArray(a) ? a : [a]; } // Counts decimals function countDecimals ( numStr ) { var pieces = numStr.split("."); return pieces.length > 1 ? pieces[1].length : 0; } // http://youmightnotneedjquery.com/#add_class function addClass ( el, className ) { if ( el.classList ) { el.classList.add(className); } else { el.className += ' ' + className; } } // http://youmightnotneedjquery.com/#remove_class function removeClass ( el, className ) { if ( el.classList ) { el.classList.remove(className); } else { el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); } } // https://plainjs.com/javascript/attributes/adding-removing-and-testing-for-classes-9/ function hasClass ( el, className ) { return el.classList ? el.classList.contains(className) : new RegExp('\\b' + className + '\\b').test(el.className); } // https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY#Notes function getPageOffset ( ) { var supportPageOffset = window.pageXOffset !== undefined, isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"), x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft, y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop; return { x: x, y: y }; } // we provide a function to compute constants instead // of accessing window.* as soon as the module needs it // so that we do not compute anything if not needed function getActions ( ) { // Determine the events to bind. IE11 implements pointerEvents without // a prefix, which breaks compatibility with the IE10 implementation. return window.navigator.pointerEnabled ? { start: 'pointerdown', move: 'pointermove', end: 'pointerup' } : window.navigator.msPointerEnabled ? { start: 'MSPointerDown', move: 'MSPointerMove', end: 'MSPointerUp' } : { start: 'mousedown touchstart', move: 'mousemove touchmove', end: 'mouseup touchend' }; } // Value calculation // Determine the size of a sub-range in relation to a full range. function subRangeRatio ( pa, pb ) { return (100 / (pb - pa)); } // (percentage) How many percent is this value of this range? function fromPercentage ( range, value ) { return (value * 100) / ( range[1] - range[0] ); } // (percentage) Where is this value on this range? function toPercentage ( range, value ) { return fromPercentage( range, range[0] < 0 ? value + Math.abs(range[0]) : value - range[0] ); } // (value) How much is this percentage on this range? function isPercentage ( range, value ) { return ((value * ( range[1] - range[0] )) / 100) + range[0]; } // Range conversion function getJ ( value, arr ) { var j = 1; while ( value >= arr[j] ){ j += 1; } return j; } // (percentage) Input a value, find where, on a scale of 0-100, it applies. function toStepping ( xVal, xPct, value ) { if ( value >= xVal.slice(-1)[0] ){ return 100; } var j = getJ( value, xVal ), va, vb, pa, pb; va = xVal[j-1]; vb = xVal[j]; pa = xPct[j-1]; pb = xPct[j]; return pa + (toPercentage([va, vb], value) / subRangeRatio (pa, pb)); } // (value) Input a percentage, find where it is on the specified range. function fromStepping ( xVal, xPct, value ) { // There is no range group that fits 100 if ( value >= 100 ){ return xVal.slice(-1)[0]; } var j = getJ( value, xPct ), va, vb, pa, pb; va = xVal[j-1]; vb = xVal[j]; pa = xPct[j-1]; pb = xPct[j]; return isPercentage([va, vb], (value - pa) * subRangeRatio (pa, pb)); } // (percentage) Get the step that applies at a certain value. function getStep ( xPct, xSteps, snap, value ) { if ( value === 100 ) { return value; } var j = getJ( value, xPct ), a, b; // If 'snap' is set, steps are used as fixed points on the slider. if ( snap ) { a = xPct[j-1]; b = xPct[j]; // Find the closest position, a or b. if ((value - a) > ((b-a)/2)){ return b; } return a; } if ( !xSteps[j-1] ){ return value; } return xPct[j-1] + closest( value - xPct[j-1], xSteps[j-1] ); } // Entry parsing function handleEntryPoint ( index, value, that ) { var percentage; // Wrap numerical input in an array. if ( typeof value === "number" ) { value = [value]; } // Reject any invalid input, by testing whether value is an array. if ( Object.prototype.toString.call( value ) !== '[object Array]' ){ throw new Error("noUiSlider: 'range' contains invalid value."); } // Covert min/max syntax to 0 and 100. if ( index === 'min' ) { percentage = 0; } else if ( index === 'max' ) { percentage = 100; } else { percentage = parseFloat( index ); } // Check for correct input. if ( !isNumeric( percentage ) || !isNumeric( value[0] ) ) { throw new Error("noUiSlider: 'range' value isn't numeric."); } // Store values. that.xPct.push( percentage ); that.xVal.push( value[0] ); // NaN will evaluate to false too, but to keep // logging clear, set step explicitly. Make sure // not to override the 'step' setting with false. if ( !percentage ) { if ( !isNaN( value[1] ) ) { that.xSteps[0] = value[1]; } } else { that.xSteps.push( isNaN(value[1]) ? false : value[1] ); } } function handleStepPoint ( i, n, that ) { // Ignore 'false' stepping. if ( !n ) { return true; } // Factor to range ratio that.xSteps[i] = fromPercentage([ that.xVal[i] ,that.xVal[i+1] ], n) / subRangeRatio ( that.xPct[i], that.xPct[i+1] ); } // Interface // The interface to Spectrum handles all direction-based // conversions, so the above values are unaware. function Spectrum ( entry, snap, direction, singleStep ) { this.xPct = []; this.xVal = []; this.xSteps = [ singleStep || false ]; this.xNumSteps = [ false ]; this.snap = snap; this.direction = direction; var index, ordered = [ /* [0, 'min'], [1, '50%'], [2, 'max'] */ ]; // Map the object keys to an array. for ( index in entry ) { if ( entry.hasOwnProperty(index) ) { ordered.push([entry[index], index]); } } // Sort all entries by value (numeric sort). if ( ordered.length && typeof ordered[0][0] === "object" ) { ordered.sort(function(a, b) { return a[0][0] - b[0][0]; }); } else { ordered.sort(function(a, b) { return a[0] - b[0]; }); } // Convert all entries to subranges. for ( index = 0; index < ordered.length; index++ ) { handleEntryPoint(ordered[index][1], ordered[index][0], this); } // Store the actual step values. // xSteps is sorted in the same order as xPct and xVal. this.xNumSteps = this.xSteps.slice(0); // Convert all numeric steps to the percentage of the subrange they represent. for ( index = 0; index < this.xNumSteps.length; index++ ) { handleStepPoint(index, this.xNumSteps[index], this); } } Spectrum.prototype.getMargin = function ( value ) { return this.xPct.length === 2 ? fromPercentage(this.xVal, value) : false; }; Spectrum.prototype.toStepping = function ( value ) { value = toStepping( this.xVal, this.xPct, value ); // Invert the value if this is a right-to-left slider. if ( this.direction ) { value = 100 - value; } return value; }; Spectrum.prototype.fromStepping = function ( value ) { // Invert the value if this is a right-to-left slider. if ( this.direction ) { value = 100 - value; } return fromStepping( this.xVal, this.xPct, value ); }; Spectrum.prototype.getStep = function ( value ) { // Find the proper step for rtl sliders by search in inverse direction. // Fixes issue #262. if ( this.direction ) { value = 100 - value; } value = getStep(this.xPct, this.xSteps, this.snap, value ); if ( this.direction ) { value = 100 - value; } return value; }; Spectrum.prototype.getApplicableStep = function ( value ) { // If the value is 100%, return the negative step twice. var j = getJ(value, this.xPct), offset = value === 100 ? 2 : 1; return [this.xNumSteps[j-2], this.xVal[j-offset], this.xNumSteps[j-offset]]; }; // Outside testing Spectrum.prototype.convert = function ( value ) { return this.getStep(this.toStepping(value)); }; /* Every input option is tested and parsed. This'll prevent endless validation in internal methods. These tests are structured with an item for every option available. An option can be marked as required by setting the 'r' flag. The testing function is provided with three arguments: - The provided value for the option; - A reference to the options object; - The name for the option; The testing function returns false when an error is detected, or true when everything is OK. It can also modify the option object, to make sure all values can be correctly looped elsewhere. */ var defaultFormatter = { 'to': function( value ){ return value !== undefined && value.toFixed(2); }, 'from': Number }; function testStep ( parsed, entry ) { if ( !isNumeric( entry ) ) { throw new Error("noUiSlider: 'step' is not numeric."); } // The step option can still be used to set stepping // for linear sliders. Overwritten if set in 'range'. parsed.singleStep = entry; } function testRange ( parsed, entry ) { // Filter incorrect input. if ( typeof entry !== 'object' || Array.isArray(entry) ) { throw new Error("noUiSlider: 'range' is not an object."); } // Catch missing start or end. if ( entry.min === undefined || entry.max === undefined ) { throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'."); } // Catch equal start or end. if ( entry.min === entry.max ) { throw new Error("noUiSlider: 'range' 'min' and 'max' cannot be equal."); } parsed.spectrum = new Spectrum(entry, parsed.snap, parsed.dir, parsed.singleStep); } function testStart ( parsed, entry ) { entry = asArray(entry); // Validate input. Values aren't tested, as the public .val method // will always provide a valid location. if ( !Array.isArray( entry ) || !entry.length || entry.length > 2 ) { throw new Error("noUiSlider: 'start' option is incorrect."); } // Store the number of handles. parsed.handles = entry.length; // When the slider is initialized, the .val method will // be called with the start options. parsed.start = entry; } function testSnap ( parsed, entry ) { // Enforce 100% stepping within subranges. parsed.snap = entry; if ( typeof entry !== 'boolean' ){ throw new Error("noUiSlider: 'snap' option must be a boolean."); } } function testAnimate ( parsed, entry ) { // Enforce 100% stepping within subranges. parsed.animate = entry; if ( typeof entry !== 'boolean' ){ throw new Error("noUiSlider: 'animate' option must be a boolean."); } } function testAnimationDuration ( parsed, entry ) { parsed.animationDuration = entry; if ( typeof entry !== 'number' ){ throw new Error("noUiSlider: 'animationDuration' option must be a number."); } } function testConnect ( parsed, entry ) { if ( entry === 'lower' && parsed.handles === 1 ) { parsed.connect = 1; } else if ( entry === 'upper' && parsed.handles === 1 ) { parsed.connect = 2; } else if ( entry === true && parsed.handles === 2 ) { parsed.connect = 3; } else if ( entry === false ) { parsed.connect = 0; } else { throw new Error("noUiSlider: 'connect' option doesn't match handle count."); } } function testOrientation ( parsed, entry ) { // Set orientation to an a numerical value for easy // array selection. switch ( entry ){ case 'horizontal': parsed.ort = 0; break; case 'vertical': parsed.ort = 1; break; default: throw new Error("noUiSlider: 'orientation' option is invalid."); } } function testMargin ( parsed, entry ) { if ( !isNumeric(entry) ){ throw new Error("noUiSlider: 'margin' option must be numeric."); } // Issue #582 if ( entry === 0 ) { return; } parsed.margin = parsed.spectrum.getMargin(entry); if ( !parsed.margin ) { throw new Error("noUiSlider: 'margin' option is only supported on linear sliders."); } } function testLimit ( parsed, entry ) { if ( !isNumeric(entry) ){ throw new Error("noUiSlider: 'limit' option must be numeric."); } parsed.limit = parsed.spectrum.getMargin(entry); if ( !parsed.limit ) { throw new Error("noUiSlider: 'limit' option is only supported on linear sliders."); } } function testDirection ( parsed, entry ) { // Set direction as a numerical value for easy parsing. // Invert connection for RTL sliders, so that the proper // handles get the connect/background classes. switch ( entry ) { case 'ltr': parsed.dir = 0; break; case 'rtl': parsed.dir = 1; parsed.connect = [0,2,1,3][parsed.connect]; break; default: throw new Error("noUiSlider: 'direction' option was not recognized."); } } function testBehaviour ( parsed, entry ) { // Make sure the input is a string. if ( typeof entry !== 'string' ) { throw new Error("noUiSlider: 'behaviour' must be a string containing options."); } // Check if the string contains any keywords. // None are required. var tap = entry.indexOf('tap') >= 0, drag = entry.indexOf('drag') >= 0, fixed = entry.indexOf('fixed') >= 0, snap = entry.indexOf('snap') >= 0, hover = entry.indexOf('hover') >= 0; // Fix #472 if ( drag && !parsed.connect ) { throw new Error("noUiSlider: 'drag' behaviour must be used with 'connect': true."); } parsed.events = { tap: tap || snap, drag: drag, fixed: fixed, snap: snap, hover: hover }; } function testTooltips ( parsed, entry ) { var i; if ( entry === false ) { return; } else if ( entry === true ) { parsed.tooltips = []; for ( i = 0; i < parsed.handles; i++ ) { parsed.tooltips.push(true); } } else { parsed.tooltips = asArray(entry); if ( parsed.tooltips.length !== parsed.handles ) { throw new Error("noUiSlider: must pass a formatter for all handles."); } parsed.tooltips.forEach(function(formatter){ if ( typeof formatter !== 'boolean' && (typeof formatter !== 'object' || typeof formatter.to !== 'function') ) { throw new Error("noUiSlider: 'tooltips' must be passed a formatter or 'false'."); } }); } } function testFormat ( parsed, entry ) { parsed.format = entry; // Any object with a to and from method is supported. if ( typeof entry.to === 'function' && typeof entry.from === 'function' ) { return true; } throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods."); } function testCssPrefix ( parsed, entry ) { if ( entry !== undefined && typeof entry !== 'string' && entry !== false ) { throw new Error("noUiSlider: 'cssPrefix' must be a string or `false`."); } parsed.cssPrefix = entry; } function testCssClasses ( parsed, entry ) { if ( entry !== undefined && typeof entry !== 'object' ) { throw new Error("noUiSlider: 'cssClasses' must be an object."); } if ( typeof parsed.cssPrefix === 'string' ) { parsed.cssClasses = {}; for ( var key in entry ) { if ( !entry.hasOwnProperty(key) ) { continue; } parsed.cssClasses[key] = parsed.cssPrefix + entry[key]; } } else { parsed.cssClasses = entry; } } // Test all developer settings and parse to assumption-safe values. function testOptions ( options ) { // To prove a fix for #537, freeze options here. // If the object is modified, an error will be thrown. // Object.freeze(options); var parsed = { margin: 0, limit: 0, animate: true, animationDuration: 300, format: defaultFormatter }, tests; // Tests are executed in the order they are presented here. tests = { 'step': { r: false, t: testStep }, 'start': { r: true, t: testStart }, 'connect': { r: true, t: testConnect }, 'direction': { r: true, t: testDirection }, 'snap': { r: false, t: testSnap }, 'animate': { r: false, t: testAnimate }, 'animationDuration': { r: false, t: testAnimationDuration }, 'range': { r: true, t: testRange }, 'orientation': { r: false, t: testOrientation }, 'margin': { r: false, t: testMargin }, 'limit': { r: false, t: testLimit }, 'behaviour': { r: true, t: testBehaviour }, 'format': { r: false, t: testFormat }, 'tooltips': { r: false, t: testTooltips }, 'cssPrefix': { r: false, t: testCssPrefix }, 'cssClasses': { r: false, t: testCssClasses } }; var defaults = { 'connect': false, 'direction': 'ltr', 'behaviour': 'tap', 'orientation': 'horizontal', 'cssPrefix' : 'noUi-', 'cssClasses': { target: 'target', base: 'base', origin: 'origin', handle: 'handle', handleLower: 'handle-lower', handleUpper: 'handle-upper', horizontal: 'horizontal', vertical: 'vertical', background: 'background', connect: 'connect', ltr: 'ltr', rtl: 'rtl', draggable: 'draggable', drag: 'state-drag', tap: 'state-tap', active: 'active', stacking: 'stacking', tooltip: 'tooltip', pips: 'pips', pipsHorizontal: 'pips-horizontal', pipsVertical: 'pips-vertical', marker: 'marker', markerHorizontal: 'marker-horizontal', markerVertical: 'marker-vertical', markerNormal: 'marker-normal', markerLarge: 'marker-large', markerSub: 'marker-sub', value: 'value', valueHorizontal: 'value-horizontal', valueVertical: 'value-vertical', valueNormal: 'value-normal', valueLarge: 'value-large', valueSub: 'value-sub' } }; // Run all options through a testing mechanism to ensure correct // input. It should be noted that options might get modified to // be handled properly. E.g. wrapping integers in arrays. Object.keys(tests).forEach(function( name ){ // If the option isn't set, but it is required, throw an error. if ( options[name] === undefined && defaults[name] === undefined ) { if ( tests[name].r ) { throw new Error("noUiSlider: '" + name + "' is required."); } return true; } tests[name].t( parsed, options[name] === undefined ? defaults[name] : options[name] ); }); // Forward pips options parsed.pips = options.pips; // Pre-define the styles. parsed.style = parsed.ort ? 'top' : 'left'; return parsed; } function closure ( target, options, originalOptions ){ var actions = getActions( ), // All variables local to 'closure' are prefixed with 'scope_' scope_Target = target, scope_Locations = [-1, -1], scope_Base, scope_Handles, scope_Spectrum = options.spectrum, scope_Values = [], scope_Events = {}, scope_Self; // Delimit proposed values for handle positions. function getPositions ( a, b, delimit ) { // Add movement to current position. var c = a + b[0], d = a + b[1]; // Only alter the other position on drag, // not on standard sliding. if ( delimit ) { if ( c < 0 ) { d += Math.abs(c); } if ( d > 100 ) { c -= ( d - 100 ); } // Limit values to 0 and 100. return [limit(c), limit(d)]; } return [c,d]; } // Provide a clean event with standardized offset values. function fixEvent ( e, pageOffset ) { // Prevent scrolling and panning on touch events, while // attempting to slide. The tap event also depends on this. e.preventDefault(); // Filter the event to register the type, which can be // touch, mouse or pointer. Offset changes need to be // made on an event specific basis. var touch = e.type.indexOf('touch') === 0, mouse = e.type.indexOf('mouse') === 0, pointer = e.type.indexOf('pointer') === 0, x,y, event = e; // IE10 implemented pointer events with a prefix; if ( e.type.indexOf('MSPointer') === 0 ) { pointer = true; } if ( touch ) { // noUiSlider supports one movement at a time, // so we can select the first 'changedTouch'. x = e.changedTouches[0].pageX; y = e.changedTouches[0].pageY; } pageOffset = pageOffset || getPageOffset(); if ( mouse || pointer ) { x = e.clientX + pageOffset.x; y = e.clientY + pageOffset.y; } event.pageOffset = pageOffset; event.points = [x, y]; event.cursor = mouse || pointer; // Fix #435 return event; } // Append a handle to the base. function addHandle ( direction, index ) { var origin = document.createElement('div'), handle = document.createElement('div'), classModifier = [options.cssClasses.handleLower, options.cssClasses.handleUpper]; if ( direction ) { classModifier.reverse(); } addClass(handle, options.cssClasses.handle); addClass(handle, classModifier[index]); addClass(origin, options.cssClasses.origin); origin.appendChild(handle); return origin; } // Add the proper connection classes. function addConnection ( connect, target, handles ) { // Apply the required connection classes to the elements // that need them. Some classes are made up for several // segments listed in the class list, to allow easy // renaming and provide a minor compression benefit. switch ( connect ) { case 1: addClass(target, options.cssClasses.connect); addClass(handles[0], options.cssClasses.background); break; case 3: addClass(handles[1], options.cssClasses.background); /* falls through */ case 2: addClass(handles[0], options.cssClasses.connect); /* falls through */ case 0: addClass(target, options.cssClasses.background); break; } } // Add handles to the slider base. function addHandles ( nrHandles, direction, base ) { var index, handles = []; // Append handles. for ( index = 0; index < nrHandles; index += 1 ) { // Keep a list of all added handles. handles.push( base.appendChild(addHandle( direction, index )) ); } return handles; } // Initialize a single slider. function addSlider ( direction, orientation, target ) { // Apply classes and data to the target. addClass(target, options.cssClasses.target); if ( direction === 0 ) { addClass(target, options.cssClasses.ltr); } else { addClass(target, options.cssClasses.rtl); } if ( orientation === 0 ) { addClass(target, options.cssClasses.horizontal); } else { addClass(target, options.cssClasses.vertical); } var div = document.createElement('div'); addClass(div, options.cssClasses.base); target.appendChild(div); return div; } function addTooltip ( handle, index ) { if ( !options.tooltips[index] ) { return false; } var element = document.createElement('div'); element.className = options.cssClasses.tooltip; return handle.firstChild.appendChild(element); } // The tooltips option is a shorthand for using the 'update' event. function tooltips ( ) { if ( options.dir ) { options.tooltips.reverse(); } // Tooltips are added with options.tooltips in original order. var tips = scope_Handles.map(addTooltip); if ( options.dir ) { tips.reverse(); options.tooltips.reverse(); } bindEvent('update', function(f, o, r) { if ( tips[o] ) { tips[o].innerHTML = options.tooltips[o] === true ? f[o] : options.tooltips[o].to(r[o]); } }); } function getGroup ( mode, values, stepped ) { // Use the range. if ( mode === 'range' || mode === 'steps' ) { return scope_Spectrum.xVal; } if ( mode === 'count' ) { // Divide 0 - 100 in 'count' parts. var spread = ( 100 / (values-1) ), v, i = 0; values = []; // List these parts and have them handled as 'positions'. while ((v=i++*spread) <= 100 ) { values.push(v); } mode = 'positions'; } if ( mode === 'positions' ) { // Map all percentages to on-range values. return values.map(function( value ){ return scope_Spectrum.fromStepping( stepped ? scope_Spectrum.getStep( value ) : value ); }); } if ( mode === 'values' ) { // If the value must be stepped, it needs to be converted to a percentage first. if ( stepped ) { return values.map(function( value ){ // Convert to percentage, apply step, return to value. return scope_Spectrum.fromStepping( scope_Spectrum.getStep( scope_Spectrum.toStepping( value ) ) ); }); } // Otherwise, we can simply use the values. return values; } } function generateSpread ( density, mode, group ) { function safeIncrement(value, increment) { // Avoid floating point variance by dropping the smallest decimal places. return (value + increment).toFixed(7) / 1; } var originalSpectrumDirection = scope_Spectrum.direction, indexes = {}, firstInRange = scope_Spectrum.xVal[0], lastInRange = scope_Spectrum.xVal[scope_Spectrum.xVal.length-1], ignoreFirst = false, ignoreLast = false, prevPct = 0; // This function loops the spectrum in an ltr linear fashion, // while the toStepping method is direction aware. Trick it into // believing it is ltr. scope_Spectrum.direction = 0; // Create a copy of the group, sort it and filter away all duplicates. group = unique(group.slice().sort(function(a, b){ return a - b; })); // Make sure the range starts with the first element. if ( group[0] !== firstInRange ) { group.unshift(firstInRange); ignoreFirst = true; } // Likewise for the last one. if ( group[group.length - 1] !== lastInRange ) { group.push(lastInRange); ignoreLast = true; } group.forEach(function ( current, index ) { // Get the current step and the lower + upper positions. var step, i, q, low = current, high = group[index+1], newPct, pctDifference, pctPos, type, steps, realSteps, stepsize; // When using 'steps' mode, use the provided steps. // Otherwise, we'll step on to the next subrange. if ( mode === 'steps' ) { step = scope_Spectrum.xNumSteps[ index ]; } // Default to a 'full' step. if ( !step ) { step = high-low; } // Low can be 0, so test for false. If high is undefined, // we are at the last subrange. Index 0 is already handled. if ( low === false || high === undefined ) { return; } // Find all steps in the subrange. for ( i = low; i <= high; i = safeIncrement(i, step) ) { // Get the percentage value for the current step, // calculate the size for the subrange. newPct = scope_Spectrum.toStepping( i ); pctDifference = newPct - prevPct; steps = pctDifference / density; realSteps = Math.round(steps); // This ratio represents the ammount of percentage-space a point indicates. // For a density 1 the points/percentage = 1. For density 2, that percentage needs to be re-devided. // Round the percentage offset to an even number, then divide by two // to spread the offset on both sides of the range. stepsize = pctDifference/realSteps; // Divide all points evenly, adding the correct number to this subrange. // Run up to <= so that 100% gets a point, event if ignoreLast is set. for ( q = 1; q <= realSteps; q += 1 ) { // The ratio between the rounded value and the actual size might be ~1% off. // Correct the percentage offset by the number of points // per subrange. density = 1 will result in 100 points on the // full range, 2 for 50, 4 for 25, etc. pctPos = prevPct + ( q * stepsize ); indexes[pctPos.toFixed(5)] = ['x', 0]; } // Determine the point type. type = (group.indexOf(i) > -1) ? 1 : ( mode === 'steps' ? 2 : 0 ); // Enforce the 'ignoreFirst' option by overwriting the type for 0. if ( !index && ignoreFirst ) { type = 0; } if ( !(i === high && ignoreLast)) { // Mark the 'type' of this point. 0 = plain, 1 = real value, 2 = step value. indexes[newPct.toFixed(5)] = [i, type]; } // Update the percentage count. prevPct = newPct; } }); // Reset the spectrum. scope_Spectrum.direction = originalSpectrumDirection; return indexes; } function addMarking ( spread, filterFunc, formatter ) { var element = document.createElement('div'), out = '', valueSizeClasses = [ options.cssClasses.valueNormal, options.cssClasses.valueLarge, options.cssClasses.valueSub ], markerSizeClasses = [ options.cssClasses.markerNormal, options.cssClasses.markerLarge, options.cssClasses.markerSub ], valueOrientationClasses = [ options.cssClasses.valueHorizontal, options.cssClasses.valueVertical ], markerOrientationClasses = [ options.cssClasses.markerHorizontal, options.cssClasses.markerVertical ]; addClass(element, options.cssClasses.pips); addClass(element, options.ort === 0 ? options.cssClasses.pipsHorizontal : options.cssClasses.pipsVertical); function getClasses( type, source ){ var a = source === options.cssClasses.value, orientationClasses = a ? valueOrientationClasses : markerOrientationClasses, sizeClasses = a ? valueSizeClasses : markerSizeClasses; return source + ' ' + orientationClasses[options.ort] + ' ' + sizeClasses[type]; } function getTags( offset, source, values ) { return 'class="' + getClasses(values[1], source) + '" style="' + options.style + ': ' + offset + '%"'; } function addSpread ( offset, values ){ if ( scope_Spectrum.direction ) { offset = 100 - offset; } // Apply the filter function, if it is set. values[1] = (values[1] && filterFunc) ? filterFunc(values[0], values[1]) : values[1]; // Add a marker for every point out += '<div ' + getTags(offset, options.cssClasses.marker, values) + '></div>'; // Values are only appended for points marked '1' or '2'. if ( values[1] ) { out += '<div ' + getTags(offset, options.cssClasses.value, values) + '>' + formatter.to(values[0]) + '</div>'; } } // Append all points. Object.keys(spread).forEach(function(a){ addSpread(a, spread[a]); }); element.innerHTML = out; return element; } function pips ( grid ) { var mode = grid.mode, density = grid.density || 1, filter = grid.filter || false, values = grid.values || false, stepped = grid.stepped || false, group = getGroup( mode, values, stepped ), spread = generateSpread( density, mode, group ), format = grid.format || { to: Math.round }; return scope_Target.appendChild(addMarking( spread, filter, format )); } // Shorthand for base dimensions. function baseSize ( ) { var rect = scope_Base.getBoundingClientRect(), alt = 'offset' + ['Width', 'Height'][options.ort]; return options.ort === 0 ? (rect.width||scope_Base[alt]) : (rect.height||scope_Base[alt]); } // External event handling function fireEvent ( event, handleNumber, tap ) { var i; // During initialization, do not fire events. for ( i = 0; i < options.handles; i++ ) { if ( scope_Locations[i] === -1 ) { return; } } if ( handleNumber !== undefined && options.handles !== 1 ) { handleNumber = Math.abs(handleNumber - options.dir); } Object.keys(scope_Events).forEach(function( targetEvent ) { var eventType = targetEvent.split('.')[0]; if ( event === eventType ) { scope_Events[targetEvent].forEach(function( callback ) { callback.call( // Use the slider public API as the scope ('this') scope_Self, // Return values as array, so arg_1[arg_2] is always valid. asArray(valueGet()), // Handle index, 0 or 1 handleNumber, // Unformatted slider values asArray(inSliderOrder(Array.prototype.slice.call(scope_Values))), // Event is fired by tap, true or false tap || false, // Left offset of the handle, in relation to the slider scope_Locations ); }); } }); } // Returns the input array, respecting the slider direction configuration. function inSliderOrder ( values ) { // If only one handle is used, return a single value. if ( values.length === 1 ){ return values[0]; } if ( options.dir ) { return values.reverse(); } return values; } // Handler for attaching events trough a proxy. function attach ( events, element, callback, data ) { // This function can be used to 'filter' events to the slider. // element is a node, not a nodeList var method = function ( e ){ if ( scope_Target.hasAttribute('disabled') ) { return false; } // Stop if an active 'tap' transition is taking place. if ( hasClass(scope_Target, options.cssClasses.tap) ) { return false; } e = fixEvent(e, data.pageOffset); // Ignore right or middle clicks on start #454 if ( events === actions.start && e.buttons !== undefined && e.buttons > 1 ) { return false; } // Ignore right or middle clicks on start #454 if ( data.hover && e.buttons ) { return false; } e.calcPoint = e.points[ options.ort ]; // Call the event handler with the event [ and additional data ]. callback ( e, data ); }, methods = []; // Bind a closure on the target for every event type. events.split(' ').forEach(function( eventName ){ element.addEventListener(eventName, method, false); methods.push([eventName, method]); }); return methods; } // Handle movement on document for handle and range drag. function move ( event, data ) { // Fix #498 // Check value of .buttons in 'start' to work around a bug in IE10 mobile (data.buttonsProperty). // https://connect.microsoft.com/IE/feedback/details/927005/mobile-ie10-windows-phone-buttons-property-of-pointermove-event-always-zero // IE9 has .buttons and .which zero on mousemove. // Firefox breaks the spec MDN defines. if ( navigator.appVersion.indexOf("MSIE 9") === -1 && event.buttons === 0 && data.buttonsProperty !== 0 ) { return end(event, data); } var handles = data.handles || scope_Handles, positions, state = false, proposal = ((event.calcPoint - data.start) * 100) / data.baseSize, handleNumber = handles[0] === scope_Handles[0] ? 0 : 1, i; // Calculate relative positions for the handles. positions = getPositions( proposal, data.positions, handles.length > 1); state = setHandle ( handles[0], positions[handleNumber], handles.length === 1 ); if ( handles.length > 1 ) { state = setHandle ( handles[1], positions[handleNumber?0:1], false ) || state; if ( state ) { // fire for both handles for ( i = 0; i < data.handles.length; i++ ) { fireEvent('slide', i); } } } else if ( state ) { // Fire for a single handle fireEvent('slide', handleNumber); } } // Unbind move events on document, call callbacks. function end ( event, data ) { // The handle is no longer active, so remove the class. var active = scope_Base.querySelector( '.' + options.cssClasses.active ), handleNumber = data.handles[0] === scope_Handles[0] ? 0 : 1; if ( active !== null ) { removeClass(active, options.cssClasses.active); } // Remove cursor styles and text-selection events bound to the body. if ( event.cursor ) { document.body.style.cursor = ''; document.body.removeEventListener('selectstart', document.body.noUiListener); } var d = document.documentElement; // Unbind the move and end events, which are added on 'start'. d.noUiListeners.forEach(function( c ) { d.removeEventListener(c[0], c[1]); }); // Remove dragging class. removeClass(scope_Target, options.cssClasses.drag); // Fire the change and set events. fireEvent('set', handleNumber); fireEvent('change', handleNumber); // If this is a standard handle movement, fire the end event. if ( data.handleNumber !== undefined ) { fireEvent('end', data.handleNumber); } } // Fire 'end' when a mouse or pen leaves the document. function documentLeave ( event, data ) { if ( event.type === "mouseout" && event.target.nodeName === "HTML" && event.relatedTarget === null ){ end ( event, data ); } } // Bind move events on document. function start ( event, data ) { var d = document.documentElement; // Mark the handle as 'active' so it can be styled. if ( data.handles.length === 1 ) { // Support 'disabled' handles if ( data.handles[0].hasAttribute('disabled') ) { return false; } addClass(data.handles[0].children[0], options.cssClasses.active); } // Fix #551, where a handle gets selected instead of dragged. event.preventDefault(); // A drag should never propagate up to the 'tap' event. event.stopPropagation(); // Attach the move and end events. var moveEvent = attach(actions.move, d, move, { start: event.calcPoint, baseSize: baseSize(), pageOffset: event.pageOffset, handles: data.handles, handleNumber: data.handleNumber, buttonsProperty: event.buttons, positions: [ scope_Locations[0], scope_Locations[scope_Handles.length - 1] ] }), endEvent = attach(actions.end, d, end, { handles: data.handles, handleNumber: data.handleNumber }); var outEvent = attach("mouseout", d, documentLeave, { handles: data.handles, handleNumber: data.handleNumber }); d.noUiListeners = moveEvent.concat(endEvent, outEvent); // Text selection isn't an issue on touch devices, // so adding cursor styles can be skipped. if ( event.cursor ) { // Prevent the 'I' cursor and extend the range-drag cursor. document.body.style.cursor = getComputedStyle(event.target).cursor; // Mark the target with a dragging state. if ( scope_Handles.length > 1 ) { addClass(scope_Target, options.cssClasses.drag); } var f = function(){ return false; }; document.body.noUiListener = f; // Prevent text selection when dragging the handles. document.body.addEventListener('selectstart', f, false); } if ( data.handleNumber !== undefined ) { fireEvent('start', data.handleNumber); } } // Move closest handle to tapped location. function tap ( event ) { var location = event.calcPoint, total = 0, handleNumber, to; // The tap event shouldn't propagate up and cause 'edge' to run. event.stopPropagation(); // Add up the handle offsets. scope_Handles.forEach(function(a){ total += offset(a)[ options.style ]; }); // Find the handle closest to the tapped position. handleNumber = ( location < total/2 || scope_Handles.length === 1 ) ? 0 : 1; // Check if handler is not disablet if yes set number to the next handler if (scope_Handles[handleNumber].hasAttribute('disabled')) { handleNumber = handleNumber ? 0 : 1; } location -= offset(scope_Base)[ options.style ]; // Calculate the new position. to = ( location * 100 ) / baseSize(); if ( !options.events.snap ) { // Flag the slider as it is now in a transitional state. // Transition takes a configurable amount of ms (default 300). Re-enable the slider after that. addClassFor( scope_Target, options.cssClasses.tap, options.animationDuration ); } // Support 'disabled' handles if ( scope_Handles[handleNumber].hasAttribute('disabled') ) { return false; } // Find the closest handle and calculate the tapped point. // The set handle to the new position. setHandle( scope_Handles[handleNumber], to ); fireEvent('slide', handleNumber, true); fireEvent('set', handleNumber, true); fireEvent('change', handleNumber, true); if ( options.events.snap ) { start(event, { handles: [scope_Handles[handleNumber]] }); } } // Fires a 'hover' event for a hovered mouse/pen position. function hover ( event ) { var location = event.calcPoint - offset(scope_Base)[ options.style ], to = scope_Spectrum.getStep(( location * 100 ) / baseSize()), value = scope_Spectrum.fromStepping( to ); Object.keys(scope_Events).forEach(function( targetEvent ) { if ( 'hover' === targetEvent.split('.')[0] ) { scope_Events[targetEvent].forEach(function( callback ) { callback.call( scope_Self, value ); }); } }); } // Attach events to several slider parts. function events ( behaviour ) { // Attach the standard drag event to the handles. if ( !behaviour.fixed ) { scope_Handles.forEach(function( handle, index ){ // These events are only bound to the visual handle // element, not the 'real' origin element. attach ( actions.start, handle.children[0], start, { handles: [ handle ], handleNumber: index }); }); } // Attach the tap event to the slider base. if ( behaviour.tap ) { attach ( actions.start, scope_Base, tap, { handles: scope_Handles }); } // Fire hover events if ( behaviour.hover ) { attach ( actions.move, scope_Base, hover, { hover: true } ); } // Make the range draggable. if ( behaviour.drag ){ var drag = [scope_Base.querySelector( '.' + options.cssClasses.connect )]; addClass(drag[0], options.cssClasses.draggable); // When the range is fixed, the entire range can // be dragged by the handles. The handle in the first // origin will propagate the start event upward, // but it needs to be bound manually on the other. if ( behaviour.fixed ) { drag.push(scope_Handles[(drag[0] === scope_Handles[0] ? 1 : 0)].children[0]); } drag.forEach(function( element ) { attach ( actions.start, element, start, { handles: scope_Handles }); }); } } // Test suggested values and apply margin, step. function setHandle ( handle, to, noLimitOption ) { var trigger = handle !== scope_Handles[0] ? 1 : 0, lowerMargin = scope_Locations[0] + options.margin, upperMargin = scope_Locations[1] - options.margin, lowerLimit = scope_Locations[0] + options.limit, upperLimit = scope_Locations[1] - options.limit; // For sliders with multiple handles, // limit movement to the other handle. // Apply the margin option by adding it to the handle positions. if ( scope_Handles.length > 1 ) { to = trigger ? Math.max( to, lowerMargin ) : Math.min( to, upperMargin ); } // The limit option has the opposite effect, limiting handles to a // maximum distance from another. Limit must be > 0, as otherwise // handles would be unmoveable. 'noLimitOption' is set to 'false' // for the .val() method, except for pass 4/4. if ( noLimitOption !== false && options.limit && scope_Handles.length > 1 ) { to = trigger ? Math.min ( to, lowerLimit ) : Math.max( to, upperLimit ); } // Handle the step option. to = scope_Spectrum.getStep( to ); // Limit percentage to the 0 - 100 range to = limit(to); // Return false if handle can't move if ( to === scope_Locations[trigger] ) { return false; } // Set the handle to the new position. // Use requestAnimationFrame for efficient painting. // No significant effect in Chrome, Edge sees dramatic // performace improvements. if ( window.requestAnimationFrame ) { window.requestAnimationFrame(function(){ handle.style[options.style] = to + '%'; }); } else { handle.style[options.style] = to + '%'; } // Force proper handle stacking if ( !handle.previousSibling ) { removeClass(handle, options.cssClasses.stacking); if ( to > 50 ) { addClass(handle, options.cssClasses.stacking); } } // Update locations. scope_Locations[trigger] = to; // Convert the value to the slider stepping/range. scope_Values[trigger] = scope_Spectrum.fromStepping( to ); fireEvent('update', trigger); return true; } // Loop values from value method and apply them. function setValues ( count, values ) { var i, trigger, to; // With the limit option, we'll need another limiting pass. if ( options.limit ) { count += 1; } // If there are multiple handles to be set run the setting // mechanism twice for the first handle, to make sure it // can be bounced of the second one properly. for ( i = 0; i < count; i += 1 ) { trigger = i%2; // Get the current argument from the array. to = values[trigger]; // Setting with null indicates an 'ignore'. // Inputting 'false' is invalid. if ( to !== null && to !== false ) { // If a formatted number was passed, attemt to decode it. if ( typeof to === 'number' ) { to = String(to); } to = options.format.from( to ); // Request an update for all links if the value was invalid. // Do so too if setting the handle fails. if ( to === false || isNaN(to) || setHandle( scope_Handles[trigger], scope_Spectrum.toStepping( to ), i === (3 - options.dir) ) === false ) { fireEvent('update', trigger); } } } } // Set the slider value. function valueSet ( input, fireSetEvent ) { var count, values = asArray( input ), i; // Event fires by default fireSetEvent = (fireSetEvent === undefined ? true : !!fireSetEvent); // The RTL settings is implemented by reversing the front-end, // internal mechanisms are the same. if ( options.dir && options.handles > 1 ) { values.reverse(); } // Animation is optional. // Make sure the initial values where set before using animated placement. if ( options.animate && scope_Locations[0] !== -1 ) { addClassFor( scope_Target, options.cssClasses.tap, options.animationDuration ); } // Determine how often to set the handles. count = scope_Handles.length > 1 ? 3 : 1; if ( values.length === 1 ) { count = 1; } setValues ( count, values ); // Fire the 'set' event for both handles. for ( i = 0; i < scope_Handles.length; i++ ) { // Fire the event only for handles that received a new value, as per #579 if ( values[i] !== null && fireSetEvent ) { fireEvent('set', i); } } } // Get the slider value. function valueGet ( ) { var i, retour = []; // Get the value from all handles. for ( i = 0; i < options.handles; i += 1 ){ retour[i] = options.format.to( scope_Values[i] ); } return inSliderOrder( retour ); } // Removes classes from the root and empties it. function destroy ( ) { for ( var key in options.cssClasses ) { if ( !options.cssClasses.hasOwnProperty(key) ) { continue; } removeClass(scope_Target, options.cssClasses[key]); } while (scope_Target.firstChild) { scope_Target.removeChild(scope_Target.firstChild); } delete scope_Target.noUiSlider; } // Get the current step size for the slider. function getCurrentStep ( ) { // Check all locations, map them to their stepping point. // Get the step point, then find it in the input list. var retour = scope_Locations.map(function( location, index ){ var step = scope_Spectrum.getApplicableStep( location ), // As per #391, the comparison for the decrement step can have some rounding issues. // Round the value to the precision used in the step. stepDecimals = countDecimals(String(step[2])), // Get the current numeric value value = scope_Values[index], // To move the slider 'one step up', the current step value needs to be added. // Use null if we are at the maximum slider value. increment = location === 100 ? null : step[2], // Going 'one step down' might put the slider in a different sub-range, so we // need to switch between the current or the previous step. prev = Number((value - step[2]).toFixed(stepDecimals)), // If the value fits the step, return the current step value. Otherwise, use the // previous step. Return null if the slider is at its minimum value. decrement = location === 0 ? null : (prev >= step[1]) ? step[2] : (step[0] || false); return [decrement, increment]; }); // Return values in the proper order. return inSliderOrder( retour ); } // Attach an event to this slider, possibly including a namespace function bindEvent ( namespacedEvent, callback ) { scope_Events[namespacedEvent] = scope_Events[namespacedEvent] || []; scope_Events[namespacedEvent].push(callback); // If the event bound is 'update,' fire it immediately for all handles. if ( namespacedEvent.split('.')[0] === 'update' ) { scope_Handles.forEach(function(a, index){ fireEvent('update', index); }); } } // Undo attachment of event function removeEvent ( namespacedEvent ) { var event = namespacedEvent && namespacedEvent.split('.')[0], namespace = event && namespacedEvent.substring(event.length); Object.keys(scope_Events).forEach(function( bind ){ var tEvent = bind.split('.')[0], tNamespace = bind.substring(tEvent.length); if ( (!event || event === tEvent) && (!namespace || namespace === tNamespace) ) { delete scope_Events[bind]; } }); } // Updateable: margin, limit, step, range, animate, snap function updateOptions ( optionsToUpdate, fireSetEvent ) { // Spectrum is created using the range, snap, direction and step options. // 'snap' and 'step' can be updated, 'direction' cannot, due to event binding. // If 'snap' and 'step' are not passed, they should remain unchanged. var v = valueGet(), newOptions = testOptions({ start: [0, 0], margin: optionsToUpdate.margin, limit: optionsToUpdate.limit, step: optionsToUpdate.step === undefined ? options.singleStep : optionsToUpdate.step, range: optionsToUpdate.range, animate: optionsToUpdate.animate, snap: optionsToUpdate.snap === undefined ? options.snap : optionsToUpdate.snap }); ['margin', 'limit', 'range', 'animate'].forEach(function(name){ // Only change options that we're actually passed to update. if ( optionsToUpdate[name] !== undefined ) { options[name] = optionsToUpdate[name]; } }); // Save current spectrum direction as testOptions in testRange call // doesn't rely on current direction newOptions.spectrum.direction = scope_Spectrum.direction; scope_Spectrum = newOptions.spectrum; // Invalidate the current positioning so valueSet forces an update. scope_Locations = [-1, -1]; valueSet(optionsToUpdate.start || v, fireSetEvent); } // Throw an error if the slider was already initialized. if ( scope_Target.noUiSlider ) { throw new Error('Slider was already initialized.'); } // Create the base element, initialise HTML and set classes. // Add handles and links. scope_Base = addSlider( options.dir, options.ort, scope_Target ); scope_Handles = addHandles( options.handles, options.dir, scope_Base ); // Set the connect classes. addConnection ( options.connect, scope_Target, scope_Handles ); if ( options.pips ) { pips(options.pips); } if ( options.tooltips ) { tooltips(); } scope_Self = { destroy: destroy, steps: getCurrentStep, on: bindEvent, off: removeEvent, get: valueGet, set: valueSet, updateOptions: updateOptions, options: originalOptions, // Issue #600 target: scope_Target, // Issue #597 pips: pips // Issue #594 }; // Attach user events. events( options.events ); return scope_Self; } // Run the standard initializer function initialize ( target, originalOptions ) { if ( !target.nodeName ) { throw new Error('noUiSlider.create requires a single element.'); } // Test the options and create the slider environment; var options = testOptions( originalOptions, target ), slider = closure( target, options, originalOptions ); // Use the public value method to set the start values. slider.set(options.start); target.noUiSlider = slider; return slider; } // Use an object instead of a function for future expansibility; return { create: initialize }; })); },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/nprogress/nprogress.js":[function(require,module,exports){ /* NProgress, (c) 2013, 2014 Rico Sta. Cruz - http://ricostacruz.com/nprogress * @license MIT */ ;(function(root, factory) { if (typeof define === 'function' && define.amd) { define(factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.NProgress = factory(); } })(this, function() { var NProgress = {}; NProgress.version = '0.2.0'; var Settings = NProgress.settings = { minimum: 0.08, easing: 'ease', positionUsing: '', speed: 200, trickle: true, trickleRate: 0.02, trickleSpeed: 800, showSpinner: true, barSelector: '[role="bar"]', spinnerSelector: '[role="spinner"]', parent: 'body', template: '<div class="bar" role="bar"><div class="peg"></div></div><div class="spinner" role="spinner"><div class="spinner-icon"></div></div>' }; /** * Updates configuration. * * NProgress.configure({ * minimum: 0.1 * }); */ NProgress.configure = function(options) { var key, value; for (key in options) { value = options[key]; if (value !== undefined && options.hasOwnProperty(key)) Settings[key] = value; } return this; }; /** * Last number. */ NProgress.status = null; /** * Sets the progress bar status, where `n` is a number from `0.0` to `1.0`. * * NProgress.set(0.4); * NProgress.set(1.0); */ NProgress.set = function(n) { var started = NProgress.isStarted(); n = clamp(n, Settings.minimum, 1); NProgress.status = (n === 1 ? null : n); var progress = NProgress.render(!started), bar = progress.querySelector(Settings.barSelector), speed = Settings.speed, ease = Settings.easing; progress.offsetWidth; /* Repaint */ queue(function(next) { // Set positionUsing if it hasn't already been set if (Settings.positionUsing === '') Settings.positionUsing = NProgress.getPositioningCSS(); // Add transition css(bar, barPositionCSS(n, speed, ease)); if (n === 1) { // Fade out css(progress, { transition: 'none', opacity: 1 }); progress.offsetWidth; /* Repaint */ setTimeout(function() { css(progress, { transition: 'all ' + speed + 'ms linear', opacity: 0 }); setTimeout(function() { NProgress.remove(); next(); }, speed); }, speed); } else { setTimeout(next, speed); } }); return this; }; NProgress.isStarted = function() { return typeof NProgress.status === 'number'; }; /** * Shows the progress bar. * This is the same as setting the status to 0%, except that it doesn't go backwards. * * NProgress.start(); * */ NProgress.start = function() { if (!NProgress.status) NProgress.set(0); var work = function() { setTimeout(function() { if (!NProgress.status) return; NProgress.trickle(); work(); }, Settings.trickleSpeed); }; if (Settings.trickle) work(); return this; }; /** * Hides the progress bar. * This is the *sort of* the same as setting the status to 100%, with the * difference being `done()` makes some placebo effect of some realistic motion. * * NProgress.done(); * * If `true` is passed, it will show the progress bar even if its hidden. * * NProgress.done(true); */ NProgress.done = function(force) { if (!force && !NProgress.status) return this; return NProgress.inc(0.3 + 0.5 * Math.random()).set(1); }; /** * Increments by a random amount. */ NProgress.inc = function(amount) { var n = NProgress.status; if (!n) { return NProgress.start(); } else { if (typeof amount !== 'number') { amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95); } n = clamp(n + amount, 0, 0.994); return NProgress.set(n); } }; NProgress.trickle = function() { return NProgress.inc(Math.random() * Settings.trickleRate); }; /** * Waits for all supplied jQuery promises and * increases the progress as the promises resolve. * * @param $promise jQUery Promise */ (function() { var initial = 0, current = 0; NProgress.promise = function($promise) { if (!$promise || $promise.state() === "resolved") { return this; } if (current === 0) { NProgress.start(); } initial++; current++; $promise.always(function() { current--; if (current === 0) { initial = 0; NProgress.done(); } else { NProgress.set((initial - current) / initial); } }); return this; }; })(); /** * (Internal) renders the progress bar markup based on the `template` * setting. */ NProgress.render = function(fromStart) { if (NProgress.isRendered()) return document.getElementById('nprogress'); addClass(document.documentElement, 'nprogress-busy'); var progress = document.createElement('div'); progress.id = 'nprogress'; progress.innerHTML = Settings.template; var bar = progress.querySelector(Settings.barSelector), perc = fromStart ? '-100' : toBarPerc(NProgress.status || 0), parent = document.querySelector(Settings.parent), spinner; css(bar, { transition: 'all 0 linear', transform: 'translate3d(' + perc + '%,0,0)' }); if (!Settings.showSpinner) { spinner = progress.querySelector(Settings.spinnerSelector); spinner && removeElement(spinner); } if (parent != document.body) { addClass(parent, 'nprogress-custom-parent'); } parent.appendChild(progress); return progress; }; /** * Removes the element. Opposite of render(). */ NProgress.remove = function() { removeClass(document.documentElement, 'nprogress-busy'); removeClass(document.querySelector(Settings.parent), 'nprogress-custom-parent'); var progress = document.getElementById('nprogress'); progress && removeElement(progress); }; /** * Checks if the progress bar is rendered. */ NProgress.isRendered = function() { return !!document.getElementById('nprogress'); }; /** * Determine which positioning CSS rule to use. */ NProgress.getPositioningCSS = function() { // Sniff on document.body.style var bodyStyle = document.body.style; // Sniff prefixes var vendorPrefix = ('WebkitTransform' in bodyStyle) ? 'Webkit' : ('MozTransform' in bodyStyle) ? 'Moz' : ('msTransform' in bodyStyle) ? 'ms' : ('OTransform' in bodyStyle) ? 'O' : ''; if (vendorPrefix + 'Perspective' in bodyStyle) { // Modern browsers with 3D support, e.g. Webkit, IE10 return 'translate3d'; } else if (vendorPrefix + 'Transform' in bodyStyle) { // Browsers without 3D support, e.g. IE9 return 'translate'; } else { // Browsers without translate() support, e.g. IE7-8 return 'margin'; } }; /** * Helpers */ function clamp(n, min, max) { if (n < min) return min; if (n > max) return max; return n; } /** * (Internal) converts a percentage (`0..1`) to a bar translateX * percentage (`-100%..0%`). */ function toBarPerc(n) { return (-1 + n) * 100; } /** * (Internal) returns the correct CSS for changing the bar's * position given an n percentage, and speed and ease from Settings */ function barPositionCSS(n, speed, ease) { var barCSS; if (Settings.positionUsing === 'translate3d') { barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' }; } else if (Settings.positionUsing === 'translate') { barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' }; } else { barCSS = { 'margin-left': toBarPerc(n)+'%' }; } barCSS.transition = 'all '+speed+'ms '+ease; return barCSS; } /** * (Internal) Queues a function to be executed. */ var queue = (function() { var pending = []; function next() { var fn = pending.shift(); if (fn) { fn(next); } } return function(fn) { pending.push(fn); if (pending.length == 1) next(); }; })(); /** * (Internal) Applies css properties to an element, similar to the jQuery * css method. * * While this helper does assist with vendor prefixed property names, it * does not perform any manipulation of values prior to setting styles. */ var css = (function() { var cssPrefixes = [ 'Webkit', 'O', 'Moz', 'ms' ], cssProps = {}; function camelCase(string) { return string.replace(/^-ms-/, 'ms-').replace(/-([\da-z])/gi, function(match, letter) { return letter.toUpperCase(); }); } function getVendorProp(name) { var style = document.body.style; if (name in style) return name; var i = cssPrefixes.length, capName = name.charAt(0).toUpperCase() + name.slice(1), vendorName; while (i--) { vendorName = cssPrefixes[i] + capName; if (vendorName in style) return vendorName; } return name; } function getStyleProp(name) { name = camelCase(name); return cssProps[name] || (cssProps[name] = getVendorProp(name)); } function applyCss(element, prop, value) { prop = getStyleProp(prop); element.style[prop] = value; } return function(element, properties) { var args = arguments, prop, value; if (args.length == 2) { for (prop in properties) { value = properties[prop]; if (value !== undefined && properties.hasOwnProperty(prop)) applyCss(element, prop, value); } } else { applyCss(element, args[1], args[2]); } } })(); /** * (Internal) Determines if an element or space separated list of class names contains a class name. */ function hasClass(element, name) { var list = typeof element == 'string' ? element : classList(element); return list.indexOf(' ' + name + ' ') >= 0; } /** * (Internal) Adds a class to an element. */ function addClass(element, name) { var oldList = classList(element), newList = oldList + name; if (hasClass(oldList, name)) return; // Trim the opening space. element.className = newList.substring(1); } /** * (Internal) Removes a class from an element. */ function removeClass(element, name) { var oldList = classList(element), newList; if (!hasClass(element, name)) return; // Replace the class name. newList = oldList.replace(' ' + name + ' ', ' '); // Trim the opening and closing spaces. element.className = newList.substring(1, newList.length - 1); } /** * (Internal) Gets a space separated list of the class names on the element. * The list is wrapped with a single space on each end to facilitate finding * matches within the list. */ function classList(element) { return (' ' + (element.className || '') + ' ').replace(/\s+/gi, ' '); } /** * (Internal) Removes an element from the DOM. */ function removeElement(element) { element && element.parentNode && element.parentNode.removeChild(element); } return NProgress; }); },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/index.js":[function(require,module,exports){ // Top level file is just a mixin of submodules & constants 'use strict'; var assign = require('./lib/utils/common').assign; var deflate = require('./lib/deflate'); var inflate = require('./lib/inflate'); var constants = require('./lib/zlib/constants'); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; },{"./lib/deflate":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/deflate.js","./lib/inflate":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/inflate.js","./lib/utils/common":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/utils/common.js","./lib/zlib/constants":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/constants.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/deflate.js":[function(require,module,exports){ 'use strict'; var zlib_deflate = require('./zlib/deflate'); var utils = require('./utils/common'); var strings = require('./utils/strings'); var msg = require('./zlib/messages'); var ZStream = require('./zlib/zstream'); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * - `dictionary` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ function Deflate(options) { if (!(this instanceof Deflate)) return new Deflate(options); this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } if (opt.dictionary) { var dict; // Convert data if needed if (typeof opt.dictionary === 'string') { // If we need to compress text, change encoding to utf8. dict = strings.string2buf(opt.dictionary); } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { dict = new Uint8Array(opt.dictionary); } else { dict = opt.dictionary; } status = zlib_deflate.deflateSetDictionary(this.strm, dict); if (status !== Z_OK) { throw new Error(msg[status]); } this._dict_set = true; } } /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function (status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate algorithm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * - dictionary * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg || msg[deflator.err]; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/utils/common.js","./utils/strings":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/utils/strings.js","./zlib/deflate":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/deflate.js","./zlib/messages":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/messages.js","./zlib/zstream":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/zstream.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/inflate.js":[function(require,module,exports){ 'use strict'; var zlib_inflate = require('./zlib/inflate'); var utils = require('./utils/common'); var strings = require('./utils/strings'); var c = require('./zlib/constants'); var msg = require('./zlib/messages'); var ZStream = require('./zlib/zstream'); var GZheader = require('./zlib/gzheader'); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * - `dictionary` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ function Inflate(options) { if (!(this instanceof Inflate)) return new Inflate(options); this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new GZheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); } /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var dictionary = this.options.dictionary; var status, _mode; var next_out_utf8, tail, utf8str; var dict; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_NEED_DICT && dictionary) { // Convert data if needed if (typeof dictionary === 'string') { dict = strings.string2buf(dictionary); } else if (toString.call(dictionary) === '[object ArrayBuffer]') { dict = new Uint8Array(dictionary); } else { dict = dictionary; } status = zlib_inflate.inflateSetDictionary(this.strm, dict); } if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function (status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg || msg[inflator.err]; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/utils/common.js","./utils/strings":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/utils/strings.js","./zlib/constants":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/constants.js","./zlib/gzheader":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/gzheader.js","./zlib/inflate":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/inflate.js","./zlib/messages":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/messages.js","./zlib/zstream":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/zstream.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/utils/common.js":[function(require,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (source.hasOwnProperty(p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs + len), dest_offs); return; } // Fallback to ordinary array for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function (chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i = 0, l = chunks.length; i < l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i = 0, l = chunks.length; i < l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function (chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/utils/strings.js":[function(require,module,exports){ // String encode/decode helpers 'use strict'; var utils = require('./common'); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safary // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var q = 0; q < 256; q++) { _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); } _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i = 0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for (var i = 0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function (buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function (str) { var buf = new utils.Buf8(str.length); for (var i = 0, len = buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len * 2); for (out = 0, i = 0; i < len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function (buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max - 1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; },{"./common":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/utils/common.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/adler32.js":[function(require,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It doesn't worth to make additional optimizationa as in original. // Small size is preferable. // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/constants.js":[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/crc32.js":[function(require,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n = 0; n < 256; n++) { c = n; for (var k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc ^= -1; for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/deflate.js":[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var utils = require('../utils/common'); var trees = require('./trees'); var adler32 = require('./adler32'); var crc32 = require('./crc32'); var msg = require('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only(s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; // zmemcpy(buf, strm->next_in, len); utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH - 1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH - 1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length - 1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH - 1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ function Config(good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; } var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); //s->pending_buf = (uchf *) overlay; s.pending_buf = new utils.Buf8(s.pending_buf_size); // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); s.d_buf = 1 * s.lit_bufsize; //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Initializes the compression dictionary from the given byte * sequence without producing any compressed output. */ function deflateSetDictionary(strm, dictionary) { var dictLength = dictionary.length; var s; var str, n; var wrap; var avail; var next; var input; var tmpDict; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } s = strm.state; wrap = s.wrap; if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { return Z_STREAM_ERROR; } /* when using zlib wrappers, compute Adler-32 for provided dictionary */ if (wrap === 1) { /* adler32(strm->adler, dictionary, dictLength); */ strm.adler = adler32(strm.adler, dictionary, dictLength, 0); } s.wrap = 0; /* avoid computing Adler-32 in read_buf */ /* if dictionary would fill window, just replace the history */ if (dictLength >= s.w_size) { if (wrap === 0) { /* already empty otherwise */ /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); s.strstart = 0; s.block_start = 0; s.insert = 0; } /* use the tail */ // dictionary = dictionary.slice(dictLength - s.w_size); tmpDict = new utils.Buf8(s.w_size); utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); dictionary = tmpDict; dictLength = s.w_size; } /* insert dictionary into window and hash */ avail = strm.avail_in; next = strm.next_in; input = strm.input; strm.avail_in = dictLength; strm.next_in = 0; strm.input = dictionary; fill_window(s); while (s.lookahead >= MIN_MATCH) { str = s.strstart; n = s.lookahead - (MIN_MATCH - 1); do { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; } while (--n); s.strstart = str; s.lookahead = MIN_MATCH - 1; fill_window(s); } s.strstart += s.lookahead; s.block_start = s.strstart; s.insert = s.lookahead; s.lookahead = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; strm.next_in = next; strm.input = input; strm.avail_in = avail; s.wrap = wrap; return Z_OK; } exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/utils/common.js","./adler32":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/adler32.js","./crc32":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/crc32.js","./messages":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/messages.js","./trees":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/trees.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/gzheader.js":[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/inffast.js":[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/inflate.js":[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var utils = require('../utils/common'); var adler32 = require('./adler32'); var crc32 = require('./crc32'); var inflate_fast = require('./inffast'); var inflate_table = require('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function zswap32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window, src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window, src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = zswap32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = { bits: state.lenbits }; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = { bits: state.lenbits }; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = { bits: state.distbits }; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too if ((state.flags ? hold : zswap32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } function inflateSetDictionary(strm, dictionary) { var dictLength = dictionary.length; var state; var dictid; var ret; /* check state */ if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } state = strm.state; if (state.wrap !== 0 && state.mode !== DICT) { return Z_STREAM_ERROR; } /* check for correct dictionary identifier */ if (state.mode === DICT) { dictid = 1; /* adler32(0, null, 0)*/ /* dictid = adler32(dictid, dictionary, dictLength); */ dictid = adler32(dictid, dictionary, dictLength, 0); if (dictid !== state.check) { return Z_DATA_ERROR; } } /* copy dictionary to window using updatewindow(), which will amend the existing dictionary if appropriate */ ret = updatewindow(strm, dictionary, dictLength, dictLength); if (ret) { state.mode = MEM; return Z_MEM_ERROR; } state.havedict = 1; // Tracev((stderr, "inflate: dictionary set\n")); return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/utils/common.js","./adler32":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/adler32.js","./crc32":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/crc32.js","./inffast":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/inffast.js","./inftrees":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/inftrees.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/inftrees.js":[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var utils = require('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; var lext = [ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ]; var dbase = [ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ]; var dext = [ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* process all codes and make table entries */ for (;;) { /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/utils/common.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/messages.js":[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. module.exports = { 2: 'need dictionary', /* Z_NEED_DICT 2 */ 1: 'stream end', /* Z_STREAM_END 1 */ 0: '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/trees.js":[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var utils = require('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ /* eslint-disable comma-spacing,array-bracket-spacing */ var extra_lbits = /* extra bits for each length code */ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; var extra_dbits = /* extra bits for each distance code */ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* eslint-enable comma-spacing,array-bracket-spacing */ /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES + 2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; } var static_l_desc; var static_d_desc; var static_bl_desc; function TreeDesc(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ } function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short(s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n - base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length - 1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m * 2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; tree[m * 2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits - 1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n * 2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES - 1; code++) { base_length[code] = length; for (n = 0; n < (1 << extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length - 1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1 << extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n * 2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n * 2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES + 1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n * 2 + 1]/*.Len*/ = 5; static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n * 2; var _m2 = m * 2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code + LITERALS + 1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node * 2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6 * 2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count - 3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count - 3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count - 11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes - 1, 5); send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES << 1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len + 3 + 7) >>> 3; static_lenb = (s.static_len + 3 + 7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc * 2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize - 1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/utils/common.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/lib/zlib/zstream.js":[function(require,module,exports){ 'use strict'; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/parserlib/lib/node-parserlib.js":[function(require,module,exports){ /*! Parser-Lib Copyright (c) 2009-2011 Nicholas C. Zakas. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Version v0.2.5, Build time: 7-May-2014 03:37:38 */ var parserlib = {}; (function(){ /** * A generic base to inherit from for any object * that needs event handling. * @class EventTarget * @constructor */ function EventTarget(){ /** * The array of listeners for various events. * @type Object * @property _listeners * @private */ this._listeners = {}; } EventTarget.prototype = { //restore constructor constructor: EventTarget, /** * Adds a listener for a given event type. * @param {String} type The type of event to add a listener for. * @param {Function} listener The function to call when the event occurs. * @return {void} * @method addListener */ addListener: function(type, listener){ if (!this._listeners[type]){ this._listeners[type] = []; } this._listeners[type].push(listener); }, /** * Fires an event based on the passed-in object. * @param {Object|String} event An object with at least a 'type' attribute * or a string indicating the event name. * @return {void} * @method fire */ fire: function(event){ if (typeof event == "string"){ event = { type: event }; } if (typeof event.target != "undefined"){ event.target = this; } if (typeof event.type == "undefined"){ throw new Error("Event object missing 'type' property."); } if (this._listeners[event.type]){ //create a copy of the array and use that so listeners can't chane var listeners = this._listeners[event.type].concat(); for (var i=0, len=listeners.length; i < len; i++){ listeners[i].call(this, event); } } }, /** * Removes a listener for a given event type. * @param {String} type The type of event to remove a listener from. * @param {Function} listener The function to remove from the event. * @return {void} * @method removeListener */ removeListener: function(type, listener){ if (this._listeners[type]){ var listeners = this._listeners[type]; for (var i=0, len=listeners.length; i < len; i++){ if (listeners[i] === listener){ listeners.splice(i, 1); break; } } } } }; /** * Convenient way to read through strings. * @namespace parserlib.util * @class StringReader * @constructor * @param {String} text The text to read. */ function StringReader(text){ /** * The input text with line endings normalized. * @property _input * @type String * @private */ this._input = text.replace(/\n\r?/g, "\n"); /** * The row for the character to be read next. * @property _line * @type int * @private */ this._line = 1; /** * The column for the character to be read next. * @property _col * @type int * @private */ this._col = 1; /** * The index of the character in the input to be read next. * @property _cursor * @type int * @private */ this._cursor = 0; } StringReader.prototype = { //restore constructor constructor: StringReader, //------------------------------------------------------------------------- // Position info //------------------------------------------------------------------------- /** * Returns the column of the character to be read next. * @return {int} The column of the character to be read next. * @method getCol */ getCol: function(){ return this._col; }, /** * Returns the row of the character to be read next. * @return {int} The row of the character to be read next. * @method getLine */ getLine: function(){ return this._line ; }, /** * Determines if you're at the end of the input. * @return {Boolean} True if there's no more input, false otherwise. * @method eof */ eof: function(){ return (this._cursor == this._input.length); }, //------------------------------------------------------------------------- // Basic reading //------------------------------------------------------------------------- /** * Reads the next character without advancing the cursor. * @param {int} count How many characters to look ahead (default is 1). * @return {String} The next character or null if there is no next character. * @method peek */ peek: function(count){ var c = null; count = (typeof count == "undefined" ? 1 : count); //if we're not at the end of the input... if (this._cursor < this._input.length){ //get character and increment cursor and column c = this._input.charAt(this._cursor + count - 1); } return c; }, /** * Reads the next character from the input and adjusts the row and column * accordingly. * @return {String} The next character or null if there is no next character. * @method read */ read: function(){ var c = null; //if we're not at the end of the input... if (this._cursor < this._input.length){ //if the last character was a newline, increment row count //and reset column count if (this._input.charAt(this._cursor) == "\n"){ this._line++; this._col=1; } else { this._col++; } //get character and increment cursor and column c = this._input.charAt(this._cursor++); } return c; }, //------------------------------------------------------------------------- // Misc //------------------------------------------------------------------------- /** * Saves the current location so it can be returned to later. * @method mark * @return {void} */ mark: function(){ this._bookmark = { cursor: this._cursor, line: this._line, col: this._col }; }, reset: function(){ if (this._bookmark){ this._cursor = this._bookmark.cursor; this._line = this._bookmark.line; this._col = this._bookmark.col; delete this._bookmark; } }, //------------------------------------------------------------------------- // Advanced reading //------------------------------------------------------------------------- /** * Reads up to and including the given string. Throws an error if that * string is not found. * @param {String} pattern The string to read. * @return {String} The string when it is found. * @throws Error when the string pattern is not found. * @method readTo */ readTo: function(pattern){ var buffer = "", c; /* * First, buffer must be the same length as the pattern. * Then, buffer must end with the pattern or else reach the * end of the input. */ while (buffer.length < pattern.length || buffer.lastIndexOf(pattern) != buffer.length - pattern.length){ c = this.read(); if (c){ buffer += c; } else { throw new Error("Expected \"" + pattern + "\" at line " + this._line + ", col " + this._col + "."); } } return buffer; }, /** * Reads characters while each character causes the given * filter function to return true. The function is passed * in each character and either returns true to continue * reading or false to stop. * @param {Function} filter The function to read on each character. * @return {String} The string made up of all characters that passed the * filter check. * @method readWhile */ readWhile: function(filter){ var buffer = "", c = this.read(); while(c !== null && filter(c)){ buffer += c; c = this.read(); } return buffer; }, /** * Reads characters that match either text or a regular expression and * returns those characters. If a match is found, the row and column * are adjusted; if no match is found, the reader's state is unchanged. * reading or false to stop. * @param {String|RegExp} matchter If a string, then the literal string * value is searched for. If a regular expression, then any string * matching the pattern is search for. * @return {String} The string made up of all characters that matched or * null if there was no match. * @method readMatch */ readMatch: function(matcher){ var source = this._input.substring(this._cursor), value = null; //if it's a string, just do a straight match if (typeof matcher == "string"){ if (source.indexOf(matcher) === 0){ value = this.readCount(matcher.length); } } else if (matcher instanceof RegExp){ if (matcher.test(source)){ value = this.readCount(RegExp.lastMatch.length); } } return value; }, /** * Reads a given number of characters. If the end of the input is reached, * it reads only the remaining characters and does not throw an error. * @param {int} count The number of characters to read. * @return {String} The string made up the read characters. * @method readCount */ readCount: function(count){ var buffer = ""; while(count--){ buffer += this.read(); } return buffer; } }; /** * Type to use when a syntax error occurs. * @class SyntaxError * @namespace parserlib.util * @constructor * @param {String} message The error message. * @param {int} line The line at which the error occurred. * @param {int} col The column at which the error occurred. */ function SyntaxError(message, line, col){ /** * The column at which the error occurred. * @type int * @property col */ this.col = col; /** * The line at which the error occurred. * @type int * @property line */ this.line = line; /** * The text representation of the unit. * @type String * @property text */ this.message = message; } //inherit from Error SyntaxError.prototype = new Error(); /** * Base type to represent a single syntactic unit. * @class SyntaxUnit * @namespace parserlib.util * @constructor * @param {String} text The text of the unit. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function SyntaxUnit(text, line, col, type){ /** * The column of text on which the unit resides. * @type int * @property col */ this.col = col; /** * The line of text on which the unit resides. * @type int * @property line */ this.line = line; /** * The text representation of the unit. * @type String * @property text */ this.text = text; /** * The type of syntax unit. * @type int * @property type */ this.type = type; } /** * Create a new syntax unit based solely on the given token. * Convenience method for creating a new syntax unit when * it represents a single token instead of multiple. * @param {Object} token The token object to represent. * @return {parserlib.util.SyntaxUnit} The object representing the token. * @static * @method fromToken */ SyntaxUnit.fromToken = function(token){ return new SyntaxUnit(token.value, token.startLine, token.startCol); }; SyntaxUnit.prototype = { //restore constructor constructor: SyntaxUnit, /** * Returns the text representation of the unit. * @return {String} The text representation of the unit. * @method valueOf */ valueOf: function(){ return this.toString(); }, /** * Returns the text representation of the unit. * @return {String} The text representation of the unit. * @method toString */ toString: function(){ return this.text; } }; /*global StringReader, SyntaxError*/ /** * Generic TokenStream providing base functionality. * @class TokenStreamBase * @namespace parserlib.util * @constructor * @param {String|StringReader} input The text to tokenize or a reader from * which to read the input. */ function TokenStreamBase(input, tokenData){ /** * The string reader for easy access to the text. * @type StringReader * @property _reader * @private */ this._reader = input ? new StringReader(input.toString()) : null; /** * Token object for the last consumed token. * @type Token * @property _token * @private */ this._token = null; /** * The array of token information. * @type Array * @property _tokenData * @private */ this._tokenData = tokenData; /** * Lookahead token buffer. * @type Array * @property _lt * @private */ this._lt = []; /** * Lookahead token buffer index. * @type int * @property _ltIndex * @private */ this._ltIndex = 0; this._ltIndexCache = []; } /** * Accepts an array of token information and outputs * an array of token data containing key-value mappings * and matching functions that the TokenStream needs. * @param {Array} tokens An array of token descriptors. * @return {Array} An array of processed token data. * @method createTokenData * @static */ TokenStreamBase.createTokenData = function(tokens){ var nameMap = [], typeMap = {}, tokenData = tokens.concat([]), i = 0, len = tokenData.length+1; tokenData.UNKNOWN = -1; tokenData.unshift({name:"EOF"}); for (; i < len; i++){ nameMap.push(tokenData[i].name); tokenData[tokenData[i].name] = i; if (tokenData[i].text){ typeMap[tokenData[i].text] = i; } } tokenData.name = function(tt){ return nameMap[tt]; }; tokenData.type = function(c){ return typeMap[c]; }; return tokenData; }; TokenStreamBase.prototype = { //restore constructor constructor: TokenStreamBase, //------------------------------------------------------------------------- // Matching methods //------------------------------------------------------------------------- /** * Determines if the next token matches the given token type. * If so, that token is consumed; if not, the token is placed * back onto the token stream. You can pass in any number of * token types and this will return true if any of the token * types is found. * @param {int|int[]} tokenTypes Either a single token type or an array of * token types that the next token might be. If an array is passed, * it's assumed that the token can be any of these. * @param {variant} channel (Optional) The channel to read from. If not * provided, reads from the default (unnamed) channel. * @return {Boolean} True if the token type matches, false if not. * @method match */ match: function(tokenTypes, channel){ //always convert to an array, makes things easier if (!(tokenTypes instanceof Array)){ tokenTypes = [tokenTypes]; } var tt = this.get(channel), i = 0, len = tokenTypes.length; while(i < len){ if (tt == tokenTypes[i++]){ return true; } } //no match found, put the token back this.unget(); return false; }, /** * Determines if the next token matches the given token type. * If so, that token is consumed; if not, an error is thrown. * @param {int|int[]} tokenTypes Either a single token type or an array of * token types that the next token should be. If an array is passed, * it's assumed that the token must be one of these. * @param {variant} channel (Optional) The channel to read from. If not * provided, reads from the default (unnamed) channel. * @return {void} * @method mustMatch */ mustMatch: function(tokenTypes, channel){ var token; //always convert to an array, makes things easier if (!(tokenTypes instanceof Array)){ tokenTypes = [tokenTypes]; } if (!this.match.apply(this, arguments)){ token = this.LT(1); throw new SyntaxError("Expected " + this._tokenData[tokenTypes[0]].name + " at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol); } }, //------------------------------------------------------------------------- // Consuming methods //------------------------------------------------------------------------- /** * Keeps reading from the token stream until either one of the specified * token types is found or until the end of the input is reached. * @param {int|int[]} tokenTypes Either a single token type or an array of * token types that the next token should be. If an array is passed, * it's assumed that the token must be one of these. * @param {variant} channel (Optional) The channel to read from. If not * provided, reads from the default (unnamed) channel. * @return {void} * @method advance */ advance: function(tokenTypes, channel){ while(this.LA(0) !== 0 && !this.match(tokenTypes, channel)){ this.get(); } return this.LA(0); }, /** * Consumes the next token from the token stream. * @return {int} The token type of the token that was just consumed. * @method get */ get: function(channel){ var tokenInfo = this._tokenData, reader = this._reader, value, i =0, len = tokenInfo.length, found = false, token, info; //check the lookahead buffer first if (this._lt.length && this._ltIndex >= 0 && this._ltIndex < this._lt.length){ i++; this._token = this._lt[this._ltIndex++]; info = tokenInfo[this._token.type]; //obey channels logic while((info.channel !== undefined && channel !== info.channel) && this._ltIndex < this._lt.length){ this._token = this._lt[this._ltIndex++]; info = tokenInfo[this._token.type]; i++; } //here be dragons if ((info.channel === undefined || channel === info.channel) && this._ltIndex <= this._lt.length){ this._ltIndexCache.push(i); return this._token.type; } } //call token retriever method token = this._getToken(); //if it should be hidden, don't save a token if (token.type > -1 && !tokenInfo[token.type].hide){ //apply token channel token.channel = tokenInfo[token.type].channel; //save for later this._token = token; this._lt.push(token); //save space that will be moved (must be done before array is truncated) this._ltIndexCache.push(this._lt.length - this._ltIndex + i); //keep the buffer under 5 items if (this._lt.length > 5){ this._lt.shift(); } //also keep the shift buffer under 5 items if (this._ltIndexCache.length > 5){ this._ltIndexCache.shift(); } //update lookahead index this._ltIndex = this._lt.length; } /* * Skip to the next token if: * 1. The token type is marked as hidden. * 2. The token type has a channel specified and it isn't the current channel. */ info = tokenInfo[token.type]; if (info && (info.hide || (info.channel !== undefined && channel !== info.channel))){ return this.get(channel); } else { //return just the type return token.type; } }, /** * Looks ahead a certain number of tokens and returns the token type at * that position. This will throw an error if you lookahead past the * end of input, past the size of the lookahead buffer, or back past * the first token in the lookahead buffer. * @param {int} The index of the token type to retrieve. 0 for the * current token, 1 for the next, -1 for the previous, etc. * @return {int} The token type of the token in the given position. * @method LA */ LA: function(index){ var total = index, tt; if (index > 0){ //TODO: Store 5 somewhere if (index > 5){ throw new Error("Too much lookahead."); } //get all those tokens while(total){ tt = this.get(); total--; } //unget all those tokens while(total < index){ this.unget(); total++; } } else if (index < 0){ if(this._lt[this._ltIndex+index]){ tt = this._lt[this._ltIndex+index].type; } else { throw new Error("Too much lookbehind."); } } else { tt = this._token.type; } return tt; }, /** * Looks ahead a certain number of tokens and returns the token at * that position. This will throw an error if you lookahead past the * end of input, past the size of the lookahead buffer, or back past * the first token in the lookahead buffer. * @param {int} The index of the token type to retrieve. 0 for the * current token, 1 for the next, -1 for the previous, etc. * @return {Object} The token of the token in the given position. * @method LA */ LT: function(index){ //lookahead first to prime the token buffer this.LA(index); //now find the token, subtract one because _ltIndex is already at the next index return this._lt[this._ltIndex+index-1]; }, /** * Returns the token type for the next token in the stream without * consuming it. * @return {int} The token type of the next token in the stream. * @method peek */ peek: function(){ return this.LA(1); }, /** * Returns the actual token object for the last consumed token. * @return {Token} The token object for the last consumed token. * @method token */ token: function(){ return this._token; }, /** * Returns the name of the token for the given token type. * @param {int} tokenType The type of token to get the name of. * @return {String} The name of the token or "UNKNOWN_TOKEN" for any * invalid token type. * @method tokenName */ tokenName: function(tokenType){ if (tokenType < 0 || tokenType > this._tokenData.length){ return "UNKNOWN_TOKEN"; } else { return this._tokenData[tokenType].name; } }, /** * Returns the token type value for the given token name. * @param {String} tokenName The name of the token whose value should be returned. * @return {int} The token type value for the given token name or -1 * for an unknown token. * @method tokenName */ tokenType: function(tokenName){ return this._tokenData[tokenName] || -1; }, /** * Returns the last consumed token to the token stream. * @method unget */ unget: function(){ //if (this._ltIndex > -1){ if (this._ltIndexCache.length){ this._ltIndex -= this._ltIndexCache.pop();//--; this._token = this._lt[this._ltIndex - 1]; } else { throw new Error("Too much lookahead."); } } }; parserlib.util = { StringReader: StringReader, SyntaxError : SyntaxError, SyntaxUnit : SyntaxUnit, EventTarget : EventTarget, TokenStreamBase : TokenStreamBase }; })(); /* Parser-Lib Copyright (c) 2009-2011 Nicholas C. Zakas. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Version v0.2.5, Build time: 7-May-2014 03:37:38 */ (function(){ var EventTarget = parserlib.util.EventTarget, TokenStreamBase = parserlib.util.TokenStreamBase, StringReader = parserlib.util.StringReader, SyntaxError = parserlib.util.SyntaxError, SyntaxUnit = parserlib.util.SyntaxUnit; var Colors = { aliceblue :"#f0f8ff", antiquewhite :"#faebd7", aqua :"#00ffff", aquamarine :"#7fffd4", azure :"#f0ffff", beige :"#f5f5dc", bisque :"#ffe4c4", black :"#000000", blanchedalmond :"#ffebcd", blue :"#0000ff", blueviolet :"#8a2be2", brown :"#a52a2a", burlywood :"#deb887", cadetblue :"#5f9ea0", chartreuse :"#7fff00", chocolate :"#d2691e", coral :"#ff7f50", cornflowerblue :"#6495ed", cornsilk :"#fff8dc", crimson :"#dc143c", cyan :"#00ffff", darkblue :"#00008b", darkcyan :"#008b8b", darkgoldenrod :"#b8860b", darkgray :"#a9a9a9", darkgrey :"#a9a9a9", darkgreen :"#006400", darkkhaki :"#bdb76b", darkmagenta :"#8b008b", darkolivegreen :"#556b2f", darkorange :"#ff8c00", darkorchid :"#9932cc", darkred :"#8b0000", darksalmon :"#e9967a", darkseagreen :"#8fbc8f", darkslateblue :"#483d8b", darkslategray :"#2f4f4f", darkslategrey :"#2f4f4f", darkturquoise :"#00ced1", darkviolet :"#9400d3", deeppink :"#ff1493", deepskyblue :"#00bfff", dimgray :"#696969", dimgrey :"#696969", dodgerblue :"#1e90ff", firebrick :"#b22222", floralwhite :"#fffaf0", forestgreen :"#228b22", fuchsia :"#ff00ff", gainsboro :"#dcdcdc", ghostwhite :"#f8f8ff", gold :"#ffd700", goldenrod :"#daa520", gray :"#808080", grey :"#808080", green :"#008000", greenyellow :"#adff2f", honeydew :"#f0fff0", hotpink :"#ff69b4", indianred :"#cd5c5c", indigo :"#4b0082", ivory :"#fffff0", khaki :"#f0e68c", lavender :"#e6e6fa", lavenderblush :"#fff0f5", lawngreen :"#7cfc00", lemonchiffon :"#fffacd", lightblue :"#add8e6", lightcoral :"#f08080", lightcyan :"#e0ffff", lightgoldenrodyellow :"#fafad2", lightgray :"#d3d3d3", lightgrey :"#d3d3d3", lightgreen :"#90ee90", lightpink :"#ffb6c1", lightsalmon :"#ffa07a", lightseagreen :"#20b2aa", lightskyblue :"#87cefa", lightslategray :"#778899", lightslategrey :"#778899", lightsteelblue :"#b0c4de", lightyellow :"#ffffe0", lime :"#00ff00", limegreen :"#32cd32", linen :"#faf0e6", magenta :"#ff00ff", maroon :"#800000", mediumaquamarine:"#66cdaa", mediumblue :"#0000cd", mediumorchid :"#ba55d3", mediumpurple :"#9370d8", mediumseagreen :"#3cb371", mediumslateblue :"#7b68ee", mediumspringgreen :"#00fa9a", mediumturquoise :"#48d1cc", mediumvioletred :"#c71585", midnightblue :"#191970", mintcream :"#f5fffa", mistyrose :"#ffe4e1", moccasin :"#ffe4b5", navajowhite :"#ffdead", navy :"#000080", oldlace :"#fdf5e6", olive :"#808000", olivedrab :"#6b8e23", orange :"#ffa500", orangered :"#ff4500", orchid :"#da70d6", palegoldenrod :"#eee8aa", palegreen :"#98fb98", paleturquoise :"#afeeee", palevioletred :"#d87093", papayawhip :"#ffefd5", peachpuff :"#ffdab9", peru :"#cd853f", pink :"#ffc0cb", plum :"#dda0dd", powderblue :"#b0e0e6", purple :"#800080", red :"#ff0000", rosybrown :"#bc8f8f", royalblue :"#4169e1", saddlebrown :"#8b4513", salmon :"#fa8072", sandybrown :"#f4a460", seagreen :"#2e8b57", seashell :"#fff5ee", sienna :"#a0522d", silver :"#c0c0c0", skyblue :"#87ceeb", slateblue :"#6a5acd", slategray :"#708090", slategrey :"#708090", snow :"#fffafa", springgreen :"#00ff7f", steelblue :"#4682b4", tan :"#d2b48c", teal :"#008080", thistle :"#d8bfd8", tomato :"#ff6347", turquoise :"#40e0d0", violet :"#ee82ee", wheat :"#f5deb3", white :"#ffffff", whitesmoke :"#f5f5f5", yellow :"#ffff00", yellowgreen :"#9acd32", //CSS2 system colors http://www.w3.org/TR/css3-color/#css2-system activeBorder :"Active window border.", activecaption :"Active window caption.", appworkspace :"Background color of multiple document interface.", background :"Desktop background.", buttonface :"The face background color for 3-D elements that appear 3-D due to one layer of surrounding border.", buttonhighlight :"The color of the border facing the light source for 3-D elements that appear 3-D due to one layer of surrounding border.", buttonshadow :"The color of the border away from the light source for 3-D elements that appear 3-D due to one layer of surrounding border.", buttontext :"Text on push buttons.", captiontext :"Text in caption, size box, and scrollbar arrow box.", graytext :"Grayed (disabled) text. This color is set to #000 if the current display driver does not support a solid gray color.", greytext :"Greyed (disabled) text. This color is set to #000 if the current display driver does not support a solid grey color.", highlight :"Item(s) selected in a control.", highlighttext :"Text of item(s) selected in a control.", inactiveborder :"Inactive window border.", inactivecaption :"Inactive window caption.", inactivecaptiontext :"Color of text in an inactive caption.", infobackground :"Background color for tooltip controls.", infotext :"Text color for tooltip controls.", menu :"Menu background.", menutext :"Text in menus.", scrollbar :"Scroll bar gray area.", threeddarkshadow :"The color of the darker (generally outer) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.", threedface :"The face background color for 3-D elements that appear 3-D due to two concentric layers of surrounding border.", threedhighlight :"The color of the lighter (generally outer) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.", threedlightshadow :"The color of the darker (generally inner) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.", threedshadow :"The color of the lighter (generally inner) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.", window :"Window background.", windowframe :"Window frame.", windowtext :"Text in windows." }; /*global SyntaxUnit, Parser*/ /** * Represents a selector combinator (whitespace, +, >). * @namespace parserlib.css * @class Combinator * @extends parserlib.util.SyntaxUnit * @constructor * @param {String} text The text representation of the unit. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function Combinator(text, line, col){ SyntaxUnit.call(this, text, line, col, Parser.COMBINATOR_TYPE); /** * The type of modifier. * @type String * @property type */ this.type = "unknown"; //pretty simple if (/^\s+$/.test(text)){ this.type = "descendant"; } else if (text == ">"){ this.type = "child"; } else if (text == "+"){ this.type = "adjacent-sibling"; } else if (text == "~"){ this.type = "sibling"; } } Combinator.prototype = new SyntaxUnit(); Combinator.prototype.constructor = Combinator; /*global SyntaxUnit, Parser*/ /** * Represents a media feature, such as max-width:500. * @namespace parserlib.css * @class MediaFeature * @extends parserlib.util.SyntaxUnit * @constructor * @param {SyntaxUnit} name The name of the feature. * @param {SyntaxUnit} value The value of the feature or null if none. */ function MediaFeature(name, value){ SyntaxUnit.call(this, "(" + name + (value !== null ? ":" + value : "") + ")", name.startLine, name.startCol, Parser.MEDIA_FEATURE_TYPE); /** * The name of the media feature * @type String * @property name */ this.name = name; /** * The value for the feature or null if there is none. * @type SyntaxUnit * @property value */ this.value = value; } MediaFeature.prototype = new SyntaxUnit(); MediaFeature.prototype.constructor = MediaFeature; /*global SyntaxUnit, Parser*/ /** * Represents an individual media query. * @namespace parserlib.css * @class MediaQuery * @extends parserlib.util.SyntaxUnit * @constructor * @param {String} modifier The modifier "not" or "only" (or null). * @param {String} mediaType The type of media (i.e., "print"). * @param {Array} parts Array of selectors parts making up this selector. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function MediaQuery(modifier, mediaType, features, line, col){ SyntaxUnit.call(this, (modifier ? modifier + " ": "") + (mediaType ? mediaType : "") + (mediaType && features.length > 0 ? " and " : "") + features.join(" and "), line, col, Parser.MEDIA_QUERY_TYPE); /** * The media modifier ("not" or "only") * @type String * @property modifier */ this.modifier = modifier; /** * The mediaType (i.e., "print") * @type String * @property mediaType */ this.mediaType = mediaType; /** * The parts that make up the selector. * @type Array * @property features */ this.features = features; } MediaQuery.prototype = new SyntaxUnit(); MediaQuery.prototype.constructor = MediaQuery; /*global Tokens, TokenStream, SyntaxError, Properties, Validation, ValidationError, SyntaxUnit, PropertyValue, PropertyValuePart, SelectorPart, SelectorSubPart, Selector, PropertyName, Combinator, MediaFeature, MediaQuery, EventTarget */ /** * A CSS3 parser. * @namespace parserlib.css * @class Parser * @constructor * @param {Object} options (Optional) Various options for the parser: * starHack (true|false) to allow IE6 star hack as valid, * underscoreHack (true|false) to interpret leading underscores * as IE6-7 targeting for known properties, ieFilters (true|false) * to indicate that IE < 8 filters should be accepted and not throw * syntax errors. */ function Parser(options){ //inherit event functionality EventTarget.call(this); this.options = options || {}; this._tokenStream = null; } //Static constants Parser.DEFAULT_TYPE = 0; Parser.COMBINATOR_TYPE = 1; Parser.MEDIA_FEATURE_TYPE = 2; Parser.MEDIA_QUERY_TYPE = 3; Parser.PROPERTY_NAME_TYPE = 4; Parser.PROPERTY_VALUE_TYPE = 5; Parser.PROPERTY_VALUE_PART_TYPE = 6; Parser.SELECTOR_TYPE = 7; Parser.SELECTOR_PART_TYPE = 8; Parser.SELECTOR_SUB_PART_TYPE = 9; Parser.prototype = function(){ var proto = new EventTarget(), //new prototype prop, additions = { //restore constructor constructor: Parser, //instance constants - yuck DEFAULT_TYPE : 0, COMBINATOR_TYPE : 1, MEDIA_FEATURE_TYPE : 2, MEDIA_QUERY_TYPE : 3, PROPERTY_NAME_TYPE : 4, PROPERTY_VALUE_TYPE : 5, PROPERTY_VALUE_PART_TYPE : 6, SELECTOR_TYPE : 7, SELECTOR_PART_TYPE : 8, SELECTOR_SUB_PART_TYPE : 9, //----------------------------------------------------------------- // Grammar //----------------------------------------------------------------- _stylesheet: function(){ /* * stylesheet * : [ CHARSET_SYM S* STRING S* ';' ]? * [S|CDO|CDC]* [ import [S|CDO|CDC]* ]* * [ namespace [S|CDO|CDC]* ]* * [ [ ruleset | media | page | font_face | keyframes ] [S|CDO|CDC]* ]* * ; */ var tokenStream = this._tokenStream, charset = null, count, token, tt; this.fire("startstylesheet"); //try to read character set this._charset(); this._skipCruft(); //try to read imports - may be more than one while (tokenStream.peek() == Tokens.IMPORT_SYM){ this._import(); this._skipCruft(); } //try to read namespaces - may be more than one while (tokenStream.peek() == Tokens.NAMESPACE_SYM){ this._namespace(); this._skipCruft(); } //get the next token tt = tokenStream.peek(); //try to read the rest while(tt > Tokens.EOF){ try { switch(tt){ case Tokens.MEDIA_SYM: this._media(); this._skipCruft(); break; case Tokens.PAGE_SYM: this._page(); this._skipCruft(); break; case Tokens.FONT_FACE_SYM: this._font_face(); this._skipCruft(); break; case Tokens.KEYFRAMES_SYM: this._keyframes(); this._skipCruft(); break; case Tokens.VIEWPORT_SYM: this._viewport(); this._skipCruft(); break; case Tokens.UNKNOWN_SYM: //unknown @ rule tokenStream.get(); if (!this.options.strict){ //fire error event this.fire({ type: "error", error: null, message: "Unknown @ rule: " + tokenStream.LT(0).value + ".", line: tokenStream.LT(0).startLine, col: tokenStream.LT(0).startCol }); //skip braces count=0; while (tokenStream.advance([Tokens.LBRACE, Tokens.RBRACE]) == Tokens.LBRACE){ count++; //keep track of nesting depth } while(count){ tokenStream.advance([Tokens.RBRACE]); count--; } } else { //not a syntax error, rethrow it throw new SyntaxError("Unknown @ rule.", tokenStream.LT(0).startLine, tokenStream.LT(0).startCol); } break; case Tokens.S: this._readWhitespace(); break; default: if(!this._ruleset()){ //error handling for known issues switch(tt){ case Tokens.CHARSET_SYM: token = tokenStream.LT(1); this._charset(false); throw new SyntaxError("@charset not allowed here.", token.startLine, token.startCol); case Tokens.IMPORT_SYM: token = tokenStream.LT(1); this._import(false); throw new SyntaxError("@import not allowed here.", token.startLine, token.startCol); case Tokens.NAMESPACE_SYM: token = tokenStream.LT(1); this._namespace(false); throw new SyntaxError("@namespace not allowed here.", token.startLine, token.startCol); default: tokenStream.get(); //get the last token this._unexpectedToken(tokenStream.token()); } } } } catch(ex) { if (ex instanceof SyntaxError && !this.options.strict){ this.fire({ type: "error", error: ex, message: ex.message, line: ex.line, col: ex.col }); } else { throw ex; } } tt = tokenStream.peek(); } if (tt != Tokens.EOF){ this._unexpectedToken(tokenStream.token()); } this.fire("endstylesheet"); }, _charset: function(emit){ var tokenStream = this._tokenStream, charset, token, line, col; if (tokenStream.match(Tokens.CHARSET_SYM)){ line = tokenStream.token().startLine; col = tokenStream.token().startCol; this._readWhitespace(); tokenStream.mustMatch(Tokens.STRING); token = tokenStream.token(); charset = token.value; this._readWhitespace(); tokenStream.mustMatch(Tokens.SEMICOLON); if (emit !== false){ this.fire({ type: "charset", charset:charset, line: line, col: col }); } } }, _import: function(emit){ /* * import * : IMPORT_SYM S* * [STRING|URI] S* media_query_list? ';' S* */ var tokenStream = this._tokenStream, tt, uri, importToken, mediaList = []; //read import symbol tokenStream.mustMatch(Tokens.IMPORT_SYM); importToken = tokenStream.token(); this._readWhitespace(); tokenStream.mustMatch([Tokens.STRING, Tokens.URI]); //grab the URI value uri = tokenStream.token().value.replace(/^(?:url\()?["']?([^"']+?)["']?\)?$/, "$1"); this._readWhitespace(); mediaList = this._media_query_list(); //must end with a semicolon tokenStream.mustMatch(Tokens.SEMICOLON); this._readWhitespace(); if (emit !== false){ this.fire({ type: "import", uri: uri, media: mediaList, line: importToken.startLine, col: importToken.startCol }); } }, _namespace: function(emit){ /* * namespace * : NAMESPACE_SYM S* [namespace_prefix S*]? [STRING|URI] S* ';' S* */ var tokenStream = this._tokenStream, line, col, prefix, uri; //read import symbol tokenStream.mustMatch(Tokens.NAMESPACE_SYM); line = tokenStream.token().startLine; col = tokenStream.token().startCol; this._readWhitespace(); //it's a namespace prefix - no _namespace_prefix() method because it's just an IDENT if (tokenStream.match(Tokens.IDENT)){ prefix = tokenStream.token().value; this._readWhitespace(); } tokenStream.mustMatch([Tokens.STRING, Tokens.URI]); /*if (!tokenStream.match(Tokens.STRING)){ tokenStream.mustMatch(Tokens.URI); }*/ //grab the URI value uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1"); this._readWhitespace(); //must end with a semicolon tokenStream.mustMatch(Tokens.SEMICOLON); this._readWhitespace(); if (emit !== false){ this.fire({ type: "namespace", prefix: prefix, uri: uri, line: line, col: col }); } }, _media: function(){ /* * media * : MEDIA_SYM S* media_query_list S* '{' S* ruleset* '}' S* * ; */ var tokenStream = this._tokenStream, line, col, mediaList;// = []; //look for @media tokenStream.mustMatch(Tokens.MEDIA_SYM); line = tokenStream.token().startLine; col = tokenStream.token().startCol; this._readWhitespace(); mediaList = this._media_query_list(); tokenStream.mustMatch(Tokens.LBRACE); this._readWhitespace(); this.fire({ type: "startmedia", media: mediaList, line: line, col: col }); while(true) { if (tokenStream.peek() == Tokens.PAGE_SYM){ this._page(); } else if (tokenStream.peek() == Tokens.FONT_FACE_SYM){ this._font_face(); } else if (tokenStream.peek() == Tokens.VIEWPORT_SYM){ this._viewport(); } else if (!this._ruleset()){ break; } } tokenStream.mustMatch(Tokens.RBRACE); this._readWhitespace(); this.fire({ type: "endmedia", media: mediaList, line: line, col: col }); }, //CSS3 Media Queries _media_query_list: function(){ /* * media_query_list * : S* [media_query [ ',' S* media_query ]* ]? * ; */ var tokenStream = this._tokenStream, mediaList = []; this._readWhitespace(); if (tokenStream.peek() == Tokens.IDENT || tokenStream.peek() == Tokens.LPAREN){ mediaList.push(this._media_query()); } while(tokenStream.match(Tokens.COMMA)){ this._readWhitespace(); mediaList.push(this._media_query()); } return mediaList; }, /* * Note: "expression" in the grammar maps to the _media_expression * method. */ _media_query: function(){ /* * media_query * : [ONLY | NOT]? S* media_type S* [ AND S* expression ]* * | expression [ AND S* expression ]* * ; */ var tokenStream = this._tokenStream, type = null, ident = null, token = null, expressions = []; if (tokenStream.match(Tokens.IDENT)){ ident = tokenStream.token().value.toLowerCase(); //since there's no custom tokens for these, need to manually check if (ident != "only" && ident != "not"){ tokenStream.unget(); ident = null; } else { token = tokenStream.token(); } } this._readWhitespace(); if (tokenStream.peek() == Tokens.IDENT){ type = this._media_type(); if (token === null){ token = tokenStream.token(); } } else if (tokenStream.peek() == Tokens.LPAREN){ if (token === null){ token = tokenStream.LT(1); } expressions.push(this._media_expression()); } if (type === null && expressions.length === 0){ return null; } else { this._readWhitespace(); while (tokenStream.match(Tokens.IDENT)){ if (tokenStream.token().value.toLowerCase() != "and"){ this._unexpectedToken(tokenStream.token()); } this._readWhitespace(); expressions.push(this._media_expression()); } } return new MediaQuery(ident, type, expressions, token.startLine, token.startCol); }, //CSS3 Media Queries _media_type: function(){ /* * media_type * : IDENT * ; */ return this._media_feature(); }, /** * Note: in CSS3 Media Queries, this is called "expression". * Renamed here to avoid conflict with CSS3 Selectors * definition of "expression". Also note that "expr" in the * grammar now maps to "expression" from CSS3 selectors. * @method _media_expression * @private */ _media_expression: function(){ /* * expression * : '(' S* media_feature S* [ ':' S* expr ]? ')' S* * ; */ var tokenStream = this._tokenStream, feature = null, token, expression = null; tokenStream.mustMatch(Tokens.LPAREN); feature = this._media_feature(); this._readWhitespace(); if (tokenStream.match(Tokens.COLON)){ this._readWhitespace(); token = tokenStream.LT(1); expression = this._expression(); } tokenStream.mustMatch(Tokens.RPAREN); this._readWhitespace(); return new MediaFeature(feature, (expression ? new SyntaxUnit(expression, token.startLine, token.startCol) : null)); }, //CSS3 Media Queries _media_feature: function(){ /* * media_feature * : IDENT * ; */ var tokenStream = this._tokenStream; tokenStream.mustMatch(Tokens.IDENT); return SyntaxUnit.fromToken(tokenStream.token()); }, //CSS3 Paged Media _page: function(){ /* * page: * PAGE_SYM S* IDENT? pseudo_page? S* * '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S* * ; */ var tokenStream = this._tokenStream, line, col, identifier = null, pseudoPage = null; //look for @page tokenStream.mustMatch(Tokens.PAGE_SYM); line = tokenStream.token().startLine; col = tokenStream.token().startCol; this._readWhitespace(); if (tokenStream.match(Tokens.IDENT)){ identifier = tokenStream.token().value; //The value 'auto' may not be used as a page name and MUST be treated as a syntax error. if (identifier.toLowerCase() === "auto"){ this._unexpectedToken(tokenStream.token()); } } //see if there's a colon upcoming if (tokenStream.peek() == Tokens.COLON){ pseudoPage = this._pseudo_page(); } this._readWhitespace(); this.fire({ type: "startpage", id: identifier, pseudo: pseudoPage, line: line, col: col }); this._readDeclarations(true, true); this.fire({ type: "endpage", id: identifier, pseudo: pseudoPage, line: line, col: col }); }, //CSS3 Paged Media _margin: function(){ /* * margin : * margin_sym S* '{' declaration [ ';' S* declaration? ]* '}' S* * ; */ var tokenStream = this._tokenStream, line, col, marginSym = this._margin_sym(); if (marginSym){ line = tokenStream.token().startLine; col = tokenStream.token().startCol; this.fire({ type: "startpagemargin", margin: marginSym, line: line, col: col }); this._readDeclarations(true); this.fire({ type: "endpagemargin", margin: marginSym, line: line, col: col }); return true; } else { return false; } }, //CSS3 Paged Media _margin_sym: function(){ /* * margin_sym : * TOPLEFTCORNER_SYM | * TOPLEFT_SYM | * TOPCENTER_SYM | * TOPRIGHT_SYM | * TOPRIGHTCORNER_SYM | * BOTTOMLEFTCORNER_SYM | * BOTTOMLEFT_SYM | * BOTTOMCENTER_SYM | * BOTTOMRIGHT_SYM | * BOTTOMRIGHTCORNER_SYM | * LEFTTOP_SYM | * LEFTMIDDLE_SYM | * LEFTBOTTOM_SYM | * RIGHTTOP_SYM | * RIGHTMIDDLE_SYM | * RIGHTBOTTOM_SYM * ; */ var tokenStream = this._tokenStream; if(tokenStream.match([Tokens.TOPLEFTCORNER_SYM, Tokens.TOPLEFT_SYM, Tokens.TOPCENTER_SYM, Tokens.TOPRIGHT_SYM, Tokens.TOPRIGHTCORNER_SYM, Tokens.BOTTOMLEFTCORNER_SYM, Tokens.BOTTOMLEFT_SYM, Tokens.BOTTOMCENTER_SYM, Tokens.BOTTOMRIGHT_SYM, Tokens.BOTTOMRIGHTCORNER_SYM, Tokens.LEFTTOP_SYM, Tokens.LEFTMIDDLE_SYM, Tokens.LEFTBOTTOM_SYM, Tokens.RIGHTTOP_SYM, Tokens.RIGHTMIDDLE_SYM, Tokens.RIGHTBOTTOM_SYM])) { return SyntaxUnit.fromToken(tokenStream.token()); } else { return null; } }, _pseudo_page: function(){ /* * pseudo_page * : ':' IDENT * ; */ var tokenStream = this._tokenStream; tokenStream.mustMatch(Tokens.COLON); tokenStream.mustMatch(Tokens.IDENT); //TODO: CSS3 Paged Media says only "left", "center", and "right" are allowed return tokenStream.token().value; }, _font_face: function(){ /* * font_face * : FONT_FACE_SYM S* * '{' S* declaration [ ';' S* declaration ]* '}' S* * ; */ var tokenStream = this._tokenStream, line, col; //look for @page tokenStream.mustMatch(Tokens.FONT_FACE_SYM); line = tokenStream.token().startLine; col = tokenStream.token().startCol; this._readWhitespace(); this.fire({ type: "startfontface", line: line, col: col }); this._readDeclarations(true); this.fire({ type: "endfontface", line: line, col: col }); }, _viewport: function(){ /* * viewport * : VIEWPORT_SYM S* * '{' S* declaration? [ ';' S* declaration? ]* '}' S* * ; */ var tokenStream = this._tokenStream, line, col; tokenStream.mustMatch(Tokens.VIEWPORT_SYM); line = tokenStream.token().startLine; col = tokenStream.token().startCol; this._readWhitespace(); this.fire({ type: "startviewport", line: line, col: col }); this._readDeclarations(true); this.fire({ type: "endviewport", line: line, col: col }); }, _operator: function(inFunction){ /* * operator (outside function) * : '/' S* | ',' S* | /( empty )/ * operator (inside function) * : '/' S* | '+' S* | '*' S* | '-' S* /( empty )/ * ; */ var tokenStream = this._tokenStream, token = null; if (tokenStream.match([Tokens.SLASH, Tokens.COMMA]) || (inFunction && tokenStream.match([Tokens.PLUS, Tokens.STAR, Tokens.MINUS]))){ token = tokenStream.token(); this._readWhitespace(); } return token ? PropertyValuePart.fromToken(token) : null; }, _combinator: function(){ /* * combinator * : PLUS S* | GREATER S* | TILDE S* | S+ * ; */ var tokenStream = this._tokenStream, value = null, token; if(tokenStream.match([Tokens.PLUS, Tokens.GREATER, Tokens.TILDE])){ token = tokenStream.token(); value = new Combinator(token.value, token.startLine, token.startCol); this._readWhitespace(); } return value; }, _unary_operator: function(){ /* * unary_operator * : '-' | '+' * ; */ var tokenStream = this._tokenStream; if (tokenStream.match([Tokens.MINUS, Tokens.PLUS])){ return tokenStream.token().value; } else { return null; } }, _property: function(){ /* * property * : IDENT S* * ; */ var tokenStream = this._tokenStream, value = null, hack = null, tokenValue, token, line, col; //check for star hack - throws error if not allowed if (tokenStream.peek() == Tokens.STAR && this.options.starHack){ tokenStream.get(); token = tokenStream.token(); hack = token.value; line = token.startLine; col = token.startCol; } if(tokenStream.match(Tokens.IDENT)){ token = tokenStream.token(); tokenValue = token.value; //check for underscore hack - no error if not allowed because it's valid CSS syntax if (tokenValue.charAt(0) == "_" && this.options.underscoreHack){ hack = "_"; tokenValue = tokenValue.substring(1); } value = new PropertyName(tokenValue, hack, (line||token.startLine), (col||token.startCol)); this._readWhitespace(); } return value; }, //Augmented with CSS3 Selectors _ruleset: function(){ /* * ruleset * : selectors_group * '{' S* declaration? [ ';' S* declaration? ]* '}' S* * ; */ var tokenStream = this._tokenStream, tt, selectors; /* * Error Recovery: If even a single selector fails to parse, * then the entire ruleset should be thrown away. */ try { selectors = this._selectors_group(); } catch (ex){ if (ex instanceof SyntaxError && !this.options.strict){ //fire error event this.fire({ type: "error", error: ex, message: ex.message, line: ex.line, col: ex.col }); //skip over everything until closing brace tt = tokenStream.advance([Tokens.RBRACE]); if (tt == Tokens.RBRACE){ //if there's a right brace, the rule is finished so don't do anything } else { //otherwise, rethrow the error because it wasn't handled properly throw ex; } } else { //not a syntax error, rethrow it throw ex; } //trigger parser to continue return true; } //if it got here, all selectors parsed if (selectors){ this.fire({ type: "startrule", selectors: selectors, line: selectors[0].line, col: selectors[0].col }); this._readDeclarations(true); this.fire({ type: "endrule", selectors: selectors, line: selectors[0].line, col: selectors[0].col }); } return selectors; }, //CSS3 Selectors _selectors_group: function(){ /* * selectors_group * : selector [ COMMA S* selector ]* * ; */ var tokenStream = this._tokenStream, selectors = [], selector; selector = this._selector(); if (selector !== null){ selectors.push(selector); while(tokenStream.match(Tokens.COMMA)){ this._readWhitespace(); selector = this._selector(); if (selector !== null){ selectors.push(selector); } else { this._unexpectedToken(tokenStream.LT(1)); } } } return selectors.length ? selectors : null; }, //CSS3 Selectors _selector: function(){ /* * selector * : simple_selector_sequence [ combinator simple_selector_sequence ]* * ; */ var tokenStream = this._tokenStream, selector = [], nextSelector = null, combinator = null, ws = null; //if there's no simple selector, then there's no selector nextSelector = this._simple_selector_sequence(); if (nextSelector === null){ return null; } selector.push(nextSelector); do { //look for a combinator combinator = this._combinator(); if (combinator !== null){ selector.push(combinator); nextSelector = this._simple_selector_sequence(); //there must be a next selector if (nextSelector === null){ this._unexpectedToken(tokenStream.LT(1)); } else { //nextSelector is an instance of SelectorPart selector.push(nextSelector); } } else { //if there's not whitespace, we're done if (this._readWhitespace()){ //add whitespace separator ws = new Combinator(tokenStream.token().value, tokenStream.token().startLine, tokenStream.token().startCol); //combinator is not required combinator = this._combinator(); //selector is required if there's a combinator nextSelector = this._simple_selector_sequence(); if (nextSelector === null){ if (combinator !== null){ this._unexpectedToken(tokenStream.LT(1)); } } else { if (combinator !== null){ selector.push(combinator); } else { selector.push(ws); } selector.push(nextSelector); } } else { break; } } } while(true); return new Selector(selector, selector[0].line, selector[0].col); }, //CSS3 Selectors _simple_selector_sequence: function(){ /* * simple_selector_sequence * : [ type_selector | universal ] * [ HASH | class | attrib | pseudo | negation ]* * | [ HASH | class | attrib | pseudo | negation ]+ * ; */ var tokenStream = this._tokenStream, //parts of a simple selector elementName = null, modifiers = [], //complete selector text selectorText= "", //the different parts after the element name to search for components = [ //HASH function(){ return tokenStream.match(Tokens.HASH) ? new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) : null; }, this._class, this._attrib, this._pseudo, this._negation ], i = 0, len = components.length, component = null, found = false, line, col; //get starting line and column for the selector line = tokenStream.LT(1).startLine; col = tokenStream.LT(1).startCol; elementName = this._type_selector(); if (!elementName){ elementName = this._universal(); } if (elementName !== null){ selectorText += elementName; } while(true){ //whitespace means we're done if (tokenStream.peek() === Tokens.S){ break; } //check for each component while(i < len && component === null){ component = components[i++].call(this); } if (component === null){ //we don't have a selector if (selectorText === ""){ return null; } else { break; } } else { i = 0; modifiers.push(component); selectorText += component.toString(); component = null; } } return selectorText !== "" ? new SelectorPart(elementName, modifiers, selectorText, line, col) : null; }, //CSS3 Selectors _type_selector: function(){ /* * type_selector * : [ namespace_prefix ]? element_name * ; */ var tokenStream = this._tokenStream, ns = this._namespace_prefix(), elementName = this._element_name(); if (!elementName){ /* * Need to back out the namespace that was read due to both * type_selector and universal reading namespace_prefix * first. Kind of hacky, but only way I can figure out * right now how to not change the grammar. */ if (ns){ tokenStream.unget(); if (ns.length > 1){ tokenStream.unget(); } } return null; } else { if (ns){ elementName.text = ns + elementName.text; elementName.col -= ns.length; } return elementName; } }, //CSS3 Selectors _class: function(){ /* * class * : '.' IDENT * ; */ var tokenStream = this._tokenStream, token; if (tokenStream.match(Tokens.DOT)){ tokenStream.mustMatch(Tokens.IDENT); token = tokenStream.token(); return new SelectorSubPart("." + token.value, "class", token.startLine, token.startCol - 1); } else { return null; } }, //CSS3 Selectors _element_name: function(){ /* * element_name * : IDENT * ; */ var tokenStream = this._tokenStream, token; if (tokenStream.match(Tokens.IDENT)){ token = tokenStream.token(); return new SelectorSubPart(token.value, "elementName", token.startLine, token.startCol); } else { return null; } }, //CSS3 Selectors _namespace_prefix: function(){ /* * namespace_prefix * : [ IDENT | '*' ]? '|' * ; */ var tokenStream = this._tokenStream, value = ""; //verify that this is a namespace prefix if (tokenStream.LA(1) === Tokens.PIPE || tokenStream.LA(2) === Tokens.PIPE){ if(tokenStream.match([Tokens.IDENT, Tokens.STAR])){ value += tokenStream.token().value; } tokenStream.mustMatch(Tokens.PIPE); value += "|"; } return value.length ? value : null; }, //CSS3 Selectors _universal: function(){ /* * universal * : [ namespace_prefix ]? '*' * ; */ var tokenStream = this._tokenStream, value = "", ns; ns = this._namespace_prefix(); if(ns){ value += ns; } if(tokenStream.match(Tokens.STAR)){ value += "*"; } return value.length ? value : null; }, //CSS3 Selectors _attrib: function(){ /* * attrib * : '[' S* [ namespace_prefix ]? IDENT S* * [ [ PREFIXMATCH | * SUFFIXMATCH | * SUBSTRINGMATCH | * '=' | * INCLUDES | * DASHMATCH ] S* [ IDENT | STRING ] S* * ]? ']' * ; */ var tokenStream = this._tokenStream, value = null, ns, token; if (tokenStream.match(Tokens.LBRACKET)){ token = tokenStream.token(); value = token.value; value += this._readWhitespace(); ns = this._namespace_prefix(); if (ns){ value += ns; } tokenStream.mustMatch(Tokens.IDENT); value += tokenStream.token().value; value += this._readWhitespace(); if(tokenStream.match([Tokens.PREFIXMATCH, Tokens.SUFFIXMATCH, Tokens.SUBSTRINGMATCH, Tokens.EQUALS, Tokens.INCLUDES, Tokens.DASHMATCH])){ value += tokenStream.token().value; value += this._readWhitespace(); tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]); value += tokenStream.token().value; value += this._readWhitespace(); } tokenStream.mustMatch(Tokens.RBRACKET); return new SelectorSubPart(value + "]", "attribute", token.startLine, token.startCol); } else { return null; } }, //CSS3 Selectors _pseudo: function(){ /* * pseudo * : ':' ':'? [ IDENT | functional_pseudo ] * ; */ var tokenStream = this._tokenStream, pseudo = null, colons = ":", line, col; if (tokenStream.match(Tokens.COLON)){ if (tokenStream.match(Tokens.COLON)){ colons += ":"; } if (tokenStream.match(Tokens.IDENT)){ pseudo = tokenStream.token().value; line = tokenStream.token().startLine; col = tokenStream.token().startCol - colons.length; } else if (tokenStream.peek() == Tokens.FUNCTION){ line = tokenStream.LT(1).startLine; col = tokenStream.LT(1).startCol - colons.length; pseudo = this._functional_pseudo(); } if (pseudo){ pseudo = new SelectorSubPart(colons + pseudo, "pseudo", line, col); } } return pseudo; }, //CSS3 Selectors _functional_pseudo: function(){ /* * functional_pseudo * : FUNCTION S* expression ')' * ; */ var tokenStream = this._tokenStream, value = null; if(tokenStream.match(Tokens.FUNCTION)){ value = tokenStream.token().value; value += this._readWhitespace(); value += this._expression(); tokenStream.mustMatch(Tokens.RPAREN); value += ")"; } return value; }, //CSS3 Selectors _expression: function(){ /* * expression * : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+ * ; */ var tokenStream = this._tokenStream, value = ""; while(tokenStream.match([Tokens.PLUS, Tokens.MINUS, Tokens.DIMENSION, Tokens.NUMBER, Tokens.STRING, Tokens.IDENT, Tokens.LENGTH, Tokens.FREQ, Tokens.ANGLE, Tokens.TIME, Tokens.RESOLUTION, Tokens.SLASH])){ value += tokenStream.token().value; value += this._readWhitespace(); } return value.length ? value : null; }, //CSS3 Selectors _negation: function(){ /* * negation * : NOT S* negation_arg S* ')' * ; */ var tokenStream = this._tokenStream, line, col, value = "", arg, subpart = null; if (tokenStream.match(Tokens.NOT)){ value = tokenStream.token().value; line = tokenStream.token().startLine; col = tokenStream.token().startCol; value += this._readWhitespace(); arg = this._negation_arg(); value += arg; value += this._readWhitespace(); tokenStream.match(Tokens.RPAREN); value += tokenStream.token().value; subpart = new SelectorSubPart(value, "not", line, col); subpart.args.push(arg); } return subpart; }, //CSS3 Selectors _negation_arg: function(){ /* * negation_arg * : type_selector | universal | HASH | class | attrib | pseudo * ; */ var tokenStream = this._tokenStream, args = [ this._type_selector, this._universal, function(){ return tokenStream.match(Tokens.HASH) ? new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) : null; }, this._class, this._attrib, this._pseudo ], arg = null, i = 0, len = args.length, elementName, line, col, part; line = tokenStream.LT(1).startLine; col = tokenStream.LT(1).startCol; while(i < len && arg === null){ arg = args[i].call(this); i++; } //must be a negation arg if (arg === null){ this._unexpectedToken(tokenStream.LT(1)); } //it's an element name if (arg.type == "elementName"){ part = new SelectorPart(arg, [], arg.toString(), line, col); } else { part = new SelectorPart(null, [arg], arg.toString(), line, col); } return part; }, _declaration: function(){ /* * declaration * : property ':' S* expr prio? * | /( empty )/ * ; */ var tokenStream = this._tokenStream, property = null, expr = null, prio = null, error = null, invalid = null, propertyName= ""; property = this._property(); if (property !== null){ tokenStream.mustMatch(Tokens.COLON); this._readWhitespace(); expr = this._expr(); //if there's no parts for the value, it's an error if (!expr || expr.length === 0){ this._unexpectedToken(tokenStream.LT(1)); } prio = this._prio(); /* * If hacks should be allowed, then only check the root * property. If hacks should not be allowed, treat * _property or *property as invalid properties. */ propertyName = property.toString(); if (this.options.starHack && property.hack == "*" || this.options.underscoreHack && property.hack == "_") { propertyName = property.text; } try { this._validateProperty(propertyName, expr); } catch (ex) { invalid = ex; } this.fire({ type: "property", property: property, value: expr, important: prio, line: property.line, col: property.col, invalid: invalid }); return true; } else { return false; } }, _prio: function(){ /* * prio * : IMPORTANT_SYM S* * ; */ var tokenStream = this._tokenStream, result = tokenStream.match(Tokens.IMPORTANT_SYM); this._readWhitespace(); return result; }, _expr: function(inFunction){ /* * expr * : term [ operator term ]* * ; */ var tokenStream = this._tokenStream, values = [], //valueParts = [], value = null, operator = null; value = this._term(inFunction); if (value !== null){ values.push(value); do { operator = this._operator(inFunction); //if there's an operator, keep building up the value parts if (operator){ values.push(operator); } /*else { //if there's not an operator, you have a full value values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col)); valueParts = []; }*/ value = this._term(inFunction); if (value === null){ break; } else { values.push(value); } } while(true); } //cleanup /*if (valueParts.length){ values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col)); }*/ return values.length > 0 ? new PropertyValue(values, values[0].line, values[0].col) : null; }, _term: function(inFunction){ /* * term * : unary_operator? * [ NUMBER S* | PERCENTAGE S* | LENGTH S* | ANGLE S* | * TIME S* | FREQ S* | function | ie_function ] * | STRING S* | IDENT S* | URI S* | UNICODERANGE S* | hexcolor * ; */ var tokenStream = this._tokenStream, unary = null, value = null, endChar = null, token, line, col; //returns the operator or null unary = this._unary_operator(); if (unary !== null){ line = tokenStream.token().startLine; col = tokenStream.token().startCol; } //exception for IE filters if (tokenStream.peek() == Tokens.IE_FUNCTION && this.options.ieFilters){ value = this._ie_function(); if (unary === null){ line = tokenStream.token().startLine; col = tokenStream.token().startCol; } //see if it's a simple block } else if (inFunction && tokenStream.match([Tokens.LPAREN, Tokens.LBRACE, Tokens.LBRACKET])){ token = tokenStream.token(); endChar = token.endChar; value = token.value + this._expr(inFunction).text; if (unary === null){ line = tokenStream.token().startLine; col = tokenStream.token().startCol; } tokenStream.mustMatch(Tokens.type(endChar)); value += endChar; this._readWhitespace(); //see if there's a simple match } else if (tokenStream.match([Tokens.NUMBER, Tokens.PERCENTAGE, Tokens.LENGTH, Tokens.ANGLE, Tokens.TIME, Tokens.FREQ, Tokens.STRING, Tokens.IDENT, Tokens.URI, Tokens.UNICODE_RANGE])){ value = tokenStream.token().value; if (unary === null){ line = tokenStream.token().startLine; col = tokenStream.token().startCol; } this._readWhitespace(); } else { //see if it's a color token = this._hexcolor(); if (token === null){ //if there's no unary, get the start of the next token for line/col info if (unary === null){ line = tokenStream.LT(1).startLine; col = tokenStream.LT(1).startCol; } //has to be a function if (value === null){ /* * This checks for alpha(opacity=0) style of IE * functions. IE_FUNCTION only presents progid: style. */ if (tokenStream.LA(3) == Tokens.EQUALS && this.options.ieFilters){ value = this._ie_function(); } else { value = this._function(); } } /*if (value === null){ return null; //throw new Error("Expected identifier at line " + tokenStream.token().startLine + ", character " + tokenStream.token().startCol + "."); }*/ } else { value = token.value; if (unary === null){ line = token.startLine; col = token.startCol; } } } return value !== null ? new PropertyValuePart(unary !== null ? unary + value : value, line, col) : null; }, _function: function(){ /* * function * : FUNCTION S* expr ')' S* * ; */ var tokenStream = this._tokenStream, functionText = null, expr = null, lt; if (tokenStream.match(Tokens.FUNCTION)){ functionText = tokenStream.token().value; this._readWhitespace(); expr = this._expr(true); functionText += expr; //START: Horrible hack in case it's an IE filter if (this.options.ieFilters && tokenStream.peek() == Tokens.EQUALS){ do { if (this._readWhitespace()){ functionText += tokenStream.token().value; } //might be second time in the loop if (tokenStream.LA(0) == Tokens.COMMA){ functionText += tokenStream.token().value; } tokenStream.match(Tokens.IDENT); functionText += tokenStream.token().value; tokenStream.match(Tokens.EQUALS); functionText += tokenStream.token().value; //functionText += this._term(); lt = tokenStream.peek(); while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){ tokenStream.get(); functionText += tokenStream.token().value; lt = tokenStream.peek(); } } while(tokenStream.match([Tokens.COMMA, Tokens.S])); } //END: Horrible Hack tokenStream.match(Tokens.RPAREN); functionText += ")"; this._readWhitespace(); } return functionText; }, _ie_function: function(){ /* (My own extension) * ie_function * : IE_FUNCTION S* IDENT '=' term [S* ','? IDENT '=' term]+ ')' S* * ; */ var tokenStream = this._tokenStream, functionText = null, expr = null, lt; //IE function can begin like a regular function, too if (tokenStream.match([Tokens.IE_FUNCTION, Tokens.FUNCTION])){ functionText = tokenStream.token().value; do { if (this._readWhitespace()){ functionText += tokenStream.token().value; } //might be second time in the loop if (tokenStream.LA(0) == Tokens.COMMA){ functionText += tokenStream.token().value; } tokenStream.match(Tokens.IDENT); functionText += tokenStream.token().value; tokenStream.match(Tokens.EQUALS); functionText += tokenStream.token().value; //functionText += this._term(); lt = tokenStream.peek(); while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){ tokenStream.get(); functionText += tokenStream.token().value; lt = tokenStream.peek(); } } while(tokenStream.match([Tokens.COMMA, Tokens.S])); tokenStream.match(Tokens.RPAREN); functionText += ")"; this._readWhitespace(); } return functionText; }, _hexcolor: function(){ /* * There is a constraint on the color that it must * have either 3 or 6 hex-digits (i.e., [0-9a-fA-F]) * after the "#"; e.g., "#000" is OK, but "#abcd" is not. * * hexcolor * : HASH S* * ; */ var tokenStream = this._tokenStream, token = null, color; if(tokenStream.match(Tokens.HASH)){ //need to do some validation here token = tokenStream.token(); color = token.value; if (!/#[a-f0-9]{3,6}/i.test(color)){ throw new SyntaxError("Expected a hex color but found '" + color + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol); } this._readWhitespace(); } return token; }, //----------------------------------------------------------------- // Animations methods //----------------------------------------------------------------- _keyframes: function(){ /* * keyframes: * : KEYFRAMES_SYM S* keyframe_name S* '{' S* keyframe_rule* '}' { * ; */ var tokenStream = this._tokenStream, token, tt, name, prefix = ""; tokenStream.mustMatch(Tokens.KEYFRAMES_SYM); token = tokenStream.token(); if (/^@\-([^\-]+)\-/.test(token.value)) { prefix = RegExp.$1; } this._readWhitespace(); name = this._keyframe_name(); this._readWhitespace(); tokenStream.mustMatch(Tokens.LBRACE); this.fire({ type: "startkeyframes", name: name, prefix: prefix, line: token.startLine, col: token.startCol }); this._readWhitespace(); tt = tokenStream.peek(); //check for key while(tt == Tokens.IDENT || tt == Tokens.PERCENTAGE) { this._keyframe_rule(); this._readWhitespace(); tt = tokenStream.peek(); } this.fire({ type: "endkeyframes", name: name, prefix: prefix, line: token.startLine, col: token.startCol }); this._readWhitespace(); tokenStream.mustMatch(Tokens.RBRACE); }, _keyframe_name: function(){ /* * keyframe_name: * : IDENT * | STRING * ; */ var tokenStream = this._tokenStream, token; tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]); return SyntaxUnit.fromToken(tokenStream.token()); }, _keyframe_rule: function(){ /* * keyframe_rule: * : key_list S* * '{' S* declaration [ ';' S* declaration ]* '}' S* * ; */ var tokenStream = this._tokenStream, token, keyList = this._key_list(); this.fire({ type: "startkeyframerule", keys: keyList, line: keyList[0].line, col: keyList[0].col }); this._readDeclarations(true); this.fire({ type: "endkeyframerule", keys: keyList, line: keyList[0].line, col: keyList[0].col }); }, _key_list: function(){ /* * key_list: * : key [ S* ',' S* key]* * ; */ var tokenStream = this._tokenStream, token, key, keyList = []; //must be least one key keyList.push(this._key()); this._readWhitespace(); while(tokenStream.match(Tokens.COMMA)){ this._readWhitespace(); keyList.push(this._key()); this._readWhitespace(); } return keyList; }, _key: function(){ /* * There is a restriction that IDENT can be only "from" or "to". * * key * : PERCENTAGE * | IDENT * ; */ var tokenStream = this._tokenStream, token; if (tokenStream.match(Tokens.PERCENTAGE)){ return SyntaxUnit.fromToken(tokenStream.token()); } else if (tokenStream.match(Tokens.IDENT)){ token = tokenStream.token(); if (/from|to/i.test(token.value)){ return SyntaxUnit.fromToken(token); } tokenStream.unget(); } //if it gets here, there wasn't a valid token, so time to explode this._unexpectedToken(tokenStream.LT(1)); }, //----------------------------------------------------------------- // Helper methods //----------------------------------------------------------------- /** * Not part of CSS grammar, but useful for skipping over * combination of white space and HTML-style comments. * @return {void} * @method _skipCruft * @private */ _skipCruft: function(){ while(this._tokenStream.match([Tokens.S, Tokens.CDO, Tokens.CDC])){ //noop } }, /** * Not part of CSS grammar, but this pattern occurs frequently * in the official CSS grammar. Split out here to eliminate * duplicate code. * @param {Boolean} checkStart Indicates if the rule should check * for the left brace at the beginning. * @param {Boolean} readMargins Indicates if the rule should check * for margin patterns. * @return {void} * @method _readDeclarations * @private */ _readDeclarations: function(checkStart, readMargins){ /* * Reads the pattern * S* '{' S* declaration [ ';' S* declaration ]* '}' S* * or * S* '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S* * Note that this is how it is described in CSS3 Paged Media, but is actually incorrect. * A semicolon is only necessary following a declaration is there's another declaration * or margin afterwards. */ var tokenStream = this._tokenStream, tt; this._readWhitespace(); if (checkStart){ tokenStream.mustMatch(Tokens.LBRACE); } this._readWhitespace(); try { while(true){ if (tokenStream.match(Tokens.SEMICOLON) || (readMargins && this._margin())){ //noop } else if (this._declaration()){ if (!tokenStream.match(Tokens.SEMICOLON)){ break; } } else { break; } //if ((!this._margin() && !this._declaration()) || !tokenStream.match(Tokens.SEMICOLON)){ // break; //} this._readWhitespace(); } tokenStream.mustMatch(Tokens.RBRACE); this._readWhitespace(); } catch (ex) { if (ex instanceof SyntaxError && !this.options.strict){ //fire error event this.fire({ type: "error", error: ex, message: ex.message, line: ex.line, col: ex.col }); //see if there's another declaration tt = tokenStream.advance([Tokens.SEMICOLON, Tokens.RBRACE]); if (tt == Tokens.SEMICOLON){ //if there's a semicolon, then there might be another declaration this._readDeclarations(false, readMargins); } else if (tt != Tokens.RBRACE){ //if there's a right brace, the rule is finished so don't do anything //otherwise, rethrow the error because it wasn't handled properly throw ex; } } else { //not a syntax error, rethrow it throw ex; } } }, /** * In some cases, you can end up with two white space tokens in a * row. Instead of making a change in every function that looks for * white space, this function is used to match as much white space * as necessary. * @method _readWhitespace * @return {String} The white space if found, empty string if not. * @private */ _readWhitespace: function(){ var tokenStream = this._tokenStream, ws = ""; while(tokenStream.match(Tokens.S)){ ws += tokenStream.token().value; } return ws; }, /** * Throws an error when an unexpected token is found. * @param {Object} token The token that was found. * @method _unexpectedToken * @return {void} * @private */ _unexpectedToken: function(token){ throw new SyntaxError("Unexpected token '" + token.value + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol); }, /** * Helper method used for parsing subparts of a style sheet. * @return {void} * @method _verifyEnd * @private */ _verifyEnd: function(){ if (this._tokenStream.LA(1) != Tokens.EOF){ this._unexpectedToken(this._tokenStream.LT(1)); } }, //----------------------------------------------------------------- // Validation methods //----------------------------------------------------------------- _validateProperty: function(property, value){ Validation.validate(property, value); }, //----------------------------------------------------------------- // Parsing methods //----------------------------------------------------------------- parse: function(input){ this._tokenStream = new TokenStream(input, Tokens); this._stylesheet(); }, parseStyleSheet: function(input){ //just passthrough return this.parse(input); }, parseMediaQuery: function(input){ this._tokenStream = new TokenStream(input, Tokens); var result = this._media_query(); //if there's anything more, then it's an invalid selector this._verifyEnd(); //otherwise return result return result; }, /** * Parses a property value (everything after the semicolon). * @return {parserlib.css.PropertyValue} The property value. * @throws parserlib.util.SyntaxError If an unexpected token is found. * @method parserPropertyValue */ parsePropertyValue: function(input){ this._tokenStream = new TokenStream(input, Tokens); this._readWhitespace(); var result = this._expr(); //okay to have a trailing white space this._readWhitespace(); //if there's anything more, then it's an invalid selector this._verifyEnd(); //otherwise return result return result; }, /** * Parses a complete CSS rule, including selectors and * properties. * @param {String} input The text to parser. * @return {Boolean} True if the parse completed successfully, false if not. * @method parseRule */ parseRule: function(input){ this._tokenStream = new TokenStream(input, Tokens); //skip any leading white space this._readWhitespace(); var result = this._ruleset(); //skip any trailing white space this._readWhitespace(); //if there's anything more, then it's an invalid selector this._verifyEnd(); //otherwise return result return result; }, /** * Parses a single CSS selector (no comma) * @param {String} input The text to parse as a CSS selector. * @return {Selector} An object representing the selector. * @throws parserlib.util.SyntaxError If an unexpected token is found. * @method parseSelector */ parseSelector: function(input){ this._tokenStream = new TokenStream(input, Tokens); //skip any leading white space this._readWhitespace(); var result = this._selector(); //skip any trailing white space this._readWhitespace(); //if there's anything more, then it's an invalid selector this._verifyEnd(); //otherwise return result return result; }, /** * Parses an HTML style attribute: a set of CSS declarations * separated by semicolons. * @param {String} input The text to parse as a style attribute * @return {void} * @method parseStyleAttribute */ parseStyleAttribute: function(input){ input += "}"; // for error recovery in _readDeclarations() this._tokenStream = new TokenStream(input, Tokens); this._readDeclarations(); } }; //copy over onto prototype for (prop in additions){ if (additions.hasOwnProperty(prop)){ proto[prop] = additions[prop]; } } return proto; }(); /* nth : S* [ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]? | ['-'|'+']? INTEGER | {O}{D}{D} | {E}{V}{E}{N} ] S* ; */ /*global Validation, ValidationTypes, ValidationError*/ var Properties = { //A "align-items" : "flex-start | flex-end | center | baseline | stretch", "align-content" : "flex-start | flex-end | center | space-between | space-around | stretch", "align-self" : "auto | flex-start | flex-end | center | baseline | stretch", "-webkit-align-items" : "flex-start | flex-end | center | baseline | stretch", "-webkit-align-content" : "flex-start | flex-end | center | space-between | space-around | stretch", "-webkit-align-self" : "auto | flex-start | flex-end | center | baseline | stretch", "alignment-adjust" : "auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | <percentage> | <length>", "alignment-baseline" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical", "animation" : 1, "animation-delay" : { multi: "<time>", comma: true }, "animation-direction" : { multi: "normal | alternate", comma: true }, "animation-duration" : { multi: "<time>", comma: true }, "animation-fill-mode" : { multi: "none | forwards | backwards | both", comma: true }, "animation-iteration-count" : { multi: "<number> | infinite", comma: true }, "animation-name" : { multi: "none | <ident>", comma: true }, "animation-play-state" : { multi: "running | paused", comma: true }, "animation-timing-function" : 1, //vendor prefixed "-moz-animation-delay" : { multi: "<time>", comma: true }, "-moz-animation-direction" : { multi: "normal | alternate", comma: true }, "-moz-animation-duration" : { multi: "<time>", comma: true }, "-moz-animation-iteration-count" : { multi: "<number> | infinite", comma: true }, "-moz-animation-name" : { multi: "none | <ident>", comma: true }, "-moz-animation-play-state" : { multi: "running | paused", comma: true }, "-ms-animation-delay" : { multi: "<time>", comma: true }, "-ms-animation-direction" : { multi: "normal | alternate", comma: true }, "-ms-animation-duration" : { multi: "<time>", comma: true }, "-ms-animation-iteration-count" : { multi: "<number> | infinite", comma: true }, "-ms-animation-name" : { multi: "none | <ident>", comma: true }, "-ms-animation-play-state" : { multi: "running | paused", comma: true }, "-webkit-animation-delay" : { multi: "<time>", comma: true }, "-webkit-animation-direction" : { multi: "normal | alternate", comma: true }, "-webkit-animation-duration" : { multi: "<time>", comma: true }, "-webkit-animation-fill-mode" : { multi: "none | forwards | backwards | both", comma: true }, "-webkit-animation-iteration-count" : { multi: "<number> | infinite", comma: true }, "-webkit-animation-name" : { multi: "none | <ident>", comma: true }, "-webkit-animation-play-state" : { multi: "running | paused", comma: true }, "-o-animation-delay" : { multi: "<time>", comma: true }, "-o-animation-direction" : { multi: "normal | alternate", comma: true }, "-o-animation-duration" : { multi: "<time>", comma: true }, "-o-animation-iteration-count" : { multi: "<number> | infinite", comma: true }, "-o-animation-name" : { multi: "none | <ident>", comma: true }, "-o-animation-play-state" : { multi: "running | paused", comma: true }, "appearance" : "icon | window | desktop | workspace | document | tooltip | dialog | button | push-button | hyperlink | radio-button | checkbox | menu-item | tab | menu | menubar | pull-down-menu | pop-up-menu | list-menu | radio-group | checkbox-group | outline-tree | range | field | combo-box | signature | password | normal | none | inherit", "azimuth" : function (expression) { var simple = "<angle> | leftwards | rightwards | inherit", direction = "left-side | far-left | left | center-left | center | center-right | right | far-right | right-side", behind = false, valid = false, part; if (!ValidationTypes.isAny(expression, simple)) { if (ValidationTypes.isAny(expression, "behind")) { behind = true; valid = true; } if (ValidationTypes.isAny(expression, direction)) { valid = true; if (!behind) { ValidationTypes.isAny(expression, "behind"); } } } if (expression.hasNext()) { part = expression.next(); if (valid) { throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { throw new ValidationError("Expected (<'azimuth'>) but found '" + part + "'.", part.line, part.col); } } }, //B "backface-visibility" : "visible | hidden", "background" : 1, "background-attachment" : { multi: "<attachment>", comma: true }, "background-clip" : { multi: "<box>", comma: true }, "background-color" : "<color> | inherit", "background-image" : { multi: "<bg-image>", comma: true }, "background-origin" : { multi: "<box>", comma: true }, "background-position" : { multi: "<bg-position>", comma: true }, "background-repeat" : { multi: "<repeat-style>" }, "background-size" : { multi: "<bg-size>", comma: true }, "baseline-shift" : "baseline | sub | super | <percentage> | <length>", "behavior" : 1, "binding" : 1, "bleed" : "<length>", "bookmark-label" : "<content> | <attr> | <string>", "bookmark-level" : "none | <integer>", "bookmark-state" : "open | closed", "bookmark-target" : "none | <uri> | <attr>", "border" : "<border-width> || <border-style> || <color>", "border-bottom" : "<border-width> || <border-style> || <color>", "border-bottom-color" : "<color> | inherit", "border-bottom-left-radius" : "<x-one-radius>", "border-bottom-right-radius" : "<x-one-radius>", "border-bottom-style" : "<border-style>", "border-bottom-width" : "<border-width>", "border-collapse" : "collapse | separate | inherit", "border-color" : { multi: "<color> | inherit", max: 4 }, "border-image" : 1, "border-image-outset" : { multi: "<length> | <number>", max: 4 }, "border-image-repeat" : { multi: "stretch | repeat | round", max: 2 }, "border-image-slice" : function(expression) { var valid = false, numeric = "<number> | <percentage>", fill = false, count = 0, max = 4, part; if (ValidationTypes.isAny(expression, "fill")) { fill = true; valid = true; } while (expression.hasNext() && count < max) { valid = ValidationTypes.isAny(expression, numeric); if (!valid) { break; } count++; } if (!fill) { ValidationTypes.isAny(expression, "fill"); } else { valid = true; } if (expression.hasNext()) { part = expression.next(); if (valid) { throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { throw new ValidationError("Expected ([<number> | <percentage>]{1,4} && fill?) but found '" + part + "'.", part.line, part.col); } } }, "border-image-source" : "<image> | none", "border-image-width" : { multi: "<length> | <percentage> | <number> | auto", max: 4 }, "border-left" : "<border-width> || <border-style> || <color>", "border-left-color" : "<color> | inherit", "border-left-style" : "<border-style>", "border-left-width" : "<border-width>", "border-radius" : function(expression) { var valid = false, simple = "<length> | <percentage> | inherit", slash = false, fill = false, count = 0, max = 8, part; while (expression.hasNext() && count < max) { valid = ValidationTypes.isAny(expression, simple); if (!valid) { if (expression.peek() == "/" && count > 0 && !slash) { slash = true; max = count + 5; expression.next(); } else { break; } } count++; } if (expression.hasNext()) { part = expression.next(); if (valid) { throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { throw new ValidationError("Expected (<'border-radius'>) but found '" + part + "'.", part.line, part.col); } } }, "border-right" : "<border-width> || <border-style> || <color>", "border-right-color" : "<color> | inherit", "border-right-style" : "<border-style>", "border-right-width" : "<border-width>", "border-spacing" : { multi: "<length> | inherit", max: 2 }, "border-style" : { multi: "<border-style>", max: 4 }, "border-top" : "<border-width> || <border-style> || <color>", "border-top-color" : "<color> | inherit", "border-top-left-radius" : "<x-one-radius>", "border-top-right-radius" : "<x-one-radius>", "border-top-style" : "<border-style>", "border-top-width" : "<border-width>", "border-width" : { multi: "<border-width>", max: 4 }, "bottom" : "<margin-width> | inherit", "-moz-box-align" : "start | end | center | baseline | stretch", "-moz-box-decoration-break" : "slice |clone", "-moz-box-direction" : "normal | reverse | inherit", "-moz-box-flex" : "<number>", "-moz-box-flex-group" : "<integer>", "-moz-box-lines" : "single | multiple", "-moz-box-ordinal-group" : "<integer>", "-moz-box-orient" : "horizontal | vertical | inline-axis | block-axis | inherit", "-moz-box-pack" : "start | end | center | justify", "-webkit-box-align" : "start | end | center | baseline | stretch", "-webkit-box-decoration-break" : "slice |clone", "-webkit-box-direction" : "normal | reverse | inherit", "-webkit-box-flex" : "<number>", "-webkit-box-flex-group" : "<integer>", "-webkit-box-lines" : "single | multiple", "-webkit-box-ordinal-group" : "<integer>", "-webkit-box-orient" : "horizontal | vertical | inline-axis | block-axis | inherit", "-webkit-box-pack" : "start | end | center | justify", "box-shadow" : function (expression) { var result = false, part; if (!ValidationTypes.isAny(expression, "none")) { Validation.multiProperty("<shadow>", expression, true, Infinity); } else { if (expression.hasNext()) { part = expression.next(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } } }, "box-sizing" : "content-box | border-box | inherit", "break-after" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column", "break-before" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column", "break-inside" : "auto | avoid | avoid-page | avoid-column", //C "caption-side" : "top | bottom | inherit", "clear" : "none | right | left | both | inherit", "clip" : 1, "color" : "<color> | inherit", "color-profile" : 1, "column-count" : "<integer> | auto", //http://www.w3.org/TR/css3-multicol/ "column-fill" : "auto | balance", "column-gap" : "<length> | normal", "column-rule" : "<border-width> || <border-style> || <color>", "column-rule-color" : "<color>", "column-rule-style" : "<border-style>", "column-rule-width" : "<border-width>", "column-span" : "none | all", "column-width" : "<length> | auto", "columns" : 1, "content" : 1, "counter-increment" : 1, "counter-reset" : 1, "crop" : "<shape> | auto", "cue" : "cue-after | cue-before | inherit", "cue-after" : 1, "cue-before" : 1, "cursor" : 1, //D "direction" : "ltr | rtl | inherit", "display" : "inline | block | list-item | inline-block | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | grid | inline-grid | none | inherit | -moz-box | -moz-inline-block | -moz-inline-box | -moz-inline-grid | -moz-inline-stack | -moz-inline-table | -moz-grid | -moz-grid-group | -moz-grid-line | -moz-groupbox | -moz-deck | -moz-popup | -moz-stack | -moz-marker | -webkit-box | -webkit-inline-box | -ms-flexbox | -ms-inline-flexbox | flex | -webkit-flex | inline-flex | -webkit-inline-flex", "dominant-baseline" : 1, "drop-initial-after-adjust" : "central | middle | after-edge | text-after-edge | ideographic | alphabetic | mathematical | <percentage> | <length>", "drop-initial-after-align" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical", "drop-initial-before-adjust" : "before-edge | text-before-edge | central | middle | hanging | mathematical | <percentage> | <length>", "drop-initial-before-align" : "caps-height | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical", "drop-initial-size" : "auto | line | <length> | <percentage>", "drop-initial-value" : "initial | <integer>", //E "elevation" : "<angle> | below | level | above | higher | lower | inherit", "empty-cells" : "show | hide | inherit", //F "filter" : 1, "fit" : "fill | hidden | meet | slice", "fit-position" : 1, "flex" : "<flex>", "flex-basis" : "<width>", "flex-direction" : "row | row-reverse | column | column-reverse", "flex-flow" : "<flex-direction> || <flex-wrap>", "flex-grow" : "<number>", "flex-shrink" : "<number>", "flex-wrap" : "nowrap | wrap | wrap-reverse", "-webkit-flex" : "<flex>", "-webkit-flex-basis" : "<width>", "-webkit-flex-direction" : "row | row-reverse | column | column-reverse", "-webkit-flex-flow" : "<flex-direction> || <flex-wrap>", "-webkit-flex-grow" : "<number>", "-webkit-flex-shrink" : "<number>", "-webkit-flex-wrap" : "nowrap | wrap | wrap-reverse", "-ms-flex" : "<flex>", "-ms-flex-align" : "start | end | center | stretch | baseline", "-ms-flex-direction" : "row | row-reverse | column | column-reverse | inherit", "-ms-flex-order" : "<number>", "-ms-flex-pack" : "start | end | center | justify", "-ms-flex-wrap" : "nowrap | wrap | wrap-reverse", "float" : "left | right | none | inherit", "float-offset" : 1, "font" : 1, "font-family" : 1, "font-size" : "<absolute-size> | <relative-size> | <length> | <percentage> | inherit", "font-size-adjust" : "<number> | none | inherit", "font-stretch" : "normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | inherit", "font-style" : "normal | italic | oblique | inherit", "font-variant" : "normal | small-caps | inherit", "font-weight" : "normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit", //G "grid-cell-stacking" : "columns | rows | layer", "grid-column" : 1, "grid-columns" : 1, "grid-column-align" : "start | end | center | stretch", "grid-column-sizing" : 1, "grid-column-span" : "<integer>", "grid-flow" : "none | rows | columns", "grid-layer" : "<integer>", "grid-row" : 1, "grid-rows" : 1, "grid-row-align" : "start | end | center | stretch", "grid-row-span" : "<integer>", "grid-row-sizing" : 1, //H "hanging-punctuation" : 1, "height" : "<margin-width> | <content-sizing> | inherit", "hyphenate-after" : "<integer> | auto", "hyphenate-before" : "<integer> | auto", "hyphenate-character" : "<string> | auto", "hyphenate-lines" : "no-limit | <integer>", "hyphenate-resource" : 1, "hyphens" : "none | manual | auto", //I "icon" : 1, "image-orientation" : "angle | auto", "image-rendering" : 1, "image-resolution" : 1, "inline-box-align" : "initial | last | <integer>", //J "justify-content" : "flex-start | flex-end | center | space-between | space-around", "-webkit-justify-content" : "flex-start | flex-end | center | space-between | space-around", //L "left" : "<margin-width> | inherit", "letter-spacing" : "<length> | normal | inherit", "line-height" : "<number> | <length> | <percentage> | normal | inherit", "line-break" : "auto | loose | normal | strict", "line-stacking" : 1, "line-stacking-ruby" : "exclude-ruby | include-ruby", "line-stacking-shift" : "consider-shifts | disregard-shifts", "line-stacking-strategy" : "inline-line-height | block-line-height | max-height | grid-height", "list-style" : 1, "list-style-image" : "<uri> | none | inherit", "list-style-position" : "inside | outside | inherit", "list-style-type" : "disc | circle | square | decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-latin | upper-latin | armenian | georgian | lower-alpha | upper-alpha | none | inherit", //M "margin" : { multi: "<margin-width> | inherit", max: 4 }, "margin-bottom" : "<margin-width> | inherit", "margin-left" : "<margin-width> | inherit", "margin-right" : "<margin-width> | inherit", "margin-top" : "<margin-width> | inherit", "mark" : 1, "mark-after" : 1, "mark-before" : 1, "marks" : 1, "marquee-direction" : 1, "marquee-play-count" : 1, "marquee-speed" : 1, "marquee-style" : 1, "max-height" : "<length> | <percentage> | <content-sizing> | none | inherit", "max-width" : "<length> | <percentage> | <content-sizing> | none | inherit", "min-height" : "<length> | <percentage> | <content-sizing> | contain-floats | -moz-contain-floats | -webkit-contain-floats | inherit", "min-width" : "<length> | <percentage> | <content-sizing> | contain-floats | -moz-contain-floats | -webkit-contain-floats | inherit", "move-to" : 1, //N "nav-down" : 1, "nav-index" : 1, "nav-left" : 1, "nav-right" : 1, "nav-up" : 1, //O "opacity" : "<number> | inherit", "order" : "<integer>", "-webkit-order" : "<integer>", "orphans" : "<integer> | inherit", "outline" : 1, "outline-color" : "<color> | invert | inherit", "outline-offset" : 1, "outline-style" : "<border-style> | inherit", "outline-width" : "<border-width> | inherit", "overflow" : "visible | hidden | scroll | auto | inherit", "overflow-style" : 1, "overflow-wrap" : "normal | break-word", "overflow-x" : 1, "overflow-y" : 1, //P "padding" : { multi: "<padding-width> | inherit", max: 4 }, "padding-bottom" : "<padding-width> | inherit", "padding-left" : "<padding-width> | inherit", "padding-right" : "<padding-width> | inherit", "padding-top" : "<padding-width> | inherit", "page" : 1, "page-break-after" : "auto | always | avoid | left | right | inherit", "page-break-before" : "auto | always | avoid | left | right | inherit", "page-break-inside" : "auto | avoid | inherit", "page-policy" : 1, "pause" : 1, "pause-after" : 1, "pause-before" : 1, "perspective" : 1, "perspective-origin" : 1, "phonemes" : 1, "pitch" : 1, "pitch-range" : 1, "play-during" : 1, "pointer-events" : "auto | none | visiblePainted | visibleFill | visibleStroke | visible | painted | fill | stroke | all | inherit", "position" : "static | relative | absolute | fixed | inherit", "presentation-level" : 1, "punctuation-trim" : 1, //Q "quotes" : 1, //R "rendering-intent" : 1, "resize" : 1, "rest" : 1, "rest-after" : 1, "rest-before" : 1, "richness" : 1, "right" : "<margin-width> | inherit", "rotation" : 1, "rotation-point" : 1, "ruby-align" : 1, "ruby-overhang" : 1, "ruby-position" : 1, "ruby-span" : 1, //S "size" : 1, "speak" : "normal | none | spell-out | inherit", "speak-header" : "once | always | inherit", "speak-numeral" : "digits | continuous | inherit", "speak-punctuation" : "code | none | inherit", "speech-rate" : 1, "src" : 1, "stress" : 1, "string-set" : 1, "table-layout" : "auto | fixed | inherit", "tab-size" : "<integer> | <length>", "target" : 1, "target-name" : 1, "target-new" : 1, "target-position" : 1, "text-align" : "left | right | center | justify | inherit" , "text-align-last" : 1, "text-decoration" : 1, "text-emphasis" : 1, "text-height" : 1, "text-indent" : "<length> | <percentage> | inherit", "text-justify" : "auto | none | inter-word | inter-ideograph | inter-cluster | distribute | kashida", "text-outline" : 1, "text-overflow" : 1, "text-rendering" : "auto | optimizeSpeed | optimizeLegibility | geometricPrecision | inherit", "text-shadow" : 1, "text-transform" : "capitalize | uppercase | lowercase | none | inherit", "text-wrap" : "normal | none | avoid", "top" : "<margin-width> | inherit", "-ms-touch-action" : "auto | none | pan-x | pan-y", "touch-action" : "auto | none | pan-x | pan-y", "transform" : 1, "transform-origin" : 1, "transform-style" : 1, "transition" : 1, "transition-delay" : 1, "transition-duration" : 1, "transition-property" : 1, "transition-timing-function" : 1, //U "unicode-bidi" : "normal | embed | isolate | bidi-override | isolate-override | plaintext | inherit", "user-modify" : "read-only | read-write | write-only | inherit", "user-select" : "none | text | toggle | element | elements | all | inherit", //V "vertical-align" : "auto | use-script | baseline | sub | super | top | text-top | central | middle | bottom | text-bottom | <percentage> | <length>", "visibility" : "visible | hidden | collapse | inherit", "voice-balance" : 1, "voice-duration" : 1, "voice-family" : 1, "voice-pitch" : 1, "voice-pitch-range" : 1, "voice-rate" : 1, "voice-stress" : 1, "voice-volume" : 1, "volume" : 1, //W "white-space" : "normal | pre | nowrap | pre-wrap | pre-line | inherit | -pre-wrap | -o-pre-wrap | -moz-pre-wrap | -hp-pre-wrap", //http://perishablepress.com/wrapping-content/ "white-space-collapse" : 1, "widows" : "<integer> | inherit", "width" : "<length> | <percentage> | <content-sizing> | auto | inherit", "word-break" : "normal | keep-all | break-all", "word-spacing" : "<length> | normal | inherit", "word-wrap" : "normal | break-word", "writing-mode" : "horizontal-tb | vertical-rl | vertical-lr | lr-tb | rl-tb | tb-rl | bt-rl | tb-lr | bt-lr | lr-bt | rl-bt | lr | rl | tb | inherit", //Z "z-index" : "<integer> | auto | inherit", "zoom" : "<number> | <percentage> | normal" }; /*global SyntaxUnit, Parser*/ /** * Represents a selector combinator (whitespace, +, >). * @namespace parserlib.css * @class PropertyName * @extends parserlib.util.SyntaxUnit * @constructor * @param {String} text The text representation of the unit. * @param {String} hack The type of IE hack applied ("*", "_", or null). * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function PropertyName(text, hack, line, col){ SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_NAME_TYPE); /** * The type of IE hack applied ("*", "_", or null). * @type String * @property hack */ this.hack = hack; } PropertyName.prototype = new SyntaxUnit(); PropertyName.prototype.constructor = PropertyName; PropertyName.prototype.toString = function(){ return (this.hack ? this.hack : "") + this.text; }; /*global SyntaxUnit, Parser*/ /** * Represents a single part of a CSS property value, meaning that it represents * just everything single part between ":" and ";". If there are multiple values * separated by commas, this type represents just one of the values. * @param {String[]} parts An array of value parts making up this value. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. * @namespace parserlib.css * @class PropertyValue * @extends parserlib.util.SyntaxUnit * @constructor */ function PropertyValue(parts, line, col){ SyntaxUnit.call(this, parts.join(" "), line, col, Parser.PROPERTY_VALUE_TYPE); /** * The parts that make up the selector. * @type Array * @property parts */ this.parts = parts; } PropertyValue.prototype = new SyntaxUnit(); PropertyValue.prototype.constructor = PropertyValue; /*global SyntaxUnit, Parser*/ /** * A utility class that allows for easy iteration over the various parts of a * property value. * @param {parserlib.css.PropertyValue} value The property value to iterate over. * @namespace parserlib.css * @class PropertyValueIterator * @constructor */ function PropertyValueIterator(value){ /** * Iterator value * @type int * @property _i * @private */ this._i = 0; /** * The parts that make up the value. * @type Array * @property _parts * @private */ this._parts = value.parts; /** * Keeps track of bookmarks along the way. * @type Array * @property _marks * @private */ this._marks = []; /** * Holds the original property value. * @type parserlib.css.PropertyValue * @property value */ this.value = value; } /** * Returns the total number of parts in the value. * @return {int} The total number of parts in the value. * @method count */ PropertyValueIterator.prototype.count = function(){ return this._parts.length; }; /** * Indicates if the iterator is positioned at the first item. * @return {Boolean} True if positioned at first item, false if not. * @method isFirst */ PropertyValueIterator.prototype.isFirst = function(){ return this._i === 0; }; /** * Indicates if there are more parts of the property value. * @return {Boolean} True if there are more parts, false if not. * @method hasNext */ PropertyValueIterator.prototype.hasNext = function(){ return (this._i < this._parts.length); }; /** * Marks the current spot in the iteration so it can be restored to * later on. * @return {void} * @method mark */ PropertyValueIterator.prototype.mark = function(){ this._marks.push(this._i); }; /** * Returns the next part of the property value or null if there is no next * part. Does not move the internal counter forward. * @return {parserlib.css.PropertyValuePart} The next part of the property value or null if there is no next * part. * @method peek */ PropertyValueIterator.prototype.peek = function(count){ return this.hasNext() ? this._parts[this._i + (count || 0)] : null; }; /** * Returns the next part of the property value or null if there is no next * part. * @return {parserlib.css.PropertyValuePart} The next part of the property value or null if there is no next * part. * @method next */ PropertyValueIterator.prototype.next = function(){ return this.hasNext() ? this._parts[this._i++] : null; }; /** * Returns the previous part of the property value or null if there is no * previous part. * @return {parserlib.css.PropertyValuePart} The previous part of the * property value or null if there is no next part. * @method previous */ PropertyValueIterator.prototype.previous = function(){ return this._i > 0 ? this._parts[--this._i] : null; }; /** * Restores the last saved bookmark. * @return {void} * @method restore */ PropertyValueIterator.prototype.restore = function(){ if (this._marks.length){ this._i = this._marks.pop(); } }; /*global SyntaxUnit, Parser, Colors*/ /** * Represents a single part of a CSS property value, meaning that it represents * just one part of the data between ":" and ";". * @param {String} text The text representation of the unit. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. * @namespace parserlib.css * @class PropertyValuePart * @extends parserlib.util.SyntaxUnit * @constructor */ function PropertyValuePart(text, line, col){ SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_VALUE_PART_TYPE); /** * Indicates the type of value unit. * @type String * @property type */ this.type = "unknown"; //figure out what type of data it is var temp; //it is a measurement? if (/^([+\-]?[\d\.]+)([a-z]+)$/i.test(text)){ //dimension this.type = "dimension"; this.value = +RegExp.$1; this.units = RegExp.$2; //try to narrow down switch(this.units.toLowerCase()){ case "em": case "rem": case "ex": case "px": case "cm": case "mm": case "in": case "pt": case "pc": case "ch": case "vh": case "vw": case "vmax": case "vmin": this.type = "length"; break; case "deg": case "rad": case "grad": this.type = "angle"; break; case "ms": case "s": this.type = "time"; break; case "hz": case "khz": this.type = "frequency"; break; case "dpi": case "dpcm": this.type = "resolution"; break; //default } } else if (/^([+\-]?[\d\.]+)%$/i.test(text)){ //percentage this.type = "percentage"; this.value = +RegExp.$1; } else if (/^([+\-]?\d+)$/i.test(text)){ //integer this.type = "integer"; this.value = +RegExp.$1; } else if (/^([+\-]?[\d\.]+)$/i.test(text)){ //number this.type = "number"; this.value = +RegExp.$1; } else if (/^#([a-f0-9]{3,6})/i.test(text)){ //hexcolor this.type = "color"; temp = RegExp.$1; if (temp.length == 3){ this.red = parseInt(temp.charAt(0)+temp.charAt(0),16); this.green = parseInt(temp.charAt(1)+temp.charAt(1),16); this.blue = parseInt(temp.charAt(2)+temp.charAt(2),16); } else { this.red = parseInt(temp.substring(0,2),16); this.green = parseInt(temp.substring(2,4),16); this.blue = parseInt(temp.substring(4,6),16); } } else if (/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i.test(text)){ //rgb() color with absolute numbers this.type = "color"; this.red = +RegExp.$1; this.green = +RegExp.$2; this.blue = +RegExp.$3; } else if (/^rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)){ //rgb() color with percentages this.type = "color"; this.red = +RegExp.$1 * 255 / 100; this.green = +RegExp.$2 * 255 / 100; this.blue = +RegExp.$3 * 255 / 100; } else if (/^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //rgba() color with absolute numbers this.type = "color"; this.red = +RegExp.$1; this.green = +RegExp.$2; this.blue = +RegExp.$3; this.alpha = +RegExp.$4; } else if (/^rgba\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //rgba() color with percentages this.type = "color"; this.red = +RegExp.$1 * 255 / 100; this.green = +RegExp.$2 * 255 / 100; this.blue = +RegExp.$3 * 255 / 100; this.alpha = +RegExp.$4; } else if (/^hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)){ //hsl() this.type = "color"; this.hue = +RegExp.$1; this.saturation = +RegExp.$2 / 100; this.lightness = +RegExp.$3 / 100; } else if (/^hsla\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //hsla() color with percentages this.type = "color"; this.hue = +RegExp.$1; this.saturation = +RegExp.$2 / 100; this.lightness = +RegExp.$3 / 100; this.alpha = +RegExp.$4; } else if (/^url\(["']?([^\)"']+)["']?\)/i.test(text)){ //URI this.type = "uri"; this.uri = RegExp.$1; } else if (/^([^\(]+)\(/i.test(text)){ this.type = "function"; this.name = RegExp.$1; this.value = text; } else if (/^["'][^"']*["']/.test(text)){ //string this.type = "string"; this.value = eval(text); } else if (Colors[text.toLowerCase()]){ //named color this.type = "color"; temp = Colors[text.toLowerCase()].substring(1); this.red = parseInt(temp.substring(0,2),16); this.green = parseInt(temp.substring(2,4),16); this.blue = parseInt(temp.substring(4,6),16); } else if (/^[\,\/]$/.test(text)){ this.type = "operator"; this.value = text; } else if (/^[a-z\-_\u0080-\uFFFF][a-z0-9\-_\u0080-\uFFFF]*$/i.test(text)){ this.type = "identifier"; this.value = text; } } PropertyValuePart.prototype = new SyntaxUnit(); PropertyValuePart.prototype.constructor = PropertyValuePart; /** * Create a new syntax unit based solely on the given token. * Convenience method for creating a new syntax unit when * it represents a single token instead of multiple. * @param {Object} token The token object to represent. * @return {parserlib.css.PropertyValuePart} The object representing the token. * @static * @method fromToken */ PropertyValuePart.fromToken = function(token){ return new PropertyValuePart(token.value, token.startLine, token.startCol); }; var Pseudos = { ":first-letter": 1, ":first-line": 1, ":before": 1, ":after": 1 }; Pseudos.ELEMENT = 1; Pseudos.CLASS = 2; Pseudos.isElement = function(pseudo){ return pseudo.indexOf("::") === 0 || Pseudos[pseudo.toLowerCase()] == Pseudos.ELEMENT; }; /*global SyntaxUnit, Parser, Specificity*/ /** * Represents an entire single selector, including all parts but not * including multiple selectors (those separated by commas). * @namespace parserlib.css * @class Selector * @extends parserlib.util.SyntaxUnit * @constructor * @param {Array} parts Array of selectors parts making up this selector. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function Selector(parts, line, col){ SyntaxUnit.call(this, parts.join(" "), line, col, Parser.SELECTOR_TYPE); /** * The parts that make up the selector. * @type Array * @property parts */ this.parts = parts; /** * The specificity of the selector. * @type parserlib.css.Specificity * @property specificity */ this.specificity = Specificity.calculate(this); } Selector.prototype = new SyntaxUnit(); Selector.prototype.constructor = Selector; /*global SyntaxUnit, Parser*/ /** * Represents a single part of a selector string, meaning a single set of * element name and modifiers. This does not include combinators such as * spaces, +, >, etc. * @namespace parserlib.css * @class SelectorPart * @extends parserlib.util.SyntaxUnit * @constructor * @param {String} elementName The element name in the selector or null * if there is no element name. * @param {Array} modifiers Array of individual modifiers for the element. * May be empty if there are none. * @param {String} text The text representation of the unit. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function SelectorPart(elementName, modifiers, text, line, col){ SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_PART_TYPE); /** * The tag name of the element to which this part * of the selector affects. * @type String * @property elementName */ this.elementName = elementName; /** * The parts that come after the element name, such as class names, IDs, * pseudo classes/elements, etc. * @type Array * @property modifiers */ this.modifiers = modifiers; } SelectorPart.prototype = new SyntaxUnit(); SelectorPart.prototype.constructor = SelectorPart; /*global SyntaxUnit, Parser*/ /** * Represents a selector modifier string, meaning a class name, element name, * element ID, pseudo rule, etc. * @namespace parserlib.css * @class SelectorSubPart * @extends parserlib.util.SyntaxUnit * @constructor * @param {String} text The text representation of the unit. * @param {String} type The type of selector modifier. * @param {int} line The line of text on which the unit resides. * @param {int} col The column of text on which the unit resides. */ function SelectorSubPart(text, type, line, col){ SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_SUB_PART_TYPE); /** * The type of modifier. * @type String * @property type */ this.type = type; /** * Some subparts have arguments, this represents them. * @type Array * @property args */ this.args = []; } SelectorSubPart.prototype = new SyntaxUnit(); SelectorSubPart.prototype.constructor = SelectorSubPart; /*global Pseudos, SelectorPart*/ /** * Represents a selector's specificity. * @namespace parserlib.css * @class Specificity * @constructor * @param {int} a Should be 1 for inline styles, zero for stylesheet styles * @param {int} b Number of ID selectors * @param {int} c Number of classes and pseudo classes * @param {int} d Number of element names and pseudo elements */ function Specificity(a, b, c, d){ this.a = a; this.b = b; this.c = c; this.d = d; } Specificity.prototype = { constructor: Specificity, /** * Compare this specificity to another. * @param {Specificity} other The other specificity to compare to. * @return {int} -1 if the other specificity is larger, 1 if smaller, 0 if equal. * @method compare */ compare: function(other){ var comps = ["a", "b", "c", "d"], i, len; for (i=0, len=comps.length; i < len; i++){ if (this[comps[i]] < other[comps[i]]){ return -1; } else if (this[comps[i]] > other[comps[i]]){ return 1; } } return 0; }, /** * Creates a numeric value for the specificity. * @return {int} The numeric value for the specificity. * @method valueOf */ valueOf: function(){ return (this.a * 1000) + (this.b * 100) + (this.c * 10) + this.d; }, /** * Returns a string representation for specificity. * @return {String} The string representation of specificity. * @method toString */ toString: function(){ return this.a + "," + this.b + "," + this.c + "," + this.d; } }; /** * Calculates the specificity of the given selector. * @param {parserlib.css.Selector} The selector to calculate specificity for. * @return {parserlib.css.Specificity} The specificity of the selector. * @static * @method calculate */ Specificity.calculate = function(selector){ var i, len, part, b=0, c=0, d=0; function updateValues(part){ var i, j, len, num, elementName = part.elementName ? part.elementName.text : "", modifier; if (elementName && elementName.charAt(elementName.length-1) != "*") { d++; } for (i=0, len=part.modifiers.length; i < len; i++){ modifier = part.modifiers[i]; switch(modifier.type){ case "class": case "attribute": c++; break; case "id": b++; break; case "pseudo": if (Pseudos.isElement(modifier.text)){ d++; } else { c++; } break; case "not": for (j=0, num=modifier.args.length; j < num; j++){ updateValues(modifier.args[j]); } } } } for (i=0, len=selector.parts.length; i < len; i++){ part = selector.parts[i]; if (part instanceof SelectorPart){ updateValues(part); } } return new Specificity(0, b, c, d); }; /*global Tokens, TokenStreamBase*/ var h = /^[0-9a-fA-F]$/, nonascii = /^[\u0080-\uFFFF]$/, nl = /\n|\r\n|\r|\f/; //----------------------------------------------------------------------------- // Helper functions //----------------------------------------------------------------------------- function isHexDigit(c){ return c !== null && h.test(c); } function isDigit(c){ return c !== null && /\d/.test(c); } function isWhitespace(c){ return c !== null && /\s/.test(c); } function isNewLine(c){ return c !== null && nl.test(c); } function isNameStart(c){ return c !== null && (/[a-z_\u0080-\uFFFF\\]/i.test(c)); } function isNameChar(c){ return c !== null && (isNameStart(c) || /[0-9\-\\]/.test(c)); } function isIdentStart(c){ return c !== null && (isNameStart(c) || /\-\\/.test(c)); } function mix(receiver, supplier){ for (var prop in supplier){ if (supplier.hasOwnProperty(prop)){ receiver[prop] = supplier[prop]; } } return receiver; } //----------------------------------------------------------------------------- // CSS Token Stream //----------------------------------------------------------------------------- /** * A token stream that produces CSS tokens. * @param {String|Reader} input The source of text to tokenize. * @constructor * @class TokenStream * @namespace parserlib.css */ function TokenStream(input){ TokenStreamBase.call(this, input, Tokens); } TokenStream.prototype = mix(new TokenStreamBase(), { /** * Overrides the TokenStreamBase method of the same name * to produce CSS tokens. * @param {variant} channel The name of the channel to use * for the next token. * @return {Object} A token object representing the next token. * @method _getToken * @private */ _getToken: function(channel){ var c, reader = this._reader, token = null, startLine = reader.getLine(), startCol = reader.getCol(); c = reader.read(); while(c){ switch(c){ /* * Potential tokens: * - COMMENT * - SLASH * - CHAR */ case "/": if(reader.peek() == "*"){ token = this.commentToken(c, startLine, startCol); } else { token = this.charToken(c, startLine, startCol); } break; /* * Potential tokens: * - DASHMATCH * - INCLUDES * - PREFIXMATCH * - SUFFIXMATCH * - SUBSTRINGMATCH * - CHAR */ case "|": case "~": case "^": case "$": case "*": if(reader.peek() == "="){ token = this.comparisonToken(c, startLine, startCol); } else { token = this.charToken(c, startLine, startCol); } break; /* * Potential tokens: * - STRING * - INVALID */ case "\"": case "'": token = this.stringToken(c, startLine, startCol); break; /* * Potential tokens: * - HASH * - CHAR */ case "#": if (isNameChar(reader.peek())){ token = this.hashToken(c, startLine, startCol); } else { token = this.charToken(c, startLine, startCol); } break; /* * Potential tokens: * - DOT * - NUMBER * - DIMENSION * - PERCENTAGE */ case ".": if (isDigit(reader.peek())){ token = this.numberToken(c, startLine, startCol); } else { token = this.charToken(c, startLine, startCol); } break; /* * Potential tokens: * - CDC * - MINUS * - NUMBER * - DIMENSION * - PERCENTAGE */ case "-": if (reader.peek() == "-"){ //could be closing HTML-style comment token = this.htmlCommentEndToken(c, startLine, startCol); } else if (isNameStart(reader.peek())){ token = this.identOrFunctionToken(c, startLine, startCol); } else { token = this.charToken(c, startLine, startCol); } break; /* * Potential tokens: * - IMPORTANT_SYM * - CHAR */ case "!": token = this.importantToken(c, startLine, startCol); break; /* * Any at-keyword or CHAR */ case "@": token = this.atRuleToken(c, startLine, startCol); break; /* * Potential tokens: * - NOT * - CHAR */ case ":": token = this.notToken(c, startLine, startCol); break; /* * Potential tokens: * - CDO * - CHAR */ case "<": token = this.htmlCommentStartToken(c, startLine, startCol); break; /* * Potential tokens: * - UNICODE_RANGE * - URL * - CHAR */ case "U": case "u": if (reader.peek() == "+"){ token = this.unicodeRangeToken(c, startLine, startCol); break; } /* falls through */ default: /* * Potential tokens: * - NUMBER * - DIMENSION * - LENGTH * - FREQ * - TIME * - EMS * - EXS * - ANGLE */ if (isDigit(c)){ token = this.numberToken(c, startLine, startCol); } else /* * Potential tokens: * - S */ if (isWhitespace(c)){ token = this.whitespaceToken(c, startLine, startCol); } else /* * Potential tokens: * - IDENT */ if (isIdentStart(c)){ token = this.identOrFunctionToken(c, startLine, startCol); } else /* * Potential tokens: * - CHAR * - PLUS */ { token = this.charToken(c, startLine, startCol); } } //make sure this token is wanted //TODO: check channel break; } if (!token && c === null){ token = this.createToken(Tokens.EOF,null,startLine,startCol); } return token; }, //------------------------------------------------------------------------- // Methods to create tokens //------------------------------------------------------------------------- /** * Produces a token based on available data and the current * reader position information. This method is called by other * private methods to create tokens and is never called directly. * @param {int} tt The token type. * @param {String} value The text value of the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @param {Object} options (Optional) Specifies a channel property * to indicate that a different channel should be scanned * and/or a hide property indicating that the token should * be hidden. * @return {Object} A token object. * @method createToken */ createToken: function(tt, value, startLine, startCol, options){ var reader = this._reader; options = options || {}; return { value: value, type: tt, channel: options.channel, endChar: options.endChar, hide: options.hide || false, startLine: startLine, startCol: startCol, endLine: reader.getLine(), endCol: reader.getCol() }; }, //------------------------------------------------------------------------- // Methods to create specific tokens //------------------------------------------------------------------------- /** * Produces a token for any at-rule. If the at-rule is unknown, then * the token is for a single "@" character. * @param {String} first The first character for the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method atRuleToken */ atRuleToken: function(first, startLine, startCol){ var rule = first, reader = this._reader, tt = Tokens.CHAR, valid = false, ident, c; /* * First, mark where we are. There are only four @ rules, * so anything else is really just an invalid token. * Basically, if this doesn't match one of the known @ * rules, just return '@' as an unknown token and allow * parsing to continue after that point. */ reader.mark(); //try to find the at-keyword ident = this.readName(); rule = first + ident; tt = Tokens.type(rule.toLowerCase()); //if it's not valid, use the first character only and reset the reader if (tt == Tokens.CHAR || tt == Tokens.UNKNOWN){ if (rule.length > 1){ tt = Tokens.UNKNOWN_SYM; } else { tt = Tokens.CHAR; rule = first; reader.reset(); } } return this.createToken(tt, rule, startLine, startCol); }, /** * Produces a character token based on the given character * and location in the stream. If there's a special (non-standard) * token name, this is used; otherwise CHAR is used. * @param {String} c The character for the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method charToken */ charToken: function(c, startLine, startCol){ var tt = Tokens.type(c); var opts = {}; if (tt == -1){ tt = Tokens.CHAR; } else { opts.endChar = Tokens[tt].endChar; } return this.createToken(tt, c, startLine, startCol, opts); }, /** * Produces a character token based on the given character * and location in the stream. If there's a special (non-standard) * token name, this is used; otherwise CHAR is used. * @param {String} first The first character for the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method commentToken */ commentToken: function(first, startLine, startCol){ var reader = this._reader, comment = this.readComment(first); return this.createToken(Tokens.COMMENT, comment, startLine, startCol); }, /** * Produces a comparison token based on the given character * and location in the stream. The next character must be * read and is already known to be an equals sign. * @param {String} c The character for the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method comparisonToken */ comparisonToken: function(c, startLine, startCol){ var reader = this._reader, comparison = c + reader.read(), tt = Tokens.type(comparison) || Tokens.CHAR; return this.createToken(tt, comparison, startLine, startCol); }, /** * Produces a hash token based on the specified information. The * first character provided is the pound sign (#) and then this * method reads a name afterward. * @param {String} first The first character (#) in the hash name. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method hashToken */ hashToken: function(first, startLine, startCol){ var reader = this._reader, name = this.readName(first); return this.createToken(Tokens.HASH, name, startLine, startCol); }, /** * Produces a CDO or CHAR token based on the specified information. The * first character is provided and the rest is read by the function to determine * the correct token to create. * @param {String} first The first character in the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method htmlCommentStartToken */ htmlCommentStartToken: function(first, startLine, startCol){ var reader = this._reader, text = first; reader.mark(); text += reader.readCount(3); if (text == "<!--"){ return this.createToken(Tokens.CDO, text, startLine, startCol); } else { reader.reset(); return this.charToken(first, startLine, startCol); } }, /** * Produces a CDC or CHAR token based on the specified information. The * first character is provided and the rest is read by the function to determine * the correct token to create. * @param {String} first The first character in the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method htmlCommentEndToken */ htmlCommentEndToken: function(first, startLine, startCol){ var reader = this._reader, text = first; reader.mark(); text += reader.readCount(2); if (text == "-->"){ return this.createToken(Tokens.CDC, text, startLine, startCol); } else { reader.reset(); return this.charToken(first, startLine, startCol); } }, /** * Produces an IDENT or FUNCTION token based on the specified information. The * first character is provided and the rest is read by the function to determine * the correct token to create. * @param {String} first The first character in the identifier. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method identOrFunctionToken */ identOrFunctionToken: function(first, startLine, startCol){ var reader = this._reader, ident = this.readName(first), tt = Tokens.IDENT; //if there's a left paren immediately after, it's a URI or function if (reader.peek() == "("){ ident += reader.read(); if (ident.toLowerCase() == "url("){ tt = Tokens.URI; ident = this.readURI(ident); //didn't find a valid URL or there's no closing paren if (ident.toLowerCase() == "url("){ tt = Tokens.FUNCTION; } } else { tt = Tokens.FUNCTION; } } else if (reader.peek() == ":"){ //might be an IE function //IE-specific functions always being with progid: if (ident.toLowerCase() == "progid"){ ident += reader.readTo("("); tt = Tokens.IE_FUNCTION; } } return this.createToken(tt, ident, startLine, startCol); }, /** * Produces an IMPORTANT_SYM or CHAR token based on the specified information. The * first character is provided and the rest is read by the function to determine * the correct token to create. * @param {String} first The first character in the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method importantToken */ importantToken: function(first, startLine, startCol){ var reader = this._reader, important = first, tt = Tokens.CHAR, temp, c; reader.mark(); c = reader.read(); while(c){ //there can be a comment in here if (c == "/"){ //if the next character isn't a star, then this isn't a valid !important token if (reader.peek() != "*"){ break; } else { temp = this.readComment(c); if (temp === ""){ //broken! break; } } } else if (isWhitespace(c)){ important += c + this.readWhitespace(); } else if (/i/i.test(c)){ temp = reader.readCount(8); if (/mportant/i.test(temp)){ important += c + temp; tt = Tokens.IMPORTANT_SYM; } break; //we're done } else { break; } c = reader.read(); } if (tt == Tokens.CHAR){ reader.reset(); return this.charToken(first, startLine, startCol); } else { return this.createToken(tt, important, startLine, startCol); } }, /** * Produces a NOT or CHAR token based on the specified information. The * first character is provided and the rest is read by the function to determine * the correct token to create. * @param {String} first The first character in the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method notToken */ notToken: function(first, startLine, startCol){ var reader = this._reader, text = first; reader.mark(); text += reader.readCount(4); if (text.toLowerCase() == ":not("){ return this.createToken(Tokens.NOT, text, startLine, startCol); } else { reader.reset(); return this.charToken(first, startLine, startCol); } }, /** * Produces a number token based on the given character * and location in the stream. This may return a token of * NUMBER, EMS, EXS, LENGTH, ANGLE, TIME, FREQ, DIMENSION, * or PERCENTAGE. * @param {String} first The first character for the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method numberToken */ numberToken: function(first, startLine, startCol){ var reader = this._reader, value = this.readNumber(first), ident, tt = Tokens.NUMBER, c = reader.peek(); if (isIdentStart(c)){ ident = this.readName(reader.read()); value += ident; if (/^em$|^ex$|^px$|^gd$|^rem$|^vw$|^vh$|^vmax$|^vmin$|^ch$|^cm$|^mm$|^in$|^pt$|^pc$/i.test(ident)){ tt = Tokens.LENGTH; } else if (/^deg|^rad$|^grad$/i.test(ident)){ tt = Tokens.ANGLE; } else if (/^ms$|^s$/i.test(ident)){ tt = Tokens.TIME; } else if (/^hz$|^khz$/i.test(ident)){ tt = Tokens.FREQ; } else if (/^dpi$|^dpcm$/i.test(ident)){ tt = Tokens.RESOLUTION; } else { tt = Tokens.DIMENSION; } } else if (c == "%"){ value += reader.read(); tt = Tokens.PERCENTAGE; } return this.createToken(tt, value, startLine, startCol); }, /** * Produces a string token based on the given character * and location in the stream. Since strings may be indicated * by single or double quotes, a failure to match starting * and ending quotes results in an INVALID token being generated. * The first character in the string is passed in and then * the rest are read up to and including the final quotation mark. * @param {String} first The first character in the string. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method stringToken */ stringToken: function(first, startLine, startCol){ var delim = first, string = first, reader = this._reader, prev = first, tt = Tokens.STRING, c = reader.read(); while(c){ string += c; //if the delimiter is found with an escapement, we're done. if (c == delim && prev != "\\"){ break; } //if there's a newline without an escapement, it's an invalid string if (isNewLine(reader.peek()) && c != "\\"){ tt = Tokens.INVALID; break; } //save previous and get next prev = c; c = reader.read(); } //if c is null, that means we're out of input and the string was never closed if (c === null){ tt = Tokens.INVALID; } return this.createToken(tt, string, startLine, startCol); }, unicodeRangeToken: function(first, startLine, startCol){ var reader = this._reader, value = first, temp, tt = Tokens.CHAR; //then it should be a unicode range if (reader.peek() == "+"){ reader.mark(); value += reader.read(); value += this.readUnicodeRangePart(true); //ensure there's an actual unicode range here if (value.length == 2){ reader.reset(); } else { tt = Tokens.UNICODE_RANGE; //if there's a ? in the first part, there can't be a second part if (value.indexOf("?") == -1){ if (reader.peek() == "-"){ reader.mark(); temp = reader.read(); temp += this.readUnicodeRangePart(false); //if there's not another value, back up and just take the first if (temp.length == 1){ reader.reset(); } else { value += temp; } } } } } return this.createToken(tt, value, startLine, startCol); }, /** * Produces a S token based on the specified information. Since whitespace * may have multiple characters, this consumes all whitespace characters * into a single token. * @param {String} first The first character in the token. * @param {int} startLine The beginning line for the character. * @param {int} startCol The beginning column for the character. * @return {Object} A token object. * @method whitespaceToken */ whitespaceToken: function(first, startLine, startCol){ var reader = this._reader, value = first + this.readWhitespace(); return this.createToken(Tokens.S, value, startLine, startCol); }, //------------------------------------------------------------------------- // Methods to read values from the string stream //------------------------------------------------------------------------- readUnicodeRangePart: function(allowQuestionMark){ var reader = this._reader, part = "", c = reader.peek(); //first read hex digits while(isHexDigit(c) && part.length < 6){ reader.read(); part += c; c = reader.peek(); } //then read question marks if allowed if (allowQuestionMark){ while(c == "?" && part.length < 6){ reader.read(); part += c; c = reader.peek(); } } //there can't be any other characters after this point return part; }, readWhitespace: function(){ var reader = this._reader, whitespace = "", c = reader.peek(); while(isWhitespace(c)){ reader.read(); whitespace += c; c = reader.peek(); } return whitespace; }, readNumber: function(first){ var reader = this._reader, number = first, hasDot = (first == "."), c = reader.peek(); while(c){ if (isDigit(c)){ number += reader.read(); } else if (c == "."){ if (hasDot){ break; } else { hasDot = true; number += reader.read(); } } else { break; } c = reader.peek(); } return number; }, readString: function(){ var reader = this._reader, delim = reader.read(), string = delim, prev = delim, c = reader.peek(); while(c){ c = reader.read(); string += c; //if the delimiter is found with an escapement, we're done. if (c == delim && prev != "\\"){ break; } //if there's a newline without an escapement, it's an invalid string if (isNewLine(reader.peek()) && c != "\\"){ string = ""; break; } //save previous and get next prev = c; c = reader.peek(); } //if c is null, that means we're out of input and the string was never closed if (c === null){ string = ""; } return string; }, readURI: function(first){ var reader = this._reader, uri = first, inner = "", c = reader.peek(); reader.mark(); //skip whitespace before while(c && isWhitespace(c)){ reader.read(); c = reader.peek(); } //it's a string if (c == "'" || c == "\""){ inner = this.readString(); } else { inner = this.readURL(); } c = reader.peek(); //skip whitespace after while(c && isWhitespace(c)){ reader.read(); c = reader.peek(); } //if there was no inner value or the next character isn't closing paren, it's not a URI if (inner === "" || c != ")"){ uri = first; reader.reset(); } else { uri += inner + reader.read(); } return uri; }, readURL: function(){ var reader = this._reader, url = "", c = reader.peek(); //TODO: Check for escape and nonascii while (/^[!#$%&\\*-~]$/.test(c)){ url += reader.read(); c = reader.peek(); } return url; }, readName: function(first){ var reader = this._reader, ident = first || "", c = reader.peek(); while(true){ if (c == "\\"){ ident += this.readEscape(reader.read()); c = reader.peek(); } else if(c && isNameChar(c)){ ident += reader.read(); c = reader.peek(); } else { break; } } return ident; }, readEscape: function(first){ var reader = this._reader, cssEscape = first || "", i = 0, c = reader.peek(); if (isHexDigit(c)){ do { cssEscape += reader.read(); c = reader.peek(); } while(c && isHexDigit(c) && ++i < 6); } if (cssEscape.length == 3 && /\s/.test(c) || cssEscape.length == 7 || cssEscape.length == 1){ reader.read(); } else { c = ""; } return cssEscape + c; }, readComment: function(first){ var reader = this._reader, comment = first || "", c = reader.read(); if (c == "*"){ while(c){ comment += c; //look for end of comment if (comment.length > 2 && c == "*" && reader.peek() == "/"){ comment += reader.read(); break; } c = reader.read(); } return comment; } else { return ""; } } }); var Tokens = [ /* * The following token names are defined in CSS3 Grammar: http://www.w3.org/TR/css3-syntax/#lexical */ //HTML-style comments { name: "CDO"}, { name: "CDC"}, //ignorables { name: "S", whitespace: true/*, channel: "ws"*/}, { name: "COMMENT", comment: true, hide: true, channel: "comment" }, //attribute equality { name: "INCLUDES", text: "~="}, { name: "DASHMATCH", text: "|="}, { name: "PREFIXMATCH", text: "^="}, { name: "SUFFIXMATCH", text: "$="}, { name: "SUBSTRINGMATCH", text: "*="}, //identifier types { name: "STRING"}, { name: "IDENT"}, { name: "HASH"}, //at-keywords { name: "IMPORT_SYM", text: "@import"}, { name: "PAGE_SYM", text: "@page"}, { name: "MEDIA_SYM", text: "@media"}, { name: "FONT_FACE_SYM", text: "@font-face"}, { name: "CHARSET_SYM", text: "@charset"}, { name: "NAMESPACE_SYM", text: "@namespace"}, { name: "VIEWPORT_SYM", text: ["@viewport", "@-ms-viewport"]}, { name: "UNKNOWN_SYM" }, //{ name: "ATKEYWORD"}, //CSS3 animations { name: "KEYFRAMES_SYM", text: [ "@keyframes", "@-webkit-keyframes", "@-moz-keyframes", "@-o-keyframes" ] }, //important symbol { name: "IMPORTANT_SYM"}, //measurements { name: "LENGTH"}, { name: "ANGLE"}, { name: "TIME"}, { name: "FREQ"}, { name: "DIMENSION"}, { name: "PERCENTAGE"}, { name: "NUMBER"}, //functions { name: "URI"}, { name: "FUNCTION"}, //Unicode ranges { name: "UNICODE_RANGE"}, /* * The following token names are defined in CSS3 Selectors: http://www.w3.org/TR/css3-selectors/#selector-syntax */ //invalid string { name: "INVALID"}, //combinators { name: "PLUS", text: "+" }, { name: "GREATER", text: ">"}, { name: "COMMA", text: ","}, { name: "TILDE", text: "~"}, //modifier { name: "NOT"}, /* * Defined in CSS3 Paged Media */ { name: "TOPLEFTCORNER_SYM", text: "@top-left-corner"}, { name: "TOPLEFT_SYM", text: "@top-left"}, { name: "TOPCENTER_SYM", text: "@top-center"}, { name: "TOPRIGHT_SYM", text: "@top-right"}, { name: "TOPRIGHTCORNER_SYM", text: "@top-right-corner"}, { name: "BOTTOMLEFTCORNER_SYM", text: "@bottom-left-corner"}, { name: "BOTTOMLEFT_SYM", text: "@bottom-left"}, { name: "BOTTOMCENTER_SYM", text: "@bottom-center"}, { name: "BOTTOMRIGHT_SYM", text: "@bottom-right"}, { name: "BOTTOMRIGHTCORNER_SYM", text: "@bottom-right-corner"}, { name: "LEFTTOP_SYM", text: "@left-top"}, { name: "LEFTMIDDLE_SYM", text: "@left-middle"}, { name: "LEFTBOTTOM_SYM", text: "@left-bottom"}, { name: "RIGHTTOP_SYM", text: "@right-top"}, { name: "RIGHTMIDDLE_SYM", text: "@right-middle"}, { name: "RIGHTBOTTOM_SYM", text: "@right-bottom"}, /* * The following token names are defined in CSS3 Media Queries: http://www.w3.org/TR/css3-mediaqueries/#syntax */ /*{ name: "MEDIA_ONLY", state: "media"}, { name: "MEDIA_NOT", state: "media"}, { name: "MEDIA_AND", state: "media"},*/ { name: "RESOLUTION", state: "media"}, /* * The following token names are not defined in any CSS specification but are used by the lexer. */ //not a real token, but useful for stupid IE filters { name: "IE_FUNCTION" }, //part of CSS3 grammar but not the Flex code { name: "CHAR" }, //TODO: Needed? //Not defined as tokens, but might as well be { name: "PIPE", text: "|" }, { name: "SLASH", text: "/" }, { name: "MINUS", text: "-" }, { name: "STAR", text: "*" }, { name: "LBRACE", endChar: "}", text: "{" }, { name: "RBRACE", text: "}" }, { name: "LBRACKET", endChar: "]", text: "[" }, { name: "RBRACKET", text: "]" }, { name: "EQUALS", text: "=" }, { name: "COLON", text: ":" }, { name: "SEMICOLON", text: ";" }, { name: "LPAREN", endChar: ")", text: "(" }, { name: "RPAREN", text: ")" }, { name: "DOT", text: "." } ]; (function(){ var nameMap = [], typeMap = {}; Tokens.UNKNOWN = -1; Tokens.unshift({name:"EOF"}); for (var i=0, len = Tokens.length; i < len; i++){ nameMap.push(Tokens[i].name); Tokens[Tokens[i].name] = i; if (Tokens[i].text){ if (Tokens[i].text instanceof Array){ for (var j=0; j < Tokens[i].text.length; j++){ typeMap[Tokens[i].text[j]] = i; } } else { typeMap[Tokens[i].text] = i; } } } Tokens.name = function(tt){ return nameMap[tt]; }; Tokens.type = function(c){ return typeMap[c] || -1; }; })(); //This file will likely change a lot! Very experimental! /*global Properties, ValidationTypes, ValidationError, PropertyValueIterator */ var Validation = { validate: function(property, value){ //normalize name var name = property.toString().toLowerCase(), parts = value.parts, expression = new PropertyValueIterator(value), spec = Properties[name], part, valid, j, count, msg, types, last, literals, max, multi, group; if (!spec) { if (name.indexOf("-") !== 0){ //vendor prefixed are ok throw new ValidationError("Unknown property '" + property + "'.", property.line, property.col); } } else if (typeof spec != "number"){ //initialization if (typeof spec == "string"){ if (spec.indexOf("||") > -1) { this.groupProperty(spec, expression); } else { this.singleProperty(spec, expression, 1); } } else if (spec.multi) { this.multiProperty(spec.multi, expression, spec.comma, spec.max || Infinity); } else if (typeof spec == "function") { spec(expression); } } }, singleProperty: function(types, expression, max, partial) { var result = false, value = expression.value, count = 0, part; while (expression.hasNext() && count < max) { result = ValidationTypes.isAny(expression, types); if (!result) { break; } count++; } if (!result) { if (expression.hasNext() && !expression.isFirst()) { part = expression.peek(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col); } } else if (expression.hasNext()) { part = expression.next(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } }, multiProperty: function (types, expression, comma, max) { var result = false, value = expression.value, count = 0, sep = false, part; while(expression.hasNext() && !result && count < max) { if (ValidationTypes.isAny(expression, types)) { count++; if (!expression.hasNext()) { result = true; } else if (comma) { if (expression.peek() == ",") { part = expression.next(); } else { break; } } } else { break; } } if (!result) { if (expression.hasNext() && !expression.isFirst()) { part = expression.peek(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { part = expression.previous(); if (comma && part == ",") { throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col); } } } else if (expression.hasNext()) { part = expression.next(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } }, groupProperty: function (types, expression, comma) { var result = false, value = expression.value, typeCount = types.split("||").length, groups = { count: 0 }, partial = false, name, part; while(expression.hasNext() && !result) { name = ValidationTypes.isAnyOfGroup(expression, types); if (name) { //no dupes if (groups[name]) { break; } else { groups[name] = 1; groups.count++; partial = true; if (groups.count == typeCount || !expression.hasNext()) { result = true; } } } else { break; } } if (!result) { if (partial && expression.hasNext()) { part = expression.peek(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } else { throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col); } } else if (expression.hasNext()) { part = expression.next(); throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col); } } }; /** * Type to use when a validation error occurs. * @class ValidationError * @namespace parserlib.util * @constructor * @param {String} message The error message. * @param {int} line The line at which the error occurred. * @param {int} col The column at which the error occurred. */ function ValidationError(message, line, col){ /** * The column at which the error occurred. * @type int * @property col */ this.col = col; /** * The line at which the error occurred. * @type int * @property line */ this.line = line; /** * The text representation of the unit. * @type String * @property text */ this.message = message; } //inherit from Error ValidationError.prototype = new Error(); //This file will likely change a lot! Very experimental! /*global Properties, Validation, ValidationError, PropertyValueIterator, console*/ var ValidationTypes = { isLiteral: function (part, literals) { var text = part.text.toString().toLowerCase(), args = literals.split(" | "), i, len, found = false; for (i=0,len=args.length; i < len && !found; i++){ if (text == args[i].toLowerCase()){ found = true; } } return found; }, isSimple: function(type) { return !!this.simple[type]; }, isComplex: function(type) { return !!this.complex[type]; }, /** * Determines if the next part(s) of the given expression * are any of the given types. */ isAny: function (expression, types) { var args = types.split(" | "), i, len, found = false; for (i=0,len=args.length; i < len && !found && expression.hasNext(); i++){ found = this.isType(expression, args[i]); } return found; }, /** * Determines if the next part(s) of the given expression * are one of a group. */ isAnyOfGroup: function(expression, types) { var args = types.split(" || "), i, len, found = false; for (i=0,len=args.length; i < len && !found; i++){ found = this.isType(expression, args[i]); } return found ? args[i-1] : false; }, /** * Determines if the next part(s) of the given expression * are of a given type. */ isType: function (expression, type) { var part = expression.peek(), result = false; if (type.charAt(0) != "<") { result = this.isLiteral(part, type); if (result) { expression.next(); } } else if (this.simple[type]) { result = this.simple[type](part); if (result) { expression.next(); } } else { result = this.complex[type](expression); } return result; }, simple: { "<absolute-size>": function(part){ return ValidationTypes.isLiteral(part, "xx-small | x-small | small | medium | large | x-large | xx-large"); }, "<attachment>": function(part){ return ValidationTypes.isLiteral(part, "scroll | fixed | local"); }, "<attr>": function(part){ return part.type == "function" && part.name == "attr"; }, "<bg-image>": function(part){ return this["<image>"](part) || this["<gradient>"](part) || part == "none"; }, "<gradient>": function(part) { return part.type == "function" && /^(?:\-(?:ms|moz|o|webkit)\-)?(?:repeating\-)?(?:radial\-|linear\-)?gradient/i.test(part); }, "<box>": function(part){ return ValidationTypes.isLiteral(part, "padding-box | border-box | content-box"); }, "<content>": function(part){ return part.type == "function" && part.name == "content"; }, "<relative-size>": function(part){ return ValidationTypes.isLiteral(part, "smaller | larger"); }, //any identifier "<ident>": function(part){ return part.type == "identifier"; }, "<length>": function(part){ if (part.type == "function" && /^(?:\-(?:ms|moz|o|webkit)\-)?calc/i.test(part)){ return true; }else{ return part.type == "length" || part.type == "number" || part.type == "integer" || part == "0"; } }, "<color>": function(part){ return part.type == "color" || part == "transparent"; }, "<number>": function(part){ return part.type == "number" || this["<integer>"](part); }, "<integer>": function(part){ return part.type == "integer"; }, "<line>": function(part){ return part.type == "integer"; }, "<angle>": function(part){ return part.type == "angle"; }, "<uri>": function(part){ return part.type == "uri"; }, "<image>": function(part){ return this["<uri>"](part); }, "<percentage>": function(part){ return part.type == "percentage" || part == "0"; }, "<border-width>": function(part){ return this["<length>"](part) || ValidationTypes.isLiteral(part, "thin | medium | thick"); }, "<border-style>": function(part){ return ValidationTypes.isLiteral(part, "none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset"); }, "<content-sizing>": function(part){ // http://www.w3.org/TR/css3-sizing/#width-height-keywords return ValidationTypes.isLiteral(part, "fill-available | -moz-available | -webkit-fill-available | max-content | -moz-max-content | -webkit-max-content | min-content | -moz-min-content | -webkit-min-content | fit-content | -moz-fit-content | -webkit-fit-content"); }, "<margin-width>": function(part){ return this["<length>"](part) || this["<percentage>"](part) || ValidationTypes.isLiteral(part, "auto"); }, "<padding-width>": function(part){ return this["<length>"](part) || this["<percentage>"](part); }, "<shape>": function(part){ return part.type == "function" && (part.name == "rect" || part.name == "inset-rect"); }, "<time>": function(part) { return part.type == "time"; }, "<flex-grow>": function(part){ return this["<number>"](part); }, "<flex-shrink>": function(part){ return this["<number>"](part); }, "<width>": function(part){ return this["<margin-width>"](part); }, "<flex-basis>": function(part){ return this["<width>"](part); }, "<flex-direction>": function(part){ return ValidationTypes.isLiteral(part, "row | row-reverse | column | column-reverse"); }, "<flex-wrap>": function(part){ return ValidationTypes.isLiteral(part, "nowrap | wrap | wrap-reverse"); } }, complex: { "<bg-position>": function(expression){ var types = this, result = false, numeric = "<percentage> | <length>", xDir = "left | right", yDir = "top | bottom", count = 0, hasNext = function() { return expression.hasNext() && expression.peek() != ","; }; while (expression.peek(count) && expression.peek(count) != ",") { count++; } /* <position> = [ [ left | center | right | top | bottom | <percentage> | <length> ] | [ left | center | right | <percentage> | <length> ] [ top | center | bottom | <percentage> | <length> ] | [ center | [ left | right ] [ <percentage> | <length> ]? ] && [ center | [ top | bottom ] [ <percentage> | <length> ]? ] ] */ if (count < 3) { if (ValidationTypes.isAny(expression, xDir + " | center | " + numeric)) { result = true; ValidationTypes.isAny(expression, yDir + " | center | " + numeric); } else if (ValidationTypes.isAny(expression, yDir)) { result = true; ValidationTypes.isAny(expression, xDir + " | center"); } } else { if (ValidationTypes.isAny(expression, xDir)) { if (ValidationTypes.isAny(expression, yDir)) { result = true; ValidationTypes.isAny(expression, numeric); } else if (ValidationTypes.isAny(expression, numeric)) { if (ValidationTypes.isAny(expression, yDir)) { result = true; ValidationTypes.isAny(expression, numeric); } else if (ValidationTypes.isAny(expression, "center")) { result = true; } } } else if (ValidationTypes.isAny(expression, yDir)) { if (ValidationTypes.isAny(expression, xDir)) { result = true; ValidationTypes.isAny(expression, numeric); } else if (ValidationTypes.isAny(expression, numeric)) { if (ValidationTypes.isAny(expression, xDir)) { result = true; ValidationTypes.isAny(expression, numeric); } else if (ValidationTypes.isAny(expression, "center")) { result = true; } } } else if (ValidationTypes.isAny(expression, "center")) { if (ValidationTypes.isAny(expression, xDir + " | " + yDir)) { result = true; ValidationTypes.isAny(expression, numeric); } } } return result; }, "<bg-size>": function(expression){ //<bg-size> = [ <length> | <percentage> | auto ]{1,2} | cover | contain var types = this, result = false, numeric = "<percentage> | <length> | auto", part, i, len; if (ValidationTypes.isAny(expression, "cover | contain")) { result = true; } else if (ValidationTypes.isAny(expression, numeric)) { result = true; ValidationTypes.isAny(expression, numeric); } return result; }, "<repeat-style>": function(expression){ //repeat-x | repeat-y | [repeat | space | round | no-repeat]{1,2} var result = false, values = "repeat | space | round | no-repeat", part; if (expression.hasNext()){ part = expression.next(); if (ValidationTypes.isLiteral(part, "repeat-x | repeat-y")) { result = true; } else if (ValidationTypes.isLiteral(part, values)) { result = true; if (expression.hasNext() && ValidationTypes.isLiteral(expression.peek(), values)) { expression.next(); } } } return result; }, "<shadow>": function(expression) { //inset? && [ <length>{2,4} && <color>? ] var result = false, count = 0, inset = false, color = false, part; if (expression.hasNext()) { if (ValidationTypes.isAny(expression, "inset")){ inset = true; } if (ValidationTypes.isAny(expression, "<color>")) { color = true; } while (ValidationTypes.isAny(expression, "<length>") && count < 4) { count++; } if (expression.hasNext()) { if (!color) { ValidationTypes.isAny(expression, "<color>"); } if (!inset) { ValidationTypes.isAny(expression, "inset"); } } result = (count >= 2 && count <= 4); } return result; }, "<x-one-radius>": function(expression) { //[ <length> | <percentage> ] [ <length> | <percentage> ]? var result = false, simple = "<length> | <percentage> | inherit"; if (ValidationTypes.isAny(expression, simple)){ result = true; ValidationTypes.isAny(expression, simple); } return result; }, "<flex>": function(expression) { // http://www.w3.org/TR/2014/WD-css-flexbox-1-20140325/#flex-property // none | [ <flex-grow> <flex-shrink>? || <flex-basis> ] // Valid syntaxes, according to https://developer.mozilla.org/en-US/docs/Web/CSS/flex#Syntax // * none // * <flex-grow> // * <flex-basis> // * <flex-grow> <flex-basis> // * <flex-grow> <flex-shrink> // * <flex-grow> <flex-shrink> <flex-basis> // * inherit var part, result = false; if (ValidationTypes.isAny(expression, "none | inherit")) { result = true; } else { if (ValidationTypes.isType(expression, "<flex-grow>")) { if (expression.peek()) { if (ValidationTypes.isType(expression, "<flex-shrink>")) { if (expression.peek()) { result = ValidationTypes.isType(expression, "<flex-basis>"); } else { result = true; } } else if (ValidationTypes.isType(expression, "<flex-basis>")) { result = expression.peek() === null; } } else { result = true; } } else if (ValidationTypes.isType(expression, "<flex-basis>")) { result = true; } } if (!result) { // Generate a more verbose error than "Expected <flex>..." part = expression.peek(); throw new ValidationError("Expected (none | [ <flex-grow> <flex-shrink>? || <flex-basis> ]) but found '" + expression.value.text + "'.", part.line, part.col); } return result; } } }; parserlib.css = { Colors :Colors, Combinator :Combinator, Parser :Parser, PropertyName :PropertyName, PropertyValue :PropertyValue, PropertyValuePart :PropertyValuePart, MediaFeature :MediaFeature, MediaQuery :MediaQuery, Selector :Selector, SelectorPart :SelectorPart, SelectorSubPart :SelectorSubPart, Specificity :Specificity, TokenStream :TokenStream, Tokens :Tokens, ValidationError :ValidationError }; })(); (function(){ for(var prop in parserlib){ exports[prop] = parserlib[prop]; } })(); },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/index.js":[function(require,module,exports){ 'use strict'; module.exports = require('./src/js/main'); },{"./src/js/main":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/main.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/class.js":[function(require,module,exports){ 'use strict'; function oldAdd(element, className) { var classes = element.className.split(' '); if (classes.indexOf(className) < 0) { classes.push(className); } element.className = classes.join(' '); } function oldRemove(element, className) { var classes = element.className.split(' '); var idx = classes.indexOf(className); if (idx >= 0) { classes.splice(idx, 1); } element.className = classes.join(' '); } exports.add = function (element, className) { if (element.classList) { element.classList.add(className); } else { oldAdd(element, className); } }; exports.remove = function (element, className) { if (element.classList) { element.classList.remove(className); } else { oldRemove(element, className); } }; exports.list = function (element) { if (element.classList) { return Array.prototype.slice.apply(element.classList); } else { return element.className.split(' '); } }; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/dom.js":[function(require,module,exports){ 'use strict'; var DOM = {}; DOM.e = function (tagName, className) { var element = document.createElement(tagName); element.className = className; return element; }; DOM.appendTo = function (child, parent) { parent.appendChild(child); return child; }; function cssGet(element, styleName) { return window.getComputedStyle(element)[styleName]; } function cssSet(element, styleName, styleValue) { if (typeof styleValue === 'number') { styleValue = styleValue.toString() + 'px'; } element.style[styleName] = styleValue; return element; } function cssMultiSet(element, obj) { for (var key in obj) { var val = obj[key]; if (typeof val === 'number') { val = val.toString() + 'px'; } element.style[key] = val; } return element; } DOM.css = function (element, styleNameOrObject, styleValue) { if (typeof styleNameOrObject === 'object') { // multiple set with object return cssMultiSet(element, styleNameOrObject); } else { if (typeof styleValue === 'undefined') { return cssGet(element, styleNameOrObject); } else { return cssSet(element, styleNameOrObject, styleValue); } } }; DOM.matches = function (element, query) { if (typeof element.matches !== 'undefined') { return element.matches(query); } else { if (typeof element.matchesSelector !== 'undefined') { return element.matchesSelector(query); } else if (typeof element.webkitMatchesSelector !== 'undefined') { return element.webkitMatchesSelector(query); } else if (typeof element.mozMatchesSelector !== 'undefined') { return element.mozMatchesSelector(query); } else if (typeof element.msMatchesSelector !== 'undefined') { return element.msMatchesSelector(query); } } }; DOM.remove = function (element) { if (typeof element.remove !== 'undefined') { element.remove(); } else { if (element.parentNode) { element.parentNode.removeChild(element); } } }; DOM.queryChildren = function (element, selector) { return Array.prototype.filter.call(element.childNodes, function (child) { return DOM.matches(child, selector); }); }; module.exports = DOM; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/event-manager.js":[function(require,module,exports){ 'use strict'; var EventElement = function (element) { this.element = element; this.events = {}; }; EventElement.prototype.bind = function (eventName, handler) { if (typeof this.events[eventName] === 'undefined') { this.events[eventName] = []; } this.events[eventName].push(handler); this.element.addEventListener(eventName, handler, false); }; EventElement.prototype.unbind = function (eventName, handler) { var isHandlerProvided = (typeof handler !== 'undefined'); this.events[eventName] = this.events[eventName].filter(function (hdlr) { if (isHandlerProvided && hdlr !== handler) { return true; } this.element.removeEventListener(eventName, hdlr, false); return false; }, this); }; EventElement.prototype.unbindAll = function () { for (var name in this.events) { this.unbind(name); } }; var EventManager = function () { this.eventElements = []; }; EventManager.prototype.eventElement = function (element) { var ee = this.eventElements.filter(function (eventElement) { return eventElement.element === element; })[0]; if (typeof ee === 'undefined') { ee = new EventElement(element); this.eventElements.push(ee); } return ee; }; EventManager.prototype.bind = function (element, eventName, handler) { this.eventElement(element).bind(eventName, handler); }; EventManager.prototype.unbind = function (element, eventName, handler) { this.eventElement(element).unbind(eventName, handler); }; EventManager.prototype.unbindAll = function () { for (var i = 0; i < this.eventElements.length; i++) { this.eventElements[i].unbindAll(); } }; EventManager.prototype.once = function (element, eventName, handler) { var ee = this.eventElement(element); var onceHandler = function (e) { ee.unbind(eventName, onceHandler); handler(e); }; ee.bind(eventName, onceHandler); }; module.exports = EventManager; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/guid.js":[function(require,module,exports){ 'use strict'; module.exports = (function () { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return function () { return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }; })(); },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/helper.js":[function(require,module,exports){ 'use strict'; var cls = require('./class'); var dom = require('./dom'); var toInt = exports.toInt = function (x) { return parseInt(x, 10) || 0; }; var clone = exports.clone = function (obj) { if (!obj) { return null; } else if (obj.constructor === Array) { return obj.map(clone); } else if (typeof obj === 'object') { var result = {}; for (var key in obj) { result[key] = clone(obj[key]); } return result; } else { return obj; } }; exports.extend = function (original, source) { var result = clone(original); for (var key in source) { result[key] = clone(source[key]); } return result; }; exports.isEditable = function (el) { return dom.matches(el, "input,[contenteditable]") || dom.matches(el, "select,[contenteditable]") || dom.matches(el, "textarea,[contenteditable]") || dom.matches(el, "button,[contenteditable]"); }; exports.removePsClasses = function (element) { var clsList = cls.list(element); for (var i = 0; i < clsList.length; i++) { var className = clsList[i]; if (className.indexOf('ps-') === 0) { cls.remove(element, className); } } }; exports.outerWidth = function (element) { return toInt(dom.css(element, 'width')) + toInt(dom.css(element, 'paddingLeft')) + toInt(dom.css(element, 'paddingRight')) + toInt(dom.css(element, 'borderLeftWidth')) + toInt(dom.css(element, 'borderRightWidth')); }; exports.startScrolling = function (element, axis) { cls.add(element, 'ps-in-scrolling'); if (typeof axis !== 'undefined') { cls.add(element, 'ps-' + axis); } else { cls.add(element, 'ps-x'); cls.add(element, 'ps-y'); } }; exports.stopScrolling = function (element, axis) { cls.remove(element, 'ps-in-scrolling'); if (typeof axis !== 'undefined') { cls.remove(element, 'ps-' + axis); } else { cls.remove(element, 'ps-x'); cls.remove(element, 'ps-y'); } }; exports.env = { isWebKit: 'WebkitAppearance' in document.documentElement.style, supportsTouch: (('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch), supportsIePointer: window.navigator.msMaxTouchPoints !== null }; },{"./class":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/class.js","./dom":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/dom.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/main.js":[function(require,module,exports){ 'use strict'; var destroy = require('./plugin/destroy'); var initialize = require('./plugin/initialize'); var update = require('./plugin/update'); module.exports = { initialize: initialize, update: update, destroy: destroy }; },{"./plugin/destroy":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/destroy.js","./plugin/initialize":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/initialize.js","./plugin/update":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/default-setting.js":[function(require,module,exports){ 'use strict'; module.exports = { handlers: ['click-rail', 'drag-scrollbar', 'keyboard', 'wheel', 'touch'], maxScrollbarLength: null, minScrollbarLength: null, scrollXMarginOffset: 0, scrollYMarginOffset: 0, suppressScrollX: false, suppressScrollY: false, swipePropagation: true, useBothWheelAxes: false, wheelPropagation: false, wheelSpeed: 1, theme: 'default' }; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/destroy.js":[function(require,module,exports){ 'use strict'; var _ = require('../lib/helper'); var dom = require('../lib/dom'); var instances = require('./instances'); module.exports = function (element) { var i = instances.get(element); if (!i) { return; } i.event.unbindAll(); dom.remove(i.scrollbarX); dom.remove(i.scrollbarY); dom.remove(i.scrollbarXRail); dom.remove(i.scrollbarYRail); _.removePsClasses(element); instances.remove(element); }; },{"../lib/dom":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/dom.js","../lib/helper":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/helper.js","./instances":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/click-rail.js":[function(require,module,exports){ 'use strict'; var instances = require('../instances'); var updateGeometry = require('../update-geometry'); var updateScroll = require('../update-scroll'); function bindClickRailHandler(element, i) { function pageOffset(el) { return el.getBoundingClientRect(); } var stopPropagation = function (e) { e.stopPropagation(); }; i.event.bind(i.scrollbarY, 'click', stopPropagation); i.event.bind(i.scrollbarYRail, 'click', function (e) { var positionTop = e.pageY - window.pageYOffset - pageOffset(i.scrollbarYRail).top; var direction = positionTop > i.scrollbarYTop ? 1 : -1; updateScroll(element, 'top', element.scrollTop + direction * i.containerHeight); updateGeometry(element); e.stopPropagation(); }); i.event.bind(i.scrollbarX, 'click', stopPropagation); i.event.bind(i.scrollbarXRail, 'click', function (e) { var positionLeft = e.pageX - window.pageXOffset - pageOffset(i.scrollbarXRail).left; var direction = positionLeft > i.scrollbarXLeft ? 1 : -1; updateScroll(element, 'left', element.scrollLeft + direction * i.containerWidth); updateGeometry(element); e.stopPropagation(); }); } module.exports = function (element) { var i = instances.get(element); bindClickRailHandler(element, i); }; },{"../instances":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js","../update-geometry":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-geometry.js","../update-scroll":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-scroll.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/drag-scrollbar.js":[function(require,module,exports){ 'use strict'; var _ = require('../../lib/helper'); var dom = require('../../lib/dom'); var instances = require('../instances'); var updateGeometry = require('../update-geometry'); var updateScroll = require('../update-scroll'); function bindMouseScrollXHandler(element, i) { var currentLeft = null; var currentPageX = null; function updateScrollLeft(deltaX) { var newLeft = currentLeft + (deltaX * i.railXRatio); var maxLeft = Math.max(0, i.scrollbarXRail.getBoundingClientRect().left) + (i.railXRatio * (i.railXWidth - i.scrollbarXWidth)); if (newLeft < 0) { i.scrollbarXLeft = 0; } else if (newLeft > maxLeft) { i.scrollbarXLeft = maxLeft; } else { i.scrollbarXLeft = newLeft; } var scrollLeft = _.toInt(i.scrollbarXLeft * (i.contentWidth - i.containerWidth) / (i.containerWidth - (i.railXRatio * i.scrollbarXWidth))) - i.negativeScrollAdjustment; updateScroll(element, 'left', scrollLeft); } var mouseMoveHandler = function (e) { updateScrollLeft(e.pageX - currentPageX); updateGeometry(element); e.stopPropagation(); e.preventDefault(); }; var mouseUpHandler = function () { _.stopScrolling(element, 'x'); i.event.unbind(i.ownerDocument, 'mousemove', mouseMoveHandler); }; i.event.bind(i.scrollbarX, 'mousedown', function (e) { currentPageX = e.pageX; currentLeft = _.toInt(dom.css(i.scrollbarX, 'left')) * i.railXRatio; _.startScrolling(element, 'x'); i.event.bind(i.ownerDocument, 'mousemove', mouseMoveHandler); i.event.once(i.ownerDocument, 'mouseup', mouseUpHandler); e.stopPropagation(); e.preventDefault(); }); } function bindMouseScrollYHandler(element, i) { var currentTop = null; var currentPageY = null; function updateScrollTop(deltaY) { var newTop = currentTop + (deltaY * i.railYRatio); var maxTop = Math.max(0, i.scrollbarYRail.getBoundingClientRect().top) + (i.railYRatio * (i.railYHeight - i.scrollbarYHeight)); if (newTop < 0) { i.scrollbarYTop = 0; } else if (newTop > maxTop) { i.scrollbarYTop = maxTop; } else { i.scrollbarYTop = newTop; } var scrollTop = _.toInt(i.scrollbarYTop * (i.contentHeight - i.containerHeight) / (i.containerHeight - (i.railYRatio * i.scrollbarYHeight))); updateScroll(element, 'top', scrollTop); } var mouseMoveHandler = function (e) { updateScrollTop(e.pageY - currentPageY); updateGeometry(element); e.stopPropagation(); e.preventDefault(); }; var mouseUpHandler = function () { _.stopScrolling(element, 'y'); i.event.unbind(i.ownerDocument, 'mousemove', mouseMoveHandler); }; i.event.bind(i.scrollbarY, 'mousedown', function (e) { currentPageY = e.pageY; currentTop = _.toInt(dom.css(i.scrollbarY, 'top')) * i.railYRatio; _.startScrolling(element, 'y'); i.event.bind(i.ownerDocument, 'mousemove', mouseMoveHandler); i.event.once(i.ownerDocument, 'mouseup', mouseUpHandler); e.stopPropagation(); e.preventDefault(); }); } module.exports = function (element) { var i = instances.get(element); bindMouseScrollXHandler(element, i); bindMouseScrollYHandler(element, i); }; },{"../../lib/dom":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/dom.js","../../lib/helper":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/helper.js","../instances":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js","../update-geometry":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-geometry.js","../update-scroll":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-scroll.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/keyboard.js":[function(require,module,exports){ 'use strict'; var _ = require('../../lib/helper'); var dom = require('../../lib/dom'); var instances = require('../instances'); var updateGeometry = require('../update-geometry'); var updateScroll = require('../update-scroll'); function bindKeyboardHandler(element, i) { var hovered = false; i.event.bind(element, 'mouseenter', function () { hovered = true; }); i.event.bind(element, 'mouseleave', function () { hovered = false; }); var shouldPrevent = false; function shouldPreventDefault(deltaX, deltaY) { var scrollTop = element.scrollTop; if (deltaX === 0) { if (!i.scrollbarYActive) { return false; } if ((scrollTop === 0 && deltaY > 0) || (scrollTop >= i.contentHeight - i.containerHeight && deltaY < 0)) { return !i.settings.wheelPropagation; } } var scrollLeft = element.scrollLeft; if (deltaY === 0) { if (!i.scrollbarXActive) { return false; } if ((scrollLeft === 0 && deltaX < 0) || (scrollLeft >= i.contentWidth - i.containerWidth && deltaX > 0)) { return !i.settings.wheelPropagation; } } return true; } i.event.bind(i.ownerDocument, 'keydown', function (e) { if ((e.isDefaultPrevented && e.isDefaultPrevented()) || e.defaultPrevented) { return; } var focused = dom.matches(i.scrollbarX, ':focus') || dom.matches(i.scrollbarY, ':focus'); if (!hovered && !focused) { return; } var activeElement = document.activeElement ? document.activeElement : i.ownerDocument.activeElement; if (activeElement) { if (activeElement.tagName === 'IFRAME') { activeElement = activeElement.contentDocument.activeElement; } else { // go deeper if element is a webcomponent while (activeElement.shadowRoot) { activeElement = activeElement.shadowRoot.activeElement; } } if (_.isEditable(activeElement)) { return; } } var deltaX = 0; var deltaY = 0; switch (e.which) { case 37: // left if (e.metaKey) { deltaX = -i.contentWidth; } else if (e.altKey) { deltaX = -i.containerWidth; } else { deltaX = -30; } break; case 38: // up if (e.metaKey) { deltaY = i.contentHeight; } else if (e.altKey) { deltaY = i.containerHeight; } else { deltaY = 30; } break; case 39: // right if (e.metaKey) { deltaX = i.contentWidth; } else if (e.altKey) { deltaX = i.containerWidth; } else { deltaX = 30; } break; case 40: // down if (e.metaKey) { deltaY = -i.contentHeight; } else if (e.altKey) { deltaY = -i.containerHeight; } else { deltaY = -30; } break; case 33: // page up deltaY = 90; break; case 32: // space bar if (e.shiftKey) { deltaY = 90; } else { deltaY = -90; } break; case 34: // page down deltaY = -90; break; case 35: // end if (e.ctrlKey) { deltaY = -i.contentHeight; } else { deltaY = -i.containerHeight; } break; case 36: // home if (e.ctrlKey) { deltaY = element.scrollTop; } else { deltaY = i.containerHeight; } break; default: return; } updateScroll(element, 'top', element.scrollTop - deltaY); updateScroll(element, 'left', element.scrollLeft + deltaX); updateGeometry(element); shouldPrevent = shouldPreventDefault(deltaX, deltaY); if (shouldPrevent) { e.preventDefault(); } }); } module.exports = function (element) { var i = instances.get(element); bindKeyboardHandler(element, i); }; },{"../../lib/dom":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/dom.js","../../lib/helper":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/helper.js","../instances":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js","../update-geometry":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-geometry.js","../update-scroll":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-scroll.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/mouse-wheel.js":[function(require,module,exports){ 'use strict'; var instances = require('../instances'); var updateGeometry = require('../update-geometry'); var updateScroll = require('../update-scroll'); function bindMouseWheelHandler(element, i) { var shouldPrevent = false; function shouldPreventDefault(deltaX, deltaY) { var scrollTop = element.scrollTop; if (deltaX === 0) { if (!i.scrollbarYActive) { return false; } if ((scrollTop === 0 && deltaY > 0) || (scrollTop >= i.contentHeight - i.containerHeight && deltaY < 0)) { return !i.settings.wheelPropagation; } } var scrollLeft = element.scrollLeft; if (deltaY === 0) { if (!i.scrollbarXActive) { return false; } if ((scrollLeft === 0 && deltaX < 0) || (scrollLeft >= i.contentWidth - i.containerWidth && deltaX > 0)) { return !i.settings.wheelPropagation; } } return true; } function getDeltaFromEvent(e) { var deltaX = e.deltaX; var deltaY = -1 * e.deltaY; if (typeof deltaX === "undefined" || typeof deltaY === "undefined") { // OS X Safari deltaX = -1 * e.wheelDeltaX / 6; deltaY = e.wheelDeltaY / 6; } if (e.deltaMode && e.deltaMode === 1) { // Firefox in deltaMode 1: Line scrolling deltaX *= 10; deltaY *= 10; } if (deltaX !== deltaX && deltaY !== deltaY/* NaN checks */) { // IE in some mouse drivers deltaX = 0; deltaY = e.wheelDelta; } if (e.shiftKey) { // reverse axis with shift key return [-deltaY, -deltaX]; } return [deltaX, deltaY]; } function shouldBeConsumedByChild(deltaX, deltaY) { var child = element.querySelector('textarea:hover, select[multiple]:hover, .ps-child:hover'); if (child) { if (!window.getComputedStyle(child).overflow.match(/(scroll|auto)/)) { // if not scrollable return false; } var maxScrollTop = child.scrollHeight - child.clientHeight; if (maxScrollTop > 0) { if (!(child.scrollTop === 0 && deltaY > 0) && !(child.scrollTop === maxScrollTop && deltaY < 0)) { return true; } } var maxScrollLeft = child.scrollLeft - child.clientWidth; if (maxScrollLeft > 0) { if (!(child.scrollLeft === 0 && deltaX < 0) && !(child.scrollLeft === maxScrollLeft && deltaX > 0)) { return true; } } } return false; } function mousewheelHandler(e) { var delta = getDeltaFromEvent(e); var deltaX = delta[0]; var deltaY = delta[1]; if (shouldBeConsumedByChild(deltaX, deltaY)) { return; } shouldPrevent = false; if (!i.settings.useBothWheelAxes) { // deltaX will only be used for horizontal scrolling and deltaY will // only be used for vertical scrolling - this is the default updateScroll(element, 'top', element.scrollTop - (deltaY * i.settings.wheelSpeed)); updateScroll(element, 'left', element.scrollLeft + (deltaX * i.settings.wheelSpeed)); } else if (i.scrollbarYActive && !i.scrollbarXActive) { // only vertical scrollbar is active and useBothWheelAxes option is // active, so let's scroll vertical bar using both mouse wheel axes if (deltaY) { updateScroll(element, 'top', element.scrollTop - (deltaY * i.settings.wheelSpeed)); } else { updateScroll(element, 'top', element.scrollTop + (deltaX * i.settings.wheelSpeed)); } shouldPrevent = true; } else if (i.scrollbarXActive && !i.scrollbarYActive) { // useBothWheelAxes and only horizontal bar is active, so use both // wheel axes for horizontal bar if (deltaX) { updateScroll(element, 'left', element.scrollLeft + (deltaX * i.settings.wheelSpeed)); } else { updateScroll(element, 'left', element.scrollLeft - (deltaY * i.settings.wheelSpeed)); } shouldPrevent = true; } updateGeometry(element); shouldPrevent = (shouldPrevent || shouldPreventDefault(deltaX, deltaY)); if (shouldPrevent) { e.stopPropagation(); e.preventDefault(); } } if (typeof window.onwheel !== "undefined") { i.event.bind(element, 'wheel', mousewheelHandler); } else if (typeof window.onmousewheel !== "undefined") { i.event.bind(element, 'mousewheel', mousewheelHandler); } } module.exports = function (element) { var i = instances.get(element); bindMouseWheelHandler(element, i); }; },{"../instances":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js","../update-geometry":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-geometry.js","../update-scroll":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-scroll.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/native-scroll.js":[function(require,module,exports){ 'use strict'; var instances = require('../instances'); var updateGeometry = require('../update-geometry'); function bindNativeScrollHandler(element, i) { i.event.bind(element, 'scroll', function () { updateGeometry(element); }); } module.exports = function (element) { var i = instances.get(element); bindNativeScrollHandler(element, i); }; },{"../instances":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js","../update-geometry":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-geometry.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/selection.js":[function(require,module,exports){ 'use strict'; var _ = require('../../lib/helper'); var instances = require('../instances'); var updateGeometry = require('../update-geometry'); var updateScroll = require('../update-scroll'); function bindSelectionHandler(element, i) { function getRangeNode() { var selection = window.getSelection ? window.getSelection() : document.getSelection ? document.getSelection() : ''; if (selection.toString().length === 0) { return null; } else { return selection.getRangeAt(0).commonAncestorContainer; } } var scrollingLoop = null; var scrollDiff = {top: 0, left: 0}; function startScrolling() { if (!scrollingLoop) { scrollingLoop = setInterval(function () { if (!instances.get(element)) { clearInterval(scrollingLoop); return; } updateScroll(element, 'top', element.scrollTop + scrollDiff.top); updateScroll(element, 'left', element.scrollLeft + scrollDiff.left); updateGeometry(element); }, 50); // every .1 sec } } function stopScrolling() { if (scrollingLoop) { clearInterval(scrollingLoop); scrollingLoop = null; } _.stopScrolling(element); } var isSelected = false; i.event.bind(i.ownerDocument, 'selectionchange', function () { if (element.contains(getRangeNode())) { isSelected = true; } else { isSelected = false; stopScrolling(); } }); i.event.bind(window, 'mouseup', function () { if (isSelected) { isSelected = false; stopScrolling(); } }); i.event.bind(window, 'keyup', function () { if (isSelected) { isSelected = false; stopScrolling(); } }); i.event.bind(window, 'mousemove', function (e) { if (isSelected) { var mousePosition = {x: e.pageX, y: e.pageY}; var containerGeometry = { left: element.offsetLeft, right: element.offsetLeft + element.offsetWidth, top: element.offsetTop, bottom: element.offsetTop + element.offsetHeight }; if (mousePosition.x < containerGeometry.left + 3) { scrollDiff.left = -5; _.startScrolling(element, 'x'); } else if (mousePosition.x > containerGeometry.right - 3) { scrollDiff.left = 5; _.startScrolling(element, 'x'); } else { scrollDiff.left = 0; } if (mousePosition.y < containerGeometry.top + 3) { if (containerGeometry.top + 3 - mousePosition.y < 5) { scrollDiff.top = -5; } else { scrollDiff.top = -20; } _.startScrolling(element, 'y'); } else if (mousePosition.y > containerGeometry.bottom - 3) { if (mousePosition.y - containerGeometry.bottom + 3 < 5) { scrollDiff.top = 5; } else { scrollDiff.top = 20; } _.startScrolling(element, 'y'); } else { scrollDiff.top = 0; } if (scrollDiff.top === 0 && scrollDiff.left === 0) { stopScrolling(); } else { startScrolling(); } } }); } module.exports = function (element) { var i = instances.get(element); bindSelectionHandler(element, i); }; },{"../../lib/helper":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/helper.js","../instances":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js","../update-geometry":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-geometry.js","../update-scroll":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-scroll.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/touch.js":[function(require,module,exports){ 'use strict'; var _ = require('../../lib/helper'); var instances = require('../instances'); var updateGeometry = require('../update-geometry'); var updateScroll = require('../update-scroll'); function bindTouchHandler(element, i, supportsTouch, supportsIePointer) { function shouldPreventDefault(deltaX, deltaY) { var scrollTop = element.scrollTop; var scrollLeft = element.scrollLeft; var magnitudeX = Math.abs(deltaX); var magnitudeY = Math.abs(deltaY); if (magnitudeY > magnitudeX) { // user is perhaps trying to swipe up/down the page if (((deltaY < 0) && (scrollTop === i.contentHeight - i.containerHeight)) || ((deltaY > 0) && (scrollTop === 0))) { return !i.settings.swipePropagation; } } else if (magnitudeX > magnitudeY) { // user is perhaps trying to swipe left/right across the page if (((deltaX < 0) && (scrollLeft === i.contentWidth - i.containerWidth)) || ((deltaX > 0) && (scrollLeft === 0))) { return !i.settings.swipePropagation; } } return true; } function applyTouchMove(differenceX, differenceY) { updateScroll(element, 'top', element.scrollTop - differenceY); updateScroll(element, 'left', element.scrollLeft - differenceX); updateGeometry(element); } var startOffset = {}; var startTime = 0; var speed = {}; var easingLoop = null; var inGlobalTouch = false; var inLocalTouch = false; function globalTouchStart() { inGlobalTouch = true; } function globalTouchEnd() { inGlobalTouch = false; } function getTouch(e) { if (e.targetTouches) { return e.targetTouches[0]; } else { // Maybe IE pointer return e; } } function shouldHandle(e) { if (e.targetTouches && e.targetTouches.length === 1) { return true; } if (e.pointerType && e.pointerType !== 'mouse' && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) { return true; } return false; } function touchStart(e) { if (shouldHandle(e)) { inLocalTouch = true; var touch = getTouch(e); startOffset.pageX = touch.pageX; startOffset.pageY = touch.pageY; startTime = (new Date()).getTime(); if (easingLoop !== null) { clearInterval(easingLoop); } e.stopPropagation(); } } function touchMove(e) { if (!inLocalTouch && i.settings.swipePropagation) { touchStart(e); } if (!inGlobalTouch && inLocalTouch && shouldHandle(e)) { var touch = getTouch(e); var currentOffset = {pageX: touch.pageX, pageY: touch.pageY}; var differenceX = currentOffset.pageX - startOffset.pageX; var differenceY = currentOffset.pageY - startOffset.pageY; applyTouchMove(differenceX, differenceY); startOffset = currentOffset; var currentTime = (new Date()).getTime(); var timeGap = currentTime - startTime; if (timeGap > 0) { speed.x = differenceX / timeGap; speed.y = differenceY / timeGap; startTime = currentTime; } if (shouldPreventDefault(differenceX, differenceY)) { e.stopPropagation(); e.preventDefault(); } } } function touchEnd() { if (!inGlobalTouch && inLocalTouch) { inLocalTouch = false; clearInterval(easingLoop); easingLoop = setInterval(function () { if (!instances.get(element)) { clearInterval(easingLoop); return; } if (!speed.x && !speed.y) { clearInterval(easingLoop); return; } if (Math.abs(speed.x) < 0.01 && Math.abs(speed.y) < 0.01) { clearInterval(easingLoop); return; } applyTouchMove(speed.x * 30, speed.y * 30); speed.x *= 0.8; speed.y *= 0.8; }, 10); } } if (supportsTouch) { i.event.bind(window, 'touchstart', globalTouchStart); i.event.bind(window, 'touchend', globalTouchEnd); i.event.bind(element, 'touchstart', touchStart); i.event.bind(element, 'touchmove', touchMove); i.event.bind(element, 'touchend', touchEnd); } else if (supportsIePointer) { if (window.PointerEvent) { i.event.bind(window, 'pointerdown', globalTouchStart); i.event.bind(window, 'pointerup', globalTouchEnd); i.event.bind(element, 'pointerdown', touchStart); i.event.bind(element, 'pointermove', touchMove); i.event.bind(element, 'pointerup', touchEnd); } else if (window.MSPointerEvent) { i.event.bind(window, 'MSPointerDown', globalTouchStart); i.event.bind(window, 'MSPointerUp', globalTouchEnd); i.event.bind(element, 'MSPointerDown', touchStart); i.event.bind(element, 'MSPointerMove', touchMove); i.event.bind(element, 'MSPointerUp', touchEnd); } } } module.exports = function (element) { if (!_.env.supportsTouch && !_.env.supportsIePointer) { return; } var i = instances.get(element); bindTouchHandler(element, i, _.env.supportsTouch, _.env.supportsIePointer); }; },{"../../lib/helper":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/helper.js","../instances":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js","../update-geometry":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-geometry.js","../update-scroll":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-scroll.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/initialize.js":[function(require,module,exports){ 'use strict'; var _ = require('../lib/helper'); var cls = require('../lib/class'); var instances = require('./instances'); var updateGeometry = require('./update-geometry'); // Handlers var handlers = { 'click-rail': require('./handler/click-rail'), 'drag-scrollbar': require('./handler/drag-scrollbar'), 'keyboard': require('./handler/keyboard'), 'wheel': require('./handler/mouse-wheel'), 'touch': require('./handler/touch'), 'selection': require('./handler/selection') }; var nativeScrollHandler = require('./handler/native-scroll'); module.exports = function (element, userSettings) { userSettings = typeof userSettings === 'object' ? userSettings : {}; cls.add(element, 'ps-container'); // Create a plugin instance. var i = instances.add(element); i.settings = _.extend(i.settings, userSettings); cls.add(element, 'ps-theme-' + i.settings.theme); i.settings.handlers.forEach(function (handlerName) { handlers[handlerName](element); }); nativeScrollHandler(element); updateGeometry(element); }; },{"../lib/class":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/class.js","../lib/helper":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/helper.js","./handler/click-rail":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/click-rail.js","./handler/drag-scrollbar":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/drag-scrollbar.js","./handler/keyboard":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/keyboard.js","./handler/mouse-wheel":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/mouse-wheel.js","./handler/native-scroll":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/native-scroll.js","./handler/selection":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/selection.js","./handler/touch":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/handler/touch.js","./instances":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js","./update-geometry":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-geometry.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js":[function(require,module,exports){ 'use strict'; var _ = require('../lib/helper'); var cls = require('../lib/class'); var defaultSettings = require('./default-setting'); var dom = require('../lib/dom'); var EventManager = require('../lib/event-manager'); var guid = require('../lib/guid'); var instances = {}; function Instance(element) { var i = this; i.settings = _.clone(defaultSettings); i.containerWidth = null; i.containerHeight = null; i.contentWidth = null; i.contentHeight = null; i.isRtl = dom.css(element, 'direction') === "rtl"; i.isNegativeScroll = (function () { var originalScrollLeft = element.scrollLeft; var result = null; element.scrollLeft = -1; result = element.scrollLeft < 0; element.scrollLeft = originalScrollLeft; return result; })(); i.negativeScrollAdjustment = i.isNegativeScroll ? element.scrollWidth - element.clientWidth : 0; i.event = new EventManager(); i.ownerDocument = element.ownerDocument || document; function focus() { cls.add(element, 'ps-focus'); } function blur() { cls.remove(element, 'ps-focus'); } i.scrollbarXRail = dom.appendTo(dom.e('div', 'ps-scrollbar-x-rail'), element); i.scrollbarX = dom.appendTo(dom.e('div', 'ps-scrollbar-x'), i.scrollbarXRail); i.scrollbarX.setAttribute('tabindex', 0); i.event.bind(i.scrollbarX, 'focus', focus); i.event.bind(i.scrollbarX, 'blur', blur); i.scrollbarXActive = null; i.scrollbarXWidth = null; i.scrollbarXLeft = null; i.scrollbarXBottom = _.toInt(dom.css(i.scrollbarXRail, 'bottom')); i.isScrollbarXUsingBottom = i.scrollbarXBottom === i.scrollbarXBottom; // !isNaN i.scrollbarXTop = i.isScrollbarXUsingBottom ? null : _.toInt(dom.css(i.scrollbarXRail, 'top')); i.railBorderXWidth = _.toInt(dom.css(i.scrollbarXRail, 'borderLeftWidth')) + _.toInt(dom.css(i.scrollbarXRail, 'borderRightWidth')); // Set rail to display:block to calculate margins dom.css(i.scrollbarXRail, 'display', 'block'); i.railXMarginWidth = _.toInt(dom.css(i.scrollbarXRail, 'marginLeft')) + _.toInt(dom.css(i.scrollbarXRail, 'marginRight')); dom.css(i.scrollbarXRail, 'display', ''); i.railXWidth = null; i.railXRatio = null; i.scrollbarYRail = dom.appendTo(dom.e('div', 'ps-scrollbar-y-rail'), element); i.scrollbarY = dom.appendTo(dom.e('div', 'ps-scrollbar-y'), i.scrollbarYRail); i.scrollbarY.setAttribute('tabindex', 0); i.event.bind(i.scrollbarY, 'focus', focus); i.event.bind(i.scrollbarY, 'blur', blur); i.scrollbarYActive = null; i.scrollbarYHeight = null; i.scrollbarYTop = null; i.scrollbarYRight = _.toInt(dom.css(i.scrollbarYRail, 'right')); i.isScrollbarYUsingRight = i.scrollbarYRight === i.scrollbarYRight; // !isNaN i.scrollbarYLeft = i.isScrollbarYUsingRight ? null : _.toInt(dom.css(i.scrollbarYRail, 'left')); i.scrollbarYOuterWidth = i.isRtl ? _.outerWidth(i.scrollbarY) : null; i.railBorderYWidth = _.toInt(dom.css(i.scrollbarYRail, 'borderTopWidth')) + _.toInt(dom.css(i.scrollbarYRail, 'borderBottomWidth')); dom.css(i.scrollbarYRail, 'display', 'block'); i.railYMarginHeight = _.toInt(dom.css(i.scrollbarYRail, 'marginTop')) + _.toInt(dom.css(i.scrollbarYRail, 'marginBottom')); dom.css(i.scrollbarYRail, 'display', ''); i.railYHeight = null; i.railYRatio = null; } function getId(element) { return element.getAttribute('data-ps-id'); } function setId(element, id) { element.setAttribute('data-ps-id', id); } function removeId(element) { element.removeAttribute('data-ps-id'); } exports.add = function (element) { var newId = guid(); setId(element, newId); instances[newId] = new Instance(element); return instances[newId]; }; exports.remove = function (element) { delete instances[getId(element)]; removeId(element); }; exports.get = function (element) { return instances[getId(element)]; }; },{"../lib/class":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/class.js","../lib/dom":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/dom.js","../lib/event-manager":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/event-manager.js","../lib/guid":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/guid.js","../lib/helper":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/helper.js","./default-setting":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/default-setting.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-geometry.js":[function(require,module,exports){ 'use strict'; var _ = require('../lib/helper'); var cls = require('../lib/class'); var dom = require('../lib/dom'); var instances = require('./instances'); var updateScroll = require('./update-scroll'); function getThumbSize(i, thumbSize) { if (i.settings.minScrollbarLength) { thumbSize = Math.max(thumbSize, i.settings.minScrollbarLength); } if (i.settings.maxScrollbarLength) { thumbSize = Math.min(thumbSize, i.settings.maxScrollbarLength); } return thumbSize; } function updateCss(element, i) { var xRailOffset = {width: i.railXWidth}; if (i.isRtl) { xRailOffset.left = i.negativeScrollAdjustment + element.scrollLeft + i.containerWidth - i.contentWidth; } else { xRailOffset.left = element.scrollLeft; } if (i.isScrollbarXUsingBottom) { xRailOffset.bottom = i.scrollbarXBottom - element.scrollTop; } else { xRailOffset.top = i.scrollbarXTop + element.scrollTop; } dom.css(i.scrollbarXRail, xRailOffset); var yRailOffset = {top: element.scrollTop, height: i.railYHeight}; if (i.isScrollbarYUsingRight) { if (i.isRtl) { yRailOffset.right = i.contentWidth - (i.negativeScrollAdjustment + element.scrollLeft) - i.scrollbarYRight - i.scrollbarYOuterWidth; } else { yRailOffset.right = i.scrollbarYRight - element.scrollLeft; } } else { if (i.isRtl) { yRailOffset.left = i.negativeScrollAdjustment + element.scrollLeft + i.containerWidth * 2 - i.contentWidth - i.scrollbarYLeft - i.scrollbarYOuterWidth; } else { yRailOffset.left = i.scrollbarYLeft + element.scrollLeft; } } dom.css(i.scrollbarYRail, yRailOffset); dom.css(i.scrollbarX, {left: i.scrollbarXLeft, width: i.scrollbarXWidth - i.railBorderXWidth}); dom.css(i.scrollbarY, {top: i.scrollbarYTop, height: i.scrollbarYHeight - i.railBorderYWidth}); } module.exports = function (element) { var i = instances.get(element); i.containerWidth = element.clientWidth; i.containerHeight = element.clientHeight; i.contentWidth = element.scrollWidth; i.contentHeight = element.scrollHeight; var existingRails; if (!element.contains(i.scrollbarXRail)) { existingRails = dom.queryChildren(element, '.ps-scrollbar-x-rail'); if (existingRails.length > 0) { existingRails.forEach(function (rail) { dom.remove(rail); }); } dom.appendTo(i.scrollbarXRail, element); } if (!element.contains(i.scrollbarYRail)) { existingRails = dom.queryChildren(element, '.ps-scrollbar-y-rail'); if (existingRails.length > 0) { existingRails.forEach(function (rail) { dom.remove(rail); }); } dom.appendTo(i.scrollbarYRail, element); } if (!i.settings.suppressScrollX && i.containerWidth + i.settings.scrollXMarginOffset < i.contentWidth) { i.scrollbarXActive = true; i.railXWidth = i.containerWidth - i.railXMarginWidth; i.railXRatio = i.containerWidth / i.railXWidth; i.scrollbarXWidth = getThumbSize(i, _.toInt(i.railXWidth * i.containerWidth / i.contentWidth)); i.scrollbarXLeft = _.toInt((i.negativeScrollAdjustment + element.scrollLeft) * (i.railXWidth - i.scrollbarXWidth) / (i.contentWidth - i.containerWidth)); } else { i.scrollbarXActive = false; } if (!i.settings.suppressScrollY && i.containerHeight + i.settings.scrollYMarginOffset < i.contentHeight) { i.scrollbarYActive = true; i.railYHeight = i.containerHeight - i.railYMarginHeight; i.railYRatio = i.containerHeight / i.railYHeight; i.scrollbarYHeight = getThumbSize(i, _.toInt(i.railYHeight * i.containerHeight / i.contentHeight)); i.scrollbarYTop = _.toInt(element.scrollTop * (i.railYHeight - i.scrollbarYHeight) / (i.contentHeight - i.containerHeight)); } else { i.scrollbarYActive = false; } if (i.scrollbarXLeft >= i.railXWidth - i.scrollbarXWidth) { i.scrollbarXLeft = i.railXWidth - i.scrollbarXWidth; } if (i.scrollbarYTop >= i.railYHeight - i.scrollbarYHeight) { i.scrollbarYTop = i.railYHeight - i.scrollbarYHeight; } updateCss(element, i); if (i.scrollbarXActive) { cls.add(element, 'ps-active-x'); } else { cls.remove(element, 'ps-active-x'); i.scrollbarXWidth = 0; i.scrollbarXLeft = 0; updateScroll(element, 'left', 0); } if (i.scrollbarYActive) { cls.add(element, 'ps-active-y'); } else { cls.remove(element, 'ps-active-y'); i.scrollbarYHeight = 0; i.scrollbarYTop = 0; updateScroll(element, 'top', 0); } }; },{"../lib/class":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/class.js","../lib/dom":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/dom.js","../lib/helper":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/helper.js","./instances":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js","./update-scroll":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-scroll.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-scroll.js":[function(require,module,exports){ 'use strict'; var instances = require('./instances'); var lastTop; var lastLeft; var createDOMEvent = function (name) { var event = document.createEvent("Event"); event.initEvent(name, true, true); return event; }; module.exports = function (element, axis, value) { if (typeof element === 'undefined') { throw 'You must provide an element to the update-scroll function'; } if (typeof axis === 'undefined') { throw 'You must provide an axis to the update-scroll function'; } if (typeof value === 'undefined') { throw 'You must provide a value to the update-scroll function'; } if (axis === 'top' && value <= 0) { element.scrollTop = value = 0; // don't allow negative scroll element.dispatchEvent(createDOMEvent('ps-y-reach-start')); } if (axis === 'left' && value <= 0) { element.scrollLeft = value = 0; // don't allow negative scroll element.dispatchEvent(createDOMEvent('ps-x-reach-start')); } var i = instances.get(element); if (axis === 'top' && value >= i.contentHeight - i.containerHeight) { // don't allow scroll past container value = i.contentHeight - i.containerHeight; if (value - element.scrollTop <= 1) { // mitigates rounding errors on non-subpixel scroll values value = element.scrollTop; } else { element.scrollTop = value; } element.dispatchEvent(createDOMEvent('ps-y-reach-end')); } if (axis === 'left' && value >= i.contentWidth - i.containerWidth) { // don't allow scroll past container value = i.contentWidth - i.containerWidth; if (value - element.scrollLeft <= 1) { // mitigates rounding errors on non-subpixel scroll values value = element.scrollLeft; } else { element.scrollLeft = value; } element.dispatchEvent(createDOMEvent('ps-x-reach-end')); } if (!lastTop) { lastTop = element.scrollTop; } if (!lastLeft) { lastLeft = element.scrollLeft; } if (axis === 'top' && value < lastTop) { element.dispatchEvent(createDOMEvent('ps-scroll-up')); } if (axis === 'top' && value > lastTop) { element.dispatchEvent(createDOMEvent('ps-scroll-down')); } if (axis === 'left' && value < lastLeft) { element.dispatchEvent(createDOMEvent('ps-scroll-left')); } if (axis === 'left' && value > lastLeft) { element.dispatchEvent(createDOMEvent('ps-scroll-right')); } if (axis === 'top') { element.scrollTop = lastTop = value; element.dispatchEvent(createDOMEvent('ps-scroll-y')); } if (axis === 'left') { element.scrollLeft = lastLeft = value; element.dispatchEvent(createDOMEvent('ps-scroll-x')); } }; },{"./instances":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update.js":[function(require,module,exports){ 'use strict'; var _ = require('../lib/helper'); var dom = require('../lib/dom'); var instances = require('./instances'); var updateGeometry = require('./update-geometry'); var updateScroll = require('./update-scroll'); module.exports = function (element) { var i = instances.get(element); if (!i) { return; } // Recalcuate negative scrollLeft adjustment i.negativeScrollAdjustment = i.isNegativeScroll ? element.scrollWidth - element.clientWidth : 0; // Recalculate rail margins dom.css(i.scrollbarXRail, 'display', 'block'); dom.css(i.scrollbarYRail, 'display', 'block'); i.railXMarginWidth = _.toInt(dom.css(i.scrollbarXRail, 'marginLeft')) + _.toInt(dom.css(i.scrollbarXRail, 'marginRight')); i.railYMarginHeight = _.toInt(dom.css(i.scrollbarYRail, 'marginTop')) + _.toInt(dom.css(i.scrollbarYRail, 'marginBottom')); // Hide scrollbars not to affect scrollWidth and scrollHeight dom.css(i.scrollbarXRail, 'display', 'none'); dom.css(i.scrollbarYRail, 'display', 'none'); updateGeometry(element); // Update top/left scroll to trigger events updateScroll(element, 'top', element.scrollTop); updateScroll(element, 'left', element.scrollLeft); dom.css(i.scrollbarXRail, 'display', ''); dom.css(i.scrollbarYRail, 'display', ''); }; },{"../lib/dom":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/dom.js","../lib/helper":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/lib/helper.js","./instances":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/instances.js","./update-geometry":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-geometry.js","./update-scroll":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/src/js/plugin/update-scroll.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/process/browser.js":[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/querystringify/index.js":[function(require,module,exports){ 'use strict'; var has = Object.prototype.hasOwnProperty; /** * Decode a URI encoded string. * * @param {String} input The URI encoded string. * @returns {String} The decoded string. * @api private */ function decode(input) { return decodeURIComponent(input.replace(/\+/g, ' ')); } /** * Simple query string parser. * * @param {String} query The query string that needs to be parsed. * @returns {Object} * @api public */ function querystring(query) { var parser = /([^=?&]+)=?([^&]*)/g , result = {} , part; // // Little nifty parsing hack, leverage the fact that RegExp.exec increments // the lastIndex property so we can continue executing this loop until we've // parsed all results. // for (; part = parser.exec(query); result[decode(part[1])] = decode(part[2]) ); return result; } /** * Transform a query string to an object. * * @param {Object} obj Object that should be transformed. * @param {String} prefix Optional prefix. * @returns {String} * @api public */ function querystringify(obj, prefix) { prefix = prefix || ''; var pairs = []; // // Optionally prefix with a '?' if needed // if ('string' !== typeof prefix) prefix = '?'; for (var key in obj) { if (has.call(obj, key)) { pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key])); } } return pairs.length ? prefix + pairs.join('&') : ''; } // // Expose the module. // exports.stringify = querystringify; exports.parse = querystring; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/requires-port/index.js":[function(require,module,exports){ 'use strict'; /** * Check if we're required to add a port number. * * @see https://url.spec.whatwg.org/#default-port * @param {Number|String} port Port number we need to check * @param {String} protocol Protocol we need to check against. * @returns {Boolean} Is it a default port for the given protocol * @api private */ module.exports = function required(port, protocol) { protocol = protocol.split(':')[0]; port = +port; if (!port) return false; switch (protocol) { case 'http': case 'ws': return port !== 80; case 'https': case 'wss': return port !== 443; case 'ftp': return port !== 21; case 'gopher': return port !== 70; case 'file': return false; } return port !== 0; }; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/svg4everybody/dist/svg4everybody.js":[function(require,module,exports){ !function(root, factory) { "function" == typeof define && define.amd ? // AMD. Register as an anonymous module unless amdModuleId is set define([], function() { return root.svg4everybody = factory(); }) : "object" == typeof module && module.exports ? // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory() : root.svg4everybody = factory(); }(this, function() { /*! svg4everybody v2.1.8 | github.com/jonathantneal/svg4everybody */ function embed(parent, svg, target) { // if the target exists if (target) { // create a document fragment to hold the contents of the target var fragment = document.createDocumentFragment(), viewBox = !svg.hasAttribute("viewBox") && target.getAttribute("viewBox"); // conditionally set the viewBox on the svg viewBox && svg.setAttribute("viewBox", viewBox); // copy the contents of the clone into the fragment for (// clone the target var clone = target.cloneNode(!0); clone.childNodes.length; ) { fragment.appendChild(clone.firstChild); } // append the fragment into the svg parent.appendChild(fragment); } } function loadreadystatechange(xhr) { // listen to changes in the request xhr.onreadystatechange = function() { // if the request is ready if (4 === xhr.readyState) { // get the cached html document var cachedDocument = xhr._cachedDocument; // ensure the cached html document based on the xhr response cachedDocument || (cachedDocument = xhr._cachedDocument = document.implementation.createHTMLDocument(""), cachedDocument.body.innerHTML = xhr.responseText, xhr._cachedTarget = {}), // clear the xhr embeds list and embed each item xhr._embeds.splice(0).map(function(item) { // get the cached target var target = xhr._cachedTarget[item.id]; // ensure the cached target target || (target = xhr._cachedTarget[item.id] = cachedDocument.getElementById(item.id)), // embed the target into the svg embed(item.parent, item.svg, target); }); } }, // test the ready state change immediately xhr.onreadystatechange(); } function svg4everybody(rawopts) { function oninterval() { // while the index exists in the live <use> collection for (// get the cached <use> index var index = 0; index < uses.length; ) { // get the current <use> var use = uses[index], parent = use.parentNode, svg = getSVGAncestor(parent); if (svg) { var src = use.getAttribute("xlink:href") || use.getAttribute("href"); !src && opts.attributeName && (src = use.getAttribute(opts.attributeName)); if (polyfill) { if (!opts.validate || opts.validate(src, svg, use)) { // remove the <use> element parent.removeChild(use); // parse the src and get the url and id var srcSplit = src.split("#"), url = srcSplit.shift(), id = srcSplit.join("#"); // if the link is external if (url.length) { // get the cached xhr request var xhr = requests[url]; // ensure the xhr request exists xhr || (xhr = requests[url] = new XMLHttpRequest(), xhr.open("GET", url), xhr.send(), xhr._embeds = []), // add the svg and id as an item to the xhr embeds list xhr._embeds.push({ parent: parent, svg: svg, id: id }), // prepare the xhr ready state change event loadreadystatechange(xhr); } else { // embed the local id into the svg embed(parent, svg, document.getElementById(id)); } } else { // increase the index when the previous value was not "valid" ++index, ++numberOfSvgUseElementsToBypass; } } } else { // increase the index when the previous value was not "valid" ++index; } } // continue the interval (!uses.length || uses.length - numberOfSvgUseElementsToBypass > 0) && requestAnimationFrame(oninterval, 67); } var polyfill, opts = Object(rawopts), newerIEUA = /\bTrident\/[567]\b|\bMSIE (?:9|10)\.0\b/, webkitUA = /\bAppleWebKit\/(\d+)\b/, olderEdgeUA = /\bEdge\/12\.(\d+)\b/, edgeUA = /\bEdge\/.(\d+)\b/, inIframe = window.top !== window.self; polyfill = "polyfill" in opts ? opts.polyfill : newerIEUA.test(navigator.userAgent) || (navigator.userAgent.match(olderEdgeUA) || [])[1] < 10547 || (navigator.userAgent.match(webkitUA) || [])[1] < 537 || edgeUA.test(navigator.userAgent) && inIframe; // create xhr requests object var requests = {}, requestAnimationFrame = window.requestAnimationFrame || setTimeout, uses = document.getElementsByTagName("use"), numberOfSvgUseElementsToBypass = 0; // conditionally start the interval if the polyfill is active polyfill && oninterval(); } function getSVGAncestor(node) { for (var svg = node; "svg" !== svg.nodeName.toLowerCase() && (svg = svg.parentNode); ) {} return svg; } return svg4everybody; }); },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/ticky/ticky-browser.js":[function(require,module,exports){ var si = typeof setImmediate === 'function', tick; if (si) { tick = function (fn) { setImmediate(fn); }; } else { tick = function (fn) { setTimeout(fn, 0); }; } module.exports = tick; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/url-parse/index.js":[function(require,module,exports){ (function (global){ 'use strict'; var required = require('requires-port') , qs = require('querystringify') , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//; /** * These are the parse rules for the URL parser, it informs the parser * about: * * 0. The char it Needs to parse, if it's a string it should be done using * indexOf, RegExp using exec and NaN means set as current value. * 1. The property we should set when parsing this value. * 2. Indication if it's backwards or forward parsing, when set as number it's * the value of extra chars that should be split off. * 3. Inherit from location if non existing in the parser. * 4. `toLowerCase` the resulting value. */ var rules = [ ['#', 'hash'], // Extract from the back. ['?', 'query'], // Extract from the back. ['/', 'pathname'], // Extract from the back. ['@', 'auth', 1], // Extract from the front. [NaN, 'host', undefined, 1, 1], // Set left over value. [/:(\d+)$/, 'port', undefined, 1], // RegExp the back. [NaN, 'hostname', undefined, 1, 1] // Set left over. ]; /** * These properties should not be copied or inherited from. This is only needed * for all non blob URL's as a blob URL does not include a hash, only the * origin. * * @type {Object} * @private */ var ignore = { hash: 1, query: 1 }; /** * The location object differs when your code is loaded through a normal page, * Worker or through a worker using a blob. And with the blobble begins the * trouble as the location object will contain the URL of the blob, not the * location of the page where our code is loaded in. The actual origin is * encoded in the `pathname` so we can thankfully generate a good "default" * location from it so we can generate proper relative URL's again. * * @param {Object|String} loc Optional default location object. * @returns {Object} lolcation object. * @api public */ function lolcation(loc) { loc = loc || global.location || {}; var finaldestination = {} , type = typeof loc , key; if ('blob:' === loc.protocol) { finaldestination = new URL(unescape(loc.pathname), {}); } else if ('string' === type) { finaldestination = new URL(loc, {}); for (key in ignore) delete finaldestination[key]; } else if ('object' === type) { for (key in loc) { if (key in ignore) continue; finaldestination[key] = loc[key]; } if (finaldestination.slashes === undefined) { finaldestination.slashes = slashes.test(loc.href); } } return finaldestination; } /** * @typedef ProtocolExtract * @type Object * @property {String} protocol Protocol matched in the URL, in lowercase. * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`. * @property {String} rest Rest of the URL that is not part of the protocol. */ /** * Extract protocol information from a URL with/without double slash ("//"). * * @param {String} address URL we want to extract from. * @return {ProtocolExtract} Extracted information. * @api private */ function extractProtocol(address) { var match = protocolre.exec(address); return { protocol: match[1] ? match[1].toLowerCase() : '', slashes: !!match[2], rest: match[3] }; } /** * Resolve a relative URL pathname against a base URL pathname. * * @param {String} relative Pathname of the relative URL. * @param {String} base Pathname of the base URL. * @return {String} Resolved pathname. * @api private */ function resolve(relative, base) { var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')) , i = path.length , last = path[i - 1] , unshift = false , up = 0; while (i--) { if (path[i] === '.') { path.splice(i, 1); } else if (path[i] === '..') { path.splice(i, 1); up++; } else if (up) { if (i === 0) unshift = true; path.splice(i, 1); up--; } } if (unshift) path.unshift(''); if (last === '.' || last === '..') path.push(''); return path.join('/'); } /** * The actual URL instance. Instead of returning an object we've opted-in to * create an actual constructor as it's much more memory efficient and * faster and it pleases my OCD. * * @constructor * @param {String} address URL we want to parse. * @param {Object|String} location Location defaults for relative paths. * @param {Boolean|Function} parser Parser for the query string. * @api public */ function URL(address, location, parser) { if (!(this instanceof URL)) { return new URL(address, location, parser); } var relative, extracted, parse, instruction, index, key , instructions = rules.slice() , type = typeof location , url = this , i = 0; // // The following if statements allows this module two have compatibility with // 2 different API: // // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments // where the boolean indicates that the query string should also be parsed. // // 2. The `URL` interface of the browser which accepts a URL, object as // arguments. The supplied object will be used as default values / fall-back // for relative paths. // if ('object' !== type && 'string' !== type) { parser = location; location = null; } if (parser && 'function' !== typeof parser) parser = qs.parse; location = lolcation(location); // // Extract protocol information before running the instructions. // extracted = extractProtocol(address || ''); relative = !extracted.protocol && !extracted.slashes; url.slashes = extracted.slashes || relative && location.slashes; url.protocol = extracted.protocol || location.protocol || ''; address = extracted.rest; // // When the authority component is absent the URL starts with a path // component. // if (!extracted.slashes) instructions[2] = [/(.*)/, 'pathname']; for (; i < instructions.length; i++) { instruction = instructions[i]; parse = instruction[0]; key = instruction[1]; if (parse !== parse) { url[key] = address; } else if ('string' === typeof parse) { if (~(index = address.indexOf(parse))) { if ('number' === typeof instruction[2]) { url[key] = address.slice(0, index); address = address.slice(index + instruction[2]); } else { url[key] = address.slice(index); address = address.slice(0, index); } } } else if ((index = parse.exec(address))) { url[key] = index[1]; address = address.slice(0, index.index); } url[key] = url[key] || ( relative && instruction[3] ? location[key] || '' : '' ); // // Hostname, host and protocol should be lowercased so they can be used to // create a proper `origin`. // if (instruction[4]) url[key] = url[key].toLowerCase(); } // // Also parse the supplied query string in to an object. If we're supplied // with a custom parser as function use that instead of the default build-in // parser. // if (parser) url.query = parser(url.query); // // If the URL is relative, resolve the pathname against the base URL. // if ( relative && location.slashes && url.pathname.charAt(0) !== '/' && (url.pathname !== '' || location.pathname !== '') ) { url.pathname = resolve(url.pathname, location.pathname); } // // We should not add port numbers if they are already the default port number // for a given protocol. As the host also contains the port number we're going // override it with the hostname which contains no port number. // if (!required(url.port, url.protocol)) { url.host = url.hostname; url.port = ''; } // // Parse down the `auth` for the username and password. // url.username = url.password = ''; if (url.auth) { instruction = url.auth.split(':'); url.username = instruction[0] || ''; url.password = instruction[1] || ''; } url.origin = url.protocol && url.host && url.protocol !== 'file:' ? url.protocol +'//'+ url.host : 'null'; // // The href is just the compiled result. // url.href = url.toString(); } /** * This is convenience method for changing properties in the URL instance to * insure that they all propagate correctly. * * @param {String} part Property we need to adjust. * @param {Mixed} value The newly assigned value. * @param {Boolean|Function} fn When setting the query, it will be the function * used to parse the query. * When setting the protocol, double slash will be * removed from the final url if it is true. * @returns {URL} * @api public */ function set(part, value, fn) { var url = this; switch (part) { case 'query': if ('string' === typeof value && value.length) { value = (fn || qs.parse)(value); } url[part] = value; break; case 'port': url[part] = value; if (!required(value, url.protocol)) { url.host = url.hostname; url[part] = ''; } else if (value) { url.host = url.hostname +':'+ value; } break; case 'hostname': url[part] = value; if (url.port) value += ':'+ url.port; url.host = value; break; case 'host': url[part] = value; if (/:\d+$/.test(value)) { value = value.split(':'); url.port = value.pop(); url.hostname = value.join(':'); } else { url.hostname = value; url.port = ''; } break; case 'protocol': url.protocol = value.toLowerCase(); url.slashes = !fn; break; case 'pathname': url.pathname = value.length && value.charAt(0) !== '/' ? '/' + value : value; break; default: url[part] = value; } for (var i = 0; i < rules.length; i++) { var ins = rules[i]; if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); } url.origin = url.protocol && url.host && url.protocol !== 'file:' ? url.protocol +'//'+ url.host : 'null'; url.href = url.toString(); return url; } /** * Transform the properties back in to a valid and full URL string. * * @param {Function} stringify Optional query stringify function. * @returns {String} * @api public */ function toString(stringify) { if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify; var query , url = this , protocol = url.protocol; if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':'; var result = protocol + (url.slashes ? '//' : ''); if (url.username) { result += url.username; if (url.password) result += ':'+ url.password; result += '@'; } result += url.host + url.pathname; query = 'object' === typeof url.query ? stringify(url.query) : url.query; if (query) result += '?' !== query.charAt(0) ? '?'+ query : query; if (url.hash) result += url.hash; return result; } URL.prototype = { set: set, toString: toString }; // // Expose the URL parser and some additional properties that might be useful for // others or testing. // URL.extractProtocol = extractProtocol; URL.location = lolcation; URL.qs = qs; module.exports = URL; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"querystringify":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/querystringify/index.js","requires-port":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/requires-port/index.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/util/node_modules/inherits/inherits_browser.js":[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/util/support/isBufferBrowser.js":[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/util/util.js":[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/util/support/isBufferBrowser.js","_process":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/process/browser.js","inherits":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/util/node_modules/inherits/inherits_browser.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/uuid/index.js":[function(require,module,exports){ var v1 = require('./v1'); var v4 = require('./v4'); var uuid = v4; uuid.v1 = v1; uuid.v4 = v4; module.exports = uuid; },{"./v1":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/uuid/v1.js","./v4":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/uuid/v4.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/uuid/lib/bytesToUuid.js":[function(require,module,exports){ /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid(buf, offset) { var i = offset || 0; var bth = byteToHex; return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]]; } module.exports = bytesToUuid; },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/uuid/lib/rng-browser.js":[function(require,module,exports){ (function (global){ // Unique ID creation requires a high quality random # generator. In the // browser this is a little complicated due to unknown quality of Math.random() // and inconsistent support for the `crypto` API. We do the best we can via // feature-detection var rng; var crypto = global.crypto || global.msCrypto; // for IE 11 if (crypto && crypto.getRandomValues) { // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef rng = function whatwgRNG() { crypto.getRandomValues(rnds8); return rnds8; }; } if (!rng) { // Math.random()-based (RNG) // // If all else fails, use Math.random(). It's fast, but is of unspecified // quality. var rnds = new Array(16); rng = function() { for (var i = 0, r; i < 16; i++) { if ((i & 0x03) === 0) r = Math.random() * 0x100000000; rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; } return rnds; }; } module.exports = rng; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/uuid/v1.js":[function(require,module,exports){ var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid'); // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html // random #'s we need to init node and clockseq var _seedBytes = rng(); // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) var _nodeId = [ _seedBytes[0] | 0x01, _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] ]; // Per 4.2.2, randomize (14 bit) clockseq var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff; // Previous uuid creation time var _lastMSecs = 0, _lastNSecs = 0; // See https://github.com/broofa/node-uuid for API details function v1(options, buf, offset) { var i = buf && offset || 0; var b = buf || []; options = options || {}; var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` var node = options.node || _nodeId; for (var n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf ? buf : bytesToUuid(b); } module.exports = v1; },{"./lib/bytesToUuid":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/uuid/lib/bytesToUuid.js","./lib/rng":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/uuid/lib/rng-browser.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/uuid/v4.js":[function(require,module,exports){ var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid'); function v4(options, buf, offset) { var i = buf && offset || 0; if (typeof(options) == 'string') { buf = options == 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); } module.exports = v4; },{"./lib/bytesToUuid":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/uuid/lib/bytesToUuid.js","./lib/rng":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/uuid/lib/rng-browser.js"}],"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/webfontloader/webfontloader.js":[function(require,module,exports){ /* Web Font Loader v1.6.28 - (c) Adobe Systems, Google. License: Apache 2.0 */(function(){function aa(a,b,c){return a.call.apply(a.bind,arguments)}function ba(a,b,c){if(!a)throw Error();if(2<arguments.length){var d=Array.prototype.slice.call(arguments,2);return function(){var c=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(c,d);return a.apply(b,c)}}return function(){return a.apply(b,arguments)}}function p(a,b,c){p=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?aa:ba;return p.apply(null,arguments)}var q=Date.now||function(){return+new Date};function ca(a,b){this.a=a;this.o=b||a;this.c=this.o.document}var da=!!window.FontFace;function t(a,b,c,d){b=a.c.createElement(b);if(c)for(var e in c)c.hasOwnProperty(e)&&("style"==e?b.style.cssText=c[e]:b.setAttribute(e,c[e]));d&&b.appendChild(a.c.createTextNode(d));return b}function u(a,b,c){a=a.c.getElementsByTagName(b)[0];a||(a=document.documentElement);a.insertBefore(c,a.lastChild)}function v(a){a.parentNode&&a.parentNode.removeChild(a)} function w(a,b,c){b=b||[];c=c||[];for(var d=a.className.split(/\s+/),e=0;e<b.length;e+=1){for(var f=!1,g=0;g<d.length;g+=1)if(b[e]===d[g]){f=!0;break}f||d.push(b[e])}b=[];for(e=0;e<d.length;e+=1){f=!1;for(g=0;g<c.length;g+=1)if(d[e]===c[g]){f=!0;break}f||b.push(d[e])}a.className=b.join(" ").replace(/\s+/g," ").replace(/^\s+|\s+$/,"")}function y(a,b){for(var c=a.className.split(/\s+/),d=0,e=c.length;d<e;d++)if(c[d]==b)return!0;return!1} function ea(a){return a.o.location.hostname||a.a.location.hostname}function z(a,b,c){function d(){m&&e&&f&&(m(g),m=null)}b=t(a,"link",{rel:"stylesheet",href:b,media:"all"});var e=!1,f=!0,g=null,m=c||null;da?(b.onload=function(){e=!0;d()},b.onerror=function(){e=!0;g=Error("Stylesheet failed to load");d()}):setTimeout(function(){e=!0;d()},0);u(a,"head",b)} function A(a,b,c,d){var e=a.c.getElementsByTagName("head")[0];if(e){var f=t(a,"script",{src:b}),g=!1;f.onload=f.onreadystatechange=function(){g||this.readyState&&"loaded"!=this.readyState&&"complete"!=this.readyState||(g=!0,c&&c(null),f.onload=f.onreadystatechange=null,"HEAD"==f.parentNode.tagName&&e.removeChild(f))};e.appendChild(f);setTimeout(function(){g||(g=!0,c&&c(Error("Script load timeout")))},d||5E3);return f}return null};function B(){this.a=0;this.c=null}function C(a){a.a++;return function(){a.a--;D(a)}}function E(a,b){a.c=b;D(a)}function D(a){0==a.a&&a.c&&(a.c(),a.c=null)};function F(a){this.a=a||"-"}F.prototype.c=function(a){for(var b=[],c=0;c<arguments.length;c++)b.push(arguments[c].replace(/[\W_]+/g,"").toLowerCase());return b.join(this.a)};function G(a,b){this.c=a;this.f=4;this.a="n";var c=(b||"n4").match(/^([nio])([1-9])$/i);c&&(this.a=c[1],this.f=parseInt(c[2],10))}function fa(a){return H(a)+" "+(a.f+"00")+" 300px "+I(a.c)}function I(a){var b=[];a=a.split(/,\s*/);for(var c=0;c<a.length;c++){var d=a[c].replace(/['"]/g,"");-1!=d.indexOf(" ")||/^\d/.test(d)?b.push("'"+d+"'"):b.push(d)}return b.join(",")}function J(a){return a.a+a.f}function H(a){var b="normal";"o"===a.a?b="oblique":"i"===a.a&&(b="italic");return b} function ga(a){var b=4,c="n",d=null;a&&((d=a.match(/(normal|oblique|italic)/i))&&d[1]&&(c=d[1].substr(0,1).toLowerCase()),(d=a.match(/([1-9]00|normal|bold)/i))&&d[1]&&(/bold/i.test(d[1])?b=7:/[1-9]00/.test(d[1])&&(b=parseInt(d[1].substr(0,1),10))));return c+b};function ha(a,b){this.c=a;this.f=a.o.document.documentElement;this.h=b;this.a=new F("-");this.j=!1!==b.events;this.g=!1!==b.classes}function ia(a){a.g&&w(a.f,[a.a.c("wf","loading")]);K(a,"loading")}function L(a){if(a.g){var b=y(a.f,a.a.c("wf","active")),c=[],d=[a.a.c("wf","loading")];b||c.push(a.a.c("wf","inactive"));w(a.f,c,d)}K(a,"inactive")}function K(a,b,c){if(a.j&&a.h[b])if(c)a.h[b](c.c,J(c));else a.h[b]()};function ja(){this.c={}}function ka(a,b,c){var d=[],e;for(e in b)if(b.hasOwnProperty(e)){var f=a.c[e];f&&d.push(f(b[e],c))}return d};function M(a,b){this.c=a;this.f=b;this.a=t(this.c,"span",{"aria-hidden":"true"},this.f)}function N(a){u(a.c,"body",a.a)}function O(a){return"display:block;position:absolute;top:-9999px;left:-9999px;font-size:300px;width:auto;height:auto;line-height:normal;margin:0;padding:0;font-variant:normal;white-space:nowrap;font-family:"+I(a.c)+";"+("font-style:"+H(a)+";font-weight:"+(a.f+"00")+";")};function P(a,b,c,d,e,f){this.g=a;this.j=b;this.a=d;this.c=c;this.f=e||3E3;this.h=f||void 0}P.prototype.start=function(){var a=this.c.o.document,b=this,c=q(),d=new Promise(function(d,e){function f(){q()-c>=b.f?e():a.fonts.load(fa(b.a),b.h).then(function(a){1<=a.length?d():setTimeout(f,25)},function(){e()})}f()}),e=null,f=new Promise(function(a,d){e=setTimeout(d,b.f)});Promise.race([f,d]).then(function(){e&&(clearTimeout(e),e=null);b.g(b.a)},function(){b.j(b.a)})};function Q(a,b,c,d,e,f,g){this.v=a;this.B=b;this.c=c;this.a=d;this.s=g||"BESbswy";this.f={};this.w=e||3E3;this.u=f||null;this.m=this.j=this.h=this.g=null;this.g=new M(this.c,this.s);this.h=new M(this.c,this.s);this.j=new M(this.c,this.s);this.m=new M(this.c,this.s);a=new G(this.a.c+",serif",J(this.a));a=O(a);this.g.a.style.cssText=a;a=new G(this.a.c+",sans-serif",J(this.a));a=O(a);this.h.a.style.cssText=a;a=new G("serif",J(this.a));a=O(a);this.j.a.style.cssText=a;a=new G("sans-serif",J(this.a));a= O(a);this.m.a.style.cssText=a;N(this.g);N(this.h);N(this.j);N(this.m)}var R={D:"serif",C:"sans-serif"},S=null;function T(){if(null===S){var a=/AppleWebKit\/([0-9]+)(?:\.([0-9]+))/.exec(window.navigator.userAgent);S=!!a&&(536>parseInt(a[1],10)||536===parseInt(a[1],10)&&11>=parseInt(a[2],10))}return S}Q.prototype.start=function(){this.f.serif=this.j.a.offsetWidth;this.f["sans-serif"]=this.m.a.offsetWidth;this.A=q();U(this)}; function la(a,b,c){for(var d in R)if(R.hasOwnProperty(d)&&b===a.f[R[d]]&&c===a.f[R[d]])return!0;return!1}function U(a){var b=a.g.a.offsetWidth,c=a.h.a.offsetWidth,d;(d=b===a.f.serif&&c===a.f["sans-serif"])||(d=T()&&la(a,b,c));d?q()-a.A>=a.w?T()&&la(a,b,c)&&(null===a.u||a.u.hasOwnProperty(a.a.c))?V(a,a.v):V(a,a.B):ma(a):V(a,a.v)}function ma(a){setTimeout(p(function(){U(this)},a),50)}function V(a,b){setTimeout(p(function(){v(this.g.a);v(this.h.a);v(this.j.a);v(this.m.a);b(this.a)},a),0)};function W(a,b,c){this.c=a;this.a=b;this.f=0;this.m=this.j=!1;this.s=c}var X=null;W.prototype.g=function(a){var b=this.a;b.g&&w(b.f,[b.a.c("wf",a.c,J(a).toString(),"active")],[b.a.c("wf",a.c,J(a).toString(),"loading"),b.a.c("wf",a.c,J(a).toString(),"inactive")]);K(b,"fontactive",a);this.m=!0;na(this)}; W.prototype.h=function(a){var b=this.a;if(b.g){var c=y(b.f,b.a.c("wf",a.c,J(a).toString(),"active")),d=[],e=[b.a.c("wf",a.c,J(a).toString(),"loading")];c||d.push(b.a.c("wf",a.c,J(a).toString(),"inactive"));w(b.f,d,e)}K(b,"fontinactive",a);na(this)};function na(a){0==--a.f&&a.j&&(a.m?(a=a.a,a.g&&w(a.f,[a.a.c("wf","active")],[a.a.c("wf","loading"),a.a.c("wf","inactive")]),K(a,"active")):L(a.a))};function oa(a){this.j=a;this.a=new ja;this.h=0;this.f=this.g=!0}oa.prototype.load=function(a){this.c=new ca(this.j,a.context||this.j);this.g=!1!==a.events;this.f=!1!==a.classes;pa(this,new ha(this.c,a),a)}; function qa(a,b,c,d,e){var f=0==--a.h;(a.f||a.g)&&setTimeout(function(){var a=e||null,m=d||null||{};if(0===c.length&&f)L(b.a);else{b.f+=c.length;f&&(b.j=f);var h,l=[];for(h=0;h<c.length;h++){var k=c[h],n=m[k.c],r=b.a,x=k;r.g&&w(r.f,[r.a.c("wf",x.c,J(x).toString(),"loading")]);K(r,"fontloading",x);r=null;if(null===X)if(window.FontFace){var x=/Gecko.*Firefox\/(\d+)/.exec(window.navigator.userAgent),xa=/OS X.*Version\/10\..*Safari/.exec(window.navigator.userAgent)&&/Apple/.exec(window.navigator.vendor); X=x?42<parseInt(x[1],10):xa?!1:!0}else X=!1;X?r=new P(p(b.g,b),p(b.h,b),b.c,k,b.s,n):r=new Q(p(b.g,b),p(b.h,b),b.c,k,b.s,a,n);l.push(r)}for(h=0;h<l.length;h++)l[h].start()}},0)}function pa(a,b,c){var d=[],e=c.timeout;ia(b);var d=ka(a.a,c,a.c),f=new W(a.c,b,e);a.h=d.length;b=0;for(c=d.length;b<c;b++)d[b].load(function(b,d,c){qa(a,f,b,d,c)})};function ra(a,b){this.c=a;this.a=b} ra.prototype.load=function(a){function b(){if(f["__mti_fntLst"+d]){var c=f["__mti_fntLst"+d](),e=[],h;if(c)for(var l=0;l<c.length;l++){var k=c[l].fontfamily;void 0!=c[l].fontStyle&&void 0!=c[l].fontWeight?(h=c[l].fontStyle+c[l].fontWeight,e.push(new G(k,h))):e.push(new G(k))}a(e)}else setTimeout(function(){b()},50)}var c=this,d=c.a.projectId,e=c.a.version;if(d){var f=c.c.o;A(this.c,(c.a.api||"https://fast.fonts.net/jsapi")+"/"+d+".js"+(e?"?v="+e:""),function(e){e?a([]):(f["__MonotypeConfiguration__"+ d]=function(){return c.a},b())}).id="__MonotypeAPIScript__"+d}else a([])};function sa(a,b){this.c=a;this.a=b}sa.prototype.load=function(a){var b,c,d=this.a.urls||[],e=this.a.families||[],f=this.a.testStrings||{},g=new B;b=0;for(c=d.length;b<c;b++)z(this.c,d[b],C(g));var m=[];b=0;for(c=e.length;b<c;b++)if(d=e[b].split(":"),d[1])for(var h=d[1].split(","),l=0;l<h.length;l+=1)m.push(new G(d[0],h[l]));else m.push(new G(d[0]));E(g,function(){a(m,f)})};function ta(a,b){a?this.c=a:this.c=ua;this.a=[];this.f=[];this.g=b||""}var ua="https://fonts.googleapis.com/css";function va(a,b){for(var c=b.length,d=0;d<c;d++){var e=b[d].split(":");3==e.length&&a.f.push(e.pop());var f="";2==e.length&&""!=e[1]&&(f=":");a.a.push(e.join(f))}} function wa(a){if(0==a.a.length)throw Error("No fonts to load!");if(-1!=a.c.indexOf("kit="))return a.c;for(var b=a.a.length,c=[],d=0;d<b;d++)c.push(a.a[d].replace(/ /g,"+"));b=a.c+"?family="+c.join("%7C");0<a.f.length&&(b+="&subset="+a.f.join(","));0<a.g.length&&(b+="&text="+encodeURIComponent(a.g));return b};function ya(a){this.f=a;this.a=[];this.c={}} var za={latin:"BESbswy","latin-ext":"\u00e7\u00f6\u00fc\u011f\u015f",cyrillic:"\u0439\u044f\u0416",greek:"\u03b1\u03b2\u03a3",khmer:"\u1780\u1781\u1782",Hanuman:"\u1780\u1781\u1782"},Aa={thin:"1",extralight:"2","extra-light":"2",ultralight:"2","ultra-light":"2",light:"3",regular:"4",book:"4",medium:"5","semi-bold":"6",semibold:"6","demi-bold":"6",demibold:"6",bold:"7","extra-bold":"8",extrabold:"8","ultra-bold":"8",ultrabold:"8",black:"9",heavy:"9",l:"3",r:"4",b:"7"},Ba={i:"i",italic:"i",n:"n",normal:"n"}, Ca=/^(thin|(?:(?:extra|ultra)-?)?light|regular|book|medium|(?:(?:semi|demi|extra|ultra)-?)?bold|black|heavy|l|r|b|[1-9]00)?(n|i|normal|italic)?$/; function Da(a){for(var b=a.f.length,c=0;c<b;c++){var d=a.f[c].split(":"),e=d[0].replace(/\+/g," "),f=["n4"];if(2<=d.length){var g;var m=d[1];g=[];if(m)for(var m=m.split(","),h=m.length,l=0;l<h;l++){var k;k=m[l];if(k.match(/^[\w-]+$/)){var n=Ca.exec(k.toLowerCase());if(null==n)k="";else{k=n[2];k=null==k||""==k?"n":Ba[k];n=n[1];if(null==n||""==n)n="4";else var r=Aa[n],n=r?r:isNaN(n)?"4":n.substr(0,1);k=[k,n].join("")}}else k="";k&&g.push(k)}0<g.length&&(f=g);3==d.length&&(d=d[2],g=[],d=d?d.split(","): g,0<d.length&&(d=za[d[0]])&&(a.c[e]=d))}a.c[e]||(d=za[e])&&(a.c[e]=d);for(d=0;d<f.length;d+=1)a.a.push(new G(e,f[d]))}};function Ea(a,b){this.c=a;this.a=b}var Fa={Arimo:!0,Cousine:!0,Tinos:!0};Ea.prototype.load=function(a){var b=new B,c=this.c,d=new ta(this.a.api,this.a.text),e=this.a.families;va(d,e);var f=new ya(e);Da(f);z(c,wa(d),C(b));E(b,function(){a(f.a,f.c,Fa)})};function Ga(a,b){this.c=a;this.a=b}Ga.prototype.load=function(a){var b=this.a.id,c=this.c.o;b?A(this.c,(this.a.api||"https://use.typekit.net")+"/"+b+".js",function(b){if(b)a([]);else if(c.Typekit&&c.Typekit.config&&c.Typekit.config.fn){b=c.Typekit.config.fn;for(var e=[],f=0;f<b.length;f+=2)for(var g=b[f],m=b[f+1],h=0;h<m.length;h++)e.push(new G(g,m[h]));try{c.Typekit.load({events:!1,classes:!1,async:!0})}catch(l){}a(e)}},2E3):a([])};function Ha(a,b){this.c=a;this.f=b;this.a=[]}Ha.prototype.load=function(a){var b=this.f.id,c=this.c.o,d=this;b?(c.__webfontfontdeckmodule__||(c.__webfontfontdeckmodule__={}),c.__webfontfontdeckmodule__[b]=function(b,c){for(var g=0,m=c.fonts.length;g<m;++g){var h=c.fonts[g];d.a.push(new G(h.name,ga("font-weight:"+h.weight+";font-style:"+h.style)))}a(d.a)},A(this.c,(this.f.api||"https://f.fontdeck.com/s/css/js/")+ea(this.c)+"/"+b+".js",function(b){b&&a([])})):a([])};var Y=new oa(window);Y.a.c.custom=function(a,b){return new sa(b,a)};Y.a.c.fontdeck=function(a,b){return new Ha(b,a)};Y.a.c.monotype=function(a,b){return new ra(b,a)};Y.a.c.typekit=function(a,b){return new Ga(b,a)};Y.a.c.google=function(a,b){return new Ea(b,a)};var Z={load:p(Y.load,Y)};"function"===typeof define&&define.amd?define(function(){return Z}):"undefined"!==typeof module&&module.exports?module.exports=Z:(window.WebFont=Z,window.WebFontConfig&&Y.load(window.WebFontConfig));}()); },{}],"/Users/rohmann/repos/themeco/x/x/cornerstone/tmp/core_object-input_staging-KN5xJTYA.tmp/browserify_stubs.js":[function(require,module,exports){ define('npm:Faker', function(){ return { 'default': require('Faker')};}) define('npm:base64-js', function(){ return { 'default': require('base64-js')};}) define('npm:bowser', function(){ return { 'default': require('bowser')};}) define('npm:contra/emitter', function(){ return { 'default': require('contra/emitter')};}) define('npm:crossvent', function(){ return { 'default': require('crossvent')};}) define('npm:dropzone', function(){ return { 'default': require('dropzone')};}) define('npm:fuse.js', function(){ return { 'default': require('fuse.js')};}) define('npm:htmlhint', function(){ return { 'default': require('htmlhint')};}) define('npm:in-view', function(){ return { 'default': require('in-view')};}) define('npm:js-base64', function(){ return { 'default': require('js-base64')};}) define('npm:nouislider', function(){ return { 'default': require('nouislider')};}) define('npm:nprogress', function(){ return { 'default': require('nprogress')};}) define('npm:pako', function(){ return { 'default': require('pako')};}) define('npm:perfect-scrollbar', function(){ return { 'default': require('perfect-scrollbar')};}) define('npm:svg4everybody', function(){ return { 'default': require('svg4everybody')};}) define('npm:url-parse', function(){ return { 'default': require('url-parse')};}) define('npm:uuid', function(){ return { 'default': require('uuid')};}) define('npm:webfontloader', function(){ return { 'default': require('webfontloader')};}) },{"Faker":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/Faker/index.js","base64-js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/base64-js/index.js","bowser":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/bowser/src/bowser.js","contra/emitter":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/contra/emitter.js","crossvent":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/crossvent/src/crossvent.js","dropzone":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/dropzone/dist/dropzone.js","fuse.js":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/fuse.js/src/fuse.js","htmlhint":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/htmlhint/index.js","in-view":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/in-view/dist/in-view.min.js","js-base64":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/js-base64/base64.js","nouislider":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/nouislider/distribute/nouislider.js","nprogress":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/nprogress/nprogress.js","pako":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/pako/index.js","perfect-scrollbar":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/perfect-scrollbar/index.js","svg4everybody":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/svg4everybody/dist/svg4everybody.js","url-parse":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/url-parse/index.js","uuid":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/uuid/index.js","webfontloader":"/Users/rohmann/repos/themeco/x/x/cornerstone/node_modules/webfontloader/webfontloader.js"}]},{},["/Users/rohmann/repos/themeco/x/x/cornerstone/tmp/core_object-input_staging-KN5xJTYA.tmp/browserify_stubs.js"]); ;/* globals Ember, Proxy, define */ (function() { 'use strict'; var HAS_NATIVE_PROXY = typeof Proxy === 'function'; var SAFE_LOOKUP_FACTORY_METHOD = '_lookupFactory'; function factoryFor(fullName, options) { var factory = this[SAFE_LOOKUP_FACTORY_METHOD](fullName, options); if (!factory) { return; } var FactoryManager = { class: factory, create: function() { return this.class.create.apply(this.class, arguments); } }; Ember.runInDebug(function() { if (HAS_NATIVE_PROXY) { var validator = { get: function(obj, prop) { if (prop !== 'class' && prop !== 'create') { throw new Error('You attempted to access "' + prop + '" on a factory manager created by container#factoryFor. "' + prop + '" is not a member of a factory manager.'); } return obj[prop]; }, set: function(obj, prop, value) { throw new Error('You attempted to set "' + prop + '" on a factory manager created by container#factoryFor. A factory manager is a read-only construct.'); } }; // Note: // We have to proxy access to the manager here so that private property // access doesn't cause the above errors to occur. var m = FactoryManager; var proxiedManager = { class: m.class, create: function(props) { return m.create(props); } }; FactoryManager = new Proxy(proxiedManager, validator); } }); return FactoryManager; } if (typeof define === 'function') { define('ember-factory-for-polyfill/vendor/ember-factory-for-polyfill/index', ['exports'], function(exports) { exports._factoryFor = factoryFor; exports._updateSafeLookupFactoryMethod = function(methodName) { SAFE_LOOKUP_FACTORY_METHOD = methodName; }; return exports; }); } var FactoryForMixin = Ember.Mixin.create({ factoryFor: factoryFor }); // added in Ember 2.8 if (Ember.ApplicationInstance) { // augment the main application's "owner" Ember.ApplicationInstance.reopen(FactoryForMixin); } else { // in Ember < 2.8 the Ember.ApplicationInstance is not // exposed globally, so we have to monkey patch the // `Ember.Application#buildInstance` method to ensure // that the built instance has a `factoryFor` method // this gives us support for Ember 2.3 - 2.7 Ember.Application.reopen({ buildInstance: function(_options) { var options = _options || {}; options.factoryFor = factoryFor; var instance = this._super(options); return instance; } }); } // added in Ember 2.3 if (Ember._ContainerProxyMixin) { // supports ember-test-helpers's build-registry (and other tooling that use // Ember._ContainerProxyMixin to emulate an "owner") var ContainerProxyMixinWithFactoryFor = Ember.Mixin.create(Ember._ContainerProxyMixin, FactoryForMixin); Ember._ContainerProxyMixin = ContainerProxyMixinWithFactoryFor; } })(); ;/** * sifter.js * Copyright (c) 2013 Brian Reavis & contributors * * 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. * * @author Brian Reavis <brian@thirdroute.com> */ (function(root, factory) { if (typeof define === 'function' && define.amd) { define('sifter', factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.Sifter = factory(); } }(this, function() { /** * Textually searches arrays and hashes of objects * by property (or multiple properties). Designed * specifically for autocomplete. * * @constructor * @param {array|object} items * @param {object} items */ var Sifter = function(items, settings) { this.items = items; this.settings = settings || {diacritics: true}; }; /** * Splits a search string into an array of individual * regexps to be used to match results. * * @param {string} query * @returns {array} */ Sifter.prototype.tokenize = function(query) { query = trim(String(query || '').toLowerCase()); if (!query || !query.length) return []; var i, n, regex, letter; var tokens = []; var words = query.split(/ +/); for (i = 0, n = words.length; i < n; i++) { regex = escape_regex(words[i]); if (this.settings.diacritics) { for (letter in DIACRITICS) { if (DIACRITICS.hasOwnProperty(letter)) { regex = regex.replace(new RegExp(letter, 'g'), DIACRITICS[letter]); } } } tokens.push({ string : words[i], regex : new RegExp(regex, 'i') }); } return tokens; }; /** * Iterates over arrays and hashes. * * ``` * this.iterator(this.items, function(item, id) { * // invoked for each item * }); * ``` * * @param {array|object} object */ Sifter.prototype.iterator = function(object, callback) { var iterator; if (is_array(object)) { iterator = Array.prototype.forEach || function(callback) { for (var i = 0, n = this.length; i < n; i++) { callback(this[i], i, this); } }; } else { iterator = function(callback) { for (var key in this) { if (this.hasOwnProperty(key)) { callback(this[key], key, this); } } }; } iterator.apply(object, [callback]); }; /** * Returns a function to be used to score individual results. * * Good matches will have a higher score than poor matches. * If an item is not a match, 0 will be returned by the function. * * @param {object|string} search * @param {object} options (optional) * @returns {function} */ Sifter.prototype.getScoreFunction = function(search, options) { var self, fields, tokens, token_count; self = this; search = self.prepareSearch(search, options); tokens = search.tokens; fields = search.options.fields; token_count = tokens.length; /** * Calculates how close of a match the * given value is against a search token. * * @param {mixed} value * @param {object} token * @return {number} */ var scoreValue = function(value, token) { var score, pos; if (!value) return 0; value = String(value || ''); pos = value.search(token.regex); if (pos === -1) return 0; score = token.string.length / value.length; if (pos === 0) score += 0.5; return score; }; /** * Calculates the score of an object * against the search query. * * @param {object} token * @param {object} data * @return {number} */ var scoreObject = (function() { var field_count = fields.length; if (!field_count) { return function() { return 0; }; } if (field_count === 1) { return function(token, data) { return scoreValue(data[fields[0]], token); }; } return function(token, data) { for (var i = 0, sum = 0; i < field_count; i++) { sum += scoreValue(data[fields[i]], token); } return sum / field_count; }; })(); if (!token_count) { return function() { return 0; }; } if (token_count === 1) { return function(data) { return scoreObject(tokens[0], data); }; } if (search.options.conjunction === 'and') { return function(data) { var score; for (var i = 0, sum = 0; i < token_count; i++) { score = scoreObject(tokens[i], data); if (score <= 0) return 0; sum += score; } return sum / token_count; }; } else { return function(data) { for (var i = 0, sum = 0; i < token_count; i++) { sum += scoreObject(tokens[i], data); } return sum / token_count; }; } }; /** * Returns a function that can be used to compare two * results, for sorting purposes. If no sorting should * be performed, `null` will be returned. * * @param {string|object} search * @param {object} options * @return function(a,b) */ Sifter.prototype.getSortFunction = function(search, options) { var i, n, self, field, fields, fields_count, multiplier, multipliers, get_field, implicit_score, sort; self = this; search = self.prepareSearch(search, options); sort = (!search.query && options.sort_empty) || options.sort; /** * Fetches the specified sort field value * from a search result item. * * @param {string} name * @param {object} result * @return {mixed} */ get_field = function(name, result) { if (name === '$score') return result.score; return self.items[result.id][name]; }; // parse options fields = []; if (sort) { for (i = 0, n = sort.length; i < n; i++) { if (search.query || sort[i].field !== '$score') { fields.push(sort[i]); } } } // the "$score" field is implied to be the primary // sort field, unless it's manually specified if (search.query) { implicit_score = true; for (i = 0, n = fields.length; i < n; i++) { if (fields[i].field === '$score') { implicit_score = false; break; } } if (implicit_score) { fields.unshift({field: '$score', direction: 'desc'}); } } else { for (i = 0, n = fields.length; i < n; i++) { if (fields[i].field === '$score') { fields.splice(i, 1); break; } } } multipliers = []; for (i = 0, n = fields.length; i < n; i++) { multipliers.push(fields[i].direction === 'desc' ? -1 : 1); } // build function fields_count = fields.length; if (!fields_count) { return null; } else if (fields_count === 1) { field = fields[0].field; multiplier = multipliers[0]; return function(a, b) { return multiplier * cmp( get_field(field, a), get_field(field, b) ); }; } else { return function(a, b) { var i, result, a_value, b_value, field; for (i = 0; i < fields_count; i++) { field = fields[i].field; result = multipliers[i] * cmp( get_field(field, a), get_field(field, b) ); if (result) return result; } return 0; }; } }; /** * Parses a search query and returns an object * with tokens and fields ready to be populated * with results. * * @param {string} query * @param {object} options * @returns {object} */ Sifter.prototype.prepareSearch = function(query, options) { if (typeof query === 'object') return query; options = extend({}, options); var option_fields = options.fields; var option_sort = options.sort; var option_sort_empty = options.sort_empty; if (option_fields && !is_array(option_fields)) options.fields = [option_fields]; if (option_sort && !is_array(option_sort)) options.sort = [option_sort]; if (option_sort_empty && !is_array(option_sort_empty)) options.sort_empty = [option_sort_empty]; return { options : options, query : String(query || '').toLowerCase(), tokens : this.tokenize(query), total : 0, items : [] }; }; /** * Searches through all items and returns a sorted array of matches. * * The `options` parameter can contain: * * - fields {string|array} * - sort {array} * - score {function} * - filter {bool} * - limit {integer} * * Returns an object containing: * * - options {object} * - query {string} * - tokens {array} * - total {int} * - items {array} * * @param {string} query * @param {object} options * @returns {object} */ Sifter.prototype.search = function(query, options) { var self = this, value, score, search, calculateScore; var fn_sort; var fn_score; search = this.prepareSearch(query, options); options = search.options; query = search.query; // generate result scoring function fn_score = options.score || self.getScoreFunction(search); // perform search and sort if (query.length) { self.iterator(self.items, function(item, id) { score = fn_score(item); if (options.filter === false || score > 0) { search.items.push({'score': score, 'id': id}); } }); } else { self.iterator(self.items, function(item, id) { search.items.push({'score': 1, 'id': id}); }); } fn_sort = self.getSortFunction(search, options); if (fn_sort) search.items.sort(fn_sort); // apply limits search.total = search.items.length; if (typeof options.limit === 'number') { search.items = search.items.slice(0, options.limit); } return search; }; // utilities // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - var cmp = function(a, b) { if (typeof a === 'number' && typeof b === 'number') { return a > b ? 1 : (a < b ? -1 : 0); } a = asciifold(String(a || '')); b = asciifold(String(b || '')); if (a > b) return 1; if (b > a) return -1; return 0; }; var extend = function(a, b) { var i, n, k, object; for (i = 1, n = arguments.length; i < n; i++) { object = arguments[i]; if (!object) continue; for (k in object) { if (object.hasOwnProperty(k)) { a[k] = object[k]; } } } return a; }; var trim = function(str) { return (str + '').replace(/^\s+|\s+$|/g, ''); }; var escape_regex = function(str) { return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); }; var is_array = Array.isArray || (typeof $ !== 'undefined' && $.isArray) || function(object) { return Object.prototype.toString.call(object) === '[object Array]'; }; var DIACRITICS = { 'a': '[aÀÁÂÃÄÅàáâãäåĀāąĄ]', 'c': '[cÇçćĆčČ]', 'd': '[dđĐďĎð]', 'e': '[eÈÉÊËèéêëěĚĒēęĘ]', 'i': '[iÌÍÎÏìíîïĪī]', 'l': '[lłŁ]', 'n': '[nÑñňŇńŃ]', 'o': '[oÒÓÔÕÕÖØòóôõöøŌō]', 'r': '[rřŘ]', 's': '[sŠšśŚ]', 't': '[tťŤ]', 'u': '[uÙÚÛÜùúûüůŮŪū]', 'y': '[yŸÿýÝ]', 'z': '[zŽžżŻźŹ]' }; var asciifold = (function() { var i, n, k, chunk; var foreignletters = ''; var lookup = {}; for (k in DIACRITICS) { if (DIACRITICS.hasOwnProperty(k)) { chunk = DIACRITICS[k].substring(2, DIACRITICS[k].length - 1); foreignletters += chunk; for (i = 0, n = chunk.length; i < n; i++) { lookup[chunk.charAt(i)] = k; } } } var regexp = new RegExp('[' + foreignletters + ']', 'g'); return function(str) { return str.replace(regexp, function(foreignletter) { return lookup[foreignletter]; }).toLowerCase(); }; })(); // export // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - return Sifter; })); /** * microplugin.js * Copyright (c) 2013 Brian Reavis & contributors * * 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. * * @author Brian Reavis <brian@thirdroute.com> */ (function(root, factory) { if (typeof define === 'function' && define.amd) { define('microplugin', factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.MicroPlugin = factory(); } }(this, function() { var MicroPlugin = {}; MicroPlugin.mixin = function(Interface) { Interface.plugins = {}; /** * Initializes the listed plugins (with options). * Acceptable formats: * * List (without options): * ['a', 'b', 'c'] * * List (with options): * [{'name': 'a', options: {}}, {'name': 'b', options: {}}] * * Hash (with options): * {'a': { ... }, 'b': { ... }, 'c': { ... }} * * @param {mixed} plugins */ Interface.prototype.initializePlugins = function(plugins) { var i, n, key; var self = this; var queue = []; self.plugins = { names : [], settings : {}, requested : {}, loaded : {} }; if (utils.isArray(plugins)) { for (i = 0, n = plugins.length; i < n; i++) { if (typeof plugins[i] === 'string') { queue.push(plugins[i]); } else { self.plugins.settings[plugins[i].name] = plugins[i].options; queue.push(plugins[i].name); } } } else if (plugins) { for (key in plugins) { if (plugins.hasOwnProperty(key)) { self.plugins.settings[key] = plugins[key]; queue.push(key); } } } while (queue.length) { self.require(queue.shift()); } }; Interface.prototype.loadPlugin = function(name) { var self = this; var plugins = self.plugins; var plugin = Interface.plugins[name]; if (!Interface.plugins.hasOwnProperty(name)) { throw new Error('Unable to find "' + name + '" plugin'); } plugins.requested[name] = true; plugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]); plugins.names.push(name); }; /** * Initializes a plugin. * * @param {string} name */ Interface.prototype.require = function(name) { var self = this; var plugins = self.plugins; if (!self.plugins.loaded.hasOwnProperty(name)) { if (plugins.requested[name]) { throw new Error('Plugin has circular dependency ("' + name + '")'); } self.loadPlugin(name); } return plugins.loaded[name]; }; /** * Registers a plugin. * * @param {string} name * @param {function} fn */ Interface.define = function(name, fn) { Interface.plugins[name] = { 'name' : name, 'fn' : fn }; }; }; var utils = { isArray: Array.isArray || function(vArg) { return Object.prototype.toString.call(vArg) === '[object Array]'; } }; return MicroPlugin; })); /** * selectize.js (v) * Copyright (c) 2013–2015 Brian Reavis & contributors * * 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. * * @author Brian Reavis <brian@thirdroute.com> */ /*jshint curly:false */ /*jshint browser:true */ (function(root, factory) { if (typeof define === 'function' && define.amd) { define('selectize', ['jquery','sifter','microplugin'], factory); } else if (typeof exports === 'object') { module.exports = factory(require('jquery'), require('sifter'), require('microplugin')); } else { root.Selectize = factory(root.jQuery, root.Sifter, root.MicroPlugin); } }(this, function($, Sifter, MicroPlugin) { 'use strict'; var highlight = function($element, pattern) { if (typeof pattern === 'string' && !pattern.length) return; var regex = (typeof pattern === 'string') ? new RegExp(pattern, 'i') : pattern; var highlight = function(node) { var skip = 0; if (node.nodeType === 3) { var pos = node.data.search(regex); if (pos >= 0 && node.data.length > 0) { var match = node.data.match(regex); var spannode = document.createElement('span'); spannode.className = 'highlight'; var middlebit = node.splitText(pos); var endbit = middlebit.splitText(match[0].length); var middleclone = middlebit.cloneNode(true); spannode.appendChild(middleclone); middlebit.parentNode.replaceChild(spannode, middlebit); skip = 1; } } else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) { for (var i = 0; i < node.childNodes.length; ++i) { i += highlight(node.childNodes[i]); } } return skip; }; return $element.each(function() { highlight(this); }); }; var MicroEvent = function() {}; MicroEvent.prototype = { on: function(event, fct){ this._events = this._events || {}; this._events[event] = this._events[event] || []; this._events[event].push(fct); }, off: function(event, fct){ var n = arguments.length; if (n === 0) return delete this._events; if (n === 1) return delete this._events[event]; this._events = this._events || {}; if (event in this._events === false) return; this._events[event].splice(this._events[event].indexOf(fct), 1); }, trigger: function(event /* , args... */){ this._events = this._events || {}; if (event in this._events === false) return; for (var i = 0; i < this._events[event].length; i++){ this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1)); } } }; /** * Mixin will delegate all MicroEvent.js function in the destination object. * * - MicroEvent.mixin(Foobar) will make Foobar able to use MicroEvent * * @param {object} the object which will support MicroEvent */ MicroEvent.mixin = function(destObject){ var props = ['on', 'off', 'trigger']; for (var i = 0; i < props.length; i++){ destObject.prototype[props[i]] = MicroEvent.prototype[props[i]]; } }; var IS_MAC = /Mac/.test(navigator.userAgent); var KEY_A = 65; var KEY_COMMA = 188; var KEY_RETURN = 13; var KEY_ESC = 27; var KEY_LEFT = 37; var KEY_UP = 38; var KEY_P = 80; var KEY_RIGHT = 39; var KEY_DOWN = 40; var KEY_N = 78; var KEY_BACKSPACE = 8; var KEY_DELETE = 46; var KEY_SHIFT = 16; var KEY_CMD = IS_MAC ? 91 : 17; var KEY_CTRL = IS_MAC ? 18 : 17; var KEY_TAB = 9; var TAG_SELECT = 1; var TAG_INPUT = 2; // for now, android support in general is too spotty to support validity var SUPPORTS_VALIDITY_API = !/android/i.test(window.navigator.userAgent) && !!document.createElement('form').validity; var isset = function(object) { return typeof object !== 'undefined'; }; /** * Converts a scalar to its best string representation * for hash keys and HTML attribute values. * * Transformations: * 'str' -> 'str' * null -> '' * undefined -> '' * true -> '1' * false -> '0' * 0 -> '0' * 1 -> '1' * * @param {string} value * @returns {string|null} */ var hash_key = function(value) { if (typeof value === 'undefined' || value === null) return null; if (typeof value === 'boolean') return value ? '1' : '0'; return value + ''; }; /** * Escapes a string for use within HTML. * * @param {string} str * @returns {string} */ var escape_html = function(str) { return (str + '') .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"'); }; /** * Escapes "$" characters in replacement strings. * * @param {string} str * @returns {string} */ var escape_replace = function(str) { return (str + '').replace(/\$/g, '$$$$'); }; var hook = {}; /** * Wraps `method` on `self` so that `fn` * is invoked before the original method. * * @param {object} self * @param {string} method * @param {function} fn */ hook.before = function(self, method, fn) { var original = self[method]; self[method] = function() { fn.apply(self, arguments); return original.apply(self, arguments); }; }; /** * Wraps `method` on `self` so that `fn` * is invoked after the original method. * * @param {object} self * @param {string} method * @param {function} fn */ hook.after = function(self, method, fn) { var original = self[method]; self[method] = function() { var result = original.apply(self, arguments); fn.apply(self, arguments); return result; }; }; /** * Wraps `fn` so that it can only be invoked once. * * @param {function} fn * @returns {function} */ var once = function(fn) { var called = false; return function() { if (called) return; called = true; fn.apply(this, arguments); }; }; /** * Wraps `fn` so that it can only be called once * every `delay` milliseconds (invoked on the falling edge). * * @param {function} fn * @param {int} delay * @returns {function} */ var debounce = function(fn, delay) { var timeout; return function() { var self = this; var args = arguments; window.clearTimeout(timeout); timeout = window.setTimeout(function() { fn.apply(self, args); }, delay); }; }; /** * Debounce all fired events types listed in `types` * while executing the provided `fn`. * * @param {object} self * @param {array} types * @param {function} fn */ var debounce_events = function(self, types, fn) { var type; var trigger = self.trigger; var event_args = {}; // override trigger method self.trigger = function() { var type = arguments[0]; if (types.indexOf(type) !== -1) { event_args[type] = arguments; } else { return trigger.apply(self, arguments); } }; // invoke provided function fn.apply(self, []); self.trigger = trigger; // trigger queued events for (type in event_args) { if (event_args.hasOwnProperty(type)) { trigger.apply(self, event_args[type]); } } }; /** * A workaround for http://bugs.jquery.com/ticket/6696 * * @param {object} $parent - Parent element to listen on. * @param {string} event - Event name. * @param {string} selector - Descendant selector to filter by. * @param {function} fn - Event handler. */ var watchChildEvent = function($parent, event, selector, fn) { $parent.on(event, selector, function(e) { var child = e.target; while (child && child.parentNode !== $parent[0]) { child = child.parentNode; } e.currentTarget = child; return fn.apply(this, [e]); }); }; /** * Determines the current selection within a text input control. * Returns an object containing: * - start * - length * * @param {object} input * @returns {object} */ var getSelection = function(input) { var result = {}; if ('selectionStart' in input) { result.start = input.selectionStart; result.length = input.selectionEnd - result.start; } else if (document.selection) { input.focus(); var sel = document.selection.createRange(); var selLen = document.selection.createRange().text.length; sel.moveStart('character', -input.value.length); result.start = sel.text.length - selLen; result.length = selLen; } return result; }; /** * Copies CSS properties from one element to another. * * @param {object} $from * @param {object} $to * @param {array} properties */ var transferStyles = function($from, $to, properties) { var i, n, styles = {}; if (properties) { for (i = 0, n = properties.length; i < n; i++) { styles[properties[i]] = $from.css(properties[i]); } } else { styles = $from.css(); } $to.css(styles); }; /** * Measures the width of a string within a * parent element (in pixels). * * @param {string} str * @param {object} $parent * @returns {int} */ var measureString = function(str, $parent) { if (!str) { return 0; } var $test = $('<test>').css({ position: 'absolute', top: -99999, left: -99999, width: 'auto', padding: 0, whiteSpace: 'pre' }).text(str).appendTo('body'); transferStyles($parent, $test, [ 'letterSpacing', 'fontSize', 'fontFamily', 'fontWeight', 'textTransform' ]); var width = $test.width(); $test.remove(); return width; }; /** * Sets up an input to grow horizontally as the user * types. If the value is changed manually, you can * trigger the "update" handler to resize: * * $input.trigger('update'); * * @param {object} $input */ var autoGrow = function($input) { var currentWidth = null; var update = function(e, options) { var value, keyCode, printable, placeholder, width; var shift, character, selection; e = e || window.event || {}; options = options || {}; if (e.metaKey || e.altKey) return; if (!options.force && $input.data('grow') === false) return; value = $input.val(); if (e.type && e.type.toLowerCase() === 'keydown') { keyCode = e.keyCode; printable = ( (keyCode >= 97 && keyCode <= 122) || // a-z (keyCode >= 65 && keyCode <= 90) || // A-Z (keyCode >= 48 && keyCode <= 57) || // 0-9 keyCode === 32 // space ); if (keyCode === KEY_DELETE || keyCode === KEY_BACKSPACE) { selection = getSelection($input[0]); if (selection.length) { value = value.substring(0, selection.start) + value.substring(selection.start + selection.length); } else if (keyCode === KEY_BACKSPACE && selection.start) { value = value.substring(0, selection.start - 1) + value.substring(selection.start + 1); } else if (keyCode === KEY_DELETE && typeof selection.start !== 'undefined') { value = value.substring(0, selection.start) + value.substring(selection.start + 1); } } else if (printable) { shift = e.shiftKey; character = String.fromCharCode(e.keyCode); if (shift) character = character.toUpperCase(); else character = character.toLowerCase(); value += character; } } placeholder = $input.attr('placeholder'); if (!value && placeholder) { value = placeholder; } width = measureString(value, $input) + 4; if (width !== currentWidth) { currentWidth = width; $input.width(width); $input.triggerHandler('resize'); } }; $input.on('keydown keyup update blur', update); update(); }; var domToString = function(d) { var tmp = document.createElement('div'); tmp.appendChild(d.cloneNode(true)); return tmp.innerHTML; }; var Selectize = function($input, settings) { var key, i, n, dir, input, self = this; input = $input[0]; input.selectize = self; // detect rtl environment var computedStyle = window.getComputedStyle && window.getComputedStyle(input, null); dir = computedStyle ? computedStyle.getPropertyValue('direction') : input.currentStyle && input.currentStyle.direction; dir = dir || $input.parents('[dir]:first').attr('dir') || ''; // setup default state $.extend(self, { order : 0, settings : settings, $input : $input, tabIndex : $input.attr('tabindex') || '', tagType : input.tagName.toLowerCase() === 'select' ? TAG_SELECT : TAG_INPUT, rtl : /rtl/i.test(dir), eventNS : '.selectize' + (++Selectize.count), highlightedValue : null, isOpen : false, isDisabled : false, isRequired : $input.is('[required]'), isInvalid : false, isLocked : false, isFocused : false, isInputHidden : false, isSetup : false, isShiftDown : false, isCmdDown : false, isCtrlDown : false, ignoreFocus : false, ignoreBlur : false, ignoreHover : false, hasOptions : false, currentResults : null, lastValue : '', caretPos : 0, loading : 0, loadedSearches : {}, $activeOption : null, $activeItems : [], optgroups : {}, options : {}, userOptions : {}, items : [], renderCache : {}, onSearchChange : settings.loadThrottle === null ? self.onSearchChange : debounce(self.onSearchChange, settings.loadThrottle) }); // search system self.sifter = new Sifter(this.options, {diacritics: settings.diacritics}); // build options table if (self.settings.options) { for (i = 0, n = self.settings.options.length; i < n; i++) { self.registerOption(self.settings.options[i]); } delete self.settings.options; } // build optgroup table if (self.settings.optgroups) { for (i = 0, n = self.settings.optgroups.length; i < n; i++) { self.registerOptionGroup(self.settings.optgroups[i]); } delete self.settings.optgroups; } // option-dependent defaults self.settings.mode = self.settings.mode || (self.settings.maxItems === 1 ? 'single' : 'multi'); if (typeof self.settings.hideSelected !== 'boolean') { self.settings.hideSelected = self.settings.mode === 'multi'; } self.initializePlugins(self.settings.plugins); self.setupCallbacks(); self.setupTemplates(); self.setup(); }; // mixins // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MicroEvent.mixin(Selectize); MicroPlugin.mixin(Selectize); // methods // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $.extend(Selectize.prototype, { /** * Creates all elements and sets up event bindings. */ setup: function() { var self = this; var settings = self.settings; var eventNS = self.eventNS; var $window = $(window); var $document = $(document); var $input = self.$input; var $wrapper; var $control; var $control_input; var $dropdown; var $dropdown_content; var $dropdown_parent; var inputMode; var timeout_blur; var timeout_focus; var classes; var classes_plugins; inputMode = self.settings.mode; classes = $input.attr('class') || ''; $wrapper = $('<div>').addClass(settings.wrapperClass).addClass(classes).addClass(inputMode); $control = $('<div>').addClass(settings.inputClass).addClass('items').appendTo($wrapper); $control_input = $('<input type="text" autocomplete="off" />').appendTo($control).attr('tabindex', $input.is(':disabled') ? '-1' : self.tabIndex); $dropdown_parent = $(settings.dropdownParent || $wrapper); $dropdown = $('<div>').addClass(settings.dropdownClass).addClass(inputMode).hide().appendTo($dropdown_parent); $dropdown_content = $('<div>').addClass(settings.dropdownContentClass).appendTo($dropdown); if(self.settings.copyClassesToDropdown) { $dropdown.addClass(classes); } $wrapper.css({ width: $input[0].style.width }); if (self.plugins.names.length) { classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-'); $wrapper.addClass(classes_plugins); $dropdown.addClass(classes_plugins); } if ((settings.maxItems === null || settings.maxItems > 1) && self.tagType === TAG_SELECT) { $input.attr('multiple', 'multiple'); } if (self.settings.placeholder) { $control_input.attr('placeholder', settings.placeholder); } // if splitOn was not passed in, construct it from the delimiter to allow pasting universally if (!self.settings.splitOn && self.settings.delimiter) { var delimiterEscaped = self.settings.delimiter.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); self.settings.splitOn = new RegExp('\\s*' + delimiterEscaped + '+\\s*'); } if ($input.attr('autocorrect')) { $control_input.attr('autocorrect', $input.attr('autocorrect')); } if ($input.attr('autocapitalize')) { $control_input.attr('autocapitalize', $input.attr('autocapitalize')); } self.$wrapper = $wrapper; self.$control = $control; self.$control_input = $control_input; self.$dropdown = $dropdown; self.$dropdown_content = $dropdown_content; $dropdown.on('mouseenter', '[data-selectable]', function() { return self.onOptionHover.apply(self, arguments); }); $dropdown.on('mousedown click', '[data-selectable]', function() { return self.onOptionSelect.apply(self, arguments); }); watchChildEvent($control, 'mousedown', '*:not(input)', function() { return self.onItemSelect.apply(self, arguments); }); autoGrow($control_input); $control.on({ mousedown : function() { return self.onMouseDown.apply(self, arguments); }, click : function() { return self.onClick.apply(self, arguments); } }); $control_input.on({ mousedown : function(e) { e.stopPropagation(); }, keydown : function() { return self.onKeyDown.apply(self, arguments); }, keyup : function() { return self.onKeyUp.apply(self, arguments); }, keypress : function() { return self.onKeyPress.apply(self, arguments); }, resize : function() { self.positionDropdown.apply(self, []); }, blur : function() { return self.onBlur.apply(self, arguments); }, focus : function() { self.ignoreBlur = false; return self.onFocus.apply(self, arguments); }, paste : function() { return self.onPaste.apply(self, arguments); } }); $document.on('keydown' + eventNS, function(e) { self.isCmdDown = e[IS_MAC ? 'metaKey' : 'ctrlKey']; self.isCtrlDown = e[IS_MAC ? 'altKey' : 'ctrlKey']; self.isShiftDown = e.shiftKey; }); $document.on('keyup' + eventNS, function(e) { if (e.keyCode === KEY_CTRL) self.isCtrlDown = false; if (e.keyCode === KEY_SHIFT) self.isShiftDown = false; if (e.keyCode === KEY_CMD) self.isCmdDown = false; }); $document.on('mousedown' + eventNS, function(e) { if (self.isFocused) { // prevent events on the dropdown scrollbar from causing the control to blur if (e.target === self.$dropdown[0] || e.target.parentNode === self.$dropdown[0]) { return false; } // blur on click outside if (!self.$control.has(e.target).length && e.target !== self.$control[0]) { self.blur(e.target); } } }); $window.on(['scroll' + eventNS, 'resize' + eventNS].join(' '), function() { if (self.isOpen) { self.positionDropdown.apply(self, arguments); } }); $window.on('mousemove' + eventNS, function() { self.ignoreHover = false; }); // store original children and tab index so that they can be // restored when the destroy() method is called. this.revertSettings = { $children : $input.children().detach(), tabindex : $input.attr('tabindex') }; $input.attr('tabindex', -1).hide().after(self.$wrapper); if ($.isArray(settings.items)) { self.setValue(settings.items); delete settings.items; } // feature detect for the validation API if (SUPPORTS_VALIDITY_API) { $input.on('invalid' + eventNS, function(e) { e.preventDefault(); self.isInvalid = true; self.refreshState(); }); } self.updateOriginalInput(); self.refreshItems(); self.refreshState(); self.updatePlaceholder(); self.isSetup = true; if ($input.is(':disabled')) { self.disable(); } self.on('change', this.onChange); $input.data('selectize', self); $input.addClass('selectized'); self.trigger('initialize'); // preload options if (settings.preload === true) { self.onSearchChange(''); } }, /** * Sets up default rendering functions. */ setupTemplates: function() { var self = this; var field_label = self.settings.labelField; var field_optgroup = self.settings.optgroupLabelField; var templates = { 'optgroup': function(data) { return '<div class="optgroup">' + data.html + '</div>'; }, 'optgroup_header': function(data, escape) { return '<div class="optgroup-header">' + escape(data[field_optgroup]) + '</div>'; }, 'option': function(data, escape) { return '<div class="option">' + escape(data[field_label]) + '</div>'; }, 'item': function(data, escape) { return '<div class="item">' + escape(data[field_label]) + '</div>'; }, 'option_create': function(data, escape) { return '<div class="create">Add <strong>' + escape(data.input) + '</strong>…</div>'; } }; self.settings.render = $.extend({}, templates, self.settings.render); }, /** * Maps fired events to callbacks provided * in the settings used when creating the control. */ setupCallbacks: function() { var key, fn, callbacks = { 'initialize' : 'onInitialize', 'change' : 'onChange', 'item_add' : 'onItemAdd', 'item_remove' : 'onItemRemove', 'clear' : 'onClear', 'option_add' : 'onOptionAdd', 'option_remove' : 'onOptionRemove', 'option_clear' : 'onOptionClear', 'optgroup_add' : 'onOptionGroupAdd', 'optgroup_remove' : 'onOptionGroupRemove', 'optgroup_clear' : 'onOptionGroupClear', 'dropdown_open' : 'onDropdownOpen', 'dropdown_close' : 'onDropdownClose', 'type' : 'onType', 'load' : 'onLoad', 'focus' : 'onFocus', 'blur' : 'onBlur' }; for (key in callbacks) { if (callbacks.hasOwnProperty(key)) { fn = this.settings[callbacks[key]]; if (fn) this.on(key, fn); } } }, /** * Triggered when the main control element * has a click event. * * @param {object} e * @return {boolean} */ onClick: function(e) { var self = this; // necessary for mobile webkit devices (manual focus triggering // is ignored unless invoked within a click event) if (!self.isFocused) { self.focus(); e.preventDefault(); } }, /** * Triggered when the main control element * has a mouse down event. * * @param {object} e * @return {boolean} */ onMouseDown: function(e) { var self = this; var defaultPrevented = e.isDefaultPrevented(); var $target = $(e.target); if (self.isFocused) { // retain focus by preventing native handling. if the // event target is the input it should not be modified. // otherwise, text selection within the input won't work. if (e.target !== self.$control_input[0]) { if (self.settings.mode === 'single') { // toggle dropdown self.isOpen ? self.close() : self.open(); } else if (!defaultPrevented) { self.setActiveItem(null); } return false; } } else { // give control focus if (!defaultPrevented) { window.setTimeout(function() { self.focus(); }, 0); } } }, /** * Triggered when the value of the control has been changed. * This should propagate the event to the original DOM * input / select element. */ onChange: function() { this.$input.trigger('change'); }, /** * Triggered on <input> paste. * * @param {object} e * @returns {boolean} */ onPaste: function(e) { var self = this; if (self.isFull() || self.isInputHidden || self.isLocked) { e.preventDefault(); } else { // If a regex or string is included, this will split the pasted // input and create Items for each separate value if (self.settings.splitOn) { setTimeout(function() { var splitInput = $.trim(self.$control_input.val() || '').split(self.settings.splitOn); for (var i = 0, n = splitInput.length; i < n; i++) { self.createItem(splitInput[i]); } }, 0); } } }, /** * Triggered on <input> keypress. * * @param {object} e * @returns {boolean} */ onKeyPress: function(e) { if (this.isLocked) return e && e.preventDefault(); var character = String.fromCharCode(e.keyCode || e.which); if (this.settings.create && this.settings.mode === 'multi' && character === this.settings.delimiter) { this.createItem(); e.preventDefault(); return false; } }, /** * Triggered on <input> keydown. * * @param {object} e * @returns {boolean} */ onKeyDown: function(e) { var isInput = e.target === this.$control_input[0]; var self = this; if (self.isLocked) { if (e.keyCode !== KEY_TAB) { e.preventDefault(); } return; } switch (e.keyCode) { case KEY_A: if (self.isCmdDown) { self.selectAll(); return; } break; case KEY_ESC: if (self.isOpen) { e.preventDefault(); e.stopPropagation(); self.close(); } return; case KEY_N: if (!e.ctrlKey || e.altKey) break; case KEY_DOWN: if (!self.isOpen && self.hasOptions) { self.open(); } else if (self.$activeOption) { self.ignoreHover = true; var $next = self.getAdjacentOption(self.$activeOption, 1); if ($next.length) self.setActiveOption($next, true, true); } e.preventDefault(); return; case KEY_P: if (!e.ctrlKey || e.altKey) break; case KEY_UP: if (self.$activeOption) { self.ignoreHover = true; var $prev = self.getAdjacentOption(self.$activeOption, -1); if ($prev.length) self.setActiveOption($prev, true, true); } e.preventDefault(); return; case KEY_RETURN: if (self.isOpen && self.$activeOption) { self.onOptionSelect({currentTarget: self.$activeOption}); e.preventDefault(); } return; case KEY_LEFT: self.advanceSelection(-1, e); return; case KEY_RIGHT: self.advanceSelection(1, e); return; case KEY_TAB: if (self.settings.selectOnTab && self.isOpen && self.$activeOption) { self.onOptionSelect({currentTarget: self.$activeOption}); // Default behaviour is to jump to the next field, we only want this // if the current field doesn't accept any more entries if (!self.isFull()) { e.preventDefault(); } } if (self.settings.create && self.createItem()) { e.preventDefault(); } return; case KEY_BACKSPACE: case KEY_DELETE: self.deleteSelection(e); return; } if ((self.isFull() || self.isInputHidden) && !(IS_MAC ? e.metaKey : e.ctrlKey)) { e.preventDefault(); return; } }, /** * Triggered on <input> keyup. * * @param {object} e * @returns {boolean} */ onKeyUp: function(e) { var self = this; if (self.isLocked) return e && e.preventDefault(); var value = self.$control_input.val() || ''; if (self.lastValue !== value) { self.lastValue = value; self.onSearchChange(value); self.refreshOptions(); self.trigger('type', value); } }, /** * Invokes the user-provide option provider / loader. * * Note: this function is debounced in the Selectize * constructor (by `settings.loadDelay` milliseconds) * * @param {string} value */ onSearchChange: function(value) { var self = this; var fn = self.settings.load; if (!fn) return; if (self.loadedSearches.hasOwnProperty(value)) return; self.loadedSearches[value] = true; self.load(function(callback) { fn.apply(self, [value, callback]); }); }, /** * Triggered on <input> focus. * * @param {object} e (optional) * @returns {boolean} */ onFocus: function(e) { var self = this; var wasFocused = self.isFocused; if (self.isDisabled) { self.blur(); e && e.preventDefault(); return false; } if (self.ignoreFocus) return; self.isFocused = true; if (self.settings.preload === 'focus') self.onSearchChange(''); if (!wasFocused) self.trigger('focus'); if (!self.$activeItems.length) { self.showInput(); self.setActiveItem(null); self.refreshOptions(!!self.settings.openOnFocus); } self.refreshState(); }, /** * Triggered on <input> blur. * * @param {object} e * @param {Element} dest */ onBlur: function(e, dest) { var self = this; if (!self.isFocused) return; self.isFocused = false; if (self.ignoreFocus) { return; } else if (!self.ignoreBlur && document.activeElement === self.$dropdown_content[0]) { // necessary to prevent IE closing the dropdown when the scrollbar is clicked self.ignoreBlur = true; self.onFocus(e); return; } var deactivate = function() { self.close(); self.setTextboxValue(''); self.setActiveItem(null); self.setActiveOption(null); self.setCaret(self.items.length); self.refreshState(); // IE11 bug: element still marked as active (dest || document.body).focus(); self.ignoreFocus = false; self.trigger('blur'); }; self.ignoreFocus = true; if (self.settings.create && self.settings.createOnBlur) { self.createItem(null, false, deactivate); } else { deactivate(); } }, /** * Triggered when the user rolls over * an option in the autocomplete dropdown menu. * * @param {object} e * @returns {boolean} */ onOptionHover: function(e) { if (this.ignoreHover) return; this.setActiveOption(e.currentTarget, false); }, /** * Triggered when the user clicks on an option * in the autocomplete dropdown menu. * * @param {object} e * @returns {boolean} */ onOptionSelect: function(e) { var value, $target, $option, self = this; if (e.preventDefault) { e.preventDefault(); e.stopPropagation(); } $target = $(e.currentTarget); if ($target.hasClass('create')) { self.createItem(null, function() { if (self.settings.closeAfterSelect) { self.close(); } }); } else { value = $target.attr('data-value'); if (typeof value !== 'undefined') { self.lastQuery = null; self.setTextboxValue(''); self.addItem(value); if (self.settings.closeAfterSelect) { self.close(); } else if (!self.settings.hideSelected && e.type && /mouse/.test(e.type)) { self.setActiveOption(self.getOption(value)); } } } }, /** * Triggered when the user clicks on an item * that has been selected. * * @param {object} e * @returns {boolean} */ onItemSelect: function(e) { var self = this; if (self.isLocked) return; if (self.settings.mode === 'multi') { e.preventDefault(); self.setActiveItem(e.currentTarget, e); } }, /** * Invokes the provided method that provides * results to a callback---which are then added * as options to the control. * * @param {function} fn */ load: function(fn) { var self = this; var $wrapper = self.$wrapper.addClass(self.settings.loadingClass); self.loading++; fn.apply(self, [function(results) { self.loading = Math.max(self.loading - 1, 0); if (results && results.length) { self.addOption(results); self.refreshOptions(self.isFocused && !self.isInputHidden); } if (!self.loading) { $wrapper.removeClass(self.settings.loadingClass); } self.trigger('load', results); }]); }, /** * Sets the input field of the control to the specified value. * * @param {string} value */ setTextboxValue: function(value) { var $input = this.$control_input; var changed = $input.val() !== value; if (changed) { $input.val(value).triggerHandler('update'); this.lastValue = value; } }, /** * Returns the value of the control. If multiple items * can be selected (e.g. <select multiple>), this returns * an array. If only one item can be selected, this * returns a string. * * @returns {mixed} */ getValue: function() { if (this.tagType === TAG_SELECT && this.$input.attr('multiple')) { return this.items; } else { return this.items.join(this.settings.delimiter); } }, /** * Resets the selected items to the given value. * * @param {mixed} value */ setValue: function(value, silent) { var events = silent ? [] : ['change']; debounce_events(this, events, function() { this.clear(silent); this.addItems(value, silent); }); }, /** * Sets the selected item. * * @param {object} $item * @param {object} e (optional) */ setActiveItem: function($item, e) { var self = this; var eventName; var i, idx, begin, end, item, swap; var $last; if (self.settings.mode === 'single') return; $item = $($item); // clear the active selection if (!$item.length) { $(self.$activeItems).removeClass('active'); self.$activeItems = []; if (self.isFocused) { self.showInput(); } return; } // modify selection eventName = e && e.type.toLowerCase(); if (eventName === 'mousedown' && self.isShiftDown && self.$activeItems.length) { $last = self.$control.children('.active:last'); begin = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$last[0]]); end = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$item[0]]); if (begin > end) { swap = begin; begin = end; end = swap; } for (i = begin; i <= end; i++) { item = self.$control[0].childNodes[i]; if (self.$activeItems.indexOf(item) === -1) { $(item).addClass('active'); self.$activeItems.push(item); } } e.preventDefault(); } else if ((eventName === 'mousedown' && self.isCtrlDown) || (eventName === 'keydown' && this.isShiftDown)) { if ($item.hasClass('active')) { idx = self.$activeItems.indexOf($item[0]); self.$activeItems.splice(idx, 1); $item.removeClass('active'); } else { self.$activeItems.push($item.addClass('active')[0]); } } else { $(self.$activeItems).removeClass('active'); self.$activeItems = [$item.addClass('active')[0]]; } // ensure control has focus self.hideInput(); if (!this.isFocused) { self.focus(); } }, /** * Sets the selected item in the dropdown menu * of available options. * * @param {object} $object * @param {boolean} scroll * @param {boolean} animate */ setActiveOption: function($option, scroll, animate) { var height_menu, height_item, y; var scroll_top, scroll_bottom; var self = this; if (self.$activeOption) self.$activeOption.removeClass('active'); self.$activeOption = null; $option = $($option); if (!$option.length) return; self.$activeOption = $option.addClass('active'); if (scroll || !isset(scroll)) { height_menu = self.$dropdown_content.height(); height_item = self.$activeOption.outerHeight(true); scroll = self.$dropdown_content.scrollTop() || 0; y = self.$activeOption.offset().top - self.$dropdown_content.offset().top + scroll; scroll_top = y; scroll_bottom = y - height_menu + height_item; if (y + height_item > height_menu + scroll) { self.$dropdown_content.stop().animate({scrollTop: scroll_bottom}, animate ? self.settings.scrollDuration : 0); } else if (y < scroll) { self.$dropdown_content.stop().animate({scrollTop: scroll_top}, animate ? self.settings.scrollDuration : 0); } } }, /** * Selects all items (CTRL + A). */ selectAll: function() { var self = this; if (self.settings.mode === 'single') return; self.$activeItems = Array.prototype.slice.apply(self.$control.children(':not(input)').addClass('active')); if (self.$activeItems.length) { self.hideInput(); self.close(); } self.focus(); }, /** * Hides the input element out of view, while * retaining its focus. */ hideInput: function() { var self = this; self.setTextboxValue(''); self.$control_input.css({opacity: 0, position: 'absolute', left: self.rtl ? 10000 : -10000}); self.isInputHidden = true; }, /** * Restores input visibility. */ showInput: function() { this.$control_input.css({opacity: 1, position: 'relative', left: 0}); this.isInputHidden = false; }, /** * Gives the control focus. */ focus: function() { var self = this; if (self.isDisabled) return; self.ignoreFocus = true; self.$control_input[0].focus(); window.setTimeout(function() { self.ignoreFocus = false; self.onFocus(); }, 0); }, /** * Forces the control out of focus. * * @param {Element} dest */ blur: function(dest) { this.$control_input[0].blur(); this.onBlur(null, dest); }, /** * Returns a function that scores an object * to show how good of a match it is to the * provided query. * * @param {string} query * @param {object} options * @return {function} */ getScoreFunction: function(query) { return this.sifter.getScoreFunction(query, this.getSearchOptions()); }, /** * Returns search options for sifter (the system * for scoring and sorting results). * * @see https://github.com/brianreavis/sifter.js * @return {object} */ getSearchOptions: function() { var settings = this.settings; var sort = settings.sortField; if (typeof sort === 'string') { sort = [{field: sort}]; } return { fields : settings.searchField, conjunction : settings.searchConjunction, sort : sort }; }, /** * Searches through available options and returns * a sorted array of matches. * * Returns an object containing: * * - query {string} * - tokens {array} * - total {int} * - items {array} * * @param {string} query * @returns {object} */ search: function(query) { var i, value, score, result, calculateScore; var self = this; var settings = self.settings; var options = this.getSearchOptions(); // validate user-provided result scoring function if (settings.score) { calculateScore = self.settings.score.apply(this, [query]); if (typeof calculateScore !== 'function') { throw new Error('Selectize "score" setting must be a function that returns a function'); } } // perform search if (query !== self.lastQuery) { self.lastQuery = query; result = self.sifter.search(query, $.extend(options, {score: calculateScore})); self.currentResults = result; } else { result = $.extend(true, {}, self.currentResults); } // filter out selected items if (settings.hideSelected) { for (i = result.items.length - 1; i >= 0; i--) { if (self.items.indexOf(hash_key(result.items[i].id)) !== -1) { result.items.splice(i, 1); } } } return result; }, /** * Refreshes the list of available options shown * in the autocomplete dropdown menu. * * @param {boolean} triggerDropdown */ refreshOptions: function(triggerDropdown) { var i, j, k, n, groups, groups_order, option, option_html, optgroup, optgroups, html, html_children, has_create_option; var $active, $active_before, $create; if (typeof triggerDropdown === 'undefined') { triggerDropdown = true; } var self = this; var query = $.trim(self.$control_input.val()); var results = self.search(query); var $dropdown_content = self.$dropdown_content; var active_before = self.$activeOption && hash_key(self.$activeOption.attr('data-value')); // build markup n = results.items.length; if (typeof self.settings.maxOptions === 'number') { n = Math.min(n, self.settings.maxOptions); } // render and group available options individually groups = {}; groups_order = []; for (i = 0; i < n; i++) { option = self.options[results.items[i].id]; option_html = self.render('option', option); optgroup = option[self.settings.optgroupField] || ''; optgroups = $.isArray(optgroup) ? optgroup : [optgroup]; for (j = 0, k = optgroups && optgroups.length; j < k; j++) { optgroup = optgroups[j]; if (!self.optgroups.hasOwnProperty(optgroup)) { optgroup = ''; } if (!groups.hasOwnProperty(optgroup)) { groups[optgroup] = document.createDocumentFragment(); groups_order.push(optgroup); } groups[optgroup].appendChild(option_html); } } // sort optgroups if (this.settings.lockOptgroupOrder) { groups_order.sort(function(a, b) { var a_order = self.optgroups[a].$order || 0; var b_order = self.optgroups[b].$order || 0; return a_order - b_order; }); } // render optgroup headers & join groups html = document.createDocumentFragment(); for (i = 0, n = groups_order.length; i < n; i++) { optgroup = groups_order[i]; if (self.optgroups.hasOwnProperty(optgroup) && groups[optgroup].childNodes.length) { // render the optgroup header and options within it, // then pass it to the wrapper template html_children = document.createDocumentFragment(); html_children.appendChild(self.render('optgroup_header', self.optgroups[optgroup])); html_children.appendChild(groups[optgroup]); html.appendChild(self.render('optgroup', $.extend({}, self.optgroups[optgroup], { html: domToString(html_children), dom: html_children }))); } else { html.appendChild(groups[optgroup]); } } $dropdown_content.html(html); // highlight matching terms inline if (self.settings.highlight && results.query.length && results.tokens.length) { for (i = 0, n = results.tokens.length; i < n; i++) { highlight($dropdown_content, results.tokens[i].regex); } } // add "selected" class to selected options if (!self.settings.hideSelected) { for (i = 0, n = self.items.length; i < n; i++) { self.getOption(self.items[i]).addClass('selected'); } } // add create option has_create_option = self.canCreate(query); if (has_create_option) { $dropdown_content.prepend(self.render('option_create', {input: query})); $create = $($dropdown_content[0].childNodes[0]); } // activate self.hasOptions = results.items.length > 0 || has_create_option; if (self.hasOptions) { if (results.items.length > 0) { $active_before = active_before && self.getOption(active_before); if ($active_before && $active_before.length) { $active = $active_before; } else if (self.settings.mode === 'single' && self.items.length) { $active = self.getOption(self.items[0]); } if (!$active || !$active.length) { if ($create && !self.settings.addPrecedence) { $active = self.getAdjacentOption($create, 1); } else { $active = $dropdown_content.find('[data-selectable]:first'); } } } else { $active = $create; } self.setActiveOption($active); if (triggerDropdown && !self.isOpen) { self.open(); } } else { self.setActiveOption(null); if (triggerDropdown && self.isOpen) { self.close(); } } }, /** * Adds an available option. If it already exists, * nothing will happen. Note: this does not refresh * the options list dropdown (use `refreshOptions` * for that). * * Usage: * * this.addOption(data) * * @param {object|array} data */ addOption: function(data) { var i, n, value, self = this; if ($.isArray(data)) { for (i = 0, n = data.length; i < n; i++) { self.addOption(data[i]); } return; } if (value = self.registerOption(data)) { self.userOptions[value] = true; self.lastQuery = null; self.trigger('option_add', value, data); } }, /** * Registers an option to the pool of options. * * @param {object} data * @return {boolean|string} */ registerOption: function(data) { var key = hash_key(data[this.settings.valueField]); if (!key || this.options.hasOwnProperty(key)) return false; data.$order = data.$order || ++this.order; this.options[key] = data; return key; }, /** * Registers an option group to the pool of option groups. * * @param {object} data * @return {boolean|string} */ registerOptionGroup: function(data) { var key = hash_key(data[this.settings.optgroupValueField]); if (!key) return false; data.$order = data.$order || ++this.order; this.optgroups[key] = data; return key; }, /** * Registers a new optgroup for options * to be bucketed into. * * @param {string} id * @param {object} data */ addOptionGroup: function(id, data) { data[this.settings.optgroupValueField] = id; if (id = this.registerOptionGroup(data)) { this.trigger('optgroup_add', id, data); } }, /** * Removes an existing option group. * * @param {string} id */ removeOptionGroup: function(id) { if (this.optgroups.hasOwnProperty(id)) { delete this.optgroups[id]; this.renderCache = {}; this.trigger('optgroup_remove', id); } }, /** * Clears all existing option groups. */ clearOptionGroups: function() { this.optgroups = {}; this.renderCache = {}; this.trigger('optgroup_clear'); }, /** * Updates an option available for selection. If * it is visible in the selected items or options * dropdown, it will be re-rendered automatically. * * @param {string} value * @param {object} data */ updateOption: function(value, data) { var self = this; var $item, $item_new; var value_new, index_item, cache_items, cache_options, order_old; value = hash_key(value); value_new = hash_key(data[self.settings.valueField]); // sanity checks if (value === null) return; if (!self.options.hasOwnProperty(value)) return; if (typeof value_new !== 'string') throw new Error('Value must be set in option data'); order_old = self.options[value].$order; // update references if (value_new !== value) { delete self.options[value]; index_item = self.items.indexOf(value); if (index_item !== -1) { self.items.splice(index_item, 1, value_new); } } data.$order = data.$order || order_old; self.options[value_new] = data; // invalidate render cache cache_items = self.renderCache['item']; cache_options = self.renderCache['option']; if (cache_items) { delete cache_items[value]; delete cache_items[value_new]; } if (cache_options) { delete cache_options[value]; delete cache_options[value_new]; } // update the item if it's selected if (self.items.indexOf(value_new) !== -1) { $item = self.getItem(value); $item_new = $(self.render('item', data)); if ($item.hasClass('active')) $item_new.addClass('active'); $item.replaceWith($item_new); } // invalidate last query because we might have updated the sortField self.lastQuery = null; // update dropdown contents if (self.isOpen) { self.refreshOptions(false); } }, /** * Removes a single option. * * @param {string} value * @param {boolean} silent */ removeOption: function(value, silent) { var self = this; value = hash_key(value); var cache_items = self.renderCache['item']; var cache_options = self.renderCache['option']; if (cache_items) delete cache_items[value]; if (cache_options) delete cache_options[value]; delete self.userOptions[value]; delete self.options[value]; self.lastQuery = null; self.trigger('option_remove', value); self.removeItem(value, silent); }, /** * Clears all options. */ clearOptions: function() { var self = this; self.loadedSearches = {}; self.userOptions = {}; self.renderCache = {}; self.options = self.sifter.items = {}; self.lastQuery = null; self.trigger('option_clear'); self.clear(); }, /** * Returns the jQuery element of the option * matching the given value. * * @param {string} value * @returns {object} */ getOption: function(value) { return this.getElementWithValue(value, this.$dropdown_content.find('[data-selectable]')); }, /** * Returns the jQuery element of the next or * previous selectable option. * * @param {object} $option * @param {int} direction can be 1 for next or -1 for previous * @return {object} */ getAdjacentOption: function($option, direction) { var $options = this.$dropdown.find('[data-selectable]'); var index = $options.index($option) + direction; return index >= 0 && index < $options.length ? $options.eq(index) : $(); }, /** * Finds the first element with a "data-value" attribute * that matches the given value. * * @param {mixed} value * @param {object} $els * @return {object} */ getElementWithValue: function(value, $els) { value = hash_key(value); if (typeof value !== 'undefined' && value !== null) { for (var i = 0, n = $els.length; i < n; i++) { if ($els[i].getAttribute('data-value') === value) { return $($els[i]); } } } return $(); }, /** * Returns the jQuery element of the item * matching the given value. * * @param {string} value * @returns {object} */ getItem: function(value) { return this.getElementWithValue(value, this.$control.children()); }, /** * "Selects" multiple items at once. Adds them to the list * at the current caret position. * * @param {string} value * @param {boolean} silent */ addItems: function(values, silent) { var items = $.isArray(values) ? values : [values]; for (var i = 0, n = items.length; i < n; i++) { this.isPending = (i < n - 1); this.addItem(items[i], silent); } }, /** * "Selects" an item. Adds it to the list * at the current caret position. * * @param {string} value * @param {boolean} silent */ addItem: function(value, silent) { var events = silent ? [] : ['change']; debounce_events(this, events, function() { var $item, $option, $options; var self = this; var inputMode = self.settings.mode; var i, active, value_next, wasFull; value = hash_key(value); if (self.items.indexOf(value) !== -1) { if (inputMode === 'single') self.close(); return; } if (!self.options.hasOwnProperty(value)) return; if (inputMode === 'single') self.clear(silent); if (inputMode === 'multi' && self.isFull()) return; $item = $(self.render('item', self.options[value])); wasFull = self.isFull(); self.items.splice(self.caretPos, 0, value); self.insertAtCaret($item); if (!self.isPending || (!wasFull && self.isFull())) { self.refreshState(); } if (self.isSetup) { $options = self.$dropdown_content.find('[data-selectable]'); // update menu / remove the option (if this is not one item being added as part of series) if (!self.isPending) { $option = self.getOption(value); value_next = self.getAdjacentOption($option, 1).attr('data-value'); self.refreshOptions(self.isFocused && inputMode !== 'single'); if (value_next) { self.setActiveOption(self.getOption(value_next)); } } // hide the menu if the maximum number of items have been selected or no options are left if (!$options.length || self.isFull()) { self.close(); } else { self.positionDropdown(); } self.updatePlaceholder(); self.trigger('item_add', value, $item); self.updateOriginalInput({silent: silent}); } }); }, /** * Removes the selected item matching * the provided value. * * @param {string} value */ removeItem: function(value, silent) { var self = this; var $item, i, idx; $item = (typeof value === 'object') ? value : self.getItem(value); value = hash_key($item.attr('data-value')); i = self.items.indexOf(value); if (i !== -1) { $item.remove(); if ($item.hasClass('active')) { idx = self.$activeItems.indexOf($item[0]); self.$activeItems.splice(idx, 1); } self.items.splice(i, 1); self.lastQuery = null; if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) { self.removeOption(value, silent); } if (i < self.caretPos) { self.setCaret(self.caretPos - 1); } self.refreshState(); self.updatePlaceholder(); self.updateOriginalInput({silent: silent}); self.positionDropdown(); self.trigger('item_remove', value, $item); } }, /** * Invokes the `create` method provided in the * selectize options that should provide the data * for the new item, given the user input. * * Once this completes, it will be added * to the item list. * * @param {string} value * @param {boolean} [triggerDropdown] * @param {function} [callback] * @return {boolean} */ createItem: function(input, triggerDropdown) { var self = this; var caret = self.caretPos; input = input || $.trim(self.$control_input.val() || ''); var callback = arguments[arguments.length - 1]; if (typeof callback !== 'function') callback = function() {}; if (typeof triggerDropdown !== 'boolean') { triggerDropdown = true; } if (!self.canCreate(input)) { callback(); return false; } self.lock(); var setup = (typeof self.settings.create === 'function') ? this.settings.create : function(input) { var data = {}; data[self.settings.labelField] = input; data[self.settings.valueField] = input; return data; }; var create = once(function(data) { self.unlock(); if (!data || typeof data !== 'object') return callback(); var value = hash_key(data[self.settings.valueField]); if (typeof value !== 'string') return callback(); self.setTextboxValue(''); self.addOption(data); self.setCaret(caret); self.addItem(value); self.refreshOptions(triggerDropdown && self.settings.mode !== 'single'); callback(data); }); var output = setup.apply(this, [input, create]); if (typeof output !== 'undefined') { create(output); } return true; }, /** * Re-renders the selected item lists. */ refreshItems: function() { this.lastQuery = null; if (this.isSetup) { this.addItem(this.items); } this.refreshState(); this.updateOriginalInput(); }, /** * Updates all state-dependent attributes * and CSS classes. */ refreshState: function() { var invalid, self = this; if (self.isRequired) { if (self.items.length) self.isInvalid = false; self.$control_input.prop('required', invalid); } self.refreshClasses(); }, /** * Updates all state-dependent CSS classes. */ refreshClasses: function() { var self = this; var isFull = self.isFull(); var isLocked = self.isLocked; self.$wrapper .toggleClass('rtl', self.rtl); self.$control .toggleClass('focus', self.isFocused) .toggleClass('disabled', self.isDisabled) .toggleClass('required', self.isRequired) .toggleClass('invalid', self.isInvalid) .toggleClass('locked', isLocked) .toggleClass('full', isFull).toggleClass('not-full', !isFull) .toggleClass('input-active', self.isFocused && !self.isInputHidden) .toggleClass('dropdown-active', self.isOpen) .toggleClass('has-options', !$.isEmptyObject(self.options)) .toggleClass('has-items', self.items.length > 0); self.$control_input.data('grow', !isFull && !isLocked); }, /** * Determines whether or not more items can be added * to the control without exceeding the user-defined maximum. * * @returns {boolean} */ isFull: function() { return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems; }, /** * Refreshes the original <select> or <input> * element to reflect the current state. */ updateOriginalInput: function(opts) { var i, n, options, label, self = this; opts = opts || {}; if (self.tagType === TAG_SELECT) { options = []; for (i = 0, n = self.items.length; i < n; i++) { label = self.options[self.items[i]][self.settings.labelField] || ''; options.push('<option value="' + escape_html(self.items[i]) + '" selected="selected">' + escape_html(label) + '</option>'); } if (!options.length && !this.$input.attr('multiple')) { options.push('<option value="" selected="selected"></option>'); } self.$input.html(options.join('')); } else { self.$input.val(self.getValue()); self.$input.attr('value',self.$input.val()); } if (self.isSetup) { if (!opts.silent) { self.trigger('change', self.$input.val()); } } }, /** * Shows/hide the input placeholder depending * on if there items in the list already. */ updatePlaceholder: function() { if (!this.settings.placeholder) return; var $input = this.$control_input; if (this.items.length) { $input.removeAttr('placeholder'); } else { $input.attr('placeholder', this.settings.placeholder); } $input.triggerHandler('update', {force: true}); }, /** * Shows the autocomplete dropdown containing * the available options. */ open: function() { var self = this; if (self.isLocked || self.isOpen || (self.settings.mode === 'multi' && self.isFull())) return; self.focus(); self.isOpen = true; self.refreshState(); self.$dropdown.css({visibility: 'hidden', display: 'block'}); self.positionDropdown(); self.$dropdown.css({visibility: 'visible'}); self.trigger('dropdown_open', self.$dropdown); }, /** * Closes the autocomplete dropdown menu. */ close: function() { var self = this; var trigger = self.isOpen; if (self.settings.mode === 'single' && self.items.length) { self.hideInput(); } self.isOpen = false; self.$dropdown.hide(); self.setActiveOption(null); self.refreshState(); if (trigger) self.trigger('dropdown_close', self.$dropdown); }, /** * Calculates and applies the appropriate * position of the dropdown. */ positionDropdown: function() { var $control = this.$control; var offset = this.settings.dropdownParent === 'body' ? $control.offset() : $control.position(); offset.top += $control.outerHeight(true); this.$dropdown.css({ width : $control.outerWidth(), top : offset.top, left : offset.left }); }, /** * Resets / clears all selected items * from the control. * * @param {boolean} silent */ clear: function(silent) { var self = this; if (!self.items.length) return; self.$control.children(':not(input)').remove(); self.items = []; self.lastQuery = null; self.setCaret(0); self.setActiveItem(null); self.updatePlaceholder(); self.updateOriginalInput({silent: silent}); self.refreshState(); self.showInput(); self.trigger('clear'); }, /** * A helper method for inserting an element * at the current caret position. * * @param {object} $el */ insertAtCaret: function($el) { var caret = Math.min(this.caretPos, this.items.length); if (caret === 0) { this.$control.prepend($el); } else { $(this.$control[0].childNodes[caret]).before($el); } this.setCaret(caret + 1); }, /** * Removes the current selected item(s). * * @param {object} e (optional) * @returns {boolean} */ deleteSelection: function(e) { var i, n, direction, selection, values, caret, option_select, $option_select, $tail; var self = this; direction = (e && e.keyCode === KEY_BACKSPACE) ? -1 : 1; selection = getSelection(self.$control_input[0]); if (self.$activeOption && !self.settings.hideSelected) { option_select = self.getAdjacentOption(self.$activeOption, -1).attr('data-value'); } // determine items that will be removed values = []; if (self.$activeItems.length) { $tail = self.$control.children('.active:' + (direction > 0 ? 'last' : 'first')); caret = self.$control.children(':not(input)').index($tail); if (direction > 0) { caret++; } for (i = 0, n = self.$activeItems.length; i < n; i++) { values.push($(self.$activeItems[i]).attr('data-value')); } if (e) { e.preventDefault(); e.stopPropagation(); } } else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) { if (direction < 0 && selection.start === 0 && selection.length === 0) { values.push(self.items[self.caretPos - 1]); } else if (direction > 0 && selection.start === self.$control_input.val().length) { values.push(self.items[self.caretPos]); } } // allow the callback to abort if (!values.length || (typeof self.settings.onDelete === 'function' && self.settings.onDelete.apply(self, [values]) === false)) { return false; } // perform removal if (typeof caret !== 'undefined') { self.setCaret(caret); } while (values.length) { self.removeItem(values.pop()); } self.showInput(); self.positionDropdown(); self.refreshOptions(true); // select previous option if (option_select) { $option_select = self.getOption(option_select); if ($option_select.length) { self.setActiveOption($option_select); } } return true; }, /** * Selects the previous / next item (depending * on the `direction` argument). * * > 0 - right * < 0 - left * * @param {int} direction * @param {object} e (optional) */ advanceSelection: function(direction, e) { var tail, selection, idx, valueLength, cursorAtEdge, $tail; var self = this; if (direction === 0) return; if (self.rtl) direction *= -1; tail = direction > 0 ? 'last' : 'first'; selection = getSelection(self.$control_input[0]); if (self.isFocused && !self.isInputHidden) { valueLength = self.$control_input.val().length; cursorAtEdge = direction < 0 ? selection.start === 0 && selection.length === 0 : selection.start === valueLength; if (cursorAtEdge && !valueLength) { self.advanceCaret(direction, e); } } else { $tail = self.$control.children('.active:' + tail); if ($tail.length) { idx = self.$control.children(':not(input)').index($tail); self.setActiveItem(null); self.setCaret(direction > 0 ? idx + 1 : idx); } } }, /** * Moves the caret left / right. * * @param {int} direction * @param {object} e (optional) */ advanceCaret: function(direction, e) { var self = this, fn, $adj; if (direction === 0) return; fn = direction > 0 ? 'next' : 'prev'; if (self.isShiftDown) { $adj = self.$control_input[fn](); if ($adj.length) { self.hideInput(); self.setActiveItem($adj); e && e.preventDefault(); } } else { self.setCaret(self.caretPos + direction); } }, /** * Moves the caret to the specified index. * * @param {int} i */ setCaret: function(i) { var self = this; if (self.settings.mode === 'single') { i = self.items.length; } else { i = Math.max(0, Math.min(self.items.length, i)); } if(!self.isPending) { // the input must be moved by leaving it in place and moving the // siblings, due to the fact that focus cannot be restored once lost // on mobile webkit devices var j, n, fn, $children, $child; $children = self.$control.children(':not(input)'); for (j = 0, n = $children.length; j < n; j++) { $child = $($children[j]).detach(); if (j < i) { self.$control_input.before($child); } else { self.$control.append($child); } } } self.caretPos = i; }, /** * Disables user input on the control. Used while * items are being asynchronously created. */ lock: function() { this.close(); this.isLocked = true; this.refreshState(); }, /** * Re-enables user input on the control. */ unlock: function() { this.isLocked = false; this.refreshState(); }, /** * Disables user input on the control completely. * While disabled, it cannot receive focus. */ disable: function() { var self = this; self.$input.prop('disabled', true); self.$control_input.prop('disabled', true).prop('tabindex', -1); self.isDisabled = true; self.lock(); }, /** * Enables the control so that it can respond * to focus and user input. */ enable: function() { var self = this; self.$input.prop('disabled', false); self.$control_input.prop('disabled', false).prop('tabindex', self.tabIndex); self.isDisabled = false; self.unlock(); }, /** * Completely destroys the control and * unbinds all event listeners so that it can * be garbage collected. */ destroy: function() { var self = this; var eventNS = self.eventNS; var revertSettings = self.revertSettings; self.trigger('destroy'); self.off(); self.$wrapper.remove(); self.$dropdown.remove(); self.$input .html('') .append(revertSettings.$children) .removeAttr('tabindex') .removeClass('selectized') .attr({tabindex: revertSettings.tabindex}) .show(); self.$control_input.removeData('grow'); self.$input.removeData('selectize'); $(window).off(eventNS); $(document).off(eventNS); $(document.body).off(eventNS); delete self.$input[0].selectize; }, /** * A helper method for rendering "item" and * "option" templates, given the data. * * @param {string} templateName * @param {object} data * @returns {string} */ render: function(templateName, data) { var value, id, label; var html = ''; var cache = false; var self = this; var regex_tag = /^[\t \r\n]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i; if (templateName === 'option' || templateName === 'item') { value = hash_key(data[self.settings.valueField]); cache = !!value; } // pull markup from cache if it exists if (cache) { if (!isset(self.renderCache[templateName])) { self.renderCache[templateName] = {}; } if (self.renderCache[templateName].hasOwnProperty(value)) { return self.renderCache[templateName][value]; } } // render markup html = $(self.settings.render[templateName].apply(this, [data, escape_html])); // add mandatory attributes if (templateName === 'option' || templateName === 'option_create') { html.attr('data-selectable', ''); } else if (templateName === 'optgroup') { id = data[self.settings.optgroupValueField] || ''; html.attr('data-group', id); } if (templateName === 'option' || templateName === 'item') { html.attr('data-value', value || ''); } // update cache if (cache) { self.renderCache[templateName][value] = html[0]; } return html[0]; }, /** * Clears the render cache for a template. If * no template is given, clears all render * caches. * * @param {string} templateName */ clearCache: function(templateName) { var self = this; if (typeof templateName === 'undefined') { self.renderCache = {}; } else { delete self.renderCache[templateName]; } }, /** * Determines whether or not to display the * create item prompt, given a user input. * * @param {string} input * @return {boolean} */ canCreate: function(input) { var self = this; if (!self.settings.create) return false; var filter = self.settings.createFilter; return input.length && (typeof filter !== 'function' || filter.apply(self, [input])) && (typeof filter !== 'string' || new RegExp(filter).test(input)) && (!(filter instanceof RegExp) || filter.test(input)); } }); Selectize.count = 0; Selectize.defaults = { options: [], optgroups: [], plugins: [], delimiter: ',', splitOn: null, // regexp or string for splitting up values from a paste command persist: true, diacritics: true, create: false, createOnBlur: false, createFilter: null, highlight: true, openOnFocus: true, maxOptions: 1000, maxItems: null, hideSelected: null, addPrecedence: false, selectOnTab: false, preload: false, allowEmptyOption: false, closeAfterSelect: false, scrollDuration: 60, loadThrottle: 300, loadingClass: 'loading', dataAttr: 'data-data', optgroupField: 'optgroup', valueField: 'value', labelField: 'text', optgroupLabelField: 'label', optgroupValueField: 'value', lockOptgroupOrder: false, sortField: '$order', searchField: ['text'], searchConjunction: 'and', mode: null, wrapperClass: 'selectize-control', inputClass: 'selectize-input', dropdownClass: 'selectize-dropdown', dropdownContentClass: 'selectize-dropdown-content', dropdownParent: null, copyClassesToDropdown: true, /* load : null, // function(query, callback) { ... } score : null, // function(search) { ... } onInitialize : null, // function() { ... } onChange : null, // function(value) { ... } onItemAdd : null, // function(value, $item) { ... } onItemRemove : null, // function(value) { ... } onClear : null, // function() { ... } onOptionAdd : null, // function(value, data) { ... } onOptionRemove : null, // function(value) { ... } onOptionClear : null, // function() { ... } onOptionGroupAdd : null, // function(id, data) { ... } onOptionGroupRemove : null, // function(id) { ... } onOptionGroupClear : null, // function() { ... } onDropdownOpen : null, // function($dropdown) { ... } onDropdownClose : null, // function($dropdown) { ... } onType : null, // function(str) { ... } onDelete : null, // function(values) { ... } */ render: { /* item: null, optgroup: null, optgroup_header: null, option: null, option_create: null */ } }; $.fn.selectize = function(settings_user) { var defaults = $.fn.selectize.defaults; var settings = $.extend({}, defaults, settings_user); var attr_data = settings.dataAttr; var field_label = settings.labelField; var field_value = settings.valueField; var field_optgroup = settings.optgroupField; var field_optgroup_label = settings.optgroupLabelField; var field_optgroup_value = settings.optgroupValueField; /** * Initializes selectize from a <input type="text"> element. * * @param {object} $input * @param {object} settings_element */ var init_textbox = function($input, settings_element) { var i, n, values, option; var data_raw = $input.attr(attr_data); if (!data_raw) { var value = $.trim($input.val() || ''); if (!settings.allowEmptyOption && !value.length) return; values = value.split(settings.delimiter); for (i = 0, n = values.length; i < n; i++) { option = {}; option[field_label] = values[i]; option[field_value] = values[i]; settings_element.options.push(option); } settings_element.items = values; } else { settings_element.options = JSON.parse(data_raw); for (i = 0, n = settings_element.options.length; i < n; i++) { settings_element.items.push(settings_element.options[i][field_value]); } } }; /** * Initializes selectize from a <select> element. * * @param {object} $input * @param {object} settings_element */ var init_select = function($input, settings_element) { var i, n, tagName, $children, order = 0; var options = settings_element.options; var optionsMap = {}; var readData = function($el) { var data = attr_data && $el.attr(attr_data); if (typeof data === 'string' && data.length) { return JSON.parse(data); } return null; }; var addOption = function($option, group) { $option = $($option); var value = hash_key($option.attr('value')); if (!value && !settings.allowEmptyOption) return; // if the option already exists, it's probably been // duplicated in another optgroup. in this case, push // the current group to the "optgroup" property on the // existing option so that it's rendered in both places. if (optionsMap.hasOwnProperty(value)) { if (group) { var arr = optionsMap[value][field_optgroup]; if (!arr) { optionsMap[value][field_optgroup] = group; } else if (!$.isArray(arr)) { optionsMap[value][field_optgroup] = [arr, group]; } else { arr.push(group); } } return; } var option = readData($option) || {}; option[field_label] = option[field_label] || $option.text(); option[field_value] = option[field_value] || value; option[field_optgroup] = option[field_optgroup] || group; optionsMap[value] = option; options.push(option); if ($option.is(':selected')) { settings_element.items.push(value); } }; var addGroup = function($optgroup) { var i, n, id, optgroup, $options; $optgroup = $($optgroup); id = $optgroup.attr('label'); if (id) { optgroup = readData($optgroup) || {}; optgroup[field_optgroup_label] = id; optgroup[field_optgroup_value] = id; settings_element.optgroups.push(optgroup); } $options = $('option', $optgroup); for (i = 0, n = $options.length; i < n; i++) { addOption($options[i], id); } }; settings_element.maxItems = $input.attr('multiple') ? null : 1; $children = $input.children(); for (i = 0, n = $children.length; i < n; i++) { tagName = $children[i].tagName.toLowerCase(); if (tagName === 'optgroup') { addGroup($children[i]); } else if (tagName === 'option') { addOption($children[i]); } } }; return this.each(function() { if (this.selectize) return; var instance; var $input = $(this); var tag_name = this.tagName.toLowerCase(); var placeholder = $input.attr('placeholder') || $input.attr('data-placeholder'); if (!placeholder && !settings.allowEmptyOption) { placeholder = $input.children('option[value=""]').text(); } var settings_element = { 'placeholder' : placeholder, 'options' : [], 'optgroups' : [], 'items' : [] }; if (tag_name === 'select') { init_select($input, settings_element); } else { init_textbox($input, settings_element); } instance = new Selectize($input, $.extend(true, {}, defaults, settings_element, settings_user)); }); }; $.fn.selectize.defaults = Selectize.defaults; $.fn.selectize.support = { validity: SUPPORTS_VALIDITY_API }; Selectize.define('drag_drop', function(options) { if (!$.fn.sortable) throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".'); if (this.settings.mode !== 'multi') return; var self = this; self.lock = (function() { var original = self.lock; return function() { var sortable = self.$control.data('sortable'); if (sortable) sortable.disable(); return original.apply(self, arguments); }; })(); self.unlock = (function() { var original = self.unlock; return function() { var sortable = self.$control.data('sortable'); if (sortable) sortable.enable(); return original.apply(self, arguments); }; })(); self.setup = (function() { var original = self.setup; return function() { original.apply(this, arguments); var $control = self.$control.sortable({ items: '[data-value]', forcePlaceholderSize: true, disabled: self.isLocked, start: function(e, ui) { ui.placeholder.css('width', ui.helper.css('width')); $control.css({overflow: 'visible'}); }, stop: function() { $control.css({overflow: 'hidden'}); var active = self.$activeItems ? self.$activeItems.slice() : null; var values = []; $control.children('[data-value]').each(function() { values.push($(this).attr('data-value')); }); self.setValue(values); self.setActiveItem(active); } }); }; })(); }); Selectize.define('dropdown_header', function(options) { var self = this; options = $.extend({ title : 'Untitled', headerClass : 'selectize-dropdown-header', titleRowClass : 'selectize-dropdown-header-title', labelClass : 'selectize-dropdown-header-label', closeClass : 'selectize-dropdown-header-close', html: function(data) { return ( '<div class="' + data.headerClass + '">' + '<div class="' + data.titleRowClass + '">' + '<span class="' + data.labelClass + '">' + data.title + '</span>' + '<a href="javascript:void(0)" class="' + data.closeClass + '">×</a>' + '</div>' + '</div>' ); } }, options); self.setup = (function() { var original = self.setup; return function() { original.apply(self, arguments); self.$dropdown_header = $(options.html(options)); self.$dropdown.prepend(self.$dropdown_header); }; })(); }); Selectize.define('optgroup_columns', function(options) { var self = this; options = $.extend({ equalizeWidth : true, equalizeHeight : true }, options); this.getAdjacentOption = function($option, direction) { var $options = $option.closest('[data-group]').find('[data-selectable]'); var index = $options.index($option) + direction; return index >= 0 && index < $options.length ? $options.eq(index) : $(); }; this.onKeyDown = (function() { var original = self.onKeyDown; return function(e) { var index, $option, $options, $optgroup; if (this.isOpen && (e.keyCode === KEY_LEFT || e.keyCode === KEY_RIGHT)) { self.ignoreHover = true; $optgroup = this.$activeOption.closest('[data-group]'); index = $optgroup.find('[data-selectable]').index(this.$activeOption); if(e.keyCode === KEY_LEFT) { $optgroup = $optgroup.prev('[data-group]'); } else { $optgroup = $optgroup.next('[data-group]'); } $options = $optgroup.find('[data-selectable]'); $option = $options.eq(Math.min($options.length - 1, index)); if ($option.length) { this.setActiveOption($option); } return; } return original.apply(this, arguments); }; })(); var getScrollbarWidth = function() { var div; var width = getScrollbarWidth.width; var doc = document; if (typeof width === 'undefined') { div = doc.createElement('div'); div.innerHTML = '<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>'; div = div.firstChild; doc.body.appendChild(div); width = getScrollbarWidth.width = div.offsetWidth - div.clientWidth; doc.body.removeChild(div); } return width; }; var equalizeSizes = function() { var i, n, height_max, width, width_last, width_parent, $optgroups; $optgroups = $('[data-group]', self.$dropdown_content); n = $optgroups.length; if (!n || !self.$dropdown_content.width()) return; if (options.equalizeHeight) { height_max = 0; for (i = 0; i < n; i++) { height_max = Math.max(height_max, $optgroups.eq(i).height()); } $optgroups.css({height: height_max}); } if (options.equalizeWidth) { width_parent = self.$dropdown_content.innerWidth() - getScrollbarWidth(); width = Math.round(width_parent / n); $optgroups.css({width: width}); if (n > 1) { width_last = width_parent - width * (n - 1); $optgroups.eq(n - 1).css({width: width_last}); } } }; if (options.equalizeHeight || options.equalizeWidth) { hook.after(this, 'positionDropdown', equalizeSizes); hook.after(this, 'refreshOptions', equalizeSizes); } }); Selectize.define('remove_button', function(options) { if (this.settings.mode === 'single') return; options = $.extend({ label : '×', title : 'Remove', className : 'remove', append : true }, options); var self = this; var html = '<a href="javascript:void(0)" class="' + options.className + '" tabindex="-1" title="' + escape_html(options.title) + '">' + options.label + '</a>'; /** * Appends an element as a child (with raw HTML). * * @param {string} html_container * @param {string} html_element * @return {string} */ var append = function(html_container, html_element) { var pos = html_container.search(/(<\/[^>]+>\s*)$/); return html_container.substring(0, pos) + html_element + html_container.substring(pos); }; this.setup = (function() { var original = self.setup; return function() { // override the item rendering method to add the button to each if (options.append) { var render_item = self.settings.render.item; self.settings.render.item = function(data) { return append(render_item.apply(this, arguments), html); }; } original.apply(this, arguments); // add event listener this.$control.on('click', '.' + options.className, function(e) { e.preventDefault(); if (self.isLocked) return; var $item = $(e.currentTarget).parent(); self.setActiveItem($item); if (self.deleteSelection()) { self.setCaret(self.items.length); } }); }; })(); }); Selectize.define('restore_on_backspace', function(options) { var self = this; options.text = options.text || function(option) { return option[this.settings.labelField]; }; this.onKeyDown = (function() { var original = self.onKeyDown; return function(e) { var index, option; if (e.keyCode === KEY_BACKSPACE && this.$control_input.val() === '' && !this.$activeItems.length) { index = this.caretPos - 1; if (index >= 0 && index < this.items.length) { option = this.options[this.items[index]]; if (this.deleteSelection(e)) { this.setTextboxValue(options.text.apply(this, [option])); this.refreshOptions(true); } e.preventDefault(); return; } } return original.apply(this, arguments); }; })(); }); return Selectize; })); ;/* globals define */ define('ember/load-initializers', ['exports', 'ember-load-initializers', 'ember'], function(exports, loadInitializers, Ember) { Ember['default'].deprecate( 'Usage of `' + 'ember/load-initializers' + '` module is deprecated, please update to `ember-load-initializers`.', false, { id: 'ember-load-initializers.legacy-shims', until: '3.0.0' } ); exports['default'] = loadInitializers['default']; }); ;/* globals define */ function createDeprecatedModule(moduleId) { define(moduleId, ['exports', 'ember-resolver/resolver', 'ember'], function(exports, Resolver, Ember) { Ember['default'].deprecate( 'Usage of `' + moduleId + '` module is deprecated, please update to `ember-resolver`.', false, { id: 'ember-resolver.legacy-shims', until: '3.0.0' } ); exports['default'] = Resolver['default']; }); } createDeprecatedModule('ember/resolver'); createDeprecatedModule('resolver'); ;;(function() { /*! * @overview Ember - JavaScript Application Framework * @copyright Copyright 2011-2016 Tilde Inc. and contributors * Portions Copyright 2006-2011 Strobe Inc. * Portions Copyright 2008-2011 Apple Inc. All rights reserved. * @license Licensed under MIT license * See https://raw.github.com/emberjs/ember.js/master/LICENSE * @version 2.8.0 */ var enifed, requireModule, require, Ember; var mainContext = this; (function() { var isNode = typeof window === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; if (!isNode) { Ember = this.Ember = this.Ember || {}; } if (typeof Ember === 'undefined') { Ember = {}; } if (typeof Ember.__loader === 'undefined') { var registry = {}; var seen = {}; enifed = function(name, deps, callback) { var value = { }; if (!callback) { value.deps = []; value.callback = deps; } else { value.deps = deps; value.callback = callback; } registry[name] = value; }; require = requireModule = function(name) { return internalRequire(name, null); }; // setup `require` module require['default'] = require; require.has = function registryHas(moduleName) { return !!registry[moduleName] || !!registry[moduleName + '/index']; }; function missingModule(name, referrerName) { if (referrerName) { throw new Error('Could not find module ' + name + ' required by: ' + referrerName); } else { throw new Error('Could not find module ' + name); } } function internalRequire(_name, referrerName) { var name = _name; var mod = registry[name]; if (!mod) { name = name + '/index'; mod = registry[name]; } var exports = seen[name]; if (exports !== undefined) { return exports; } exports = seen[name] = {}; if (!mod) { missingModule(_name, referrerName); } var deps = mod.deps; var callback = mod.callback; var reified = new Array(deps.length); for (var i = 0; i < deps.length; i++) { if (deps[i] === 'exports') { reified[i] = exports; } else if (deps[i] === 'require') { reified[i] = require; } else { reified[i] = internalRequire(deps[i], name); } } callback.apply(this, reified); return exports; } requireModule._eak_seen = registry; Ember.__loader = { define: enifed, require: require, registry: registry }; } else { enifed = Ember.__loader.define; require = requireModule = Ember.__loader.require; } })(); enifed('backburner', ['exports', 'backburner/utils', 'backburner/platform', 'backburner/binary-search', 'backburner/deferred-action-queues'], function (exports, _backburnerUtils, _backburnerPlatform, _backburnerBinarySearch, _backburnerDeferredActionQueues) { 'use strict'; exports.default = Backburner; function Backburner(queueNames, options) { this.queueNames = queueNames; this.options = options || {}; if (!this.options.defaultQueue) { this.options.defaultQueue = queueNames[0]; } this.instanceStack = []; this._debouncees = []; this._throttlers = []; this._eventCallbacks = { end: [], begin: [] }; var _this = this; this._boundClearItems = function () { clearItems(); }; this._timerTimeoutId = undefined; this._timers = []; this._platform = this.options._platform || _backburnerPlatform.default; this._boundRunExpiredTimers = function () { _this._runExpiredTimers(); }; } Backburner.prototype = { begin: function () { var options = this.options; var onBegin = options && options.onBegin; var previousInstance = this.currentInstance; if (previousInstance) { this.instanceStack.push(previousInstance); } this.currentInstance = new _backburnerDeferredActionQueues.default(this.queueNames, options); this._trigger('begin', this.currentInstance, previousInstance); if (onBegin) { onBegin(this.currentInstance, previousInstance); } }, end: function () { var options = this.options; var onEnd = options && options.onEnd; var currentInstance = this.currentInstance; var nextInstance = null; // Prevent double-finally bug in Safari 6.0.2 and iOS 6 // This bug appears to be resolved in Safari 6.0.5 and iOS 7 var finallyAlreadyCalled = false; try { currentInstance.flush(); } finally { if (!finallyAlreadyCalled) { finallyAlreadyCalled = true; this.currentInstance = null; if (this.instanceStack.length) { nextInstance = this.instanceStack.pop(); this.currentInstance = nextInstance; } this._trigger('end', currentInstance, nextInstance); if (onEnd) { onEnd(currentInstance, nextInstance); } } } }, /** Trigger an event. Supports up to two arguments. Designed around triggering transition events from one run loop instance to the next, which requires an argument for the first instance and then an argument for the next instance. @private @method _trigger @param {String} eventName @param {any} arg1 @param {any} arg2 */ _trigger: function (eventName, arg1, arg2) { var callbacks = this._eventCallbacks[eventName]; if (callbacks) { for (var i = 0; i < callbacks.length; i++) { callbacks[i](arg1, arg2); } } }, on: function (eventName, callback) { if (typeof callback !== 'function') { throw new TypeError('Callback must be a function'); } var callbacks = this._eventCallbacks[eventName]; if (callbacks) { callbacks.push(callback); } else { throw new TypeError('Cannot on() event "' + eventName + '" because it does not exist'); } }, off: function (eventName, callback) { if (eventName) { var callbacks = this._eventCallbacks[eventName]; var callbackFound = false; if (!callbacks) return; if (callback) { for (var i = 0; i < callbacks.length; i++) { if (callbacks[i] === callback) { callbackFound = true; callbacks.splice(i, 1); i--; } } } if (!callbackFound) { throw new TypeError('Cannot off() callback that does not exist'); } } else { throw new TypeError('Cannot off() event "' + eventName + '" because it does not exist'); } }, run: function () /* target, method, args */{ var length = arguments.length; var method, target, args; if (length === 1) { method = arguments[0]; target = null; } else { target = arguments[0]; method = arguments[1]; } if (_backburnerUtils.isString(method)) { method = target[method]; } if (length > 2) { args = new Array(length - 2); for (var i = 0, l = length - 2; i < l; i++) { args[i] = arguments[i + 2]; } } else { args = []; } var onError = getOnError(this.options); this.begin(); // guard against Safari 6's double-finally bug var didFinally = false; if (onError) { try { return method.apply(target, args); } catch (error) { onError(error); } finally { if (!didFinally) { didFinally = true; this.end(); } } } else { try { return method.apply(target, args); } finally { if (!didFinally) { didFinally = true; this.end(); } } } }, /* Join the passed method with an existing queue and execute immediately, if there isn't one use `Backburner#run`. The join method is like the run method except that it will schedule into an existing queue if one already exists. In either case, the join method will immediately execute the passed in function and return its result. @method join @param {Object} target @param {Function} method The method to be executed @param {any} args The method arguments @return method result */ join: function () /* target, method, args */{ if (!this.currentInstance) { return this.run.apply(this, arguments); } var length = arguments.length; var method, target; if (length === 1) { method = arguments[0]; target = null; } else { target = arguments[0]; method = arguments[1]; } if (_backburnerUtils.isString(method)) { method = target[method]; } if (length === 1) { return method(); } else if (length === 2) { return method.call(target); } else { var args = new Array(length - 2); for (var i = 0, l = length - 2; i < l; i++) { args[i] = arguments[i + 2]; } return method.apply(target, args); } }, /* Defer the passed function to run inside the specified queue. @method defer @param {String} queueName @param {Object} target @param {Function|String} method The method or method name to be executed @param {any} args The method arguments @return method result */ defer: function (queueName /* , target, method, args */) { var length = arguments.length; var method, target, args; if (length === 2) { method = arguments[1]; target = null; } else { target = arguments[1]; method = arguments[2]; } if (_backburnerUtils.isString(method)) { method = target[method]; } var stack = this.DEBUG ? new Error() : undefined; if (length > 3) { args = new Array(length - 3); for (var i = 3; i < length; i++) { args[i - 3] = arguments[i]; } } else { args = undefined; } if (!this.currentInstance) { createAutorun(this); } return this.currentInstance.schedule(queueName, target, method, args, false, stack); }, deferOnce: function (queueName /* , target, method, args */) { var length = arguments.length; var method, target, args; if (length === 2) { method = arguments[1]; target = null; } else { target = arguments[1]; method = arguments[2]; } if (_backburnerUtils.isString(method)) { method = target[method]; } var stack = this.DEBUG ? new Error() : undefined; if (length > 3) { args = new Array(length - 3); for (var i = 3; i < length; i++) { args[i - 3] = arguments[i]; } } else { args = undefined; } if (!this.currentInstance) { createAutorun(this); } return this.currentInstance.schedule(queueName, target, method, args, true, stack); }, setTimeout: function () { var l = arguments.length; var args = new Array(l); for (var x = 0; x < l; x++) { args[x] = arguments[x]; } var length = args.length, method, wait, target, methodOrTarget, methodOrWait, methodOrArgs; if (length === 0) { return; } else if (length === 1) { method = args.shift(); wait = 0; } else if (length === 2) { methodOrTarget = args[0]; methodOrWait = args[1]; if (_backburnerUtils.isFunction(methodOrWait) || _backburnerUtils.isFunction(methodOrTarget[methodOrWait])) { target = args.shift(); method = args.shift(); wait = 0; } else if (_backburnerUtils.isCoercableNumber(methodOrWait)) { method = args.shift(); wait = args.shift(); } else { method = args.shift(); wait = 0; } } else { var last = args[args.length - 1]; if (_backburnerUtils.isCoercableNumber(last)) { wait = args.pop(); } else { wait = 0; } methodOrTarget = args[0]; methodOrArgs = args[1]; if (_backburnerUtils.isFunction(methodOrArgs) || _backburnerUtils.isString(methodOrArgs) && methodOrTarget !== null && methodOrArgs in methodOrTarget) { target = args.shift(); method = args.shift(); } else { method = args.shift(); } } var executeAt = Date.now() + parseInt(wait !== wait ? 0 : wait, 10); if (_backburnerUtils.isString(method)) { method = target[method]; } var onError = getOnError(this.options); function fn() { if (onError) { try { method.apply(target, args); } catch (e) { onError(e); } } else { method.apply(target, args); } } return this._setTimeout(fn, executeAt); }, _setTimeout: function (fn, executeAt) { if (this._timers.length === 0) { this._timers.push(executeAt, fn); this._installTimerTimeout(); return fn; } // find position to insert var i = _backburnerBinarySearch.default(executeAt, this._timers); this._timers.splice(i, 0, executeAt, fn); // we should be the new earliest timer if i == 0 if (i === 0) { this._reinstallTimerTimeout(); } return fn; }, throttle: function (target, method /* , args, wait, [immediate] */) { var backburner = this; var args = new Array(arguments.length); for (var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } var immediate = args.pop(); var wait, throttler, index, timer; if (_backburnerUtils.isNumber(immediate) || _backburnerUtils.isString(immediate)) { wait = immediate; immediate = true; } else { wait = args.pop(); } wait = parseInt(wait, 10); index = findThrottler(target, method, this._throttlers); if (index > -1) { return this._throttlers[index]; } // throttled timer = this._platform.setTimeout(function () { if (!immediate) { backburner.run.apply(backburner, args); } var index = findThrottler(target, method, backburner._throttlers); if (index > -1) { backburner._throttlers.splice(index, 1); } }, wait); if (immediate) { this.run.apply(this, args); } throttler = [target, method, timer]; this._throttlers.push(throttler); return throttler; }, debounce: function (target, method /* , args, wait, [immediate] */) { var backburner = this; var args = new Array(arguments.length); for (var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } var immediate = args.pop(); var wait, index, debouncee, timer; if (_backburnerUtils.isNumber(immediate) || _backburnerUtils.isString(immediate)) { wait = immediate; immediate = false; } else { wait = args.pop(); } wait = parseInt(wait, 10); // Remove debouncee index = findDebouncee(target, method, this._debouncees); if (index > -1) { debouncee = this._debouncees[index]; this._debouncees.splice(index, 1); this._platform.clearTimeout(debouncee[2]); } timer = this._platform.setTimeout(function () { if (!immediate) { backburner.run.apply(backburner, args); } var index = findDebouncee(target, method, backburner._debouncees); if (index > -1) { backburner._debouncees.splice(index, 1); } }, wait); if (immediate && index === -1) { backburner.run.apply(backburner, args); } debouncee = [target, method, timer]; backburner._debouncees.push(debouncee); return debouncee; }, cancelTimers: function () { _backburnerUtils.each(this._throttlers, this._boundClearItems); this._throttlers = []; _backburnerUtils.each(this._debouncees, this._boundClearItems); this._debouncees = []; this._clearTimerTimeout(); this._timers = []; if (this._autorun) { this._platform.clearTimeout(this._autorun); this._autorun = null; } }, hasTimers: function () { return !!this._timers.length || !!this._debouncees.length || !!this._throttlers.length || this._autorun; }, cancel: function (timer) { var timerType = typeof timer; if (timer && timerType === 'object' && timer.queue && timer.method) { // we're cancelling a deferOnce return timer.queue.cancel(timer); } else if (timerType === 'function') { // we're cancelling a setTimeout for (var i = 0, l = this._timers.length; i < l; i += 2) { if (this._timers[i + 1] === timer) { this._timers.splice(i, 2); // remove the two elements if (i === 0) { this._reinstallTimerTimeout(); } return true; } } } else if (Object.prototype.toString.call(timer) === '[object Array]') { // we're cancelling a throttle or debounce return this._cancelItem(findThrottler, this._throttlers, timer) || this._cancelItem(findDebouncee, this._debouncees, timer); } else { return; // timer was null or not a timer } }, _cancelItem: function (findMethod, array, timer) { var item, index; if (timer.length < 3) { return false; } index = findMethod(timer[0], timer[1], array); if (index > -1) { item = array[index]; if (item[2] === timer[2]) { array.splice(index, 1); this._platform.clearTimeout(timer[2]); return true; } } return false; }, _runExpiredTimers: function () { this._timerTimeoutId = undefined; this.run(this, this._scheduleExpiredTimers); }, _scheduleExpiredTimers: function () { var n = Date.now(); var timers = this._timers; var i = 0; var l = timers.length; for (; i < l; i += 2) { var executeAt = timers[i]; var fn = timers[i + 1]; if (executeAt <= n) { this.schedule(this.options.defaultQueue, null, fn); } else { break; } } timers.splice(0, i); this._installTimerTimeout(); }, _reinstallTimerTimeout: function () { this._clearTimerTimeout(); this._installTimerTimeout(); }, _clearTimerTimeout: function () { if (!this._timerTimeoutId) { return; } this._platform.clearTimeout(this._timerTimeoutId); this._timerTimeoutId = undefined; }, _installTimerTimeout: function () { if (!this._timers.length) { return; } var minExpiresAt = this._timers[0]; var n = Date.now(); var wait = Math.max(0, minExpiresAt - n); this._timerTimeoutId = this._platform.setTimeout(this._boundRunExpiredTimers, wait); } }; Backburner.prototype.schedule = Backburner.prototype.defer; Backburner.prototype.scheduleOnce = Backburner.prototype.deferOnce; Backburner.prototype.later = Backburner.prototype.setTimeout; function getOnError(options) { return options.onError || options.onErrorTarget && options.onErrorTarget[options.onErrorMethod]; } function createAutorun(backburner) { backburner.begin(); backburner._autorun = backburner._platform.setTimeout(function () { backburner._autorun = null; backburner.end(); }); } function findDebouncee(target, method, debouncees) { return findItem(target, method, debouncees); } function findThrottler(target, method, throttlers) { return findItem(target, method, throttlers); } function findItem(target, method, collection) { var item; var index = -1; for (var i = 0, l = collection.length; i < l; i++) { item = collection[i]; if (item[0] === target && item[1] === method) { index = i; break; } } return index; } function clearItems(item) { this._platform.clearTimeout(item[2]); } }); enifed("backburner/binary-search", ["exports"], function (exports) { "use strict"; exports.default = binarySearch; function binarySearch(time, timers) { var start = 0; var end = timers.length - 2; var middle, l; while (start < end) { // since timers is an array of pairs 'l' will always // be an integer l = (end - start) / 2; // compensate for the index in case even number // of pairs inside timers middle = start + l - l % 2; if (time >= timers[middle]) { start = middle + 2; } else { end = middle; } } return time >= timers[start] ? start + 2 : start; } }); enifed('backburner/deferred-action-queues', ['exports', 'backburner/utils', 'backburner/queue'], function (exports, _backburnerUtils, _backburnerQueue) { 'use strict'; exports.default = DeferredActionQueues; function DeferredActionQueues(queueNames, options) { var queues = this.queues = {}; this.queueNames = queueNames = queueNames || []; this.options = options; _backburnerUtils.each(queueNames, function (queueName) { queues[queueName] = new _backburnerQueue.default(queueName, options[queueName], options); }); } function noSuchQueue(name) { throw new Error('You attempted to schedule an action in a queue (' + name + ') that doesn\'t exist'); } function noSuchMethod(name) { throw new Error('You attempted to schedule an action in a queue (' + name + ') for a method that doesn\'t exist'); } DeferredActionQueues.prototype = { schedule: function (name, target, method, args, onceFlag, stack) { var queues = this.queues; var queue = queues[name]; if (!queue) { noSuchQueue(name); } if (!method) { noSuchMethod(name); } if (onceFlag) { return queue.pushUnique(target, method, args, stack); } else { return queue.push(target, method, args, stack); } }, flush: function () { var queues = this.queues; var queueNames = this.queueNames; var queueName, queue; var queueNameIndex = 0; var numberOfQueues = queueNames.length; while (queueNameIndex < numberOfQueues) { queueName = queueNames[queueNameIndex]; queue = queues[queueName]; var numberOfQueueItems = queue._queue.length; if (numberOfQueueItems === 0) { queueNameIndex++; } else { queue.flush(false /* async */); queueNameIndex = 0; } } } }; }); enifed('backburner/platform', ['exports'], function (exports) { 'use strict'; var GlobalContext; /* global self */ if (typeof self === 'object') { GlobalContext = self; /* global global */ } else if (typeof global === 'object') { GlobalContext = global; /* global window */ } else if (typeof window === 'object') { GlobalContext = window; } else { throw new Error('no global: `self`, `global` nor `window` was found'); } exports.default = GlobalContext; }); enifed('backburner/queue', ['exports', 'backburner/utils'], function (exports, _backburnerUtils) { 'use strict'; exports.default = Queue; function Queue(name, options, globalOptions) { this.name = name; this.globalOptions = globalOptions || {}; this.options = options; this._queue = []; this.targetQueues = {}; this._queueBeingFlushed = undefined; } Queue.prototype = { push: function (target, method, args, stack) { var queue = this._queue; queue.push(target, method, args, stack); return { queue: this, target: target, method: method }; }, pushUniqueWithoutGuid: function (target, method, args, stack) { var queue = this._queue; for (var i = 0, l = queue.length; i < l; i += 4) { var currentTarget = queue[i]; var currentMethod = queue[i + 1]; if (currentTarget === target && currentMethod === method) { queue[i + 2] = args; // replace args queue[i + 3] = stack; // replace stack return; } } queue.push(target, method, args, stack); }, targetQueue: function (targetQueue, target, method, args, stack) { var queue = this._queue; for (var i = 0, l = targetQueue.length; i < l; i += 2) { var currentMethod = targetQueue[i]; var currentIndex = targetQueue[i + 1]; if (currentMethod === method) { queue[currentIndex + 2] = args; // replace args queue[currentIndex + 3] = stack; // replace stack return; } } targetQueue.push(method, queue.push(target, method, args, stack) - 4); }, pushUniqueWithGuid: function (guid, target, method, args, stack) { var hasLocalQueue = this.targetQueues[guid]; if (hasLocalQueue) { this.targetQueue(hasLocalQueue, target, method, args, stack); } else { this.targetQueues[guid] = [method, this._queue.push(target, method, args, stack) - 4]; } return { queue: this, target: target, method: method }; }, pushUnique: function (target, method, args, stack) { var KEY = this.globalOptions.GUID_KEY; if (target && KEY) { var guid = target[KEY]; if (guid) { return this.pushUniqueWithGuid(guid, target, method, args, stack); } } this.pushUniqueWithoutGuid(target, method, args, stack); return { queue: this, target: target, method: method }; }, invoke: function (target, method, args, _, _errorRecordedForStack) { if (args && args.length > 0) { method.apply(target, args); } else { method.call(target); } }, invokeWithOnError: function (target, method, args, onError, errorRecordedForStack) { try { if (args && args.length > 0) { method.apply(target, args); } else { method.call(target); } } catch (error) { onError(error, errorRecordedForStack); } }, flush: function (sync) { var queue = this._queue; var length = queue.length; if (length === 0) { return; } var globalOptions = this.globalOptions; var options = this.options; var before = options && options.before; var after = options && options.after; var onError = globalOptions.onError || globalOptions.onErrorTarget && globalOptions.onErrorTarget[globalOptions.onErrorMethod]; var target, method, args, errorRecordedForStack; var invoke = onError ? this.invokeWithOnError : this.invoke; this.targetQueues = Object.create(null); var queueItems = this._queueBeingFlushed = this._queue.slice(); this._queue = []; if (before) { before(); } for (var i = 0; i < length; i += 4) { target = queueItems[i]; method = queueItems[i + 1]; args = queueItems[i + 2]; errorRecordedForStack = queueItems[i + 3]; // Debugging assistance if (_backburnerUtils.isString(method)) { method = target[method]; } // method could have been nullified / canceled during flush if (method) { // // ** Attention intrepid developer ** // // To find out the stack of this task when it was scheduled onto // the run loop, add the following to your app.js: // // Ember.run.backburner.DEBUG = true; // NOTE: This slows your app, don't leave it on in production. // // Once that is in place, when you are at a breakpoint and navigate // here in the stack explorer, you can look at `errorRecordedForStack.stack`, // which will be the captured stack when this job was scheduled. // invoke(target, method, args, onError, errorRecordedForStack); } } if (after) { after(); } this._queueBeingFlushed = undefined; if (sync !== false && this._queue.length > 0) { // check if new items have been added this.flush(true); } }, cancel: function (actionToCancel) { var queue = this._queue, currentTarget, currentMethod, i, l; var target = actionToCancel.target; var method = actionToCancel.method; var GUID_KEY = this.globalOptions.GUID_KEY; if (GUID_KEY && this.targetQueues && target) { var targetQueue = this.targetQueues[target[GUID_KEY]]; if (targetQueue) { for (i = 0, l = targetQueue.length; i < l; i++) { if (targetQueue[i] === method) { targetQueue.splice(i, 1); } } } } for (i = 0, l = queue.length; i < l; i += 4) { currentTarget = queue[i]; currentMethod = queue[i + 1]; if (currentTarget === target && currentMethod === method) { queue.splice(i, 4); return true; } } // if not found in current queue // could be in the queue that is being flushed queue = this._queueBeingFlushed; if (!queue) { return; } for (i = 0, l = queue.length; i < l; i += 4) { currentTarget = queue[i]; currentMethod = queue[i + 1]; if (currentTarget === target && currentMethod === method) { // don't mess with array during flush // just nullify the method queue[i + 1] = null; return true; } } } }; }); enifed('backburner/utils', ['exports'], function (exports) { 'use strict'; exports.each = each; exports.isString = isString; exports.isFunction = isFunction; exports.isNumber = isNumber; exports.isCoercableNumber = isCoercableNumber; var NUMBER = /\d+/; function each(collection, callback) { for (var i = 0; i < collection.length; i++) { callback(collection[i]); } } function isString(suspect) { return typeof suspect === 'string'; } function isFunction(suspect) { return typeof suspect === 'function'; } function isNumber(suspect) { return typeof suspect === 'number'; } function isCoercableNumber(number) { return isNumber(number) || NUMBER.test(number); } }); enifed('ember-console/index', ['exports', 'ember-environment'], function (exports, _emberEnvironment) { 'use strict'; function K() {} function consoleMethod(name) { var consoleObj = undefined; if (_emberEnvironment.context.imports.console) { consoleObj = _emberEnvironment.context.imports.console; } else if (typeof console !== 'undefined') { consoleObj = console; } var method = typeof consoleObj === 'object' ? consoleObj[name] : null; if (typeof method !== 'function') { return; } if (typeof method.bind === 'function') { return method.bind(consoleObj); } return function () { method.apply(consoleObj, arguments); }; } function assertPolyfill(test, message) { if (!test) { try { // attempt to preserve the stack throw new Error('assertion failed: ' + message); } catch (error) { setTimeout(function () { throw error; }, 0); } } } /** Inside Ember-Metal, simply uses the methods from `imports.console`. Override this to provide more robust logging functionality. @class Logger @namespace Ember @public */ exports.default = { /** Logs the arguments to the console. You can pass as many arguments as you want and they will be joined together with a space. ```javascript var foo = 1; Ember.Logger.log('log value of foo:', foo); // "log value of foo: 1" will be printed to the console ``` @method log @for Ember.Logger @param {*} arguments @public */ log: consoleMethod('log') || K, /** Prints the arguments to the console with a warning icon. You can pass as many arguments as you want and they will be joined together with a space. ```javascript Ember.Logger.warn('Something happened!'); // "Something happened!" will be printed to the console with a warning icon. ``` @method warn @for Ember.Logger @param {*} arguments @public */ warn: consoleMethod('warn') || K, /** Prints the arguments to the console with an error icon, red text and a stack trace. You can pass as many arguments as you want and they will be joined together with a space. ```javascript Ember.Logger.error('Danger! Danger!'); // "Danger! Danger!" will be printed to the console in red text. ``` @method error @for Ember.Logger @param {*} arguments @public */ error: consoleMethod('error') || K, /** Logs the arguments to the console. You can pass as many arguments as you want and they will be joined together with a space. ```javascript var foo = 1; Ember.Logger.info('log value of foo:', foo); // "log value of foo: 1" will be printed to the console ``` @method info @for Ember.Logger @param {*} arguments @public */ info: consoleMethod('info') || K, /** Logs the arguments to the console in blue text. You can pass as many arguments as you want and they will be joined together with a space. ```javascript var foo = 1; Ember.Logger.debug('log value of foo:', foo); // "log value of foo: 1" will be printed to the console ``` @method debug @for Ember.Logger @param {*} arguments @public */ debug: consoleMethod('debug') || consoleMethod('info') || K, /** If the value passed into `Ember.Logger.assert` is not truthy it will throw an error with a stack trace. ```javascript Ember.Logger.assert(true); // undefined Ember.Logger.assert(true === false); // Throws an Assertion failed error. Ember.Logger.assert(true === false, 'Something invalid'); // Throws an Assertion failed error with message. ``` @method assert @for Ember.Logger @param {Boolean} bool Value to test @param {String} message Assertion message on failed @public */ assert: consoleMethod('assert') || assertPolyfill }; }); enifed('ember-debug/deprecate', ['exports', 'ember-metal/error', 'ember-console', 'ember-environment', 'ember-debug/handlers'], function (exports, _emberMetalError, _emberConsole, _emberEnvironment, _emberDebugHandlers) { /*global __fail__*/ 'use strict'; var _slice = Array.prototype.slice; exports.registerHandler = registerHandler; exports.default = deprecate; function registerHandler(handler) { _emberDebugHandlers.registerHandler('deprecate', handler); } function formatMessage(_message, options) { var message = _message; if (options && options.id) { message = message + (' [deprecation id: ' + options.id + ']'); } if (options && options.url) { message += ' See ' + options.url + ' for more details.'; } return message; } registerHandler(function logDeprecationToConsole(message, options) { var updatedMessage = formatMessage(message, options); _emberConsole.default.warn('DEPRECATION: ' + updatedMessage); }); var captureErrorForStack = undefined; if (new Error().stack) { captureErrorForStack = function () { return new Error(); }; } else { captureErrorForStack = function () { try { __fail__.fail(); } catch (e) { return e; } }; } registerHandler(function logDeprecationStackTrace(message, options, next) { if (_emberEnvironment.ENV.LOG_STACKTRACE_ON_DEPRECATION) { var stackStr = ''; var error = captureErrorForStack(); var stack = undefined; if (error.stack) { if (error['arguments']) { // Chrome stack = error.stack.replace(/^\s+at\s+/gm, '').replace(/^([^\(]+?)([\n$])/gm, '{anonymous}($1)$2').replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}($1)').split('\n'); stack.shift(); } else { // Firefox stack = error.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^\(/gm, '{anonymous}(').split('\n'); } stackStr = '\n ' + stack.slice(2).join('\n '); } var updatedMessage = formatMessage(message, options); _emberConsole.default.warn('DEPRECATION: ' + updatedMessage + stackStr); } else { next.apply(undefined, arguments); } }); registerHandler(function raiseOnDeprecation(message, options, next) { if (_emberEnvironment.ENV.RAISE_ON_DEPRECATION) { var updatedMessage = formatMessage(message); throw new _emberMetalError.default(updatedMessage); } else { next.apply(undefined, arguments); } }); var missingOptionsDeprecation = 'When calling `Ember.deprecate` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include `id` and `until` properties.'; exports.missingOptionsDeprecation = missingOptionsDeprecation; var missingOptionsIdDeprecation = 'When calling `Ember.deprecate` you must provide `id` in options.'; exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation; var missingOptionsUntilDeprecation = 'When calling `Ember.deprecate` you must provide `until` in options.'; exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation; /** @module ember @submodule ember-debug */ /** Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only). * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. @method deprecate @param {String} message A description of the deprecation. @param {Boolean} test A boolean. If falsy, the deprecation will be displayed. @param {Object} options @param {String} options.id A unique id for this deprecation. The id can be used by Ember debugging tools to change the behavior (raise, log or silence) for that specific deprecation. The id should be namespaced by dots, e.g. "view.helper.select". @param {string} options.until The version of Ember when this deprecation warning will be removed. @param {String} [options.url] An optional url to the transition guide on the emberjs.com website. @for Ember @public */ function deprecate(message, test, options) { if (!options || !options.id && !options.until) { deprecate(missingOptionsDeprecation, false, { id: 'ember-debug.deprecate-options-missing', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } if (options && !options.id) { deprecate(missingOptionsIdDeprecation, false, { id: 'ember-debug.deprecate-id-missing', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } if (options && !options.until) { deprecate(missingOptionsUntilDeprecation, options && options.until, { id: 'ember-debug.deprecate-until-missing', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } _emberDebugHandlers.invoke.apply(undefined, ['deprecate'].concat(_slice.call(arguments))); } }); enifed("ember-debug/handlers", ["exports"], function (exports) { "use strict"; exports.registerHandler = registerHandler; exports.invoke = invoke; var HANDLERS = {}; exports.HANDLERS = HANDLERS; function registerHandler(type, callback) { var nextHandler = HANDLERS[type] || function () {}; HANDLERS[type] = function (message, options) { callback(message, options, nextHandler); }; } function invoke(type, message, test, options) { if (test) { return; } var handlerForType = HANDLERS[type]; if (!handlerForType) { return; } if (handlerForType) { handlerForType(message, options); } } }); enifed('ember-debug/index', ['exports', 'ember-metal/core', 'ember-environment', 'ember-metal/testing', 'ember-metal/debug', 'ember-metal/features', 'ember-metal/error', 'ember-console', 'ember-debug/deprecate', 'ember-debug/warn'], function (exports, _emberMetalCore, _emberEnvironment, _emberMetalTesting, _emberMetalDebug, _emberMetalFeatures, _emberMetalError, _emberConsole, _emberDebugDeprecate, _emberDebugWarn) { 'use strict'; exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags; /** @module ember @submodule ember-debug */ /** @class Ember @public */ /** Define an assertion that will throw an exception if the condition is not met. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. ```javascript // Test for truthiness Ember.assert('Must pass a valid object', obj); // Fail unconditionally Ember.assert('This code path should never be run'); ``` @method assert @param {String} desc A description of the assertion. This will become the text of the Error thrown if the assertion fails. @param {Boolean} test Must be truthy for the assertion to pass. If falsy, an exception will be thrown. @public */ _emberMetalDebug.setDebugFunction('assert', function assert(desc, test) { if (!test) { throw new _emberMetalError.default('Assertion Failed: ' + desc); } }); /** Display a debug notice. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. ```javascript Ember.debug('I\'m a debug notice!'); ``` @method debug @param {String} message A debug message to display. @public */ _emberMetalDebug.setDebugFunction('debug', function debug(message) { _emberConsole.default.debug('DEBUG: ' + message); }); /** Display an info notice. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. @method info @private */ _emberMetalDebug.setDebugFunction('info', function info() { _emberConsole.default.info.apply(undefined, arguments); }); /** Alias an old, deprecated method with its new counterpart. Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only) when the assigned method is called. * In a production build, this method is defined as an empty function (NOP). ```javascript Ember.oldMethod = Ember.deprecateFunc('Please use the new, updated method', Ember.newMethod); ``` @method deprecateFunc @param {String} message A description of the deprecation. @param {Object} [options] The options object for Ember.deprecate. @param {Function} func The new function called to replace its deprecated counterpart. @return {Function} A new function that wraps the original function with a deprecation warning @private */ _emberMetalDebug.setDebugFunction('deprecateFunc', function deprecateFunc() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length === 3) { var _ret = (function () { var message = args[0]; var options = args[1]; var func = args[2]; return { v: function () { _emberMetalDebug.deprecate(message, false, options); return func.apply(this, arguments); } }; })(); if (typeof _ret === 'object') return _ret.v; } else { var _ret2 = (function () { var message = args[0]; var func = args[1]; return { v: function () { _emberMetalDebug.deprecate(message); return func.apply(this, arguments); } }; })(); if (typeof _ret2 === 'object') return _ret2.v; } }); /** Run a function meant for debugging. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. ```javascript Ember.runInDebug(() => { Ember.Component.reopen({ didInsertElement() { console.log("I'm happy"); } }); }); ``` @method runInDebug @param {Function} func The function to be executed. @since 1.5.0 @public */ _emberMetalDebug.setDebugFunction('runInDebug', function runInDebug(func) { func(); }); _emberMetalDebug.setDebugFunction('debugSeal', function debugSeal(obj) { Object.seal(obj); }); _emberMetalDebug.setDebugFunction('deprecate', _emberDebugDeprecate.default); _emberMetalDebug.setDebugFunction('warn', _emberDebugWarn.default); /** Will call `Ember.warn()` if ENABLE_OPTIONAL_FEATURES or any specific FEATURES flag is truthy. This method is called automatically in debug canary builds. @private @method _warnIfUsingStrippedFeatureFlags @return {void} */ function _warnIfUsingStrippedFeatureFlags(FEATURES, knownFeatures, featuresWereStripped) { if (featuresWereStripped) { _emberMetalDebug.warn('Ember.ENV.ENABLE_OPTIONAL_FEATURES is only available in canary builds.', !_emberEnvironment.ENV.ENABLE_OPTIONAL_FEATURES, { id: 'ember-debug.feature-flag-with-features-stripped' }); var keys = Object.keys(FEATURES || {}); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key === 'isEnabled' || !(key in knownFeatures)) { continue; } _emberMetalDebug.warn('FEATURE["' + key + '"] is set as enabled, but FEATURE flags are only available in canary builds.', !FEATURES[key], { id: 'ember-debug.feature-flag-with-features-stripped' }); } } } if (!_emberMetalTesting.isTesting()) { (function () { // Complain if they're using FEATURE flags in builds other than canary _emberMetalFeatures.FEATURES['features-stripped-test'] = true; var featuresWereStripped = true; if (false) { featuresWereStripped = false; } delete _emberMetalFeatures.FEATURES['features-stripped-test']; _warnIfUsingStrippedFeatureFlags(_emberEnvironment.ENV.FEATURES, _emberMetalFeatures.DEFAULT_FEATURES, featuresWereStripped); // Inform the developer about the Ember Inspector if not installed. var isFirefox = _emberEnvironment.environment.isFirefox; var isChrome = _emberEnvironment.environment.isChrome; if (typeof window !== 'undefined' && (isFirefox || isChrome) && window.addEventListener) { window.addEventListener('load', function () { if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset.emberExtension) { var downloadURL; if (isChrome) { downloadURL = 'https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi'; } else if (isFirefox) { downloadURL = 'https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/'; } _emberMetalDebug.debug('For more advanced debugging, install the Ember Inspector from ' + downloadURL); } }, false); } })(); } /** @public @class Ember.Debug */ _emberMetalCore.default.Debug = {}; /** Allows for runtime registration of handler functions that override the default deprecation behavior. Deprecations are invoked by calls to [Ember.deprecate](http://emberjs.com/api/classes/Ember.html#method_deprecate). The following example demonstrates its usage by registering a handler that throws an error if the message contains the word "should", otherwise defers to the default handler. ```javascript Ember.Debug.registerDeprecationHandler((message, options, next) => { if (message.indexOf('should') !== -1) { throw new Error(`Deprecation message with should: ${message}`); } else { // defer to whatever handler was registered before this one next(message, options); } } ``` The handler function takes the following arguments: <ul> <li> <code>message</code> - The message received from the deprecation call.</li> <li> <code>options</code> - An object passed in with the deprecation call containing additional information including:</li> <ul> <li> <code>id</code> - An id of the deprecation in the form of <code>package-name.specific-deprecation</code>.</li> <li> <code>until</code> - The Ember version number the feature and deprecation will be removed in.</li> </ul> <li> <code>next</code> - A function that calls into the previously registered handler.</li> </ul> @public @static @method registerDeprecationHandler @param handler {Function} A function to handle deprecation calls. @since 2.1.0 */ _emberMetalCore.default.Debug.registerDeprecationHandler = _emberDebugDeprecate.registerHandler; /** Allows for runtime registration of handler functions that override the default warning behavior. Warnings are invoked by calls made to [Ember.warn](http://emberjs.com/api/classes/Ember.html#method_warn). The following example demonstrates its usage by registering a handler that does nothing overriding Ember's default warning behavior. ```javascript // next is not called, so no warnings get the default behavior Ember.Debug.registerWarnHandler(() => {}); ``` The handler function takes the following arguments: <ul> <li> <code>message</code> - The message received from the warn call. </li> <li> <code>options</code> - An object passed in with the warn call containing additional information including:</li> <ul> <li> <code>id</code> - An id of the warning in the form of <code>package-name.specific-warning</code>.</li> </ul> <li> <code>next</code> - A function that calls into the previously registered handler.</li> </ul> @public @static @method registerWarnHandler @param handler {Function} A function to handle warnings. @since 2.1.0 */ _emberMetalCore.default.Debug.registerWarnHandler = _emberDebugWarn.registerHandler; /* We are transitioning away from `ember.js` to `ember.debug.js` to make it much clearer that it is only for local development purposes. This flag value is changed by the tooling (by a simple string replacement) so that if `ember.js` (which must be output for backwards compat reasons) is used a nice helpful warning message will be printed out. */ var runningNonEmberDebugJS = false; exports.runningNonEmberDebugJS = runningNonEmberDebugJS; if (runningNonEmberDebugJS) { _emberMetalDebug.warn('Please use `ember.debug.js` instead of `ember.js` for development and debugging.'); } }); // reexports enifed('ember-debug/warn', ['exports', 'ember-console', 'ember-metal/debug', 'ember-debug/handlers'], function (exports, _emberConsole, _emberMetalDebug, _emberDebugHandlers) { 'use strict'; var _slice = Array.prototype.slice; exports.registerHandler = registerHandler; exports.default = warn; function registerHandler(handler) { _emberDebugHandlers.registerHandler('warn', handler); } registerHandler(function logWarning(message, options) { _emberConsole.default.warn('WARNING: ' + message); if ('trace' in _emberConsole.default) { _emberConsole.default.trace(); } }); var missingOptionsDeprecation = 'When calling `Ember.warn` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include an `id` property.'; exports.missingOptionsDeprecation = missingOptionsDeprecation; var missingOptionsIdDeprecation = 'When calling `Ember.warn` you must provide `id` in options.'; exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation; /** @module ember @submodule ember-debug */ /** Display a warning with the provided message. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. @method warn @param {String} message A warning to display. @param {Boolean} test An optional boolean. If falsy, the warning will be displayed. @param {Object} options An object that can be used to pass a unique `id` for this warning. The `id` can be used by Ember debugging tools to change the behavior (raise, log, or silence) for that specific warning. The `id` should be namespaced by dots, e.g. "ember-debug.feature-flag-with-features-stripped" @for Ember @public */ function warn(message, test, options) { if (!options) { _emberMetalDebug.deprecate(missingOptionsDeprecation, false, { id: 'ember-debug.warn-options-missing', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } if (options && !options.id) { _emberMetalDebug.deprecate(missingOptionsIdDeprecation, false, { id: 'ember-debug.warn-id-missing', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' }); } _emberDebugHandlers.invoke.apply(undefined, ['warn'].concat(_slice.call(arguments))); } }); enifed('ember-environment/global', ['exports'], function (exports) { /* globals global, window, self, mainContext */ // from lodash to catch fake globals 'use strict'; function checkGlobal(value) { return value && value.Object === Object ? value : undefined; } // element ids can ruin global miss checks function checkElementIdShadowing(value) { return value && value.nodeType === undefined ? value : undefined; } // export real global exports.default = checkGlobal(checkElementIdShadowing(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || mainContext || // set before strict mode in Ember loader/wrapper new Function('return this')(); // eval outside of strict mode }); enifed('ember-environment/index', ['exports', 'ember-environment/global', 'ember-environment/utils'], function (exports, _emberEnvironmentGlobal, _emberEnvironmentUtils) { /* globals module */ 'use strict'; /** The hash of environment variables used to control various configuration settings. To specify your own or override default settings, add the desired properties to a global hash named `EmberENV` (or `ENV` for backwards compatibility with earlier versions of Ember). The `EmberENV` hash must be created before loading Ember. @class EmberENV @type Object @public */ var ENV = typeof _emberEnvironmentGlobal.default.EmberENV === 'object' && _emberEnvironmentGlobal.default.EmberENV || typeof _emberEnvironmentGlobal.default.ENV === 'object' && _emberEnvironmentGlobal.default.ENV || {}; exports.ENV = ENV; // ENABLE_ALL_FEATURES was documented, but you can't actually enable non optional features. if (ENV.ENABLE_ALL_FEATURES) { ENV.ENABLE_OPTIONAL_FEATURES = true; } /** Determines whether Ember should add to `Array`, `Function`, and `String` native object prototypes, a few extra methods in order to provide a more friendly API. We generally recommend leaving this option set to true however, if you need to turn it off, you can add the configuration property `EXTEND_PROTOTYPES` to `EmberENV` and set it to `false`. Note, when disabled (the default configuration for Ember Addons), you will instead have to access all methods and functions from the Ember namespace. @property EXTEND_PROTOTYPES @type Boolean @default true @for EmberENV @public */ ENV.EXTEND_PROTOTYPES = _emberEnvironmentUtils.normalizeExtendPrototypes(ENV.EXTEND_PROTOTYPES); /** The `LOG_STACKTRACE_ON_DEPRECATION` property, when true, tells Ember to log a full stack trace during deprecation warnings. @property LOG_STACKTRACE_ON_DEPRECATION @type Boolean @default true @for EmberENV @public */ ENV.LOG_STACKTRACE_ON_DEPRECATION = _emberEnvironmentUtils.defaultTrue(ENV.LOG_STACKTRACE_ON_DEPRECATION); /** The `LOG_VERSION` property, when true, tells Ember to log versions of all dependent libraries in use. @property LOG_VERSION @type Boolean @default true @for EmberENV @public */ ENV.LOG_VERSION = _emberEnvironmentUtils.defaultTrue(ENV.LOG_VERSION); // default false ENV.MODEL_FACTORY_INJECTIONS = _emberEnvironmentUtils.defaultFalse(ENV.MODEL_FACTORY_INJECTIONS); /** Debug parameter you can turn on. This will log all bindings that fire to the console. This should be disabled in production code. Note that you can also enable this from the console or temporarily. @property LOG_BINDINGS @for EmberENV @type Boolean @default false @public */ ENV.LOG_BINDINGS = _emberEnvironmentUtils.defaultFalse(ENV.LOG_BINDINGS); ENV.RAISE_ON_DEPRECATION = _emberEnvironmentUtils.defaultFalse(ENV.RAISE_ON_DEPRECATION); // check if window exists and actually is the global var hasDOM = typeof window !== 'undefined' && window === _emberEnvironmentGlobal.default && window.document && window.document.createElement && !ENV.disableBrowserEnvironment; // is this a public thing? // legacy imports/exports/lookup stuff (should we keep this??) var originalContext = _emberEnvironmentGlobal.default.Ember || {}; var context = { // import jQuery imports: originalContext.imports || _emberEnvironmentGlobal.default, // export Ember exports: originalContext.exports || _emberEnvironmentGlobal.default, // search for Namespaces lookup: originalContext.lookup || _emberEnvironmentGlobal.default }; exports.context = context; // TODO: cleanup single source of truth issues with this stuff var environment = hasDOM ? { hasDOM: true, isChrome: !!window.chrome && !window.opera, isFirefox: typeof InstallTrigger !== 'undefined', isPhantom: !!window.callPhantom, location: window.location, history: window.history, userAgent: window.navigator.userAgent, window: window } : { hasDOM: false, isChrome: false, isFirefox: false, isPhantom: false, location: null, history: null, userAgent: 'Lynx (textmode)', window: null }; exports.environment = environment; }); enifed("ember-environment/utils", ["exports"], function (exports) { "use strict"; exports.defaultTrue = defaultTrue; exports.defaultFalse = defaultFalse; exports.normalizeExtendPrototypes = normalizeExtendPrototypes; function defaultTrue(v) { return v === false ? false : true; } function defaultFalse(v) { return v === true ? true : false; } function normalizeExtendPrototypes(obj) { if (obj === false) { return { String: false, Array: false, Function: false }; } else if (!obj || obj === true) { return { String: true, Array: true, Function: true }; } else { return { String: defaultTrue(obj.String), Array: defaultTrue(obj.Array), Function: defaultTrue(obj.Function) }; } } }); enifed('ember-htmlbars-template-compiler/index', ['exports', 'ember-htmlbars-template-compiler/system/compile', 'ember-htmlbars-template-compiler/system/precompile', 'ember-htmlbars-template-compiler/system/compile-options'], function (exports, _emberHtmlbarsTemplateCompilerSystemCompile, _emberHtmlbarsTemplateCompilerSystemPrecompile, _emberHtmlbarsTemplateCompilerSystemCompileOptions) { 'use strict'; exports.compile = _emberHtmlbarsTemplateCompilerSystemCompile.default; exports.precompile = _emberHtmlbarsTemplateCompilerSystemPrecompile.default; exports.defaultCompileOptions = _emberHtmlbarsTemplateCompilerSystemCompileOptions.default; exports.registerPlugin = _emberHtmlbarsTemplateCompilerSystemCompileOptions.registerPlugin; }); enifed('ember-htmlbars-template-compiler/plugins/transform-closure-component-attrs-into-mut', ['exports'], function (exports) { 'use strict'; exports.default = TransformClosureComponentAttrsIntoMut; function TransformClosureComponentAttrsIntoMut() { // set later within HTMLBars to the syntax package this.syntax = null; } /** @private @method transform @param {AST} ast The AST to be transformed. */ TransformClosureComponentAttrsIntoMut.prototype.transform = function TransformClosureComponentAttrsIntoMut_transform(ast) { var b = this.syntax.builders; this.syntax.traverse(ast, { SubExpression: function (node) { if (isComponentClosure(node)) { mutParameters(b, node); } } }); return ast; }; function isComponentClosure(node) { return node.type === 'SubExpression' && node.path.original === 'component'; } function mutParameters(builder, node) { for (var i = 1; i < node.params.length; i++) { if (node.params[i].type === 'PathExpression') { node.params[i] = builder.sexpr(builder.path('@mut'), [node.params[i]]); } } for (var i = 0; i < node.hash.pairs.length; i++) { var pair = node.hash.pairs[i]; var value = pair.value; if (value.type === 'PathExpression') { pair.value = builder.sexpr(builder.path('@mut'), [pair.value]); } } } }); enifed('ember-htmlbars-template-compiler/plugins/transform-component-attrs-into-mut', ['exports'], function (exports) { 'use strict'; exports.default = TransformComponentAttrsIntoMut; function TransformComponentAttrsIntoMut() { // set later within HTMLBars to the syntax package this.syntax = null; } /** @private @method transform @param {AST} ast The AST to be transformed. */ TransformComponentAttrsIntoMut.prototype.transform = function TransformComponentAttrsIntoMut_transform(ast) { var b = this.syntax.builders; var walker = new this.syntax.Walker(); walker.visit(ast, function (node) { if (!validate(node)) { return; } for (var i = 0; i < node.hash.pairs.length; i++) { var pair = node.hash.pairs[i]; var value = pair.value; if (value.type === 'PathExpression') { pair.value = b.sexpr(b.path('@mut'), [pair.value]); } } }); return ast; }; function validate(node) { return node.type === 'BlockStatement' || node.type === 'MustacheStatement'; } }); enifed('ember-htmlbars-template-compiler/plugins/transform-component-curly-to-readonly', ['exports'], function (exports) { 'use strict'; exports.default = TransformComponentCurlyToReadonly; function TransformComponentCurlyToReadonly() { // set later within HTMLBars to the syntax package this.syntax = null; } /** @private @method transform @param {AST} ast The AST to be transformed. */ TransformComponentCurlyToReadonly.prototype.transform = function TransformComponetnCurlyToReadonly_transform(ast) { var b = this.syntax.builders; var walker = new this.syntax.Walker(); walker.visit(ast, function (node) { if (!validate(node)) { return; } for (var i = 0; i < node.attributes.length; i++) { var attr = node.attributes[i]; if (attr.value.type !== 'MustacheStatement') { return; } if (attr.value.params.length || attr.value.hash.pairs.length) { return; } attr.value = b.mustache(b.path('readonly'), [attr.value.path], null, !attr.value.escape); } }); return ast; }; function validate(node) { return node.type === 'ComponentNode'; } }); enifed('ember-htmlbars-template-compiler/system/compile-options', ['exports', 'ember/version', 'ember-metal/assign', 'ember-template-compiler/plugins', 'ember-htmlbars-template-compiler/plugins/transform-closure-component-attrs-into-mut', 'ember-htmlbars-template-compiler/plugins/transform-component-attrs-into-mut', 'ember-htmlbars-template-compiler/plugins/transform-component-curly-to-readonly'], function (exports, _emberVersion, _emberMetalAssign, _emberTemplateCompilerPlugins, _emberHtmlbarsTemplateCompilerPluginsTransformClosureComponentAttrsIntoMut, _emberHtmlbarsTemplateCompilerPluginsTransformComponentAttrsIntoMut, _emberHtmlbarsTemplateCompilerPluginsTransformComponentCurlyToReadonly) { /** @module ember @submodule ember-htmlbars */ 'use strict'; exports.registerPlugin = registerPlugin; exports.removePlugin = removePlugin; exports.default = compileOptions; var PLUGINS = [].concat(_emberTemplateCompilerPlugins.default, [ // the following are ember-htmlbars specific _emberHtmlbarsTemplateCompilerPluginsTransformClosureComponentAttrsIntoMut.default, _emberHtmlbarsTemplateCompilerPluginsTransformComponentAttrsIntoMut.default, _emberHtmlbarsTemplateCompilerPluginsTransformComponentCurlyToReadonly.default]); exports.PLUGINS = PLUGINS; var USER_PLUGINS = []; function mergePlugins() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; options = _emberMetalAssign.default({}, options); if (!options.plugins) { options.plugins = { ast: [].concat(USER_PLUGINS, PLUGINS) }; } else { var potententialPugins = [].concat(USER_PLUGINS, PLUGINS); var pluginsToAdd = potententialPugins.filter(function (plugin) { return options.plugins.ast.indexOf(plugin) === -1; }); options.plugins.ast = options.plugins.ast.slice().concat(pluginsToAdd); } return options; } function registerPlugin(type, PluginClass) { if (type !== 'ast') { throw new Error('Attempting to register ' + PluginClass + ' as "' + type + '" which is not a valid HTMLBars plugin type.'); } if (USER_PLUGINS.indexOf(PluginClass) === -1) { USER_PLUGINS = [PluginClass].concat(USER_PLUGINS); } } function removePlugin(type, PluginClass) { if (type !== 'ast') { throw new Error('Attempting to unregister ' + PluginClass + ' as "' + type + '" which is not a valid Glimmer plugin type.'); } USER_PLUGINS = USER_PLUGINS.filter(function (plugin) { return plugin !== PluginClass; }); } /** @private @property compileOptions */ function compileOptions(_options) { var disableComponentGeneration = true; var options = undefined; // When calling `Ember.Handlebars.compile()` a second argument of `true` // had a special meaning (long since lost), this just gaurds against // `options` being true, and causing an error during compilation. if (_options === true) { options = {}; } else { options = _options || {}; } options.disableComponentGeneration = disableComponentGeneration; options = mergePlugins(options); options.buildMeta = function buildMeta(program) { return { revision: 'Ember@' + _emberVersion.default, loc: program.loc, moduleName: options.moduleName }; }; return options; } }); enifed('ember-htmlbars-template-compiler/system/compile', ['exports', 'require', 'ember-htmlbars-template-compiler/system/compile-options'], function (exports, _require, _emberHtmlbarsTemplateCompilerSystemCompileOptions) { 'use strict'; exports.default = compiler; var compile = undefined, template = undefined; function compiler(string, options) { if (!template && _require.has('ember-htmlbars')) { template = _require.default('ember-htmlbars').template; } if (!compile && _require.has('htmlbars-compiler/compiler')) { compile = _require.default('htmlbars-compiler/compiler').compile; } if (!compile) { throw new Error('Cannot call `compile` without the template compiler loaded. Please load `ember-template-compiler.js` prior to calling `compile`.'); } if (!template) { throw new Error('Cannot call `compile` with only the template compiler loaded. Please load `ember.debug.js` or `ember.prod.js` prior to calling `compile`.'); } var templateSpec = compile(string, _emberHtmlbarsTemplateCompilerSystemCompileOptions.default(options)); return template(templateSpec); } }); enifed('ember-htmlbars-template-compiler/system/precompile', ['exports', 'ember-htmlbars-template-compiler/system/compile-options', 'require'], function (exports, _emberHtmlbarsTemplateCompilerSystemCompileOptions, _require) { 'use strict'; exports.default = precompile; var compileSpec = undefined; function precompile(templateString, options) { if (!compileSpec && _require.has('htmlbars-compiler/compiler')) { compileSpec = _require.default('htmlbars-compiler/compiler').compileSpec; } if (!compileSpec) { throw new Error('Cannot call `compileSpec` without the template compiler loaded. Please load `ember-template-compiler.js` prior to calling `compileSpec`.'); } return compileSpec(templateString, _emberHtmlbarsTemplateCompilerSystemCompileOptions.default(options)); } }); enifed('ember-metal/alias', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/error', 'ember-metal/properties', 'ember-metal/computed', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/dependent_keys'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalError, _emberMetalProperties, _emberMetalComputed, _emberMetalUtils, _emberMetalMeta, _emberMetalDependent_keys) { 'use strict'; exports.default = alias; exports.AliasedProperty = AliasedProperty; function alias(altKey) { return new AliasedProperty(altKey); } function AliasedProperty(altKey) { this.isDescriptor = true; this.altKey = altKey; this._dependentKeys = [altKey]; } AliasedProperty.prototype = Object.create(_emberMetalProperties.Descriptor.prototype); AliasedProperty.prototype.get = function AliasedProperty_get(obj, keyName) { return _emberMetalProperty_get.get(obj, this.altKey); }; AliasedProperty.prototype.set = function AliasedProperty_set(obj, keyName, value) { return _emberMetalProperty_set.set(obj, this.altKey, value); }; AliasedProperty.prototype.willWatch = function (obj, keyName) { _emberMetalDependent_keys.addDependentKeys(this, obj, keyName, _emberMetalMeta.meta(obj)); }; AliasedProperty.prototype.didUnwatch = function (obj, keyName) { _emberMetalDependent_keys.removeDependentKeys(this, obj, keyName, _emberMetalMeta.meta(obj)); }; AliasedProperty.prototype.setup = function (obj, keyName) { _emberMetalDebug.assert('Setting alias \'' + keyName + '\' on self', this.altKey !== keyName); var m = _emberMetalMeta.meta(obj); if (m.peekWatching(keyName)) { _emberMetalDependent_keys.addDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.teardown = function (obj, keyName) { var m = _emberMetalMeta.meta(obj); if (m.peekWatching(keyName)) { _emberMetalDependent_keys.removeDependentKeys(this, obj, keyName, m); } }; AliasedProperty.prototype.readOnly = function () { this.set = AliasedProperty_readOnlySet; return this; }; function AliasedProperty_readOnlySet(obj, keyName, value) { throw new _emberMetalError.default('Cannot set read-only property \'' + keyName + '\' on object: ' + _emberMetalUtils.inspect(obj)); } AliasedProperty.prototype.oneWay = function () { this.set = AliasedProperty_oneWaySet; return this; }; function AliasedProperty_oneWaySet(obj, keyName, value) { _emberMetalProperties.defineProperty(obj, keyName, null); return _emberMetalProperty_set.set(obj, keyName, value); } // Backwards compatibility with Ember Data. AliasedProperty.prototype._meta = undefined; AliasedProperty.prototype.meta = _emberMetalComputed.ComputedProperty.prototype.meta; }); enifed("ember-metal/assign", ["exports"], function (exports) { /** Copy properties from a source object to a target object. ```javascript var a = { first: 'Yehuda' }; var b = { last: 'Katz' }; var c = { company: 'Tilde Inc.' }; Ember.assign(a, b, c); // a === { first: 'Yehuda', last: 'Katz', company: 'Tilde Inc.' }, b === { last: 'Katz' }, c === { company: 'Tilde Inc.' } ``` @method assign @for Ember @param {Object} original The object to assign into @param {Object} ...args The objects to copy properties from @return {Object} @public */ "use strict"; exports.default = assign; function assign(original) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } for (var i = 0; i < args.length; i++) { var arg = args[i]; if (!arg) { continue; } var updates = Object.keys(arg); for (var _i = 0; _i < updates.length; _i++) { var prop = updates[_i]; original[prop] = arg[prop]; } } return original; } }); enifed('ember-metal/binding', ['exports', 'ember-console', 'ember-environment', 'ember-metal/run_loop', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set', 'ember-metal/utils', 'ember-metal/events', 'ember-metal/observer', 'ember-metal/path_cache'], function (exports, _emberConsole, _emberEnvironment, _emberMetalRun_loop, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set, _emberMetalUtils, _emberMetalEvents, _emberMetalObserver, _emberMetalPath_cache) { 'use strict'; exports.bind = bind; /** @module ember @submodule ember-metal */ // .......................................................... // BINDING // function Binding(toPath, fromPath) { // Configuration this._from = fromPath; this._to = toPath; this._oneWay = undefined; // State this._direction = undefined; this._readyToSync = undefined; this._fromObj = undefined; this._fromPath = undefined; this._toObj = undefined; } /** @class Binding @namespace Ember @deprecated See http://emberjs.com/deprecations/v2.x#toc_ember-binding @public */ Binding.prototype = { /** This copies the Binding so it can be connected to another object. @method copy @return {Ember.Binding} `this` @public */ copy: function () { var copy = new Binding(this._to, this._from); if (this._oneWay) { copy._oneWay = true; } return copy; }, // .......................................................... // CONFIG // /** This will set `from` property path to the specified value. It will not attempt to resolve this property path to an actual object until you connect the binding. The binding will search for the property path starting at the root object you pass when you `connect()` the binding. It follows the same rules as `get()` - see that method for more information. @method from @param {String} path The property path to connect to. @return {Ember.Binding} `this` @public */ from: function (path) { this._from = path; return this; }, /** This will set the `to` property path to the specified value. It will not attempt to resolve this property path to an actual object until you connect the binding. The binding will search for the property path starting at the root object you pass when you `connect()` the binding. It follows the same rules as `get()` - see that method for more information. @method to @param {String|Tuple} path A property path or tuple. @return {Ember.Binding} `this` @public */ to: function (path) { this._to = path; return this; }, /** Configures the binding as one way. A one-way binding will relay changes on the `from` side to the `to` side, but not the other way around. This means that if you change the `to` side directly, the `from` side may have a different value. @method oneWay @return {Ember.Binding} `this` @public */ oneWay: function () { this._oneWay = true; return this; }, /** @method toString @return {String} string representation of binding @public */ toString: function () { var oneWay = this._oneWay ? '[oneWay]' : ''; return 'Ember.Binding<' + _emberMetalUtils.guidFor(this) + '>(' + this._from + ' -> ' + this._to + ')' + oneWay; }, // .......................................................... // CONNECT AND SYNC // /** Attempts to connect this binding instance so that it can receive and relay changes. This method will raise an exception if you have not set the from/to properties yet. @method connect @param {Object} obj The root object for this binding. @return {Ember.Binding} `this` @public */ connect: function (obj) { _emberMetalDebug.assert('Must pass a valid object to Ember.Binding.connect()', !!obj); var fromObj = undefined, fromPath = undefined, possibleGlobal = undefined; // If the binding's "from" path could be interpreted as a global, verify // whether the path refers to a global or not by consulting `Ember.lookup`. if (_emberMetalPath_cache.isGlobalPath(this._from)) { var _name = _emberMetalPath_cache.getFirstKey(this._from); possibleGlobal = _emberEnvironment.context.lookup[_name]; if (possibleGlobal) { fromObj = possibleGlobal; fromPath = _emberMetalPath_cache.getTailPath(this._from); } } if (fromObj === undefined) { fromObj = obj; fromPath = this._from; } _emberMetalProperty_set.trySet(obj, this._to, _emberMetalProperty_get.get(fromObj, fromPath)); // Add an observer on the object to be notified when the binding should be updated. _emberMetalObserver.addObserver(fromObj, fromPath, this, 'fromDidChange'); // If the binding is a two-way binding, also set up an observer on the target. if (!this._oneWay) { _emberMetalObserver.addObserver(obj, this._to, this, 'toDidChange'); } _emberMetalEvents.addListener(obj, 'willDestroy', this, 'disconnect'); fireDeprecations(obj, this._to, this._from, possibleGlobal, this._oneWay, !possibleGlobal && !this._oneWay); this._readyToSync = true; this._fromObj = fromObj; this._fromPath = fromPath; this._toObj = obj; return this; }, /** Disconnects the binding instance. Changes will no longer be relayed. You will not usually need to call this method. @method disconnect @return {Ember.Binding} `this` @public */ disconnect: function () { _emberMetalDebug.assert('Must pass a valid object to Ember.Binding.disconnect()', !!this._toObj); // Remove an observer on the object so we're no longer notified of // changes that should update bindings. _emberMetalObserver.removeObserver(this._fromObj, this._fromPath, this, 'fromDidChange'); // If the binding is two-way, remove the observer from the target as well. if (!this._oneWay) { _emberMetalObserver.removeObserver(this._toObj, this._to, this, 'toDidChange'); } this._readyToSync = false; // Disable scheduled syncs... return this; }, // .......................................................... // PRIVATE // /* Called when the from side changes. */ fromDidChange: function (target) { this._scheduleSync('fwd'); }, /* Called when the to side changes. */ toDidChange: function (target) { this._scheduleSync('back'); }, _scheduleSync: function (dir) { var existingDir = this._direction; // If we haven't scheduled the binding yet, schedule it. if (existingDir === undefined) { _emberMetalRun_loop.default.schedule('sync', this, '_sync'); this._direction = dir; } // If both a 'back' and 'fwd' sync have been scheduled on the same object, // default to a 'fwd' sync so that it remains deterministic. if (existingDir === 'back' && dir === 'fwd') { this._direction = 'fwd'; } }, _sync: function () { var log = _emberEnvironment.ENV.LOG_BINDINGS; var toObj = this._toObj; // Don't synchronize destroyed objects or disconnected bindings. if (toObj.isDestroyed || !this._readyToSync) { return; } // Get the direction of the binding for the object we are // synchronizing from. var direction = this._direction; var fromObj = this._fromObj; var fromPath = this._fromPath; this._direction = undefined; // If we're synchronizing from the remote object... if (direction === 'fwd') { var fromValue = _emberMetalProperty_get.get(fromObj, fromPath); if (log) { _emberConsole.default.log(' ', this.toString(), '->', fromValue, fromObj); } if (this._oneWay) { _emberMetalProperty_set.trySet(toObj, this._to, fromValue); } else { _emberMetalObserver._suspendObserver(toObj, this._to, this, 'toDidChange', function () { _emberMetalProperty_set.trySet(toObj, this._to, fromValue); }); } // If we're synchronizing *to* the remote object. } else if (direction === 'back') { var toValue = _emberMetalProperty_get.get(toObj, this._to); if (log) { _emberConsole.default.log(' ', this.toString(), '<-', toValue, toObj); } _emberMetalObserver._suspendObserver(fromObj, fromPath, this, 'fromDidChange', function () { _emberMetalProperty_set.trySet(fromObj, fromPath, toValue); }); } } }; function fireDeprecations(obj, toPath, fromPath, deprecateGlobal, deprecateOneWay, deprecateAlias) { var deprecateGlobalMessage = '`Ember.Binding` is deprecated. Since you' + ' are binding to a global consider using a service instead.'; var deprecateOneWayMessage = '`Ember.Binding` is deprecated. Since you' + ' are using a `oneWay` binding consider using a `readOnly` computed' + ' property instead.'; var deprecateAliasMessage = '`Ember.Binding` is deprecated. Consider' + ' using an `alias` computed property instead.'; var objectInfo = 'The `' + toPath + '` property of `' + obj + '` is an `Ember.Binding` connected to `' + fromPath + '`, but '; _emberMetalDebug.deprecate(objectInfo + deprecateGlobalMessage, !deprecateGlobal, { id: 'ember-metal.binding', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_ember-binding' }); _emberMetalDebug.deprecate(objectInfo + deprecateOneWayMessage, !deprecateOneWay, { id: 'ember-metal.binding', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_ember-binding' }); _emberMetalDebug.deprecate(objectInfo + deprecateAliasMessage, !deprecateAlias, { id: 'ember-metal.binding', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_ember-binding' }); } function mixinProperties(to, from) { for (var key in from) { if (from.hasOwnProperty(key)) { to[key] = from[key]; } } } mixinProperties(Binding, { /* See `Ember.Binding.from`. @method from @static */ from: function (from) { var C = this; return new C(undefined, from); }, /* See `Ember.Binding.to`. @method to @static */ to: function (to) { var C = this; return new C(to, undefined); } }); /** An `Ember.Binding` connects the properties of two objects so that whenever the value of one property changes, the other property will be changed also. ## Automatic Creation of Bindings with `/^*Binding/`-named Properties. You do not usually create Binding objects directly but instead describe bindings in your class or object definition using automatic binding detection. Properties ending in a `Binding` suffix will be converted to `Ember.Binding` instances. The value of this property should be a string representing a path to another object or a custom binding instance created using Binding helpers (see "One Way Bindings"): ``` valueBinding: "MyApp.someController.title" ``` This will create a binding from `MyApp.someController.title` to the `value` property of your object instance automatically. Now the two values will be kept in sync. ## One Way Bindings One especially useful binding customization you can use is the `oneWay()` helper. This helper tells Ember that you are only interested in receiving changes on the object you are binding from. For example, if you are binding to a preference and you want to be notified if the preference has changed, but your object will not be changing the preference itself, you could do: ``` bigTitlesBinding: Ember.Binding.oneWay("MyApp.preferencesController.bigTitles") ``` This way if the value of `MyApp.preferencesController.bigTitles` changes the `bigTitles` property of your object will change also. However, if you change the value of your `bigTitles` property, it will not update the `preferencesController`. One way bindings are almost twice as fast to setup and twice as fast to execute because the binding only has to worry about changes to one side. You should consider using one way bindings anytime you have an object that may be created frequently and you do not intend to change a property; only to monitor it for changes (such as in the example above). ## Adding Bindings Manually All of the examples above show you how to configure a custom binding, but the result of these customizations will be a binding template, not a fully active Binding instance. The binding will actually become active only when you instantiate the object the binding belongs to. It is useful, however, to understand what actually happens when the binding is activated. For a binding to function it must have at least a `from` property and a `to` property. The `from` property path points to the object/key that you want to bind from while the `to` path points to the object/key you want to bind to. When you define a custom binding, you are usually describing the property you want to bind from (such as `MyApp.someController.value` in the examples above). When your object is created, it will automatically assign the value you want to bind `to` based on the name of your binding key. In the examples above, during init, Ember objects will effectively call something like this on your binding: ```javascript binding = Ember.Binding.from("valueBinding").to("value"); ``` This creates a new binding instance based on the template you provide, and sets the to path to the `value` property of the new object. Now that the binding is fully configured with a `from` and a `to`, it simply needs to be connected to become active. This is done through the `connect()` method: ```javascript binding.connect(this); ``` Note that when you connect a binding you pass the object you want it to be connected to. This object will be used as the root for both the from and to side of the binding when inspecting relative paths. This allows the binding to be automatically inherited by subclassed objects as well. This also allows you to bind between objects using the paths you declare in `from` and `to`: ```javascript // Example 1 binding = Ember.Binding.from("App.someObject.value").to("value"); binding.connect(this); // Example 2 binding = Ember.Binding.from("parentView.value").to("App.someObject.value"); binding.connect(this); ``` Now that the binding is connected, it will observe both the from and to side and relay changes. If you ever needed to do so (you almost never will, but it is useful to understand this anyway), you could manually create an active binding by using the `Ember.bind()` helper method. (This is the same method used by to setup your bindings on objects): ```javascript Ember.bind(MyApp.anotherObject, "value", "MyApp.someController.value"); ``` Both of these code fragments have the same effect as doing the most friendly form of binding creation like so: ```javascript MyApp.anotherObject = Ember.Object.create({ valueBinding: "MyApp.someController.value", // OTHER CODE FOR THIS OBJECT... }); ``` Ember's built in binding creation method makes it easy to automatically create bindings for you. You should always use the highest-level APIs available, even if you understand how it works underneath. @class Binding @namespace Ember @since Ember 0.9 @public */ // Ember.Binding = Binding; ES6TODO: where to put this? /** Global helper method to create a new binding. Just pass the root object along with a `to` and `from` path to create and connect the binding. @method bind @for Ember @param {Object} obj The root object of the transform. @param {String} to The path to the 'to' side of the binding. Must be relative to obj. @param {String} from The path to the 'from' side of the binding. Must be relative to obj or a global path. @return {Ember.Binding} binding instance @public */ function bind(obj, to, from) { return new Binding(to, from).connect(obj); } exports.Binding = Binding; }); enifed('ember-metal/cache', ['exports', 'ember-metal/empty_object'], function (exports, _emberMetalEmpty_object) { 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Cache = (function () { function Cache(limit, func, key, store) { _classCallCheck(this, Cache); this.size = 0; this.misses = 0; this.hits = 0; this.limit = limit; this.func = func; this.key = key; this.store = store || new DefaultStore(); } Cache.prototype.get = function get(obj) { var key = this.key === undefined ? obj : this.key(obj); var value = this.store.get(key); if (value === undefined) { this.misses++; value = this._set(key, this.func(obj)); } else if (value === UNDEFINED) { this.hits++; value = undefined; } else { this.hits++; // nothing to translate } return value; }; Cache.prototype.set = function set(obj, value) { var key = this.key === undefined ? obj : this.key(obj); return this._set(key, value); }; Cache.prototype._set = function _set(key, value) { if (this.limit > this.size) { this.size++; if (value === undefined) { this.store.set(key, UNDEFINED); } else { this.store.set(key, value); } } return value; }; Cache.prototype.purge = function purge() { this.store.clear(); this.size = 0; this.hits = 0; this.misses = 0; }; return Cache; })(); exports.default = Cache; function UNDEFINED() {} var DefaultStore = (function () { function DefaultStore() { _classCallCheck(this, DefaultStore); this.data = new _emberMetalEmpty_object.default(); } DefaultStore.prototype.get = function get(key) { return this.data[key]; }; DefaultStore.prototype.set = function set(key, value) { this.data[key] = value; }; DefaultStore.prototype.clear = function clear() { this.data = new _emberMetalEmpty_object.default(); }; return DefaultStore; })(); }); enifed('ember-metal/chains', ['exports', 'ember-metal/property_get', 'ember-metal/meta', 'ember-metal/watch_key', 'ember-metal/empty_object', 'ember-metal/watch_path'], function (exports, _emberMetalProperty_get, _emberMetalMeta, _emberMetalWatch_key, _emberMetalEmpty_object, _emberMetalWatch_path) { 'use strict'; exports.finishChains = finishChains; var FIRST_KEY = /^([^\.]+)/; function firstKey(path) { return path.match(FIRST_KEY)[0]; } function isObject(obj) { return obj && typeof obj === 'object'; } function isVolatile(obj) { return !(isObject(obj) && obj.isDescriptor && obj._volatile === false); } function ChainWatchers() { // chain nodes that reference a key in this obj by key // we only create ChainWatchers when we are going to add them // so create this upfront this.chains = new _emberMetalEmpty_object.default(); } ChainWatchers.prototype = { add: function (key, node) { var nodes = this.chains[key]; if (nodes === undefined) { this.chains[key] = [node]; } else { nodes.push(node); } }, remove: function (key, node) { var nodes = this.chains[key]; if (nodes) { for (var i = 0; i < nodes.length; i++) { if (nodes[i] === node) { nodes.splice(i, 1); break; } } } }, has: function (key, node) { var nodes = this.chains[key]; if (nodes) { for (var i = 0; i < nodes.length; i++) { if (nodes[i] === node) { return true; } } } return false; }, revalidateAll: function () { for (var key in this.chains) { this.notify(key, true, undefined); } }, revalidate: function (key) { this.notify(key, true, undefined); }, // key: the string key that is part of a path changed // revalidate: boolean; the chains that are watching this value should revalidate // callback: function that will be called with the object and path that // will be/are invalidated by this key change, depending on // whether the revalidate flag is passed notify: function (key, revalidate, callback) { var nodes = this.chains[key]; if (nodes === undefined || nodes.length === 0) { return; } var affected = undefined; if (callback) { affected = []; } for (var i = 0; i < nodes.length; i++) { nodes[i].notify(revalidate, affected); } if (callback === undefined) { return; } // we gather callbacks so we don't notify them during revalidation for (var i = 0; i < affected.length; i += 2) { var obj = affected[i]; var path = affected[i + 1]; callback(obj, path); } } }; function makeChainWatcher() { return new ChainWatchers(); } function addChainWatcher(obj, keyName, node) { if (!isObject(obj)) { return; } var m = _emberMetalMeta.meta(obj); m.writableChainWatchers(makeChainWatcher).add(keyName, node); _emberMetalWatch_key.watchKey(obj, keyName, m); } function removeChainWatcher(obj, keyName, node) { if (!isObject(obj)) { return; } var m = _emberMetalMeta.peekMeta(obj); if (!m || !m.readableChainWatchers()) { return; } // make meta writable m = _emberMetalMeta.meta(obj); m.readableChainWatchers().remove(keyName, node); _emberMetalWatch_key.unwatchKey(obj, keyName, m); } // A ChainNode watches a single key on an object. If you provide a starting // value for the key then the node won't actually watch it. For a root node // pass null for parent and key and object for value. function ChainNode(parent, key, value) { this._parent = parent; this._key = key; // _watching is true when calling get(this._parent, this._key) will // return the value of this node. // // It is false for the root of a chain (because we have no parent) // and for global paths (because the parent node is the object with // the observer on it) this._watching = value === undefined; this._chains = undefined; this._object = undefined; this.count = 0; this._value = value; this._paths = {}; if (this._watching) { this._object = parent.value(); if (this._object) { addChainWatcher(this._object, this._key, this); } } } function lazyGet(obj, key) { if (!obj) { return; } var meta = _emberMetalMeta.peekMeta(obj); // check if object meant only to be a prototype if (meta && meta.proto === obj) { return; } // Use `get` if the return value is an EachProxy or an uncacheable value. if (isVolatile(obj[key])) { return _emberMetalProperty_get.get(obj, key); // Otherwise attempt to get the cached value of the computed property } else { var cache = meta.readableCache(); if (cache && key in cache) { return cache[key]; } } } ChainNode.prototype = { value: function () { if (this._value === undefined && this._watching) { var obj = this._parent.value(); this._value = lazyGet(obj, this._key); } return this._value; }, destroy: function () { if (this._watching) { var obj = this._object; if (obj) { removeChainWatcher(obj, this._key, this); } this._watching = false; // so future calls do nothing } }, // copies a top level object only copy: function (obj) { var ret = new ChainNode(null, null, obj); var paths = this._paths; var path = undefined; for (path in paths) { // this check will also catch non-number vals. if (paths[path] <= 0) { continue; } ret.add(path); } return ret; }, // called on the root node of a chain to setup watchers on the specified // path. add: function (path) { var paths = this._paths; paths[path] = (paths[path] || 0) + 1; var key = firstKey(path); var tail = path.slice(key.length + 1); this.chain(key, tail); }, // called on the root node of a chain to teardown watcher on the specified // path remove: function (path) { var paths = this._paths; if (paths[path] > 0) { paths[path]--; } var key = firstKey(path); var tail = path.slice(key.length + 1); this.unchain(key, tail); }, chain: function (key, path) { var chains = this._chains; var node = undefined; if (chains === undefined) { chains = this._chains = new _emberMetalEmpty_object.default(); } else { node = chains[key]; } if (node === undefined) { node = chains[key] = new ChainNode(this, key, undefined); } node.count++; // count chains... // chain rest of path if there is one if (path) { key = firstKey(path); path = path.slice(key.length + 1); node.chain(key, path); } }, unchain: function (key, path) { var chains = this._chains; var node = chains[key]; // unchain rest of path first... if (path && path.length > 1) { var nextKey = firstKey(path); var nextPath = path.slice(nextKey.length + 1); node.unchain(nextKey, nextPath); } // delete node if needed. node.count--; if (node.count <= 0) { chains[node._key] = undefined; node.destroy(); } }, notify: function (revalidate, affected) { if (revalidate && this._watching) { var obj = this._parent.value(); if (obj !== this._object) { removeChainWatcher(this._object, this._key, this); this._object = obj; addChainWatcher(obj, this._key, this); } this._value = undefined; } // then notify chains... var chains = this._chains; var node = undefined; if (chains) { for (var key in chains) { node = chains[key]; if (node !== undefined) { node.notify(revalidate, affected); } } } if (affected && this._parent) { this._parent.populateAffected(this._key, 1, affected); } }, populateAffected: function (path, depth, affected) { if (this._key) { path = this._key + '.' + path; } if (this._parent) { this._parent.populateAffected(path, depth + 1, affected); } else { if (depth > 1) { affected.push(this.value(), path); } } } }; function finishChains(obj) { // We only create meta if we really have to var m = _emberMetalMeta.peekMeta(obj); if (m) { m = _emberMetalMeta.meta(obj); // finish any current chains node watchers that reference obj var chainWatchers = m.readableChainWatchers(); if (chainWatchers) { chainWatchers.revalidateAll(); } // ensure that if we have inherited any chains they have been // copied onto our own meta. if (m.readableChains()) { m.writableChains(_emberMetalWatch_path.makeChainNode); } } } exports.removeChainWatcher = removeChainWatcher; exports.ChainNode = ChainNode; }); enifed('ember-metal/computed', ['exports', 'ember-metal/debug', 'ember-metal/property_set', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/expand_properties', 'ember-metal/error', 'ember-metal/properties', 'ember-metal/property_events', 'ember-metal/dependent_keys'], function (exports, _emberMetalDebug, _emberMetalProperty_set, _emberMetalUtils, _emberMetalMeta, _emberMetalExpand_properties, _emberMetalError, _emberMetalProperties, _emberMetalProperty_events, _emberMetalDependent_keys) { 'use strict'; exports.default = computed; /** @module ember @submodule ember-metal */ function UNDEFINED() {} var DEEP_EACH_REGEX = /\.@each\.[^.]+\./; /** A computed property transforms an object literal with object's accessor function(s) into a property. By default the function backing the computed property will only be called once and the result will be cached. You can specify various properties that your computed property depends on. This will force the cached result to be recomputed if the dependencies are modified. In the following example we declare a computed property - `fullName` - by calling `.Ember.computed()` with property dependencies (`firstName` and `lastName`) as leading arguments and getter accessor function. The `fullName` getter function will be called once (regardless of how many times it is accessed) as long as its dependencies have not changed. Once `firstName` or `lastName` are updated any future calls (or anything bound) to `fullName` will incorporate the new values. ```javascript let Person = Ember.Object.extend({ // these will be supplied by `create` firstName: null, lastName: null, fullName: Ember.computed('firstName', 'lastName', function() { let firstName = this.get('firstName'), lastName = this.get('lastName'); return firstName + ' ' + lastName; }) }); let tom = Person.create({ firstName: 'Tom', lastName: 'Dale' }); tom.get('fullName') // 'Tom Dale' ``` You can also define what Ember should do when setting a computed property by providing additional function (`set`) in hash argument. If you try to set a computed property, it will try to invoke setter accessor function with the key and value you want to set it to as arguments. ```javascript let Person = Ember.Object.extend({ // these will be supplied by `create` firstName: null, lastName: null, fullName: Ember.computed('firstName', 'lastName', { get(key) { let firstName = this.get('firstName'), lastName = this.get('lastName'); return firstName + ' ' + lastName; }, set(key, value) { let [firstName, lastName] = value.split(' '); this.set('firstName', firstName); this.set('lastName', lastName); return value; } }) }); let person = Person.create(); person.set('fullName', 'Peter Wagenet'); person.get('firstName'); // 'Peter' person.get('lastName'); // 'Wagenet' ``` You can overwrite computed property with normal property (no longer computed), that won't change if dependencies change, if you set computed property and it won't have setter accessor function defined. You can also mark computed property as `.readOnly()` and block all attempts to set it. ```javascript let Person = Ember.Object.extend({ // these will be supplied by `create` firstName: null, lastName: null, fullName: Ember.computed('firstName', 'lastName', { get(key) { let firstName = this.get('firstName'); let lastName = this.get('lastName'); return firstName + ' ' + lastName; } }).readOnly() }); let person = Person.create(); person.set('fullName', 'Peter Wagenet'); // Uncaught Error: Cannot set read-only property "fullName" on object: <(...):emberXXX> ``` Additional resources: - [New CP syntax RFC](https://github.com/emberjs/rfcs/blob/master/text/0011-improved-cp-syntax.md) - [New computed syntax explained in "Ember 1.12 released" ](http://emberjs.com/blog/2015/05/13/ember-1-12-released.html#toc_new-computed-syntax) @class ComputedProperty @namespace Ember @public */ function ComputedProperty(config, opts) { this.isDescriptor = true; if (typeof config === 'function') { this._getter = config; } else { _emberMetalDebug.assert('Ember.computed expects a function or an object as last argument.', typeof config === 'object' && !Array.isArray(config)); _emberMetalDebug.assert('Config object passed to an Ember.computed can only contain `get` or `set` keys.', (function () { var keys = Object.keys(config); for (var i = 0; i < keys.length; i++) { if (keys[i] !== 'get' && keys[i] !== 'set') { return false; } } return true; })()); this._getter = config.get; this._setter = config.set; } _emberMetalDebug.assert('Computed properties must receive a getter or a setter, you passed none.', !!this._getter || !!this._setter); this._dependentKeys = undefined; this._suspended = undefined; this._meta = undefined; this._volatile = false; this._dependentKeys = opts && opts.dependentKeys; this._readOnly = false; } ComputedProperty.prototype = new _emberMetalProperties.Descriptor(); var ComputedPropertyPrototype = ComputedProperty.prototype; /** Call on a computed property to set it into non-cached mode. When in this mode the computed property will not automatically cache the return value. It also does not automatically fire any change events. You must manually notify any changes if you want to observe this property. Dependency keys have no effect on volatile properties as they are for cache invalidation and notification when cached value is invalidated. ```javascript let outsideService = Ember.Object.extend({ value: Ember.computed(function() { return OutsideService.getValue(); }).volatile() }).create(); ``` @method volatile @return {Ember.ComputedProperty} this @chainable @public */ ComputedPropertyPrototype.volatile = function () { this._volatile = true; return this; }; /** Call on a computed property to set it into read-only mode. When in this mode the computed property will throw an error when set. ```javascript let Person = Ember.Object.extend({ guid: Ember.computed(function() { return 'guid-guid-guid'; }).readOnly() }); let person = Person.create(); person.set('guid', 'new-guid'); // will throw an exception ``` @method readOnly @return {Ember.ComputedProperty} this @chainable @public */ ComputedPropertyPrototype.readOnly = function () { this._readOnly = true; _emberMetalDebug.assert('Computed properties that define a setter using the new syntax cannot be read-only', !(this._readOnly && this._setter && this._setter !== this._getter)); return this; }; /** Sets the dependent keys on this computed property. Pass any number of arguments containing key paths that this computed property depends on. ```javascript let President = Ember.Object.extend({ fullName: Ember.computed(function() { return this.get('firstName') + ' ' + this.get('lastName'); // Tell Ember that this computed property depends on firstName // and lastName }).property('firstName', 'lastName') }); let president = President.create({ firstName: 'Barack', lastName: 'Obama' }); president.get('fullName'); // 'Barack Obama' ``` @method property @param {String} path* zero or more property paths @return {Ember.ComputedProperty} this @chainable @public */ ComputedPropertyPrototype.property = function () { var args = []; function addArg(property) { _emberMetalDebug.warn('Dependent keys containing @each only work one level deep. ' + 'You cannot use nested forms like todos.@each.owner.name or todos.@each.owner.@each.name. ' + 'Please create an intermediary computed property.', DEEP_EACH_REGEX.test(property) === false, { id: 'ember-metal.computed-deep-each' }); args.push(property); } for (var i = 0; i < arguments.length; i++) { _emberMetalExpand_properties.default(arguments[i], addArg); } this._dependentKeys = args; return this; }; /** In some cases, you may want to annotate computed properties with additional metadata about how they function or what values they operate on. For example, computed property functions may close over variables that are then no longer available for introspection. You can pass a hash of these values to a computed property like this: ``` person: Ember.computed(function() { let personId = this.get('personId'); return App.Person.create({ id: personId }); }).meta({ type: App.Person }) ``` The hash that you pass to the `meta()` function will be saved on the computed property descriptor under the `_meta` key. Ember runtime exposes a public API for retrieving these values from classes, via the `metaForProperty()` function. @method meta @param {Object} meta @chainable @public */ ComputedPropertyPrototype.meta = function (meta) { if (arguments.length === 0) { return this._meta || {}; } else { this._meta = meta; return this; } }; // invalidate cache when CP key changes ComputedPropertyPrototype.didChange = function (obj, keyName) { // _suspended is set via a CP.set to ensure we don't clear // the cached value set by the setter if (this._volatile || this._suspended === obj) { return; } // don't create objects just to invalidate var meta = _emberMetalMeta.peekMeta(obj); if (!meta || meta.source !== obj) { return; } var cache = meta.readableCache(); if (cache && cache[keyName] !== undefined) { cache[keyName] = undefined; _emberMetalDependent_keys.removeDependentKeys(this, obj, keyName, meta); } }; ComputedPropertyPrototype.get = function (obj, keyName) { if (this._volatile) { return this._getter.call(obj, keyName); } var meta = _emberMetalMeta.meta(obj); var cache = meta.writableCache(); var result = cache[keyName]; if (result === UNDEFINED) { return undefined; } else if (result !== undefined) { return result; } var ret = this._getter.call(obj, keyName); if (ret === undefined) { cache[keyName] = UNDEFINED; } else { cache[keyName] = ret; } var chainWatchers = meta.readableChainWatchers(); if (chainWatchers) { chainWatchers.revalidate(keyName); } _emberMetalDependent_keys.addDependentKeys(this, obj, keyName, meta); return ret; }; ComputedPropertyPrototype.set = function computedPropertySetEntry(obj, keyName, value) { if (this._readOnly) { this._throwReadOnlyError(obj, keyName); } if (!this._setter) { return this.clobberSet(obj, keyName, value); } if (this._volatile) { return this.volatileSet(obj, keyName, value); } return this.setWithSuspend(obj, keyName, value); }; ComputedPropertyPrototype._throwReadOnlyError = function computedPropertyThrowReadOnlyError(obj, keyName) { throw new _emberMetalError.default('Cannot set read-only property "' + keyName + '" on object: ' + _emberMetalUtils.inspect(obj)); }; ComputedPropertyPrototype.clobberSet = function computedPropertyClobberSet(obj, keyName, value) { var cachedValue = cacheFor(obj, keyName); _emberMetalProperties.defineProperty(obj, keyName, null, cachedValue); _emberMetalProperty_set.set(obj, keyName, value); return value; }; ComputedPropertyPrototype.volatileSet = function computedPropertyVolatileSet(obj, keyName, value) { return this._setter.call(obj, keyName, value); }; ComputedPropertyPrototype.setWithSuspend = function computedPropertySetWithSuspend(obj, keyName, value) { var oldSuspended = this._suspended; this._suspended = obj; try { return this._set(obj, keyName, value); } finally { this._suspended = oldSuspended; } }; ComputedPropertyPrototype._set = function computedPropertySet(obj, keyName, value) { // cache requires own meta var meta = _emberMetalMeta.meta(obj); // either there is a writable cache or we need one to update var cache = meta.writableCache(); var hadCachedValue = false; var cachedValue = undefined; if (cache[keyName] !== undefined) { if (cache[keyName] !== UNDEFINED) { cachedValue = cache[keyName]; } hadCachedValue = true; } var ret = this._setter.call(obj, keyName, value, cachedValue); // allows setter to return the same value that is cached already if (hadCachedValue && cachedValue === ret) { return ret; } _emberMetalProperty_events.propertyWillChange(obj, keyName); if (hadCachedValue) { cache[keyName] = undefined; } if (!hadCachedValue) { _emberMetalDependent_keys.addDependentKeys(this, obj, keyName, meta); } if (ret === undefined) { cache[keyName] = UNDEFINED; } else { cache[keyName] = ret; } _emberMetalProperty_events.propertyDidChange(obj, keyName); return ret; }; /* called before property is overridden */ ComputedPropertyPrototype.teardown = function (obj, keyName) { if (this._volatile) { return; } var meta = _emberMetalMeta.meta(obj); var cache = meta.readableCache(); if (cache && cache[keyName] !== undefined) { _emberMetalDependent_keys.removeDependentKeys(this, obj, keyName, meta); cache[keyName] = undefined; } }; /** This helper returns a new property descriptor that wraps the passed computed property function. You can use this helper to define properties with mixins or via `Ember.defineProperty()`. If you pass a function as an argument, it will be used as a getter. A computed property defined in this way might look like this: ```js let Person = Ember.Object.extend({ init() { this._super(...arguments); this.firstName = 'Betty'; this.lastName = 'Jones'; }, fullName: Ember.computed('firstName', 'lastName', function() { return `${this.get('firstName')} ${this.get('lastName')}`; }) }); let client = Person.create(); client.get('fullName'); // 'Betty Jones' client.set('lastName', 'Fuller'); client.get('fullName'); // 'Betty Fuller' ``` You can pass a hash with two functions, `get` and `set`, as an argument to provide both a getter and setter: ```js let Person = Ember.Object.extend({ init() { this._super(...arguments); this.firstName = 'Betty'; this.lastName = 'Jones'; }, fullName: Ember.computed('firstName', 'lastName', { get(key) { return `${this.get('firstName')} ${this.get('lastName')}`; }, set(key, value) { let [firstName, lastName] = value.split(/\s+/); this.setProperties({ firstName, lastName }); return value; } }); }) let client = Person.create(); client.get('firstName'); // 'Betty' client.set('fullName', 'Carroll Fuller'); client.get('firstName'); // 'Carroll' ``` The `set` function should accept two parameters, `key` and `value`. The value returned from `set` will be the new value of the property. _Note: This is the preferred way to define computed properties when writing third-party libraries that depend on or use Ember, since there is no guarantee that the user will have [prototype Extensions](http://emberjs.com/guides/configuring-ember/disabling-prototype-extensions/) enabled._ The alternative syntax, with prototype extensions, might look like: ```js fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); }.property('firstName', 'lastName') ``` @class computed @namespace Ember @constructor @static @param {String} [dependentKeys*] Optional dependent keys that trigger this computed property. @param {Function} func The computed property function. @return {Ember.ComputedProperty} property descriptor instance @public */ function computed(func) { var args = undefined; if (arguments.length > 1) { args = [].slice.call(arguments); func = args.pop(); } var cp = new ComputedProperty(func); if (args) { cp.property.apply(cp, args); } return cp; } /** Returns the cached value for a property, if one exists. This can be useful for peeking at the value of a computed property that is generated lazily, without accidentally causing it to be created. @method cacheFor @for Ember @param {Object} obj the object whose property you want to check @param {String} key the name of the property whose cached value you want to return @return {Object} the cached value @public */ function cacheFor(obj, key) { var meta = _emberMetalMeta.peekMeta(obj); var cache = meta && meta.source === obj && meta.readableCache(); var ret = cache && cache[key]; if (ret === UNDEFINED) { return undefined; } return ret; } cacheFor.set = function (cache, key, value) { if (value === undefined) { cache[key] = UNDEFINED; } else { cache[key] = value; } }; cacheFor.get = function (cache, key) { var ret = cache[key]; if (ret === UNDEFINED) { return undefined; } return ret; }; cacheFor.remove = function (cache, key) { cache[key] = undefined; }; exports.ComputedProperty = ComputedProperty; exports.computed = computed; exports.cacheFor = cacheFor; }); enifed('ember-metal/core', ['exports', 'ember-environment'], function (exports, _emberEnvironment) { 'use strict'; /** @module ember @submodule ember-metal */ /** This namespace contains all Ember methods and functions. Future versions of Ember may overwrite this namespace and therefore, you should avoid adding any new properties. At the heart of Ember is Ember-Runtime, a set of core functions that provide cross-platform compatibility and object property observing. Ember-Runtime is small and performance-focused so you can use it alongside other cross-platform libraries such as jQuery. For more details, see [Ember-Runtime](http://emberjs.com/api/modules/ember-runtime.html). @class Ember @static @public */ var Ember = typeof _emberEnvironment.context.imports.Ember === 'object' && _emberEnvironment.context.imports.Ember || {}; // Make sure these are set whether Ember was already defined or not Ember.isNamespace = true; Ember.toString = function () { return 'Ember'; }; // .......................................................... // BOOTSTRAP // exports.default = Ember; }); enifed("ember-metal/debug", ["exports"], function (exports) { "use strict"; exports.getDebugFunction = getDebugFunction; exports.setDebugFunction = setDebugFunction; exports.assert = assert; exports.info = info; exports.warn = warn; exports.debug = debug; exports.deprecate = deprecate; exports.deprecateFunc = deprecateFunc; exports.runInDebug = runInDebug; exports.debugSeal = debugSeal; var debugFunctions = { assert: function () {}, info: function () {}, warn: function () {}, debug: function () {}, deprecate: function () {}, deprecateFunc: function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return args[args.length - 1]; }, runInDebug: function () {}, debugSeal: function () {} }; exports.debugFunctions = debugFunctions; function getDebugFunction(name) { return debugFunctions[name]; } function setDebugFunction(name, fn) { debugFunctions[name] = fn; } function assert() { return debugFunctions.assert.apply(undefined, arguments); } function info() { return debugFunctions.info.apply(undefined, arguments); } function warn() { return debugFunctions.warn.apply(undefined, arguments); } function debug() { return debugFunctions.debug.apply(undefined, arguments); } function deprecate() { return debugFunctions.deprecate.apply(undefined, arguments); } function deprecateFunc() { return debugFunctions.deprecateFunc.apply(undefined, arguments); } function runInDebug() { return debugFunctions.runInDebug.apply(undefined, arguments); } function debugSeal() { return debugFunctions.debugSeal.apply(undefined, arguments); } }); enifed('ember-metal/dependent_keys', ['exports', 'ember-metal/watching'], function (exports, _emberMetalWatching) { 'no use strict'; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed exports.addDependentKeys = addDependentKeys; exports.removeDependentKeys = removeDependentKeys; /** @module ember @submodule ember-metal */ // .......................................................... // DEPENDENT KEYS // function addDependentKeys(desc, obj, keyName, meta) { // the descriptor has a list of dependent keys, so // add all of its dependent keys. var idx = undefined, depKey = undefined; var depKeys = desc._dependentKeys; if (!depKeys) { return; } for (idx = 0; idx < depKeys.length; idx++) { depKey = depKeys[idx]; // Increment the number of times depKey depends on keyName. meta.writeDeps(depKey, keyName, (meta.peekDeps(depKey, keyName) || 0) + 1); // Watch the depKey _emberMetalWatching.watch(obj, depKey, meta); } } function removeDependentKeys(desc, obj, keyName, meta) { // the descriptor has a list of dependent keys, so // remove all of its dependent keys. var depKeys = desc._dependentKeys; if (!depKeys) { return; } for (var idx = 0; idx < depKeys.length; idx++) { var depKey = depKeys[idx]; // Decrement the number of times depKey depends on keyName. meta.writeDeps(depKey, keyName, (meta.peekDeps(depKey, keyName) || 0) - 1); // Unwatch the depKey _emberMetalWatching.unwatch(obj, depKey, meta); } } }); enifed('ember-metal/deprecate_property', ['exports', 'ember-metal/debug', 'ember-metal/property_get', 'ember-metal/property_set'], function (exports, _emberMetalDebug, _emberMetalProperty_get, _emberMetalProperty_set) { /** @module ember @submodule ember-metal */ 'use strict'; exports.deprecateProperty = deprecateProperty; /** Used internally to allow changing properties in a backwards compatible way, and print a helpful deprecation warning. @method deprecateProperty @param {Object} object The object to add the deprecated property to. @param {String} deprecatedKey The property to add (and print deprecation warnings upon accessing). @param {String} newKey The property that will be aliased. @private @since 1.7.0 */ function deprecateProperty(object, deprecatedKey, newKey, options) { function _deprecate() { _emberMetalDebug.deprecate('Usage of `' + deprecatedKey + '` is deprecated, use `' + newKey + '` instead.', false, options); } Object.defineProperty(object, deprecatedKey, { configurable: true, enumerable: false, set: function (value) { _deprecate(); _emberMetalProperty_set.set(this, newKey, value); }, get: function () { _deprecate(); return _emberMetalProperty_get.get(this, newKey); } }); } }); enifed('ember-metal/dictionary', ['exports', 'ember-metal/empty_object'], function (exports, _emberMetalEmpty_object) { 'use strict'; exports.default = makeDictionary; // the delete is meant to hint at runtimes that this object should remain in // dictionary mode. This is clearly a runtime specific hack, but currently it // appears worthwhile in some usecases. Please note, these deletes do increase // the cost of creation dramatically over a plain Object.create. And as this // only makes sense for long-lived dictionaries that aren't instantiated often. function makeDictionary(parent) { var dict = undefined; if (parent === null) { dict = new _emberMetalEmpty_object.default(); } else { dict = Object.create(parent); } dict['_dict'] = null; delete dict['_dict']; return dict; } }); enifed("ember-metal/empty_object", ["exports"], function (exports) { // This exists because `Object.create(null)` is absurdly slow compared // to `new EmptyObject()`. In either case, you want a null prototype // when you're treating the object instances as arbitrary dictionaries // and don't want your keys colliding with build-in methods on the // default object prototype. "use strict"; var proto = Object.create(null, { // without this, we will always still end up with (new // EmptyObject()).constructor === Object constructor: { value: undefined, enumerable: false, writable: true } }); function EmptyObject() {} EmptyObject.prototype = proto; exports.default = EmptyObject; }); enifed('ember-metal/error', ['exports'], function (exports) { 'use strict'; exports.default = EmberError; var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; /** A subclass of the JavaScript Error object for use in Ember. @class Error @namespace Ember @extends Error @constructor @public */ function EmberError() { var tmp = Error.apply(this, arguments); // Adds a `stack` property to the given error object that will yield the // stack trace at the time captureStackTrace was called. // When collecting the stack trace all frames above the topmost call // to this function, including that call, will be left out of the // stack trace. // This is useful because we can hide Ember implementation details // that are not very helpful for the user. if (Error.captureStackTrace) { Error.captureStackTrace(this, EmberError); } // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } } EmberError.prototype = Object.create(Error.prototype); }); enifed('ember-metal/error_handler', ['exports', 'ember-console', 'ember-metal/testing'], function (exports, _emberConsole, _emberMetalTesting) { 'use strict'; exports.getOnerror = getOnerror; exports.setOnerror = setOnerror; exports.dispatchError = dispatchError; exports.setDispatchOverride = setDispatchOverride; // To maintain stacktrace consistency across browsers var getStack = function (error) { var stack = error.stack; var message = error.message; if (stack.indexOf(message) === -1) { stack = message + '\n' + stack; } return stack; }; var onerror = undefined; // Ember.onerror getter function getOnerror() { return onerror; } // Ember.onerror setter function setOnerror(handler) { onerror = handler; } var dispatchOverride = undefined; // dispatch error function dispatchError(error) { if (dispatchOverride) { dispatchOverride(error); } else { defaultDispatch(error); } } // allows testing adapter to override dispatch function setDispatchOverride(handler) { dispatchOverride = handler; } function defaultDispatch(error) { if (_emberMetalTesting.isTesting()) { throw error; } if (onerror) { onerror(error); } else { _emberConsole.default.error(getStack(error)); } } }); enifed('ember-metal/events', ['exports', 'ember-metal/debug', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/meta_listeners'], function (exports, _emberMetalDebug, _emberMetalUtils, _emberMetalMeta, _emberMetalMeta_listeners) { 'no use strict'; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed /** @module ember @submodule ember-metal */ exports.accumulateListeners = accumulateListeners; exports.addListener = addListener; exports.removeListener = removeListener; exports.suspendListener = suspendListener; exports.suspendListeners = suspendListeners; exports.watchedEvents = watchedEvents; exports.sendEvent = sendEvent; exports.hasListeners = hasListeners; exports.listenersFor = listenersFor; exports.on = on; /* The event system uses a series of nested hashes to store listeners on an object. When a listener is registered, or when an event arrives, these hashes are consulted to determine which target and action pair to invoke. The hashes are stored in the object's meta hash, and look like this: // Object's meta hash { listeners: { // variable name: `listenerSet` "foo:changed": [ // variable name: `actions` target, method, flags ] } } */ function indexOf(array, target, method) { var index = -1; // hashes are added to the end of the event array // so it makes sense to start searching at the end // of the array and search in reverse for (var i = array.length - 3; i >= 0; i -= 3) { if (target === array[i] && method === array[i + 1]) { index = i; break; } } return index; } function accumulateListeners(obj, eventName, otherActions) { var meta = _emberMetalMeta.peekMeta(obj); if (!meta) { return; } var actions = meta.matchingListeners(eventName); var newActions = []; for (var i = actions.length - 3; i >= 0; i -= 3) { var target = actions[i]; var method = actions[i + 1]; var flags = actions[i + 2]; var actionIndex = indexOf(otherActions, target, method); if (actionIndex === -1) { otherActions.push(target, method, flags); newActions.push(target, method, flags); } } return newActions; } /** Add an event listener @method addListener @for Ember @param obj @param {String} eventName @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Boolean} once A flag whether a function should only be called once @public */ function addListener(obj, eventName, target, method, once) { _emberMetalDebug.assert('You must pass at least an object and event name to Ember.addListener', !!obj && !!eventName); _emberMetalDebug.deprecate('didInitAttrs called in ' + (obj && obj.toString && obj.toString()) + '.', eventName !== 'didInitAttrs', { id: 'ember-views.did-init-attrs', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_ember-component-didinitattrs' }); if (!method && 'function' === typeof target) { method = target; target = null; } var flags = 0; if (once) { flags |= _emberMetalMeta_listeners.ONCE; } _emberMetalMeta.meta(obj).addToListeners(eventName, target, method, flags); if ('function' === typeof obj.didAddListener) { obj.didAddListener(eventName, target, method); } } /** Remove an event listener Arguments should match those passed to `Ember.addListener`. @method removeListener @for Ember @param obj @param {String} eventName @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @public */ function removeListener(obj, eventName, target, method) { _emberMetalDebug.assert('You must pass at least an object and event name to Ember.removeListener', !!obj && !!eventName); if (!method && 'function' === typeof target) { method = target; target = null; } _emberMetalMeta.meta(obj).removeFromListeners(eventName, target, method, function () { if ('function' === typeof obj.didRemoveListener) { obj.didRemoveListener.apply(obj, arguments); } }); } /** Suspend listener during callback. This should only be used by the target of the event listener when it is taking an action that would cause the event, e.g. an object might suspend its property change listener while it is setting that property. @method suspendListener @for Ember @private @param obj @param {String} eventName @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Function} callback */ function suspendListener(obj, eventName, target, method, callback) { return suspendListeners(obj, [eventName], target, method, callback); } /** Suspends multiple listeners during a callback. @method suspendListeners @for Ember @private @param obj @param {Array} eventNames Array of event names @param {Object|Function} target A target object or a function @param {Function|String} method A function or the name of a function to be called on `target` @param {Function} callback */ function suspendListeners(obj, eventNames, target, method, callback) { if (!method && 'function' === typeof target) { method = target; target = null; } return _emberMetalMeta.meta(obj).suspendListeners(eventNames, target, method, callback); } /** Return a list of currently watched events @private @method watchedEvents @for Ember @param obj */ function watchedEvents(obj) { return _emberMetalMeta.meta(obj).watchedEvents(); } /** Send an event. The execution of suspended listeners is skipped, and once listeners are removed. A listener without a target is executed on the passed object. If an array of actions is not passed, the actions stored on the passed object are invoked. @method sendEvent @for Ember @param obj @param {String} eventName @param {Array} params Optional parameters for each listener. @param {Array} actions Optional array of actions (listeners). @return true @public */ function sendEvent(obj, eventName, params, actions) { if (!actions) { var meta = _emberMetalMeta.peekMeta(obj); actions = meta && meta.matchingListeners(eventName); } if (!actions || actions.length === 0) { return; } for (var i = actions.length - 3; i >= 0; i -= 3) { // looping in reverse for once listeners var target = actions[i]; var method = actions[i + 1]; var flags = actions[i + 2]; if (!method) { continue; } if (flags & _emberMetalMeta_listeners.SUSPENDED) { continue; } if (flags & _emberMetalMeta_listeners.ONCE) { removeListener(obj, eventName, target, method); } if (!target) { target = obj; } if ('string' === typeof method) { if (params) { _emberMetalUtils.applyStr(target, method, params); } else { target[method](); } } else { if (params) { method.apply(target, params); } else { method.call(target); } } } return true; } /** @private @method hasListeners @for Ember @param obj @param {String} eventName */ function hasListeners(obj, eventName) { var meta = _emberMetalMeta.peekMeta(obj); if (!meta) { return false; } return meta.matchingListeners(eventName).length > 0; } /** @private @method listenersFor @for Ember @param obj @param {String} eventName */ function listenersFor(obj, eventName) { var ret = []; var meta = _emberMetalMeta.peekMeta(obj); var actions = meta && meta.matchingListeners(eventName); if (!actions) { return ret; } for (var i = 0; i < actions.length; i += 3) { var target = actions[i]; var method = actions[i + 1]; ret.push([target, method]); } return ret; } /** Define a property as a function that should be executed when a specified event or events are triggered. ``` javascript let Job = Ember.Object.extend({ logCompleted: Ember.on('completed', function() { console.log('Job completed!'); }) }); let job = Job.create(); Ember.sendEvent(job, 'completed'); // Logs 'Job completed!' ``` @method on @for Ember @param {String} eventNames* @param {Function} func @return func @public */ function on() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var func = args.pop(); var events = args; func.__ember_listens__ = events; return func; } }); enifed('ember-metal/expand_properties', ['exports', 'ember-metal/debug'], function (exports, _emberMetalDebug) { 'use strict'; exports.default = expandProperties; /** @module ember @submodule ember-metal */ var SPLIT_REGEX = /\{|\}/; var END_WITH_EACH_REGEX = /\.@each$/; /** Expands `pattern`, invoking `callback` for each expansion. The only pattern supported is brace-expansion, anything else will be passed once to `callback` directly. Example ```js function echo(arg){ console.log(arg); } Ember.expandProperties('foo.bar', echo); //=> 'foo.bar' Ember.expandProperties('{foo,bar}', echo); //=> 'foo', 'bar' Ember.expandProperties('foo.{bar,baz}', echo); //=> 'foo.bar', 'foo.baz' Ember.expandProperties('{foo,bar}.baz', echo); //=> 'foo.baz', 'bar.baz' Ember.expandProperties('foo.{bar,baz}.[]', echo) //=> 'foo.bar.[]', 'foo.baz.[]' Ember.expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs' Ember.expandProperties('{foo}.bar.{baz}') //=> 'foo.bar.baz' ``` @method expandProperties @for Ember @private @param {String} pattern The property pattern to expand. @param {Function} callback The callback to invoke. It is invoked once per expansion, and is passed the expansion. */ function expandProperties(pattern, callback) { _emberMetalDebug.assert('A computed property key must be a string', typeof pattern === 'string'); _emberMetalDebug.assert('Brace expanded properties cannot contain spaces, e.g. "user.{firstName, lastName}" should be "user.{firstName,lastName}"', pattern.indexOf(' ') === -1); var parts = pattern.split(SPLIT_REGEX); var properties = [parts]; for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (part.indexOf(',') >= 0) { properties = duplicateAndReplace(properties, part.split(','), i); } } for (var i = 0; i < properties.length; i++) { callback(properties[i].join('').replace(END_WITH_EACH_REGEX, '.[]')); } } function duplicateAndReplace(properties, currentParts, index) { var all = []; properties.forEach(function (property) { currentParts.forEach(function (part) { var current = property.slice(0); current[index] = part; all.push(current); }); }); return all; } }); enifed('ember-metal/features', ['exports', 'ember-environment', 'ember-metal/assign', 'ember/features'], function (exports, _emberEnvironment, _emberMetalAssign, _emberFeatures) { 'use strict'; exports.default = isEnabled; /** The hash of enabled Canary features. Add to this, any canary features before creating your application. Alternatively (and recommended), you can also define `EmberENV.FEATURES` if you need to enable features flagged at runtime. @class FEATURES @namespace Ember @static @since 1.1.0 @public */ var FEATURES = _emberMetalAssign.default(_emberFeatures.default, _emberEnvironment.ENV.FEATURES); exports.FEATURES = FEATURES; /** Determine whether the specified `feature` is enabled. Used by Ember's build tools to exclude experimental features from beta/stable builds. You can define the following configuration options: * `EmberENV.ENABLE_OPTIONAL_FEATURES` - enable any features that have not been explicitly enabled/disabled. @method isEnabled @param {String} feature The feature to check @return {Boolean} @for Ember.FEATURES @since 1.1.0 @public */ function isEnabled(feature) { var featureValue = FEATURES[feature]; if (featureValue === true || featureValue === false || featureValue === undefined) { return featureValue; } else if (_emberEnvironment.ENV.ENABLE_OPTIONAL_FEATURES) { return true; } else { return false; } } exports.DEFAULT_FEATURES = _emberFeatures.default; }); enifed('ember-metal/get_properties', ['exports', 'ember-metal/property_get'], function (exports, _emberMetalProperty_get) { 'use strict'; exports.default = getProperties; /** To get multiple properties at once, call `Ember.getProperties` with an object followed by a list of strings or an array: ```javascript Ember.getProperties(record, 'firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` is equivalent to: ```javascript Ember.getProperties(record, ['firstName', 'lastName', 'zipCode']); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` @method getProperties @for Ember @param {Object} obj @param {String...|Array} list of keys to get @return {Object} @public */ function getProperties(obj) { var ret = {}; var propertyNames = arguments; var i = 1; if (arguments.length === 2 && Array.isArray(arguments[1])) { i = 0; propertyNames = arguments[1]; } for (; i < propertyNames.length; i++) { ret[propertyNames[i]] = _emberMetalProperty_get.get(obj, propertyNames[i]); } return ret; } }); enifed('ember-metal/index', ['exports', 'require', 'ember-environment', 'ember/version', 'ember-metal/core', 'ember-metal/debug', 'ember-metal/features', 'ember-metal/assign', 'ember-metal/merge', 'ember-metal/instrumentation', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/error', 'ember-metal/cache', 'ember-console', 'ember-metal/property_get', 'ember-metal/events', 'ember-metal/observer_set', 'ember-metal/property_events', 'ember-metal/properties', 'ember-metal/property_set', 'ember-metal/weak_map', 'ember-metal/map', 'ember-metal/get_properties', 'ember-metal/set_properties', 'ember-metal/watch_key', 'ember-metal/chains', 'ember-metal/watch_path', 'ember-metal/watching', 'ember-metal/expand_properties', 'ember-metal/computed', 'ember-metal/alias', 'ember-metal/observer', 'ember-metal/mixin', 'ember-metal/binding', 'ember-metal/path_cache', 'ember-metal/testing', 'ember-metal/error_handler', 'ember-metal/run_loop', 'ember-metal/libraries', 'ember-metal/is_none', 'ember-metal/is_empty', 'ember-metal/is_blank', 'ember-metal/is_present', 'backburner'], function (exports, _require, _emberEnvironment, _emberVersion, _emberMetalCore, _emberMetalDebug, _emberMetalFeatures, _emberMetalAssign, _emberMetalMerge, _emberMetalInstrumentation, _emberMetalUtils, _emberMetalMeta, _emberMetalError, _emberMetalCache, _emberConsole, _emberMetalProperty_get, _emberMetalEvents, _emberMetalObserver_set, _emberMetalProperty_events, _emberMetalProperties, _emberMetalProperty_set, _emberMetalWeak_map, _emberMetalMap, _emberMetalGet_properties, _emberMetalSet_properties, _emberMetalWatch_key, _emberMetalChains, _emberMetalWatch_path, _emberMetalWatching, _emberMetalExpand_properties, _emberMetalComputed, _emberMetalAlias, _emberMetalObserver, _emberMetalMixin, _emberMetalBinding, _emberMetalPath_cache, _emberMetalTesting, _emberMetalError_handler, _emberMetalRun_loop, _emberMetalLibraries, _emberMetalIs_none, _emberMetalIs_empty, _emberMetalIs_blank, _emberMetalIs_present, _backburner) { /** @module ember @submodule ember-metal */ // BEGIN IMPORTS 'use strict'; _emberMetalComputed.computed.alias = _emberMetalAlias.default; // END IMPORTS // BEGIN EXPORTS var EmberInstrumentation = _emberMetalCore.default.Instrumentation = {}; EmberInstrumentation.instrument = _emberMetalInstrumentation.instrument; EmberInstrumentation.subscribe = _emberMetalInstrumentation.subscribe; EmberInstrumentation.unsubscribe = _emberMetalInstrumentation.unsubscribe; EmberInstrumentation.reset = _emberMetalInstrumentation.reset; _emberMetalCore.default.instrument = _emberMetalInstrumentation.instrument; _emberMetalCore.default.subscribe = _emberMetalInstrumentation.subscribe; _emberMetalCore.default._Cache = _emberMetalCache.default; _emberMetalCore.default.generateGuid = _emberMetalUtils.generateGuid; _emberMetalCore.default.GUID_KEY = _emberMetalUtils.GUID_KEY; _emberMetalCore.default.NAME_KEY = _emberMetalMixin.NAME_KEY; _emberMetalCore.default.platform = { defineProperty: true, hasPropertyAccessors: true }; _emberMetalCore.default.Error = _emberMetalError.default; _emberMetalCore.default.guidFor = _emberMetalUtils.guidFor; _emberMetalCore.default.META_DESC = _emberMetalMeta.META_DESC; _emberMetalCore.default.meta = _emberMetalMeta.meta; _emberMetalCore.default.inspect = _emberMetalUtils.inspect; _emberMetalCore.default.tryCatchFinally = _emberMetalUtils.deprecatedTryCatchFinally; _emberMetalCore.default.makeArray = _emberMetalUtils.makeArray; _emberMetalCore.default.canInvoke = _emberMetalUtils.canInvoke; _emberMetalCore.default.tryInvoke = _emberMetalUtils.tryInvoke; _emberMetalCore.default.wrap = _emberMetalUtils.wrap; _emberMetalCore.default.apply = _emberMetalUtils.apply; _emberMetalCore.default.applyStr = _emberMetalUtils.applyStr; _emberMetalCore.default.uuid = _emberMetalUtils.uuid; _emberMetalCore.default.Logger = _emberConsole.default; _emberMetalCore.default.get = _emberMetalProperty_get.get; _emberMetalCore.default.getWithDefault = _emberMetalProperty_get.getWithDefault; _emberMetalCore.default._getPath = _emberMetalProperty_get._getPath; _emberMetalCore.default.on = _emberMetalEvents.on; _emberMetalCore.default.addListener = _emberMetalEvents.addListener; _emberMetalCore.default.removeListener = _emberMetalEvents.removeListener; _emberMetalCore.default._suspendListener = _emberMetalEvents.suspendListener; _emberMetalCore.default._suspendListeners = _emberMetalEvents.suspendListeners; _emberMetalCore.default.sendEvent = _emberMetalEvents.sendEvent; _emberMetalCore.default.hasListeners = _emberMetalEvents.hasListeners; _emberMetalCore.default.watchedEvents = _emberMetalEvents.watchedEvents; _emberMetalCore.default.listenersFor = _emberMetalEvents.listenersFor; _emberMetalCore.default.accumulateListeners = _emberMetalEvents.accumulateListeners; _emberMetalCore.default._ObserverSet = _emberMetalObserver_set.default; _emberMetalCore.default.propertyWillChange = _emberMetalProperty_events.propertyWillChange; _emberMetalCore.default.propertyDidChange = _emberMetalProperty_events.propertyDidChange; _emberMetalCore.default.overrideChains = _emberMetalProperty_events.overrideChains; _emberMetalCore.default.beginPropertyChanges = _emberMetalProperty_events.beginPropertyChanges; _emberMetalCore.default.endPropertyChanges = _emberMetalProperty_events.endPropertyChanges; _emberMetalCore.default.changeProperties = _emberMetalProperty_events.changeProperties; _emberMetalCore.default.defineProperty = _emberMetalProperties.defineProperty; _emberMetalCore.default.set = _emberMetalProperty_set.set; _emberMetalCore.default.trySet = _emberMetalProperty_set.trySet; if (false) { _emberMetalCore.default.WeakMap = _emberMetalWeak_map.default; } _emberMetalCore.default.OrderedSet = _emberMetalMap.OrderedSet; _emberMetalCore.default.Map = _emberMetalMap.Map; _emberMetalCore.default.MapWithDefault = _emberMetalMap.MapWithDefault; _emberMetalCore.default.getProperties = _emberMetalGet_properties.default; _emberMetalCore.default.setProperties = _emberMetalSet_properties.default; _emberMetalCore.default.watchKey = _emberMetalWatch_key.watchKey; _emberMetalCore.default.unwatchKey = _emberMetalWatch_key.unwatchKey; _emberMetalCore.default.removeChainWatcher = _emberMetalChains.removeChainWatcher; _emberMetalCore.default._ChainNode = _emberMetalChains.ChainNode; _emberMetalCore.default.finishChains = _emberMetalChains.finishChains; _emberMetalCore.default.watchPath = _emberMetalWatch_path.watchPath; _emberMetalCore.default.unwatchPath = _emberMetalWatch_path.unwatchPath; _emberMetalCore.default.watch = _emberMetalWatching.watch; _emberMetalCore.default.isWatching = _emberMetalWatching.isWatching; _emberMetalCore.default.unwatch = _emberMetalWatching.unwatch; _emberMetalCore.default.rewatch = _emberMetalWatching.rewatch; _emberMetalCore.default.destroy = _emberMetalWatching.destroy; _emberMetalCore.default.expandProperties = _emberMetalExpand_properties.default; _emberMetalCore.default.ComputedProperty = _emberMetalComputed.ComputedProperty; _emberMetalCore.default.computed = _emberMetalComputed.computed; _emberMetalCore.default.cacheFor = _emberMetalComputed.cacheFor; _emberMetalCore.default.addObserver = _emberMetalObserver.addObserver; _emberMetalCore.default.observersFor = _emberMetalObserver.observersFor; _emberMetalCore.default.removeObserver = _emberMetalObserver.removeObserver; _emberMetalCore.default._suspendObserver = _emberMetalObserver._suspendObserver; _emberMetalCore.default._suspendObservers = _emberMetalObserver._suspendObservers; _emberMetalCore.default.required = _emberMetalMixin.required; _emberMetalCore.default.aliasMethod = _emberMetalMixin.aliasMethod; _emberMetalCore.default.observer = _emberMetalMixin.observer; _emberMetalCore.default.immediateObserver = _emberMetalMixin._immediateObserver; _emberMetalCore.default.mixin = _emberMetalMixin.mixin; _emberMetalCore.default.Mixin = _emberMetalMixin.Mixin; _emberMetalCore.default.bind = _emberMetalBinding.bind; _emberMetalCore.default.Binding = _emberMetalBinding.Binding; _emberMetalCore.default.isGlobalPath = _emberMetalPath_cache.isGlobalPath; _emberMetalCore.default.run = _emberMetalRun_loop.default; /** @class Backburner @for Ember @private */ _emberMetalCore.default.Backburner = function () { _emberMetalDebug.deprecate('Usage of Ember.Backburner is deprecated.', false, { id: 'ember-metal.ember-backburner', until: '2.8.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-backburner' }); function BackburnerAlias(args) { return _backburner.default.apply(this, args); } BackburnerAlias.prototype = _backburner.default.prototype; return new BackburnerAlias(arguments); }; _emberMetalCore.default._Backburner = _backburner.default; /** The semantic version @property VERSION @type String @public */ _emberMetalCore.default.VERSION = _emberVersion.default; _emberMetalCore.default.libraries = _emberMetalLibraries.default; _emberMetalLibraries.default.registerCoreLibrary('Ember', _emberMetalCore.default.VERSION); _emberMetalCore.default.isNone = _emberMetalIs_none.default; _emberMetalCore.default.isEmpty = _emberMetalIs_empty.default; _emberMetalCore.default.isBlank = _emberMetalIs_blank.default; _emberMetalCore.default.isPresent = _emberMetalIs_present.default; _emberMetalCore.default.assign = Object.assign || _emberMetalAssign.default; _emberMetalCore.default.merge = _emberMetalMerge.default; _emberMetalCore.default.FEATURES = _emberMetalFeatures.FEATURES; _emberMetalCore.default.FEATURES.isEnabled = _emberMetalFeatures.default; _emberMetalCore.default.EXTEND_PROTOTYPES = _emberEnvironment.ENV.EXTEND_PROTOTYPES; // BACKWARDS COMPAT ACCESSORS FOR ENV FLAGS Object.defineProperty(_emberMetalCore.default, 'LOG_STACKTRACE_ON_DEPRECATION', { get: function () { return _emberEnvironment.ENV.LOG_STACKTRACE_ON_DEPRECATION; }, set: function (value) { _emberEnvironment.ENV.LOG_STACKTRACE_ON_DEPRECATION = !!value; }, enumerable: false }); Object.defineProperty(_emberMetalCore.default, 'LOG_VERSION', { get: function () { return _emberEnvironment.ENV.LOG_VERSION; }, set: function (value) { _emberEnvironment.ENV.LOG_VERSION = !!value; }, enumerable: false }); Object.defineProperty(_emberMetalCore.default, 'MODEL_FACTORY_INJECTIONS', { get: function () { return _emberEnvironment.ENV.MODEL_FACTORY_INJECTIONS; }, set: function (value) { _emberEnvironment.ENV.MODEL_FACTORY_INJECTIONS = !!value; }, enumerable: false }); Object.defineProperty(_emberMetalCore.default, 'LOG_BINDINGS', { get: function () { return _emberEnvironment.ENV.LOG_BINDINGS; }, set: function (value) { _emberEnvironment.ENV.LOG_BINDINGS = !!value; }, enumerable: false }); Object.defineProperty(_emberMetalCore.default, 'ENV', { get: function () { return _emberEnvironment.ENV; }, enumerable: false }); /** The context that Ember searches for namespace instances on. @private */ Object.defineProperty(_emberMetalCore.default, 'lookup', { get: function () { return _emberEnvironment.context.lookup; }, set: function (value) { _emberEnvironment.context.lookup = value; }, enumerable: false }); Object.defineProperty(_emberMetalCore.default, 'testing', { get: _emberMetalTesting.isTesting, set: _emberMetalTesting.setTesting, enumerable: false }); /** A function may be assigned to `Ember.onerror` to be called when Ember internals encounter an error. This is useful for specialized error handling and reporting code. ```javascript Ember.onerror = function(error) { Em.$.ajax('/report-error', 'POST', { stack: error.stack, otherInformation: 'whatever app state you want to provide' }); }; ``` Internally, `Ember.onerror` is used as Backburner's error handler. @event onerror @for Ember @param {Exception} error the error object @public */ Object.defineProperty(_emberMetalCore.default, 'onerror', { get: _emberMetalError_handler.getOnerror, set: _emberMetalError_handler.setOnerror, enumerable: false }); /** An empty function useful for some operations. Always returns `this`. @method K @return {Object} @public */ _emberMetalCore.default.K = function K() { return this; }; // The debug functions are exported to globals with `require` to // prevent babel-plugin-filter-imports from removing them. var debugModule = _require.default('ember-metal/debug'); _emberMetalCore.default.assert = debugModule.assert; _emberMetalCore.default.warn = debugModule.warn; _emberMetalCore.default.debug = debugModule.debug; _emberMetalCore.default.deprecate = debugModule.deprecate; _emberMetalCore.default.deprecateFunc = debugModule.deprecateFunc; _emberMetalCore.default.runInDebug = debugModule.runInDebug; // END EXPORTS // do this for side-effects of updating Ember.assert, warn, etc when // ember-debug is present // This needs to be called before any deprecateFunc if (_require.has('ember-debug')) { _require.default('ember-debug'); } else { _emberMetalCore.default.Debug = {}; _emberMetalCore.default.Debug.registerDeprecationHandler = function () {}; _emberMetalCore.default.Debug.registerWarnHandler = function () {}; } _emberMetalCore.default.create = _emberMetalDebug.deprecateFunc('Ember.create is deprecated in favor of Object.create', { id: 'ember-metal.ember-create', until: '3.0.0' }, Object.create); _emberMetalCore.default.keys = _emberMetalDebug.deprecateFunc('Ember.keys is deprecated in favor of Object.keys', { id: 'ember-metal.ember.keys', until: '3.0.0' }, Object.keys); /* globals module */ if (typeof module === 'object' && module.exports) { module.exports = _emberMetalCore.default; } else { _emberEnvironment.context.exports.Ember = _emberEnvironment.context.exports.Em = _emberMetalCore.default; } exports.default = _emberMetalCore.default; }); // reexports enifed('ember-metal/injected_property', ['exports', 'ember-metal/debug', 'ember-metal/computed', 'ember-metal/alias', 'ember-metal/properties', 'container/owner'], function (exports, _emberMetalDebug, _emberMetalComputed, _emberMetalAlias, _emberMetalProperties, _containerOwner) { 'use strict'; exports.default = InjectedProperty; /** Read-only property that returns the result of a container lookup. @class InjectedProperty @namespace Ember @constructor @param {String} type The container type the property will lookup @param {String} name (optional) The name the property will lookup, defaults to the property's name @private */ function InjectedProperty(type, name) { this.type = type; this.name = name; this._super$Constructor(injectedPropertyGet); AliasedPropertyPrototype.oneWay.call(this); } function injectedPropertyGet(keyName) { var desc = this[keyName]; var owner = _containerOwner.getOwner(this) || this.container; // fallback to `container` for backwards compat _emberMetalDebug.assert('InjectedProperties should be defined with the Ember.inject computed property macros.', desc && desc.isDescriptor && desc.type); _emberMetalDebug.assert('Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container.', owner); return owner.lookup(desc.type + ':' + (desc.name || keyName)); } InjectedProperty.prototype = Object.create(_emberMetalProperties.Descriptor.prototype); var InjectedPropertyPrototype = InjectedProperty.prototype; var ComputedPropertyPrototype = _emberMetalComputed.ComputedProperty.prototype; var AliasedPropertyPrototype = _emberMetalAlias.AliasedProperty.prototype; InjectedPropertyPrototype._super$Constructor = _emberMetalComputed.ComputedProperty; InjectedPropertyPrototype.get = ComputedPropertyPrototype.get; InjectedPropertyPrototype.readOnly = ComputedPropertyPrototype.readOnly; InjectedPropertyPrototype.teardown = ComputedPropertyPrototype.teardown; }); enifed('ember-metal/instrumentation', ['exports', 'ember-environment', 'ember-metal/features'], function (exports, _emberEnvironment, _emberMetalFeatures) { 'use strict'; exports.instrument = instrument; exports._instrumentStart = _instrumentStart; exports.subscribe = subscribe; exports.unsubscribe = unsubscribe; exports.reset = reset; /** The purpose of the Ember Instrumentation module is to provide efficient, general-purpose instrumentation for Ember. Subscribe to a listener by using `Ember.subscribe`: ```javascript Ember.subscribe("render", { before(name, timestamp, payload) { }, after(name, timestamp, payload) { } }); ``` If you return a value from the `before` callback, that same value will be passed as a fourth parameter to the `after` callback. Instrument a block of code by using `Ember.instrument`: ```javascript Ember.instrument("render.handlebars", payload, function() { // rendering logic }, binding); ``` Event names passed to `Ember.instrument` are namespaced by periods, from more general to more specific. Subscribers can listen for events by whatever level of granularity they are interested in. In the above example, the event is `render.handlebars`, and the subscriber listened for all events beginning with `render`. It would receive callbacks for events named `render`, `render.handlebars`, `render.container`, or even `render.handlebars.layout`. @class Instrumentation @namespace Ember @static @private */ var subscribers = []; exports.subscribers = subscribers; var cache = {}; function populateListeners(name) { var listeners = []; var subscriber = undefined; for (var i = 0; i < subscribers.length; i++) { subscriber = subscribers[i]; if (subscriber.regex.test(name)) { listeners.push(subscriber.object); } } cache[name] = listeners; return listeners; } var time = (function () { var perf = 'undefined' !== typeof window ? window.performance || {} : {}; var fn = perf.now || perf.mozNow || perf.webkitNow || perf.msNow || perf.oNow; // fn.bind will be available in all the browsers that support the advanced window.performance... ;-) return fn ? fn.bind(perf) : function () { return +new Date(); }; })(); /** Notifies event's subscribers, calls `before` and `after` hooks. @method instrument @namespace Ember.Instrumentation @param {String} [name] Namespaced event name. @param {Object} _payload @param {Function} callback Function that you're instrumenting. @param {Object} binding Context that instrument function is called with. @private */ function instrument(name, _payload, callback, binding) { if (arguments.length <= 3 && typeof _payload === 'function') { binding = callback; callback = _payload; _payload = undefined; } if (subscribers.length === 0) { return callback.call(binding); } var payload = _payload || {}; var finalizer = _instrumentStart(name, function () { return payload; }); if (finalizer) { return withFinalizer(callback, finalizer, payload, binding); } else { return callback.call(binding); } } var flaggedInstrument = undefined; if (false) { exports.flaggedInstrument = flaggedInstrument = instrument; } else { exports.flaggedInstrument = flaggedInstrument = function (name, payload, callback) { return callback(); }; } exports.flaggedInstrument = flaggedInstrument; function withFinalizer(callback, finalizer, payload, binding) { var result = undefined; try { result = callback.call(binding); } catch (e) { payload.exception = e; result = payload; } finally { finalizer(); return result; } } // private for now function _instrumentStart(name, _payload) { var listeners = cache[name]; if (!listeners) { listeners = populateListeners(name); } if (listeners.length === 0) { return; } var payload = _payload(); var STRUCTURED_PROFILE = _emberEnvironment.ENV.STRUCTURED_PROFILE; var timeName = undefined; if (STRUCTURED_PROFILE) { timeName = name + ': ' + payload.object; console.time(timeName); } var beforeValues = new Array(listeners.length); var i = undefined, listener = undefined; var timestamp = time(); for (i = 0; i < listeners.length; i++) { listener = listeners[i]; beforeValues[i] = listener.before(name, timestamp, payload); } return function _instrumentEnd() { var i = undefined, listener = undefined; var timestamp = time(); for (i = 0; i < listeners.length; i++) { listener = listeners[i]; if (typeof listener.after === 'function') { listener.after(name, timestamp, payload, beforeValues[i]); } } if (STRUCTURED_PROFILE) { console.timeEnd(timeName); } }; } /** Subscribes to a particular event or instrumented block of code. @method subscribe @namespace Ember.Instrumentation @param {String} [pattern] Namespaced event name. @param {Object} [object] Before and After hooks. @return {Subscriber} @private */ function subscribe(pattern, object) { var paths = pattern.split('.'); var path = undefined; var regex = []; for (var i = 0; i < paths.length; i++) { path = paths[i]; if (path === '*') { regex.push('[^\\.]*'); } else { regex.push(path); } } regex = regex.join('\\.'); regex = regex + '(\\..*)?'; var subscriber = { pattern: pattern, regex: new RegExp('^' + regex + '$'), object: object }; subscribers.push(subscriber); cache = {}; return subscriber; } /** Unsubscribes from a particular event or instrumented block of code. @method unsubscribe @namespace Ember.Instrumentation @param {Object} [subscriber] @private */ function unsubscribe(subscriber) { var index = undefined; for (var i = 0; i < subscribers.length; i++) { if (subscribers[i] === subscriber) { index = i; } } subscribers.splice(index, 1); cache = {}; } /** Resets `Ember.Instrumentation` by flushing list of subscribers. @method reset @namespace Ember.Instrumentation @private */ function reset() { subscribers.length = 0; cache = {}; } }); enifed('ember-metal/is_blank', ['exports', 'ember-metal/is_empty'], function (exports, _emberMetalIs_empty) { 'use strict'; exports.default = isBlank; /** A value is blank if it is empty or a whitespace string. ```javascript Ember.isBlank(); // true Ember.isBlank(null); // true Ember.isBlank(undefined); // true Ember.isBlank(''); // true Ember.isBlank([]); // true Ember.isBlank('\n\t'); // true Ember.isBlank(' '); // true Ember.isBlank({}); // false Ember.isBlank('\n\t Hello'); // false Ember.isBlank('Hello world'); // false Ember.isBlank([1,2,3]); // false ``` @method isBlank @for Ember @param {Object} obj Value to test @return {Boolean} @since 1.5.0 @public */ function isBlank(obj) { return _emberMetalIs_empty.default(obj) || typeof obj === 'string' && obj.match(/\S/) === null; } }); enifed('ember-metal/is_empty', ['exports', 'ember-metal/property_get', 'ember-metal/is_none'], function (exports, _emberMetalProperty_get, _emberMetalIs_none) { 'use strict'; exports.default = isEmpty; /** Verifies that a value is `null` or an empty string, empty array, or empty function. Constrains the rules on `Ember.isNone` by returning true for empty string and empty arrays. ```javascript Ember.isEmpty(); // true Ember.isEmpty(null); // true Ember.isEmpty(undefined); // true Ember.isEmpty(''); // true Ember.isEmpty([]); // true Ember.isEmpty({}); // false Ember.isEmpty('Adam Hawkins'); // false Ember.isEmpty([0,1,2]); // false Ember.isEmpty('\n\t'); // false Ember.isEmpty(' '); // false ``` @method isEmpty @for Ember @param {Object} obj Value to test @return {Boolean} @public */ function isEmpty(obj) { var none = _emberMetalIs_none.default(obj); if (none) { return none; } if (typeof obj.size === 'number') { return !obj.size; } var objectType = typeof obj; if (objectType === 'object') { var size = _emberMetalProperty_get.get(obj, 'size'); if (typeof size === 'number') { return !size; } } if (typeof obj.length === 'number' && objectType !== 'function') { return !obj.length; } if (objectType === 'object') { var _length = _emberMetalProperty_get.get(obj, 'length'); if (typeof _length === 'number') { return !_length; } } return false; } }); enifed("ember-metal/is_none", ["exports"], function (exports) { /** Returns true if the passed value is null or undefined. This avoids errors from JSLint complaining about use of ==, which can be technically confusing. ```javascript Ember.isNone(); // true Ember.isNone(null); // true Ember.isNone(undefined); // true Ember.isNone(''); // false Ember.isNone([]); // false Ember.isNone(function() {}); // false ``` @method isNone @for Ember @param {Object} obj Value to test @return {Boolean} @public */ "use strict"; exports.default = isNone; function isNone(obj) { return obj === null || obj === undefined; } }); enifed('ember-metal/is_present', ['exports', 'ember-metal/is_blank'], function (exports, _emberMetalIs_blank) { 'use strict'; exports.default = isPresent; /** A value is present if it not `isBlank`. ```javascript Ember.isPresent(); // false Ember.isPresent(null); // false Ember.isPresent(undefined); // false Ember.isPresent(''); // false Ember.isPresent(' '); // false Ember.isPresent('\n\t'); // false Ember.isPresent([]); // false Ember.isPresent({ length: 0 }) // false Ember.isPresent(false); // true Ember.isPresent(true); // true Ember.isPresent('string'); // true Ember.isPresent(0); // true Ember.isPresent(function() {}) // true Ember.isPresent({}); // true Ember.isPresent(false); // true Ember.isPresent('\n\t Hello'); // true Ember.isPresent([1,2,3]); // true ``` @method isPresent @for Ember @param {Object} obj Value to test @return {Boolean} @since 1.8.0 @public */ function isPresent(obj) { return !_emberMetalIs_blank.default(obj); } }); enifed('ember-metal/libraries', ['exports', 'ember-metal/debug', 'ember-metal/features'], function (exports, _emberMetalDebug, _emberMetalFeatures) { 'use strict'; exports.Libraries = Libraries; /** Helper class that allows you to register your library with Ember. Singleton created at `Ember.libraries`. @class Libraries @constructor @private */ function Libraries() { this._registry = []; this._coreLibIndex = 0; } Libraries.prototype = { constructor: Libraries, _getLibraryByName: function (name) { var libs = this._registry; var count = libs.length; for (var i = 0; i < count; i++) { if (libs[i].name === name) { return libs[i]; } } }, register: function (name, version, isCoreLibrary) { var index = this._registry.length; if (!this._getLibraryByName(name)) { if (isCoreLibrary) { index = this._coreLibIndex++; } this._registry.splice(index, 0, { name: name, version: version }); } else { _emberMetalDebug.warn('Library "' + name + '" is already registered with Ember.', false, { id: 'ember-metal.libraries-register' }); } }, registerCoreLibrary: function (name, version) { this.register(name, version, true); }, deRegister: function (name) { var lib = this._getLibraryByName(name); var index = undefined; if (lib) { index = this._registry.indexOf(lib); this._registry.splice(index, 1); } } }; if (false) { Libraries.prototype.isRegistered = function (name) { return !!this._getLibraryByName(name); }; } exports.default = new Libraries(); }); enifed('ember-metal/map', ['exports', 'ember-metal/utils', 'ember-metal/empty_object'], function (exports, _emberMetalUtils, _emberMetalEmpty_object) { /** @module ember @submodule ember-metal */ /* JavaScript (before ES6) does not have a Map implementation. Objects, which are often used as dictionaries, may only have Strings as keys. Because Ember has a way to get a unique identifier for every object via `Ember.guidFor`, we can implement a performant Map with arbitrary keys. Because it is commonly used in low-level bookkeeping, Map is implemented as a pure JavaScript object for performance. This implementation follows the current iteration of the ES6 proposal for maps (http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets), with one exception: as we do not have the luxury of in-VM iteration, we implement a forEach method for iteration. Map is mocked out to look like an Ember object, so you can do `Ember.Map.create()` for symmetry with other Ember classes. */ 'use strict'; function missingFunction(fn) { throw new TypeError(Object.prototype.toString.call(fn) + ' is not a function'); } function missingNew(name) { throw new TypeError('Constructor ' + name + ' requires \'new\''); } function copyNull(obj) { var output = new _emberMetalEmpty_object.default(); for (var prop in obj) { // hasOwnPropery is not needed because obj is new EmptyObject(); output[prop] = obj[prop]; } return output; } function copyMap(original, newObject) { var keys = original._keys.copy(); var values = copyNull(original._values); newObject._keys = keys; newObject._values = values; newObject.size = original.size; return newObject; } /** This class is used internally by Ember and Ember Data. Please do not use it at this time. We plan to clean it up and add many tests soon. @class OrderedSet @namespace Ember @constructor @private */ function OrderedSet() { if (this instanceof OrderedSet) { this.clear(); this._silenceRemoveDeprecation = false; } else { missingNew('OrderedSet'); } } /** @method create @static @return {Ember.OrderedSet} @private */ OrderedSet.create = function () { var Constructor = this; return new Constructor(); }; OrderedSet.prototype = { constructor: OrderedSet, /** @method clear @private */ clear: function () { this.presenceSet = new _emberMetalEmpty_object.default(); this.list = []; this.size = 0; }, /** @method add @param obj @param guid (optional, and for internal use) @return {Ember.OrderedSet} @private */ add: function (obj, _guid) { var guid = _guid || _emberMetalUtils.guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] !== true) { presenceSet[guid] = true; this.size = list.push(obj); } return this; }, /** @since 1.8.0 @method delete @param obj @param _guid (optional and for internal use only) @return {Boolean} @private */ delete: function (obj, _guid) { var guid = _guid || _emberMetalUtils.guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] === true) { delete presenceSet[guid]; var index = list.indexOf(obj); if (index > -1) { list.splice(index, 1); } this.size = list.length; return true; } else { return false; } }, /** @method isEmpty @return {Boolean} @private */ isEmpty: function () { return this.size === 0; }, /** @method has @param obj @return {Boolean} @private */ has: function (obj) { if (this.size === 0) { return false; } var guid = _emberMetalUtils.guidFor(obj); var presenceSet = this.presenceSet; return presenceSet[guid] === true; }, /** @method forEach @param {Function} fn @param self @private */ forEach: function (fn /*, ...thisArg*/) { if (typeof fn !== 'function') { missingFunction(fn); } if (this.size === 0) { return; } var list = this.list; if (arguments.length === 2) { for (var i = 0; i < list.length; i++) { fn.call(arguments[1], list[i]); } } else { for (var i = 0; i < list.length; i++) { fn(list[i]); } } }, /** @method toArray @return {Array} @private */ toArray: function () { return this.list.slice(); }, /** @method copy @return {Ember.OrderedSet} @private */ copy: function () { var Constructor = this.constructor; var set = new Constructor(); set._silenceRemoveDeprecation = this._silenceRemoveDeprecation; set.presenceSet = copyNull(this.presenceSet); set.list = this.toArray(); set.size = this.size; return set; } }; /** A Map stores values indexed by keys. Unlike JavaScript's default Objects, the keys of a Map can be any JavaScript object. Internally, a Map has two data structures: 1. `keys`: an OrderedSet of all of the existing keys 2. `values`: a JavaScript Object indexed by the `Ember.guidFor(key)` When a key/value pair is added for the first time, we add the key to the `keys` OrderedSet, and create or replace an entry in `values`. When an entry is deleted, we delete its entry in `keys` and `values`. @class Map @namespace Ember @private @constructor */ function Map() { if (this instanceof Map) { this._keys = OrderedSet.create(); this._keys._silenceRemoveDeprecation = true; this._values = new _emberMetalEmpty_object.default(); this.size = 0; } else { missingNew('Map'); } } /** @method create @static @private */ Map.create = function () { var Constructor = this; return new Constructor(); }; Map.prototype = { constructor: Map, /** This property will change as the number of objects in the map changes. @since 1.8.0 @property size @type number @default 0 @private */ size: 0, /** Retrieve the value associated with a given key. @method get @param {*} key @return {*} the value associated with the key, or `undefined` @private */ get: function (key) { if (this.size === 0) { return; } var values = this._values; var guid = _emberMetalUtils.guidFor(key); return values[guid]; }, /** Adds a value to the map. If a value for the given key has already been provided, the new value will replace the old value. @method set @param {*} key @param {*} value @return {Ember.Map} @private */ set: function (key, value) { var keys = this._keys; var values = this._values; var guid = _emberMetalUtils.guidFor(key); // ensure we don't store -0 var k = key === -0 ? 0 : key; keys.add(k, guid); values[guid] = value; this.size = keys.size; return this; }, /** Removes a value from the map for an associated key. @since 1.8.0 @method delete @param {*} key @return {Boolean} true if an item was removed, false otherwise @private */ delete: function (key) { if (this.size === 0) { return false; } // don't use ES6 "delete" because it will be annoying // to use in browsers that are not ES6 friendly; var keys = this._keys; var values = this._values; var guid = _emberMetalUtils.guidFor(key); if (keys.delete(key, guid)) { delete values[guid]; this.size = keys.size; return true; } else { return false; } }, /** Check whether a key is present. @method has @param {*} key @return {Boolean} true if the item was present, false otherwise @private */ has: function (key) { return this._keys.has(key); }, /** Iterate over all the keys and values. Calls the function once for each key, passing in value, key, and the map being iterated over, in that order. The keys are guaranteed to be iterated over in insertion order. @method forEach @param {Function} callback @param {*} self if passed, the `this` value inside the callback. By default, `this` is the map. @private */ forEach: function (callback /*, ...thisArg*/) { if (typeof callback !== 'function') { missingFunction(callback); } if (this.size === 0) { return; } var map = this; var cb = undefined, thisArg = undefined; if (arguments.length === 2) { thisArg = arguments[1]; cb = function (key) { return callback.call(thisArg, map.get(key), key, map); }; } else { cb = function (key) { return callback(map.get(key), key, map); }; } this._keys.forEach(cb); }, /** @method clear @private */ clear: function () { this._keys.clear(); this._values = new _emberMetalEmpty_object.default(); this.size = 0; }, /** @method copy @return {Ember.Map} @private */ copy: function () { return copyMap(this, new Map()); } }; /** @class MapWithDefault @namespace Ember @extends Ember.Map @private @constructor @param [options] @param {*} [options.defaultValue] */ function MapWithDefault(options) { this._super$constructor(); this.defaultValue = options.defaultValue; } /** @method create @static @param [options] @param {*} [options.defaultValue] @return {Ember.MapWithDefault|Ember.Map} If options are passed, returns `Ember.MapWithDefault` otherwise returns `Ember.Map` @private */ MapWithDefault.create = function (options) { if (options) { return new MapWithDefault(options); } else { return new Map(); } }; MapWithDefault.prototype = Object.create(Map.prototype); MapWithDefault.prototype.constructor = MapWithDefault; MapWithDefault.prototype._super$constructor = Map; MapWithDefault.prototype._super$get = Map.prototype.get; /** Retrieve the value associated with a given key. @method get @param {*} key @return {*} the value associated with the key, or the default value @private */ MapWithDefault.prototype.get = function (key) { var hasValue = this.has(key); if (hasValue) { return this._super$get(key); } else { var defaultValue = this.defaultValue(key); this.set(key, defaultValue); return defaultValue; } }; /** @method copy @return {Ember.MapWithDefault} @private */ MapWithDefault.prototype.copy = function () { var Constructor = this.constructor; return copyMap(this, new Constructor({ defaultValue: this.defaultValue })); }; exports.default = Map; exports.OrderedSet = OrderedSet; exports.Map = Map; exports.MapWithDefault = MapWithDefault; }); enifed('ember-metal/merge', ['exports'], function (exports) { /** Merge the contents of two objects together into the first object. ```javascript Ember.merge({ first: 'Tom' }, { last: 'Dale' }); // { first: 'Tom', last: 'Dale' } var a = { first: 'Yehuda' }; var b = { last: 'Katz' }; Ember.merge(a, b); // a == { first: 'Yehuda', last: 'Katz' }, b == { last: 'Katz' } ``` @method merge @for Ember @param {Object} original The object to merge into @param {Object} updates The object to copy properties from @return {Object} @public */ 'use strict'; exports.default = merge; function merge(original, updates) { if (!updates || typeof updates !== 'object') { return original; } var props = Object.keys(updates); var prop = undefined; for (var i = 0; i < props.length; i++) { prop = props[i]; original[prop] = updates[prop]; } return original; } }); enifed('ember-metal/meta', ['exports', 'ember-metal/features', 'ember-metal/meta_listeners', 'ember-metal/empty_object', 'ember-metal/utils', 'ember-metal/symbol'], function (exports, _emberMetalFeatures, _emberMetalMeta_listeners, _emberMetalEmpty_object, _emberMetalUtils, _emberMetalSymbol) { 'no use strict'; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed exports.meta = meta; exports.peekMeta = peekMeta; exports.deleteMeta = deleteMeta; /** @module ember-metal */ /* This declares several meta-programmed members on the Meta class. Such meta! In general, the `readable` variants will give you an object (if it already exists) that you can read but should not modify. The `writable` variants will give you a mutable object, and they will create it if it didn't already exist. The following methods will get generated metaprogrammatically, and I'm including them here for greppability: writableCache, readableCache, writeWatching, peekWatching, clearWatching, writeMixins, peekMixins, clearMixins, writeBindings, peekBindings, clearBindings, writeValues, peekValues, clearValues, writeDeps, forEachInDeps writableChainWatchers, readableChainWatchers, writableChains, readableChains, writableTag, readableTag */ var members = { cache: ownMap, weak: ownMap, watching: inheritedMap, mixins: inheritedMap, bindings: inheritedMap, values: inheritedMap, deps: inheritedMapOfMaps, chainWatchers: ownCustomObject, chains: inheritedCustomObject, tag: ownCustomObject }; var memberNames = Object.keys(members); var META_FIELD = '__ember_meta__'; function Meta(obj, parentMeta) { this._cache = undefined; this._weak = undefined; this._watching = undefined; this._mixins = undefined; this._bindings = undefined; this._values = undefined; this._deps = undefined; this._chainWatchers = undefined; this._chains = undefined; this._tag = undefined; // used only internally this.source = obj; // when meta(obj).proto === obj, the object is intended to be only a // prototype and doesn't need to actually be observable itself this.proto = undefined; // The next meta in our inheritance chain. We (will) track this // explicitly instead of using prototypical inheritance because we // have detailed knowledge of how each property should really be // inherited, and we can optimize it much better than JS runtimes. this.parent = parentMeta; this._initializeListeners(); } Meta.prototype.isInitialized = function (obj) { return this.proto !== obj; }; for (var _name in _emberMetalMeta_listeners.protoMethods) { Meta.prototype[_name] = _emberMetalMeta_listeners.protoMethods[_name]; } memberNames.forEach(function (name) { return members[name](name, Meta); }); // Implements a member that is a lazily created, non-inheritable // POJO. function ownMap(name, Meta) { var key = memberProperty(name); var capitalized = capitalize(name); Meta.prototype['writable' + capitalized] = function () { return this._getOrCreateOwnMap(key); }; Meta.prototype['readable' + capitalized] = function () { return this[key]; }; } Meta.prototype._getOrCreateOwnMap = function (key) { var ret = this[key]; if (!ret) { ret = this[key] = new _emberMetalEmpty_object.default(); } return ret; }; // Implements a member that is a lazily created POJO with inheritable // values. function inheritedMap(name, Meta) { var key = memberProperty(name); var capitalized = capitalize(name); Meta.prototype['write' + capitalized] = function (subkey, value) { var map = this._getOrCreateOwnMap(key); map[subkey] = value; }; Meta.prototype['peek' + capitalized] = function (subkey) { return this._findInherited(key, subkey); }; Meta.prototype['forEach' + capitalized] = function (fn) { var pointer = this; var seen = new _emberMetalEmpty_object.default(); while (pointer !== undefined) { var map = pointer[key]; if (map) { for (var _key in map) { if (!seen[_key]) { seen[_key] = true; fn(_key, map[_key]); } } } pointer = pointer.parent; } }; Meta.prototype['clear' + capitalized] = function () { this[key] = undefined; }; Meta.prototype['deleteFrom' + capitalized] = function (subkey) { delete this._getOrCreateOwnMap(key)[subkey]; }; Meta.prototype['hasIn' + capitalized] = function (subkey) { return this._findInherited(key, subkey) !== undefined; }; } Meta.prototype._getInherited = function (key) { var pointer = this; while (pointer !== undefined) { if (pointer[key]) { return pointer[key]; } pointer = pointer.parent; } }; Meta.prototype._findInherited = function (key, subkey) { var pointer = this; while (pointer !== undefined) { var map = pointer[key]; if (map) { var value = map[subkey]; if (value !== undefined) { return value; } } pointer = pointer.parent; } }; var UNDEFINED = _emberMetalSymbol.default('undefined'); exports.UNDEFINED = UNDEFINED; // Implements a member that provides a lazily created map of maps, // with inheritance at both levels. function inheritedMapOfMaps(name, Meta) { var key = memberProperty(name); var capitalized = capitalize(name); Meta.prototype['write' + capitalized] = function (subkey, itemkey, value) { var outerMap = this._getOrCreateOwnMap(key); var innerMap = outerMap[subkey]; if (!innerMap) { innerMap = outerMap[subkey] = new _emberMetalEmpty_object.default(); } innerMap[itemkey] = value; }; Meta.prototype['peek' + capitalized] = function (subkey, itemkey) { var pointer = this; while (pointer !== undefined) { var map = pointer[key]; if (map) { var value = map[subkey]; if (value) { if (value[itemkey] !== undefined) { return value[itemkey]; } } } pointer = pointer.parent; } }; Meta.prototype['has' + capitalized] = function (subkey) { var pointer = this; while (pointer !== undefined) { if (pointer[key] && pointer[key][subkey]) { return true; } pointer = pointer.parent; } return false; }; Meta.prototype['forEachIn' + capitalized] = function (subkey, fn) { return this._forEachIn(key, subkey, fn); }; } Meta.prototype._forEachIn = function (key, subkey, fn) { var pointer = this; var seen = new _emberMetalEmpty_object.default(); var calls = []; while (pointer !== undefined) { var map = pointer[key]; if (map) { var innerMap = map[subkey]; if (innerMap) { for (var innerKey in innerMap) { if (!seen[innerKey]) { seen[innerKey] = true; calls.push([innerKey, innerMap[innerKey]]); } } } } pointer = pointer.parent; } for (var i = 0; i < calls.length; i++) { var _calls$i = calls[i]; var innerKey = _calls$i[0]; var value = _calls$i[1]; fn(innerKey, value); } }; // Implements a member that provides a non-heritable, lazily-created // object using the method you provide. function ownCustomObject(name, Meta) { var key = memberProperty(name); var capitalized = capitalize(name); Meta.prototype['writable' + capitalized] = function (create) { var ret = this[key]; if (!ret) { ret = this[key] = create(this.source); } return ret; }; Meta.prototype['readable' + capitalized] = function () { return this[key]; }; } // Implements a member that provides an inheritable, lazily-created // object using the method you provide. We will derived children from // their parents by calling your object's `copy()` method. function inheritedCustomObject(name, Meta) { var key = memberProperty(name); var capitalized = capitalize(name); Meta.prototype['writable' + capitalized] = function (create) { var ret = this[key]; if (!ret) { if (this.parent) { ret = this[key] = this.parent['writable' + capitalized](create).copy(this.source); } else { ret = this[key] = create(this.source); } } return ret; }; Meta.prototype['readable' + capitalized] = function () { return this._getInherited(key); }; } function memberProperty(name) { return '_' + name; } // there's a more general-purpose capitalize in ember-runtime, but we // don't want to make ember-metal depend on ember-runtime. function capitalize(name) { return name.replace(/^\w/, function (m) { return m.toUpperCase(); }); } var META_DESC = { writable: true, configurable: true, enumerable: false, value: null }; exports.META_DESC = META_DESC; var EMBER_META_PROPERTY = { name: META_FIELD, descriptor: META_DESC }; if (true) { Meta.prototype.readInheritedValue = function (key, subkey) { var internalKey = '_' + key; var pointer = this; while (pointer !== undefined) { var map = pointer[internalKey]; if (map) { var value = map[subkey]; if (value !== undefined || subkey in map) { return map[subkey]; } } pointer = pointer.parent; } return UNDEFINED; }; Meta.prototype.writeValue = function (obj, key, value) { var descriptor = _emberMetalUtils.lookupDescriptor(obj, key); var isMandatorySetter = descriptor && descriptor.set && descriptor.set.isMandatorySetter; if (isMandatorySetter) { this.writeValues(key, value); } else { obj[key] = value; } }; } // choose the one appropriate for given platform var setMeta = function (obj, meta) { // if `null` already, just set it to the new value // otherwise define property first if (obj[META_FIELD] !== null) { if (obj.__defineNonEnumerable) { obj.__defineNonEnumerable(EMBER_META_PROPERTY); } else { Object.defineProperty(obj, META_FIELD, META_DESC); } } obj[META_FIELD] = meta; }; /** Retrieves the meta hash for an object. If `writable` is true ensures the hash is writable for this object as well. The meta object contains information about computed property descriptors as well as any watched properties and other information. You generally will not access this information directly but instead work with higher level methods that manipulate this hash indirectly. @method meta @for Ember @private @param {Object} obj The object to retrieve meta for @param {Boolean} [writable=true] Pass `false` if you do not intend to modify the meta hash, allowing the method to avoid making an unnecessary copy. @return {Object} the meta hash for an object */ function meta(obj) { var maybeMeta = peekMeta(obj); var parent = undefined; // remove this code, in-favor of explicit parent if (maybeMeta) { if (maybeMeta.source === obj) { return maybeMeta; } parent = maybeMeta; } var newMeta = new Meta(obj, parent); setMeta(obj, newMeta); return newMeta; } function peekMeta(obj) { return obj[META_FIELD]; } function deleteMeta(obj) { if (typeof obj[META_FIELD] !== 'object') { return; } obj[META_FIELD] = null; } }); enifed('ember-metal/meta_listeners', ['exports'], function (exports) { /* When we render a rich template hierarchy, the set of events that *might* happen tends to be much larger than the set of events that actually happen. This implies that we should make listener creation & destruction cheap, even at the cost of making event dispatch more expensive. Thus we store a new listener with a single push and no new allocations, without even bothering to do deduplication -- we can save that for dispatch time, if an event actually happens. */ /* listener flags */ 'use strict'; var ONCE = 1; exports.ONCE = ONCE; var SUSPENDED = 2; exports.SUSPENDED = SUSPENDED; var protoMethods = { addToListeners: function (eventName, target, method, flags) { if (!this._listeners) { this._listeners = []; } this._listeners.push(eventName, target, method, flags); }, _finalizeListeners: function () { if (this._listenersFinalized) { return; } if (!this._listeners) { this._listeners = []; } var pointer = this.parent; while (pointer) { var listeners = pointer._listeners; if (listeners) { this._listeners = this._listeners.concat(listeners); } if (pointer._listenersFinalized) { break; } pointer = pointer.parent; } this._listenersFinalized = true; }, removeFromListeners: function (eventName, target, method, didRemove) { var pointer = this; while (pointer) { var listeners = pointer._listeners; if (listeners) { for (var index = listeners.length - 4; index >= 0; index -= 4) { if (listeners[index] === eventName && (!method || listeners[index + 1] === target && listeners[index + 2] === method)) { if (pointer === this) { // we are modifying our own list, so we edit directly if (typeof didRemove === 'function') { didRemove(eventName, target, listeners[index + 2]); } listeners.splice(index, 4); } else { // we are trying to remove an inherited listener, so we do // just-in-time copying to detach our own listeners from // our inheritance chain. this._finalizeListeners(); return this.removeFromListeners(eventName, target, method); } } } } if (pointer._listenersFinalized) { break; } pointer = pointer.parent; } }, matchingListeners: function (eventName) { var pointer = this; var result = []; while (pointer) { var listeners = pointer._listeners; if (listeners) { for (var index = 0; index < listeners.length - 3; index += 4) { if (listeners[index] === eventName) { pushUniqueListener(result, listeners, index); } } } if (pointer._listenersFinalized) { break; } pointer = pointer.parent; } var sus = this._suspendedListeners; if (sus) { for (var susIndex = 0; susIndex < sus.length - 2; susIndex += 3) { if (eventName === sus[susIndex]) { for (var resultIndex = 0; resultIndex < result.length - 2; resultIndex += 3) { if (result[resultIndex] === sus[susIndex + 1] && result[resultIndex + 1] === sus[susIndex + 2]) { result[resultIndex + 2] |= SUSPENDED; } } } } } return result; }, suspendListeners: function (eventNames, target, method, callback) { var sus = this._suspendedListeners; if (!sus) { sus = this._suspendedListeners = []; } for (var i = 0; i < eventNames.length; i++) { sus.push(eventNames[i], target, method); } try { return callback.call(target); } finally { if (sus.length === eventNames.length) { this._suspendedListeners = undefined; } else { for (var i = sus.length - 3; i >= 0; i -= 3) { if (sus[i + 1] === target && sus[i + 2] === method && eventNames.indexOf(sus[i]) !== -1) { sus.splice(i, 3); } } } } }, watchedEvents: function () { var pointer = this; var names = {}; while (pointer) { var listeners = pointer._listeners; if (listeners) { for (var index = 0; index < listeners.length - 3; index += 4) { names[listeners[index]] = true; } } if (pointer._listenersFinalized) { break; } pointer = pointer.parent; } return Object.keys(names); }, _initializeListeners: function () { this._listeners = undefined; this._listenersFinalized = undefined; this._suspendedListeners = undefined; } }; exports.protoMethods = protoMethods; function pushUniqueListener(destination, source, index) { var target = source[index + 1]; var method = source[index + 2]; for (var destinationIndex = 0; destinationIndex < destination.length - 2; destinationIndex += 3) { if (destination[destinationIndex] === target && destination[destinationIndex + 1] === method) { return; } } destination.push(target, method, source[index + 3]); } }); enifed('ember-metal/mixin', ['exports', 'ember-metal/error', 'ember-metal/debug', 'ember-metal/assign', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/expand_properties', 'ember-metal/properties', 'ember-metal/computed', 'ember-metal/binding', 'ember-metal/observer', 'ember-metal/events'], function (exports, _emberMetalError, _emberMetalDebug, _emberMetalAssign, _emberMetalUtils, _emberMetalMeta, _emberMetalExpand_properties, _emberMetalProperties, _emberMetalComputed, _emberMetalBinding, _emberMetalObserver, _emberMetalEvents) { 'no use strict'; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed /** @module ember @submodule ember-metal */ exports.detectBinding = detectBinding; exports.mixin = mixin; exports.default = Mixin; exports.hasUnprocessedMixins = hasUnprocessedMixins; exports.clearUnprocessedMixins = clearUnprocessedMixins; exports.required = required; exports.aliasMethod = aliasMethod; exports.observer = observer; exports._immediateObserver = _immediateObserver; exports._beforeObserver = _beforeObserver; function ROOT() {} ROOT.__hasSuper = false; var a_slice = [].slice; function isMethod(obj) { return 'function' === typeof obj && obj.isMethod !== false && obj !== Boolean && obj !== Object && obj !== Number && obj !== Array && obj !== Date && obj !== String; } var CONTINUE = {}; function mixinProperties(mixinsMeta, mixin) { var guid = undefined; if (mixin instanceof Mixin) { guid = _emberMetalUtils.guidFor(mixin); if (mixinsMeta.peekMixins(guid)) { return CONTINUE; } mixinsMeta.writeMixins(guid, mixin); return mixin.properties; } else { return mixin; // apply anonymous mixin properties } } function concatenatedMixinProperties(concatProp, props, values, base) { var concats = undefined; // reset before adding each new mixin to pickup concats from previous concats = values[concatProp] || base[concatProp]; if (props[concatProp]) { concats = concats ? concats.concat(props[concatProp]) : props[concatProp]; } return concats; } function giveDescriptorSuper(meta, key, property, values, descs, base) { var superProperty = undefined; // Computed properties override methods, and do not call super to them if (values[key] === undefined) { // Find the original descriptor in a parent mixin superProperty = descs[key]; } // If we didn't find the original descriptor in a parent mixin, find // it on the original object. if (!superProperty) { var possibleDesc = base[key]; var superDesc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; superProperty = superDesc; } if (superProperty === undefined || !(superProperty instanceof _emberMetalComputed.ComputedProperty)) { return property; } // Since multiple mixins may inherit from the same parent, we need // to clone the computed property so that other mixins do not receive // the wrapped version. property = Object.create(property); property._getter = _emberMetalUtils.wrap(property._getter, superProperty._getter); if (superProperty._setter) { if (property._setter) { property._setter = _emberMetalUtils.wrap(property._setter, superProperty._setter); } else { property._setter = superProperty._setter; } } return property; } function giveMethodSuper(obj, key, method, values, descs) { var superMethod = undefined; // Methods overwrite computed properties, and do not call super to them. if (descs[key] === undefined) { // Find the original method in a parent mixin superMethod = values[key]; } // If we didn't find the original value in a parent mixin, find it in // the original object superMethod = superMethod || obj[key]; // Only wrap the new method if the original method was a function if (superMethod === undefined || 'function' !== typeof superMethod) { return method; } return _emberMetalUtils.wrap(method, superMethod); } function applyConcatenatedProperties(obj, key, value, values) { var baseValue = values[key] || obj[key]; if (baseValue) { if ('function' === typeof baseValue.concat) { if (value === null || value === undefined) { return baseValue; } else { return baseValue.concat(value); } } else { return _emberMetalUtils.makeArray(baseValue).concat(value); } } else { return _emberMetalUtils.makeArray(value); } } function applyMergedProperties(obj, key, value, values) { var baseValue = values[key] || obj[key]; _emberMetalDebug.runInDebug(function () { if (Array.isArray(value)) { // use conditional to avoid stringifying every time _emberMetalDebug.assert('You passed in `' + JSON.stringify(value) + '` as the value for `' + key + '` but `' + key + '` cannot be an Array', false); } }); if (!baseValue) { return value; } var newBase = _emberMetalAssign.default({}, baseValue); var hasFunction = false; for (var prop in value) { if (!value.hasOwnProperty(prop)) { continue; } var propValue = value[prop]; if (isMethod(propValue)) { // TODO: support for Computed Properties, etc? hasFunction = true; newBase[prop] = giveMethodSuper(obj, prop, propValue, baseValue, {}); } else { newBase[prop] = propValue; } } if (hasFunction) { newBase._super = ROOT; } return newBase; } function addNormalizedProperty(base, key, value, meta, descs, values, concats, mergings) { if (value instanceof _emberMetalProperties.Descriptor) { if (value === REQUIRED && descs[key]) { return CONTINUE; } // Wrap descriptor function to implement // _super() if needed if (value._getter) { value = giveDescriptorSuper(meta, key, value, values, descs, base); } descs[key] = value; values[key] = undefined; } else { if (concats && concats.indexOf(key) >= 0 || key === 'concatenatedProperties' || key === 'mergedProperties') { value = applyConcatenatedProperties(base, key, value, values); } else if (mergings && mergings.indexOf(key) >= 0) { value = applyMergedProperties(base, key, value, values); } else if (isMethod(value)) { value = giveMethodSuper(base, key, value, values, descs); } descs[key] = undefined; values[key] = value; } } function mergeMixins(mixins, m, descs, values, base, keys) { var currentMixin = undefined, props = undefined, key = undefined, concats = undefined, mergings = undefined, meta = undefined; function removeKeys(keyName) { delete descs[keyName]; delete values[keyName]; } for (var i = 0; i < mixins.length; i++) { currentMixin = mixins[i]; _emberMetalDebug.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(currentMixin), typeof currentMixin === 'object' && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== '[object Array]'); props = mixinProperties(m, currentMixin); if (props === CONTINUE) { continue; } if (props) { meta = _emberMetalMeta.meta(base); if (base.willMergeMixin) { base.willMergeMixin(props); } concats = concatenatedMixinProperties('concatenatedProperties', props, values, base); mergings = concatenatedMixinProperties('mergedProperties', props, values, base); for (key in props) { if (!props.hasOwnProperty(key)) { continue; } keys.push(key); addNormalizedProperty(base, key, props[key], meta, descs, values, concats, mergings); } // manually copy toString() because some JS engines do not enumerate it if (props.hasOwnProperty('toString')) { base.toString = props.toString; } } else if (currentMixin.mixins) { mergeMixins(currentMixin.mixins, m, descs, values, base, keys); if (currentMixin._without) { currentMixin._without.forEach(removeKeys); } } } } function detectBinding(key) { var length = key.length; return length > 7 && key.charCodeAt(length - 7) === 66 && key.indexOf('inding', length - 6) !== -1; } // warm both paths of above function detectBinding('notbound'); detectBinding('fooBinding'); function connectBindings(obj, m) { // TODO Mixin.apply(instance) should disconnect binding if exists m.forEachBindings(function (key, binding) { if (binding) { var to = key.slice(0, -7); // strip Binding off end if (binding instanceof _emberMetalBinding.Binding) { binding = binding.copy(); // copy prototypes' instance binding.to(to); } else { // binding is string path binding = new _emberMetalBinding.Binding(to, binding); } binding.connect(obj); obj[key] = binding; } }); // mark as applied m.clearBindings(); } function finishPartial(obj, m) { connectBindings(obj, m || _emberMetalMeta.meta(obj)); return obj; } function followAlias(obj, desc, m, descs, values) { var altKey = desc.methodName; var value = undefined; var possibleDesc = undefined; if (descs[altKey] || values[altKey]) { value = values[altKey]; desc = descs[altKey]; } else if ((possibleDesc = obj[altKey]) && possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) { desc = possibleDesc; value = undefined; } else { desc = undefined; value = obj[altKey]; } return { desc: desc, value: value }; } function updateObserversAndListeners(obj, key, observerOrListener, pathsKey, updateMethod) { var paths = observerOrListener[pathsKey]; if (paths) { for (var i = 0; i < paths.length; i++) { updateMethod(obj, paths[i], null, key); } } } function replaceObserversAndListeners(obj, key, observerOrListener) { var prev = obj[key]; if ('function' === typeof prev) { updateObserversAndListeners(obj, key, prev, '__ember_observesBefore__', _emberMetalObserver._removeBeforeObserver); updateObserversAndListeners(obj, key, prev, '__ember_observes__', _emberMetalObserver.removeObserver); updateObserversAndListeners(obj, key, prev, '__ember_listens__', _emberMetalEvents.removeListener); } if ('function' === typeof observerOrListener) { updateObserversAndListeners(obj, key, observerOrListener, '__ember_observesBefore__', _emberMetalObserver._addBeforeObserver); updateObserversAndListeners(obj, key, observerOrListener, '__ember_observes__', _emberMetalObserver.addObserver); updateObserversAndListeners(obj, key, observerOrListener, '__ember_listens__', _emberMetalEvents.addListener); } } function applyMixin(obj, mixins, partial) { var descs = {}; var values = {}; var m = _emberMetalMeta.meta(obj); var keys = []; var key = undefined, value = undefined, desc = undefined; obj._super = ROOT; // Go through all mixins and hashes passed in, and: // // * Handle concatenated properties // * Handle merged properties // * Set up _super wrapping if necessary // * Set up computed property descriptors // * Copying `toString` in broken browsers mergeMixins(mixins, m, descs, values, obj, keys); for (var i = 0; i < keys.length; i++) { key = keys[i]; if (key === 'constructor' || !values.hasOwnProperty(key)) { continue; } desc = descs[key]; value = values[key]; if (desc === REQUIRED) { continue; } while (desc && desc instanceof Alias) { var followed = followAlias(obj, desc, m, descs, values); desc = followed.desc; value = followed.value; } if (desc === undefined && value === undefined) { continue; } replaceObserversAndListeners(obj, key, value); if (detectBinding(key)) { m.writeBindings(key, value); } _emberMetalProperties.defineProperty(obj, key, desc, value, m); } if (!partial) { // don't apply to prototype finishPartial(obj, m); } return obj; } /** @method mixin @for Ember @param obj @param mixins* @return obj @private */ function mixin(obj) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } applyMixin(obj, args, false); return obj; } var NAME_KEY = _emberMetalUtils.GUID_KEY + '_name'; exports.NAME_KEY = NAME_KEY; /** The `Ember.Mixin` class allows you to create mixins, whose properties can be added to other classes. For instance, ```javascript App.Editable = Ember.Mixin.create({ edit: function() { console.log('starting to edit'); this.set('isEditing', true); }, isEditing: false }); // Mix mixins into classes by passing them as the first arguments to // .extend. App.CommentView = Ember.View.extend(App.Editable, { template: Ember.Handlebars.compile('{{#if view.isEditing}}...{{else}}...{{/if}}') }); commentView = App.CommentView.create(); commentView.edit(); // outputs 'starting to edit' ``` Note that Mixins are created with `Ember.Mixin.create`, not `Ember.Mixin.extend`. Note that mixins extend a constructor's prototype so arrays and object literals defined as properties will be shared amongst objects that implement the mixin. If you want to define a property in a mixin that is not shared, you can define it either as a computed property or have it be created on initialization of the object. ```javascript //filters array will be shared amongst any object implementing mixin App.Filterable = Ember.Mixin.create({ filters: Ember.A() }); //filters will be a separate array for every object implementing the mixin App.Filterable = Ember.Mixin.create({ filters: Ember.computed(function() {return Ember.A();}) }); //filters will be created as a separate array during the object's initialization App.Filterable = Ember.Mixin.create({ init: function() { this._super(...arguments); this.set("filters", Ember.A()); } }); ``` @class Mixin @namespace Ember @public */ function Mixin(args, properties) { this.properties = properties; var length = args && args.length; if (length > 0) { var m = new Array(length); for (var i = 0; i < length; i++) { var x = args[i]; if (x instanceof Mixin) { m[i] = x; } else { m[i] = new Mixin(undefined, x); } } this.mixins = m; } else { this.mixins = undefined; } this.ownerConstructor = undefined; this._without = undefined; this[_emberMetalUtils.GUID_KEY] = null; this[NAME_KEY] = null; _emberMetalDebug.debugSeal(this); } Mixin._apply = applyMixin; Mixin.applyPartial = function (obj) { var args = a_slice.call(arguments, 1); return applyMixin(obj, args, true); }; Mixin.finishPartial = finishPartial; var unprocessedFlag = false; function hasUnprocessedMixins() { return unprocessedFlag; } function clearUnprocessedMixins() { unprocessedFlag = false; } /** @method create @static @param arguments* @public */ Mixin.create = function () { // ES6TODO: this relies on a global state? unprocessedFlag = true; var M = this; for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return new M(args, undefined); }; var MixinPrototype = Mixin.prototype; /** @method reopen @param arguments* @private */ MixinPrototype.reopen = function () { var currentMixin = undefined; if (this.properties) { currentMixin = new Mixin(undefined, this.properties); this.properties = undefined; this.mixins = [currentMixin]; } else if (!this.mixins) { this.mixins = []; } var mixins = this.mixins; var idx = undefined; for (idx = 0; idx < arguments.length; idx++) { currentMixin = arguments[idx]; _emberMetalDebug.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(currentMixin), typeof currentMixin === 'object' && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== '[object Array]'); if (currentMixin instanceof Mixin) { mixins.push(currentMixin); } else { mixins.push(new Mixin(undefined, currentMixin)); } } return this; }; /** @method apply @param obj @return applied object @private */ MixinPrototype.apply = function (obj) { return applyMixin(obj, [this], false); }; MixinPrototype.applyPartial = function (obj) { return applyMixin(obj, [this], true); }; MixinPrototype.toString = Object.toString; function _detect(curMixin, targetMixin, seen) { var guid = _emberMetalUtils.guidFor(curMixin); if (seen[guid]) { return false; } seen[guid] = true; if (curMixin === targetMixin) { return true; } var mixins = curMixin.mixins; var loc = mixins ? mixins.length : 0; while (--loc >= 0) { if (_detect(mixins[loc], targetMixin, seen)) { return true; } } return false; } /** @method detect @param obj @return {Boolean} @private */ MixinPrototype.detect = function (obj) { if (!obj) { return false; } if (obj instanceof Mixin) { return _detect(obj, this, {}); } var m = _emberMetalMeta.peekMeta(obj); if (!m) { return false; } return !!m.peekMixins(_emberMetalUtils.guidFor(this)); }; MixinPrototype.without = function () { var ret = new Mixin([this]); for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } ret._without = args; return ret; }; function _keys(ret, mixin, seen) { if (seen[_emberMetalUtils.guidFor(mixin)]) { return; } seen[_emberMetalUtils.guidFor(mixin)] = true; if (mixin.properties) { var props = Object.keys(mixin.properties); for (var i = 0; i < props.length; i++) { var key = props[i]; ret[key] = true; } } else if (mixin.mixins) { mixin.mixins.forEach(function (x) { return _keys(ret, x, seen); }); } } MixinPrototype.keys = function () { var keys = {}; var seen = {}; _keys(keys, this, seen); var ret = Object.keys(keys); return ret; }; _emberMetalDebug.debugSeal(MixinPrototype); // returns the mixins currently applied to the specified object // TODO: Make Ember.mixin Mixin.mixins = function (obj) { var m = _emberMetalMeta.peekMeta(obj); var ret = []; if (!m) { return ret; } m.forEachMixins(function (key, currentMixin) { // skip primitive mixins since these are always anonymous if (!currentMixin.properties) { ret.push(currentMixin); } }); return ret; }; var REQUIRED = new _emberMetalProperties.Descriptor(); REQUIRED.toString = function () { return '(Required Property)'; }; /** Denotes a required property for a mixin @method required @for Ember @private */ function required() { _emberMetalDebug.deprecate('Ember.required is deprecated as its behavior is inconsistent and unreliable.', false, { id: 'ember-metal.required', until: '3.0.0' }); return REQUIRED; } function Alias(methodName) { this.isDescriptor = true; this.methodName = methodName; } Alias.prototype = new _emberMetalProperties.Descriptor(); /** Makes a method available via an additional name. ```javascript App.Person = Ember.Object.extend({ name: function() { return 'Tomhuda Katzdale'; }, moniker: Ember.aliasMethod('name') }); let goodGuy = App.Person.create(); goodGuy.name(); // 'Tomhuda Katzdale' goodGuy.moniker(); // 'Tomhuda Katzdale' ``` @method aliasMethod @for Ember @param {String} methodName name of the method to alias @public */ function aliasMethod(methodName) { return new Alias(methodName); } // .......................................................... // OBSERVER HELPER // /** Specify a method that observes property changes. ```javascript Ember.Object.extend({ valueObserver: Ember.observer('value', function() { // Executes whenever the "value" property changes }) }); ``` Also available as `Function.prototype.observes` if prototype extensions are enabled. @method observer @for Ember @param {String} propertyNames* @param {Function} func @return func @public */ function observer() { for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } var func = args.slice(-1)[0]; var paths = undefined; var addWatchedProperty = function (path) { paths.push(path); }; var _paths = args.slice(0, -1); if (typeof func !== 'function') { // revert to old, soft-deprecated argument ordering _emberMetalDebug.deprecate('Passing the dependentKeys after the callback function in Ember.observer is deprecated. Ensure the callback function is the last argument.', false, { id: 'ember-metal.observer-argument-order', until: '3.0.0' }); func = args[0]; _paths = args.slice(1); } paths = []; for (var i = 0; i < _paths.length; ++i) { _emberMetalExpand_properties.default(_paths[i], addWatchedProperty); } if (typeof func !== 'function') { throw new _emberMetalError.default('Ember.observer called without a function'); } func.__ember_observes__ = paths; return func; } /** Specify a method that observes property changes. ```javascript Ember.Object.extend({ valueObserver: Ember.immediateObserver('value', function() { // Executes whenever the "value" property changes }) }); ``` In the future, `Ember.observer` may become asynchronous. In this event, `Ember.immediateObserver` will maintain the synchronous behavior. Also available as `Function.prototype.observesImmediately` if prototype extensions are enabled. @method _immediateObserver @for Ember @param {String} propertyNames* @param {Function} func @deprecated Use `Ember.observer` instead. @return func @private */ function _immediateObserver() { _emberMetalDebug.deprecate('Usage of `Ember.immediateObserver` is deprecated, use `Ember.observer` instead.', false, { id: 'ember-metal.immediate-observer', until: '3.0.0' }); for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; _emberMetalDebug.assert('Immediate observers must observe internal properties only, not properties on other objects.', typeof arg !== 'string' || arg.indexOf('.') === -1); } return observer.apply(this, arguments); } /** When observers fire, they are called with the arguments `obj`, `keyName`. Note, `@each.property` observer is called per each add or replace of an element and it's not called with a specific enumeration item. A `_beforeObserver` fires before a property changes. A `_beforeObserver` is an alternative form of `.observesBefore()`. ```javascript App.PersonView = Ember.View.extend({ friends: [{ name: 'Tom' }, { name: 'Stefan' }, { name: 'Kris' }], valueDidChange: Ember.observer('content.value', function(obj, keyName) { // only run if updating a value already in the DOM if (this.get('state') === 'inDOM') { let color = obj.get(keyName) > this.changingFrom ? 'green' : 'red'; // logic } }), friendsDidChange: Ember.observer('friends.@each.name', function(obj, keyName) { // some logic // obj.get(keyName) returns friends array }) }); ``` Also available as `Function.prototype.observesBefore` if prototype extensions are enabled. @method beforeObserver @for Ember @param {String} propertyNames* @param {Function} func @return func @deprecated @private */ function _beforeObserver() { for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } var func = args.slice(-1)[0]; var paths = undefined; var addWatchedProperty = function (path) { paths.push(path); }; var _paths = args.slice(0, -1); if (typeof func !== 'function') { // revert to old, soft-deprecated argument ordering func = args[0]; _paths = args.slice(1); } paths = []; for (var i = 0; i < _paths.length; ++i) { _emberMetalExpand_properties.default(_paths[i], addWatchedProperty); } if (typeof func !== 'function') { throw new _emberMetalError.default('Ember.beforeObserver called without a function'); } func.__ember_observesBefore__ = paths; return func; } exports.Mixin = Mixin; exports.required = required; exports.REQUIRED = REQUIRED; }); enifed('ember-metal/observer', ['exports', 'ember-metal/watching', 'ember-metal/events'], function (exports, _emberMetalWatching, _emberMetalEvents) { 'use strict'; exports.addObserver = addObserver; exports.observersFor = observersFor; exports.removeObserver = removeObserver; exports._addBeforeObserver = _addBeforeObserver; exports._suspendObserver = _suspendObserver; exports._suspendObservers = _suspendObservers; exports._removeBeforeObserver = _removeBeforeObserver; /** @module ember-metal */ var AFTER_OBSERVERS = ':change'; var BEFORE_OBSERVERS = ':before'; function changeEvent(keyName) { return keyName + AFTER_OBSERVERS; } function beforeEvent(keyName) { return keyName + BEFORE_OBSERVERS; } /** @method addObserver @for Ember @param obj @param {String} _path @param {Object|Function} target @param {Function|String} [method] @public */ function addObserver(obj, _path, target, method) { _emberMetalEvents.addListener(obj, changeEvent(_path), target, method); _emberMetalWatching.watch(obj, _path); return this; } function observersFor(obj, path) { return _emberMetalEvents.listenersFor(obj, changeEvent(path)); } /** @method removeObserver @for Ember @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @public */ function removeObserver(obj, path, target, method) { _emberMetalWatching.unwatch(obj, path); _emberMetalEvents.removeListener(obj, changeEvent(path), target, method); return this; } /** @method _addBeforeObserver @for Ember @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @deprecated @private */ function _addBeforeObserver(obj, path, target, method) { _emberMetalEvents.addListener(obj, beforeEvent(path), target, method); _emberMetalWatching.watch(obj, path); return this; } // Suspend observer during callback. // // This should only be used by the target of the observer // while it is setting the observed path. function _suspendObserver(obj, path, target, method, callback) { return _emberMetalEvents.suspendListener(obj, changeEvent(path), target, method, callback); } function _suspendObservers(obj, paths, target, method, callback) { var events = paths.map(changeEvent); return _emberMetalEvents.suspendListeners(obj, events, target, method, callback); } /** @method removeBeforeObserver @for Ember @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @deprecated @private */ function _removeBeforeObserver(obj, path, target, method) { _emberMetalWatching.unwatch(obj, path); _emberMetalEvents.removeListener(obj, beforeEvent(path), target, method); return this; } }); enifed('ember-metal/observer_set', ['exports', 'ember-metal/utils', 'ember-metal/events'], function (exports, _emberMetalUtils, _emberMetalEvents) { 'use strict'; exports.default = ObserverSet; /* this.observerSet = { [senderGuid]: { // variable name: `keySet` [keyName]: listIndex } }, this.observers = [ { sender: obj, keyName: keyName, eventName: eventName, listeners: [ [target, method, flags] ] }, ... ] */ function ObserverSet() { this.clear(); } ObserverSet.prototype.add = function (sender, keyName, eventName) { var observerSet = this.observerSet; var observers = this.observers; var senderGuid = _emberMetalUtils.guidFor(sender); var keySet = observerSet[senderGuid]; var index = undefined; if (!keySet) { observerSet[senderGuid] = keySet = {}; } index = keySet[keyName]; if (index === undefined) { index = observers.push({ sender: sender, keyName: keyName, eventName: eventName, listeners: [] }) - 1; keySet[keyName] = index; } return observers[index].listeners; }; ObserverSet.prototype.flush = function () { var observers = this.observers; var i = undefined, observer = undefined, sender = undefined; this.clear(); for (i = 0; i < observers.length; ++i) { observer = observers[i]; sender = observer.sender; if (sender.isDestroying || sender.isDestroyed) { continue; } _emberMetalEvents.sendEvent(sender, observer.eventName, [sender, observer.keyName], observer.listeners); } }; ObserverSet.prototype.clear = function () { this.observerSet = {}; this.observers = []; }; }); enifed('ember-metal/path_cache', ['exports', 'ember-metal/cache'], function (exports, _emberMetalCache) { 'use strict'; exports.isGlobal = isGlobal; exports.isGlobalPath = isGlobalPath; exports.hasThis = hasThis; exports.isPath = isPath; exports.getFirstKey = getFirstKey; exports.getTailPath = getTailPath; var IS_GLOBAL = /^[A-Z$]/; var IS_GLOBAL_PATH = /^[A-Z$].*[\.]/; var HAS_THIS = 'this.'; var isGlobalCache = new _emberMetalCache.default(1000, function (key) { return IS_GLOBAL.test(key); }); var isGlobalPathCache = new _emberMetalCache.default(1000, function (key) { return IS_GLOBAL_PATH.test(key); }); var hasThisCache = new _emberMetalCache.default(1000, function (key) { return key.lastIndexOf(HAS_THIS, 0) === 0; }); var firstDotIndexCache = new _emberMetalCache.default(1000, function (key) { return key.indexOf('.'); }); var firstKeyCache = new _emberMetalCache.default(1000, function (path) { var index = firstDotIndexCache.get(path); if (index === -1) { return path; } else { return path.slice(0, index); } }); var tailPathCache = new _emberMetalCache.default(1000, function (path) { var index = firstDotIndexCache.get(path); if (index !== -1) { return path.slice(index + 1); } }); var caches = { isGlobalCache: isGlobalCache, isGlobalPathCache: isGlobalPathCache, hasThisCache: hasThisCache, firstDotIndexCache: firstDotIndexCache, firstKeyCache: firstKeyCache, tailPathCache: tailPathCache }; exports.caches = caches; function isGlobal(path) { return isGlobalCache.get(path); } function isGlobalPath(path) { return isGlobalPathCache.get(path); } function hasThis(path) { return hasThisCache.get(path); } function isPath(path) { return firstDotIndexCache.get(path) !== -1; } function getFirstKey(path) { return firstKeyCache.get(path); } function getTailPath(path) { return tailPathCache.get(path); } }); enifed('ember-metal/properties', ['exports', 'ember-metal/debug', 'ember-metal/features', 'ember-metal/meta', 'ember-metal/property_events'], function (exports, _emberMetalDebug, _emberMetalFeatures, _emberMetalMeta, _emberMetalProperty_events) { /** @module ember-metal */ 'use strict'; exports.Descriptor = Descriptor; exports.MANDATORY_SETTER_FUNCTION = MANDATORY_SETTER_FUNCTION; exports.DEFAULT_GETTER_FUNCTION = DEFAULT_GETTER_FUNCTION; exports.INHERITING_GETTER_FUNCTION = INHERITING_GETTER_FUNCTION; exports.defineProperty = defineProperty; // .......................................................... // DESCRIPTOR // /** Objects of this type can implement an interface to respond to requests to get and set. The default implementation handles simple properties. @class Descriptor @private */ function Descriptor() { this.isDescriptor = true; } var REDEFINE_SUPPORTED = (function () { // https://github.com/spalger/kibana/commit/b7e35e6737df585585332857a4c397dc206e7ff9 var a = Object.create(Object.prototype, { prop: { configurable: true, value: 1 } }); Object.defineProperty(a, 'prop', { configurable: true, value: 2 }); return a.prop === 2; })(); // .......................................................... // DEFINING PROPERTIES API // function MANDATORY_SETTER_FUNCTION(name) { function SETTER_FUNCTION(value) { var m = _emberMetalMeta.peekMeta(this); if (!m.isInitialized(this)) { m.writeValues(name, value); } else { _emberMetalDebug.assert('You must use Ember.set() to set the `' + name + '` property (of ' + this + ') to `' + value + '`.', false); } } SETTER_FUNCTION.isMandatorySetter = true; return SETTER_FUNCTION; } function DEFAULT_GETTER_FUNCTION(name) { return function GETTER_FUNCTION() { var meta = _emberMetalMeta.peekMeta(this); return meta && meta.peekValues(name); }; } function INHERITING_GETTER_FUNCTION(name) { function IGETTER_FUNCTION() { var meta = _emberMetalMeta.peekMeta(this); var val = meta && meta.readInheritedValue('values', name); if (val === _emberMetalMeta.UNDEFINED) { var proto = Object.getPrototypeOf(this); return proto && proto[name]; } else { return val; } } IGETTER_FUNCTION.isInheritingGetter = true; return IGETTER_FUNCTION; } /** NOTE: This is a low-level method used by other parts of the API. You almost never want to call this method directly. Instead you should use `Ember.mixin()` to define new properties. Defines a property on an object. This method works much like the ES5 `Object.defineProperty()` method except that it can also accept computed properties and other special descriptors. Normally this method takes only three parameters. However if you pass an instance of `Descriptor` as the third param then you can pass an optional value as the fourth parameter. This is often more efficient than creating new descriptor hashes for each property. ## Examples ```javascript // ES5 compatible mode Ember.defineProperty(contact, 'firstName', { writable: true, configurable: false, enumerable: true, value: 'Charles' }); // define a simple property Ember.defineProperty(contact, 'lastName', undefined, 'Jolley'); // define a computed property Ember.defineProperty(contact, 'fullName', Ember.computed('firstName', 'lastName', function() { return this.firstName+' '+this.lastName; })); ``` @private @method defineProperty @for Ember @param {Object} obj the object to define this property on. This may be a prototype. @param {String} keyName the name of the property @param {Descriptor} [desc] an instance of `Descriptor` (typically a computed property) or an ES5 descriptor. You must provide this or `data` but not both. @param {*} [data] something other than a descriptor, that will become the explicit value of this property. */ function defineProperty(obj, keyName, desc, data, meta) { var possibleDesc = undefined, existingDesc = undefined, watching = undefined, value = undefined; if (!meta) { meta = _emberMetalMeta.meta(obj); } var watchEntry = meta.peekWatching(keyName); possibleDesc = obj[keyName]; existingDesc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; watching = watchEntry !== undefined && watchEntry > 0; if (existingDesc) { existingDesc.teardown(obj, keyName); } if (desc instanceof Descriptor) { value = desc; if (true) { if (watching) { Object.defineProperty(obj, keyName, { configurable: true, enumerable: true, writable: true, value: value }); } else { obj[keyName] = value; } } else { obj[keyName] = value; } if (desc.setup) { desc.setup(obj, keyName); } } else { if (desc == null) { value = data; if (true) { if (watching) { meta.writeValues(keyName, data); var defaultDescriptor = { configurable: true, enumerable: true, set: MANDATORY_SETTER_FUNCTION(keyName), get: DEFAULT_GETTER_FUNCTION(keyName) }; if (REDEFINE_SUPPORTED) { Object.defineProperty(obj, keyName, defaultDescriptor); } else { handleBrokenPhantomDefineProperty(obj, keyName, defaultDescriptor); } } else { obj[keyName] = data; } } else { obj[keyName] = data; } } else { value = desc; // fallback to ES5 Object.defineProperty(obj, keyName, desc); } } // if key is being watched, override chains that // were initialized with the prototype if (watching) { _emberMetalProperty_events.overrideChains(obj, keyName, meta); } // The `value` passed to the `didDefineProperty` hook is // either the descriptor or data, whichever was passed. if (obj.didDefineProperty) { obj.didDefineProperty(obj, keyName, value); } return this; } function handleBrokenPhantomDefineProperty(obj, keyName, desc) { // https://github.com/ariya/phantomjs/issues/11856 Object.defineProperty(obj, keyName, { configurable: true, writable: true, value: 'iCry' }); Object.defineProperty(obj, keyName, desc); } }); enifed('ember-metal/property_events', ['exports', 'ember-metal/utils', 'ember-metal/meta', 'ember-metal/events', 'ember-metal/tags', 'ember-metal/observer_set', 'ember-metal/symbol'], function (exports, _emberMetalUtils, _emberMetalMeta, _emberMetalEvents, _emberMetalTags, _emberMetalObserver_set, _emberMetalSymbol) { 'use strict'; var PROPERTY_DID_CHANGE = _emberMetalSymbol.default('PROPERTY_DID_CHANGE'); exports.PROPERTY_DID_CHANGE = PROPERTY_DID_CHANGE; var beforeObserverSet = new _emberMetalObserver_set.default(); var observerSet = new _emberMetalObserver_set.default(); var deferred = 0; // .......................................................... // PROPERTY CHANGES // /** This function is called just before an object property is about to change. It will notify any before observers and prepare caches among other things. Normally you will not need to call this method directly but if for some reason you can't directly watch a property you can invoke this method manually along with `Ember.propertyDidChange()` which you should call just after the property value changes. @method propertyWillChange @for Ember @param {Object} obj The object with the property that will change @param {String} keyName The property key (or path) that will change. @return {void} @private */ function propertyWillChange(obj, keyName) { var m = _emberMetalMeta.peekMeta(obj); if (m && !m.isInitialized(obj)) { return; } var watching = m && m.peekWatching(keyName) > 0; var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; if (desc && desc.willChange) { desc.willChange(obj, keyName); } if (watching) { dependentKeysWillChange(obj, keyName, m); chainsWillChange(obj, keyName, m); notifyBeforeObservers(obj, keyName); } } /** This function is called just after an object property has changed. It will notify any observers and clear caches among other things. Normally you will not need to call this method directly but if for some reason you can't directly watch a property you can invoke this method manually along with `Ember.propertyWillChange()` which you should call just before the property value changes. @method propertyDidChange @for Ember @param {Object} obj The object with the property that will change @param {String} keyName The property key (or path) that will change. @return {void} @private */ function propertyDidChange(obj, keyName) { var m = _emberMetalMeta.peekMeta(obj); if (m && !m.isInitialized(obj)) { return; } var watching = m && m.peekWatching(keyName) > 0; var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; // shouldn't this mean that we're watching this key? if (desc && desc.didChange) { desc.didChange(obj, keyName); } if (watching) { if (m.hasDeps(keyName)) { dependentKeysDidChange(obj, keyName, m); } chainsDidChange(obj, keyName, m, false); notifyObservers(obj, keyName); } if (obj[PROPERTY_DID_CHANGE]) { obj[PROPERTY_DID_CHANGE](keyName); } _emberMetalTags.markObjectAsDirty(m); } var WILL_SEEN = undefined, DID_SEEN = undefined; // called whenever a property is about to change to clear the cache of any dependent keys (and notify those properties of changes, etc...) function dependentKeysWillChange(obj, depKey, meta) { if (obj.isDestroying) { return; } if (meta && meta.hasDeps(depKey)) { var seen = WILL_SEEN; var _top = !seen; if (_top) { seen = WILL_SEEN = {}; } iterDeps(propertyWillChange, obj, depKey, seen, meta); if (_top) { WILL_SEEN = null; } } } // called whenever a property has just changed to update dependent keys function dependentKeysDidChange(obj, depKey, meta) { if (obj.isDestroying) { return; } if (meta && meta.hasDeps(depKey)) { var seen = DID_SEEN; var _top2 = !seen; if (_top2) { seen = DID_SEEN = {}; } iterDeps(propertyDidChange, obj, depKey, seen, meta); if (_top2) { DID_SEEN = null; } } } function iterDeps(method, obj, depKey, seen, meta) { var possibleDesc = undefined, desc = undefined; var guid = _emberMetalUtils.guidFor(obj); var current = seen[guid]; if (!current) { current = seen[guid] = {}; } if (current[depKey]) { return; } current[depKey] = true; meta.forEachInDeps(depKey, function (key, value) { if (!value) { return; } possibleDesc = obj[key]; desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; if (desc && desc._suspended === obj) { return; } method(obj, key); }); } function chainsWillChange(obj, keyName, m) { var c = m.readableChainWatchers(); if (c) { c.notify(keyName, false, propertyWillChange); } } function chainsDidChange(obj, keyName, m) { var c = m.readableChainWatchers(); if (c) { c.notify(keyName, true, propertyDidChange); } } function overrideChains(obj, keyName, m) { var c = m.readableChainWatchers(); if (c) { c.revalidate(keyName); } } /** @method beginPropertyChanges @chainable @private */ function beginPropertyChanges() { deferred++; } /** @method endPropertyChanges @private */ function endPropertyChanges() { deferred--; if (deferred <= 0) { beforeObserverSet.clear(); observerSet.flush(); } } /** Make a series of property changes together in an exception-safe way. ```javascript Ember.changeProperties(function() { obj1.set('foo', mayBlowUpWhenSet); obj2.set('bar', baz); }); ``` @method changeProperties @param {Function} callback @param [binding] @private */ function changeProperties(callback, binding) { beginPropertyChanges(); try { callback.call(binding); } finally { endPropertyChanges.call(binding); } } function notifyBeforeObservers(obj, keyName) { if (obj.isDestroying) { return; } var eventName = keyName + ':before'; var listeners = undefined, added = undefined; if (deferred) { listeners = beforeObserverSet.add(obj, keyName, eventName); added = _emberMetalEvents.accumulateListeners(obj, eventName, listeners); _emberMetalEvents.sendEvent(obj, eventName, [obj, keyName], added); } else { _emberMetalEvents.sendEvent(obj, eventName, [obj, keyName]); } } function notifyObservers(obj, keyName) { if (obj.isDestroying) { return; } var eventName = keyName + ':change'; var listeners = undefined; if (deferred) { listeners = observerSet.add(obj, keyName, eventName); _emberMetalEvents.accumulateListeners(obj, eventName, listeners); } else { _emberMetalEvents.sendEvent(obj, eventName, [obj, keyName]); } } exports.propertyWillChange = propertyWillChange; exports.propertyDidChange = propertyDidChange; exports.overrideChains = overrideChains; exports.beginPropertyChanges = beginPropertyChanges; exports.endPropertyChanges = endPropertyChanges; exports.changeProperties = changeProperties; }); enifed('ember-metal/property_get', ['exports', 'ember-metal/debug', 'ember-metal/path_cache'], function (exports, _emberMetalDebug, _emberMetalPath_cache) { /** @module ember-metal */ 'use strict'; exports.get = get; exports._getPath = _getPath; exports.getWithDefault = getWithDefault; var ALLOWABLE_TYPES = { object: true, function: true, string: true }; // .......................................................... // GET AND SET // // If we are on a platform that supports accessors we can use those. // Otherwise simulate accessors by looking up the property directly on the // object. /** Gets the value of a property on an object. If the property is computed, the function will be invoked. If the property is not defined but the object implements the `unknownProperty` method then that will be invoked. If you plan to run on IE8 and older browsers then you should use this method anytime you want to retrieve a property on an object that you don't know for sure is private. (Properties beginning with an underscore '_' are considered private.) On all newer browsers, you only need to use this method to retrieve properties if the property might not be defined on the object and you want to respect the `unknownProperty` handler. Otherwise you can ignore this method. Note that if the object itself is `undefined`, this method will throw an error. @method get @for Ember @param {Object} obj The object to retrieve from. @param {String} keyName The property key to retrieve @return {Object} the property value or `null`. @public */ function get(obj, keyName) { _emberMetalDebug.assert('Get must be called with two arguments; an object and a property key', arguments.length === 2); _emberMetalDebug.assert('Cannot call get with \'' + keyName + '\' on an undefined object.', obj !== undefined && obj !== null); _emberMetalDebug.assert('The key provided to get must be a string, you passed ' + keyName, typeof keyName === 'string'); _emberMetalDebug.assert('\'this\' in paths is not supported', !_emberMetalPath_cache.hasThis(keyName)); // Helpers that operate with 'this' within an #each if (keyName === '') { return obj; } var value = obj[keyName]; var desc = value !== null && typeof value === 'object' && value.isDescriptor ? value : undefined; var ret = undefined; if (desc === undefined && _emberMetalPath_cache.isPath(keyName)) { return _getPath(obj, keyName); } if (desc) { return desc.get(obj, keyName); } else { ret = value; if (ret === undefined && 'object' === typeof obj && !(keyName in obj) && 'function' === typeof obj.unknownProperty) { return obj.unknownProperty(keyName); } return ret; } } function _getPath(root, path) { var obj = root; var parts = path.split('.'); for (var i = 0; i < parts.length; i++) { if (!isGettable(obj)) { return undefined; } obj = get(obj, parts[i]); if (obj && obj.isDestroyed) { return undefined; } } return obj; } function isGettable(obj) { if (obj == null) { return false; } return ALLOWABLE_TYPES[typeof obj]; } /** Retrieves the value of a property from an Object, or a default value in the case that the property returns `undefined`. ```javascript Ember.getWithDefault(person, 'lastName', 'Doe'); ``` @method getWithDefault @for Ember @param {Object} obj The object to retrieve from. @param {String} keyName The name of the property to retrieve @param {Object} defaultValue The value to return if the property value is undefined @return {Object} The property value or the defaultValue. @public */ function getWithDefault(root, key, defaultValue) { var value = get(root, key); if (value === undefined) { return defaultValue; } return value; } exports.default = get; }); enifed('ember-metal/property_set', ['exports', 'ember-metal/debug', 'ember-metal/features', 'ember-metal/property_get', 'ember-metal/property_events', 'ember-metal/error', 'ember-metal/path_cache', 'ember-metal/meta', 'ember-metal/utils'], function (exports, _emberMetalDebug, _emberMetalFeatures, _emberMetalProperty_get, _emberMetalProperty_events, _emberMetalError, _emberMetalPath_cache, _emberMetalMeta, _emberMetalUtils) { 'use strict'; exports.set = set; exports.trySet = trySet; /** Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the property is not defined but the object implements the `setUnknownProperty` method then that will be invoked as well. @method set @for Ember @param {Object} obj The object to modify. @param {String} keyName The property key to set @param {Object} value The value to set @return {Object} the passed value. @public */ function set(obj, keyName, value, tolerant) { _emberMetalDebug.assert('Set must be called with three or four arguments; an object, a property key, a value and tolerant true/false', arguments.length === 3 || arguments.length === 4); _emberMetalDebug.assert('Cannot call set with \'' + keyName + '\' on an undefined object.', obj && typeof obj === 'object' || typeof obj === 'function'); _emberMetalDebug.assert('The key provided to set must be a string, you passed ' + keyName, typeof keyName === 'string'); _emberMetalDebug.assert('\'this\' in paths is not supported', !_emberMetalPath_cache.hasThis(keyName)); _emberMetalDebug.assert('calling set on destroyed object: ' + _emberMetalUtils.toString(obj) + '.' + keyName + ' = ' + _emberMetalUtils.toString(value), !obj.isDestroyed); if (_emberMetalPath_cache.isPath(keyName)) { return setPath(obj, keyName, value, tolerant); } var meta = _emberMetalMeta.peekMeta(obj); var possibleDesc = obj[keyName]; var desc = undefined, currentValue = undefined; if (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) { desc = possibleDesc; } else { currentValue = possibleDesc; } if (desc) { /* computed property */ desc.set(obj, keyName, value); } else if (obj.setUnknownProperty && currentValue === undefined && !(keyName in obj)) { /* unknown property */ _emberMetalDebug.assert('setUnknownProperty must be a function', typeof obj.setUnknownProperty === 'function'); obj.setUnknownProperty(keyName, value); } else if (currentValue === value) { /* no change */ return value; } else { _emberMetalProperty_events.propertyWillChange(obj, keyName); if (true) { setWithMandatorySetter(meta, obj, keyName, value); } else { obj[keyName] = value; } _emberMetalProperty_events.propertyDidChange(obj, keyName); } return value; } if (true) { var setWithMandatorySetter = function (meta, obj, keyName, value) { if (meta && meta.peekWatching(keyName) > 0) { makeEnumerable(obj, keyName); meta.writeValue(obj, keyName, value); } else { obj[keyName] = value; } }; var makeEnumerable = function (obj, key) { var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc && desc.set && desc.set.isMandatorySetter) { desc.enumerable = true; Object.defineProperty(obj, key, desc); } }; } function setPath(root, path, value, tolerant) { // get the last part of the path var keyName = path.slice(path.lastIndexOf('.') + 1); // get the first part of the part path = path === keyName ? keyName : path.slice(0, path.length - (keyName.length + 1)); // unless the path is this, look up the first part to // get the root if (path !== 'this') { root = _emberMetalProperty_get._getPath(root, path); } if (!keyName || keyName.length === 0) { throw new _emberMetalError.default('Property set failed: You passed an empty path'); } if (!root) { if (tolerant) { return; } else { throw new _emberMetalError.default('Property set failed: object in path "' + path + '" could not be found or was destroyed.'); } } return set(root, keyName, value); } /** Error-tolerant form of `Ember.set`. Will not blow up if any part of the chain is `undefined`, `null`, or destroyed. This is primarily used when syncing bindings, which may try to update after an object has been destroyed. @method trySet @for Ember @param {Object} root The object to modify. @param {String} path The property path to set @param {Object} value The value to set @public */ function trySet(root, path, value) { return set(root, path, value, true); } }); enifed("ember-metal/replace", ["exports"], function (exports) { "use strict"; exports.default = replace; var splice = Array.prototype.splice; function replace(array, idx, amt, objects) { var args = [].concat(objects); var ret = []; // https://code.google.com/p/chromium/issues/detail?id=56588 var size = 60000; var start = idx; var ends = amt; var count = undefined, chunk = undefined; while (args.length) { count = ends > size ? size : ends; if (count <= 0) { count = 0; } chunk = args.splice(0, size); chunk = [start, count].concat(chunk); start += size; ends -= count; ret = ret.concat(splice.apply(array, chunk)); } return ret; } }); enifed('ember-metal/run_loop', ['exports', 'ember-metal/debug', 'ember-metal/testing', 'ember-metal/error_handler', 'ember-metal/utils', 'ember-metal/property_events', 'backburner'], function (exports, _emberMetalDebug, _emberMetalTesting, _emberMetalError_handler, _emberMetalUtils, _emberMetalProperty_events, _backburner) { 'use strict'; exports.default = run; function onBegin(current) { run.currentRunLoop = current; } function onEnd(current, next) { run.currentRunLoop = next; } var onErrorTarget = { get onerror() { return _emberMetalError_handler.getOnerror(); }, set onerror(handler) { return _emberMetalError_handler.setOnerror(handler); } }; var backburner = new _backburner.default(['sync', 'actions', 'destroy'], { GUID_KEY: _emberMetalUtils.GUID_KEY, sync: { before: _emberMetalProperty_events.beginPropertyChanges, after: _emberMetalProperty_events.endPropertyChanges }, defaultQueue: 'actions', onBegin: onBegin, onEnd: onEnd, onErrorTarget: onErrorTarget, onErrorMethod: 'onerror' }); // .......................................................... // run - this is ideally the only public API the dev sees // /** Runs the passed target and method inside of a RunLoop, ensuring any deferred actions including bindings and views updates are flushed at the end. Normally you should not need to invoke this method yourself. However if you are implementing raw event handlers when interfacing with other libraries or plugins, you should probably wrap all of your code inside this call. ```javascript run(function() { // code to be executed within a RunLoop }); ``` @class run @namespace Ember @static @constructor @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Object} return value from invoking the passed function. @public */ function run() { return backburner.run.apply(backburner, arguments); } /** If no run-loop is present, it creates a new one. If a run loop is present it will queue itself to run on the existing run-loops action queue. Please note: This is not for normal usage, and should be used sparingly. If invoked when not within a run loop: ```javascript run.join(function() { // creates a new run-loop }); ``` Alternatively, if called within an existing run loop: ```javascript run(function() { // creates a new run-loop run.join(function() { // joins with the existing run-loop, and queues for invocation on // the existing run-loops action queue. }); }); ``` @method join @namespace Ember @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Object} Return value from invoking the passed function. Please note, when called within an existing loop, no return value is possible. @public */ run.join = function () { return backburner.join.apply(backburner, arguments); }; /** Allows you to specify which context to call the specified function in while adding the execution of that function to the Ember run loop. This ability makes this method a great way to asynchronously integrate third-party libraries into your Ember application. `run.bind` takes two main arguments, the desired context and the function to invoke in that context. Any additional arguments will be supplied as arguments to the function that is passed in. Let's use the creation of a TinyMCE component as an example. Currently, TinyMCE provides a setup configuration option we can use to do some processing after the TinyMCE instance is initialized but before it is actually rendered. We can use that setup option to do some additional setup for our component. The component itself could look something like the following: ```javascript App.RichTextEditorComponent = Ember.Component.extend({ initializeTinyMCE: Ember.on('didInsertElement', function() { tinymce.init({ selector: '#' + this.$().prop('id'), setup: Ember.run.bind(this, this.setupEditor) }); }), setupEditor: function(editor) { this.set('editor', editor); editor.on('change', function() { console.log('content changed!'); }); } }); ``` In this example, we use Ember.run.bind to bind the setupEditor method to the context of the App.RichTextEditorComponent and to have the invocation of that method be safely handled and executed by the Ember run loop. @method bind @namespace Ember @param {Object} [target] target of method to call @param {Function|String} method Method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Any additional arguments you wish to pass to the method. @return {Function} returns a new function that will always have a particular context @since 1.4.0 @public */ run.bind = function () { for (var _len = arguments.length, curried = Array(_len), _key = 0; _key < _len; _key++) { curried[_key] = arguments[_key]; } return function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return run.join.apply(run, curried.concat(args)); }; }; run.backburner = backburner; run.currentRunLoop = null; run.queues = backburner.queueNames; /** Begins a new RunLoop. Any deferred actions invoked after the begin will be buffered until you invoke a matching call to `run.end()`. This is a lower-level way to use a RunLoop instead of using `run()`. ```javascript run.begin(); // code to be executed within a RunLoop run.end(); ``` @method begin @return {void} @public */ run.begin = function () { backburner.begin(); }; /** Ends a RunLoop. This must be called sometime after you call `run.begin()` to flush any deferred actions. This is a lower-level way to use a RunLoop instead of using `run()`. ```javascript run.begin(); // code to be executed within a RunLoop run.end(); ``` @method end @return {void} @public */ run.end = function () { backburner.end(); }; /** Array of named queues. This array determines the order in which queues are flushed at the end of the RunLoop. You can define your own queues by simply adding the queue name to this array. Normally you should not need to inspect or modify this property. @property queues @type Array @default ['sync', 'actions', 'destroy'] @private */ /** Adds the passed target/method and any optional arguments to the named queue to be executed at the end of the RunLoop. If you have not already started a RunLoop when calling this method one will be started for you automatically. At the end of a RunLoop, any methods scheduled in this way will be invoked. Methods will be invoked in an order matching the named queues defined in the `run.queues` property. ```javascript run.schedule('sync', this, function() { // this will be executed in the first RunLoop queue, when bindings are synced console.log('scheduled on sync queue'); }); run.schedule('actions', this, function() { // this will be executed in the 'actions' queue, after bindings have synced. console.log('scheduled on actions queue'); }); // Note the functions will be run in order based on the run queues order. // Output would be: // scheduled on sync queue // scheduled on actions queue ``` @method schedule @param {String} queue The name of the queue to schedule against. Default queues are 'sync' and 'actions' @param {Object} [target] target object to use as the context when invoking a method. @param {String|Function} method The method to invoke. If you pass a string it will be resolved on the target object at the time the scheduled item is invoked allowing you to change the target function. @param {Object} [arguments*] Optional arguments to be passed to the queued method. @return {void} @public */ run.schedule = function () /* queue, target, method */{ _emberMetalDebug.assert('You have turned on testing mode, which disabled the run-loop\'s autorun. ' + 'You will need to wrap any code with asynchronous side-effects in a run', run.currentRunLoop || !_emberMetalTesting.isTesting()); backburner.schedule.apply(backburner, arguments); }; // Used by global test teardown run.hasScheduledTimers = function () { return backburner.hasTimers(); }; // Used by global test teardown run.cancelTimers = function () { backburner.cancelTimers(); }; /** Immediately flushes any events scheduled in the 'sync' queue. Bindings use this queue so this method is a useful way to immediately force all bindings in the application to sync. You should call this method anytime you need any changed state to propagate throughout the app immediately without repainting the UI (which happens in the later 'render' queue added by the `ember-views` package). ```javascript run.sync(); ``` @method sync @return {void} @private */ run.sync = function () { if (backburner.currentInstance) { backburner.currentInstance.queues.sync.flush(); } }; /** Invokes the passed target/method and optional arguments after a specified period of time. The last parameter of this method must always be a number of milliseconds. You should use this method whenever you need to run some action after a period of time instead of using `setTimeout()`. This method will ensure that items that expire during the same script execution cycle all execute together, which is often more efficient than using a real setTimeout. ```javascript run.later(myContext, function() { // code here will execute within a RunLoop in about 500ms with this == myContext }, 500); ``` @method later @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} wait Number of milliseconds to wait. @return {*} Timer information for use in cancelling, see `run.cancel`. @public */ run.later = function () /*target, method*/{ return backburner.later.apply(backburner, arguments); }; /** Schedule a function to run one time during the current RunLoop. This is equivalent to calling `scheduleOnce` with the "actions" queue. @method once @param {Object} [target] The target of the method to invoke. @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} Timer information for use in cancelling, see `run.cancel`. @public */ run.once = function () { _emberMetalDebug.assert('You have turned on testing mode, which disabled the run-loop\'s autorun. ' + 'You will need to wrap any code with asynchronous side-effects in a run', run.currentRunLoop || !_emberMetalTesting.isTesting()); for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } args.unshift('actions'); return backburner.scheduleOnce.apply(backburner, args); }; /** Schedules a function to run one time in a given queue of the current RunLoop. Calling this method with the same queue/target/method combination will have no effect (past the initial call). Note that although you can pass optional arguments these will not be considered when looking for duplicates. New arguments will replace previous calls. ```javascript function sayHi() { console.log('hi'); } run(function() { run.scheduleOnce('afterRender', myContext, sayHi); run.scheduleOnce('afterRender', myContext, sayHi); // sayHi will only be executed once, in the afterRender queue of the RunLoop }); ``` Also note that passing an anonymous function to `run.scheduleOnce` will not prevent additional calls with an identical anonymous function from scheduling the items multiple times, e.g.: ```javascript function scheduleIt() { run.scheduleOnce('actions', myContext, function() { console.log('Closure'); }); } scheduleIt(); scheduleIt(); // "Closure" will print twice, even though we're using `run.scheduleOnce`, // because the function we pass to it is anonymous and won't match the // previously scheduled operation. ``` Available queues, and their order, can be found at `run.queues` @method scheduleOnce @param {String} [queue] The name of the queue to schedule against. Default queues are 'sync' and 'actions'. @param {Object} [target] The target of the method to invoke. @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} Timer information for use in cancelling, see `run.cancel`. @public */ run.scheduleOnce = function () /*queue, target, method*/{ _emberMetalDebug.assert('You have turned on testing mode, which disabled the run-loop\'s autorun. ' + 'You will need to wrap any code with asynchronous side-effects in a run', run.currentRunLoop || !_emberMetalTesting.isTesting()); return backburner.scheduleOnce.apply(backburner, arguments); }; /** Schedules an item to run from within a separate run loop, after control has been returned to the system. This is equivalent to calling `run.later` with a wait time of 1ms. ```javascript run.next(myContext, function() { // code to be executed in the next run loop, // which will be scheduled after the current one }); ``` Multiple operations scheduled with `run.next` will coalesce into the same later run loop, along with any other operations scheduled by `run.later` that expire right around the same time that `run.next` operations will fire. Note that there are often alternatives to using `run.next`. For instance, if you'd like to schedule an operation to happen after all DOM element operations have completed within the current run loop, you can make use of the `afterRender` run loop queue (added by the `ember-views` package, along with the preceding `render` queue where all the DOM element operations happen). Example: ```javascript export default Ember.Component.extend({ didInsertElement() { this._super(...arguments); run.scheduleOnce('afterRender', this, 'processChildElements'); }, processChildElements() { // ... do something with component's child component // elements after they've finished rendering, which // can't be done within this component's // `didInsertElement` hook because that gets run // before the child elements have been added to the DOM. } }); ``` One benefit of the above approach compared to using `run.next` is that you will be able to perform DOM/CSS operations before unprocessed elements are rendered to the screen, which may prevent flickering or other artifacts caused by delaying processing until after rendering. The other major benefit to the above approach is that `run.next` introduces an element of non-determinism, which can make things much harder to test, due to its reliance on `setTimeout`; it's much harder to guarantee the order of scheduled operations when they are scheduled outside of the current run loop, i.e. with `run.next`. @method next @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. If you pass a string it will be resolved on the target at the time the method is invoked. @param {Object} [args*] Optional arguments to pass to the timeout. @return {Object} Timer information for use in cancelling, see `run.cancel`. @public */ run.next = function () { for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } args.push(1); return backburner.later.apply(backburner, args); }; /** Cancels a scheduled item. Must be a value returned by `run.later()`, `run.once()`, `run.scheduleOnce()`, `run.next()`, `run.debounce()`, or `run.throttle()`. ```javascript let runNext = run.next(myContext, function() { // will not be executed }); run.cancel(runNext); let runLater = run.later(myContext, function() { // will not be executed }, 500); run.cancel(runLater); let runScheduleOnce = run.scheduleOnce('afterRender', myContext, function() { // will not be executed }); run.cancel(runScheduleOnce); let runOnce = run.once(myContext, function() { // will not be executed }); run.cancel(runOnce); let throttle = run.throttle(myContext, function() { // will not be executed }, 1, false); run.cancel(throttle); let debounce = run.debounce(myContext, function() { // will not be executed }, 1); run.cancel(debounce); let debounceImmediate = run.debounce(myContext, function() { // will be executed since we passed in true (immediate) }, 100, true); // the 100ms delay until this method can be called again will be cancelled run.cancel(debounceImmediate); ``` @method cancel @param {Object} timer Timer object to cancel @return {Boolean} true if cancelled or false/undefined if it wasn't found @public */ run.cancel = function (timer) { return backburner.cancel(timer); }; /** Delay calling the target method until the debounce period has elapsed with no additional debounce calls. If `debounce` is called again before the specified time has elapsed, the timer is reset and the entire period must pass again before the target method is called. This method should be used when an event may be called multiple times but the action should only be called once when the event is done firing. A common example is for scroll events where you only want updates to happen once scrolling has ceased. ```javascript function whoRan() { console.log(this.name + ' ran.'); } let myContext = { name: 'debounce' }; run.debounce(myContext, whoRan, 150); // less than 150ms passes run.debounce(myContext, whoRan, 150); // 150ms passes // whoRan is invoked with context myContext // console logs 'debounce ran.' one time. ``` Immediate allows you to run the function immediately, but debounce other calls for this function until the wait time has elapsed. If `debounce` is called again before the specified time has elapsed, the timer is reset and the entire period must pass again before the method can be called again. ```javascript function whoRan() { console.log(this.name + ' ran.'); } let myContext = { name: 'debounce' }; run.debounce(myContext, whoRan, 150, true); // console logs 'debounce ran.' one time immediately. // 100ms passes run.debounce(myContext, whoRan, 150, true); // 150ms passes and nothing else is logged to the console and // the debouncee is no longer being watched run.debounce(myContext, whoRan, 150, true); // console logs 'debounce ran.' one time immediately. // 150ms passes and nothing else is logged to the console and // the debouncee is no longer being watched ``` @method debounce @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} wait Number of milliseconds to wait. @param {Boolean} immediate Trigger the function on the leading instead of the trailing edge of the wait interval. Defaults to false. @return {Array} Timer information for use in cancelling, see `run.cancel`. @public */ run.debounce = function () { return backburner.debounce.apply(backburner, arguments); }; /** Ensure that the target method is never called more frequently than the specified spacing period. The target method is called immediately. ```javascript function whoRan() { console.log(this.name + ' ran.'); } let myContext = { name: 'throttle' }; run.throttle(myContext, whoRan, 150); // whoRan is invoked with context myContext // console logs 'throttle ran.' // 50ms passes run.throttle(myContext, whoRan, 150); // 50ms passes run.throttle(myContext, whoRan, 150); // 150ms passes run.throttle(myContext, whoRan, 150); // whoRan is invoked with context myContext // console logs 'throttle ran.' ``` @method throttle @param {Object} [target] target of method to invoke @param {Function|String} method The method to invoke. May be a function or a string. If you pass a string then it will be looked up on the passed target. @param {Object} [args*] Optional arguments to pass to the timeout. @param {Number} spacing Number of milliseconds to space out requests. @param {Boolean} immediate Trigger the function on the leading instead of the trailing edge of the wait interval. Defaults to true. @return {Array} Timer information for use in cancelling, see `run.cancel`. @public */ run.throttle = function () { return backburner.throttle.apply(backburner, arguments); }; /** Add a new named queue after the specified queue. The queue to add will only be added once. @method _addQueue @param {String} name the name of the queue to add. @param {String} after the name of the queue to add after. @private */ run._addQueue = function (name, after) { if (run.queues.indexOf(name) === -1) { run.queues.splice(run.queues.indexOf(after) + 1, 0, name); } }; }); enifed('ember-metal/set_properties', ['exports', 'ember-metal/property_events', 'ember-metal/property_set'], function (exports, _emberMetalProperty_events, _emberMetalProperty_set) { 'use strict'; exports.default = setProperties; /** Set a list of properties on an object. These properties are set inside a single `beginPropertyChanges` and `endPropertyChanges` batch, so observers will be buffered. ```javascript let anObject = Ember.Object.create(); anObject.setProperties({ firstName: 'Stanley', lastName: 'Stuart', age: 21 }); ``` @method setProperties @param obj @param {Object} properties @return properties @public */ function setProperties(obj, properties) { if (!properties || typeof properties !== 'object') { return properties; } _emberMetalProperty_events.changeProperties(function () { var props = Object.keys(properties); var propertyName = undefined; for (var i = 0; i < props.length; i++) { propertyName = props[i]; _emberMetalProperty_set.set(obj, propertyName, properties[propertyName]); } }); return properties; } }); enifed('ember-metal/symbol', ['exports', 'ember-metal/utils'], function (exports, _emberMetalUtils) { 'use strict'; exports.default = symbol; function symbol(debugName) { // TODO: Investigate using platform symbols, but we do not // want to require non-enumerability for this API, which // would introduce a large cost. return _emberMetalUtils.intern(debugName + ' [id=' + _emberMetalUtils.GUID_KEY + Math.floor(Math.random() * new Date()) + ']'); } }); enifed('ember-metal/tags', ['exports', 'ember-metal/meta', 'require'], function (exports, _emberMetalMeta, _require2) { 'use strict'; exports.setHasViews = setHasViews; exports.tagFor = tagFor; var hasGlimmer = _require2.has('glimmer-reference'); var CONSTANT_TAG = undefined, CURRENT_TAG = undefined, DirtyableTag = undefined, makeTag = undefined, run = undefined; var hasViews = function () { return false; }; function setHasViews(fn) { hasViews = fn; } var markObjectAsDirty = undefined; exports.markObjectAsDirty = markObjectAsDirty; function tagFor(object, _meta) { if (!hasGlimmer) { throw new Error('Cannot call tagFor without Glimmer'); } if (object && typeof object === 'object') { var meta = _meta || _emberMetalMeta.meta(object); return meta.writableTag(makeTag); } else { return CONSTANT_TAG; } } function K() {} function ensureRunloop() { if (!run) { run = _require2.default('ember-metal/run_loop').default; } if (hasViews() && !run.backburner.currentInstance) { run.schedule('actions', K); } } if (hasGlimmer) { var _require = _require2.default('glimmer-reference'); DirtyableTag = _require.DirtyableTag; CONSTANT_TAG = _require.CONSTANT_TAG; CURRENT_TAG = _require.CURRENT_TAG; makeTag = function () { return new DirtyableTag(); }; exports.markObjectAsDirty = markObjectAsDirty = function (meta) { ensureRunloop(); var tag = meta && meta.readableTag() || CURRENT_TAG; tag.dirty(); }; } else { exports.markObjectAsDirty = markObjectAsDirty = function () {}; } }); enifed("ember-metal/testing", ["exports"], function (exports) { "use strict"; exports.isTesting = isTesting; exports.setTesting = setTesting; var testing = false; function isTesting() { return testing; } function setTesting(value) { testing = !!value; } }); enifed('ember-metal/utils', ['exports'], function (exports) { 'no use strict'; // Remove "use strict"; from transpiled module until // https://bugs.webkit.org/show_bug.cgi?id=138038 is fixed /** @module ember-metal */ /** Previously we used `Ember.$.uuid`, however `$.uuid` has been removed from jQuery master. We'll just bootstrap our own uuid now. @private @return {Number} the uuid */ exports.uuid = uuid; exports.intern = intern; exports.generateGuid = generateGuid; exports.guidFor = guidFor; exports.wrap = wrap; exports.tryInvoke = tryInvoke; exports.makeArray = makeArray; exports.inspect = inspect; exports.applyStr = applyStr; exports.lookupDescriptor = lookupDescriptor; exports.toString = toString; var _uuid = 0; /** Generates a universally unique identifier. This method is used internally by Ember for assisting with the generation of GUID's and other unique identifiers. @public @return {Number} [description] */ function uuid() { return ++_uuid; } /** Prefix used for guids through out Ember. @private @property GUID_PREFIX @for Ember @type String @final */ var GUID_PREFIX = 'ember'; // Used for guid generation... var numberCache = []; var stringCache = {}; /** Strongly hint runtimes to intern the provided string. When do I need to use this function? For the most part, never. Pre-mature optimization is bad, and often the runtime does exactly what you need it to, and more often the trade-off isn't worth it. Why? Runtimes store strings in at least 2 different representations: Ropes and Symbols (interned strings). The Rope provides a memory efficient data-structure for strings created from concatenation or some other string manipulation like splitting. Unfortunately checking equality of different ropes can be quite costly as runtimes must resort to clever string comparison algorithms. These algorithms typically cost in proportion to the length of the string. Luckily, this is where the Symbols (interned strings) shine. As Symbols are unique by their string content, equality checks can be done by pointer comparison. How do I know if my string is a rope or symbol? Typically (warning general sweeping statement, but truthy in runtimes at present) static strings created as part of the JS source are interned. Strings often used for comparisons can be interned at runtime if some criteria are met. One of these criteria can be the size of the entire rope. For example, in chrome 38 a rope longer then 12 characters will not intern, nor will segments of that rope. Some numbers: http://jsperf.com/eval-vs-keys/8 Known Trick™ @private @return {String} interned version of the provided string */ function intern(str) { var obj = {}; obj[str] = 1; for (var key in obj) { if (key === str) { return key; } } return str; } /** A unique key used to assign guids and other private metadata to objects. If you inspect an object in your browser debugger you will often see these. They can be safely ignored. On browsers that support it, these properties are added with enumeration disabled so they won't show up when you iterate over your properties. @private @property GUID_KEY @for Ember @type String @final */ var GUID_KEY = intern('__ember' + +new Date()); var GUID_DESC = { writable: true, configurable: true, enumerable: false, value: null }; exports.GUID_DESC = GUID_DESC; var nullDescriptor = { configurable: true, writable: true, enumerable: false, value: null }; var GUID_KEY_PROPERTY = { name: GUID_KEY, descriptor: nullDescriptor }; exports.GUID_KEY_PROPERTY = GUID_KEY_PROPERTY; /** Generates a new guid, optionally saving the guid to the object that you pass in. You will rarely need to use this method. Instead you should call `Ember.guidFor(obj)`, which return an existing guid if available. @private @method generateGuid @for Ember @param {Object} [obj] Object the guid will be used for. If passed in, the guid will be saved on the object and reused whenever you pass the same object again. If no object is passed, just generate a new guid. @param {String} [prefix] Prefix to place in front of the guid. Useful when you want to separate the guid into separate namespaces. @return {String} the guid */ function generateGuid(obj, prefix) { if (!prefix) { prefix = GUID_PREFIX; } var ret = prefix + uuid(); if (obj) { if (obj[GUID_KEY] === null) { obj[GUID_KEY] = ret; } else { GUID_DESC.value = ret; if (obj.__defineNonEnumerable) { obj.__defineNonEnumerable(GUID_KEY_PROPERTY); } else { Object.defineProperty(obj, GUID_KEY, GUID_DESC); } } } return ret; } /** Returns a unique id for the object. If the object does not yet have a guid, one will be assigned to it. You can call this on any object, `Ember.Object`-based or not, but be aware that it will add a `_guid` property. You can also use this method on DOM Element objects. @public @method guidFor @for Ember @param {Object} obj any object, string, number, Element, or primitive @return {String} the unique guid for this instance. */ function guidFor(obj) { if (obj && obj[GUID_KEY]) { return obj[GUID_KEY]; } // special cases where we don't want to add a key to object if (obj === undefined) { return '(undefined)'; } if (obj === null) { return '(null)'; } var ret = undefined; var type = typeof obj; // Don't allow prototype changes to String etc. to change the guidFor switch (type) { case 'number': ret = numberCache[obj]; if (!ret) { ret = numberCache[obj] = 'nu' + obj; } return ret; case 'string': ret = stringCache[obj]; if (!ret) { ret = stringCache[obj] = 'st' + uuid(); } return ret; case 'boolean': return obj ? '(true)' : '(false)'; default: if (obj === Object) { return '(Object)'; } if (obj === Array) { return '(Array)'; } ret = GUID_PREFIX + uuid(); if (obj[GUID_KEY] === null) { obj[GUID_KEY] = ret; } else { GUID_DESC.value = ret; if (obj.__defineNonEnumerable) { obj.__defineNonEnumerable(GUID_KEY_PROPERTY); } else { Object.defineProperty(obj, GUID_KEY, GUID_DESC); } } return ret; } } var HAS_SUPER_PATTERN = /\.(_super|call\(this|apply\(this)/; var fnToString = Function.prototype.toString; var checkHasSuper = (function () { var sourceAvailable = fnToString.call(function () { return this; }).indexOf('return this') > -1; if (sourceAvailable) { return function checkHasSuper(func) { return HAS_SUPER_PATTERN.test(fnToString.call(func)); }; } return function checkHasSuper() { return true; }; })(); exports.checkHasSuper = checkHasSuper; function ROOT() {} ROOT.__hasSuper = false; function hasSuper(func) { if (func.__hasSuper === undefined) { func.__hasSuper = checkHasSuper(func); } return func.__hasSuper; } /** Wraps the passed function so that `this._super` will point to the superFunc when the function is invoked. This is the primitive we use to implement calls to super. @private @method wrap @for Ember @param {Function} func The function to call @param {Function} superFunc The super function. @return {Function} wrapped function. */ function wrap(func, superFunc) { if (!hasSuper(func)) { return func; } // ensure an unwrapped super that calls _super is wrapped with a terminal _super if (!superFunc.wrappedFunction && hasSuper(superFunc)) { return _wrap(func, _wrap(superFunc, ROOT)); } return _wrap(func, superFunc); } function _wrap(func, superFunc) { function superWrapper() { var orig = this._super; this._super = superFunc; var ret = func.apply(this, arguments); this._super = orig; return ret; } superWrapper.wrappedFunction = func; superWrapper.__ember_observes__ = func.__ember_observes__; superWrapper.__ember_observesBefore__ = func.__ember_observesBefore__; superWrapper.__ember_listens__ = func.__ember_listens__; return superWrapper; } /** Checks to see if the `methodName` exists on the `obj`. ```javascript let foo = { bar: function() { return 'bar'; }, baz: null }; Ember.canInvoke(foo, 'bar'); // true Ember.canInvoke(foo, 'baz'); // false Ember.canInvoke(foo, 'bat'); // false ``` @method canInvoke @for Ember @param {Object} obj The object to check for the method @param {String} methodName The method name to check for @return {Boolean} @private */ function canInvoke(obj, methodName) { return !!(obj && typeof obj[methodName] === 'function'); } /** Checks to see if the `methodName` exists on the `obj`, and if it does, invokes it with the arguments passed. ```javascript let d = new Date('03/15/2013'); Ember.tryInvoke(d, 'getTime'); // 1363320000000 Ember.tryInvoke(d, 'setFullYear', [2014]); // 1394856000000 Ember.tryInvoke(d, 'noSuchMethod', [2014]); // undefined ``` @method tryInvoke @for Ember @param {Object} obj The object to check for the method @param {String} methodName The method name to check for @param {Array} [args] The arguments to pass to the method @return {*} the return value of the invoked method or undefined if it cannot be invoked @public */ function tryInvoke(obj, methodName, args) { if (canInvoke(obj, methodName)) { return args ? applyStr(obj, methodName, args) : applyStr(obj, methodName); } } // ........................................ // TYPING & ARRAY MESSAGING // var objectToString = Object.prototype.toString; /** Forces the passed object to be part of an array. If the object is already an array, it will return the object. Otherwise, it will add the object to an array. If obj is `null` or `undefined`, it will return an empty array. ```javascript Ember.makeArray(); // [] Ember.makeArray(null); // [] Ember.makeArray(undefined); // [] Ember.makeArray('lindsay'); // ['lindsay'] Ember.makeArray([1, 2, 42]); // [1, 2, 42] let controller = Ember.ArrayProxy.create({ content: [] }); Ember.makeArray(controller) === controller; // true ``` @method makeArray @for Ember @param {Object} obj the object @return {Array} @private */ function makeArray(obj) { if (obj === null || obj === undefined) { return []; } return Array.isArray(obj) ? obj : [obj]; } /** Convenience method to inspect an object. This method will attempt to convert the object into a useful string description. It is a pretty simple implementation. If you want something more robust, use something like JSDump: https://github.com/NV/jsDump @method inspect @for Ember @param {Object} obj The object you want to inspect. @return {String} A description of the object @since 1.4.0 @private */ function inspect(obj) { if (obj === null) { return 'null'; } if (obj === undefined) { return 'undefined'; } if (Array.isArray(obj)) { return '[' + obj + ']'; } // for non objects var type = typeof obj; if (type !== 'object' && type !== 'symbol') { return '' + obj; } // overridden toString if (typeof obj.toString === 'function' && obj.toString !== objectToString) { return obj.toString(); } // Object.prototype.toString === {}.toString var v = undefined; var ret = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { v = obj[key]; if (v === 'toString') { continue; } // ignore useless items if (typeof v === 'function') { v = 'function() { ... }'; } if (v && typeof v.toString !== 'function') { ret.push(key + ': ' + objectToString.call(v)); } else { ret.push(key + ': ' + v); } } } return '{' + ret.join(', ') + '}'; } /** @param {Object} t target @param {String} m method @param {Array} a args @private */ function applyStr(t, m, a) { var l = a && a.length; if (!a || !l) { return t[m](); } switch (l) { case 1: return t[m](a[0]); case 2: return t[m](a[0], a[1]); case 3: return t[m](a[0], a[1], a[2]); case 4: return t[m](a[0], a[1], a[2], a[3]); case 5: return t[m](a[0], a[1], a[2], a[3], a[4]); default: return t[m].apply(t, a); } } function lookupDescriptor(obj, keyName) { var current = obj; while (current) { var descriptor = Object.getOwnPropertyDescriptor(current, keyName); if (descriptor) { return descriptor; } current = Object.getPrototypeOf(current); } return null; } // A `toString` util function that supports objects without a `toString` // method, e.g. an object created with `Object.create(null)`. function toString(obj) { if (obj && obj.toString) { return obj.toString(); } else { return objectToString.call(obj); } } exports.GUID_KEY = GUID_KEY; exports.makeArray = makeArray; exports.canInvoke = canInvoke; }); enifed('ember-metal/watch_key', ['exports', 'ember-metal/features', 'ember-metal/meta', 'ember-metal/properties', 'ember-metal/utils'], function (exports, _emberMetalFeatures, _emberMetalMeta, _emberMetalProperties, _emberMetalUtils) { 'use strict'; exports.watchKey = watchKey; exports.unwatchKey = unwatchKey; var handleMandatorySetter = undefined; function watchKey(obj, keyName, meta) { var m = meta || _emberMetalMeta.meta(obj); // activate watching first time if (!m.peekWatching(keyName)) { m.writeWatching(keyName, 1); var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; if (desc && desc.willWatch) { desc.willWatch(obj, keyName); } if ('function' === typeof obj.willWatchProperty) { obj.willWatchProperty(keyName); } if (true) { // NOTE: this is dropped for prod + minified builds handleMandatorySetter(m, obj, keyName); } } else { m.writeWatching(keyName, (m.peekWatching(keyName) || 0) + 1); } } if (true) { (function () { var hasOwnProperty = function (obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); }; var propertyIsEnumerable = function (obj, key) { return Object.prototype.propertyIsEnumerable.call(obj, key); }; // Future traveler, although this code looks scary. It merely exists in // development to aid in development asertions. Production builds of // ember strip this entire block out handleMandatorySetter = function handleMandatorySetter(m, obj, keyName) { var descriptor = _emberMetalUtils.lookupDescriptor(obj, keyName); var configurable = descriptor ? descriptor.configurable : true; var isWritable = descriptor ? descriptor.writable : true; var hasValue = descriptor ? 'value' in descriptor : true; var possibleDesc = descriptor && descriptor.value; var isDescriptor = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor; if (isDescriptor) { return; } // this x in Y deopts, so keeping it in this function is better; if (configurable && isWritable && hasValue && keyName in obj) { var desc = { configurable: true, set: _emberMetalProperties.MANDATORY_SETTER_FUNCTION(keyName), enumerable: propertyIsEnumerable(obj, keyName), get: undefined }; if (hasOwnProperty(obj, keyName)) { m.writeValues(keyName, obj[keyName]); desc.get = _emberMetalProperties.DEFAULT_GETTER_FUNCTION(keyName); } else { desc.get = _emberMetalProperties.INHERITING_GETTER_FUNCTION(keyName); } Object.defineProperty(obj, keyName, desc); } }; })(); } function unwatchKey(obj, keyName, meta) { var m = meta || _emberMetalMeta.meta(obj); var count = m.peekWatching(keyName); if (count === 1) { m.writeWatching(keyName, 0); var possibleDesc = obj[keyName]; var desc = possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor ? possibleDesc : undefined; if (desc && desc.didUnwatch) { desc.didUnwatch(obj, keyName); } if ('function' === typeof obj.didUnwatchProperty) { obj.didUnwatchProperty(keyName); } if (true) { // It is true, the following code looks quite WAT. But have no fear, It // exists purely to improve development ergonomics and is removed from // ember.min.js and ember.prod.js builds. // // Some further context: Once a property is watched by ember, bypassing `set` // for mutation, will bypass observation. This code exists to assert when // that occurs, and attempt to provide more helpful feedback. The alternative // is tricky to debug partially observable properties. if (!desc && keyName in obj) { var maybeMandatoryDescriptor = _emberMetalUtils.lookupDescriptor(obj, keyName); if (maybeMandatoryDescriptor.set && maybeMandatoryDescriptor.set.isMandatorySetter) { if (maybeMandatoryDescriptor.get && maybeMandatoryDescriptor.get.isInheritingGetter) { var possibleValue = m.readInheritedValue('values', keyName); if (possibleValue === _emberMetalMeta.UNDEFINED) { delete obj[keyName]; return; } } Object.defineProperty(obj, keyName, { configurable: true, enumerable: Object.prototype.propertyIsEnumerable.call(obj, keyName), writable: true, value: m.peekValues(keyName) }); m.deleteFromValues(keyName); } } } } else if (count > 1) { m.writeWatching(keyName, count - 1); } } }); enifed('ember-metal/watch_path', ['exports', 'ember-metal/meta', 'ember-metal/chains'], function (exports, _emberMetalMeta, _emberMetalChains) { 'use strict'; exports.makeChainNode = makeChainNode; exports.watchPath = watchPath; exports.unwatchPath = unwatchPath; // get the chains for the current object. If the current object has // chains inherited from the proto they will be cloned and reconfigured for // the current object. function chainsFor(obj, meta) { return (meta || _emberMetalMeta.meta(obj)).writableChains(makeChainNode); } function makeChainNode(obj) { return new _emberMetalChains.ChainNode(null, null, obj); } function watchPath(obj, keyPath, meta) { var m = meta || _emberMetalMeta.meta(obj); var counter = m.peekWatching(keyPath) || 0; if (!counter) { // activate watching first time m.writeWatching(keyPath, 1); chainsFor(obj, m).add(keyPath); } else { m.writeWatching(keyPath, counter + 1); } } function unwatchPath(obj, keyPath, meta) { var m = meta || _emberMetalMeta.meta(obj); var counter = m.peekWatching(keyPath) || 0; if (counter === 1) { m.writeWatching(keyPath, 0); chainsFor(obj, m).remove(keyPath); } else if (counter > 1) { m.writeWatching(keyPath, counter - 1); } } }); enifed('ember-metal/watching', ['exports', 'ember-metal/chains', 'ember-metal/watch_key', 'ember-metal/watch_path', 'ember-metal/path_cache', 'ember-metal/meta'], function (exports, _emberMetalChains, _emberMetalWatch_key, _emberMetalWatch_path, _emberMetalPath_cache, _emberMetalMeta) { /** @module ember-metal */ 'use strict'; exports.isWatching = isWatching; exports.watcherCount = watcherCount; exports.unwatch = unwatch; exports.destroy = destroy; /** Starts watching a property on an object. Whenever the property changes, invokes `Ember.propertyWillChange` and `Ember.propertyDidChange`. This is the primitive used by observers and dependent keys; usually you will never call this method directly but instead use higher level methods like `Ember.addObserver()` @private @method watch @for Ember @param obj @param {String} _keyPath */ function watch(obj, _keyPath, m) { if (!_emberMetalPath_cache.isPath(_keyPath)) { _emberMetalWatch_key.watchKey(obj, _keyPath, m); } else { _emberMetalWatch_path.watchPath(obj, _keyPath, m); } } exports.watch = watch; function isWatching(obj, key) { var meta = _emberMetalMeta.peekMeta(obj); return (meta && meta.peekWatching(key)) > 0; } function watcherCount(obj, key) { var meta = _emberMetalMeta.peekMeta(obj); return meta && meta.peekWatching(key) || 0; } function unwatch(obj, _keyPath, m) { if (!_emberMetalPath_cache.isPath(_keyPath)) { _emberMetalWatch_key.unwatchKey(obj, _keyPath, m); } else { _emberMetalWatch_path.unwatchPath(obj, _keyPath, m); } } var NODE_STACK = []; /** Tears down the meta on an object so that it can be garbage collected. Multiple calls will have no effect. @method destroy @for Ember @param {Object} obj the object to destroy @return {void} @private */ function destroy(obj) { var meta = _emberMetalMeta.peekMeta(obj); var node = undefined, nodes = undefined, key = undefined, nodeObject = undefined; if (meta) { _emberMetalMeta.deleteMeta(obj); // remove chainWatchers to remove circular references that would prevent GC node = meta.readableChains(); if (node) { NODE_STACK.push(node); // process tree while (NODE_STACK.length > 0) { node = NODE_STACK.pop(); // push children nodes = node._chains; if (nodes) { for (key in nodes) { if (nodes[key] !== undefined) { NODE_STACK.push(nodes[key]); } } } // remove chainWatcher in node object if (node._watching) { nodeObject = node._object; if (nodeObject) { _emberMetalChains.removeChainWatcher(nodeObject, node._key, node); } } } } } } }); enifed('ember-metal/weak_map', ['exports', 'ember-metal/utils', 'ember-metal/meta'], function (exports, _emberMetalUtils, _emberMetalMeta) { 'use strict'; exports.default = WeakMap; var id = 0; function UNDEFINED() {} // Returns whether Type(value) is Object according to the terminology in the spec function isObject(value) { return typeof value === 'object' && value !== null || typeof value === 'function'; } /* * @class Ember.WeakMap * @public * @category ember-metal-weakmap * * A partial polyfill for [WeakMap](http://www.ecma-international.org/ecma-262/6.0/#sec-weakmap-objects). * * There is a small but important caveat. This implementation assumes that the * weak map will live longer (in the sense of garbage collection) than all of its * keys, otherwise it is possible to leak the values stored in the weak map. In * practice, most use cases satisfy this limitation which is why it is included * in ember-metal. */ function WeakMap(iterable) { if (!(this instanceof WeakMap)) { throw new TypeError('Constructor WeakMap requires \'new\''); } this._id = _emberMetalUtils.GUID_KEY + id++; if (iterable === null || iterable === undefined) { return; } else if (Array.isArray(iterable)) { for (var i = 0; i < iterable.length; i++) { var _iterable$i = iterable[i]; var key = _iterable$i[0]; var value = _iterable$i[1]; this.set(key, value); } } else { throw new TypeError('The weak map constructor polyfill only supports an array argument'); } } /* * @method get * @param key {Object | Function} * @return {Any} stored value */ WeakMap.prototype.get = function (obj) { if (!isObject(obj)) { return undefined; } var meta = _emberMetalMeta.peekMeta(obj); if (meta) { var map = meta.readableWeak(); if (map) { if (map[this._id] === UNDEFINED) { return undefined; } return map[this._id]; } } }; /* * @method set * @param key {Object | Function} * @param value {Any} * @return {WeakMap} the weak map */ WeakMap.prototype.set = function (obj, value) { if (!isObject(obj)) { throw new TypeError('Invalid value used as weak map key'); } if (value === undefined) { value = UNDEFINED; } _emberMetalMeta.meta(obj).writableWeak()[this._id] = value; return this; }; /* * @method has * @param key {Object | Function} * @return {boolean} if the key exists */ WeakMap.prototype.has = function (obj) { if (!isObject(obj)) { return false; } var meta = _emberMetalMeta.peekMeta(obj); if (meta) { var map = meta.readableWeak(); if (map) { return map[this._id] !== undefined; } } return false; }; /* * @method delete * @param key {Object | Function} * @return {boolean} if the key was deleted */ WeakMap.prototype.delete = function (obj) { if (this.has(obj)) { delete _emberMetalMeta.meta(obj).writableWeak()[this._id]; return true; } else { return false; } }; /* * @method toString * @return {String} */ WeakMap.prototype.toString = function () { return '[object WeakMap]'; }; }); enifed('ember-template-compiler/compat', ['exports', 'ember-metal/core', 'ember-template-compiler/compiler'], function (exports, _emberMetalCore, _emberTemplateCompilerCompiler) { 'use strict'; var EmberHandlebars = _emberMetalCore.default.Handlebars = _emberMetalCore.default.Handlebars || {}; var EmberHTMLBars = _emberMetalCore.default.HTMLBars = _emberMetalCore.default.HTMLBars || {}; var _compiler = _emberTemplateCompilerCompiler.default(); var precompile = _compiler.precompile; var compile = _compiler.compile; var registerPlugin = _compiler.registerPlugin; EmberHTMLBars.precompile = EmberHandlebars.precompile = precompile; EmberHTMLBars.compile = EmberHandlebars.compile = compile; EmberHTMLBars.registerPlugin = registerPlugin; }); // reexports enifed('ember-template-compiler/compat/precompile', ['exports', 'require', 'ember-metal/features'], function (exports, _require, _emberMetalFeatures) { /** @module ember @submodule ember-template-compiler */ 'use strict'; var compile = undefined, compileSpec = undefined, compileOptions = undefined; // Note we don't really want to expose this from main file if (false) { compileOptions = _require.default('ember-glimmer-template-compiler/system/compile-options').default; } else { compileOptions = _require.default('ember-htmlbars-template-compiler/system/compile-options').default; } exports.default = function (string) { if ((!compile || !compileSpec) && _require.has('htmlbars-compiler/compiler')) { var Compiler = _require.default('htmlbars-compiler/compiler'); compile = Compiler.compile; compileSpec = Compiler.compileSpec; } if (!compile || !compileSpec) { throw new Error('Cannot call `precompile` without the template compiler loaded. Please load `ember-template-compiler.js` prior to calling `precompile`.'); } var asObject = arguments[1] === undefined ? true : arguments[1]; var compileFunc = asObject ? compile : compileSpec; return compileFunc(string, compileOptions()); }; }); enifed('ember-template-compiler/compiler', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = pickCompiler; function pickCompiler() { var compiler = undefined; if (false) { compiler = _require.default('ember-glimmer-template-compiler'); } else { compiler = _require.default('ember-htmlbars-template-compiler'); } return compiler; } }); enifed('ember-template-compiler/index', ['exports', 'ember-template-compiler/compat', 'ember-template-compiler/system/bootstrap', 'ember-metal', 'ember-template-compiler/system/precompile', 'ember-template-compiler/system/compile', 'ember-template-compiler/system/register-plugin', 'ember-template-compiler/system/compile-options'], function (exports, _emberTemplateCompilerCompat, _emberTemplateCompilerSystemBootstrap, _emberMetal, _emberTemplateCompilerSystemPrecompile, _emberTemplateCompilerSystemCompile, _emberTemplateCompilerSystemRegisterPlugin, _emberTemplateCompilerSystemCompileOptions) { 'use strict'; exports._Ember = _emberMetal.default; // Is this still needed exports.precompile = _emberTemplateCompilerSystemPrecompile.default; exports.compile = _emberTemplateCompilerSystemCompile.default; exports.registerPlugin = _emberTemplateCompilerSystemRegisterPlugin.default; exports.defaultCompileOptions = _emberTemplateCompilerSystemCompileOptions.default; // used for adding Ember.Handlebars.compile for backwards compat }); // used to bootstrap templates enifed('ember-template-compiler/plugins/assert-reserved-named-arguments', ['exports', 'ember-metal/debug', 'ember-template-compiler/system/calculate-location-display'], function (exports, _emberMetalDebug, _emberTemplateCompilerSystemCalculateLocationDisplay) { 'use strict'; exports.default = AssertReservedNamedArguments; function AssertReservedNamedArguments(options) { this.syntax = null; this.options = options; } AssertReservedNamedArguments.prototype.transform = function AssertReservedNamedArguments_transform(ast) { var moduleName = this.options.moduleName; this.syntax.traverse(ast, { PathExpression: function (node) { if (node.original[0] === '@') { _emberMetalDebug.assert(assertMessage(moduleName, node)); } } }); return ast; }; function assertMessage(moduleName, node) { var path = node.original; var source = _emberTemplateCompilerSystemCalculateLocationDisplay.default(moduleName, node.loc); return '\'' + path + '\' is not a valid path. ' + source; } }); enifed('ember-template-compiler/plugins/deprecate-render-model', ['exports', 'ember-metal/debug', 'ember-template-compiler/system/calculate-location-display'], function (exports, _emberMetalDebug, _emberTemplateCompilerSystemCalculateLocationDisplay) { 'use strict'; exports.default = DeprecateRenderModel; function DeprecateRenderModel(options) { this.syntax = null; this.options = options; } DeprecateRenderModel.prototype.transform = function DeprecateRenderModel_transform(ast) { var moduleName = this.options.moduleName; var walker = new this.syntax.Walker(); walker.visit(ast, function (node) { if (!validate(node)) { return; } each(node.params, function (param) { if (param.type !== 'PathExpression') { return; } _emberMetalDebug.deprecate(deprecationMessage(moduleName, node, param), false, { id: 'ember-template-compiler.deprecate-render-model', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_model-param-in-code-render-code-helper' }); }); }); return ast; }; function validate(node) { return node.type === 'MustacheStatement' && node.path.original === 'render' && node.params.length > 1; } function each(list, callback) { for (var i = 0, l = list.length; i < l; i++) { callback(list[i]); } } function deprecationMessage(moduleName, node, param) { var sourceInformation = _emberTemplateCompilerSystemCalculateLocationDisplay.default(moduleName, node.loc); var componentName = node.params[0].original; var modelName = param.original; var original = '{{render "' + componentName + '" ' + modelName + '}}'; var preferred = '{{' + componentName + ' model=' + modelName + '}}'; return 'Please refactor `' + original + '` to a component and invoke via' + (' `' + preferred + '`. ' + sourceInformation); } }); enifed('ember-template-compiler/plugins/index', ['exports', 'ember-template-compiler/plugins/transform-old-binding-syntax', 'ember-template-compiler/plugins/transform-item-class', 'ember-template-compiler/plugins/transform-angle-bracket-components', 'ember-template-compiler/plugins/transform-input-on-to-onEvent', 'ember-template-compiler/plugins/transform-top-level-components', 'ember-template-compiler/plugins/transform-inline-link-to', 'ember-template-compiler/plugins/transform-old-class-binding-syntax', 'ember-template-compiler/plugins/deprecate-render-model', 'ember-template-compiler/plugins/assert-reserved-named-arguments'], function (exports, _emberTemplateCompilerPluginsTransformOldBindingSyntax, _emberTemplateCompilerPluginsTransformItemClass, _emberTemplateCompilerPluginsTransformAngleBracketComponents, _emberTemplateCompilerPluginsTransformInputOnToOnEvent, _emberTemplateCompilerPluginsTransformTopLevelComponents, _emberTemplateCompilerPluginsTransformInlineLinkTo, _emberTemplateCompilerPluginsTransformOldClassBindingSyntax, _emberTemplateCompilerPluginsDeprecateRenderModel, _emberTemplateCompilerPluginsAssertReservedNamedArguments) { 'use strict'; exports.default = Object.freeze([_emberTemplateCompilerPluginsTransformOldBindingSyntax.default, _emberTemplateCompilerPluginsTransformItemClass.default, _emberTemplateCompilerPluginsTransformAngleBracketComponents.default, _emberTemplateCompilerPluginsTransformInputOnToOnEvent.default, _emberTemplateCompilerPluginsTransformTopLevelComponents.default, _emberTemplateCompilerPluginsTransformInlineLinkTo.default, _emberTemplateCompilerPluginsTransformOldClassBindingSyntax.default, _emberTemplateCompilerPluginsDeprecateRenderModel.default, _emberTemplateCompilerPluginsAssertReservedNamedArguments.default]); }); enifed('ember-template-compiler/plugins/transform-angle-bracket-components', ['exports'], function (exports) { 'use strict'; exports.default = TransformAngleBracketComponents; function TransformAngleBracketComponents() { // set later within HTMLBars to the syntax package this.syntax = null; } /** @private @method transform @param {AST} ast The AST to be transformed. */ TransformAngleBracketComponents.prototype.transform = function TransformAngleBracketComponents_transform(ast) { var walker = new this.syntax.Walker(); walker.visit(ast, function (node) { if (!validate(node)) { return; } node.tag = '<' + node.tag + '>'; }); return ast; }; function validate(node) { return node.type === 'ComponentNode'; } }); enifed('ember-template-compiler/plugins/transform-inline-link-to', ['exports'], function (exports) { 'use strict'; exports.default = TransformInlineLinkTo; function TransformInlineLinkTo(options) { this.options = options; this.syntax = null; } TransformInlineLinkTo.prototype.transform = function TransformInlineLinkTo_transform(ast) { var _syntax = this.syntax; var traverse = _syntax.traverse; var b = _syntax.builders; function buildProgram(content, loc) { return b.program([buildStatement(content, loc)], null, loc); } function buildStatement(content, loc) { switch (content.type) { case 'PathExpression': return b.mustache(content, null, null, null, loc); case 'SubExpression': return b.mustache(content.path, content.params, content.hash, null, loc); // The default case handles literals. default: return b.text('' + content.value, loc); } } function unsafeHtml(expr) { return b.sexpr('-html-safe', [expr]); } traverse(ast, { MustacheStatement: function (node) { if (node.path.original === 'link-to') { var content = node.escaped ? node.params[0] : unsafeHtml(node.params[0]); return b.block('link-to', node.params.slice(1), node.hash, buildProgram(content, node.loc), null, node.loc); } } }); return ast; }; }); enifed('ember-template-compiler/plugins/transform-input-on-to-onEvent', ['exports', 'ember-metal/debug', 'ember-template-compiler/system/calculate-location-display'], function (exports, _emberMetalDebug, _emberTemplateCompilerSystemCalculateLocationDisplay) { 'use strict'; exports.default = TransformInputOnToOnEvent; /** @module ember @submodule ember-htmlbars */ /** An HTMLBars AST transformation that replaces all instances of ```handlebars {{input on="enter" action="doStuff"}} {{input on="key-press" action="doStuff"}} ``` with ```handlebars {{input enter="doStuff"}} {{input key-press="doStuff"}} ``` @private @class TransformInputOnToOnEvent */ function TransformInputOnToOnEvent() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; // set later within HTMLBars to the syntax package this.syntax = null; this.options = options; } /** @private @method transform @param {AST} ast The AST to be transformed. */ TransformInputOnToOnEvent.prototype.transform = function TransformInputOnToOnEvent_transform(ast) { var pluginContext = this; var b = pluginContext.syntax.builders; var walker = new pluginContext.syntax.Walker(); var moduleName = pluginContext.options.moduleName; walker.visit(ast, function (node) { if (pluginContext.validate(node)) { var action = hashPairForKey(node.hash, 'action'); var on = hashPairForKey(node.hash, 'on'); var onEvent = hashPairForKey(node.hash, 'onEvent'); var normalizedOn = on || onEvent; var moduleInfo = _emberTemplateCompilerSystemCalculateLocationDisplay.default(moduleName, node.loc); if (normalizedOn && normalizedOn.value.type !== 'StringLiteral') { _emberMetalDebug.deprecate('Using a dynamic value for \'#{normalizedOn.key}=\' with the \'{{input}}\' helper ' + moduleInfo + 'is deprecated.', false, { id: 'ember-template-compiler.transform-input-on-to-onEvent.dynamic-value', until: '3.0.0' }); normalizedOn.key = 'onEvent'; return; // exit early, as we cannot transform further } removeFromHash(node.hash, normalizedOn); removeFromHash(node.hash, action); if (!action) { _emberMetalDebug.deprecate('Using \'{{input ' + normalizedOn.key + '="' + normalizedOn.value.value + '" ...}}\' without specifying an action ' + moduleInfo + 'will do nothing.', false, { id: 'ember-template-compiler.transform-input-on-to-onEvent.no-action', until: '3.0.0' }); return; // exit early, if no action was available there is nothing to do } var specifiedOn = normalizedOn ? normalizedOn.key + '="' + normalizedOn.value.value + '" ' : ''; if (normalizedOn && normalizedOn.value.value === 'keyPress') { // using `keyPress` in the root of the component will // clobber the keyPress event handler normalizedOn.value.value = 'key-press'; } var expected = (normalizedOn ? normalizedOn.value.value : 'enter') + '="' + action.value.original + '"'; _emberMetalDebug.deprecate('Using \'{{input ' + specifiedOn + 'action="' + action.value.original + '"}}\' ' + moduleInfo + 'is deprecated. Please use \'{{input ' + expected + '}}\' instead.', false, { id: 'ember-template-compiler.transform-input-on-to-onEvent.normalized-on', until: '3.0.0' }); if (!normalizedOn) { normalizedOn = b.pair('onEvent', b.string('enter')); } node.hash.pairs.push(b.pair(normalizedOn.value.value, action.value)); } }); return ast; }; TransformInputOnToOnEvent.prototype.validate = function TransformWithAsToHash_validate(node) { return node.type === 'MustacheStatement' && node.path.original === 'input' && (hashPairForKey(node.hash, 'action') || hashPairForKey(node.hash, 'on') || hashPairForKey(node.hash, 'onEvent')); }; function hashPairForKey(hash, key) { for (var i = 0; i < hash.pairs.length; i++) { var pair = hash.pairs[i]; if (pair.key === key) { return pair; } } return false; } function removeFromHash(hash, pairToRemove) { var newPairs = []; for (var i = 0; i < hash.pairs.length; i++) { var pair = hash.pairs[i]; if (pair !== pairToRemove) { newPairs.push(pair); } } hash.pairs = newPairs; } }); enifed('ember-template-compiler/plugins/transform-item-class', ['exports'], function (exports) { 'use strict'; exports.default = TransformItemClass; function TransformItemClass() { this.syntax = null; } TransformItemClass.prototype.transform = function TransformItemClass_transform(ast) { var b = this.syntax.builders; var walker = new this.syntax.Walker(); walker.visit(ast, function (node) { if (!validate(node)) { return; } for (var i = 0; i < node.hash.pairs.length; i++) { var pair = node.hash.pairs[i]; var key = pair.key; var value = pair.value; if (key !== 'itemClass') { return; } if (value.type === 'StringLiteral') { return; } var propName = value.original; var params = [value]; var sexprParams = [b.string(propName), b.path(propName)]; params.push(b.sexpr(b.string('-normalize-class'), sexprParams)); var sexpr = b.sexpr(b.string('if'), params); pair.value = sexpr; } }); return ast; }; function validate(node) { return (node.type === 'BlockStatement' || node.type === 'MustacheStatement') && node.path.original === 'collection'; } }); enifed('ember-template-compiler/plugins/transform-old-binding-syntax', ['exports', 'ember-metal/debug', 'ember-template-compiler/system/calculate-location-display'], function (exports, _emberMetalDebug, _emberTemplateCompilerSystemCalculateLocationDisplay) { 'use strict'; exports.default = TransformOldBindingSyntax; function TransformOldBindingSyntax(options) { this.syntax = null; this.options = options; } TransformOldBindingSyntax.prototype.transform = function TransformOldBindingSyntax_transform(ast) { var moduleName = this.options.moduleName; var b = this.syntax.builders; var walker = new this.syntax.Walker(); walker.visit(ast, function (node) { if (!validate(node)) { return; } for (var i = 0; i < node.hash.pairs.length; i++) { var pair = node.hash.pairs[i]; var key = pair.key; var value = pair.value; var sourceInformation = _emberTemplateCompilerSystemCalculateLocationDisplay.default(moduleName, pair.loc); if (key === 'classBinding') { return; } _emberMetalDebug.assert('Setting \'attributeBindings\' via template helpers is not allowed ' + sourceInformation, key !== 'attributeBindings'); if (key.substr(-7) === 'Binding') { var newKey = key.slice(0, -7); _emberMetalDebug.deprecate('You\'re using legacy binding syntax: ' + key + '=' + exprToString(value) + ' ' + sourceInformation + '. Please replace with ' + newKey + '=' + value.original, false, { id: 'ember-template-compiler.transform-old-binding-syntax', until: '3.0.0' }); pair.key = newKey; if (value.type === 'StringLiteral') { pair.value = b.path(value.original); } } } }); return ast; }; function validate(node) { return node.type === 'BlockStatement' || node.type === 'MustacheStatement'; } function exprToString(expr) { switch (expr.type) { case 'StringLiteral': return '"' + expr.original + '"'; case 'PathExpression': return expr.original; } } }); enifed('ember-template-compiler/plugins/transform-old-class-binding-syntax', ['exports'], function (exports) { 'use strict'; exports.default = TransformOldClassBindingSyntax; function TransformOldClassBindingSyntax(options) { this.syntax = null; this.options = options; } TransformOldClassBindingSyntax.prototype.transform = function TransformOldClassBindingSyntax_transform(ast) { var b = this.syntax.builders; var walker = new this.syntax.Walker(); walker.visit(ast, function (node) { if (!validate(node)) { return; } var allOfTheMicrosyntaxes = []; var allOfTheMicrosyntaxIndexes = []; var classPair = undefined; each(node.hash.pairs, function (pair, index) { var key = pair.key; if (key === 'classBinding' || key === 'classNameBindings') { allOfTheMicrosyntaxIndexes.push(index); allOfTheMicrosyntaxes.push(pair); } else if (key === 'class') { classPair = pair; } }); if (allOfTheMicrosyntaxes.length === 0) { return; } var classValue = []; if (classPair) { classValue.push(classPair.value); classValue.push(b.string(' ')); } else { classPair = b.pair('class', null); node.hash.pairs.push(classPair); } each(allOfTheMicrosyntaxIndexes, function (index) { node.hash.pairs.splice(index, 1); }); each(allOfTheMicrosyntaxes, function (_ref) { var value = _ref.value; var loc = _ref.loc; var sexprs = []; // TODO: add helpful deprecation when both `classNames` and `classNameBindings` can // be removed. if (value.type === 'StringLiteral') { var microsyntax = parseMicrosyntax(value.original); buildSexprs(microsyntax, sexprs, b); classValue.push.apply(classValue, sexprs); } }); var hash = b.hash(); classPair.value = b.sexpr(b.path('concat'), classValue, hash); }); return ast; }; function buildSexprs(microsyntax, sexprs, b) { for (var i = 0; i < microsyntax.length; i++) { var _microsyntax$i = microsyntax[i]; var propName = _microsyntax$i[0]; var activeClass = _microsyntax$i[1]; var inactiveClass = _microsyntax$i[2]; var sexpr = undefined; // :my-class-name microsyntax for static values if (propName === '') { sexpr = b.string(activeClass); } else { var params = [b.path(propName)]; if (activeClass || activeClass === '') { params.push(b.string(activeClass)); } else { var sexprParams = [b.string(propName), b.path(propName)]; var hash = b.hash(); if (activeClass !== undefined) { hash.pairs.push(b.pair('activeClass', b.string(activeClass))); } if (inactiveClass !== undefined) { hash.pairs.push(b.pair('inactiveClass', b.string(inactiveClass))); } params.push(b.sexpr(b.string('-normalize-class'), sexprParams, hash)); } if (inactiveClass || inactiveClass === '') { params.push(b.string(inactiveClass)); } sexpr = b.sexpr(b.path('if'), params); } sexprs.push(sexpr); sexprs.push(b.string(' ')); } } function validate(node) { return node.type === 'BlockStatement' || node.type === 'MustacheStatement'; } function each(list, callback) { for (var i = 0; i < list.length; i++) { callback(list[i], i); } } function parseMicrosyntax(string) { var segments = string.split(' '); for (var i = 0; i < segments.length; i++) { segments[i] = segments[i].split(':'); } return segments; } }); enifed('ember-template-compiler/plugins/transform-top-level-components', ['exports'], function (exports) { 'use strict'; exports.default = TransformTopLevelComponents; function TransformTopLevelComponents() { // set later within HTMLBars to the syntax package this.syntax = null; } /** @private @method transform @param {AST} The AST to be transformed. */ TransformTopLevelComponents.prototype.transform = function TransformTopLevelComponents_transform(ast) { hasSingleComponentNode(ast, function (component) { component.tag = '@' + component.tag; component.isStatic = true; }); return ast; }; function hasSingleComponentNode(program, componentCallback) { var loc = program.loc; var body = program.body; if (!loc || loc.start.line !== 1 || loc.start.column !== 0) { return; } var lastComponentNode = undefined; var lastIndex = undefined; var nodeCount = 0; for (var i = 0; i < body.length; i++) { var curr = body[i]; // text node with whitespace only if (curr.type === 'TextNode' && /^[\s]*$/.test(curr.chars)) { continue; } // has multiple root elements if we've been here before if (nodeCount++ > 0) { return false; } if (curr.type === 'ComponentNode' || curr.type === 'ElementNode') { lastComponentNode = curr; lastIndex = i; } } if (!lastComponentNode) { return; } if (lastComponentNode.type === 'ComponentNode') { componentCallback(lastComponentNode); } } }); enifed('ember-template-compiler/system/bootstrap', ['exports', 'ember-metal/error', 'ember-template-compiler', 'ember-templates/template_registry'], function (exports, _emberMetalError, _emberTemplateCompiler, _emberTemplatesTemplate_registry) { /** @module ember @submodule ember-templates */ 'use strict'; /** @module ember @submodule ember-templates */ /** Find templates stored in the head tag as script tags and make them available to `Ember.CoreView` in the global `Ember.TEMPLATES` object. Script tags with `text/x-handlebars` will be compiled with Ember's template compiler and are suitable for use as a view's template. @private @method bootstrap @for Ember.HTMLBars @static @param ctx */ function bootstrap() { var context = arguments.length <= 0 || arguments[0] === undefined ? document : arguments[0]; var selector = 'script[type="text/x-handlebars"]'; var elements = context.querySelectorAll(selector); for (var i = 0; i < elements.length; i++) { var script = elements[i]; // Get the name of the script // First look for data-template-name attribute, then fall back to its // id if no name is found. var templateName = script.getAttribute('data-template-name') || script.getAttribute('id') || 'application'; var template = undefined; template = _emberTemplateCompiler.compile(script.innerHTML, { moduleName: templateName }); // Check if template of same name already exists. if (_emberTemplatesTemplate_registry.has(templateName)) { throw new _emberMetalError.default('Template named "' + templateName + '" already exists.'); } // For templates which have a name, we save them and then remove them from the DOM. _emberTemplatesTemplate_registry.set(templateName, template); // Remove script tag from DOM. script.parentNode.removeChild(script); } } exports.default = bootstrap; }); enifed('ember-template-compiler/system/calculate-location-display', ['exports'], function (exports) { 'use strict'; exports.default = calculateLocationDisplay; function calculateLocationDisplay(moduleName, _loc) { var loc = _loc || {}; var _ref = loc.start || {}; var column = _ref.column; var line = _ref.line; var moduleInfo = ''; if (moduleName) { moduleInfo += '\'' + moduleName + '\' '; } if (line !== undefined && column !== undefined) { if (moduleName) { // only prepend @ if the moduleName was present moduleInfo += '@ '; } moduleInfo += 'L' + line + ':C' + column; } if (moduleInfo) { moduleInfo = '(' + moduleInfo + ') '; } return moduleInfo; } }); enifed('ember-template-compiler/system/compile-options', ['exports', 'ember-template-compiler/compiler'], function (exports, _emberTemplateCompilerCompiler) { 'use strict'; var _compiler = _emberTemplateCompilerCompiler.default(); var defaultCompileOptions = _compiler.defaultCompileOptions; exports.default = defaultCompileOptions; }); enifed('ember-template-compiler/system/compile', ['exports', 'ember-template-compiler/compiler', 'ember-template-compiler/system/compile-options', 'ember-metal/assign'], function (exports, _emberTemplateCompilerCompiler, _emberTemplateCompilerSystemCompileOptions, _emberMetalAssign) { /** @module ember @submodule ember-template-compiler */ 'use strict'; /** Uses HTMLBars `compile` function to process a string into a compiled template. This is not present in production builds. @private @method compile @param {String} templateString This is the string to be compiled by HTMLBars. @param {Object} options This is an options hash to augment the compiler options. */ exports.default = function (templateString, options) { var _compiler = _emberTemplateCompilerCompiler.default(); var compile = _compiler.compile; return compile(templateString, _emberMetalAssign.default({}, _emberTemplateCompilerSystemCompileOptions.default(), options)); }; }); enifed('ember-template-compiler/system/precompile', ['exports', 'ember-metal/assign', 'ember-template-compiler/compiler', 'ember-template-compiler/system/compile-options'], function (exports, _emberMetalAssign, _emberTemplateCompilerCompiler, _emberTemplateCompilerSystemCompileOptions) { /** @module ember @submodule ember-template-compiler */ 'use strict'; /** Uses HTMLBars `compile` function to process a string into a compiled template string. The returned string must be passed through `Ember.HTMLBars.template`. This is not present in production builds. @private @method precompile @param {String} templateString This is the string to be compiled by HTMLBars. */ exports.default = function (templateString, options) { var _compiler = _emberTemplateCompilerCompiler.default(); var precompile = _compiler.precompile; return precompile(templateString, _emberMetalAssign.default({}, _emberTemplateCompilerSystemCompileOptions.default(), options)); }; }); enifed('ember-template-compiler/system/register-plugin', ['exports', 'ember-template-compiler/compiler'], function (exports, _emberTemplateCompilerCompiler) { 'use strict'; var _compiler = _emberTemplateCompilerCompiler.default(); var registerPlugin = _compiler.registerPlugin; exports.default = registerPlugin; }); enifed('ember-templates/compat', ['exports', 'ember-metal/core', 'ember-templates/template', 'ember-templates/string', 'ember-runtime/system/string', 'ember-metal/features', 'ember-templates/make-bound-helper'], function (exports, _emberMetalCore, _emberTemplatesTemplate, _emberTemplatesString, _emberRuntimeSystemString, _emberMetalFeatures, _emberTemplatesMakeBoundHelper) { 'use strict'; var EmberHandlebars = _emberMetalCore.default.Handlebars = _emberMetalCore.default.Handlebars || {}; exports.EmberHandlebars = EmberHandlebars; var EmberHTMLBars = _emberMetalCore.default.HTMLBars = _emberMetalCore.default.HTMLBars || {}; exports.EmberHTMLBars = EmberHTMLBars; var EmberHandleBarsUtils = EmberHandlebars.Utils = EmberHandlebars.Utils || {}; exports.EmberHandleBarsUtils = EmberHandleBarsUtils; Object.defineProperty(EmberHandlebars, 'SafeString', { get: _emberTemplatesString.getSafeString }); EmberHTMLBars.template = EmberHandlebars.template = _emberTemplatesTemplate.default; EmberHandleBarsUtils.escapeExpression = _emberTemplatesString.escapeExpression; _emberRuntimeSystemString.default.htmlSafe = _emberTemplatesString.htmlSafe; if (true) { _emberRuntimeSystemString.default.isHTMLSafe = _emberTemplatesString.isHTMLSafe; } EmberHTMLBars.makeBoundHelper = _emberTemplatesMakeBoundHelper.default; }); // reexports enifed('ember-templates/component', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/component').default; } else { return _require.default('ember-htmlbars/component').default; } })(); }); enifed('ember-templates/components/checkbox', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/components/checkbox').default; } else { return _require.default('ember-htmlbars/components/checkbox').default; } })(); }); enifed('ember-templates/components/link-to', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/components/link-to').default; } else { return _require.default('ember-htmlbars/components/link-to').default; } })(); }); enifed('ember-templates/components/text_area', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/components/text_area').default; } else { return _require.default('ember-htmlbars/components/text_area').default; } })(); }); enifed('ember-templates/components/text_field', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/components/text_field').default; } else { return _require.default('ember-htmlbars/components/text_field').default; } })(); }); enifed('ember-templates/helper', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/helper').default; } else { return _require.default('ember-htmlbars/helper').default; } })(); var helper = (function () { if (false) { return _require.default('ember-glimmer/helper').helper; } else { return _require.default('ember-htmlbars/helper').helper; } })(); exports.helper = helper; }); enifed('ember-templates/index', ['exports', 'ember-metal/core', 'ember-templates/template_registry', 'ember-templates/renderer', 'ember-templates/component', 'ember-templates/helper', 'ember-templates/components/checkbox', 'ember-templates/components/text_field', 'ember-templates/components/text_area', 'ember-templates/components/link-to', 'ember-templates/string', 'ember-environment', 'ember-templates/compat'], function (exports, _emberMetalCore, _emberTemplatesTemplate_registry, _emberTemplatesRenderer, _emberTemplatesComponent, _emberTemplatesHelper, _emberTemplatesComponentsCheckbox, _emberTemplatesComponentsText_field, _emberTemplatesComponentsText_area, _emberTemplatesComponentsLinkTo, _emberTemplatesString, _emberEnvironment, _emberTemplatesCompat) { 'use strict'; _emberMetalCore.default._Renderer = _emberTemplatesRenderer.Renderer; _emberMetalCore.default.Component = _emberTemplatesComponent.default; _emberTemplatesHelper.default.helper = _emberTemplatesHelper.helper; _emberMetalCore.default.Helper = _emberTemplatesHelper.default; _emberMetalCore.default.Checkbox = _emberTemplatesComponentsCheckbox.default; _emberMetalCore.default.TextField = _emberTemplatesComponentsText_field.default; _emberMetalCore.default.TextArea = _emberTemplatesComponentsText_area.default; _emberMetalCore.default.LinkComponent = _emberTemplatesComponentsLinkTo.default; if (_emberEnvironment.ENV.EXTEND_PROTOTYPES.String) { String.prototype.htmlSafe = function () { return _emberTemplatesString.htmlSafe(this); }; } /** Global hash of shared templates. This will automatically be populated by the build tools so that you can store your Handlebars templates in separate files that get loaded into JavaScript at buildtime. @property TEMPLATES @for Ember @type Object @private */ Object.defineProperty(_emberMetalCore.default, 'TEMPLATES', { get: _emberTemplatesTemplate_registry.getTemplates, set: _emberTemplatesTemplate_registry.setTemplates, configurable: false, enumerable: false }); exports.default = _emberMetalCore.default; }); // reexports enifed('ember-templates/make-bound-helper', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; exports.default = (function () { if (false) { return _require.default('ember-glimmer/make-bound-helper').default; } else { return _require.default('ember-htmlbars/make-bound-helper').default; } })(); }); enifed('ember-templates/renderer', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; var InteractiveRenderer = (function () { if (false) { return _require.default('ember-glimmer/renderer').InteractiveRenderer; } else { return _require.default('ember-htmlbars/renderer').InteractiveRenderer; } })(); exports.InteractiveRenderer = InteractiveRenderer; var InertRenderer = (function () { if (false) { return _require.default('ember-glimmer/renderer').InertRenderer; } else { return _require.default('ember-htmlbars/renderer').InertRenderer; } })(); exports.InertRenderer = InertRenderer; var Renderer = (function () { if (false) { return _require.default('ember-glimmer/renderer').Renderer; } else { return _require.default('ember-htmlbars/renderer').Renderer; } })(); exports.Renderer = Renderer; }); enifed('ember-templates/string', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; var strings = (function () { if (false) { return _require.default('ember-glimmer/utils/string'); } else { return _require.default('ember-htmlbars/utils/string'); } })(); var SafeString = strings.SafeString; exports.SafeString = SafeString; var escapeExpression = strings.escapeExpression; exports.escapeExpression = escapeExpression; var htmlSafe = strings.htmlSafe; exports.htmlSafe = htmlSafe; var isHTMLSafe = strings.isHTMLSafe; exports.isHTMLSafe = isHTMLSafe; var getSafeString = strings.getSafeString; exports.getSafeString = getSafeString; }); enifed('ember-templates/template', ['exports', 'ember-metal/features', 'require'], function (exports, _emberMetalFeatures, _require) { 'use strict'; var htmlbarsTemplate = undefined, glimmerTemplate = undefined; if (_require.has('ember-htmlbars')) { htmlbarsTemplate = _require.default('ember-htmlbars').template; } if (_require.has('ember-glimmer')) { glimmerTemplate = _require.default('ember-glimmer').template; } var template = false ? glimmerTemplate : htmlbarsTemplate; exports.default = template; }); enifed("ember-templates/template_registry", ["exports"], function (exports) { // STATE within a module is frowned apon, this exists // to support Ember.TEMPLATES but shield ember internals from this legacy // global API. "use strict"; exports.setTemplates = setTemplates; exports.getTemplates = getTemplates; exports.get = get; exports.has = has; exports.set = set; var TEMPLATES = {}; function setTemplates(templates) { TEMPLATES = templates; } function getTemplates() { return TEMPLATES; } function get(name) { if (TEMPLATES.hasOwnProperty(name)) { return TEMPLATES[name]; } } function has(name) { return TEMPLATES.hasOwnProperty(name); } function set(name, template) { return TEMPLATES[name] = template; } }); enifed("ember/features", ["exports"], function (exports) { "use strict"; exports.default = {}; }); enifed("ember/version", ["exports"], function (exports) { "use strict"; exports.default = "2.8.0"; }); enifed("htmlbars-compiler", ["exports", "htmlbars-compiler/compiler"], function (exports, _htmlbarsCompilerCompiler) { "use strict"; exports.compile = _htmlbarsCompilerCompiler.compile; exports.compileSpec = _htmlbarsCompilerCompiler.compileSpec; exports.template = _htmlbarsCompilerCompiler.template; }); enifed("htmlbars-compiler/compiler", ["exports", "htmlbars-syntax/parser", "htmlbars-compiler/template-compiler", "htmlbars-runtime/hooks", "htmlbars-runtime/render"], function (exports, _htmlbarsSyntaxParser, _htmlbarsCompilerTemplateCompiler, _htmlbarsRuntimeHooks, _htmlbarsRuntimeRender) { /*jshint evil:true*/ "use strict"; exports.compileSpec = compileSpec; exports.template = template; exports.compile = compile; /* * Compile a string into a template spec string. The template spec is a string * representation of a template. Usually, you would use compileSpec for * pre-compilation of a template on the server. * * Example usage: * * var templateSpec = compileSpec("Howdy {{name}}"); * // This next step is basically what plain compile does * var template = new Function("return " + templateSpec)(); * * @method compileSpec * @param {String} string An HTMLBars template string * @return {TemplateSpec} A template spec string */ function compileSpec(string, options) { var ast = _htmlbarsSyntaxParser.preprocess(string, options); var compiler = new _htmlbarsCompilerTemplateCompiler.default(options); var program = compiler.compile(ast); return program; } /* * @method template * @param {TemplateSpec} templateSpec A precompiled template * @return {Template} A template spec string */ function template(templateSpec) { return new Function("return " + templateSpec)(); } /* * Compile a string into a template rendering function * * Example usage: * * // Template is the hydration portion of the compiled template * var template = compile("Howdy {{name}}"); * * // Template accepts three arguments: * // * // 1. A context object * // 2. An env object * // 3. A contextualElement (optional, document.body is the default) * // * // The env object *must* have at least these two properties: * // * // 1. `hooks` - Basic hooks for rendering a template * // 2. `dom` - An instance of DOMHelper * // * import {hooks} from 'htmlbars-runtime'; * import {DOMHelper} from 'morph'; * var context = {name: 'whatever'}, * env = {hooks: hooks, dom: new DOMHelper()}, * contextualElement = document.body; * var domFragment = template(context, env, contextualElement); * * @method compile * @param {String} string An HTMLBars template string * @param {Object} options A set of options to provide to the compiler * @return {Template} A function for rendering the template */ function compile(string, options) { return _htmlbarsRuntimeHooks.wrap(template(compileSpec(string, options)), _htmlbarsRuntimeRender.default); } }); enifed("htmlbars-compiler/fragment-javascript-compiler", ["exports", "htmlbars-compiler/utils", "htmlbars-util/quoting"], function (exports, _htmlbarsCompilerUtils, _htmlbarsUtilQuoting) { "use strict"; var svgNamespace = "http://www.w3.org/2000/svg", // http://www.w3.org/html/wg/drafts/html/master/syntax.html#html-integration-point svgHTMLIntegrationPoints = { 'foreignObject': true, 'desc': true, 'title': true }; function FragmentJavaScriptCompiler() { this.source = []; this.depth = -1; } exports.default = FragmentJavaScriptCompiler; FragmentJavaScriptCompiler.prototype.compile = function (opcodes, options) { this.source.length = 0; this.depth = -1; this.indent = options && options.indent || ""; this.namespaceFrameStack = [{ namespace: null, depth: null }]; this.domNamespace = null; this.source.push('function buildFragment(dom) {\n'); _htmlbarsCompilerUtils.processOpcodes(this, opcodes); this.source.push(this.indent + '}'); return this.source.join(''); }; FragmentJavaScriptCompiler.prototype.createFragment = function () { var el = 'el' + ++this.depth; this.source.push(this.indent + ' var ' + el + ' = dom.createDocumentFragment();\n'); }; FragmentJavaScriptCompiler.prototype.createElement = function (tagName) { var el = 'el' + ++this.depth; if (tagName === 'svg') { this.pushNamespaceFrame({ namespace: svgNamespace, depth: this.depth }); } this.ensureNamespace(); this.source.push(this.indent + ' var ' + el + ' = dom.createElement(' + _htmlbarsUtilQuoting.string(tagName) + ');\n'); if (svgHTMLIntegrationPoints[tagName]) { this.pushNamespaceFrame({ namespace: null, depth: this.depth }); } }; FragmentJavaScriptCompiler.prototype.createText = function (str) { var el = 'el' + ++this.depth; this.source.push(this.indent + ' var ' + el + ' = dom.createTextNode(' + _htmlbarsUtilQuoting.string(str) + ');\n'); }; FragmentJavaScriptCompiler.prototype.createComment = function (str) { var el = 'el' + ++this.depth; this.source.push(this.indent + ' var ' + el + ' = dom.createComment(' + _htmlbarsUtilQuoting.string(str) + ');\n'); }; FragmentJavaScriptCompiler.prototype.returnNode = function () { var el = 'el' + this.depth; this.source.push(this.indent + ' return ' + el + ';\n'); }; FragmentJavaScriptCompiler.prototype.setAttribute = function (name, value, namespace) { var el = 'el' + this.depth; if (namespace) { this.source.push(this.indent + ' dom.setAttributeNS(' + el + ',' + _htmlbarsUtilQuoting.string(namespace) + ',' + _htmlbarsUtilQuoting.string(name) + ',' + _htmlbarsUtilQuoting.string(value) + ');\n'); } else { this.source.push(this.indent + ' dom.setAttribute(' + el + ',' + _htmlbarsUtilQuoting.string(name) + ',' + _htmlbarsUtilQuoting.string(value) + ');\n'); } }; FragmentJavaScriptCompiler.prototype.appendChild = function () { if (this.depth === this.getCurrentNamespaceFrame().depth) { this.popNamespaceFrame(); } var child = 'el' + this.depth--; var el = 'el' + this.depth; this.source.push(this.indent + ' dom.appendChild(' + el + ', ' + child + ');\n'); }; FragmentJavaScriptCompiler.prototype.getCurrentNamespaceFrame = function () { return this.namespaceFrameStack[this.namespaceFrameStack.length - 1]; }; FragmentJavaScriptCompiler.prototype.pushNamespaceFrame = function (frame) { this.namespaceFrameStack.push(frame); }; FragmentJavaScriptCompiler.prototype.popNamespaceFrame = function () { return this.namespaceFrameStack.pop(); }; FragmentJavaScriptCompiler.prototype.ensureNamespace = function () { var correctNamespace = this.getCurrentNamespaceFrame().namespace; if (this.domNamespace !== correctNamespace) { this.source.push(this.indent + ' dom.setNamespace(' + (correctNamespace ? _htmlbarsUtilQuoting.string(correctNamespace) : 'null') + ');\n'); this.domNamespace = correctNamespace; } }; }); enifed("htmlbars-compiler/fragment-opcode-compiler", ["exports", "htmlbars-compiler/template-visitor", "htmlbars-compiler/utils", "htmlbars-util", "htmlbars-util/array-utils"], function (exports, _htmlbarsCompilerTemplateVisitor, _htmlbarsCompilerUtils, _htmlbarsUtil, _htmlbarsUtilArrayUtils) { "use strict"; function FragmentOpcodeCompiler() { this.opcodes = []; } exports.default = FragmentOpcodeCompiler; FragmentOpcodeCompiler.prototype.compile = function (ast) { var templateVisitor = new _htmlbarsCompilerTemplateVisitor.default(); templateVisitor.visit(ast); _htmlbarsCompilerUtils.processOpcodes(this, templateVisitor.actions); return this.opcodes; }; FragmentOpcodeCompiler.prototype.opcode = function (type, params) { this.opcodes.push([type, params]); }; FragmentOpcodeCompiler.prototype.text = function (text) { this.opcode('createText', [text.chars]); this.opcode('appendChild'); }; FragmentOpcodeCompiler.prototype.comment = function (comment) { this.opcode('createComment', [comment.value]); this.opcode('appendChild'); }; FragmentOpcodeCompiler.prototype.openElement = function (element) { this.opcode('createElement', [element.tag]); _htmlbarsUtilArrayUtils.forEach(element.attributes, this.attribute, this); }; FragmentOpcodeCompiler.prototype.closeElement = function () { this.opcode('appendChild'); }; FragmentOpcodeCompiler.prototype.startProgram = function () { this.opcodes.length = 0; this.opcode('createFragment'); }; FragmentOpcodeCompiler.prototype.endProgram = function () { this.opcode('returnNode'); }; FragmentOpcodeCompiler.prototype.mustache = function () { this.pushMorphPlaceholderNode(); }; FragmentOpcodeCompiler.prototype.component = function () { this.pushMorphPlaceholderNode(); }; FragmentOpcodeCompiler.prototype.block = function () { this.pushMorphPlaceholderNode(); }; FragmentOpcodeCompiler.prototype.pushMorphPlaceholderNode = function () { this.opcode('createComment', [""]); this.opcode('appendChild'); }; FragmentOpcodeCompiler.prototype.attribute = function (attr) { if (attr.value.type === 'TextNode') { var namespace = _htmlbarsUtil.getAttrNamespace(attr.name); this.opcode('setAttribute', [attr.name, attr.value.chars, namespace]); } }; FragmentOpcodeCompiler.prototype.setNamespace = function (namespace) { this.opcode('setNamespace', [namespace]); }; }); enifed("htmlbars-compiler/hydration-javascript-compiler", ["exports", "htmlbars-compiler/utils", "htmlbars-util/quoting", "htmlbars-util/template-utils"], function (exports, _htmlbarsCompilerUtils, _htmlbarsUtilQuoting, _htmlbarsUtilTemplateUtils) { "use strict"; function HydrationJavaScriptCompiler() { this.stack = []; this.source = []; this.mustaches = []; this.parents = [['fragment']]; this.parentCount = 0; this.morphs = []; this.fragmentProcessing = []; this.hooks = undefined; } exports.default = HydrationJavaScriptCompiler; var prototype = HydrationJavaScriptCompiler.prototype; prototype.compile = function (opcodes, options) { this.stack.length = 0; this.mustaches.length = 0; this.source.length = 0; this.parents.length = 1; this.parents[0] = ['fragment']; this.morphs.length = 0; this.fragmentProcessing.length = 0; this.parentCount = 0; this.indent = options && options.indent || ""; this.hooks = {}; this.hasOpenBoundary = false; this.hasCloseBoundary = false; this.statements = []; this.expressionStack = []; this.locals = []; this.hasOpenBoundary = false; this.hasCloseBoundary = false; _htmlbarsCompilerUtils.processOpcodes(this, opcodes); if (this.hasOpenBoundary) { this.source.unshift(this.indent + " dom.insertBoundary(fragment, 0);\n"); } if (this.hasCloseBoundary) { this.source.unshift(this.indent + " dom.insertBoundary(fragment, null);\n"); } var i, l; var indent = this.indent; var morphs; var result = { createMorphsProgram: '', hydrateMorphsProgram: '', fragmentProcessingProgram: '', statements: this.statements, locals: this.locals, hasMorphs: false }; result.hydrateMorphsProgram = this.source.join(''); if (this.morphs.length) { result.hasMorphs = true; morphs = indent + ' var morphs = new Array(' + this.morphs.length + ');\n'; for (i = 0, l = this.morphs.length; i < l; ++i) { var morph = this.morphs[i]; morphs += indent + ' morphs[' + i + '] = ' + morph + ';\n'; } } if (this.fragmentProcessing.length) { var processing = ""; for (i = 0, l = this.fragmentProcessing.length; i < l; ++i) { processing += this.indent + ' ' + this.fragmentProcessing[i] + '\n'; } result.fragmentProcessingProgram = processing; } var createMorphsProgram; if (result.hasMorphs) { createMorphsProgram = 'function buildRenderNodes(dom, fragment, contextualElement) {\n' + result.fragmentProcessingProgram + morphs; if (this.hasOpenBoundary) { createMorphsProgram += indent + " dom.insertBoundary(fragment, 0);\n"; } if (this.hasCloseBoundary) { createMorphsProgram += indent + " dom.insertBoundary(fragment, null);\n"; } createMorphsProgram += indent + ' return morphs;\n' + indent + '}'; } else { createMorphsProgram = 'function buildRenderNodes() { return []; }'; } result.createMorphsProgram = createMorphsProgram; return result; }; prototype.prepareArray = function (length) { var values = []; for (var i = 0; i < length; i++) { values.push(this.expressionStack.pop()); } this.expressionStack.push(values); }; prototype.prepareObject = function (size) { var pairs = []; for (var i = 0; i < size; i++) { pairs.push(this.expressionStack.pop(), this.expressionStack.pop()); } this.expressionStack.push(pairs); }; prototype.openBoundary = function () { this.hasOpenBoundary = true; }; prototype.closeBoundary = function () { this.hasCloseBoundary = true; }; prototype.pushLiteral = function (value) { this.expressionStack.push(value); }; prototype.pushGetHook = function (path, meta) { this.expressionStack.push(_htmlbarsUtilTemplateUtils.buildStatement('get', path, meta)); }; prototype.pushSexprHook = function (meta) { var statement = _htmlbarsUtilTemplateUtils.buildStatement('subexpr', this.expressionStack.pop(), this.expressionStack.pop(), this.expressionStack.pop(), meta); this.expressionStack.push(statement); }; prototype.pushConcatHook = function () { this.expressionStack.push(_htmlbarsUtilTemplateUtils.buildStatement('concat', this.expressionStack.pop())); }; prototype.printSetHook = function (name) { this.locals.push(name); }; prototype.printBlockHook = function (templateId, inverseId, meta) { this.pushStatement('block', this.expressionStack.pop(), // path this.expressionStack.pop(), // params this.expressionStack.pop(), // hash templateId, inverseId, meta); }; prototype.printInlineHook = function (meta) { var path = this.expressionStack.pop(); var params = this.expressionStack.pop(); var hash = this.expressionStack.pop(); this.pushStatement('inline', path, params, hash, meta); }; prototype.printContentHook = function (meta) { this.pushStatement('content', this.expressionStack.pop(), meta); }; prototype.printComponentHook = function (templateId) { this.pushStatement('component', this.expressionStack.pop(), // path this.expressionStack.pop(), // attrs templateId); }; prototype.printAttributeHook = function () { this.pushStatement('attribute', this.expressionStack.pop(), // name this.expressionStack.pop() // value; ); }; prototype.printElementHook = function (meta) { this.pushStatement('element', this.expressionStack.pop(), // path this.expressionStack.pop(), // params this.expressionStack.pop(), // hash meta); }; prototype.createMorph = function (morphNum, parentPath, startIndex, endIndex, escaped) { var isRoot = parentPath.length === 0; var parent = this.getParent(); var morphMethod = escaped ? 'createMorphAt' : 'createUnsafeMorphAt'; var morph = "dom." + morphMethod + "(" + parent + "," + (startIndex === null ? "-1" : startIndex) + "," + (endIndex === null ? "-1" : endIndex) + (isRoot ? ",contextualElement)" : ")"); this.morphs[morphNum] = morph; }; prototype.createAttrMorph = function (attrMorphNum, elementNum, name, escaped, namespace) { var morphMethod = escaped ? 'createAttrMorph' : 'createUnsafeAttrMorph'; var morph = "dom." + morphMethod + "(element" + elementNum + ", '" + name + (namespace ? "', '" + namespace : '') + "')"; this.morphs[attrMorphNum] = morph; }; prototype.createElementMorph = function (morphNum, elementNum) { var morphMethod = 'createElementMorph'; var morph = "dom." + morphMethod + "(element" + elementNum + ")"; this.morphs[morphNum] = morph; }; prototype.repairClonedNode = function (blankChildTextNodes, isElementChecked) { var parent = this.getParent(), processing = 'if (this.cachedFragment) { dom.repairClonedNode(' + parent + ',' + _htmlbarsUtilQuoting.array(blankChildTextNodes) + (isElementChecked ? ',true' : '') + '); }'; this.fragmentProcessing.push(processing); }; prototype.shareElement = function (elementNum) { var elementNodesName = "element" + elementNum; this.fragmentProcessing.push('var ' + elementNodesName + ' = ' + this.getParent() + ';'); this.parents[this.parents.length - 1] = [elementNodesName]; }; prototype.consumeParent = function (i) { var newParent = this.lastParent().slice(); newParent.push(i); this.parents.push(newParent); }; prototype.popParent = function () { this.parents.pop(); }; prototype.getParent = function () { var last = this.lastParent().slice(); var frag = last.shift(); if (!last.length) { return frag; } return 'dom.childAt(' + frag + ', [' + last.join(', ') + '])'; }; prototype.lastParent = function () { return this.parents[this.parents.length - 1]; }; prototype.pushStatement = function () { this.statements.push(_htmlbarsUtilTemplateUtils.buildStatement.apply(undefined, arguments)); }; }); enifed("htmlbars-compiler/hydration-opcode-compiler", ["exports", "htmlbars-compiler/template-visitor", "htmlbars-compiler/utils", "htmlbars-util", "htmlbars-util/array-utils", "htmlbars-syntax/utils"], function (exports, _htmlbarsCompilerTemplateVisitor, _htmlbarsCompilerUtils, _htmlbarsUtil, _htmlbarsUtilArrayUtils, _htmlbarsSyntaxUtils) { "use strict"; function detectIsElementChecked(element) { for (var i = 0, len = element.attributes.length; i < len; i++) { if (element.attributes[i].name === 'checked') { return true; } } return false; } function HydrationOpcodeCompiler() { this.opcodes = []; this.paths = []; this.templateId = 0; this.currentDOMChildIndex = 0; this.morphs = []; this.morphNum = 0; this.element = null; this.elementNum = -1; } exports.default = HydrationOpcodeCompiler; HydrationOpcodeCompiler.prototype.compile = function (ast) { var templateVisitor = new _htmlbarsCompilerTemplateVisitor.default(); templateVisitor.visit(ast); _htmlbarsCompilerUtils.processOpcodes(this, templateVisitor.actions); return this.opcodes; }; HydrationOpcodeCompiler.prototype.accept = function (node) { this[node.type](node); }; HydrationOpcodeCompiler.prototype.opcode = function (type) { var params = [].slice.call(arguments, 1); this.opcodes.push([type, params]); }; HydrationOpcodeCompiler.prototype.startProgram = function (program, c, blankChildTextNodes) { this.opcodes.length = 0; this.paths.length = 0; this.morphs.length = 0; this.templateId = 0; this.currentDOMChildIndex = -1; this.morphNum = 0; var blockParams = program.blockParams || []; for (var i = 0; i < blockParams.length; i++) { this.opcode('printSetHook', blockParams[i], i); } if (blankChildTextNodes.length > 0) { this.opcode('repairClonedNode', blankChildTextNodes); } }; HydrationOpcodeCompiler.prototype.insertBoundary = function (first) { this.opcode(first ? 'openBoundary' : 'closeBoundary'); }; HydrationOpcodeCompiler.prototype.endProgram = function () { distributeMorphs(this.morphs, this.opcodes); }; HydrationOpcodeCompiler.prototype.text = function () { ++this.currentDOMChildIndex; }; HydrationOpcodeCompiler.prototype.comment = function () { ++this.currentDOMChildIndex; }; HydrationOpcodeCompiler.prototype.openElement = function (element, pos, len, mustacheCount, blankChildTextNodes) { distributeMorphs(this.morphs, this.opcodes); ++this.currentDOMChildIndex; this.element = this.currentDOMChildIndex; this.opcode('consumeParent', this.currentDOMChildIndex); // If our parent reference will be used more than once, cache its reference. if (mustacheCount > 1) { shareElement(this); } var isElementChecked = detectIsElementChecked(element); if (blankChildTextNodes.length > 0 || isElementChecked) { this.opcode('repairClonedNode', blankChildTextNodes, isElementChecked); } this.paths.push(this.currentDOMChildIndex); this.currentDOMChildIndex = -1; _htmlbarsUtilArrayUtils.forEach(element.attributes, this.attribute, this); _htmlbarsUtilArrayUtils.forEach(element.modifiers, this.elementModifier, this); }; HydrationOpcodeCompiler.prototype.closeElement = function () { distributeMorphs(this.morphs, this.opcodes); this.opcode('popParent'); this.currentDOMChildIndex = this.paths.pop(); }; HydrationOpcodeCompiler.prototype.mustache = function (mustache, childIndex, childCount) { this.pushMorphPlaceholderNode(childIndex, childCount); var opcode; if (_htmlbarsSyntaxUtils.isHelper(mustache)) { prepareHash(this, mustache.hash); prepareParams(this, mustache.params); preparePath(this, mustache.path); opcode = 'printInlineHook'; } else { preparePath(this, mustache.path); opcode = 'printContentHook'; } var morphNum = this.morphNum++; var start = this.currentDOMChildIndex; var end = this.currentDOMChildIndex; this.morphs.push([morphNum, this.paths.slice(), start, end, mustache.escaped]); this.opcode(opcode, meta(mustache)); }; function meta(node) { var loc = node.loc; if (!loc) { return []; } var source = loc.source; var start = loc.start; var end = loc.end; return ['loc', [source || null, [start.line, start.column], [end.line, end.column]]]; } HydrationOpcodeCompiler.prototype.block = function (block, childIndex, childCount) { this.pushMorphPlaceholderNode(childIndex, childCount); prepareHash(this, block.hash); prepareParams(this, block.params); preparePath(this, block.path); var morphNum = this.morphNum++; var start = this.currentDOMChildIndex; var end = this.currentDOMChildIndex; this.morphs.push([morphNum, this.paths.slice(), start, end, true]); var templateId = this.templateId++; var inverseId = block.inverse === null ? null : this.templateId++; this.opcode('printBlockHook', templateId, inverseId, meta(block)); }; HydrationOpcodeCompiler.prototype.component = function (component, childIndex, childCount) { this.pushMorphPlaceholderNode(childIndex, childCount, component.isStatic); var program = component.program || {}; var blockParams = program.blockParams || []; var attrs = component.attributes; for (var i = attrs.length - 1; i >= 0; i--) { var name = attrs[i].name; var value = attrs[i].value; // TODO: Introduce context specific AST nodes to avoid switching here. if (value.type === 'TextNode') { this.opcode('pushLiteral', value.chars); } else if (value.type === 'MustacheStatement') { this.accept(_htmlbarsSyntaxUtils.unwrapMustache(value)); } else if (value.type === 'ConcatStatement') { prepareParams(this, value.parts); this.opcode('pushConcatHook', this.morphNum); } this.opcode('pushLiteral', name); } var morphNum = this.morphNum++; var start = this.currentDOMChildIndex; var end = this.currentDOMChildIndex; this.morphs.push([morphNum, this.paths.slice(), start, end, true]); this.opcode('prepareObject', attrs.length); this.opcode('pushLiteral', component.tag); this.opcode('printComponentHook', this.templateId++, blockParams.length, meta(component)); }; HydrationOpcodeCompiler.prototype.attribute = function (attr) { var value = attr.value; var escaped = true; var namespace = _htmlbarsUtil.getAttrNamespace(attr.name); // TODO: Introduce context specific AST nodes to avoid switching here. if (value.type === 'TextNode') { return; } else if (value.type === 'MustacheStatement') { escaped = value.escaped; this.accept(_htmlbarsSyntaxUtils.unwrapMustache(value)); } else if (value.type === 'ConcatStatement') { prepareParams(this, value.parts); this.opcode('pushConcatHook', this.morphNum); } this.opcode('pushLiteral', attr.name); var attrMorphNum = this.morphNum++; if (this.element !== null) { shareElement(this); } this.opcode('createAttrMorph', attrMorphNum, this.elementNum, attr.name, escaped, namespace); this.opcode('printAttributeHook'); }; HydrationOpcodeCompiler.prototype.elementModifier = function (modifier) { prepareHash(this, modifier.hash); prepareParams(this, modifier.params); preparePath(this, modifier.path); // If we have a helper in a node, and this element has not been cached, cache it if (this.element !== null) { shareElement(this); } publishElementMorph(this); this.opcode('printElementHook', meta(modifier)); }; HydrationOpcodeCompiler.prototype.pushMorphPlaceholderNode = function (childIndex, childCount, skipBoundaryNodes) { if (!skipBoundaryNodes) { if (this.paths.length === 0) { if (childIndex === 0) { this.opcode('openBoundary'); } if (childIndex === childCount - 1) { this.opcode('closeBoundary'); } } } this.comment(); }; HydrationOpcodeCompiler.prototype.MustacheStatement = function (mustache) { prepareHash(this, mustache.hash); prepareParams(this, mustache.params); preparePath(this, mustache.path); this.opcode('pushSexprHook', meta(mustache)); }; HydrationOpcodeCompiler.prototype.SubExpression = function (sexpr) { prepareHash(this, sexpr.hash); prepareParams(this, sexpr.params); preparePath(this, sexpr.path); this.opcode('pushSexprHook', meta(sexpr)); }; HydrationOpcodeCompiler.prototype.PathExpression = function (path) { this.opcode('pushGetHook', path.original, meta(path)); }; HydrationOpcodeCompiler.prototype.StringLiteral = function (node) { this.opcode('pushLiteral', node.value); }; HydrationOpcodeCompiler.prototype.BooleanLiteral = function (node) { this.opcode('pushLiteral', node.value); }; HydrationOpcodeCompiler.prototype.NumberLiteral = function (node) { this.opcode('pushLiteral', node.value); }; HydrationOpcodeCompiler.prototype.UndefinedLiteral = function (node) { this.opcode('pushLiteral', node.value); }; HydrationOpcodeCompiler.prototype.NullLiteral = function (node) { this.opcode('pushLiteral', node.value); }; function preparePath(compiler, path) { compiler.opcode('pushLiteral', path.original); } function prepareParams(compiler, params) { for (var i = params.length - 1; i >= 0; i--) { var param = params[i]; compiler[param.type](param); } compiler.opcode('prepareArray', params.length); } function prepareHash(compiler, hash) { var pairs = hash.pairs; for (var i = pairs.length - 1; i >= 0; i--) { var key = pairs[i].key; var value = pairs[i].value; compiler[value.type](value); compiler.opcode('pushLiteral', key); } compiler.opcode('prepareObject', pairs.length); } function shareElement(compiler) { compiler.opcode('shareElement', ++compiler.elementNum); compiler.element = null; // Set element to null so we don't cache it twice } function publishElementMorph(compiler) { var morphNum = compiler.morphNum++; compiler.opcode('createElementMorph', morphNum, compiler.elementNum); } function distributeMorphs(morphs, opcodes) { if (morphs.length === 0) { return; } // Splice morphs after the most recent shareParent/consumeParent. var o; for (o = opcodes.length - 1; o >= 0; --o) { var opcode = opcodes[o][0]; if (opcode === 'shareElement' || opcode === 'consumeParent' || opcode === 'popParent') { break; } } var spliceArgs = [o + 1, 0]; for (var i = 0; i < morphs.length; ++i) { spliceArgs.push(['createMorph', morphs[i].slice()]); } opcodes.splice.apply(opcodes, spliceArgs); morphs.length = 0; } }); enifed('htmlbars-compiler/template-compiler', ['exports', 'htmlbars-compiler/fragment-opcode-compiler', 'htmlbars-compiler/fragment-javascript-compiler', 'htmlbars-compiler/hydration-opcode-compiler', 'htmlbars-compiler/hydration-javascript-compiler', 'htmlbars-compiler/template-visitor', 'htmlbars-compiler/utils', 'htmlbars-util/quoting', 'htmlbars-util/array-utils'], function (exports, _htmlbarsCompilerFragmentOpcodeCompiler, _htmlbarsCompilerFragmentJavascriptCompiler, _htmlbarsCompilerHydrationOpcodeCompiler, _htmlbarsCompilerHydrationJavascriptCompiler, _htmlbarsCompilerTemplateVisitor, _htmlbarsCompilerUtils, _htmlbarsUtilQuoting, _htmlbarsUtilArrayUtils) { 'use strict'; function TemplateCompiler(options) { this.options = options || {}; this.consumerBuildMeta = this.options.buildMeta || function () {}; this.fragmentOpcodeCompiler = new _htmlbarsCompilerFragmentOpcodeCompiler.default(); this.fragmentCompiler = new _htmlbarsCompilerFragmentJavascriptCompiler.default(); this.hydrationOpcodeCompiler = new _htmlbarsCompilerHydrationOpcodeCompiler.default(); this.hydrationCompiler = new _htmlbarsCompilerHydrationJavascriptCompiler.default(); this.templates = []; this.childTemplates = []; } exports.default = TemplateCompiler; TemplateCompiler.prototype.compile = function (ast) { var templateVisitor = new _htmlbarsCompilerTemplateVisitor.default(); templateVisitor.visit(ast); _htmlbarsCompilerUtils.processOpcodes(this, templateVisitor.actions); return this.templates.pop(); }; TemplateCompiler.prototype.startProgram = function (program, childTemplateCount, blankChildTextNodes) { this.fragmentOpcodeCompiler.startProgram(program, childTemplateCount, blankChildTextNodes); this.hydrationOpcodeCompiler.startProgram(program, childTemplateCount, blankChildTextNodes); this.childTemplates.length = 0; while (childTemplateCount--) { this.childTemplates.push(this.templates.pop()); } }; TemplateCompiler.prototype.insertBoundary = function (first) { this.hydrationOpcodeCompiler.insertBoundary(first); }; TemplateCompiler.prototype.getChildTemplateVars = function (indent) { var vars = ''; if (this.childTemplates) { for (var i = 0; i < this.childTemplates.length; i++) { vars += indent + 'var child' + i + ' = ' + this.childTemplates[i] + ';\n'; } } return vars; }; TemplateCompiler.prototype.getHydrationHooks = function (indent, hooks) { var hookVars = []; for (var hook in hooks) { hookVars.push(hook + ' = hooks.' + hook); } if (hookVars.length > 0) { return indent + 'var hooks = env.hooks, ' + hookVars.join(', ') + ';\n'; } else { return ''; } }; TemplateCompiler.prototype.endProgram = function (program, programDepth) { this.fragmentOpcodeCompiler.endProgram(program); this.hydrationOpcodeCompiler.endProgram(program); var indent = _htmlbarsUtilQuoting.repeat(" ", programDepth); var options = { indent: indent + " " }; // function build(dom) { return fragment; } var fragmentProgram = this.fragmentCompiler.compile(this.fragmentOpcodeCompiler.opcodes, options); // function hydrate(fragment) { return mustaches; } var hydrationPrograms = this.hydrationCompiler.compile(this.hydrationOpcodeCompiler.opcodes, options); var blockParams = program.blockParams || []; var templateSignature = 'context, rootNode, env, options'; if (blockParams.length > 0) { templateSignature += ', blockArguments'; } var statements = _htmlbarsUtilArrayUtils.map(hydrationPrograms.statements, function (s) { return indent + ' ' + JSON.stringify(s); }).join(",\n"); var locals = JSON.stringify(hydrationPrograms.locals); var templates = _htmlbarsUtilArrayUtils.map(this.childTemplates, function (_, index) { return 'child' + index; }).join(', '); var template = '(function() {\n' + this.getChildTemplateVars(indent + ' ') + indent + ' return {\n' + this.buildMeta(indent + ' ', program) + indent + ' isEmpty: ' + (program.body.length ? 'false' : 'true') + ',\n' + indent + ' arity: ' + blockParams.length + ',\n' + indent + ' cachedFragment: null,\n' + indent + ' hasRendered: false,\n' + indent + ' buildFragment: ' + fragmentProgram + ',\n' + indent + ' buildRenderNodes: ' + hydrationPrograms.createMorphsProgram + ',\n' + indent + ' statements: [\n' + statements + '\n' + indent + ' ],\n' + indent + ' locals: ' + locals + ',\n' + indent + ' templates: [' + templates + ']\n' + indent + ' };\n' + indent + '}())'; this.templates.push(template); }; TemplateCompiler.prototype.buildMeta = function (indent, program) { var meta = this.consumerBuildMeta(program) || {}; var head = indent + 'meta: '; var stringMeta = JSON.stringify(meta, null, 2).replace(/\n/g, '\n' + indent); var tail = ',\n'; return head + stringMeta + tail; }; TemplateCompiler.prototype.openElement = function (element, i, l, r, c, b) { this.fragmentOpcodeCompiler.openElement(element, i, l, r, c, b); this.hydrationOpcodeCompiler.openElement(element, i, l, r, c, b); }; TemplateCompiler.prototype.closeElement = function (element, i, l, r) { this.fragmentOpcodeCompiler.closeElement(element, i, l, r); this.hydrationOpcodeCompiler.closeElement(element, i, l, r); }; TemplateCompiler.prototype.component = function (component, i, l, s) { this.fragmentOpcodeCompiler.component(component, i, l, s); this.hydrationOpcodeCompiler.component(component, i, l, s); }; TemplateCompiler.prototype.block = function (block, i, l, s) { this.fragmentOpcodeCompiler.block(block, i, l, s); this.hydrationOpcodeCompiler.block(block, i, l, s); }; TemplateCompiler.prototype.text = function (string, i, l, r) { this.fragmentOpcodeCompiler.text(string, i, l, r); this.hydrationOpcodeCompiler.text(string, i, l, r); }; TemplateCompiler.prototype.comment = function (string, i, l, r) { this.fragmentOpcodeCompiler.comment(string, i, l, r); this.hydrationOpcodeCompiler.comment(string, i, l, r); }; TemplateCompiler.prototype.mustache = function (mustache, i, l, s) { this.fragmentOpcodeCompiler.mustache(mustache, i, l, s); this.hydrationOpcodeCompiler.mustache(mustache, i, l, s); }; TemplateCompiler.prototype.setNamespace = function (namespace) { this.fragmentOpcodeCompiler.setNamespace(namespace); }; }); enifed('htmlbars-compiler/template-visitor', ['exports'], function (exports) { 'use strict'; var push = Array.prototype.push; function Frame() { this.parentNode = null; this.children = null; this.childIndex = null; this.childCount = null; this.childTemplateCount = 0; this.mustacheCount = 0; this.actions = []; } /** * Takes in an AST and outputs a list of actions to be consumed * by a compiler. For example, the template * * foo{{bar}}<div>baz</div> * * produces the actions * * [['startProgram', [programNode, 0]], * ['text', [textNode, 0, 3]], * ['mustache', [mustacheNode, 1, 3]], * ['openElement', [elementNode, 2, 3, 0]], * ['text', [textNode, 0, 1]], * ['closeElement', [elementNode, 2, 3], * ['endProgram', [programNode]]] * * This visitor walks the AST depth first and backwards. As * a result the bottom-most child template will appear at the * top of the actions list whereas the root template will appear * at the bottom of the list. For example, * * <div>{{#if}}foo{{else}}bar<b></b>{{/if}}</div> * * produces the actions * * [['startProgram', [programNode, 0]], * ['text', [textNode, 0, 2, 0]], * ['openElement', [elementNode, 1, 2, 0]], * ['closeElement', [elementNode, 1, 2]], * ['endProgram', [programNode]], * ['startProgram', [programNode, 0]], * ['text', [textNode, 0, 1]], * ['endProgram', [programNode]], * ['startProgram', [programNode, 2]], * ['openElement', [elementNode, 0, 1, 1]], * ['block', [blockNode, 0, 1]], * ['closeElement', [elementNode, 0, 1]], * ['endProgram', [programNode]]] * * The state of the traversal is maintained by a stack of frames. * Whenever a node with children is entered (either a ProgramNode * or an ElementNode) a frame is pushed onto the stack. The frame * contains information about the state of the traversal of that * node. For example, * * - index of the current child node being visited * - the number of mustaches contained within its child nodes * - the list of actions generated by its child nodes */ function TemplateVisitor() { this.frameStack = []; this.actions = []; this.programDepth = -1; } // Traversal methods TemplateVisitor.prototype.visit = function (node) { this[node.type](node); }; TemplateVisitor.prototype.Program = function (program) { this.programDepth++; var parentFrame = this.getCurrentFrame(); var programFrame = this.pushFrame(); programFrame.parentNode = program; programFrame.children = program.body; programFrame.childCount = program.body.length; programFrame.blankChildTextNodes = []; programFrame.actions.push(['endProgram', [program, this.programDepth]]); for (var i = program.body.length - 1; i >= 0; i--) { programFrame.childIndex = i; this.visit(program.body[i]); } programFrame.actions.push(['startProgram', [program, programFrame.childTemplateCount, programFrame.blankChildTextNodes.reverse()]]); this.popFrame(); this.programDepth--; // Push the completed template into the global actions list if (parentFrame) { parentFrame.childTemplateCount++; } push.apply(this.actions, programFrame.actions.reverse()); }; TemplateVisitor.prototype.ElementNode = function (element) { var parentFrame = this.getCurrentFrame(); var elementFrame = this.pushFrame(); elementFrame.parentNode = element; elementFrame.children = element.children; elementFrame.childCount = element.children.length; elementFrame.mustacheCount += element.modifiers.length; elementFrame.blankChildTextNodes = []; var actionArgs = [element, parentFrame.childIndex, parentFrame.childCount]; elementFrame.actions.push(['closeElement', actionArgs]); for (var i = element.attributes.length - 1; i >= 0; i--) { this.visit(element.attributes[i]); } for (i = element.children.length - 1; i >= 0; i--) { elementFrame.childIndex = i; this.visit(element.children[i]); } elementFrame.actions.push(['openElement', actionArgs.concat([elementFrame.mustacheCount, elementFrame.blankChildTextNodes.reverse()])]); this.popFrame(); // Propagate the element's frame state to the parent frame if (elementFrame.mustacheCount > 0) { parentFrame.mustacheCount++; } parentFrame.childTemplateCount += elementFrame.childTemplateCount; push.apply(parentFrame.actions, elementFrame.actions); }; TemplateVisitor.prototype.AttrNode = function (attr) { if (attr.value.type !== 'TextNode') { this.getCurrentFrame().mustacheCount++; } }; TemplateVisitor.prototype.TextNode = function (text) { var frame = this.getCurrentFrame(); if (text.chars === '') { frame.blankChildTextNodes.push(domIndexOf(frame.children, text)); } frame.actions.push(['text', [text, frame.childIndex, frame.childCount]]); }; TemplateVisitor.prototype.BlockStatement = function (node) { var frame = this.getCurrentFrame(); frame.mustacheCount++; frame.actions.push(['block', [node, frame.childIndex, frame.childCount]]); if (node.inverse) { this.visit(node.inverse); } if (node.program) { this.visit(node.program); } }; TemplateVisitor.prototype.ComponentNode = function (node) { var frame = this.getCurrentFrame(); frame.mustacheCount++; frame.actions.push(['component', [node, frame.childIndex, frame.childCount]]); if (node.program) { this.visit(node.program); } }; TemplateVisitor.prototype.PartialStatement = function (node) { var frame = this.getCurrentFrame(); frame.mustacheCount++; frame.actions.push(['mustache', [node, frame.childIndex, frame.childCount]]); }; TemplateVisitor.prototype.CommentStatement = function (text) { var frame = this.getCurrentFrame(); frame.actions.push(['comment', [text, frame.childIndex, frame.childCount]]); }; TemplateVisitor.prototype.MustacheStatement = function (mustache) { var frame = this.getCurrentFrame(); frame.mustacheCount++; frame.actions.push(['mustache', [mustache, frame.childIndex, frame.childCount]]); }; // Frame helpers TemplateVisitor.prototype.getCurrentFrame = function () { return this.frameStack[this.frameStack.length - 1]; }; TemplateVisitor.prototype.pushFrame = function () { var frame = new Frame(); this.frameStack.push(frame); return frame; }; TemplateVisitor.prototype.popFrame = function () { return this.frameStack.pop(); }; exports.default = TemplateVisitor; // Returns the index of `domNode` in the `nodes` array, skipping // over any nodes which do not represent DOM nodes. function domIndexOf(nodes, domNode) { var index = -1; for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; if (node.type !== 'TextNode' && node.type !== 'ElementNode') { continue; } else { index++; } if (node === domNode) { return index; } } return -1; } }); enifed("htmlbars-compiler/utils", ["exports"], function (exports) { "use strict"; exports.processOpcodes = processOpcodes; function processOpcodes(compiler, opcodes) { for (var i = 0, l = opcodes.length; i < l; i++) { var method = opcodes[i][0]; var params = opcodes[i][1]; if (params) { compiler[method].apply(compiler, params); } else { compiler[method].call(compiler); } } } }); enifed('htmlbars-runtime', ['exports', 'htmlbars-runtime/hooks', 'htmlbars-runtime/render', 'htmlbars-util/morph-utils', 'htmlbars-util/template-utils'], function (exports, _htmlbarsRuntimeHooks, _htmlbarsRuntimeRender, _htmlbarsUtilMorphUtils, _htmlbarsUtilTemplateUtils) { 'use strict'; var internal = { blockFor: _htmlbarsUtilTemplateUtils.blockFor, manualElement: _htmlbarsRuntimeRender.manualElement, hostBlock: _htmlbarsRuntimeHooks.hostBlock, continueBlock: _htmlbarsRuntimeHooks.continueBlock, hostYieldWithShadowTemplate: _htmlbarsRuntimeHooks.hostYieldWithShadowTemplate, visitChildren: _htmlbarsUtilMorphUtils.visitChildren, validateChildMorphs: _htmlbarsUtilMorphUtils.validateChildMorphs, clearMorph: _htmlbarsUtilTemplateUtils.clearMorph }; exports.hooks = _htmlbarsRuntimeHooks.default; exports.render = _htmlbarsRuntimeRender.default; exports.internal = internal; }); enifed('htmlbars-runtime/expression-visitor', ['exports'], function (exports) { /** # Expression Nodes: These nodes are not directly responsible for any part of the DOM, but are eventually passed to a Statement Node. * get * subexpr * concat */ 'use strict'; exports.acceptParams = acceptParams; exports.acceptHash = acceptHash; function acceptParams(nodes, env, scope) { var array = []; for (var i = 0, l = nodes.length; i < l; i++) { array.push(acceptExpression(nodes[i], env, scope).value); } return array; } function acceptHash(pairs, env, scope) { var object = {}; for (var i = 0, l = pairs.length; i < l; i += 2) { var key = pairs[i]; var value = pairs[i + 1]; object[key] = acceptExpression(value, env, scope).value; } return object; } function acceptExpression(node, env, scope) { var ret = { value: null }; // Primitive literals are unambiguously non-array representations of // themselves. if (Array.isArray(node)) { // if (node.length !== 7) { throw new Error('FIXME: Invalid statement length!'); } ret.value = evaluateNode(node, env, scope); } else { ret.value = node; } return ret; } function evaluateNode(node, env, scope) { switch (node[0]) { // can be used by manualElement case 'value': return node[1]; case 'get': return evaluateGet(node, env, scope); case 'subexpr': return evaluateSubexpr(node, env, scope); case 'concat': return evaluateConcat(node, env, scope); } } function evaluateGet(node, env, scope) { var path = node[1]; return env.hooks.get(env, scope, path); } function evaluateSubexpr(node, env, scope) { var path = node[1]; var rawParams = node[2]; var rawHash = node[3]; var params = acceptParams(rawParams, env, scope); var hash = acceptHash(rawHash, env, scope); return env.hooks.subexpr(env, scope, path, params, hash); } function evaluateConcat(node, env, scope) { var rawParts = node[1]; var parts = acceptParams(rawParts, env, scope); return env.hooks.concat(env, parts); } }); enifed("htmlbars-runtime/hooks", ["exports", "htmlbars-runtime/render", "morph-range/morph-list", "htmlbars-util/object-utils", "htmlbars-util/morph-utils", "htmlbars-util/template-utils"], function (exports, _htmlbarsRuntimeRender, _morphRangeMorphList, _htmlbarsUtilObjectUtils, _htmlbarsUtilMorphUtils, _htmlbarsUtilTemplateUtils) { "use strict"; exports.wrap = wrap; exports.wrapForHelper = wrapForHelper; exports.createScope = createScope; exports.createFreshScope = createFreshScope; exports.bindShadowScope = bindShadowScope; exports.createChildScope = createChildScope; exports.bindSelf = bindSelf; exports.updateSelf = updateSelf; exports.bindLocal = bindLocal; exports.updateLocal = updateLocal; exports.bindBlock = bindBlock; exports.block = block; exports.continueBlock = continueBlock; exports.hostBlock = hostBlock; exports.handleRedirect = handleRedirect; exports.handleKeyword = handleKeyword; exports.linkRenderNode = linkRenderNode; exports.inline = inline; exports.keyword = keyword; exports.invokeHelper = invokeHelper; exports.classify = classify; exports.partial = partial; exports.range = range; exports.element = element; exports.attribute = attribute; exports.subexpr = subexpr; exports.get = get; exports.getRoot = getRoot; exports.getBlock = getBlock; exports.getChild = getChild; exports.getValue = getValue; exports.getCellOrValue = getCellOrValue; exports.component = component; exports.concat = concat; exports.hasHelper = hasHelper; exports.lookupHelper = lookupHelper; exports.bindScope = bindScope; exports.updateScope = updateScope; /** HTMLBars delegates the runtime behavior of a template to hooks provided by the host environment. These hooks explain the lexical environment of a Handlebars template, the internal representation of references, and the interaction between an HTMLBars template and the DOM it is managing. While HTMLBars host hooks have access to all of this internal machinery, templates and helpers have access to the abstraction provided by the host hooks. ## The Lexical Environment The default lexical environment of an HTMLBars template includes: * Any local variables, provided by *block arguments* * The current value of `self` ## Simple Nesting Let's look at a simple template with a nested block: ```hbs <h1>{{title}}</h1> {{#if author}} <p class="byline">{{author}}</p> {{/if}} ``` In this case, the lexical environment at the top-level of the template does not change inside of the `if` block. This is achieved via an implementation of `if` that looks like this: ```js registerHelper('if', function(params) { if (!!params[0]) { return this.yield(); } }); ``` A call to `this.yield` invokes the child template using the current lexical environment. ## Block Arguments It is possible for nested blocks to introduce new local variables: ```hbs {{#count-calls as |i|}} <h1>{{title}}</h1> <p>Called {{i}} times</p> {{/count}} ``` In this example, the child block inherits its surrounding lexical environment, but augments it with a single new variable binding. The implementation of `count-calls` supplies the value of `i`, but does not otherwise alter the environment: ```js var count = 0; registerHelper('count-calls', function() { return this.yield([ ++count ]); }); ``` */ function wrap(template) { if (template === null) { return null; } return { meta: template.meta, arity: template.arity, raw: template, render: function (self, env, options, blockArguments) { var scope = env.hooks.createFreshScope(); var contextualElement = options && options.contextualElement; var renderOptions = new _htmlbarsRuntimeRender.RenderOptions(null, self, blockArguments, contextualElement); return _htmlbarsRuntimeRender.default(template, env, scope, renderOptions); } }; } function wrapForHelper(template, env, scope, morph, renderState, visitor) { if (!template) { return {}; } var yieldArgs = yieldTemplate(template, env, scope, morph, renderState, visitor); return { meta: template.meta, arity: template.arity, 'yield': yieldArgs, // quoted since it's a reserved word, see issue #420 yieldItem: yieldItem(template, env, scope, morph, renderState, visitor), raw: template, render: function (self, blockArguments) { yieldArgs(blockArguments, self); } }; } // Called by a user-land helper to render a template. function yieldTemplate(template, env, parentScope, morph, renderState, visitor) { return function (blockArguments, self) { // Render state is used to track the progress of the helper (since it // may call into us multiple times). As the user-land helper calls // into library code, we track what needs to be cleaned up after the // helper has returned. // // Here, we remember that a template has been yielded and so we do not // need to remove the previous template. (If no template is yielded // this render by the helper, we assume nothing should be shown and // remove any previous rendered templates.) renderState.morphToClear = null; // In this conditional is true, it means that on the previous rendering pass // the helper yielded multiple items via `yieldItem()`, but this time they // are yielding a single template. In that case, we mark the morph list for // cleanup so it is removed from the DOM. if (morph.morphList) { _htmlbarsUtilTemplateUtils.clearMorphList(morph.morphList, morph, env); renderState.morphListToClear = null; } var scope = parentScope; if (morph.lastYielded && isStableTemplate(template, morph.lastYielded)) { return morph.lastResult.revalidateWith(env, undefined, self, blockArguments, visitor); } // Check to make sure that we actually **need** a new scope, and can't // share the parent scope. Note that we need to move this check into // a host hook, because the host's notion of scope may require a new // scope in more cases than the ones we can determine statically. if (self !== undefined || parentScope === null || template.arity) { scope = env.hooks.createChildScope(parentScope); } morph.lastYielded = { self: self, template: template, shadowTemplate: null }; // Render the template that was selected by the helper var renderOptions = new _htmlbarsRuntimeRender.RenderOptions(morph, self, blockArguments); _htmlbarsRuntimeRender.default(template, env, scope, renderOptions); }; } function yieldItem(template, env, parentScope, morph, renderState, visitor) { // Initialize state that tracks multiple items being // yielded in. var currentMorph = null; // Candidate morphs for deletion. var candidates = {}; // Reuse existing MorphList if this is not a first-time // render. var morphList = morph.morphList; if (morphList) { currentMorph = morphList.firstChildMorph; } // Advances the currentMorph pointer to the morph in the previously-rendered // list that matches the yielded key. While doing so, it marks any morphs // that it advances past as candidates for deletion. Assuming those morphs // are not yielded in later, they will be removed in the prune step during // cleanup. // Note that this helper function assumes that the morph being seeked to is // guaranteed to exist in the previous MorphList; if this is called and the // morph does not exist, it will result in an infinite loop function advanceToKey(key) { var seek = currentMorph; while (seek.key !== key) { candidates[seek.key] = seek; seek = seek.nextMorph; } currentMorph = seek.nextMorph; return seek; } return function (_key, blockArguments, self) { if (typeof _key !== 'string') { throw new Error("You must provide a string key when calling `yieldItem`; you provided " + _key); } // At least one item has been yielded, so we do not wholesale // clear the last MorphList but instead apply a prune operation. renderState.morphListToClear = null; morph.lastYielded = null; var morphList, morphMap; if (!morph.morphList) { morph.morphList = new _morphRangeMorphList.default(); morph.morphMap = {}; morph.setMorphList(morph.morphList); } morphList = morph.morphList; morphMap = morph.morphMap; // A map of morphs that have been yielded in on this // rendering pass. Any morphs that do not make it into // this list will be pruned from the MorphList during the cleanup // process. var handledMorphs = renderState.handledMorphs; var key = undefined; if (_key in handledMorphs) { // In this branch we are dealing with a duplicate key. The strategy // is to take the original key and append a counter to it that is // incremented every time the key is reused. In order to greatly // reduce the chance of colliding with another valid key we also add // an extra string "--z8mS2hvDW0A--" to the new key. var collisions = renderState.collisions; if (collisions === undefined) { collisions = renderState.collisions = {}; } var count = collisions[_key] | 0; collisions[_key] = ++count; key = _key + '--z8mS2hvDW0A--' + count; } else { key = _key; } if (currentMorph && currentMorph.key === key) { yieldTemplate(template, env, parentScope, currentMorph, renderState, visitor)(blockArguments, self); currentMorph = currentMorph.nextMorph; handledMorphs[key] = currentMorph; } else if (morphMap[key] !== undefined) { var foundMorph = morphMap[key]; if (key in candidates) { // If we already saw this morph, move it forward to this position morphList.insertBeforeMorph(foundMorph, currentMorph); } else { // Otherwise, move the pointer forward to the existing morph for this key advanceToKey(key); } handledMorphs[foundMorph.key] = foundMorph; yieldTemplate(template, env, parentScope, foundMorph, renderState, visitor)(blockArguments, self); } else { var childMorph = _htmlbarsRuntimeRender.createChildMorph(env.dom, morph); childMorph.key = key; morphMap[key] = handledMorphs[key] = childMorph; morphList.insertBeforeMorph(childMorph, currentMorph); yieldTemplate(template, env, parentScope, childMorph, renderState, visitor)(blockArguments, self); } renderState.morphListToPrune = morphList; morph.childNodes = null; }; } function isStableTemplate(template, lastYielded) { return !lastYielded.shadowTemplate && template === lastYielded.template; } function optionsFor(template, inverse, env, scope, morph, visitor) { // If there was a template yielded last time, set morphToClear so it will be cleared // if no template is yielded on this render. var morphToClear = morph.lastResult ? morph : null; var renderState = new _htmlbarsUtilTemplateUtils.RenderState(morphToClear, morph.morphList || null); return { templates: { template: wrapForHelper(template, env, scope, morph, renderState, visitor), inverse: wrapForHelper(inverse, env, scope, morph, renderState, visitor) }, renderState: renderState }; } function thisFor(options) { return { arity: options.template.arity, 'yield': options.template.yield, // quoted since it's a reserved word, see issue #420 yieldItem: options.template.yieldItem, yieldIn: options.template.yieldIn }; } /** Host Hook: createScope @param {Scope?} parentScope @return Scope Corresponds to entering a new HTMLBars block. This hook is invoked when a block is entered with a new `self` or additional local variables. When invoked for a top-level template, the `parentScope` is `null`, and this hook should return a fresh Scope. When invoked for a child template, the `parentScope` is the scope for the parent environment. Note that the `Scope` is an opaque value that is passed to other host hooks. For example, the `get` hook uses the scope to retrieve a value for a given scope and variable name. */ function createScope(env, parentScope) { if (parentScope) { return env.hooks.createChildScope(parentScope); } else { return env.hooks.createFreshScope(); } } function createFreshScope() { // because `in` checks have unpredictable performance, keep a // separate dictionary to track whether a local was bound. // See `bindLocal` for more information. return { self: null, blocks: {}, locals: {}, localPresent: {} }; } /** Host Hook: bindShadowScope @param {Scope?} parentScope @return Scope Corresponds to rendering a new template into an existing render tree, but with a new top-level lexical scope. This template is called the "shadow root". If a shadow template invokes `{{yield}}`, it will render the block provided to the shadow root in the original lexical scope. ```hbs {{!-- post template --}} <p>{{props.title}}</p> {{yield}} {{!-- blog template --}} {{#post title="Hello world"}} <p>by {{byline}}</p> <article>This is my first post</article> {{/post}} {{#post title="Goodbye world"}} <p>by {{byline}}</p> <article>This is my last post</article> {{/post}} ``` ```js helpers.post = function(params, hash, options) { options.template.yieldIn(postTemplate, { props: hash }); }; blog.render({ byline: "Yehuda Katz" }); ``` Produces: ```html <p>Hello world</p> <p>by Yehuda Katz</p> <article>This is my first post</article> <p>Goodbye world</p> <p>by Yehuda Katz</p> <article>This is my last post</article> ``` In short, `yieldIn` creates a new top-level scope for the provided template and renders it, making the original block available to `{{yield}}` in that template. */ function bindShadowScope(env /*, parentScope, shadowScope */) { return env.hooks.createFreshScope(); } function createChildScope(parent) { var scope = Object.create(parent); scope.locals = Object.create(parent.locals); scope.localPresent = Object.create(parent.localPresent); scope.blocks = Object.create(parent.blocks); return scope; } /** Host Hook: bindSelf @param {Scope} scope @param {any} self Corresponds to entering a template. This hook is invoked when the `self` value for a scope is ready to be bound. The host must ensure that child scopes reflect the change to the `self` in future calls to the `get` hook. */ function bindSelf(env, scope, self) { scope.self = self; } function updateSelf(env, scope, self) { env.hooks.bindSelf(env, scope, self); } /** Host Hook: bindLocal @param {Environment} env @param {Scope} scope @param {String} name @param {any} value Corresponds to entering a template with block arguments. This hook is invoked when a local variable for a scope has been provided. The host must ensure that child scopes reflect the change in future calls to the `get` hook. */ function bindLocal(env, scope, name, value) { scope.localPresent[name] = true; scope.locals[name] = value; } function updateLocal(env, scope, name, value) { env.hooks.bindLocal(env, scope, name, value); } /** Host Hook: bindBlock @param {Environment} env @param {Scope} scope @param {Function} block Corresponds to entering a shadow template that was invoked by a block helper with `yieldIn`. This hook is invoked with an opaque block that will be passed along to the shadow template, and inserted into the shadow template when `{{yield}}` is used. Optionally provide a non-default block name that can be targeted by `{{yield to=blockName}}`. */ function bindBlock(env, scope, block) { var name = arguments.length <= 3 || arguments[3] === undefined ? 'default' : arguments[3]; scope.blocks[name] = block; } /** Host Hook: block @param {RenderNode} renderNode @param {Environment} env @param {Scope} scope @param {String} path @param {Array} params @param {Object} hash @param {Block} block @param {Block} elseBlock Corresponds to: ```hbs {{#helper param1 param2 key1=val1 key2=val2}} {{!-- child template --}} {{/helper}} ``` This host hook is a workhorse of the system. It is invoked whenever a block is encountered, and is responsible for resolving the helper to call, and then invoke it. The helper should be invoked with: - `{Array} params`: the parameters passed to the helper in the template. - `{Object} hash`: an object containing the keys and values passed in the hash position in the template. The values in `params` and `hash` will already be resolved through a previous call to the `get` host hook. The helper should be invoked with a `this` value that is an object with one field: `{Function} yield`: when invoked, this function executes the block with the current scope. It takes an optional array of block parameters. If block parameters are supplied, HTMLBars will invoke the `bindLocal` host hook to bind the supplied values to the block arguments provided by the template. In general, the default implementation of `block` should work for most host environments. It delegates to other host hooks where appropriate, and properly invokes the helper with the appropriate arguments. */ function block(morph, env, scope, path, params, hash, template, inverse, visitor) { if (handleRedirect(morph, env, scope, path, params, hash, template, inverse, visitor)) { return; } continueBlock(morph, env, scope, path, params, hash, template, inverse, visitor); } function continueBlock(morph, env, scope, path, params, hash, template, inverse, visitor) { hostBlock(morph, env, scope, template, inverse, null, visitor, function (options) { var helper = env.hooks.lookupHelper(env, scope, path); return env.hooks.invokeHelper(morph, env, scope, visitor, params, hash, helper, options.templates, thisFor(options.templates)); }); } function hostBlock(morph, env, scope, template, inverse, shadowOptions, visitor, callback) { var options = optionsFor(template, inverse, env, scope, morph, visitor); _htmlbarsUtilTemplateUtils.renderAndCleanup(morph, env, options, shadowOptions, callback); } function handleRedirect(morph, env, scope, path, params, hash, template, inverse, visitor) { if (!path) { return false; } var redirect = env.hooks.classify(env, scope, path); if (redirect) { switch (redirect) { case 'component': env.hooks.component(morph, env, scope, path, params, hash, { default: template, inverse: inverse }, visitor);break; case 'inline': env.hooks.inline(morph, env, scope, path, params, hash, visitor);break; case 'block': env.hooks.block(morph, env, scope, path, params, hash, template, inverse, visitor);break; default: throw new Error("Internal HTMLBars redirection to " + redirect + " not supported"); } return true; } if (handleKeyword(path, morph, env, scope, params, hash, template, inverse, visitor)) { return true; } return false; } function handleKeyword(path, morph, env, scope, params, hash, template, inverse, visitor) { var keyword = env.hooks.keywords[path]; if (!keyword) { return false; } if (typeof keyword === 'function') { return keyword(morph, env, scope, params, hash, template, inverse, visitor); } if (keyword.willRender) { keyword.willRender(morph, env); } var lastState, newState; if (keyword.setupState) { lastState = _htmlbarsUtilObjectUtils.shallowCopy(morph.getState()); newState = morph.setState(keyword.setupState(lastState, env, scope, params, hash)); } if (keyword.childEnv) { // Build the child environment... env = keyword.childEnv(morph.getState(), env); // ..then save off the child env builder on the render node. If the render // node tree is re-rendered and this node is not dirty, the child env // builder will still be invoked so that child dirty render nodes still get // the correct child env. morph.buildChildEnv = keyword.childEnv; } var firstTime = !morph.rendered; if (keyword.isEmpty) { var isEmpty = keyword.isEmpty(morph.getState(), env, scope, params, hash); if (isEmpty) { if (!firstTime) { _htmlbarsUtilTemplateUtils.clearMorph(morph, env, false); } return true; } } if (firstTime) { if (keyword.render) { keyword.render(morph, env, scope, params, hash, template, inverse, visitor); } morph.rendered = true; return true; } var isStable; if (keyword.isStable) { isStable = keyword.isStable(lastState, newState); } else { isStable = stableState(lastState, newState); } if (isStable) { if (keyword.rerender) { var newEnv = keyword.rerender(morph, env, scope, params, hash, template, inverse, visitor); env = newEnv || env; } _htmlbarsUtilMorphUtils.validateChildMorphs(env, morph, visitor); return true; } else { _htmlbarsUtilTemplateUtils.clearMorph(morph, env, false); } // If the node is unstable, re-render from scratch if (keyword.render) { keyword.render(morph, env, scope, params, hash, template, inverse, visitor); morph.rendered = true; return true; } } function stableState(oldState, newState) { if (_htmlbarsUtilObjectUtils.keyLength(oldState) !== _htmlbarsUtilObjectUtils.keyLength(newState)) { return false; } for (var prop in oldState) { if (oldState[prop] !== newState[prop]) { return false; } } return true; } function linkRenderNode() /* morph, env, scope, params, hash */{ return; } /** Host Hook: inline @param {RenderNode} renderNode @param {Environment} env @param {Scope} scope @param {String} path @param {Array} params @param {Hash} hash Corresponds to: ```hbs {{helper param1 param2 key1=val1 key2=val2}} ``` This host hook is similar to the `block` host hook, but it invokes helpers that do not supply an attached block. Like the `block` hook, the helper should be invoked with: - `{Array} params`: the parameters passed to the helper in the template. - `{Object} hash`: an object containing the keys and values passed in the hash position in the template. The values in `params` and `hash` will already be resolved through a previous call to the `get` host hook. In general, the default implementation of `inline` should work for most host environments. It delegates to other host hooks where appropriate, and properly invokes the helper with the appropriate arguments. The default implementation of `inline` also makes `partial` a keyword. Instead of invoking a helper named `partial`, it invokes the `partial` host hook. */ function inline(morph, env, scope, path, params, hash, visitor) { if (handleRedirect(morph, env, scope, path, params, hash, null, null, visitor)) { return; } var value = undefined, hasValue = undefined; if (morph.linkedResult) { value = env.hooks.getValue(morph.linkedResult); hasValue = true; } else { var options = optionsFor(null, null, env, scope, morph); var helper = env.hooks.lookupHelper(env, scope, path); var result = env.hooks.invokeHelper(morph, env, scope, visitor, params, hash, helper, options.templates, thisFor(options.templates)); if (result && result.link) { morph.linkedResult = result.value; _htmlbarsUtilMorphUtils.linkParams(env, scope, morph, '@content-helper', [morph.linkedResult], null); } if (result && 'value' in result) { value = env.hooks.getValue(result.value); hasValue = true; } } if (hasValue) { if (morph.lastValue !== value) { morph.setContent(value); } morph.lastValue = value; } } function keyword(path, morph, env, scope, params, hash, template, inverse, visitor) { handleKeyword(path, morph, env, scope, params, hash, template, inverse, visitor); } function invokeHelper(morph, env, scope, visitor, _params, _hash, helper, templates, context) { var params = normalizeArray(env, _params); var hash = normalizeObject(env, _hash); return { value: helper.call(context, params, hash, templates) }; } function normalizeArray(env, array) { var out = new Array(array.length); for (var i = 0, l = array.length; i < l; i++) { out[i] = env.hooks.getCellOrValue(array[i]); } return out; } function normalizeObject(env, object) { var out = {}; for (var prop in object) { out[prop] = env.hooks.getCellOrValue(object[prop]); } return out; } function classify() /* env, scope, path */{ return null; } var keywords = { partial: function (morph, env, scope, params) { var value = env.hooks.partial(morph, env, scope, params[0]); morph.setContent(value); return true; }, // quoted since it's a reserved word, see issue #420 'yield': function (morph, env, scope, params, hash, template, inverse, visitor) { // the current scope is provided purely for the creation of shadow // scopes; it should not be provided to user code. var to = env.hooks.getValue(hash.to) || 'default'; var block = env.hooks.getBlock(scope, to); if (block) { block.invoke(env, params, hash.self, morph, scope, visitor); } return true; }, hasBlock: function (morph, env, scope, params) { var name = env.hooks.getValue(params[0]) || 'default'; return !!env.hooks.getBlock(scope, name); }, hasBlockParams: function (morph, env, scope, params) { var name = env.hooks.getValue(params[0]) || 'default'; var block = env.hooks.getBlock(scope, name); return !!(block && block.arity); } }; exports.keywords = keywords; /** Host Hook: partial @param {RenderNode} renderNode @param {Environment} env @param {Scope} scope @param {String} path Corresponds to: ```hbs {{partial "location"}} ``` This host hook is invoked by the default implementation of the `inline` hook. This makes `partial` a keyword in an HTMLBars environment using the default `inline` host hook. It is implemented as a host hook so that it can retrieve the named partial out of the `Environment`. Helpers, in contrast, only have access to the values passed in to them, and not to the ambient lexical environment. The host hook should invoke the referenced partial with the ambient `self`. */ function partial(renderNode, env, scope, path) { var template = env.partials[path]; return template.render(scope.self, env, {}).fragment; } /** Host hook: range @param {RenderNode} renderNode @param {Environment} env @param {Scope} scope @param {any} value Corresponds to: ```hbs {{content}} {{{unescaped}}} ``` This hook is responsible for updating a render node that represents a range of content with a value. */ function range(morph, env, scope, path, value, visitor) { if (handleRedirect(morph, env, scope, path, [], {}, null, null, visitor)) { return; } value = env.hooks.getValue(value); if (morph.lastValue !== value) { morph.setContent(value); } morph.lastValue = value; } /** Host hook: element @param {RenderNode} renderNode @param {Environment} env @param {Scope} scope @param {String} path @param {Array} params @param {Hash} hash Corresponds to: ```hbs <div {{bind-attr foo=bar}}></div> ``` This hook is responsible for invoking a helper that modifies an element. Its purpose is largely legacy support for awkward idioms that became common when using the string-based Handlebars engine. Most of the uses of the `element` hook are expected to be superseded by component syntax and the `attribute` hook. */ function element(morph, env, scope, path, params, hash, visitor) { if (handleRedirect(morph, env, scope, path, params, hash, null, null, visitor)) { return; } var helper = env.hooks.lookupHelper(env, scope, path); if (helper) { env.hooks.invokeHelper(null, env, scope, null, params, hash, helper, { element: morph.element }); } } /** Host hook: attribute @param {RenderNode} renderNode @param {Environment} env @param {String} name @param {any} value Corresponds to: ```hbs <div foo={{bar}}></div> ``` This hook is responsible for updating a render node that represents an element's attribute with a value. It receives the name of the attribute as well as an already-resolved value, and should update the render node with the value if appropriate. */ function attribute(morph, env, scope, name, value) { value = env.hooks.getValue(value); if (morph.lastValue !== value) { morph.setContent(value); } morph.lastValue = value; } function subexpr(env, scope, helperName, params, hash) { var helper = env.hooks.lookupHelper(env, scope, helperName); var result = env.hooks.invokeHelper(null, env, scope, null, params, hash, helper, {}); if (result && 'value' in result) { return env.hooks.getValue(result.value); } } /** Host Hook: get @param {Environment} env @param {Scope} scope @param {String} path Corresponds to: ```hbs {{foo.bar}} ^ {{helper foo.bar key=value}} ^ ^ ``` This hook is the "leaf" hook of the system. It is used to resolve a path relative to the current scope. */ function get(env, scope, path) { if (path === '') { return scope.self; } var keys = path.split('.'); var value = env.hooks.getRoot(scope, keys[0])[0]; for (var i = 1; i < keys.length; i++) { if (value) { value = env.hooks.getChild(value, keys[i]); } else { break; } } return value; } function getRoot(scope, key) { if (scope.localPresent[key]) { return [scope.locals[key]]; } else if (scope.self) { return [scope.self[key]]; } else { return [undefined]; } } function getBlock(scope, key) { return scope.blocks[key]; } function getChild(value, key) { return value[key]; } function getValue(reference) { return reference; } function getCellOrValue(reference) { return reference; } function component(morph, env, scope, tagName, params, attrs, templates, visitor) { if (env.hooks.hasHelper(env, scope, tagName)) { return env.hooks.block(morph, env, scope, tagName, params, attrs, templates.default, templates.inverse, visitor); } componentFallback(morph, env, scope, tagName, attrs, templates.default); } function concat(env, params) { var value = ""; for (var i = 0, l = params.length; i < l; i++) { value += env.hooks.getValue(params[i]); } return value; } function componentFallback(morph, env, scope, tagName, attrs, template) { var element = env.dom.createElement(tagName); for (var name in attrs) { element.setAttribute(name, env.hooks.getValue(attrs[name])); } var fragment = _htmlbarsRuntimeRender.default(template, env, scope, {}).fragment; element.appendChild(fragment); morph.setNode(element); } function hasHelper(env, scope, helperName) { return env.helpers[helperName] !== undefined; } function lookupHelper(env, scope, helperName) { return env.helpers[helperName]; } function bindScope() /* env, scope */{ // this function is used to handle host-specified extensions to scope // other than `self`, `locals` and `block`. } function updateScope(env, scope) { env.hooks.bindScope(env, scope); } exports.default = { // fundamental hooks that you will likely want to override bindLocal: bindLocal, bindSelf: bindSelf, bindScope: bindScope, classify: classify, component: component, concat: concat, createFreshScope: createFreshScope, getChild: getChild, getRoot: getRoot, getBlock: getBlock, getValue: getValue, getCellOrValue: getCellOrValue, keywords: keywords, linkRenderNode: linkRenderNode, partial: partial, subexpr: subexpr, // fundamental hooks with good default behavior bindBlock: bindBlock, bindShadowScope: bindShadowScope, updateLocal: updateLocal, updateSelf: updateSelf, updateScope: updateScope, createChildScope: createChildScope, hasHelper: hasHelper, lookupHelper: lookupHelper, invokeHelper: invokeHelper, cleanupRenderNode: null, destroyRenderNode: null, willCleanupTree: null, didCleanupTree: null, willRenderNode: null, didRenderNode: null, // derived hooks attribute: attribute, block: block, createScope: createScope, element: element, get: get, inline: inline, range: range, keyword: keyword }; }); enifed("htmlbars-runtime/morph", ["exports", "morph-range"], function (exports, _morphRange) { "use strict"; var guid = 1; function HTMLBarsMorph(domHelper, contextualElement) { this.super$constructor(domHelper, contextualElement); this._state = undefined; this.ownerNode = null; this.isDirty = false; this.isSubtreeDirty = false; this.lastYielded = null; this.lastResult = null; this.lastValue = null; this.buildChildEnv = null; this.morphList = null; this.morphMap = null; this.key = null; this.linkedParams = null; this.linkedResult = null; this.childNodes = null; this.rendered = false; this.guid = "range" + guid++; this.seen = false; } HTMLBarsMorph.empty = function (domHelper, contextualElement) { var morph = new HTMLBarsMorph(domHelper, contextualElement); morph.clear(); return morph; }; HTMLBarsMorph.create = function (domHelper, contextualElement, node) { var morph = new HTMLBarsMorph(domHelper, contextualElement); morph.setNode(node); return morph; }; HTMLBarsMorph.attach = function (domHelper, contextualElement, firstNode, lastNode) { var morph = new HTMLBarsMorph(domHelper, contextualElement); morph.setRange(firstNode, lastNode); return morph; }; var prototype = HTMLBarsMorph.prototype = Object.create(_morphRange.default.prototype); prototype.constructor = HTMLBarsMorph; prototype.super$constructor = _morphRange.default; prototype.getState = function () { if (!this._state) { this._state = {}; } return this._state; }; prototype.setState = function (newState) { /*jshint -W093 */ return this._state = newState; }; exports.default = HTMLBarsMorph; }); enifed("htmlbars-runtime/node-visitor", ["exports", "htmlbars-util/morph-utils", "htmlbars-runtime/expression-visitor"], function (exports, _htmlbarsUtilMorphUtils, _htmlbarsRuntimeExpressionVisitor) { "use strict"; /** Node classification: # Primary Statement Nodes: These nodes are responsible for a render node that represents a morph-range. * block * inline * content * element * component # Leaf Statement Nodes: This node is responsible for a render node that represents a morph-attr. * attribute */ function linkParamsAndHash(env, scope, morph, path, params, hash) { if (morph.linkedParams) { params = morph.linkedParams.params; hash = morph.linkedParams.hash; } else { params = params && _htmlbarsRuntimeExpressionVisitor.acceptParams(params, env, scope); hash = hash && _htmlbarsRuntimeExpressionVisitor.acceptHash(hash, env, scope); } _htmlbarsUtilMorphUtils.linkParams(env, scope, morph, path, params, hash); return [params, hash]; } var AlwaysDirtyVisitor = { block: function (node, morph, env, scope, template, visitor) { var path = node[1]; var params = node[2]; var hash = node[3]; var templateId = node[4]; var inverseId = node[5]; var paramsAndHash = linkParamsAndHash(env, scope, morph, path, params, hash); morph.isDirty = morph.isSubtreeDirty = false; env.hooks.block(morph, env, scope, path, paramsAndHash[0], paramsAndHash[1], templateId === null ? null : template.templates[templateId], inverseId === null ? null : template.templates[inverseId], visitor); }, inline: function (node, morph, env, scope, visitor) { var path = node[1]; var params = node[2]; var hash = node[3]; var paramsAndHash = linkParamsAndHash(env, scope, morph, path, params, hash); morph.isDirty = morph.isSubtreeDirty = false; env.hooks.inline(morph, env, scope, path, paramsAndHash[0], paramsAndHash[1], visitor); }, content: function (node, morph, env, scope, visitor) { var path = node[1]; morph.isDirty = morph.isSubtreeDirty = false; if (isHelper(env, scope, path)) { env.hooks.inline(morph, env, scope, path, [], {}, visitor); if (morph.linkedResult) { _htmlbarsUtilMorphUtils.linkParams(env, scope, morph, '@content-helper', [morph.linkedResult], null); } return; } var params = undefined; if (morph.linkedParams) { params = morph.linkedParams.params; } else { params = [env.hooks.get(env, scope, path)]; } _htmlbarsUtilMorphUtils.linkParams(env, scope, morph, '@range', params, null); env.hooks.range(morph, env, scope, path, params[0], visitor); }, element: function (node, morph, env, scope, visitor) { var path = node[1]; var params = node[2]; var hash = node[3]; var paramsAndHash = linkParamsAndHash(env, scope, morph, path, params, hash); morph.isDirty = morph.isSubtreeDirty = false; env.hooks.element(morph, env, scope, path, paramsAndHash[0], paramsAndHash[1], visitor); }, attribute: function (node, morph, env, scope) { var name = node[1]; var value = node[2]; var paramsAndHash = linkParamsAndHash(env, scope, morph, '@attribute', [value], null); morph.isDirty = morph.isSubtreeDirty = false; env.hooks.attribute(morph, env, scope, name, paramsAndHash[0][0]); }, component: function (node, morph, env, scope, template, visitor) { var path = node[1]; var attrs = node[2]; var templateId = node[3]; var inverseId = node[4]; var paramsAndHash = linkParamsAndHash(env, scope, morph, path, [], attrs); var templates = { default: template.templates[templateId], inverse: template.templates[inverseId] }; morph.isDirty = morph.isSubtreeDirty = false; env.hooks.component(morph, env, scope, path, paramsAndHash[0], paramsAndHash[1], templates, visitor); }, attributes: function (node, morph, env, scope, parentMorph, visitor) { var template = node[1]; env.hooks.attributes(morph, env, scope, template, parentMorph, visitor); } }; exports.AlwaysDirtyVisitor = AlwaysDirtyVisitor; exports.default = { block: function (node, morph, env, scope, template, visitor) { dirtyCheck(env, morph, visitor, function (visitor) { AlwaysDirtyVisitor.block(node, morph, env, scope, template, visitor); }); }, inline: function (node, morph, env, scope, visitor) { dirtyCheck(env, morph, visitor, function (visitor) { AlwaysDirtyVisitor.inline(node, morph, env, scope, visitor); }); }, content: function (node, morph, env, scope, visitor) { dirtyCheck(env, morph, visitor, function (visitor) { AlwaysDirtyVisitor.content(node, morph, env, scope, visitor); }); }, element: function (node, morph, env, scope, template, visitor) { dirtyCheck(env, morph, visitor, function (visitor) { AlwaysDirtyVisitor.element(node, morph, env, scope, template, visitor); }); }, attribute: function (node, morph, env, scope, template) { dirtyCheck(env, morph, null, function () { AlwaysDirtyVisitor.attribute(node, morph, env, scope, template); }); }, component: function (node, morph, env, scope, template, visitor) { dirtyCheck(env, morph, visitor, function (visitor) { AlwaysDirtyVisitor.component(node, morph, env, scope, template, visitor); }); }, attributes: function (node, morph, env, scope, parentMorph, visitor) { AlwaysDirtyVisitor.attributes(node, morph, env, scope, parentMorph, visitor); } }; function dirtyCheck(_env, morph, visitor, callback) { var isDirty = morph.isDirty; var isSubtreeDirty = morph.isSubtreeDirty; var env = _env; if (isSubtreeDirty) { visitor = AlwaysDirtyVisitor; } if (isDirty || isSubtreeDirty) { callback(visitor); } else { if (morph.buildChildEnv) { env = morph.buildChildEnv(morph.getState(), env); } _htmlbarsUtilMorphUtils.validateChildMorphs(env, morph, visitor); } } function isHelper(env, scope, path) { return env.hooks.keywords[path] !== undefined || env.hooks.hasHelper(env, scope, path); } }); enifed("htmlbars-runtime/render", ["exports", "htmlbars-util/morph-utils", "htmlbars-runtime/node-visitor", "htmlbars-runtime/morph", "htmlbars-util/template-utils", "htmlbars-util/void-tag-names"], function (exports, _htmlbarsUtilMorphUtils, _htmlbarsRuntimeNodeVisitor, _htmlbarsRuntimeMorph, _htmlbarsUtilTemplateUtils, _htmlbarsUtilVoidTagNames) { "use strict"; exports.default = render; exports.RenderOptions = RenderOptions; exports.manualElement = manualElement; exports.attachAttributes = attachAttributes; exports.createChildMorph = createChildMorph; exports.getCachedFragment = getCachedFragment; var svgNamespace = "http://www.w3.org/2000/svg"; function render(template, env, scope, options) { var dom = env.dom; var contextualElement; if (options) { if (options.renderNode) { contextualElement = options.renderNode.contextualElement; } else if (options.contextualElement) { contextualElement = options.contextualElement; } } dom.detectNamespace(contextualElement); var renderResult = RenderResult.build(env, scope, template, options, contextualElement); renderResult.render(); return renderResult; } function RenderOptions(renderNode, self, blockArguments, contextualElement) { this.renderNode = renderNode || null; this.self = self; this.blockArguments = blockArguments || null; this.contextualElement = contextualElement || null; } function RenderResult(env, scope, options, rootNode, ownerNode, nodes, fragment, template, shouldSetContent) { this.root = rootNode; this.fragment = fragment; this.nodes = nodes; this.template = template; this.statements = template.statements.slice(); this.env = env; this.scope = scope; this.shouldSetContent = shouldSetContent; if (options.self !== undefined) { this.bindSelf(options.self); } if (options.blockArguments !== undefined) { this.bindLocals(options.blockArguments); } this.initializeNodes(ownerNode); } RenderResult.build = function (env, scope, template, options, contextualElement) { var dom = env.dom; var fragment = getCachedFragment(template, env); var nodes = template.buildRenderNodes(dom, fragment, contextualElement); var rootNode, ownerNode, shouldSetContent; if (options && options.renderNode) { rootNode = options.renderNode; ownerNode = rootNode.ownerNode; shouldSetContent = true; } else { rootNode = dom.createMorph(null, fragment.firstChild, fragment.lastChild, contextualElement); ownerNode = rootNode; rootNode.ownerNode = ownerNode; shouldSetContent = false; } if (rootNode.childNodes) { _htmlbarsUtilMorphUtils.visitChildren(rootNode.childNodes, function (node) { _htmlbarsUtilTemplateUtils.clearMorph(node, env, true); }); } rootNode.childNodes = nodes; return new RenderResult(env, scope, options, rootNode, ownerNode, nodes, fragment, template, shouldSetContent); }; function manualElement(tagName, attributes, _isEmpty) { var statements = []; for (var key in attributes) { if (typeof attributes[key] === 'string') { continue; } statements.push(_htmlbarsUtilTemplateUtils.buildStatement("attribute", key, attributes[key])); } var isEmpty = _isEmpty || _htmlbarsUtilVoidTagNames.default[tagName]; if (!isEmpty) { statements.push(_htmlbarsUtilTemplateUtils.buildStatement('content', 'yield')); } var template = { arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); if (tagName === 'svg') { dom.setNamespace(svgNamespace); } var el1 = dom.createElement(tagName); for (var key in attributes) { if (typeof attributes[key] !== 'string') { continue; } dom.setAttribute(el1, key, attributes[key]); } if (!isEmpty) { var el2 = dom.createComment(""); dom.appendChild(el1, el2); } dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment) { var element = dom.childAt(fragment, [0]); var morphs = []; for (var key in attributes) { if (typeof attributes[key] === 'string') { continue; } morphs.push(dom.createAttrMorph(element, key)); } if (!isEmpty) { morphs.push(dom.createMorphAt(element, 0, 0)); } return morphs; }, statements: statements, locals: [], templates: [] }; return template; } function attachAttributes(attributes) { var statements = []; for (var key in attributes) { if (typeof attributes[key] === 'string') { continue; } statements.push(_htmlbarsUtilTemplateUtils.buildStatement("attribute", key, attributes[key])); } var template = { arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = this.element; if (el0.namespaceURI === "http://www.w3.org/2000/svg") { dom.setNamespace(svgNamespace); } for (var key in attributes) { if (typeof attributes[key] !== 'string') { continue; } dom.setAttribute(el0, key, attributes[key]); } return el0; }, buildRenderNodes: function buildRenderNodes(dom) { var element = this.element; var morphs = []; for (var key in attributes) { if (typeof attributes[key] === 'string') { continue; } morphs.push(dom.createAttrMorph(element, key)); } return morphs; }, statements: statements, locals: [], templates: [], element: null }; return template; } RenderResult.prototype.initializeNodes = function (ownerNode) { var childNodes = this.root.childNodes; for (var i = 0, l = childNodes.length; i < l; i++) { childNodes[i].ownerNode = ownerNode; } }; RenderResult.prototype.render = function () { this.root.lastResult = this; this.root.rendered = true; this.populateNodes(_htmlbarsRuntimeNodeVisitor.AlwaysDirtyVisitor); if (this.shouldSetContent && this.root.setContent) { this.root.setContent(this.fragment); } }; RenderResult.prototype.dirty = function () { _htmlbarsUtilMorphUtils.visitChildren([this.root], function (node) { node.isDirty = true; }); }; RenderResult.prototype.revalidate = function (env, self, blockArguments, scope) { this.revalidateWith(env, scope, self, blockArguments, _htmlbarsRuntimeNodeVisitor.default); }; RenderResult.prototype.rerender = function (env, self, blockArguments, scope) { this.revalidateWith(env, scope, self, blockArguments, _htmlbarsRuntimeNodeVisitor.AlwaysDirtyVisitor); }; RenderResult.prototype.revalidateWith = function (env, scope, self, blockArguments, visitor) { if (env !== undefined) { this.env = env; } if (scope !== undefined) { this.scope = scope; } this.updateScope(); if (self !== undefined) { this.updateSelf(self); } if (blockArguments !== undefined) { this.updateLocals(blockArguments); } this.populateNodes(visitor); }; RenderResult.prototype.destroy = function () { var rootNode = this.root; _htmlbarsUtilTemplateUtils.clearMorph(rootNode, this.env, true); }; RenderResult.prototype.populateNodes = function (visitor) { var env = this.env; var scope = this.scope; var template = this.template; var nodes = this.nodes; var statements = this.statements; var i, l; for (i = 0, l = statements.length; i < l; i++) { var statement = statements[i]; var morph = nodes[i]; if (env.hooks.willRenderNode) { env.hooks.willRenderNode(morph, env, scope); } switch (statement[0]) { case 'block': visitor.block(statement, morph, env, scope, template, visitor);break; case 'inline': visitor.inline(statement, morph, env, scope, visitor);break; case 'content': visitor.content(statement, morph, env, scope, visitor);break; case 'element': visitor.element(statement, morph, env, scope, template, visitor);break; case 'attribute': visitor.attribute(statement, morph, env, scope);break; case 'component': visitor.component(statement, morph, env, scope, template, visitor);break; } if (env.hooks.didRenderNode) { env.hooks.didRenderNode(morph, env, scope); } } }; RenderResult.prototype.bindScope = function () { this.env.hooks.bindScope(this.env, this.scope); }; RenderResult.prototype.updateScope = function () { this.env.hooks.updateScope(this.env, this.scope); }; RenderResult.prototype.bindSelf = function (self) { this.env.hooks.bindSelf(this.env, this.scope, self); }; RenderResult.prototype.updateSelf = function (self) { this.env.hooks.updateSelf(this.env, this.scope, self); }; RenderResult.prototype.bindLocals = function (blockArguments) { var localNames = this.template.locals; for (var i = 0, l = localNames.length; i < l; i++) { this.env.hooks.bindLocal(this.env, this.scope, localNames[i], blockArguments[i]); } }; RenderResult.prototype.updateLocals = function (blockArguments) { var localNames = this.template.locals; for (var i = 0, l = localNames.length; i < l; i++) { this.env.hooks.updateLocal(this.env, this.scope, localNames[i], blockArguments[i]); } }; function initializeNode(node, owner) { node.ownerNode = owner; } function createChildMorph(dom, parentMorph, contextualElement) { var morph = _htmlbarsRuntimeMorph.default.empty(dom, contextualElement || parentMorph.contextualElement); initializeNode(morph, parentMorph.ownerNode); return morph; } function getCachedFragment(template, env) { var dom = env.dom, fragment; if (env.useFragmentCache && dom.canClone) { if (template.cachedFragment === null) { fragment = template.buildFragment(dom); if (template.hasRendered) { template.cachedFragment = fragment; } else { template.hasRendered = true; } } if (template.cachedFragment) { fragment = dom.cloneNode(template.cachedFragment, true); } } else if (!fragment) { fragment = template.buildFragment(dom); } return fragment; } }); enifed("htmlbars-syntax", ["exports", "htmlbars-syntax/builders", "htmlbars-syntax/parser", "htmlbars-syntax/generation/print", "htmlbars-syntax/traversal/traverse", "htmlbars-syntax/traversal/walker"], function (exports, _htmlbarsSyntaxBuilders, _htmlbarsSyntaxParser, _htmlbarsSyntaxGenerationPrint, _htmlbarsSyntaxTraversalTraverse, _htmlbarsSyntaxTraversalWalker) { "use strict"; exports.builders = _htmlbarsSyntaxBuilders.default; exports.parse = _htmlbarsSyntaxParser.default; exports.print = _htmlbarsSyntaxGenerationPrint.default; exports.traverse = _htmlbarsSyntaxTraversalTraverse.default; exports.Walker = _htmlbarsSyntaxTraversalWalker.default; }); enifed("htmlbars-syntax/builders", ["exports"], function (exports) { // Statements "use strict"; exports.buildMustache = buildMustache; exports.buildBlock = buildBlock; exports.buildElementModifier = buildElementModifier; exports.buildPartial = buildPartial; exports.buildComment = buildComment; exports.buildConcat = buildConcat; exports.buildElement = buildElement; exports.buildComponent = buildComponent; exports.buildAttr = buildAttr; exports.buildText = buildText; exports.buildSexpr = buildSexpr; exports.buildPath = buildPath; exports.buildString = buildString; exports.buildBoolean = buildBoolean; exports.buildNumber = buildNumber; exports.buildNull = buildNull; exports.buildUndefined = buildUndefined; exports.buildHash = buildHash; exports.buildPair = buildPair; exports.buildProgram = buildProgram; function buildMustache(path, params, hash, raw, loc) { return { type: "MustacheStatement", path: buildPath(path), params: params || [], hash: hash || buildHash([]), escaped: !raw, loc: buildLoc(loc) }; } function buildBlock(path, params, hash, program, inverse, loc) { return { type: "BlockStatement", path: buildPath(path), params: params || [], hash: hash || buildHash([]), program: program || null, inverse: inverse || null, loc: buildLoc(loc) }; } function buildElementModifier(path, params, hash, loc) { return { type: "ElementModifierStatement", path: buildPath(path), params: params || [], hash: hash || buildHash([]), loc: buildLoc(loc) }; } function buildPartial(name, params, hash, indent) { return { type: "PartialStatement", name: name, params: params || [], hash: hash || buildHash([]), indent: indent }; } function buildComment(value) { return { type: "CommentStatement", value: value }; } function buildConcat(parts) { return { type: "ConcatStatement", parts: parts || [] }; } // Nodes function buildElement(tag, attributes, modifiers, children, loc) { return { type: "ElementNode", tag: tag || "", attributes: attributes || [], modifiers: modifiers || [], children: children || [], loc: buildLoc(loc) }; } function buildComponent(tag, attributes, program, loc) { return { type: "ComponentNode", tag: tag, attributes: attributes, program: program, loc: buildLoc(loc), // this should be true only if this component node is guaranteed // to produce start and end points that can never change after the // initial render, regardless of changes to dynamic inputs. If // a component represents a "fragment" (any number of top-level nodes), // this will usually not be true. isStatic: false }; } function buildAttr(name, value, loc) { return { type: "AttrNode", name: name, value: value, loc: buildLoc(loc) }; } function buildText(chars, loc) { return { type: "TextNode", chars: chars || "", loc: buildLoc(loc) }; } // Expressions function buildSexpr(path, params, hash) { return { type: "SubExpression", path: buildPath(path), params: params || [], hash: hash || buildHash([]) }; } function buildPath(original) { if (typeof original === 'string') { return { type: "PathExpression", original: original, parts: original.split('.') }; } else { return original; } } function buildString(value) { return { type: "StringLiteral", value: value, original: value }; } function buildBoolean(value) { return { type: "BooleanLiteral", value: value, original: value }; } function buildNumber(value) { return { type: "NumberLiteral", value: value, original: value }; } function buildNull() { return { type: "NullLiteral", value: null, original: null }; } function buildUndefined() { return { type: "UndefinedLiteral", value: undefined, original: undefined }; } // Miscellaneous function buildHash(pairs) { return { type: "Hash", pairs: pairs || [] }; } function buildPair(key, value) { return { type: "HashPair", key: key, value: value }; } function buildProgram(body, blockParams, loc) { return { type: "Program", body: body || [], blockParams: blockParams || [], loc: buildLoc(loc) }; } function buildSource(source) { return source || null; } function buildPosition(line, column) { return { line: typeof line === 'number' ? line : null, column: typeof column === 'number' ? column : null }; } function buildLoc(startLine, startColumn, endLine, endColumn, source) { if (arguments.length === 1) { var loc = startLine; if (typeof loc === 'object') { return { source: buildSource(loc.source), start: buildPosition(loc.start.line, loc.start.column), end: buildPosition(loc.end.line, loc.end.column) }; } else { return null; } } else { return { source: buildSource(source), start: buildPosition(startLine, startColumn), end: buildPosition(endLine, endColumn) }; } } exports.default = { mustache: buildMustache, block: buildBlock, partial: buildPartial, comment: buildComment, element: buildElement, elementModifier: buildElementModifier, component: buildComponent, attr: buildAttr, text: buildText, sexpr: buildSexpr, path: buildPath, string: buildString, boolean: buildBoolean, number: buildNumber, undefined: buildUndefined, null: buildNull, concat: buildConcat, hash: buildHash, pair: buildPair, program: buildProgram, loc: buildLoc, pos: buildPosition }; }); enifed('htmlbars-syntax/generation/print', ['exports'], function (exports) { 'use strict'; exports.default = build; function build(ast) { if (!ast) { return ''; } var output = []; switch (ast.type) { case 'Program': { var chainBlock = ast.chained && ast.body[0]; if (chainBlock) { chainBlock.chained = true; } var body = buildEach(ast.body).join(''); output.push(body); } break; case 'ElementNode': output.push('<', ast.tag); if (ast.attributes.length) { output.push(' ', buildEach(ast.attributes).join(' ')); } if (ast.modifiers.length) { output.push(' ', buildEach(ast.modifiers).join(' ')); } output.push('>'); output.push.apply(output, buildEach(ast.children)); output.push('</', ast.tag, '>'); break; case 'AttrNode': output.push(ast.name, '='); var value = build(ast.value); if (ast.value.type === 'TextNode') { output.push('"', value, '"'); } else { output.push(value); } break; case 'ConcatStatement': output.push('"'); ast.parts.forEach(function (node) { if (node.type === 'StringLiteral') { output.push(node.original); } else { output.push(build(node)); } }); output.push('"'); break; case 'TextNode': output.push(ast.chars); break; case 'MustacheStatement': { output.push(compactJoin(['{{', pathParams(ast), '}}'])); } break; case 'ElementModifierStatement': { output.push(compactJoin(['{{', pathParams(ast), '}}'])); } break; case 'PathExpression': output.push(ast.original); break; case 'SubExpression': { output.push('(', pathParams(ast), ')'); } break; case 'BooleanLiteral': output.push(ast.value ? 'true' : false); break; case 'BlockStatement': { var lines = []; if (ast.chained) { lines.push(['{{else ', pathParams(ast), '}}'].join('')); } else { lines.push(openBlock(ast)); } lines.push(build(ast.program)); if (ast.inverse) { if (!ast.inverse.chained) { lines.push('{{else}}'); } lines.push(build(ast.inverse)); } if (!ast.chained) { lines.push(closeBlock(ast)); } output.push(lines.join('')); } break; case 'PartialStatement': { output.push(compactJoin(['{{>', pathParams(ast), '}}'])); } break; case 'CommentStatement': { output.push(compactJoin(['<!--', ast.value, '-->'])); } break; case 'StringLiteral': { output.push('"' + ast.value + '"'); } break; case 'NumberLiteral': { output.push(ast.value); } break; case 'UndefinedLiteral': { output.push('undefined'); } break; case 'NullLiteral': { output.push('null'); } break; case 'Hash': { output.push(ast.pairs.map(function (pair) { return build(pair); }).join(' ')); } break; case 'HashPair': { output.push(ast.key + '=' + build(ast.value)); } break; } return output.join(''); } function compact(array) { var newArray = []; array.forEach(function (a) { if (typeof a !== 'undefined' && a !== null && a !== '') { newArray.push(a); } }); return newArray; } function buildEach(asts) { var output = []; asts.forEach(function (node) { output.push(build(node)); }); return output; } function pathParams(ast) { var name = build(ast.name); var path = build(ast.path); var params = buildEach(ast.params).join(' '); var hash = build(ast.hash); return compactJoin([name, path, params, hash], ' '); } function compactJoin(array, delimiter) { return compact(array).join(delimiter || ''); } function blockParams(block) { var params = block.program.blockParams; if (params.length) { return ' as |' + params.join(',') + '|'; } } function openBlock(block) { return ['{{#', pathParams(block), blockParams(block), '}}'].join(''); } function closeBlock(block) { return ['{{/', build(block.path), '}}'].join(''); } }); enifed('htmlbars-syntax/handlebars/compiler/ast', ['exports'], function (exports) { 'use strict'; var AST = { Program: function (statements, blockParams, strip, locInfo) { this.loc = locInfo; this.type = 'Program'; this.body = statements; this.blockParams = blockParams; this.strip = strip; }, MustacheStatement: function (path, params, hash, escaped, strip, locInfo) { this.loc = locInfo; this.type = 'MustacheStatement'; this.path = path; this.params = params || []; this.hash = hash; this.escaped = escaped; this.strip = strip; }, BlockStatement: function (path, params, hash, program, inverse, openStrip, inverseStrip, closeStrip, locInfo) { this.loc = locInfo; this.type = 'BlockStatement'; this.path = path; this.params = params || []; this.hash = hash; this.program = program; this.inverse = inverse; this.openStrip = openStrip; this.inverseStrip = inverseStrip; this.closeStrip = closeStrip; }, PartialStatement: function (name, params, hash, strip, locInfo) { this.loc = locInfo; this.type = 'PartialStatement'; this.name = name; this.params = params || []; this.hash = hash; this.indent = ''; this.strip = strip; }, ContentStatement: function (string, locInfo) { this.loc = locInfo; this.type = 'ContentStatement'; this.original = this.value = string; }, CommentStatement: function (comment, strip, locInfo) { this.loc = locInfo; this.type = 'CommentStatement'; this.value = comment; this.strip = strip; }, SubExpression: function (path, params, hash, locInfo) { this.loc = locInfo; this.type = 'SubExpression'; this.path = path; this.params = params || []; this.hash = hash; }, PathExpression: function (data, depth, parts, original, locInfo) { this.loc = locInfo; this.type = 'PathExpression'; this.data = data; this.original = original; this.parts = parts; this.depth = depth; }, StringLiteral: function (string, locInfo) { this.loc = locInfo; this.type = 'StringLiteral'; this.original = this.value = string; }, NumberLiteral: function (number, locInfo) { this.loc = locInfo; this.type = 'NumberLiteral'; this.original = this.value = Number(number); }, BooleanLiteral: function (bool, locInfo) { this.loc = locInfo; this.type = 'BooleanLiteral'; this.original = this.value = bool === 'true'; }, UndefinedLiteral: function (locInfo) { this.loc = locInfo; this.type = 'UndefinedLiteral'; this.original = this.value = undefined; }, NullLiteral: function (locInfo) { this.loc = locInfo; this.type = 'NullLiteral'; this.original = this.value = null; }, Hash: function (pairs, locInfo) { this.loc = locInfo; this.type = 'Hash'; this.pairs = pairs; }, HashPair: function (key, value, locInfo) { this.loc = locInfo; this.type = 'HashPair'; this.key = key; this.value = value; }, // Public API used to evaluate derived attributes regarding AST nodes helpers: { // a mustache is definitely a helper if: // * it is an eligible helper, and // * it has at least one parameter or hash segment helperExpression: function (node) { return !!(node.type === 'SubExpression' || node.params.length || node.hash); }, scopedId: function (path) { return (/^\.|this\b/.test(path.original) ); }, // an ID is simple if it only has one part, and that part is not // `..` or `this`. simpleId: function (path) { return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth; } } }; // Must be exported as an object rather than the root of the module as the jison lexer // must modify the object to operate properly. exports.default = AST; }); enifed('htmlbars-syntax/handlebars/compiler/base', ['exports', 'htmlbars-syntax/handlebars/compiler/parser', 'htmlbars-syntax/handlebars/compiler/ast', 'htmlbars-syntax/handlebars/compiler/whitespace-control', 'htmlbars-syntax/handlebars/compiler/helpers', 'htmlbars-syntax/handlebars/utils'], function (exports, _htmlbarsSyntaxHandlebarsCompilerParser, _htmlbarsSyntaxHandlebarsCompilerAst, _htmlbarsSyntaxHandlebarsCompilerWhitespaceControl, _htmlbarsSyntaxHandlebarsCompilerHelpers, _htmlbarsSyntaxHandlebarsUtils) { 'use strict'; exports.parse = parse; exports.parser = _htmlbarsSyntaxHandlebarsCompilerParser.default; var yy = {}; _htmlbarsSyntaxHandlebarsUtils.extend(yy, _htmlbarsSyntaxHandlebarsCompilerHelpers, _htmlbarsSyntaxHandlebarsCompilerAst.default); function parse(input, options) { // Just return if an already-compiled AST was passed in. if (input.type === 'Program') { return input; } _htmlbarsSyntaxHandlebarsCompilerParser.default.yy = yy; // Altering the shared object here, but this is ok as parser is a sync operation yy.locInfo = function (locInfo) { return new yy.SourceLocation(options && options.srcName, locInfo); }; var strip = new _htmlbarsSyntaxHandlebarsCompilerWhitespaceControl.default(); return strip.accept(_htmlbarsSyntaxHandlebarsCompilerParser.default.parse(input)); } }); enifed('htmlbars-syntax/handlebars/compiler/helpers', ['exports', 'htmlbars-syntax/handlebars/exception'], function (exports, _htmlbarsSyntaxHandlebarsException) { 'use strict'; exports.SourceLocation = SourceLocation; exports.id = id; exports.stripFlags = stripFlags; exports.stripComment = stripComment; exports.preparePath = preparePath; exports.prepareMustache = prepareMustache; exports.prepareRawBlock = prepareRawBlock; exports.prepareBlock = prepareBlock; function SourceLocation(source, locInfo) { this.source = source; this.start = { line: locInfo.first_line, column: locInfo.first_column }; this.end = { line: locInfo.last_line, column: locInfo.last_column }; } function id(token) { if (/^\[.*\]$/.test(token)) { return token.substr(1, token.length - 2); } else { return token; } } function stripFlags(open, close) { return { open: open.charAt(2) === '~', close: close.charAt(close.length - 3) === '~' }; } function stripComment(comment) { return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, ''); } function preparePath(data, parts, locInfo) { locInfo = this.locInfo(locInfo); var original = data ? '@' : '', dig = [], depth = 0, depthString = ''; for (var i = 0, l = parts.length; i < l; i++) { var part = parts[i].part, // If we have [] syntax then we do not treat path references as operators, // i.e. foo.[this] resolves to approximately context.foo['this'] isLiteral = parts[i].original !== part; original += (parts[i].separator || '') + part; if (!isLiteral && (part === '..' || part === '.' || part === 'this')) { if (dig.length > 0) { throw new _htmlbarsSyntaxHandlebarsException.default('Invalid path: ' + original, { loc: locInfo }); } else if (part === '..') { depth++; depthString += '../'; } } else { dig.push(part); } } return new this.PathExpression(data, depth, dig, original, locInfo); } function prepareMustache(path, params, hash, open, strip, locInfo) { // Must use charAt to support IE pre-10 var escapeFlag = open.charAt(3) || open.charAt(2), escaped = escapeFlag !== '{' && escapeFlag !== '&'; return new this.MustacheStatement(path, params, hash, escaped, strip, this.locInfo(locInfo)); } function prepareRawBlock(openRawBlock, content, close, locInfo) { if (openRawBlock.path.original !== close) { var errorNode = { loc: openRawBlock.path.loc }; throw new _htmlbarsSyntaxHandlebarsException.default(openRawBlock.path.original + " doesn't match " + close, errorNode); } locInfo = this.locInfo(locInfo); var program = new this.Program([content], null, {}, locInfo); return new this.BlockStatement(openRawBlock.path, openRawBlock.params, openRawBlock.hash, program, undefined, {}, {}, {}, locInfo); } function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) { // When we are chaining inverse calls, we will not have a close path if (close && close.path && openBlock.path.original !== close.path.original) { var errorNode = { loc: openBlock.path.loc }; throw new _htmlbarsSyntaxHandlebarsException.default(openBlock.path.original + ' doesn\'t match ' + close.path.original, errorNode); } program.blockParams = openBlock.blockParams; var inverse = undefined, inverseStrip = undefined; if (inverseAndProgram) { if (inverseAndProgram.chain) { inverseAndProgram.program.body[0].closeStrip = close.strip; } inverseStrip = inverseAndProgram.strip; inverse = inverseAndProgram.program; } if (inverted) { inverted = inverse; inverse = program; program = inverted; } return new this.BlockStatement(openBlock.path, openBlock.params, openBlock.hash, program, inverse, openBlock.strip, inverseStrip, close && close.strip, this.locInfo(locInfo)); } }); enifed("htmlbars-syntax/handlebars/compiler/parser", ["exports"], function (exports) { /* istanbul ignore next */ /* Jison generated parser */ "use strict"; var handlebars = (function () { var parser = { trace: function trace() {}, yy: {}, symbols_: { "error": 2, "root": 3, "program": 4, "EOF": 5, "program_repetition0": 6, "statement": 7, "mustache": 8, "block": 9, "rawBlock": 10, "partial": 11, "content": 12, "COMMENT": 13, "CONTENT": 14, "openRawBlock": 15, "END_RAW_BLOCK": 16, "OPEN_RAW_BLOCK": 17, "helperName": 18, "openRawBlock_repetition0": 19, "openRawBlock_option0": 20, "CLOSE_RAW_BLOCK": 21, "openBlock": 22, "block_option0": 23, "closeBlock": 24, "openInverse": 25, "block_option1": 26, "OPEN_BLOCK": 27, "openBlock_repetition0": 28, "openBlock_option0": 29, "openBlock_option1": 30, "CLOSE": 31, "OPEN_INVERSE": 32, "openInverse_repetition0": 33, "openInverse_option0": 34, "openInverse_option1": 35, "openInverseChain": 36, "OPEN_INVERSE_CHAIN": 37, "openInverseChain_repetition0": 38, "openInverseChain_option0": 39, "openInverseChain_option1": 40, "inverseAndProgram": 41, "INVERSE": 42, "inverseChain": 43, "inverseChain_option0": 44, "OPEN_ENDBLOCK": 45, "OPEN": 46, "mustache_repetition0": 47, "mustache_option0": 48, "OPEN_UNESCAPED": 49, "mustache_repetition1": 50, "mustache_option1": 51, "CLOSE_UNESCAPED": 52, "OPEN_PARTIAL": 53, "partialName": 54, "partial_repetition0": 55, "partial_option0": 56, "param": 57, "sexpr": 58, "OPEN_SEXPR": 59, "sexpr_repetition0": 60, "sexpr_option0": 61, "CLOSE_SEXPR": 62, "hash": 63, "hash_repetition_plus0": 64, "hashSegment": 65, "ID": 66, "EQUALS": 67, "blockParams": 68, "OPEN_BLOCK_PARAMS": 69, "blockParams_repetition_plus0": 70, "CLOSE_BLOCK_PARAMS": 71, "path": 72, "dataName": 73, "STRING": 74, "NUMBER": 75, "BOOLEAN": 76, "UNDEFINED": 77, "NULL": 78, "DATA": 79, "pathSegments": 80, "SEP": 81, "$accept": 0, "$end": 1 }, terminals_: { 2: "error", 5: "EOF", 13: "COMMENT", 14: "CONTENT", 16: "END_RAW_BLOCK", 17: "OPEN_RAW_BLOCK", 21: "CLOSE_RAW_BLOCK", 27: "OPEN_BLOCK", 31: "CLOSE", 32: "OPEN_INVERSE", 37: "OPEN_INVERSE_CHAIN", 42: "INVERSE", 45: "OPEN_ENDBLOCK", 46: "OPEN", 49: "OPEN_UNESCAPED", 52: "CLOSE_UNESCAPED", 53: "OPEN_PARTIAL", 59: "OPEN_SEXPR", 62: "CLOSE_SEXPR", 66: "ID", 67: "EQUALS", 69: "OPEN_BLOCK_PARAMS", 71: "CLOSE_BLOCK_PARAMS", 74: "STRING", 75: "NUMBER", 76: "BOOLEAN", 77: "UNDEFINED", 78: "NULL", 79: "DATA", 81: "SEP" }, productions_: [0, [3, 2], [4, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [12, 1], [10, 3], [15, 5], [9, 4], [9, 4], [22, 6], [25, 6], [36, 6], [41, 2], [43, 3], [43, 1], [24, 3], [8, 5], [8, 5], [11, 5], [57, 1], [57, 1], [58, 5], [63, 1], [65, 3], [68, 3], [18, 1], [18, 1], [18, 1], [18, 1], [18, 1], [18, 1], [18, 1], [54, 1], [54, 1], [73, 2], [72, 1], [80, 3], [80, 1], [6, 0], [6, 2], [19, 0], [19, 2], [20, 0], [20, 1], [23, 0], [23, 1], [26, 0], [26, 1], [28, 0], [28, 2], [29, 0], [29, 1], [30, 0], [30, 1], [33, 0], [33, 2], [34, 0], [34, 1], [35, 0], [35, 1], [38, 0], [38, 2], [39, 0], [39, 1], [40, 0], [40, 1], [44, 0], [44, 1], [47, 0], [47, 2], [48, 0], [48, 1], [50, 0], [50, 2], [51, 0], [51, 1], [55, 0], [55, 2], [56, 0], [56, 1], [60, 0], [60, 2], [61, 0], [61, 1], [64, 1], [64, 2], [70, 1], [70, 2]], performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) { var $0 = $$.length - 1; switch (yystate) { case 1: return $$[$0 - 1]; break; case 2: this.$ = new yy.Program($$[$0], null, {}, yy.locInfo(this._$)); break; case 3: this.$ = $$[$0]; break; case 4: this.$ = $$[$0]; break; case 5: this.$ = $$[$0]; break; case 6: this.$ = $$[$0]; break; case 7: this.$ = $$[$0]; break; case 8: this.$ = new yy.CommentStatement(yy.stripComment($$[$0]), yy.stripFlags($$[$0], $$[$0]), yy.locInfo(this._$)); break; case 9: this.$ = new yy.ContentStatement($$[$0], yy.locInfo(this._$)); break; case 10: this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$); break; case 11: this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] }; break; case 12: this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$); break; case 13: this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$); break; case 14: this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; break; case 15: this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; break; case 16: this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; break; case 17: this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] }; break; case 18: var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$), program = new yy.Program([inverse], null, {}, yy.locInfo(this._$)); program.chained = true; this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true }; break; case 19: this.$ = $$[$0]; break; case 20: this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) }; break; case 21: this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$); break; case 22: this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$); break; case 23: this.$ = new yy.PartialStatement($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], yy.stripFlags($$[$0 - 4], $$[$0]), yy.locInfo(this._$)); break; case 24: this.$ = $$[$0]; break; case 25: this.$ = $$[$0]; break; case 26: this.$ = new yy.SubExpression($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], yy.locInfo(this._$)); break; case 27: this.$ = new yy.Hash($$[$0], yy.locInfo(this._$)); break; case 28: this.$ = new yy.HashPair(yy.id($$[$0 - 2]), $$[$0], yy.locInfo(this._$)); break; case 29: this.$ = yy.id($$[$0 - 1]); break; case 30: this.$ = $$[$0]; break; case 31: this.$ = $$[$0]; break; case 32: this.$ = new yy.StringLiteral($$[$0], yy.locInfo(this._$)); break; case 33: this.$ = new yy.NumberLiteral($$[$0], yy.locInfo(this._$)); break; case 34: this.$ = new yy.BooleanLiteral($$[$0], yy.locInfo(this._$)); break; case 35: this.$ = new yy.UndefinedLiteral(yy.locInfo(this._$)); break; case 36: this.$ = new yy.NullLiteral(yy.locInfo(this._$)); break; case 37: this.$ = $$[$0]; break; case 38: this.$ = $$[$0]; break; case 39: this.$ = yy.preparePath(true, $$[$0], this._$); break; case 40: this.$ = yy.preparePath(false, $$[$0], this._$); break; case 41: $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2]; break; case 42: this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }]; break; case 43: this.$ = []; break; case 44: $$[$0 - 1].push($$[$0]); break; case 45: this.$ = []; break; case 46: $$[$0 - 1].push($$[$0]); break; case 53: this.$ = []; break; case 54: $$[$0 - 1].push($$[$0]); break; case 59: this.$ = []; break; case 60: $$[$0 - 1].push($$[$0]); break; case 65: this.$ = []; break; case 66: $$[$0 - 1].push($$[$0]); break; case 73: this.$ = []; break; case 74: $$[$0 - 1].push($$[$0]); break; case 77: this.$ = []; break; case 78: $$[$0 - 1].push($$[$0]); break; case 81: this.$ = []; break; case 82: $$[$0 - 1].push($$[$0]); break; case 85: this.$ = []; break; case 86: $$[$0 - 1].push($$[$0]); break; case 89: this.$ = [$$[$0]]; break; case 90: $$[$0 - 1].push($$[$0]); break; case 91: this.$ = [$$[$0]]; break; case 92: $$[$0 - 1].push($$[$0]); break; } }, table: [{ 3: 1, 4: 2, 5: [2, 43], 6: 3, 13: [2, 43], 14: [2, 43], 17: [2, 43], 27: [2, 43], 32: [2, 43], 46: [2, 43], 49: [2, 43], 53: [2, 43] }, { 1: [3] }, { 5: [1, 4] }, { 5: [2, 2], 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: [1, 11], 14: [1, 18], 15: 16, 17: [1, 21], 22: 14, 25: 15, 27: [1, 19], 32: [1, 20], 37: [2, 2], 42: [2, 2], 45: [2, 2], 46: [1, 12], 49: [1, 13], 53: [1, 17] }, { 1: [2, 1] }, { 5: [2, 44], 13: [2, 44], 14: [2, 44], 17: [2, 44], 27: [2, 44], 32: [2, 44], 37: [2, 44], 42: [2, 44], 45: [2, 44], 46: [2, 44], 49: [2, 44], 53: [2, 44] }, { 5: [2, 3], 13: [2, 3], 14: [2, 3], 17: [2, 3], 27: [2, 3], 32: [2, 3], 37: [2, 3], 42: [2, 3], 45: [2, 3], 46: [2, 3], 49: [2, 3], 53: [2, 3] }, { 5: [2, 4], 13: [2, 4], 14: [2, 4], 17: [2, 4], 27: [2, 4], 32: [2, 4], 37: [2, 4], 42: [2, 4], 45: [2, 4], 46: [2, 4], 49: [2, 4], 53: [2, 4] }, { 5: [2, 5], 13: [2, 5], 14: [2, 5], 17: [2, 5], 27: [2, 5], 32: [2, 5], 37: [2, 5], 42: [2, 5], 45: [2, 5], 46: [2, 5], 49: [2, 5], 53: [2, 5] }, { 5: [2, 6], 13: [2, 6], 14: [2, 6], 17: [2, 6], 27: [2, 6], 32: [2, 6], 37: [2, 6], 42: [2, 6], 45: [2, 6], 46: [2, 6], 49: [2, 6], 53: [2, 6] }, { 5: [2, 7], 13: [2, 7], 14: [2, 7], 17: [2, 7], 27: [2, 7], 32: [2, 7], 37: [2, 7], 42: [2, 7], 45: [2, 7], 46: [2, 7], 49: [2, 7], 53: [2, 7] }, { 5: [2, 8], 13: [2, 8], 14: [2, 8], 17: [2, 8], 27: [2, 8], 32: [2, 8], 37: [2, 8], 42: [2, 8], 45: [2, 8], 46: [2, 8], 49: [2, 8], 53: [2, 8] }, { 18: 22, 66: [1, 32], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 18: 33, 66: [1, 32], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 4: 34, 6: 3, 13: [2, 43], 14: [2, 43], 17: [2, 43], 27: [2, 43], 32: [2, 43], 37: [2, 43], 42: [2, 43], 45: [2, 43], 46: [2, 43], 49: [2, 43], 53: [2, 43] }, { 4: 35, 6: 3, 13: [2, 43], 14: [2, 43], 17: [2, 43], 27: [2, 43], 32: [2, 43], 42: [2, 43], 45: [2, 43], 46: [2, 43], 49: [2, 43], 53: [2, 43] }, { 12: 36, 14: [1, 18] }, { 18: 38, 54: 37, 58: 39, 59: [1, 40], 66: [1, 32], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 5: [2, 9], 13: [2, 9], 14: [2, 9], 16: [2, 9], 17: [2, 9], 27: [2, 9], 32: [2, 9], 37: [2, 9], 42: [2, 9], 45: [2, 9], 46: [2, 9], 49: [2, 9], 53: [2, 9] }, { 18: 41, 66: [1, 32], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 18: 42, 66: [1, 32], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 18: 43, 66: [1, 32], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 31: [2, 73], 47: 44, 59: [2, 73], 66: [2, 73], 74: [2, 73], 75: [2, 73], 76: [2, 73], 77: [2, 73], 78: [2, 73], 79: [2, 73] }, { 21: [2, 30], 31: [2, 30], 52: [2, 30], 59: [2, 30], 62: [2, 30], 66: [2, 30], 69: [2, 30], 74: [2, 30], 75: [2, 30], 76: [2, 30], 77: [2, 30], 78: [2, 30], 79: [2, 30] }, { 21: [2, 31], 31: [2, 31], 52: [2, 31], 59: [2, 31], 62: [2, 31], 66: [2, 31], 69: [2, 31], 74: [2, 31], 75: [2, 31], 76: [2, 31], 77: [2, 31], 78: [2, 31], 79: [2, 31] }, { 21: [2, 32], 31: [2, 32], 52: [2, 32], 59: [2, 32], 62: [2, 32], 66: [2, 32], 69: [2, 32], 74: [2, 32], 75: [2, 32], 76: [2, 32], 77: [2, 32], 78: [2, 32], 79: [2, 32] }, { 21: [2, 33], 31: [2, 33], 52: [2, 33], 59: [2, 33], 62: [2, 33], 66: [2, 33], 69: [2, 33], 74: [2, 33], 75: [2, 33], 76: [2, 33], 77: [2, 33], 78: [2, 33], 79: [2, 33] }, { 21: [2, 34], 31: [2, 34], 52: [2, 34], 59: [2, 34], 62: [2, 34], 66: [2, 34], 69: [2, 34], 74: [2, 34], 75: [2, 34], 76: [2, 34], 77: [2, 34], 78: [2, 34], 79: [2, 34] }, { 21: [2, 35], 31: [2, 35], 52: [2, 35], 59: [2, 35], 62: [2, 35], 66: [2, 35], 69: [2, 35], 74: [2, 35], 75: [2, 35], 76: [2, 35], 77: [2, 35], 78: [2, 35], 79: [2, 35] }, { 21: [2, 36], 31: [2, 36], 52: [2, 36], 59: [2, 36], 62: [2, 36], 66: [2, 36], 69: [2, 36], 74: [2, 36], 75: [2, 36], 76: [2, 36], 77: [2, 36], 78: [2, 36], 79: [2, 36] }, { 21: [2, 40], 31: [2, 40], 52: [2, 40], 59: [2, 40], 62: [2, 40], 66: [2, 40], 69: [2, 40], 74: [2, 40], 75: [2, 40], 76: [2, 40], 77: [2, 40], 78: [2, 40], 79: [2, 40], 81: [1, 45] }, { 66: [1, 32], 80: 46 }, { 21: [2, 42], 31: [2, 42], 52: [2, 42], 59: [2, 42], 62: [2, 42], 66: [2, 42], 69: [2, 42], 74: [2, 42], 75: [2, 42], 76: [2, 42], 77: [2, 42], 78: [2, 42], 79: [2, 42], 81: [2, 42] }, { 50: 47, 52: [2, 77], 59: [2, 77], 66: [2, 77], 74: [2, 77], 75: [2, 77], 76: [2, 77], 77: [2, 77], 78: [2, 77], 79: [2, 77] }, { 23: 48, 36: 50, 37: [1, 52], 41: 51, 42: [1, 53], 43: 49, 45: [2, 49] }, { 26: 54, 41: 55, 42: [1, 53], 45: [2, 51] }, { 16: [1, 56] }, { 31: [2, 81], 55: 57, 59: [2, 81], 66: [2, 81], 74: [2, 81], 75: [2, 81], 76: [2, 81], 77: [2, 81], 78: [2, 81], 79: [2, 81] }, { 31: [2, 37], 59: [2, 37], 66: [2, 37], 74: [2, 37], 75: [2, 37], 76: [2, 37], 77: [2, 37], 78: [2, 37], 79: [2, 37] }, { 31: [2, 38], 59: [2, 38], 66: [2, 38], 74: [2, 38], 75: [2, 38], 76: [2, 38], 77: [2, 38], 78: [2, 38], 79: [2, 38] }, { 18: 58, 66: [1, 32], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 28: 59, 31: [2, 53], 59: [2, 53], 66: [2, 53], 69: [2, 53], 74: [2, 53], 75: [2, 53], 76: [2, 53], 77: [2, 53], 78: [2, 53], 79: [2, 53] }, { 31: [2, 59], 33: 60, 59: [2, 59], 66: [2, 59], 69: [2, 59], 74: [2, 59], 75: [2, 59], 76: [2, 59], 77: [2, 59], 78: [2, 59], 79: [2, 59] }, { 19: 61, 21: [2, 45], 59: [2, 45], 66: [2, 45], 74: [2, 45], 75: [2, 45], 76: [2, 45], 77: [2, 45], 78: [2, 45], 79: [2, 45] }, { 18: 65, 31: [2, 75], 48: 62, 57: 63, 58: 66, 59: [1, 40], 63: 64, 64: 67, 65: 68, 66: [1, 69], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 66: [1, 70] }, { 21: [2, 39], 31: [2, 39], 52: [2, 39], 59: [2, 39], 62: [2, 39], 66: [2, 39], 69: [2, 39], 74: [2, 39], 75: [2, 39], 76: [2, 39], 77: [2, 39], 78: [2, 39], 79: [2, 39], 81: [1, 45] }, { 18: 65, 51: 71, 52: [2, 79], 57: 72, 58: 66, 59: [1, 40], 63: 73, 64: 67, 65: 68, 66: [1, 69], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 24: 74, 45: [1, 75] }, { 45: [2, 50] }, { 4: 76, 6: 3, 13: [2, 43], 14: [2, 43], 17: [2, 43], 27: [2, 43], 32: [2, 43], 37: [2, 43], 42: [2, 43], 45: [2, 43], 46: [2, 43], 49: [2, 43], 53: [2, 43] }, { 45: [2, 19] }, { 18: 77, 66: [1, 32], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 4: 78, 6: 3, 13: [2, 43], 14: [2, 43], 17: [2, 43], 27: [2, 43], 32: [2, 43], 45: [2, 43], 46: [2, 43], 49: [2, 43], 53: [2, 43] }, { 24: 79, 45: [1, 75] }, { 45: [2, 52] }, { 5: [2, 10], 13: [2, 10], 14: [2, 10], 17: [2, 10], 27: [2, 10], 32: [2, 10], 37: [2, 10], 42: [2, 10], 45: [2, 10], 46: [2, 10], 49: [2, 10], 53: [2, 10] }, { 18: 65, 31: [2, 83], 56: 80, 57: 81, 58: 66, 59: [1, 40], 63: 82, 64: 67, 65: 68, 66: [1, 69], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 59: [2, 85], 60: 83, 62: [2, 85], 66: [2, 85], 74: [2, 85], 75: [2, 85], 76: [2, 85], 77: [2, 85], 78: [2, 85], 79: [2, 85] }, { 18: 65, 29: 84, 31: [2, 55], 57: 85, 58: 66, 59: [1, 40], 63: 86, 64: 67, 65: 68, 66: [1, 69], 69: [2, 55], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 18: 65, 31: [2, 61], 34: 87, 57: 88, 58: 66, 59: [1, 40], 63: 89, 64: 67, 65: 68, 66: [1, 69], 69: [2, 61], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 18: 65, 20: 90, 21: [2, 47], 57: 91, 58: 66, 59: [1, 40], 63: 92, 64: 67, 65: 68, 66: [1, 69], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 31: [1, 93] }, { 31: [2, 74], 59: [2, 74], 66: [2, 74], 74: [2, 74], 75: [2, 74], 76: [2, 74], 77: [2, 74], 78: [2, 74], 79: [2, 74] }, { 31: [2, 76] }, { 21: [2, 24], 31: [2, 24], 52: [2, 24], 59: [2, 24], 62: [2, 24], 66: [2, 24], 69: [2, 24], 74: [2, 24], 75: [2, 24], 76: [2, 24], 77: [2, 24], 78: [2, 24], 79: [2, 24] }, { 21: [2, 25], 31: [2, 25], 52: [2, 25], 59: [2, 25], 62: [2, 25], 66: [2, 25], 69: [2, 25], 74: [2, 25], 75: [2, 25], 76: [2, 25], 77: [2, 25], 78: [2, 25], 79: [2, 25] }, { 21: [2, 27], 31: [2, 27], 52: [2, 27], 62: [2, 27], 65: 94, 66: [1, 95], 69: [2, 27] }, { 21: [2, 89], 31: [2, 89], 52: [2, 89], 62: [2, 89], 66: [2, 89], 69: [2, 89] }, { 21: [2, 42], 31: [2, 42], 52: [2, 42], 59: [2, 42], 62: [2, 42], 66: [2, 42], 67: [1, 96], 69: [2, 42], 74: [2, 42], 75: [2, 42], 76: [2, 42], 77: [2, 42], 78: [2, 42], 79: [2, 42], 81: [2, 42] }, { 21: [2, 41], 31: [2, 41], 52: [2, 41], 59: [2, 41], 62: [2, 41], 66: [2, 41], 69: [2, 41], 74: [2, 41], 75: [2, 41], 76: [2, 41], 77: [2, 41], 78: [2, 41], 79: [2, 41], 81: [2, 41] }, { 52: [1, 97] }, { 52: [2, 78], 59: [2, 78], 66: [2, 78], 74: [2, 78], 75: [2, 78], 76: [2, 78], 77: [2, 78], 78: [2, 78], 79: [2, 78] }, { 52: [2, 80] }, { 5: [2, 12], 13: [2, 12], 14: [2, 12], 17: [2, 12], 27: [2, 12], 32: [2, 12], 37: [2, 12], 42: [2, 12], 45: [2, 12], 46: [2, 12], 49: [2, 12], 53: [2, 12] }, { 18: 98, 66: [1, 32], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 36: 50, 37: [1, 52], 41: 51, 42: [1, 53], 43: 100, 44: 99, 45: [2, 71] }, { 31: [2, 65], 38: 101, 59: [2, 65], 66: [2, 65], 69: [2, 65], 74: [2, 65], 75: [2, 65], 76: [2, 65], 77: [2, 65], 78: [2, 65], 79: [2, 65] }, { 45: [2, 17] }, { 5: [2, 13], 13: [2, 13], 14: [2, 13], 17: [2, 13], 27: [2, 13], 32: [2, 13], 37: [2, 13], 42: [2, 13], 45: [2, 13], 46: [2, 13], 49: [2, 13], 53: [2, 13] }, { 31: [1, 102] }, { 31: [2, 82], 59: [2, 82], 66: [2, 82], 74: [2, 82], 75: [2, 82], 76: [2, 82], 77: [2, 82], 78: [2, 82], 79: [2, 82] }, { 31: [2, 84] }, { 18: 65, 57: 104, 58: 66, 59: [1, 40], 61: 103, 62: [2, 87], 63: 105, 64: 67, 65: 68, 66: [1, 69], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 30: 106, 31: [2, 57], 68: 107, 69: [1, 108] }, { 31: [2, 54], 59: [2, 54], 66: [2, 54], 69: [2, 54], 74: [2, 54], 75: [2, 54], 76: [2, 54], 77: [2, 54], 78: [2, 54], 79: [2, 54] }, { 31: [2, 56], 69: [2, 56] }, { 31: [2, 63], 35: 109, 68: 110, 69: [1, 108] }, { 31: [2, 60], 59: [2, 60], 66: [2, 60], 69: [2, 60], 74: [2, 60], 75: [2, 60], 76: [2, 60], 77: [2, 60], 78: [2, 60], 79: [2, 60] }, { 31: [2, 62], 69: [2, 62] }, { 21: [1, 111] }, { 21: [2, 46], 59: [2, 46], 66: [2, 46], 74: [2, 46], 75: [2, 46], 76: [2, 46], 77: [2, 46], 78: [2, 46], 79: [2, 46] }, { 21: [2, 48] }, { 5: [2, 21], 13: [2, 21], 14: [2, 21], 17: [2, 21], 27: [2, 21], 32: [2, 21], 37: [2, 21], 42: [2, 21], 45: [2, 21], 46: [2, 21], 49: [2, 21], 53: [2, 21] }, { 21: [2, 90], 31: [2, 90], 52: [2, 90], 62: [2, 90], 66: [2, 90], 69: [2, 90] }, { 67: [1, 96] }, { 18: 65, 57: 112, 58: 66, 59: [1, 40], 66: [1, 32], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 5: [2, 22], 13: [2, 22], 14: [2, 22], 17: [2, 22], 27: [2, 22], 32: [2, 22], 37: [2, 22], 42: [2, 22], 45: [2, 22], 46: [2, 22], 49: [2, 22], 53: [2, 22] }, { 31: [1, 113] }, { 45: [2, 18] }, { 45: [2, 72] }, { 18: 65, 31: [2, 67], 39: 114, 57: 115, 58: 66, 59: [1, 40], 63: 116, 64: 67, 65: 68, 66: [1, 69], 69: [2, 67], 72: 23, 73: 24, 74: [1, 25], 75: [1, 26], 76: [1, 27], 77: [1, 28], 78: [1, 29], 79: [1, 31], 80: 30 }, { 5: [2, 23], 13: [2, 23], 14: [2, 23], 17: [2, 23], 27: [2, 23], 32: [2, 23], 37: [2, 23], 42: [2, 23], 45: [2, 23], 46: [2, 23], 49: [2, 23], 53: [2, 23] }, { 62: [1, 117] }, { 59: [2, 86], 62: [2, 86], 66: [2, 86], 74: [2, 86], 75: [2, 86], 76: [2, 86], 77: [2, 86], 78: [2, 86], 79: [2, 86] }, { 62: [2, 88] }, { 31: [1, 118] }, { 31: [2, 58] }, { 66: [1, 120], 70: 119 }, { 31: [1, 121] }, { 31: [2, 64] }, { 14: [2, 11] }, { 21: [2, 28], 31: [2, 28], 52: [2, 28], 62: [2, 28], 66: [2, 28], 69: [2, 28] }, { 5: [2, 20], 13: [2, 20], 14: [2, 20], 17: [2, 20], 27: [2, 20], 32: [2, 20], 37: [2, 20], 42: [2, 20], 45: [2, 20], 46: [2, 20], 49: [2, 20], 53: [2, 20] }, { 31: [2, 69], 40: 122, 68: 123, 69: [1, 108] }, { 31: [2, 66], 59: [2, 66], 66: [2, 66], 69: [2, 66], 74: [2, 66], 75: [2, 66], 76: [2, 66], 77: [2, 66], 78: [2, 66], 79: [2, 66] }, { 31: [2, 68], 69: [2, 68] }, { 21: [2, 26], 31: [2, 26], 52: [2, 26], 59: [2, 26], 62: [2, 26], 66: [2, 26], 69: [2, 26], 74: [2, 26], 75: [2, 26], 76: [2, 26], 77: [2, 26], 78: [2, 26], 79: [2, 26] }, { 13: [2, 14], 14: [2, 14], 17: [2, 14], 27: [2, 14], 32: [2, 14], 37: [2, 14], 42: [2, 14], 45: [2, 14], 46: [2, 14], 49: [2, 14], 53: [2, 14] }, { 66: [1, 125], 71: [1, 124] }, { 66: [2, 91], 71: [2, 91] }, { 13: [2, 15], 14: [2, 15], 17: [2, 15], 27: [2, 15], 32: [2, 15], 42: [2, 15], 45: [2, 15], 46: [2, 15], 49: [2, 15], 53: [2, 15] }, { 31: [1, 126] }, { 31: [2, 70] }, { 31: [2, 29] }, { 66: [2, 92], 71: [2, 92] }, { 13: [2, 16], 14: [2, 16], 17: [2, 16], 27: [2, 16], 32: [2, 16], 37: [2, 16], 42: [2, 16], 45: [2, 16], 46: [2, 16], 49: [2, 16], 53: [2, 16] }], defaultActions: { 4: [2, 1], 49: [2, 50], 51: [2, 19], 55: [2, 52], 64: [2, 76], 73: [2, 80], 78: [2, 17], 82: [2, 84], 92: [2, 48], 99: [2, 18], 100: [2, 72], 105: [2, 88], 107: [2, 58], 110: [2, 64], 111: [2, 11], 123: [2, 70], 124: [2, 29] }, parseError: function parseError(str, hash) { throw new Error(str); }, parse: function parse(input) { var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; this.lexer.setInput(input); this.lexer.yy = this.yy; this.yy.lexer = this.lexer; this.yy.parser = this; if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {}; var yyloc = this.lexer.yylloc; lstack.push(yyloc); var ranges = this.lexer.options && this.lexer.options.ranges; if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError; function popStack(n) { stack.length = stack.length - 2 * n; vstack.length = vstack.length - n; lstack.length = lstack.length - n; } function lex() { var token; token = self.lexer.lex() || 1; if (typeof token !== "number") { token = self.symbols_[token] || token; } return token; } var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; while (true) { state = stack[stack.length - 1]; if (this.defaultActions[state]) { action = this.defaultActions[state]; } else { if (symbol === null || typeof symbol == "undefined") { symbol = lex(); } action = table[state] && table[state][symbol]; } if (typeof action === "undefined" || !action.length || !action[0]) { var errStr = ""; if (!recovering) { expected = []; for (p in table[state]) if (this.terminals_[p] && p > 2) { expected.push("'" + this.terminals_[p] + "'"); } if (this.lexer.showPosition) { errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; } else { errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'"); } this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected }); } } if (action[0] instanceof Array && action.length > 1) { throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); } switch (action[0]) { case 1: stack.push(symbol); vstack.push(this.lexer.yytext); lstack.push(this.lexer.yylloc); stack.push(action[1]); symbol = null; if (!preErrorSymbol) { yyleng = this.lexer.yyleng; yytext = this.lexer.yytext; yylineno = this.lexer.yylineno; yyloc = this.lexer.yylloc; if (recovering > 0) recovering--; } else { symbol = preErrorSymbol; preErrorSymbol = null; } break; case 2: len = this.productions_[action[1]][1]; yyval.$ = vstack[vstack.length - len]; yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column }; if (ranges) { yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; } r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); if (typeof r !== "undefined") { return r; } if (len) { stack = stack.slice(0, -1 * len * 2); vstack = vstack.slice(0, -1 * len); lstack = lstack.slice(0, -1 * len); } stack.push(this.productions_[action[1]][0]); vstack.push(yyval.$); lstack.push(yyval._$); newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; stack.push(newState); break; case 3: return true; } } return true; } }; /* Jison generated lexer */ var lexer = (function () { var lexer = { EOF: 1, parseError: function parseError(str, hash) { if (this.yy.parser) { this.yy.parser.parseError(str, hash); } else { throw new Error(str); } }, setInput: function (input) { this._input = input; this._more = this._less = this.done = false; this.yylineno = this.yyleng = 0; this.yytext = this.matched = this.match = ''; this.conditionStack = ['INITIAL']; this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 }; if (this.options.ranges) this.yylloc.range = [0, 0]; this.offset = 0; return this; }, input: function () { var ch = this._input[0]; this.yytext += ch; this.yyleng++; this.offset++; this.match += ch; this.matched += ch; var lines = ch.match(/(?:\r\n?|\n).*/g); if (lines) { this.yylineno++; this.yylloc.last_line++; } else { this.yylloc.last_column++; } if (this.options.ranges) this.yylloc.range[1]++; this._input = this._input.slice(1); return ch; }, unput: function (ch) { var len = ch.length; var lines = ch.split(/(?:\r\n?|\n)/g); this._input = ch + this._input; this.yytext = this.yytext.substr(0, this.yytext.length - len - 1); //this.yyleng -= len; this.offset -= len; var oldLines = this.match.split(/(?:\r\n?|\n)/g); this.match = this.match.substr(0, this.match.length - 1); this.matched = this.matched.substr(0, this.matched.length - 1); if (lines.length - 1) this.yylineno -= lines.length - 1; var r = this.yylloc.range; this.yylloc = { first_line: this.yylloc.first_line, last_line: this.yylineno + 1, first_column: this.yylloc.first_column, last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len }; if (this.options.ranges) { this.yylloc.range = [r[0], r[0] + this.yyleng - len]; } return this; }, more: function () { this._more = true; return this; }, less: function (n) { this.unput(this.match.slice(n)); }, pastInput: function () { var past = this.matched.substr(0, this.matched.length - this.match.length); return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, ""); }, upcomingInput: function () { var next = this.match; if (next.length < 20) { next += this._input.substr(0, 20 - next.length); } return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, ""); }, showPosition: function () { var pre = this.pastInput(); var c = new Array(pre.length + 1).join("-"); return pre + this.upcomingInput() + "\n" + c + "^"; }, next: function () { if (this.done) { return this.EOF; } if (!this._input) this.done = true; var token, match, tempMatch, index, col, lines; if (!this._more) { this.yytext = ''; this.match = ''; } var rules = this._currentRules(); for (var i = 0; i < rules.length; i++) { tempMatch = this._input.match(this.rules[rules[i]]); if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { match = tempMatch; index = i; if (!this.options.flex) break; } } if (match) { lines = match[0].match(/(?:\r\n?|\n).*/g); if (lines) this.yylineno += lines.length; this.yylloc = { first_line: this.yylloc.last_line, last_line: this.yylineno + 1, first_column: this.yylloc.last_column, last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length }; this.yytext += match[0]; this.match += match[0]; this.matches = match; this.yyleng = this.yytext.length; if (this.options.ranges) { this.yylloc.range = [this.offset, this.offset += this.yyleng]; } this._more = false; this._input = this._input.slice(match[0].length); this.matched += match[0]; token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]); if (this.done && this._input) this.done = false; if (token) return token;else return; } if (this._input === "") { return this.EOF; } else { return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno }); } }, lex: function lex() { var r = this.next(); if (typeof r !== 'undefined') { return r; } else { return this.lex(); } }, begin: function begin(condition) { this.conditionStack.push(condition); }, popState: function popState() { return this.conditionStack.pop(); }, _currentRules: function _currentRules() { return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; }, topState: function () { return this.conditionStack[this.conditionStack.length - 2]; }, pushState: function begin(condition) { this.begin(condition); } }; lexer.options = {}; lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) { function strip(start, end) { return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end); } var YYSTATE = YY_START; switch ($avoiding_name_collisions) { case 0: if (yy_.yytext.slice(-2) === "\\\\") { strip(0, 1); this.begin("mu"); } else if (yy_.yytext.slice(-1) === "\\") { strip(0, 1); this.begin("emu"); } else { this.begin("mu"); } if (yy_.yytext) return 14; break; case 1: return 14; break; case 2: this.popState(); return 14; break; case 3: yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9); this.popState(); return 16; break; case 4: return 14; break; case 5: this.popState(); return 13; break; case 6: return 59; break; case 7: return 62; break; case 8: return 17; break; case 9: this.popState(); this.begin('raw'); return 21; break; case 10: return 53; break; case 11: return 27; break; case 12: return 45; break; case 13: this.popState();return 42; break; case 14: this.popState();return 42; break; case 15: return 32; break; case 16: return 37; break; case 17: return 49; break; case 18: return 46; break; case 19: this.unput(yy_.yytext); this.popState(); this.begin('com'); break; case 20: this.popState(); return 13; break; case 21: return 46; break; case 22: return 67; break; case 23: return 66; break; case 24: return 66; break; case 25: return 81; break; case 26: // ignore whitespace break; case 27: this.popState();return 52; break; case 28: this.popState();return 31; break; case 29: yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 74; break; case 30: yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 74; break; case 31: return 79; break; case 32: return 76; break; case 33: return 76; break; case 34: return 77; break; case 35: return 78; break; case 36: return 75; break; case 37: return 69; break; case 38: return 71; break; case 39: return 66; break; case 40: return 66; break; case 41: return 'INVALID'; break; case 42: return 5; break; } }; lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/, /^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/, /^(?:[^\x00]*?(?=(\{\{\{\{\/)))/, /^(?:[\s\S]*?--(~)?\}\})/, /^(?:\()/, /^(?:\))/, /^(?:\{\{\{\{)/, /^(?:\}\}\}\})/, /^(?:\{\{(~)?>)/, /^(?:\{\{(~)?#)/, /^(?:\{\{(~)?\/)/, /^(?:\{\{(~)?\^\s*(~)?\}\})/, /^(?:\{\{(~)?\s*else\s*(~)?\}\})/, /^(?:\{\{(~)?\^)/, /^(?:\{\{(~)?\s*else\b)/, /^(?:\{\{(~)?\{)/, /^(?:\{\{(~)?&)/, /^(?:\{\{(~)?!--)/, /^(?:\{\{(~)?![\s\S]*?\}\})/, /^(?:\{\{(~)?)/, /^(?:=)/, /^(?:\.\.)/, /^(?:\.(?=([=~}\s\/.)|])))/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}(~)?\}\})/, /^(?:(~)?\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@)/, /^(?:true(?=([~}\s)])))/, /^(?:false(?=([~}\s)])))/, /^(?:undefined(?=([~}\s)])))/, /^(?:null(?=([~}\s)])))/, /^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/, /^(?:as\s+\|)/, /^(?:\|)/, /^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/, /^(?:\[[^\]]*\])/, /^(?:.)/, /^(?:$)/]; lexer.conditions = { "mu": { "rules": [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42], "inclusive": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [5], "inclusive": false }, "raw": { "rules": [3, 4], "inclusive": false }, "INITIAL": { "rules": [0, 1, 42], "inclusive": true } }; return lexer; })(); parser.lexer = lexer; function Parser() { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser; return new Parser(); })();exports.default = handlebars; }); enifed('htmlbars-syntax/handlebars/compiler/visitor', ['exports', 'htmlbars-syntax/handlebars/exception', 'htmlbars-syntax/handlebars/compiler/ast'], function (exports, _htmlbarsSyntaxHandlebarsException, _htmlbarsSyntaxHandlebarsCompilerAst) { 'use strict'; function Visitor() { this.parents = []; } Visitor.prototype = { constructor: Visitor, mutating: false, // Visits a given value. If mutating, will replace the value if necessary. acceptKey: function (node, name) { var value = this.accept(node[name]); if (this.mutating) { // Hacky sanity check: if (value && (!value.type || !_htmlbarsSyntaxHandlebarsCompilerAst.default[value.type])) { throw new _htmlbarsSyntaxHandlebarsException.default('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type); } node[name] = value; } }, // Performs an accept operation with added sanity check to ensure // required keys are not removed. acceptRequired: function (node, name) { this.acceptKey(node, name); if (!node[name]) { throw new _htmlbarsSyntaxHandlebarsException.default(node.type + ' requires ' + name); } }, // Traverses a given array. If mutating, empty respnses will be removed // for child elements. acceptArray: function (array) { for (var i = 0, l = array.length; i < l; i++) { this.acceptKey(array, i); if (!array[i]) { array.splice(i, 1); i--; l--; } } }, accept: function (object) { if (!object) { return; } if (this.current) { this.parents.unshift(this.current); } this.current = object; var ret = this[object.type](object); this.current = this.parents.shift(); if (!this.mutating || ret) { return ret; } else if (ret !== false) { return object; } }, Program: function (program) { this.acceptArray(program.body); }, MustacheStatement: function (mustache) { this.acceptRequired(mustache, 'path'); this.acceptArray(mustache.params); this.acceptKey(mustache, 'hash'); }, BlockStatement: function (block) { this.acceptRequired(block, 'path'); this.acceptArray(block.params); this.acceptKey(block, 'hash'); this.acceptKey(block, 'program'); this.acceptKey(block, 'inverse'); }, PartialStatement: function (partial) { this.acceptRequired(partial, 'name'); this.acceptArray(partial.params); this.acceptKey(partial, 'hash'); }, ContentStatement: function () /* content */{}, CommentStatement: function () /* comment */{}, SubExpression: function (sexpr) { this.acceptRequired(sexpr, 'path'); this.acceptArray(sexpr.params); this.acceptKey(sexpr, 'hash'); }, PathExpression: function () /* path */{}, StringLiteral: function () /* string */{}, NumberLiteral: function () /* number */{}, BooleanLiteral: function () /* bool */{}, UndefinedLiteral: function () /* literal */{}, NullLiteral: function () /* literal */{}, Hash: function (hash) { this.acceptArray(hash.pairs); }, HashPair: function (pair) { this.acceptRequired(pair, 'value'); } }; exports.default = Visitor; }); enifed('htmlbars-syntax/handlebars/compiler/whitespace-control', ['exports', 'htmlbars-syntax/handlebars/compiler/visitor'], function (exports, _htmlbarsSyntaxHandlebarsCompilerVisitor) { 'use strict'; function WhitespaceControl() {} WhitespaceControl.prototype = new _htmlbarsSyntaxHandlebarsCompilerVisitor.default(); WhitespaceControl.prototype.Program = function (program) { var isRoot = !this.isRootSeen; this.isRootSeen = true; var body = program.body; for (var i = 0, l = body.length; i < l; i++) { var current = body[i], strip = this.accept(current); if (!strip) { continue; } var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot), _isNextWhitespace = isNextWhitespace(body, i, isRoot), openStandalone = strip.openStandalone && _isPrevWhitespace, closeStandalone = strip.closeStandalone && _isNextWhitespace, inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace; if (strip.close) { omitRight(body, i, true); } if (strip.open) { omitLeft(body, i, true); } if (inlineStandalone) { omitRight(body, i); if (omitLeft(body, i)) { // If we are on a standalone node, save the indent info for partials if (current.type === 'PartialStatement') { // Pull out the whitespace from the final line current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1]; } } } if (openStandalone) { omitRight((current.program || current.inverse).body); // Strip out the previous content node if it's whitespace only omitLeft(body, i); } if (closeStandalone) { // Always strip the next node omitRight(body, i); omitLeft((current.inverse || current.program).body); } } return program; }; WhitespaceControl.prototype.BlockStatement = function (block) { this.accept(block.program); this.accept(block.inverse); // Find the inverse program that is involed with whitespace stripping. var program = block.program || block.inverse, inverse = block.program && block.inverse, firstInverse = inverse, lastInverse = inverse; if (inverse && inverse.chained) { firstInverse = inverse.body[0].program; // Walk the inverse chain to find the last inverse that is actually in the chain. while (lastInverse.chained) { lastInverse = lastInverse.body[lastInverse.body.length - 1].program; } } var strip = { open: block.openStrip.open, close: block.closeStrip.close, // Determine the standalone candiacy. Basically flag our content as being possibly standalone // so our parent can determine if we actually are standalone openStandalone: isNextWhitespace(program.body), closeStandalone: isPrevWhitespace((firstInverse || program).body) }; if (block.openStrip.close) { omitRight(program.body, null, true); } if (inverse) { var inverseStrip = block.inverseStrip; if (inverseStrip.open) { omitLeft(program.body, null, true); } if (inverseStrip.close) { omitRight(firstInverse.body, null, true); } if (block.closeStrip.open) { omitLeft(lastInverse.body, null, true); } // Find standalone else statments if (isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) { omitLeft(program.body); omitRight(firstInverse.body); } } else if (block.closeStrip.open) { omitLeft(program.body, null, true); } return strip; }; WhitespaceControl.prototype.MustacheStatement = function (mustache) { return mustache.strip; }; WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) { /* istanbul ignore next */ var strip = node.strip || {}; return { inlineStandalone: true, open: strip.open, close: strip.close }; }; function isPrevWhitespace(body, i, isRoot) { if (i === undefined) { i = body.length; } // Nodes that end with newlines are considered whitespace (but are special // cased for strip operations) var prev = body[i - 1], sibling = body[i - 2]; if (!prev) { return isRoot; } if (prev.type === 'ContentStatement') { return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original); } } function isNextWhitespace(body, i, isRoot) { if (i === undefined) { i = -1; } var next = body[i + 1], sibling = body[i + 2]; if (!next) { return isRoot; } if (next.type === 'ContentStatement') { return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original); } } // Marks the node to the right of the position as omitted. // I.e. {{foo}}' ' will mark the ' ' node as omitted. // // If i is undefined, then the first child will be marked as such. // // If mulitple is truthy then all whitespace will be stripped out until non-whitespace // content is met. function omitRight(body, i, multiple) { var current = body[i == null ? 0 : i + 1]; if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) { return; } var original = current.value; current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, ''); current.rightStripped = current.value !== original; } // Marks the node to the left of the position as omitted. // I.e. ' '{{foo}} will mark the ' ' node as omitted. // // If i is undefined then the last child will be marked as such. // // If mulitple is truthy then all whitespace will be stripped out until non-whitespace // content is met. function omitLeft(body, i, multiple) { var current = body[i == null ? body.length - 1 : i - 1]; if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) { return; } // We omit the last node if it's whitespace only and not preceeded by a non-content node. var original = current.value; current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, ''); current.leftStripped = current.value !== original; return current.leftStripped; } exports.default = WhitespaceControl; }); enifed('htmlbars-syntax/handlebars/exception', ['exports'], function (exports) { 'use strict'; var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; function Exception(message, node) { var loc = node && node.loc, line = undefined, column = undefined; if (loc) { line = loc.start.line; column = loc.start.column; message += ' - ' + line + ':' + column; } var tmp = Error.prototype.constructor.call(this, message); // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } if (Error.captureStackTrace) { Error.captureStackTrace(this, Exception); } if (loc) { this.lineNumber = line; this.column = column; } } Exception.prototype = new Error(); exports.default = Exception; }); enifed('htmlbars-syntax/handlebars/safe-string', ['exports'], function (exports) { // Build out our basic SafeString type 'use strict'; function SafeString(string) { this.string = string; } SafeString.prototype.toString = SafeString.prototype.toHTML = function () { return '' + this.string; }; exports.default = SafeString; }); enifed('htmlbars-syntax/handlebars/utils', ['exports'], function (exports) { 'use strict'; exports.extend = extend; exports.indexOf = indexOf; exports.escapeExpression = escapeExpression; exports.isEmpty = isEmpty; exports.blockParams = blockParams; exports.appendContextPath = appendContextPath; var escape = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`' }; var badChars = /[&<>"'`]/g, possible = /[&<>"'`]/; function escapeChar(chr) { return escape[chr]; } function extend(obj /* , ...source */) { for (var i = 1; i < arguments.length; i++) { for (var key in arguments[i]) { if (Object.prototype.hasOwnProperty.call(arguments[i], key)) { obj[key] = arguments[i][key]; } } } return obj; } var toString = Object.prototype.toString; exports.toString = toString; // Sourced from lodash // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt /*eslint-disable func-style, no-var */ var isFunction = function (value) { return typeof value === 'function'; }; // fallback for older versions of Chrome and Safari /* istanbul ignore next */ if (isFunction(/x/)) { exports.isFunction = isFunction = function (value) { return typeof value === 'function' && toString.call(value) === '[object Function]'; }; } var isFunction; exports.isFunction = isFunction; /*eslint-enable func-style, no-var */ /* istanbul ignore next */ var isArray = Array.isArray || function (value) { return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false; }; exports.isArray = isArray; // Older IE versions do not directly support indexOf so we must implement our own, sadly. function indexOf(array, value) { for (var i = 0, len = array.length; i < len; i++) { if (array[i] === value) { return i; } } return -1; } function escapeExpression(string) { if (typeof string !== 'string') { // don't escape SafeStrings, since they're already safe if (string && string.toHTML) { return string.toHTML(); } else if (string == null) { return ''; } else if (!string) { return string + ''; } // Force a string conversion as this will be done by the append regardless and // the regex test will do this transparently behind the scenes, causing issues if // an object's to string has escaped characters in it. string = '' + string; } if (!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); } function isEmpty(value) { if (!value && value !== 0) { return true; } else if (isArray(value) && value.length === 0) { return true; } else { return false; } } function blockParams(params, ids) { params.path = ids; return params; } function appendContextPath(contextPath, id) { return (contextPath ? contextPath + '.' : '') + id; } }); enifed("htmlbars-syntax/parser", ["exports", "htmlbars-syntax/handlebars/compiler/base", "htmlbars-syntax", "simple-html-tokenizer/evented-tokenizer", "simple-html-tokenizer/entity-parser", "simple-html-tokenizer/html5-named-char-refs", "htmlbars-syntax/parser/handlebars-node-visitors", "htmlbars-syntax/parser/tokenizer-event-handlers"], function (exports, _htmlbarsSyntaxHandlebarsCompilerBase, _htmlbarsSyntax, _simpleHtmlTokenizerEventedTokenizer, _simpleHtmlTokenizerEntityParser, _simpleHtmlTokenizerHtml5NamedCharRefs, _htmlbarsSyntaxParserHandlebarsNodeVisitors, _htmlbarsSyntaxParserTokenizerEventHandlers) { "use strict"; exports.preprocess = preprocess; exports.Parser = Parser; function preprocess(html, options) { var ast = typeof html === 'object' ? html : _htmlbarsSyntaxHandlebarsCompilerBase.parse(html); var combined = new Parser(html, options).acceptNode(ast); if (options && options.plugins && options.plugins.ast) { for (var i = 0, l = options.plugins.ast.length; i < l; i++) { var plugin = new options.plugins.ast[i](options); plugin.syntax = _htmlbarsSyntax; combined = plugin.transform(combined); } } return combined; } exports.default = preprocess; var entityParser = new _simpleHtmlTokenizerEntityParser.default(_simpleHtmlTokenizerHtml5NamedCharRefs.default); function Parser(source, options) { this.options = options || {}; this.elementStack = []; this.tokenizer = new _simpleHtmlTokenizerEventedTokenizer.default(this, entityParser); this.currentNode = null; this.currentAttribute = null; if (typeof source === 'string') { this.source = source.split(/(?:\r\n?|\n)/g); } } for (var key in _htmlbarsSyntaxParserHandlebarsNodeVisitors.default) { Parser.prototype[key] = _htmlbarsSyntaxParserHandlebarsNodeVisitors.default[key]; } for (var key in _htmlbarsSyntaxParserTokenizerEventHandlers.default) { Parser.prototype[key] = _htmlbarsSyntaxParserTokenizerEventHandlers.default[key]; } Parser.prototype.acceptNode = function (node) { return this[node.type](node); }; Parser.prototype.currentElement = function () { return this.elementStack[this.elementStack.length - 1]; }; Parser.prototype.sourceForMustache = function (mustache) { var firstLine = mustache.loc.start.line - 1; var lastLine = mustache.loc.end.line - 1; var currentLine = firstLine - 1; var firstColumn = mustache.loc.start.column + 2; var lastColumn = mustache.loc.end.column - 2; var string = []; var line; if (!this.source) { return '{{' + mustache.path.id.original + '}}'; } while (currentLine < lastLine) { currentLine++; line = this.source[currentLine]; if (currentLine === firstLine) { if (firstLine === lastLine) { string.push(line.slice(firstColumn, lastColumn)); } else { string.push(line.slice(firstColumn)); } } else if (currentLine === lastLine) { string.push(line.slice(0, lastColumn)); } else { string.push(line); } } return string.join('\n'); }; }); enifed("htmlbars-syntax/parser/handlebars-node-visitors", ["exports", "htmlbars-syntax/builders", "htmlbars-syntax/utils"], function (exports, _htmlbarsSyntaxBuilders, _htmlbarsSyntaxUtils) { "use strict"; exports.default = { Program: function (program) { var body = []; var node = _htmlbarsSyntaxBuilders.default.program(body, program.blockParams, program.loc); var i, l = program.body.length; this.elementStack.push(node); if (l === 0) { return this.elementStack.pop(); } for (i = 0; i < l; i++) { this.acceptNode(program.body[i]); } // Ensure that that the element stack is balanced properly. var poppedNode = this.elementStack.pop(); if (poppedNode !== node) { throw new Error("Unclosed element `" + poppedNode.tag + "` (on line " + poppedNode.loc.start.line + ")."); } return node; }, BlockStatement: function (block) { delete block.inverseStrip; delete block.openString; delete block.closeStrip; if (this.tokenizer.state === 'comment') { this.appendToCommentData('{{' + this.sourceForMustache(block) + '}}'); return; } if (this.tokenizer.state !== 'comment' && this.tokenizer.state !== 'data' && this.tokenizer.state !== 'beforeData') { throw new Error("A block may only be used inside an HTML element or another block."); } block = acceptCommonNodes(this, block); var program = block.program ? this.acceptNode(block.program) : null; var inverse = block.inverse ? this.acceptNode(block.inverse) : null; var node = _htmlbarsSyntaxBuilders.default.block(block.path, block.params, block.hash, program, inverse, block.loc); var parentProgram = this.currentElement(); _htmlbarsSyntaxUtils.appendChild(parentProgram, node); }, MustacheStatement: function (rawMustache) { var tokenizer = this.tokenizer; var path = rawMustache.path; var params = rawMustache.params; var hash = rawMustache.hash; var escaped = rawMustache.escaped; var loc = rawMustache.loc; var mustache = _htmlbarsSyntaxBuilders.default.mustache(path, params, hash, !escaped, loc); if (tokenizer.state === 'comment') { this.appendToCommentData('{{' + this.sourceForMustache(mustache) + '}}'); return; } acceptCommonNodes(this, mustache); switch (tokenizer.state) { // Tag helpers case "tagName": addElementModifier(this.currentNode, mustache); tokenizer.state = "beforeAttributeName"; break; case "beforeAttributeName": addElementModifier(this.currentNode, mustache); break; case "attributeName": case "afterAttributeName": this.beginAttributeValue(false); this.finishAttributeValue(); addElementModifier(this.currentNode, mustache); tokenizer.state = "beforeAttributeName"; break; case "afterAttributeValueQuoted": addElementModifier(this.currentNode, mustache); tokenizer.state = "beforeAttributeName"; break; // Attribute values case "beforeAttributeValue": appendDynamicAttributeValuePart(this.currentAttribute, mustache); tokenizer.state = 'attributeValueUnquoted'; break; case "attributeValueDoubleQuoted": case "attributeValueSingleQuoted": case "attributeValueUnquoted": appendDynamicAttributeValuePart(this.currentAttribute, mustache); break; // TODO: Only append child when the tokenizer state makes // sense to do so, otherwise throw an error. default: _htmlbarsSyntaxUtils.appendChild(this.currentElement(), mustache); } return mustache; }, ContentStatement: function (content) { updateTokenizerLocation(this.tokenizer, content); this.tokenizer.tokenizePart(content.value); this.tokenizer.flushData(); }, CommentStatement: function (comment) { return comment; }, PartialStatement: function (partial) { _htmlbarsSyntaxUtils.appendChild(this.currentElement(), partial); return partial; }, SubExpression: function (sexpr) { return acceptCommonNodes(this, sexpr); }, PathExpression: function (path) { delete path.data; delete path.depth; return path; }, Hash: function (hash) { for (var i = 0; i < hash.pairs.length; i++) { this.acceptNode(hash.pairs[i].value); } return hash; }, StringLiteral: function () {}, BooleanLiteral: function () {}, NumberLiteral: function () {}, UndefinedLiteral: function () {}, NullLiteral: function () {} }; function calculateRightStrippedOffsets(original, value) { if (value === '') { // if it is empty, just return the count of newlines // in original return { lines: original.split("\n").length - 1, columns: 0 }; } // otherwise, return the number of newlines prior to // `value` var difference = original.split(value)[0]; var lines = difference.split(/\n/); var lineCount = lines.length - 1; return { lines: lineCount, columns: lines[lineCount].length }; } function updateTokenizerLocation(tokenizer, content) { var line = content.loc.start.line; var column = content.loc.start.column; if (content.rightStripped) { var offsets = calculateRightStrippedOffsets(content.original, content.value); line = line + offsets.lines; if (offsets.lines) { column = offsets.columns; } else { column = column + offsets.columns; } } tokenizer.line = line; tokenizer.column = column; } function acceptCommonNodes(compiler, node) { compiler.acceptNode(node.path); if (node.params) { for (var i = 0; i < node.params.length; i++) { compiler.acceptNode(node.params[i]); } } else { node.params = []; } if (node.hash) { compiler.acceptNode(node.hash); } else { node.hash = _htmlbarsSyntaxBuilders.default.hash(); } return node; } function addElementModifier(element, mustache) { var path = mustache.path; var params = mustache.params; var hash = mustache.hash; var loc = mustache.loc; var modifier = _htmlbarsSyntaxBuilders.default.elementModifier(path, params, hash, loc); element.modifiers.push(modifier); } function appendDynamicAttributeValuePart(attribute, part) { attribute.isDynamic = true; attribute.parts.push(part); } }); enifed("htmlbars-syntax/parser/tokenizer-event-handlers", ["exports", "htmlbars-util/void-tag-names", "htmlbars-syntax/builders", "htmlbars-syntax/utils"], function (exports, _htmlbarsUtilVoidTagNames, _htmlbarsSyntaxBuilders, _htmlbarsSyntaxUtils) { "use strict"; exports.default = { reset: function () { this.currentNode = null; }, // Comment beginComment: function () { this.currentNode = _htmlbarsSyntaxBuilders.default.comment(""); this.currentNode.loc = { source: null, start: _htmlbarsSyntaxBuilders.default.pos(this.tagOpenLine, this.tagOpenColumn), end: null }; }, appendToCommentData: function (char) { this.currentNode.value += char; }, finishComment: function () { this.currentNode.loc.end = _htmlbarsSyntaxBuilders.default.pos(this.tokenizer.line, this.tokenizer.column); _htmlbarsSyntaxUtils.appendChild(this.currentElement(), this.currentNode); }, // Data beginData: function () { this.currentNode = _htmlbarsSyntaxBuilders.default.text(); this.currentNode.loc = { source: null, start: _htmlbarsSyntaxBuilders.default.pos(this.tokenizer.line, this.tokenizer.column), end: null }; }, appendToData: function (char) { this.currentNode.chars += char; }, finishData: function () { this.currentNode.loc.end = _htmlbarsSyntaxBuilders.default.pos(this.tokenizer.line, this.tokenizer.column); _htmlbarsSyntaxUtils.appendChild(this.currentElement(), this.currentNode); }, // Tags - basic tagOpen: function () { this.tagOpenLine = this.tokenizer.line; this.tagOpenColumn = this.tokenizer.column; }, beginStartTag: function () { this.currentNode = { type: 'StartTag', name: "", attributes: [], modifiers: [], selfClosing: false, loc: null }; }, beginEndTag: function () { this.currentNode = { type: 'EndTag', name: "", attributes: [], modifiers: [], selfClosing: false, loc: null }; }, finishTag: function () { var _tokenizer = this.tokenizer; var line = _tokenizer.line; var column = _tokenizer.column; var tag = this.currentNode; tag.loc = _htmlbarsSyntaxBuilders.default.loc(this.tagOpenLine, this.tagOpenColumn, line, column); if (tag.type === 'StartTag') { this.finishStartTag(); if (_htmlbarsUtilVoidTagNames.default.hasOwnProperty(tag.name) || tag.selfClosing) { this.finishEndTag(true); } } else if (tag.type === 'EndTag') { this.finishEndTag(false); } }, finishStartTag: function () { var _currentNode = this.currentNode; var name = _currentNode.name; var attributes = _currentNode.attributes; var modifiers = _currentNode.modifiers; validateStartTag(this.currentNode, this.tokenizer); var loc = _htmlbarsSyntaxBuilders.default.loc(this.tagOpenLine, this.tagOpenColumn); var element = _htmlbarsSyntaxBuilders.default.element(name, attributes, modifiers, [], loc); this.elementStack.push(element); }, finishEndTag: function (isVoid) { var tag = this.currentNode; var element = this.elementStack.pop(); var parent = this.currentElement(); var disableComponentGeneration = this.options.disableComponentGeneration === true; validateEndTag(tag, element, isVoid); element.loc.end.line = this.tokenizer.line; element.loc.end.column = this.tokenizer.column; if (disableComponentGeneration || cannotBeComponent(element.tag)) { _htmlbarsSyntaxUtils.appendChild(parent, element); } else { var program = _htmlbarsSyntaxBuilders.default.program(element.children); _htmlbarsSyntaxUtils.parseComponentBlockParams(element, program); var component = _htmlbarsSyntaxBuilders.default.component(element.tag, element.attributes, program, element.loc); _htmlbarsSyntaxUtils.appendChild(parent, component); } }, markTagAsSelfClosing: function () { this.currentNode.selfClosing = true; }, // Tags - name appendToTagName: function (char) { this.currentNode.name += char; }, // Tags - attributes beginAttribute: function () { var tag = this.currentNode; if (tag.type === 'EndTag') { throw new Error("Invalid end tag: closing tag must not have attributes, " + ("in `" + tag.name + "` (on line " + this.tokenizer.line + ").")); } this.currentAttribute = { name: "", parts: [], isQuoted: false, isDynamic: false, // beginAttribute isn't called until after the first char is consumed start: _htmlbarsSyntaxBuilders.default.pos(this.tokenizer.line, this.tokenizer.column), valueStartLine: null, valueStartColumn: null }; }, appendToAttributeName: function (char) { this.currentAttribute.name += char; }, beginAttributeValue: function (isQuoted) { this.currentAttribute.isQuoted = isQuoted; this.currentAttribute.valueStartLine = this.tokenizer.line; this.currentAttribute.valueStartColumn = this.tokenizer.column; }, appendToAttributeValue: function (char) { var parts = this.currentAttribute.parts; if (typeof parts[parts.length - 1] === 'string') { parts[parts.length - 1] += char; } else { parts.push(char); } }, finishAttributeValue: function () { var _currentAttribute = this.currentAttribute; var name = _currentAttribute.name; var parts = _currentAttribute.parts; var isQuoted = _currentAttribute.isQuoted; var isDynamic = _currentAttribute.isDynamic; var valueStartLine = _currentAttribute.valueStartLine; var valueStartColumn = _currentAttribute.valueStartColumn; var value = assembleAttributeValue(parts, isQuoted, isDynamic, this.tokenizer.line); value.loc = _htmlbarsSyntaxBuilders.default.loc(valueStartLine, valueStartColumn, this.tokenizer.line, this.tokenizer.column); var loc = _htmlbarsSyntaxBuilders.default.loc(this.currentAttribute.start.line, this.currentAttribute.start.column, this.tokenizer.line, this.tokenizer.column); var attribute = _htmlbarsSyntaxBuilders.default.attr(name, value, loc); this.currentNode.attributes.push(attribute); } }; function assembleAttributeValue(parts, isQuoted, isDynamic, line) { if (isDynamic) { if (isQuoted) { return assembleConcatenatedValue(parts); } else { if (parts.length === 1 || parts.length === 2 && parts[1] === '/') { return parts[0]; } else { throw new Error("An unquoted attribute value must be a string or a mustache, " + "preceeded by whitespace or a '=' character, and " + ("followed by whitespace, a '>' character or a '/>' (on line " + line + ")")); } } } else { return _htmlbarsSyntaxBuilders.default.text(parts.length > 0 ? parts[0] : ""); } } function assembleConcatenatedValue(parts) { for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (typeof part === 'string') { parts[i] = _htmlbarsSyntaxBuilders.default.string(parts[i]); } else { if (part.type === 'MustacheStatement') { parts[i] = _htmlbarsSyntaxUtils.unwrapMustache(part); } else { throw new Error("Unsupported node in quoted attribute value: " + part.type); } } } return _htmlbarsSyntaxBuilders.default.concat(parts); } function cannotBeComponent(tagName) { return tagName.indexOf("-") === -1 && tagName.indexOf(".") === -1; } function validateStartTag(tag, tokenizer) { // No support for <script> tags if (tag.name === "script") { throw new Error("`SCRIPT` tags are not allowed in HTMLBars templates (on line " + tokenizer.tagLine + ")"); } } function validateEndTag(tag, element, selfClosing) { if (_htmlbarsUtilVoidTagNames.default[tag.name] && !selfClosing) { // EngTag is also called by StartTag for void and self-closing tags (i.e. // <input> or <br />, so we need to check for that here. Otherwise, we would // throw an error for those cases. throw new Error("Invalid end tag " + formatEndTagInfo(tag) + " (void elements cannot have end tags)."); } else if (element.tag === undefined) { throw new Error("Closing tag " + formatEndTagInfo(tag) + " without an open tag."); } else if (element.tag !== tag.name) { throw new Error("Closing tag " + formatEndTagInfo(tag) + " did not match last open tag `" + element.tag + "` (on line " + element.loc.start.line + ")."); } } function formatEndTagInfo(tag) { return "`" + tag.name + "` (on line " + tag.loc.end.line + ")"; } }); enifed("htmlbars-syntax/traversal/errors", ["exports"], function (exports) { "use strict"; exports.cannotRemoveNode = cannotRemoveNode; exports.cannotReplaceNode = cannotReplaceNode; exports.cannotReplaceOrRemoveInKeyHandlerYet = cannotReplaceOrRemoveInKeyHandlerYet; function TraversalError(message, node, parent, key) { this.name = "TraversalError"; this.message = message; this.node = node; this.parent = parent; this.key = key; } TraversalError.prototype = Object.create(Error.prototype); TraversalError.prototype.constructor = TraversalError; exports.default = TraversalError; function cannotRemoveNode(node, parent, key) { return new TraversalError("Cannot remove a node unless it is part of an array", node, parent, key); } function cannotReplaceNode(node, parent, key) { return new TraversalError("Cannot replace a node with multiple nodes unless it is part of an array", node, parent, key); } function cannotReplaceOrRemoveInKeyHandlerYet(node, key) { return new TraversalError("Replacing and removing in key handlers is not yet supported.", node, null, key); } }); enifed('htmlbars-syntax/traversal/traverse', ['exports', 'htmlbars-syntax/types/visitor-keys', 'htmlbars-syntax/traversal/errors'], function (exports, _htmlbarsSyntaxTypesVisitorKeys, _htmlbarsSyntaxTraversalErrors) { 'use strict'; exports.default = traverse; exports.normalizeVisitor = normalizeVisitor; function visitNode(visitor, node) { var handler = visitor[node.type] || visitor.All; var result = undefined; if (handler && handler.enter) { result = handler.enter.call(null, node); } if (result === undefined) { var keys = _htmlbarsSyntaxTypesVisitorKeys.default[node.type]; for (var i = 0; i < keys.length; i++) { visitKey(visitor, handler, node, keys[i]); } if (handler && handler.exit) { result = handler.exit.call(null, node); } } return result; } function visitKey(visitor, handler, node, key) { var value = node[key]; if (!value) { return; } var keyHandler = handler && (handler.keys[key] || handler.keys.All); var result = undefined; if (keyHandler && keyHandler.enter) { result = keyHandler.enter.call(null, node, key); if (result !== undefined) { throw _htmlbarsSyntaxTraversalErrors.cannotReplaceOrRemoveInKeyHandlerYet(node, key); } } if (Array.isArray(value)) { visitArray(visitor, value); } else { var _result = visitNode(visitor, value); if (_result !== undefined) { assignKey(node, key, _result); } } if (keyHandler && keyHandler.exit) { result = keyHandler.exit.call(null, node, key); if (result !== undefined) { throw _htmlbarsSyntaxTraversalErrors.cannotReplaceOrRemoveInKeyHandlerYet(node, key); } } } function visitArray(visitor, array) { for (var i = 0; i < array.length; i++) { var result = visitNode(visitor, array[i]); if (result !== undefined) { i += spliceArray(array, i, result) - 1; } } } function assignKey(node, key, result) { if (result === null) { throw _htmlbarsSyntaxTraversalErrors.cannotRemoveNode(node[key], node, key); } else if (Array.isArray(result)) { if (result.length === 1) { node[key] = result[0]; } else { if (result.length === 0) { throw _htmlbarsSyntaxTraversalErrors.cannotRemoveNode(node[key], node, key); } else { throw _htmlbarsSyntaxTraversalErrors.cannotReplaceNode(node[key], node, key); } } } else { node[key] = result; } } function spliceArray(array, index, result) { if (result === null) { array.splice(index, 1); return 0; } else if (Array.isArray(result)) { array.splice.apply(array, [index, 1].concat(result)); return result.length; } else { array.splice(index, 1, result); return 1; } } function traverse(node, visitor) { visitNode(normalizeVisitor(visitor), node); } function normalizeVisitor(visitor) { var normalizedVisitor = {}; for (var type in visitor) { var handler = visitor[type] || visitor.All; var normalizedKeys = {}; if (typeof handler === 'object') { var keys = handler.keys; if (keys) { for (var key in keys) { var keyHandler = keys[key]; if (typeof keyHandler === 'object') { normalizedKeys[key] = { enter: typeof keyHandler.enter === 'function' ? keyHandler.enter : null, exit: typeof keyHandler.exit === 'function' ? keyHandler.exit : null }; } else if (typeof keyHandler === 'function') { normalizedKeys[key] = { enter: keyHandler, exit: null }; } } } normalizedVisitor[type] = { enter: typeof handler.enter === 'function' ? handler.enter : null, exit: typeof handler.exit === 'function' ? handler.exit : null, keys: normalizedKeys }; } else if (typeof handler === 'function') { normalizedVisitor[type] = { enter: handler, exit: null, keys: normalizedKeys }; } } return normalizedVisitor; } }); enifed('htmlbars-syntax/traversal/walker', ['exports'], function (exports) { 'use strict'; function Walker(order) { this.order = order; this.stack = []; } exports.default = Walker; Walker.prototype.visit = function (node, callback) { if (!node) { return; } this.stack.push(node); if (this.order === 'post') { this.children(node, callback); callback(node, this); } else { callback(node, this); this.children(node, callback); } this.stack.pop(); }; var visitors = { Program: function (walker, node, callback) { for (var i = 0; i < node.body.length; i++) { walker.visit(node.body[i], callback); } }, ElementNode: function (walker, node, callback) { for (var i = 0; i < node.children.length; i++) { walker.visit(node.children[i], callback); } }, BlockStatement: function (walker, node, callback) { walker.visit(node.program, callback); walker.visit(node.inverse, callback); }, ComponentNode: function (walker, node, callback) { walker.visit(node.program, callback); } }; Walker.prototype.children = function (node, callback) { var visitor = visitors[node.type]; if (visitor) { visitor(this, node, callback); } }; }); enifed('htmlbars-syntax/types/visitor-keys', ['exports'], function (exports) { 'use strict'; exports.default = { Program: ['body'], MustacheStatement: ['path', 'params', 'hash'], BlockStatement: ['path', 'params', 'hash', 'program', 'inverse'], ElementModifierStatement: ['path', 'params', 'hash'], PartialStatement: ['name', 'params', 'hash'], CommentStatement: [], ElementNode: ['attributes', 'modifiers', 'children'], ComponentNode: ['attributes', 'program'], AttrNode: ['value'], TextNode: [], ConcatStatement: ['parts'], SubExpression: ['path', 'params', 'hash'], PathExpression: [], StringLiteral: [], BooleanLiteral: [], NumberLiteral: [], NullLiteral: [], UndefinedLiteral: [], Hash: ['pairs'], HashPair: ['value'] }; }); enifed('htmlbars-syntax/utils', ['exports', 'htmlbars-util/array-utils'], function (exports, _htmlbarsUtilArrayUtils) { 'use strict'; exports.parseComponentBlockParams = parseComponentBlockParams; exports.childrenFor = childrenFor; exports.appendChild = appendChild; exports.isHelper = isHelper; exports.unwrapMustache = unwrapMustache; // Regex to validate the identifier for block parameters. // Based on the ID validation regex in Handlebars. var ID_INVERSE_PATTERN = /[!"#%-,\.\/;->@\[-\^`\{-~]/; // Checks the component's attributes to see if it uses block params. // If it does, registers the block params with the program and // removes the corresponding attributes from the element. function parseComponentBlockParams(element, program) { var l = element.attributes.length; var attrNames = []; for (var i = 0; i < l; i++) { attrNames.push(element.attributes[i].name); } var asIndex = _htmlbarsUtilArrayUtils.indexOfArray(attrNames, 'as'); if (asIndex !== -1 && l > asIndex && attrNames[asIndex + 1].charAt(0) === '|') { // Some basic validation, since we're doing the parsing ourselves var paramsString = attrNames.slice(asIndex).join(' '); if (paramsString.charAt(paramsString.length - 1) !== '|' || paramsString.match(/\|/g).length !== 2) { throw new Error('Invalid block parameters syntax: \'' + paramsString + '\''); } var params = []; for (i = asIndex + 1; i < l; i++) { var param = attrNames[i].replace(/\|/g, ''); if (param !== '') { if (ID_INVERSE_PATTERN.test(param)) { throw new Error('Invalid identifier for block parameters: \'' + param + '\' in \'' + paramsString + '\''); } params.push(param); } } if (params.length === 0) { throw new Error('Cannot use zero block parameters: \'' + paramsString + '\''); } element.attributes = element.attributes.slice(0, asIndex); program.blockParams = params; } } function childrenFor(node) { if (node.type === 'Program') { return node.body; } if (node.type === 'ElementNode') { return node.children; } } function appendChild(parent, node) { childrenFor(parent).push(node); } function isHelper(mustache) { return mustache.params && mustache.params.length > 0 || mustache.hash && mustache.hash.pairs.length > 0; } function unwrapMustache(mustache) { if (isHelper(mustache)) { return mustache; } else { return mustache.path; } } }); enifed("htmlbars-test-helpers", ["exports", "simple-html-tokenizer/index", "htmlbars-util/array-utils"], function (exports, _simpleHtmlTokenizerIndex, _htmlbarsUtilArrayUtils) { "use strict"; exports.equalInnerHTML = equalInnerHTML; exports.equalHTML = equalHTML; exports.equalTokens = equalTokens; exports.normalizeInnerHTML = normalizeInnerHTML; exports.isCheckedInputHTML = isCheckedInputHTML; exports.getTextContent = getTextContent; function equalInnerHTML(fragment, html) { var actualHTML = normalizeInnerHTML(fragment.innerHTML); QUnit.push(actualHTML === html, actualHTML, html); } function equalHTML(node, html) { var fragment; if (!node.nodeType && node.length) { fragment = document.createDocumentFragment(); while (node[0]) { fragment.appendChild(node[0]); } } else { fragment = node; } var div = document.createElement("div"); div.appendChild(fragment.cloneNode(true)); equalInnerHTML(div, html); } function generateTokens(fragmentOrHtml) { var div = document.createElement("div"); if (typeof fragmentOrHtml === 'string') { div.innerHTML = fragmentOrHtml; } else { div.appendChild(fragmentOrHtml.cloneNode(true)); } return { tokens: _simpleHtmlTokenizerIndex.tokenize(div.innerHTML), html: div.innerHTML }; } function equalTokens(fragment, html, message) { if (fragment.fragment) { fragment = fragment.fragment; } if (html.fragment) { html = html.fragment; } var fragTokens = generateTokens(fragment); var htmlTokens = generateTokens(html); function normalizeTokens(token) { if (token.type === 'StartTag') { token.attributes = token.attributes.sort(function (a, b) { if (a[0] > b[0]) { return 1; } if (a[0] < b[0]) { return -1; } return 0; }); } } _htmlbarsUtilArrayUtils.forEach(fragTokens.tokens, normalizeTokens); _htmlbarsUtilArrayUtils.forEach(htmlTokens.tokens, normalizeTokens); var msg = "Expected: " + html + "; Actual: " + fragTokens.html; if (message) { msg += " (" + message + ")"; } deepEqual(fragTokens.tokens, htmlTokens.tokens, msg); } // detect side-effects of cloning svg elements in IE9-11 var ieSVGInnerHTML = (function () { if (!document.createElementNS) { return false; } var div = document.createElement('div'); var node = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); div.appendChild(node); var clone = div.cloneNode(true); return clone.innerHTML === '<svg xmlns="http://www.w3.org/2000/svg" />'; })(); function normalizeInnerHTML(actualHTML) { if (ieSVGInnerHTML) { // Replace `<svg xmlns="http://www.w3.org/2000/svg" height="50%" />` with `<svg height="50%"></svg>`, etc. // drop namespace attribute actualHTML = actualHTML.replace(/ xmlns="[^"]+"/, ''); // replace self-closing elements actualHTML = actualHTML.replace(/<([^ >]+) [^\/>]*\/>/gi, function (tag, tagName) { return tag.slice(0, tag.length - 3) + '></' + tagName + '>'; }); } return actualHTML; } // detect weird IE8 checked element string var checkedInput = document.createElement('input'); checkedInput.setAttribute('checked', 'checked'); var checkedInputString = checkedInput.outerHTML; function isCheckedInputHTML(element) { equal(element.outerHTML, checkedInputString); } // check which property has the node's text content var textProperty = document.createElement('div').textContent === undefined ? 'innerText' : 'textContent'; function getTextContent(el) { // textNode if (el.nodeType === 3) { return el.nodeValue; } else { return el[textProperty]; } } }); enifed('htmlbars-util', ['exports', 'htmlbars-util/safe-string', 'htmlbars-util/handlebars/utils', 'htmlbars-util/namespaces', 'htmlbars-util/morph-utils'], function (exports, _htmlbarsUtilSafeString, _htmlbarsUtilHandlebarsUtils, _htmlbarsUtilNamespaces, _htmlbarsUtilMorphUtils) { 'use strict'; exports.SafeString = _htmlbarsUtilSafeString.default; exports.escapeExpression = _htmlbarsUtilHandlebarsUtils.escapeExpression; exports.getAttrNamespace = _htmlbarsUtilNamespaces.getAttrNamespace; exports.validateChildMorphs = _htmlbarsUtilMorphUtils.validateChildMorphs; exports.linkParams = _htmlbarsUtilMorphUtils.linkParams; exports.dump = _htmlbarsUtilMorphUtils.dump; }); enifed('htmlbars-util/array-utils', ['exports'], function (exports) { 'use strict'; exports.forEach = forEach; exports.map = map; function forEach(array, callback, binding) { var i, l; if (binding === undefined) { for (i = 0, l = array.length; i < l; i++) { callback(array[i], i, array); } } else { for (i = 0, l = array.length; i < l; i++) { callback.call(binding, array[i], i, array); } } } function map(array, callback) { var output = []; var i, l; for (i = 0, l = array.length; i < l; i++) { output.push(callback(array[i], i, array)); } return output; } var getIdx; if (Array.prototype.indexOf) { getIdx = function (array, obj, from) { return array.indexOf(obj, from); }; } else { getIdx = function (array, obj, from) { if (from === undefined || from === null) { from = 0; } else if (from < 0) { from = Math.max(0, array.length + from); } for (var i = from, l = array.length; i < l; i++) { if (array[i] === obj) { return i; } } return -1; }; } var isArray = Array.isArray || function (array) { return Object.prototype.toString.call(array) === '[object Array]'; }; exports.isArray = isArray; var indexOfArray = getIdx; exports.indexOfArray = indexOfArray; }); enifed('htmlbars-util/handlebars/safe-string', ['exports'], function (exports) { // Build out our basic SafeString type 'use strict'; function SafeString(string) { this.string = string; } SafeString.prototype.toString = SafeString.prototype.toHTML = function () { return '' + this.string; }; exports.default = SafeString; }); enifed('htmlbars-util/handlebars/utils', ['exports'], function (exports) { 'use strict'; exports.extend = extend; exports.indexOf = indexOf; exports.escapeExpression = escapeExpression; exports.isEmpty = isEmpty; exports.blockParams = blockParams; exports.appendContextPath = appendContextPath; var escape = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`' }; var badChars = /[&<>"'`]/g, possible = /[&<>"'`]/; function escapeChar(chr) { return escape[chr]; } function extend(obj /* , ...source */) { for (var i = 1; i < arguments.length; i++) { for (var key in arguments[i]) { if (Object.prototype.hasOwnProperty.call(arguments[i], key)) { obj[key] = arguments[i][key]; } } } return obj; } var toString = Object.prototype.toString; exports.toString = toString; // Sourced from lodash // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt /*eslint-disable func-style, no-var */ var isFunction = function (value) { return typeof value === 'function'; }; // fallback for older versions of Chrome and Safari /* istanbul ignore next */ if (isFunction(/x/)) { exports.isFunction = isFunction = function (value) { return typeof value === 'function' && toString.call(value) === '[object Function]'; }; } var isFunction; exports.isFunction = isFunction; /*eslint-enable func-style, no-var */ /* istanbul ignore next */ var isArray = Array.isArray || function (value) { return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false; }; exports.isArray = isArray; // Older IE versions do not directly support indexOf so we must implement our own, sadly. function indexOf(array, value) { for (var i = 0, len = array.length; i < len; i++) { if (array[i] === value) { return i; } } return -1; } function escapeExpression(string) { if (typeof string !== 'string') { // don't escape SafeStrings, since they're already safe if (string && string.toHTML) { return string.toHTML(); } else if (string == null) { return ''; } else if (!string) { return string + ''; } // Force a string conversion as this will be done by the append regardless and // the regex test will do this transparently behind the scenes, causing issues if // an object's to string has escaped characters in it. string = '' + string; } if (!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); } function isEmpty(value) { if (!value && value !== 0) { return true; } else if (isArray(value) && value.length === 0) { return true; } else { return false; } } function blockParams(params, ids) { params.path = ids; return params; } function appendContextPath(contextPath, id) { return (contextPath ? contextPath + '.' : '') + id; } }); enifed("htmlbars-util/morph-utils", ["exports"], function (exports) { /*globals console*/ "use strict"; exports.visitChildren = visitChildren; exports.validateChildMorphs = validateChildMorphs; exports.linkParams = linkParams; exports.dump = dump; function visitChildren(nodes, callback) { if (!nodes || nodes.length === 0) { return; } nodes = nodes.slice(); while (nodes.length) { var node = nodes.pop(); callback(node); if (node.childNodes) { nodes.push.apply(nodes, node.childNodes); } else if (node.firstChildMorph) { var current = node.firstChildMorph; while (current) { nodes.push(current); current = current.nextMorph; } } else if (node.morphList) { var current = node.morphList.firstChildMorph; while (current) { nodes.push(current); current = current.nextMorph; } } } } function validateChildMorphs(env, morph, visitor) { var morphList = morph.morphList; if (morph.morphList) { var current = morphList.firstChildMorph; while (current) { var next = current.nextMorph; validateChildMorphs(env, current, visitor); current = next; } } else if (morph.lastResult) { morph.lastResult.revalidateWith(env, undefined, undefined, undefined, visitor); } else if (morph.childNodes) { // This means that the childNodes were wired up manually for (var i = 0, l = morph.childNodes.length; i < l; i++) { validateChildMorphs(env, morph.childNodes[i], visitor); } } } function linkParams(env, scope, morph, path, params, hash) { if (morph.linkedParams) { return; } if (env.hooks.linkRenderNode(morph, env, scope, path, params, hash)) { morph.linkedParams = { params: params, hash: hash }; } } function dump(node) { console.group(node, node.isDirty); if (node.childNodes) { map(node.childNodes, dump); } else if (node.firstChildMorph) { var current = node.firstChildMorph; while (current) { dump(current); current = current.nextMorph; } } else if (node.morphList) { dump(node.morphList); } console.groupEnd(); } function map(nodes, cb) { for (var i = 0, l = nodes.length; i < l; i++) { cb(nodes[i]); } } }); enifed('htmlbars-util/namespaces', ['exports'], function (exports) { // ref http://dev.w3.org/html5/spec-LC/namespaces.html 'use strict'; exports.getAttrNamespace = getAttrNamespace; var defaultNamespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg', xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; function getAttrNamespace(attrName, detectedNamespace) { if (detectedNamespace) { return detectedNamespace; } var namespace; var colonIndex = attrName.indexOf(':'); if (colonIndex !== -1) { var prefix = attrName.slice(0, colonIndex); namespace = defaultNamespaces[prefix]; } return namespace || null; } }); enifed("htmlbars-util/object-utils", ["exports"], function (exports) { "use strict"; exports.merge = merge; exports.shallowCopy = shallowCopy; exports.keySet = keySet; exports.keyLength = keyLength; function merge(options, defaults) { for (var prop in defaults) { if (options.hasOwnProperty(prop)) { continue; } options[prop] = defaults[prop]; } return options; } function shallowCopy(obj) { return merge({}, obj); } function keySet(obj) { var set = {}; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { set[prop] = true; } } return set; } function keyLength(obj) { var count = 0; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { count++; } } return count; } }); enifed("htmlbars-util/quoting", ["exports"], function (exports) { "use strict"; exports.hash = hash; exports.repeat = repeat; function escapeString(str) { str = str.replace(/\\/g, "\\\\"); str = str.replace(/"/g, '\\"'); str = str.replace(/\n/g, "\\n"); return str; } exports.escapeString = escapeString; function string(str) { return '"' + escapeString(str) + '"'; } exports.string = string; function array(a) { return "[" + a + "]"; } exports.array = array; function hash(pairs) { return "{" + pairs.join(", ") + "}"; } function repeat(chars, times) { var str = ""; while (times--) { str += chars; } return str; } }); enifed('htmlbars-util/safe-string', ['exports', 'htmlbars-util/handlebars/safe-string'], function (exports, _htmlbarsUtilHandlebarsSafeString) { 'use strict'; exports.default = _htmlbarsUtilHandlebarsSafeString.default; }); enifed("htmlbars-util/template-utils", ["exports", "htmlbars-util/morph-utils", "htmlbars-runtime/render"], function (exports, _htmlbarsUtilMorphUtils, _htmlbarsRuntimeRender) { "use strict"; var _slice = Array.prototype.slice; exports.RenderState = RenderState; exports.blockFor = blockFor; exports.renderAndCleanup = renderAndCleanup; exports.clearMorph = clearMorph; exports.clearMorphList = clearMorphList; exports.buildStatement = buildStatement; function RenderState(renderNode, morphList) { // The morph list that is no longer needed and can be // destroyed. this.morphListToClear = morphList; // The morph list that needs to be pruned of any items // that were not yielded on a subsequent render. this.morphListToPrune = null; // A map of morphs for each item yielded in during this // rendering pass. Any morphs in the DOM but not in this map // will be pruned during cleanup. this.handledMorphs = {}; this.collisions = undefined; // The morph to clear once rendering is complete. By // default, we set this to the previous morph (to catch // the case where nothing is yielded; in that case, we // should just clear the morph). Otherwise this gets set // to null if anything is rendered. this.morphToClear = renderNode; this.shadowOptions = null; } function Block(render, template, blockOptions) { this.render = render; this.template = template; this.blockOptions = blockOptions; this.arity = template.arity; } Block.prototype.invoke = function (env, blockArguments, _self, renderNode, parentScope, visitor) { if (renderNode.lastResult) { renderNode.lastResult.revalidateWith(env, undefined, _self, blockArguments, visitor); } else { this._firstRender(env, blockArguments, _self, renderNode, parentScope); } }; Block.prototype._firstRender = function (env, blockArguments, _self, renderNode, parentScope) { var options = { renderState: new RenderState(renderNode) }; var render = this.render; var template = this.template; var scope = this.blockOptions.scope; var shadowScope = scope ? env.hooks.createChildScope(scope) : env.hooks.createFreshScope(); env.hooks.bindShadowScope(env, parentScope, shadowScope, this.blockOptions.options); if (_self !== undefined) { env.hooks.bindSelf(env, shadowScope, _self); } else if (this.blockOptions.self !== undefined) { env.hooks.bindSelf(env, shadowScope, this.blockOptions.self); } bindBlocks(env, shadowScope, this.blockOptions.yieldTo); renderAndCleanup(renderNode, env, options, null, function () { options.renderState.morphToClear = null; var renderOptions = new _htmlbarsRuntimeRender.RenderOptions(renderNode, undefined, blockArguments); render(template, env, shadowScope, renderOptions); }); }; function blockFor(render, template, blockOptions) { return new Block(render, template, blockOptions); } function bindBlocks(env, shadowScope, blocks) { if (!blocks) { return; } if (blocks instanceof Block) { env.hooks.bindBlock(env, shadowScope, blocks); } else { for (var name in blocks) { if (blocks.hasOwnProperty(name)) { env.hooks.bindBlock(env, shadowScope, blocks[name], name); } } } } function renderAndCleanup(morph, env, options, shadowOptions, callback) { // The RenderState object is used to collect information about what the // helper or hook being invoked has yielded. Once it has finished either // yielding multiple items (via yieldItem) or a single template (via // yieldTemplate), we detect what was rendered and how it differs from // the previous render, cleaning up old state in DOM as appropriate. var renderState = options.renderState; renderState.collisions = undefined; renderState.shadowOptions = shadowOptions; // Invoke the callback, instructing it to save information about what it // renders into RenderState. var result = callback(options); // The hook can opt-out of cleanup if it handled cleanup itself. if (result && result.handled) { return; } var morphMap = morph.morphMap; // Walk the morph list, clearing any items that were yielded in a previous // render but were not yielded during this render. var morphList = renderState.morphListToPrune; if (morphList) { var handledMorphs = renderState.handledMorphs; var item = morphList.firstChildMorph; while (item) { var next = item.nextMorph; // If we don't see the key in handledMorphs, it wasn't // yielded in and we can safely remove it from DOM. if (!(item.key in handledMorphs)) { morphMap[item.key] = undefined; clearMorph(item, env, true); item.destroy(); } item = next; } } morphList = renderState.morphListToClear; if (morphList) { clearMorphList(morphList, morph, env); } var toClear = renderState.morphToClear; if (toClear) { clearMorph(toClear, env); } } function clearMorph(morph, env, destroySelf) { var cleanup = env.hooks.cleanupRenderNode; var destroy = env.hooks.destroyRenderNode; var willCleanup = env.hooks.willCleanupTree; var didCleanup = env.hooks.didCleanupTree; function destroyNode(node) { if (cleanup) { cleanup(node); } if (destroy) { destroy(node); } } if (willCleanup) { willCleanup(env, morph, destroySelf); } if (cleanup) { cleanup(morph); } if (destroySelf && destroy) { destroy(morph); } _htmlbarsUtilMorphUtils.visitChildren(morph.childNodes, destroyNode); // TODO: Deal with logical children that are not in the DOM tree morph.clear(); if (didCleanup) { didCleanup(env, morph, destroySelf); } morph.lastResult = null; morph.lastYielded = null; morph.childNodes = null; } function clearMorphList(morphList, morph, env) { var item = morphList.firstChildMorph; while (item) { var next = item.nextMorph; morph.morphMap[item.key] = undefined; clearMorph(item, env, true); item.destroy(); item = next; } // Remove the MorphList from the morph. morphList.clear(); morph.morphList = null; } function buildStatement() { var statement = [].concat(_slice.call(arguments)); // ensure array length is 7 by padding with 0 for (var i = arguments.length; i < 7; i++) { statement[i] = 0; } return statement; } }); enifed("htmlbars-util/void-tag-names", ["exports", "htmlbars-util/array-utils"], function (exports, _htmlbarsUtilArrayUtils) { "use strict"; // The HTML elements in this list are speced by // http://www.w3.org/TR/html-markup/syntax.html#syntax-elements, // and will be forced to close regardless of if they have a // self-closing /> at the end. var voidTagNames = "area base br col command embed hr img input keygen link meta param source track wbr"; var voidMap = {}; _htmlbarsUtilArrayUtils.forEach(voidTagNames.split(" "), function (tagName) { voidMap[tagName] = true; }); exports.default = voidMap; }); enifed('morph-range', ['exports', 'morph-range/utils'], function (exports, _morphRangeUtils) { 'use strict'; // constructor just initializes the fields // use one of the static initializers to create a valid morph. function Morph(domHelper, contextualElement) { this.domHelper = domHelper; // context if content if current content is detached this.contextualElement = contextualElement; // inclusive range of morph // these should be nodeType 1, 3, or 8 this.firstNode = null; this.lastNode = null; // flag to force text to setContent to be treated as html this.parseTextAsHTML = false; // morph list graph this.parentMorphList = null; this.previousMorph = null; this.nextMorph = null; } Morph.empty = function (domHelper, contextualElement) { var morph = new Morph(domHelper, contextualElement); morph.clear(); return morph; }; Morph.create = function (domHelper, contextualElement, node) { var morph = new Morph(domHelper, contextualElement); morph.setNode(node); return morph; }; Morph.attach = function (domHelper, contextualElement, firstNode, lastNode) { var morph = new Morph(domHelper, contextualElement); morph.setRange(firstNode, lastNode); return morph; }; Morph.prototype.setContent = function Morph$setContent(content) { if (content === null || content === undefined) { return this.clear(); } var type = typeof content; switch (type) { case 'string': if (this.parseTextAsHTML) { return this.domHelper.setMorphHTML(this, content); } return this.setText(content); case 'object': if (typeof content.nodeType === 'number') { return this.setNode(content); } /* Handlebars.SafeString */ if (typeof content.toHTML === 'function') { return this.setHTML(content.toHTML()); } if (this.parseTextAsHTML) { return this.setHTML(content.toString()); } /* falls through */ case 'boolean': case 'number': return this.setText(content.toString()); case 'function': raiseCannotBindToFunction(content); default: throw new TypeError('unsupported content'); } }; function raiseCannotBindToFunction(content) { var functionName = content.name; var message; if (functionName) { message = 'Unsupported Content: Cannot bind to function `' + functionName + '`'; } else { message = 'Unsupported Content: Cannot bind to function'; } throw new TypeError(message); } Morph.prototype.clear = function Morph$clear() { var node = this.setNode(this.domHelper.createComment('')); return node; }; Morph.prototype.setText = function Morph$setText(text) { var firstNode = this.firstNode; var lastNode = this.lastNode; if (firstNode && lastNode === firstNode && firstNode.nodeType === 3) { firstNode.nodeValue = text; return firstNode; } return this.setNode(text ? this.domHelper.createTextNode(text) : this.domHelper.createComment('')); }; Morph.prototype.setNode = function Morph$setNode(newNode) { var firstNode, lastNode; switch (newNode.nodeType) { case 3: firstNode = newNode; lastNode = newNode; break; case 11: firstNode = newNode.firstChild; lastNode = newNode.lastChild; if (firstNode === null) { firstNode = this.domHelper.createComment(''); newNode.appendChild(firstNode); lastNode = firstNode; } break; default: firstNode = newNode; lastNode = newNode; break; } this.setRange(firstNode, lastNode); return newNode; }; Morph.prototype.setRange = function (firstNode, lastNode) { var previousFirstNode = this.firstNode; if (previousFirstNode !== null) { var parentNode = previousFirstNode.parentNode; if (parentNode !== null) { _morphRangeUtils.insertBefore(parentNode, firstNode, lastNode, previousFirstNode); _morphRangeUtils.clear(parentNode, previousFirstNode, this.lastNode); } } this.firstNode = firstNode; this.lastNode = lastNode; if (this.parentMorphList) { this._syncFirstNode(); this._syncLastNode(); } }; Morph.prototype.destroy = function Morph$destroy() { this.unlink(); var firstNode = this.firstNode; var lastNode = this.lastNode; var parentNode = firstNode && firstNode.parentNode; this.firstNode = null; this.lastNode = null; _morphRangeUtils.clear(parentNode, firstNode, lastNode); }; Morph.prototype.unlink = function Morph$unlink() { var parentMorphList = this.parentMorphList; var previousMorph = this.previousMorph; var nextMorph = this.nextMorph; if (previousMorph) { if (nextMorph) { previousMorph.nextMorph = nextMorph; nextMorph.previousMorph = previousMorph; } else { previousMorph.nextMorph = null; parentMorphList.lastChildMorph = previousMorph; } } else { if (nextMorph) { nextMorph.previousMorph = null; parentMorphList.firstChildMorph = nextMorph; } else if (parentMorphList) { parentMorphList.lastChildMorph = parentMorphList.firstChildMorph = null; } } this.parentMorphList = null; this.nextMorph = null; this.previousMorph = null; if (parentMorphList && parentMorphList.mountedMorph) { if (!parentMorphList.firstChildMorph) { // list is empty parentMorphList.mountedMorph.clear(); return; } else { parentMorphList.firstChildMorph._syncFirstNode(); parentMorphList.lastChildMorph._syncLastNode(); } } }; Morph.prototype.setHTML = function (text) { var fragment = this.domHelper.parseHTML(text, this.contextualElement); return this.setNode(fragment); }; Morph.prototype.setMorphList = function Morph$appendMorphList(morphList) { morphList.mountedMorph = this; this.clear(); var originalFirstNode = this.firstNode; if (morphList.firstChildMorph) { this.firstNode = morphList.firstChildMorph.firstNode; this.lastNode = morphList.lastChildMorph.lastNode; var current = morphList.firstChildMorph; while (current) { var next = current.nextMorph; current.insertBeforeNode(originalFirstNode, null); current = next; } originalFirstNode.parentNode.removeChild(originalFirstNode); } }; Morph.prototype._syncFirstNode = function Morph$syncFirstNode() { var morph = this; var parentMorphList; while (parentMorphList = morph.parentMorphList) { if (parentMorphList.mountedMorph === null) { break; } if (morph !== parentMorphList.firstChildMorph) { break; } if (morph.firstNode === parentMorphList.mountedMorph.firstNode) { break; } parentMorphList.mountedMorph.firstNode = morph.firstNode; morph = parentMorphList.mountedMorph; } }; Morph.prototype._syncLastNode = function Morph$syncLastNode() { var morph = this; var parentMorphList; while (parentMorphList = morph.parentMorphList) { if (parentMorphList.mountedMorph === null) { break; } if (morph !== parentMorphList.lastChildMorph) { break; } if (morph.lastNode === parentMorphList.mountedMorph.lastNode) { break; } parentMorphList.mountedMorph.lastNode = morph.lastNode; morph = parentMorphList.mountedMorph; } }; Morph.prototype.insertBeforeNode = function Morph$insertBeforeNode(parentNode, refNode) { _morphRangeUtils.insertBefore(parentNode, this.firstNode, this.lastNode, refNode); }; Morph.prototype.appendToNode = function Morph$appendToNode(parentNode) { _morphRangeUtils.insertBefore(parentNode, this.firstNode, this.lastNode, null); }; exports.default = Morph; }); enifed('morph-range/morph-list', ['exports', 'morph-range/utils'], function (exports, _morphRangeUtils) { 'use strict'; function MorphList() { // morph graph this.firstChildMorph = null; this.lastChildMorph = null; this.mountedMorph = null; } var prototype = MorphList.prototype; prototype.clear = function MorphList$clear() { var current = this.firstChildMorph; while (current) { var next = current.nextMorph; current.previousMorph = null; current.nextMorph = null; current.parentMorphList = null; current = next; } this.firstChildMorph = this.lastChildMorph = null; }; prototype.destroy = function MorphList$destroy() {}; prototype.appendMorph = function MorphList$appendMorph(morph) { this.insertBeforeMorph(morph, null); }; prototype.insertBeforeMorph = function MorphList$insertBeforeMorph(morph, referenceMorph) { if (morph.parentMorphList !== null) { morph.unlink(); } if (referenceMorph && referenceMorph.parentMorphList !== this) { throw new Error('The morph before which the new morph is to be inserted is not a child of this morph.'); } var mountedMorph = this.mountedMorph; if (mountedMorph) { var parentNode = mountedMorph.firstNode.parentNode; var referenceNode = referenceMorph ? referenceMorph.firstNode : mountedMorph.lastNode.nextSibling; _morphRangeUtils.insertBefore(parentNode, morph.firstNode, morph.lastNode, referenceNode); // was not in list mode replace current content if (!this.firstChildMorph) { _morphRangeUtils.clear(this.mountedMorph.firstNode.parentNode, this.mountedMorph.firstNode, this.mountedMorph.lastNode); } } morph.parentMorphList = this; var previousMorph = referenceMorph ? referenceMorph.previousMorph : this.lastChildMorph; if (previousMorph) { previousMorph.nextMorph = morph; morph.previousMorph = previousMorph; } else { this.firstChildMorph = morph; } if (referenceMorph) { referenceMorph.previousMorph = morph; morph.nextMorph = referenceMorph; } else { this.lastChildMorph = morph; } this.firstChildMorph._syncFirstNode(); this.lastChildMorph._syncLastNode(); }; prototype.removeChildMorph = function MorphList$removeChildMorph(morph) { if (morph.parentMorphList !== this) { throw new Error("Cannot remove a morph from a parent it is not inside of"); } morph.destroy(); }; exports.default = MorphList; }); enifed('morph-range/morph-list.umd', ['exports', 'morph-range/morph-list'], function (exports, _morphRangeMorphList) { 'use strict'; (function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.MorphList = factory(); } })(undefined, function () { return _morphRangeMorphList.default; }); }); enifed("morph-range/utils", ["exports"], function (exports) { // inclusive of both nodes "use strict"; exports.clear = clear; exports.insertBefore = insertBefore; function clear(parentNode, firstNode, lastNode) { if (!parentNode) { return; } var node = firstNode; var nextNode; do { nextNode = node.nextSibling; parentNode.removeChild(node); if (node === lastNode) { break; } node = nextNode; } while (node); } function insertBefore(parentNode, firstNode, lastNode, refNode) { var node = firstNode; var nextNode; do { nextNode = node.nextSibling; parentNode.insertBefore(node, refNode); if (node === lastNode) { break; } node = nextNode; } while (node); } }); enifed("simple-html-tokenizer/entity-parser", ["exports"], function (exports) { "use strict"; function EntityParser(named) { this.named = named; } var HEXCHARCODE = /^#[xX]([A-Fa-f0-9]+)$/; var CHARCODE = /^#([0-9]+)$/; var NAMED = /^([A-Za-z0-9]+)$/; EntityParser.prototype.parse = function (entity) { if (!entity) { return; } var matches = entity.match(HEXCHARCODE); if (matches) { return String.fromCharCode(parseInt(matches[1], 16)); } matches = entity.match(CHARCODE); if (matches) { return String.fromCharCode(parseInt(matches[1], 10)); } matches = entity.match(NAMED); if (matches) { return this.named[matches[1]]; } }; exports.default = EntityParser; }); enifed('simple-html-tokenizer/evented-tokenizer', ['exports', 'simple-html-tokenizer/utils'], function (exports, _simpleHtmlTokenizerUtils) { 'use strict'; function EventedTokenizer(delegate, entityParser) { this.delegate = delegate; this.entityParser = entityParser; this.state = null; this.input = null; this.index = -1; this.line = -1; this.column = -1; this.tagLine = -1; this.tagColumn = -1; this.reset(); } EventedTokenizer.prototype = { reset: function () { this.state = 'beforeData'; this.input = ''; this.index = 0; this.line = 1; this.column = 0; this.tagLine = -1; this.tagColumn = -1; this.delegate.reset(); }, tokenize: function (input) { this.reset(); this.tokenizePart(input); this.tokenizeEOF(); }, tokenizePart: function (input) { this.input += _simpleHtmlTokenizerUtils.preprocessInput(input); while (this.index < this.input.length) { this.states[this.state].call(this); } }, tokenizeEOF: function () { this.flushData(); }, flushData: function () { if (this.state === 'data') { this.delegate.finishData(); this.state = 'beforeData'; } }, peek: function () { return this.input.charAt(this.index); }, consume: function () { var char = this.peek(); this.index++; if (char === "\n") { this.line++; this.column = 0; } else { this.column++; } return char; }, consumeCharRef: function () { var endIndex = this.input.indexOf(';', this.index); if (endIndex === -1) { return; } var entity = this.input.slice(this.index, endIndex); var chars = this.entityParser.parse(entity); if (chars) { var count = entity.length; // consume the entity chars while (count) { this.consume(); count--; } // consume the `;` this.consume(); return chars; } }, markTagStart: function () { // these properties to be removed in next major bump this.tagLine = this.line; this.tagColumn = this.column; if (this.delegate.tagOpen) { this.delegate.tagOpen(); } }, states: { beforeData: function () { var char = this.peek(); if (char === "<") { this.state = 'tagOpen'; this.markTagStart(); this.consume(); } else { this.state = 'data'; this.delegate.beginData(); } }, data: function () { var char = this.peek(); if (char === "<") { this.delegate.finishData(); this.state = 'tagOpen'; this.markTagStart(); this.consume(); } else if (char === "&") { this.consume(); this.delegate.appendToData(this.consumeCharRef() || "&"); } else { this.consume(); this.delegate.appendToData(char); } }, tagOpen: function () { var char = this.consume(); if (char === "!") { this.state = 'markupDeclaration'; } else if (char === "/") { this.state = 'endTagOpen'; } else if (_simpleHtmlTokenizerUtils.isAlpha(char)) { this.state = 'tagName'; this.delegate.beginStartTag(); this.delegate.appendToTagName(char.toLowerCase()); } }, markupDeclaration: function () { var char = this.consume(); if (char === "-" && this.input.charAt(this.index) === "-") { this.consume(); this.state = 'commentStart'; this.delegate.beginComment(); } }, commentStart: function () { var char = this.consume(); if (char === "-") { this.state = 'commentStartDash'; } else if (char === ">") { this.delegate.finishComment(); this.state = 'beforeData'; } else { this.delegate.appendToCommentData(char); this.state = 'comment'; } }, commentStartDash: function () { var char = this.consume(); if (char === "-") { this.state = 'commentEnd'; } else if (char === ">") { this.delegate.finishComment(); this.state = 'beforeData'; } else { this.delegate.appendToCommentData("-"); this.state = 'comment'; } }, comment: function () { var char = this.consume(); if (char === "-") { this.state = 'commentEndDash'; } else { this.delegate.appendToCommentData(char); } }, commentEndDash: function () { var char = this.consume(); if (char === "-") { this.state = 'commentEnd'; } else { this.delegate.appendToCommentData("-" + char); this.state = 'comment'; } }, commentEnd: function () { var char = this.consume(); if (char === ">") { this.delegate.finishComment(); this.state = 'beforeData'; } else { this.delegate.appendToCommentData("--" + char); this.state = 'comment'; } }, tagName: function () { var char = this.consume(); if (_simpleHtmlTokenizerUtils.isSpace(char)) { this.state = 'beforeAttributeName'; } else if (char === "/") { this.state = 'selfClosingStartTag'; } else if (char === ">") { this.delegate.finishTag(); this.state = 'beforeData'; } else { this.delegate.appendToTagName(char); } }, beforeAttributeName: function () { var char = this.peek(); if (_simpleHtmlTokenizerUtils.isSpace(char)) { this.consume(); return; } else if (char === "/") { this.state = 'selfClosingStartTag'; this.consume(); } else if (char === ">") { this.consume(); this.delegate.finishTag(); this.state = 'beforeData'; } else { this.state = 'attributeName'; this.delegate.beginAttribute(); this.consume(); this.delegate.appendToAttributeName(char); } }, attributeName: function () { var char = this.peek(); if (_simpleHtmlTokenizerUtils.isSpace(char)) { this.state = 'afterAttributeName'; this.consume(); } else if (char === "/") { this.delegate.beginAttributeValue(false); this.delegate.finishAttributeValue(); this.consume(); this.state = 'selfClosingStartTag'; } else if (char === "=") { this.state = 'beforeAttributeValue'; this.consume(); } else if (char === ">") { this.delegate.beginAttributeValue(false); this.delegate.finishAttributeValue(); this.consume(); this.delegate.finishTag(); this.state = 'beforeData'; } else { this.consume(); this.delegate.appendToAttributeName(char); } }, afterAttributeName: function () { var char = this.peek(); if (_simpleHtmlTokenizerUtils.isSpace(char)) { this.consume(); return; } else if (char === "/") { this.delegate.beginAttributeValue(false); this.delegate.finishAttributeValue(); this.consume(); this.state = 'selfClosingStartTag'; } else if (char === "=") { this.consume(); this.state = 'beforeAttributeValue'; } else if (char === ">") { this.delegate.beginAttributeValue(false); this.delegate.finishAttributeValue(); this.consume(); this.delegate.finishTag(); this.state = 'beforeData'; } else { this.delegate.beginAttributeValue(false); this.delegate.finishAttributeValue(); this.consume(); this.state = 'attributeName'; this.delegate.beginAttribute(); this.delegate.appendToAttributeName(char); } }, beforeAttributeValue: function () { var char = this.peek(); if (_simpleHtmlTokenizerUtils.isSpace(char)) { this.consume(); } else if (char === '"') { this.state = 'attributeValueDoubleQuoted'; this.delegate.beginAttributeValue(true); this.consume(); } else if (char === "'") { this.state = 'attributeValueSingleQuoted'; this.delegate.beginAttributeValue(true); this.consume(); } else if (char === ">") { this.delegate.beginAttributeValue(false); this.delegate.finishAttributeValue(); this.consume(); this.delegate.finishTag(); this.state = 'beforeData'; } else { this.state = 'attributeValueUnquoted'; this.delegate.beginAttributeValue(false); this.consume(); this.delegate.appendToAttributeValue(char); } }, attributeValueDoubleQuoted: function () { var char = this.consume(); if (char === '"') { this.delegate.finishAttributeValue(); this.state = 'afterAttributeValueQuoted'; } else if (char === "&") { this.delegate.appendToAttributeValue(this.consumeCharRef('"') || "&"); } else { this.delegate.appendToAttributeValue(char); } }, attributeValueSingleQuoted: function () { var char = this.consume(); if (char === "'") { this.delegate.finishAttributeValue(); this.state = 'afterAttributeValueQuoted'; } else if (char === "&") { this.delegate.appendToAttributeValue(this.consumeCharRef("'") || "&"); } else { this.delegate.appendToAttributeValue(char); } }, attributeValueUnquoted: function () { var char = this.peek(); if (_simpleHtmlTokenizerUtils.isSpace(char)) { this.delegate.finishAttributeValue(); this.consume(); this.state = 'beforeAttributeName'; } else if (char === "&") { this.consume(); this.delegate.appendToAttributeValue(this.consumeCharRef(">") || "&"); } else if (char === ">") { this.delegate.finishAttributeValue(); this.consume(); this.delegate.finishTag(); this.state = 'beforeData'; } else { this.consume(); this.delegate.appendToAttributeValue(char); } }, afterAttributeValueQuoted: function () { var char = this.peek(); if (_simpleHtmlTokenizerUtils.isSpace(char)) { this.consume(); this.state = 'beforeAttributeName'; } else if (char === "/") { this.consume(); this.state = 'selfClosingStartTag'; } else if (char === ">") { this.consume(); this.delegate.finishTag(); this.state = 'beforeData'; } else { this.state = 'beforeAttributeName'; } }, selfClosingStartTag: function () { var char = this.peek(); if (char === ">") { this.consume(); this.delegate.markTagAsSelfClosing(); this.delegate.finishTag(); this.state = 'beforeData'; } else { this.state = 'beforeAttributeName'; } }, endTagOpen: function () { var char = this.consume(); if (_simpleHtmlTokenizerUtils.isAlpha(char)) { this.state = 'tagName'; this.delegate.beginEndTag(); this.delegate.appendToTagName(char.toLowerCase()); } } } }; exports.default = EventedTokenizer; }); enifed("simple-html-tokenizer/html5-named-char-refs", ["exports"], function (exports) { "use strict"; exports.default = { Aacute: "Á", aacute: "á", Abreve: "Ă", abreve: "ă", ac: "∾", acd: "∿", acE: "∾̳", Acirc: "Â", acirc: "â", acute: "´", Acy: "А", acy: "а", AElig: "Æ", aelig: "æ", af: "\u2061", Afr: "𝔄", afr: "𝔞", Agrave: "À", agrave: "à", alefsym: "ℵ", aleph: "ℵ", Alpha: "Α", alpha: "α", Amacr: "Ā", amacr: "ā", amalg: "⨿", AMP: "&", amp: "&", And: "⩓", and: "∧", andand: "⩕", andd: "⩜", andslope: "⩘", andv: "⩚", ang: "∠", ange: "⦤", angle: "∠", angmsd: "∡", angmsdaa: "⦨", angmsdab: "⦩", angmsdac: "⦪", angmsdad: "⦫", angmsdae: "⦬", angmsdaf: "⦭", angmsdag: "⦮", angmsdah: "⦯", angrt: "∟", angrtvb: "⊾", angrtvbd: "⦝", angsph: "∢", angst: "Å", angzarr: "⍼", Aogon: "Ą", aogon: "ą", Aopf: "𝔸", aopf: "𝕒", ap: "≈", apacir: "⩯", apE: "⩰", ape: "≊", apid: "≋", apos: "'", ApplyFunction: "\u2061", approx: "≈", approxeq: "≊", Aring: "Å", aring: "å", Ascr: "𝒜", ascr: "𝒶", Assign: "≔", ast: "*", asymp: "≈", asympeq: "≍", Atilde: "Ã", atilde: "ã", Auml: "Ä", auml: "ä", awconint: "∳", awint: "⨑", backcong: "≌", backepsilon: "϶", backprime: "‵", backsim: "∽", backsimeq: "⋍", Backslash: "∖", Barv: "⫧", barvee: "⊽", Barwed: "⌆", barwed: "⌅", barwedge: "⌅", bbrk: "⎵", bbrktbrk: "⎶", bcong: "≌", Bcy: "Б", bcy: "б", bdquo: "„", becaus: "∵", Because: "∵", because: "∵", bemptyv: "⦰", bepsi: "϶", bernou: "ℬ", Bernoullis: "ℬ", Beta: "Β", beta: "β", beth: "ℶ", between: "≬", Bfr: "𝔅", bfr: "𝔟", bigcap: "⋂", bigcirc: "◯", bigcup: "⋃", bigodot: "⨀", bigoplus: "⨁", bigotimes: "⨂", bigsqcup: "⨆", bigstar: "★", bigtriangledown: "▽", bigtriangleup: "△", biguplus: "⨄", bigvee: "⋁", bigwedge: "⋀", bkarow: "⤍", blacklozenge: "⧫", blacksquare: "▪", blacktriangle: "▴", blacktriangledown: "▾", blacktriangleleft: "◂", blacktriangleright: "▸", blank: "␣", blk12: "▒", blk14: "░", blk34: "▓", block: "█", bne: "=⃥", bnequiv: "≡⃥", bNot: "⫭", bnot: "⌐", Bopf: "𝔹", bopf: "𝕓", bot: "⊥", bottom: "⊥", bowtie: "⋈", boxbox: "⧉", boxDL: "╗", boxDl: "╖", boxdL: "╕", boxdl: "┐", boxDR: "╔", boxDr: "╓", boxdR: "╒", boxdr: "┌", boxH: "═", boxh: "─", boxHD: "╦", boxHd: "╤", boxhD: "╥", boxhd: "┬", boxHU: "╩", boxHu: "╧", boxhU: "╨", boxhu: "┴", boxminus: "⊟", boxplus: "⊞", boxtimes: "⊠", boxUL: "╝", boxUl: "╜", boxuL: "╛", boxul: "┘", boxUR: "╚", boxUr: "╙", boxuR: "╘", boxur: "└", boxV: "║", boxv: "│", boxVH: "╬", boxVh: "╫", boxvH: "╪", boxvh: "┼", boxVL: "╣", boxVl: "╢", boxvL: "╡", boxvl: "┤", boxVR: "╠", boxVr: "╟", boxvR: "╞", boxvr: "├", bprime: "‵", Breve: "˘", breve: "˘", brvbar: "¦", Bscr: "ℬ", bscr: "𝒷", bsemi: "⁏", bsim: "∽", bsime: "⋍", bsol: "\\", bsolb: "⧅", bsolhsub: "⟈", bull: "•", bullet: "•", bump: "≎", bumpE: "⪮", bumpe: "≏", Bumpeq: "≎", bumpeq: "≏", Cacute: "Ć", cacute: "ć", Cap: "⋒", cap: "∩", capand: "⩄", capbrcup: "⩉", capcap: "⩋", capcup: "⩇", capdot: "⩀", CapitalDifferentialD: "ⅅ", caps: "∩︀", caret: "⁁", caron: "ˇ", Cayleys: "ℭ", ccaps: "⩍", Ccaron: "Č", ccaron: "č", Ccedil: "Ç", ccedil: "ç", Ccirc: "Ĉ", ccirc: "ĉ", Cconint: "∰", ccups: "⩌", ccupssm: "⩐", Cdot: "Ċ", cdot: "ċ", cedil: "¸", Cedilla: "¸", cemptyv: "⦲", cent: "¢", CenterDot: "·", centerdot: "·", Cfr: "ℭ", cfr: "𝔠", CHcy: "Ч", chcy: "ч", check: "✓", checkmark: "✓", Chi: "Χ", chi: "χ", cir: "○", circ: "ˆ", circeq: "≗", circlearrowleft: "↺", circlearrowright: "↻", circledast: "⊛", circledcirc: "⊚", circleddash: "⊝", CircleDot: "⊙", circledR: "®", circledS: "Ⓢ", CircleMinus: "⊖", CirclePlus: "⊕", CircleTimes: "⊗", cirE: "⧃", cire: "≗", cirfnint: "⨐", cirmid: "⫯", cirscir: "⧂", ClockwiseContourIntegral: "∲", CloseCurlyDoubleQuote: "”", CloseCurlyQuote: "’", clubs: "♣", clubsuit: "♣", Colon: "∷", colon: ":", Colone: "⩴", colone: "≔", coloneq: "≔", comma: ",", commat: "@", comp: "∁", compfn: "∘", complement: "∁", complexes: "ℂ", cong: "≅", congdot: "⩭", Congruent: "≡", Conint: "∯", conint: "∮", ContourIntegral: "∮", Copf: "ℂ", copf: "𝕔", coprod: "∐", Coproduct: "∐", COPY: "©", copy: "©", copysr: "℗", CounterClockwiseContourIntegral: "∳", crarr: "↵", Cross: "⨯", cross: "✗", Cscr: "𝒞", cscr: "𝒸", csub: "⫏", csube: "⫑", csup: "⫐", csupe: "⫒", ctdot: "⋯", cudarrl: "⤸", cudarrr: "⤵", cuepr: "⋞", cuesc: "⋟", cularr: "↶", cularrp: "⤽", Cup: "⋓", cup: "∪", cupbrcap: "⩈", CupCap: "≍", cupcap: "⩆", cupcup: "⩊", cupdot: "⊍", cupor: "⩅", cups: "∪︀", curarr: "↷", curarrm: "⤼", curlyeqprec: "⋞", curlyeqsucc: "⋟", curlyvee: "⋎", curlywedge: "⋏", curren: "¤", curvearrowleft: "↶", curvearrowright: "↷", cuvee: "⋎", cuwed: "⋏", cwconint: "∲", cwint: "∱", cylcty: "⌭", Dagger: "‡", dagger: "†", daleth: "ℸ", Darr: "↡", dArr: "⇓", darr: "↓", dash: "‐", Dashv: "⫤", dashv: "⊣", dbkarow: "⤏", dblac: "˝", Dcaron: "Ď", dcaron: "ď", Dcy: "Д", dcy: "д", DD: "ⅅ", dd: "ⅆ", ddagger: "‡", ddarr: "⇊", DDotrahd: "⤑", ddotseq: "⩷", deg: "°", Del: "∇", Delta: "Δ", delta: "δ", demptyv: "⦱", dfisht: "⥿", Dfr: "𝔇", dfr: "𝔡", dHar: "⥥", dharl: "⇃", dharr: "⇂", DiacriticalAcute: "´", DiacriticalDot: "˙", DiacriticalDoubleAcute: "˝", DiacriticalGrave: "`", DiacriticalTilde: "˜", diam: "⋄", Diamond: "⋄", diamond: "⋄", diamondsuit: "♦", diams: "♦", die: "¨", DifferentialD: "ⅆ", digamma: "ϝ", disin: "⋲", div: "÷", divide: "÷", divideontimes: "⋇", divonx: "⋇", DJcy: "Ђ", djcy: "ђ", dlcorn: "⌞", dlcrop: "⌍", dollar: "$", Dopf: "𝔻", dopf: "𝕕", Dot: "¨", dot: "˙", DotDot: "⃜", doteq: "≐", doteqdot: "≑", DotEqual: "≐", dotminus: "∸", dotplus: "∔", dotsquare: "⊡", doublebarwedge: "⌆", DoubleContourIntegral: "∯", DoubleDot: "¨", DoubleDownArrow: "⇓", DoubleLeftArrow: "⇐", DoubleLeftRightArrow: "⇔", DoubleLeftTee: "⫤", DoubleLongLeftArrow: "⟸", DoubleLongLeftRightArrow: "⟺", DoubleLongRightArrow: "⟹", DoubleRightArrow: "⇒", DoubleRightTee: "⊨", DoubleUpArrow: "⇑", DoubleUpDownArrow: "⇕", DoubleVerticalBar: "∥", DownArrow: "↓", Downarrow: "⇓", downarrow: "↓", DownArrowBar: "⤓", DownArrowUpArrow: "⇵", DownBreve: "̑", downdownarrows: "⇊", downharpoonleft: "⇃", downharpoonright: "⇂", DownLeftRightVector: "⥐", DownLeftTeeVector: "⥞", DownLeftVector: "↽", DownLeftVectorBar: "⥖", DownRightTeeVector: "⥟", DownRightVector: "⇁", DownRightVectorBar: "⥗", DownTee: "⊤", DownTeeArrow: "↧", drbkarow: "⤐", drcorn: "⌟", drcrop: "⌌", Dscr: "𝒟", dscr: "𝒹", DScy: "Ѕ", dscy: "ѕ", dsol: "⧶", Dstrok: "Đ", dstrok: "đ", dtdot: "⋱", dtri: "▿", dtrif: "▾", duarr: "⇵", duhar: "⥯", dwangle: "⦦", DZcy: "Џ", dzcy: "џ", dzigrarr: "⟿", Eacute: "É", eacute: "é", easter: "⩮", Ecaron: "Ě", ecaron: "ě", ecir: "≖", Ecirc: "Ê", ecirc: "ê", ecolon: "≕", Ecy: "Э", ecy: "э", eDDot: "⩷", Edot: "Ė", eDot: "≑", edot: "ė", ee: "ⅇ", efDot: "≒", Efr: "𝔈", efr: "𝔢", eg: "⪚", Egrave: "È", egrave: "è", egs: "⪖", egsdot: "⪘", el: "⪙", Element: "∈", elinters: "⏧", ell: "ℓ", els: "⪕", elsdot: "⪗", Emacr: "Ē", emacr: "ē", empty: "∅", emptyset: "∅", EmptySmallSquare: "◻", emptyv: "∅", EmptyVerySmallSquare: "▫", emsp: " ", emsp13: " ", emsp14: " ", ENG: "Ŋ", eng: "ŋ", ensp: " ", Eogon: "Ę", eogon: "ę", Eopf: "𝔼", eopf: "𝕖", epar: "⋕", eparsl: "⧣", eplus: "⩱", epsi: "ε", Epsilon: "Ε", epsilon: "ε", epsiv: "ϵ", eqcirc: "≖", eqcolon: "≕", eqsim: "≂", eqslantgtr: "⪖", eqslantless: "⪕", Equal: "⩵", equals: "=", EqualTilde: "≂", equest: "≟", Equilibrium: "⇌", equiv: "≡", equivDD: "⩸", eqvparsl: "⧥", erarr: "⥱", erDot: "≓", Escr: "ℰ", escr: "ℯ", esdot: "≐", Esim: "⩳", esim: "≂", Eta: "Η", eta: "η", ETH: "Ð", eth: "ð", Euml: "Ë", euml: "ë", euro: "€", excl: "!", exist: "∃", Exists: "∃", expectation: "ℰ", ExponentialE: "ⅇ", exponentiale: "ⅇ", fallingdotseq: "≒", Fcy: "Ф", fcy: "ф", female: "♀", ffilig: "ffi", fflig: "ff", ffllig: "ffl", Ffr: "𝔉", ffr: "𝔣", filig: "fi", FilledSmallSquare: "◼", FilledVerySmallSquare: "▪", fjlig: "fj", flat: "♭", fllig: "fl", fltns: "▱", fnof: "ƒ", Fopf: "𝔽", fopf: "𝕗", ForAll: "∀", forall: "∀", fork: "⋔", forkv: "⫙", Fouriertrf: "ℱ", fpartint: "⨍", frac12: "½", frac13: "⅓", frac14: "¼", frac15: "⅕", frac16: "⅙", frac18: "⅛", frac23: "⅔", frac25: "⅖", frac34: "¾", frac35: "⅗", frac38: "⅜", frac45: "⅘", frac56: "⅚", frac58: "⅝", frac78: "⅞", frasl: "⁄", frown: "⌢", Fscr: "ℱ", fscr: "𝒻", gacute: "ǵ", Gamma: "Γ", gamma: "γ", Gammad: "Ϝ", gammad: "ϝ", gap: "⪆", Gbreve: "Ğ", gbreve: "ğ", Gcedil: "Ģ", Gcirc: "Ĝ", gcirc: "ĝ", Gcy: "Г", gcy: "г", Gdot: "Ġ", gdot: "ġ", gE: "≧", ge: "≥", gEl: "⪌", gel: "⋛", geq: "≥", geqq: "≧", geqslant: "⩾", ges: "⩾", gescc: "⪩", gesdot: "⪀", gesdoto: "⪂", gesdotol: "⪄", gesl: "⋛︀", gesles: "⪔", Gfr: "𝔊", gfr: "𝔤", Gg: "⋙", gg: "≫", ggg: "⋙", gimel: "ℷ", GJcy: "Ѓ", gjcy: "ѓ", gl: "≷", gla: "⪥", glE: "⪒", glj: "⪤", gnap: "⪊", gnapprox: "⪊", gnE: "≩", gne: "⪈", gneq: "⪈", gneqq: "≩", gnsim: "⋧", Gopf: "𝔾", gopf: "𝕘", grave: "`", GreaterEqual: "≥", GreaterEqualLess: "⋛", GreaterFullEqual: "≧", GreaterGreater: "⪢", GreaterLess: "≷", GreaterSlantEqual: "⩾", GreaterTilde: "≳", Gscr: "𝒢", gscr: "ℊ", gsim: "≳", gsime: "⪎", gsiml: "⪐", GT: ">", Gt: "≫", gt: ">", gtcc: "⪧", gtcir: "⩺", gtdot: "⋗", gtlPar: "⦕", gtquest: "⩼", gtrapprox: "⪆", gtrarr: "⥸", gtrdot: "⋗", gtreqless: "⋛", gtreqqless: "⪌", gtrless: "≷", gtrsim: "≳", gvertneqq: "≩︀", gvnE: "≩︀", Hacek: "ˇ", hairsp: " ", half: "½", hamilt: "ℋ", HARDcy: "Ъ", hardcy: "ъ", hArr: "⇔", harr: "↔", harrcir: "⥈", harrw: "↭", Hat: "^", hbar: "ℏ", Hcirc: "Ĥ", hcirc: "ĥ", hearts: "♥", heartsuit: "♥", hellip: "…", hercon: "⊹", Hfr: "ℌ", hfr: "𝔥", HilbertSpace: "ℋ", hksearow: "⤥", hkswarow: "⤦", hoarr: "⇿", homtht: "∻", hookleftarrow: "↩", hookrightarrow: "↪", Hopf: "ℍ", hopf: "𝕙", horbar: "―", HorizontalLine: "─", Hscr: "ℋ", hscr: "𝒽", hslash: "ℏ", Hstrok: "Ħ", hstrok: "ħ", HumpDownHump: "≎", HumpEqual: "≏", hybull: "⁃", hyphen: "‐", Iacute: "Í", iacute: "í", ic: "\u2063", Icirc: "Î", icirc: "î", Icy: "И", icy: "и", Idot: "İ", IEcy: "Е", iecy: "е", iexcl: "¡", iff: "⇔", Ifr: "ℑ", ifr: "𝔦", Igrave: "Ì", igrave: "ì", ii: "ⅈ", iiiint: "⨌", iiint: "∭", iinfin: "⧜", iiota: "℩", IJlig: "IJ", ijlig: "ij", Im: "ℑ", Imacr: "Ī", imacr: "ī", image: "ℑ", ImaginaryI: "ⅈ", imagline: "ℐ", imagpart: "ℑ", imath: "ı", imof: "⊷", imped: "Ƶ", Implies: "⇒", in: "∈", incare: "℅", infin: "∞", infintie: "⧝", inodot: "ı", Int: "∬", int: "∫", intcal: "⊺", integers: "ℤ", Integral: "∫", intercal: "⊺", Intersection: "⋂", intlarhk: "⨗", intprod: "⨼", InvisibleComma: "\u2063", InvisibleTimes: "\u2062", IOcy: "Ё", iocy: "ё", Iogon: "Į", iogon: "į", Iopf: "𝕀", iopf: "𝕚", Iota: "Ι", iota: "ι", iprod: "⨼", iquest: "¿", Iscr: "ℐ", iscr: "𝒾", isin: "∈", isindot: "⋵", isinE: "⋹", isins: "⋴", isinsv: "⋳", isinv: "∈", it: "\u2062", Itilde: "Ĩ", itilde: "ĩ", Iukcy: "І", iukcy: "і", Iuml: "Ï", iuml: "ï", Jcirc: "Ĵ", jcirc: "ĵ", Jcy: "Й", jcy: "й", Jfr: "𝔍", jfr: "𝔧", jmath: "ȷ", Jopf: "𝕁", jopf: "𝕛", Jscr: "𝒥", jscr: "𝒿", Jsercy: "Ј", jsercy: "ј", Jukcy: "Є", jukcy: "є", Kappa: "Κ", kappa: "κ", kappav: "ϰ", Kcedil: "Ķ", kcedil: "ķ", Kcy: "К", kcy: "к", Kfr: "𝔎", kfr: "𝔨", kgreen: "ĸ", KHcy: "Х", khcy: "х", KJcy: "Ќ", kjcy: "ќ", Kopf: "𝕂", kopf: "𝕜", Kscr: "𝒦", kscr: "𝓀", lAarr: "⇚", Lacute: "Ĺ", lacute: "ĺ", laemptyv: "⦴", lagran: "ℒ", Lambda: "Λ", lambda: "λ", Lang: "⟪", lang: "⟨", langd: "⦑", langle: "⟨", lap: "⪅", Laplacetrf: "ℒ", laquo: "«", Larr: "↞", lArr: "⇐", larr: "←", larrb: "⇤", larrbfs: "⤟", larrfs: "⤝", larrhk: "↩", larrlp: "↫", larrpl: "⤹", larrsim: "⥳", larrtl: "↢", lat: "⪫", lAtail: "⤛", latail: "⤙", late: "⪭", lates: "⪭︀", lBarr: "⤎", lbarr: "⤌", lbbrk: "❲", lbrace: "{", lbrack: "[", lbrke: "⦋", lbrksld: "⦏", lbrkslu: "⦍", Lcaron: "Ľ", lcaron: "ľ", Lcedil: "Ļ", lcedil: "ļ", lceil: "⌈", lcub: "{", Lcy: "Л", lcy: "л", ldca: "⤶", ldquo: "“", ldquor: "„", ldrdhar: "⥧", ldrushar: "⥋", ldsh: "↲", lE: "≦", le: "≤", LeftAngleBracket: "⟨", LeftArrow: "←", Leftarrow: "⇐", leftarrow: "←", LeftArrowBar: "⇤", LeftArrowRightArrow: "⇆", leftarrowtail: "↢", LeftCeiling: "⌈", LeftDoubleBracket: "⟦", LeftDownTeeVector: "⥡", LeftDownVector: "⇃", LeftDownVectorBar: "⥙", LeftFloor: "⌊", leftharpoondown: "↽", leftharpoonup: "↼", leftleftarrows: "⇇", LeftRightArrow: "↔", Leftrightarrow: "⇔", leftrightarrow: "↔", leftrightarrows: "⇆", leftrightharpoons: "⇋", leftrightsquigarrow: "↭", LeftRightVector: "⥎", LeftTee: "⊣", LeftTeeArrow: "↤", LeftTeeVector: "⥚", leftthreetimes: "⋋", LeftTriangle: "⊲", LeftTriangleBar: "⧏", LeftTriangleEqual: "⊴", LeftUpDownVector: "⥑", LeftUpTeeVector: "⥠", LeftUpVector: "↿", LeftUpVectorBar: "⥘", LeftVector: "↼", LeftVectorBar: "⥒", lEg: "⪋", leg: "⋚", leq: "≤", leqq: "≦", leqslant: "⩽", les: "⩽", lescc: "⪨", lesdot: "⩿", lesdoto: "⪁", lesdotor: "⪃", lesg: "⋚︀", lesges: "⪓", lessapprox: "⪅", lessdot: "⋖", lesseqgtr: "⋚", lesseqqgtr: "⪋", LessEqualGreater: "⋚", LessFullEqual: "≦", LessGreater: "≶", lessgtr: "≶", LessLess: "⪡", lesssim: "≲", LessSlantEqual: "⩽", LessTilde: "≲", lfisht: "⥼", lfloor: "⌊", Lfr: "𝔏", lfr: "𝔩", lg: "≶", lgE: "⪑", lHar: "⥢", lhard: "↽", lharu: "↼", lharul: "⥪", lhblk: "▄", LJcy: "Љ", ljcy: "љ", Ll: "⋘", ll: "≪", llarr: "⇇", llcorner: "⌞", Lleftarrow: "⇚", llhard: "⥫", lltri: "◺", Lmidot: "Ŀ", lmidot: "ŀ", lmoust: "⎰", lmoustache: "⎰", lnap: "⪉", lnapprox: "⪉", lnE: "≨", lne: "⪇", lneq: "⪇", lneqq: "≨", lnsim: "⋦", loang: "⟬", loarr: "⇽", lobrk: "⟦", LongLeftArrow: "⟵", Longleftarrow: "⟸", longleftarrow: "⟵", LongLeftRightArrow: "⟷", Longleftrightarrow: "⟺", longleftrightarrow: "⟷", longmapsto: "⟼", LongRightArrow: "⟶", Longrightarrow: "⟹", longrightarrow: "⟶", looparrowleft: "↫", looparrowright: "↬", lopar: "⦅", Lopf: "𝕃", lopf: "𝕝", loplus: "⨭", lotimes: "⨴", lowast: "∗", lowbar: "_", LowerLeftArrow: "↙", LowerRightArrow: "↘", loz: "◊", lozenge: "◊", lozf: "⧫", lpar: "(", lparlt: "⦓", lrarr: "⇆", lrcorner: "⌟", lrhar: "⇋", lrhard: "⥭", lrm: "\u200e", lrtri: "⊿", lsaquo: "‹", Lscr: "ℒ", lscr: "𝓁", Lsh: "↰", lsh: "↰", lsim: "≲", lsime: "⪍", lsimg: "⪏", lsqb: "[", lsquo: "‘", lsquor: "‚", Lstrok: "Ł", lstrok: "ł", LT: "<", Lt: "≪", lt: "<", ltcc: "⪦", ltcir: "⩹", ltdot: "⋖", lthree: "⋋", ltimes: "⋉", ltlarr: "⥶", ltquest: "⩻", ltri: "◃", ltrie: "⊴", ltrif: "◂", ltrPar: "⦖", lurdshar: "⥊", luruhar: "⥦", lvertneqq: "≨︀", lvnE: "≨︀", macr: "¯", male: "♂", malt: "✠", maltese: "✠", Map: "⤅", map: "↦", mapsto: "↦", mapstodown: "↧", mapstoleft: "↤", mapstoup: "↥", marker: "▮", mcomma: "⨩", Mcy: "М", mcy: "м", mdash: "—", mDDot: "∺", measuredangle: "∡", MediumSpace: " ", Mellintrf: "ℳ", Mfr: "𝔐", mfr: "𝔪", mho: "℧", micro: "µ", mid: "∣", midast: "*", midcir: "⫰", middot: "·", minus: "−", minusb: "⊟", minusd: "∸", minusdu: "⨪", MinusPlus: "∓", mlcp: "⫛", mldr: "…", mnplus: "∓", models: "⊧", Mopf: "𝕄", mopf: "𝕞", mp: "∓", Mscr: "ℳ", mscr: "𝓂", mstpos: "∾", Mu: "Μ", mu: "μ", multimap: "⊸", mumap: "⊸", nabla: "∇", Nacute: "Ń", nacute: "ń", nang: "∠⃒", nap: "≉", napE: "⩰̸", napid: "≋̸", napos: "ʼn", napprox: "≉", natur: "♮", natural: "♮", naturals: "ℕ", nbsp: " ", nbump: "≎̸", nbumpe: "≏̸", ncap: "⩃", Ncaron: "Ň", ncaron: "ň", Ncedil: "Ņ", ncedil: "ņ", ncong: "≇", ncongdot: "⩭̸", ncup: "⩂", Ncy: "Н", ncy: "н", ndash: "–", ne: "≠", nearhk: "⤤", neArr: "⇗", nearr: "↗", nearrow: "↗", nedot: "≐̸", NegativeMediumSpace: "", NegativeThickSpace: "", NegativeThinSpace: "", NegativeVeryThinSpace: "", nequiv: "≢", nesear: "⤨", nesim: "≂̸", NestedGreaterGreater: "≫", NestedLessLess: "≪", NewLine: "\u000a", nexist: "∄", nexists: "∄", Nfr: "𝔑", nfr: "𝔫", ngE: "≧̸", nge: "≱", ngeq: "≱", ngeqq: "≧̸", ngeqslant: "⩾̸", nges: "⩾̸", nGg: "⋙̸", ngsim: "≵", nGt: "≫⃒", ngt: "≯", ngtr: "≯", nGtv: "≫̸", nhArr: "⇎", nharr: "↮", nhpar: "⫲", ni: "∋", nis: "⋼", nisd: "⋺", niv: "∋", NJcy: "Њ", njcy: "њ", nlArr: "⇍", nlarr: "↚", nldr: "‥", nlE: "≦̸", nle: "≰", nLeftarrow: "⇍", nleftarrow: "↚", nLeftrightarrow: "⇎", nleftrightarrow: "↮", nleq: "≰", nleqq: "≦̸", nleqslant: "⩽̸", nles: "⩽̸", nless: "≮", nLl: "⋘̸", nlsim: "≴", nLt: "≪⃒", nlt: "≮", nltri: "⋪", nltrie: "⋬", nLtv: "≪̸", nmid: "∤", NoBreak: "\u2060", NonBreakingSpace: " ", Nopf: "ℕ", nopf: "𝕟", Not: "⫬", not: "¬", NotCongruent: "≢", NotCupCap: "≭", NotDoubleVerticalBar: "∦", NotElement: "∉", NotEqual: "≠", NotEqualTilde: "≂̸", NotExists: "∄", NotGreater: "≯", NotGreaterEqual: "≱", NotGreaterFullEqual: "≧̸", NotGreaterGreater: "≫̸", NotGreaterLess: "≹", NotGreaterSlantEqual: "⩾̸", NotGreaterTilde: "≵", NotHumpDownHump: "≎̸", NotHumpEqual: "≏̸", notin: "∉", notindot: "⋵̸", notinE: "⋹̸", notinva: "∉", notinvb: "⋷", notinvc: "⋶", NotLeftTriangle: "⋪", NotLeftTriangleBar: "⧏̸", NotLeftTriangleEqual: "⋬", NotLess: "≮", NotLessEqual: "≰", NotLessGreater: "≸", NotLessLess: "≪̸", NotLessSlantEqual: "⩽̸", NotLessTilde: "≴", NotNestedGreaterGreater: "⪢̸", NotNestedLessLess: "⪡̸", notni: "∌", notniva: "∌", notnivb: "⋾", notnivc: "⋽", NotPrecedes: "⊀", NotPrecedesEqual: "⪯̸", NotPrecedesSlantEqual: "⋠", NotReverseElement: "∌", NotRightTriangle: "⋫", NotRightTriangleBar: "⧐̸", NotRightTriangleEqual: "⋭", NotSquareSubset: "⊏̸", NotSquareSubsetEqual: "⋢", NotSquareSuperset: "⊐̸", NotSquareSupersetEqual: "⋣", NotSubset: "⊂⃒", NotSubsetEqual: "⊈", NotSucceeds: "⊁", NotSucceedsEqual: "⪰̸", NotSucceedsSlantEqual: "⋡", NotSucceedsTilde: "≿̸", NotSuperset: "⊃⃒", NotSupersetEqual: "⊉", NotTilde: "≁", NotTildeEqual: "≄", NotTildeFullEqual: "≇", NotTildeTilde: "≉", NotVerticalBar: "∤", npar: "∦", nparallel: "∦", nparsl: "⫽⃥", npart: "∂̸", npolint: "⨔", npr: "⊀", nprcue: "⋠", npre: "⪯̸", nprec: "⊀", npreceq: "⪯̸", nrArr: "⇏", nrarr: "↛", nrarrc: "⤳̸", nrarrw: "↝̸", nRightarrow: "⇏", nrightarrow: "↛", nrtri: "⋫", nrtrie: "⋭", nsc: "⊁", nsccue: "⋡", nsce: "⪰̸", Nscr: "𝒩", nscr: "𝓃", nshortmid: "∤", nshortparallel: "∦", nsim: "≁", nsime: "≄", nsimeq: "≄", nsmid: "∤", nspar: "∦", nsqsube: "⋢", nsqsupe: "⋣", nsub: "⊄", nsubE: "⫅̸", nsube: "⊈", nsubset: "⊂⃒", nsubseteq: "⊈", nsubseteqq: "⫅̸", nsucc: "⊁", nsucceq: "⪰̸", nsup: "⊅", nsupE: "⫆̸", nsupe: "⊉", nsupset: "⊃⃒", nsupseteq: "⊉", nsupseteqq: "⫆̸", ntgl: "≹", Ntilde: "Ñ", ntilde: "ñ", ntlg: "≸", ntriangleleft: "⋪", ntrianglelefteq: "⋬", ntriangleright: "⋫", ntrianglerighteq: "⋭", Nu: "Ν", nu: "ν", num: "#", numero: "№", numsp: " ", nvap: "≍⃒", nVDash: "⊯", nVdash: "⊮", nvDash: "⊭", nvdash: "⊬", nvge: "≥⃒", nvgt: ">⃒", nvHarr: "⤄", nvinfin: "⧞", nvlArr: "⤂", nvle: "≤⃒", nvlt: "<⃒", nvltrie: "⊴⃒", nvrArr: "⤃", nvrtrie: "⊵⃒", nvsim: "∼⃒", nwarhk: "⤣", nwArr: "⇖", nwarr: "↖", nwarrow: "↖", nwnear: "⤧", Oacute: "Ó", oacute: "ó", oast: "⊛", ocir: "⊚", Ocirc: "Ô", ocirc: "ô", Ocy: "О", ocy: "о", odash: "⊝", Odblac: "Ő", odblac: "ő", odiv: "⨸", odot: "⊙", odsold: "⦼", OElig: "Œ", oelig: "œ", ofcir: "⦿", Ofr: "𝔒", ofr: "𝔬", ogon: "˛", Ograve: "Ò", ograve: "ò", ogt: "⧁", ohbar: "⦵", ohm: "Ω", oint: "∮", olarr: "↺", olcir: "⦾", olcross: "⦻", oline: "‾", olt: "⧀", Omacr: "Ō", omacr: "ō", Omega: "Ω", omega: "ω", Omicron: "Ο", omicron: "ο", omid: "⦶", ominus: "⊖", Oopf: "𝕆", oopf: "𝕠", opar: "⦷", OpenCurlyDoubleQuote: "“", OpenCurlyQuote: "‘", operp: "⦹", oplus: "⊕", Or: "⩔", or: "∨", orarr: "↻", ord: "⩝", order: "ℴ", orderof: "ℴ", ordf: "ª", ordm: "º", origof: "⊶", oror: "⩖", orslope: "⩗", orv: "⩛", oS: "Ⓢ", Oscr: "𝒪", oscr: "ℴ", Oslash: "Ø", oslash: "ø", osol: "⊘", Otilde: "Õ", otilde: "õ", Otimes: "⨷", otimes: "⊗", otimesas: "⨶", Ouml: "Ö", ouml: "ö", ovbar: "⌽", OverBar: "‾", OverBrace: "⏞", OverBracket: "⎴", OverParenthesis: "⏜", par: "∥", para: "¶", parallel: "∥", parsim: "⫳", parsl: "⫽", part: "∂", PartialD: "∂", Pcy: "П", pcy: "п", percnt: "%", period: ".", permil: "‰", perp: "⊥", pertenk: "‱", Pfr: "𝔓", pfr: "𝔭", Phi: "Φ", phi: "φ", phiv: "ϕ", phmmat: "ℳ", phone: "☎", Pi: "Π", pi: "π", pitchfork: "⋔", piv: "ϖ", planck: "ℏ", planckh: "ℎ", plankv: "ℏ", plus: "+", plusacir: "⨣", plusb: "⊞", pluscir: "⨢", plusdo: "∔", plusdu: "⨥", pluse: "⩲", PlusMinus: "±", plusmn: "±", plussim: "⨦", plustwo: "⨧", pm: "±", Poincareplane: "ℌ", pointint: "⨕", Popf: "ℙ", popf: "𝕡", pound: "£", Pr: "⪻", pr: "≺", prap: "⪷", prcue: "≼", prE: "⪳", pre: "⪯", prec: "≺", precapprox: "⪷", preccurlyeq: "≼", Precedes: "≺", PrecedesEqual: "⪯", PrecedesSlantEqual: "≼", PrecedesTilde: "≾", preceq: "⪯", precnapprox: "⪹", precneqq: "⪵", precnsim: "⋨", precsim: "≾", Prime: "″", prime: "′", primes: "ℙ", prnap: "⪹", prnE: "⪵", prnsim: "⋨", prod: "∏", Product: "∏", profalar: "⌮", profline: "⌒", profsurf: "⌓", prop: "∝", Proportion: "∷", Proportional: "∝", propto: "∝", prsim: "≾", prurel: "⊰", Pscr: "𝒫", pscr: "𝓅", Psi: "Ψ", psi: "ψ", puncsp: " ", Qfr: "𝔔", qfr: "𝔮", qint: "⨌", Qopf: "ℚ", qopf: "𝕢", qprime: "⁗", Qscr: "𝒬", qscr: "𝓆", quaternions: "ℍ", quatint: "⨖", quest: "?", questeq: "≟", QUOT: "\"", quot: "\"", rAarr: "⇛", race: "∽̱", Racute: "Ŕ", racute: "ŕ", radic: "√", raemptyv: "⦳", Rang: "⟫", rang: "⟩", rangd: "⦒", range: "⦥", rangle: "⟩", raquo: "»", Rarr: "↠", rArr: "⇒", rarr: "→", rarrap: "⥵", rarrb: "⇥", rarrbfs: "⤠", rarrc: "⤳", rarrfs: "⤞", rarrhk: "↪", rarrlp: "↬", rarrpl: "⥅", rarrsim: "⥴", Rarrtl: "⤖", rarrtl: "↣", rarrw: "↝", rAtail: "⤜", ratail: "⤚", ratio: "∶", rationals: "ℚ", RBarr: "⤐", rBarr: "⤏", rbarr: "⤍", rbbrk: "❳", rbrace: "}", rbrack: "]", rbrke: "⦌", rbrksld: "⦎", rbrkslu: "⦐", Rcaron: "Ř", rcaron: "ř", Rcedil: "Ŗ", rcedil: "ŗ", rceil: "⌉", rcub: "}", Rcy: "Р", rcy: "р", rdca: "⤷", rdldhar: "⥩", rdquo: "”", rdquor: "”", rdsh: "↳", Re: "ℜ", real: "ℜ", realine: "ℛ", realpart: "ℜ", reals: "ℝ", rect: "▭", REG: "®", reg: "®", ReverseElement: "∋", ReverseEquilibrium: "⇋", ReverseUpEquilibrium: "⥯", rfisht: "⥽", rfloor: "⌋", Rfr: "ℜ", rfr: "𝔯", rHar: "⥤", rhard: "⇁", rharu: "⇀", rharul: "⥬", Rho: "Ρ", rho: "ρ", rhov: "ϱ", RightAngleBracket: "⟩", RightArrow: "→", Rightarrow: "⇒", rightarrow: "→", RightArrowBar: "⇥", RightArrowLeftArrow: "⇄", rightarrowtail: "↣", RightCeiling: "⌉", RightDoubleBracket: "⟧", RightDownTeeVector: "⥝", RightDownVector: "⇂", RightDownVectorBar: "⥕", RightFloor: "⌋", rightharpoondown: "⇁", rightharpoonup: "⇀", rightleftarrows: "⇄", rightleftharpoons: "⇌", rightrightarrows: "⇉", rightsquigarrow: "↝", RightTee: "⊢", RightTeeArrow: "↦", RightTeeVector: "⥛", rightthreetimes: "⋌", RightTriangle: "⊳", RightTriangleBar: "⧐", RightTriangleEqual: "⊵", RightUpDownVector: "⥏", RightUpTeeVector: "⥜", RightUpVector: "↾", RightUpVectorBar: "⥔", RightVector: "⇀", RightVectorBar: "⥓", ring: "˚", risingdotseq: "≓", rlarr: "⇄", rlhar: "⇌", rlm: "\u200f", rmoust: "⎱", rmoustache: "⎱", rnmid: "⫮", roang: "⟭", roarr: "⇾", robrk: "⟧", ropar: "⦆", Ropf: "ℝ", ropf: "𝕣", roplus: "⨮", rotimes: "⨵", RoundImplies: "⥰", rpar: ")", rpargt: "⦔", rppolint: "⨒", rrarr: "⇉", Rrightarrow: "⇛", rsaquo: "›", Rscr: "ℛ", rscr: "𝓇", Rsh: "↱", rsh: "↱", rsqb: "]", rsquo: "’", rsquor: "’", rthree: "⋌", rtimes: "⋊", rtri: "▹", rtrie: "⊵", rtrif: "▸", rtriltri: "⧎", RuleDelayed: "⧴", ruluhar: "⥨", rx: "℞", Sacute: "Ś", sacute: "ś", sbquo: "‚", Sc: "⪼", sc: "≻", scap: "⪸", Scaron: "Š", scaron: "š", sccue: "≽", scE: "⪴", sce: "⪰", Scedil: "Ş", scedil: "ş", Scirc: "Ŝ", scirc: "ŝ", scnap: "⪺", scnE: "⪶", scnsim: "⋩", scpolint: "⨓", scsim: "≿", Scy: "С", scy: "с", sdot: "⋅", sdotb: "⊡", sdote: "⩦", searhk: "⤥", seArr: "⇘", searr: "↘", searrow: "↘", sect: "§", semi: ";", seswar: "⤩", setminus: "∖", setmn: "∖", sext: "✶", Sfr: "𝔖", sfr: "𝔰", sfrown: "⌢", sharp: "♯", SHCHcy: "Щ", shchcy: "щ", SHcy: "Ш", shcy: "ш", ShortDownArrow: "↓", ShortLeftArrow: "←", shortmid: "∣", shortparallel: "∥", ShortRightArrow: "→", ShortUpArrow: "↑", shy: "\u00ad", Sigma: "Σ", sigma: "σ", sigmaf: "ς", sigmav: "ς", sim: "∼", simdot: "⩪", sime: "≃", simeq: "≃", simg: "⪞", simgE: "⪠", siml: "⪝", simlE: "⪟", simne: "≆", simplus: "⨤", simrarr: "⥲", slarr: "←", SmallCircle: "∘", smallsetminus: "∖", smashp: "⨳", smeparsl: "⧤", smid: "∣", smile: "⌣", smt: "⪪", smte: "⪬", smtes: "⪬︀", SOFTcy: "Ь", softcy: "ь", sol: "/", solb: "⧄", solbar: "⌿", Sopf: "𝕊", sopf: "𝕤", spades: "♠", spadesuit: "♠", spar: "∥", sqcap: "⊓", sqcaps: "⊓︀", sqcup: "⊔", sqcups: "⊔︀", Sqrt: "√", sqsub: "⊏", sqsube: "⊑", sqsubset: "⊏", sqsubseteq: "⊑", sqsup: "⊐", sqsupe: "⊒", sqsupset: "⊐", sqsupseteq: "⊒", squ: "□", Square: "□", square: "□", SquareIntersection: "⊓", SquareSubset: "⊏", SquareSubsetEqual: "⊑", SquareSuperset: "⊐", SquareSupersetEqual: "⊒", SquareUnion: "⊔", squarf: "▪", squf: "▪", srarr: "→", Sscr: "𝒮", sscr: "𝓈", ssetmn: "∖", ssmile: "⌣", sstarf: "⋆", Star: "⋆", star: "☆", starf: "★", straightepsilon: "ϵ", straightphi: "ϕ", strns: "¯", Sub: "⋐", sub: "⊂", subdot: "⪽", subE: "⫅", sube: "⊆", subedot: "⫃", submult: "⫁", subnE: "⫋", subne: "⊊", subplus: "⪿", subrarr: "⥹", Subset: "⋐", subset: "⊂", subseteq: "⊆", subseteqq: "⫅", SubsetEqual: "⊆", subsetneq: "⊊", subsetneqq: "⫋", subsim: "⫇", subsub: "⫕", subsup: "⫓", succ: "≻", succapprox: "⪸", succcurlyeq: "≽", Succeeds: "≻", SucceedsEqual: "⪰", SucceedsSlantEqual: "≽", SucceedsTilde: "≿", succeq: "⪰", succnapprox: "⪺", succneqq: "⪶", succnsim: "⋩", succsim: "≿", SuchThat: "∋", Sum: "∑", sum: "∑", sung: "♪", Sup: "⋑", sup: "⊃", sup1: "¹", sup2: "²", sup3: "³", supdot: "⪾", supdsub: "⫘", supE: "⫆", supe: "⊇", supedot: "⫄", Superset: "⊃", SupersetEqual: "⊇", suphsol: "⟉", suphsub: "⫗", suplarr: "⥻", supmult: "⫂", supnE: "⫌", supne: "⊋", supplus: "⫀", Supset: "⋑", supset: "⊃", supseteq: "⊇", supseteqq: "⫆", supsetneq: "⊋", supsetneqq: "⫌", supsim: "⫈", supsub: "⫔", supsup: "⫖", swarhk: "⤦", swArr: "⇙", swarr: "↙", swarrow: "↙", swnwar: "⤪", szlig: "ß", Tab: "\u0009", target: "⌖", Tau: "Τ", tau: "τ", tbrk: "⎴", Tcaron: "Ť", tcaron: "ť", Tcedil: "Ţ", tcedil: "ţ", Tcy: "Т", tcy: "т", tdot: "⃛", telrec: "⌕", Tfr: "𝔗", tfr: "𝔱", there4: "∴", Therefore: "∴", therefore: "∴", Theta: "Θ", theta: "θ", thetasym: "ϑ", thetav: "ϑ", thickapprox: "≈", thicksim: "∼", ThickSpace: " ", thinsp: " ", ThinSpace: " ", thkap: "≈", thksim: "∼", THORN: "Þ", thorn: "þ", Tilde: "∼", tilde: "˜", TildeEqual: "≃", TildeFullEqual: "≅", TildeTilde: "≈", times: "×", timesb: "⊠", timesbar: "⨱", timesd: "⨰", tint: "∭", toea: "⤨", top: "⊤", topbot: "⌶", topcir: "⫱", Topf: "𝕋", topf: "𝕥", topfork: "⫚", tosa: "⤩", tprime: "‴", TRADE: "™", trade: "™", triangle: "▵", triangledown: "▿", triangleleft: "◃", trianglelefteq: "⊴", triangleq: "≜", triangleright: "▹", trianglerighteq: "⊵", tridot: "◬", trie: "≜", triminus: "⨺", TripleDot: "⃛", triplus: "⨹", trisb: "⧍", tritime: "⨻", trpezium: "⏢", Tscr: "𝒯", tscr: "𝓉", TScy: "Ц", tscy: "ц", TSHcy: "Ћ", tshcy: "ћ", Tstrok: "Ŧ", tstrok: "ŧ", twixt: "≬", twoheadleftarrow: "↞", twoheadrightarrow: "↠", Uacute: "Ú", uacute: "ú", Uarr: "↟", uArr: "⇑", uarr: "↑", Uarrocir: "⥉", Ubrcy: "Ў", ubrcy: "ў", Ubreve: "Ŭ", ubreve: "ŭ", Ucirc: "Û", ucirc: "û", Ucy: "У", ucy: "у", udarr: "⇅", Udblac: "Ű", udblac: "ű", udhar: "⥮", ufisht: "⥾", Ufr: "𝔘", ufr: "𝔲", Ugrave: "Ù", ugrave: "ù", uHar: "⥣", uharl: "↿", uharr: "↾", uhblk: "▀", ulcorn: "⌜", ulcorner: "⌜", ulcrop: "⌏", ultri: "◸", Umacr: "Ū", umacr: "ū", uml: "¨", UnderBar: "_", UnderBrace: "⏟", UnderBracket: "⎵", UnderParenthesis: "⏝", Union: "⋃", UnionPlus: "⊎", Uogon: "Ų", uogon: "ų", Uopf: "𝕌", uopf: "𝕦", UpArrow: "↑", Uparrow: "⇑", uparrow: "↑", UpArrowBar: "⤒", UpArrowDownArrow: "⇅", UpDownArrow: "↕", Updownarrow: "⇕", updownarrow: "↕", UpEquilibrium: "⥮", upharpoonleft: "↿", upharpoonright: "↾", uplus: "⊎", UpperLeftArrow: "↖", UpperRightArrow: "↗", Upsi: "ϒ", upsi: "υ", upsih: "ϒ", Upsilon: "Υ", upsilon: "υ", UpTee: "⊥", UpTeeArrow: "↥", upuparrows: "⇈", urcorn: "⌝", urcorner: "⌝", urcrop: "⌎", Uring: "Ů", uring: "ů", urtri: "◹", Uscr: "𝒰", uscr: "𝓊", utdot: "⋰", Utilde: "Ũ", utilde: "ũ", utri: "▵", utrif: "▴", uuarr: "⇈", Uuml: "Ü", uuml: "ü", uwangle: "⦧", vangrt: "⦜", varepsilon: "ϵ", varkappa: "ϰ", varnothing: "∅", varphi: "ϕ", varpi: "ϖ", varpropto: "∝", vArr: "⇕", varr: "↕", varrho: "ϱ", varsigma: "ς", varsubsetneq: "⊊︀", varsubsetneqq: "⫋︀", varsupsetneq: "⊋︀", varsupsetneqq: "⫌︀", vartheta: "ϑ", vartriangleleft: "⊲", vartriangleright: "⊳", Vbar: "⫫", vBar: "⫨", vBarv: "⫩", Vcy: "В", vcy: "в", VDash: "⊫", Vdash: "⊩", vDash: "⊨", vdash: "⊢", Vdashl: "⫦", Vee: "⋁", vee: "∨", veebar: "⊻", veeeq: "≚", vellip: "⋮", Verbar: "‖", verbar: "|", Vert: "‖", vert: "|", VerticalBar: "∣", VerticalLine: "|", VerticalSeparator: "❘", VerticalTilde: "≀", VeryThinSpace: " ", Vfr: "𝔙", vfr: "𝔳", vltri: "⊲", vnsub: "⊂⃒", vnsup: "⊃⃒", Vopf: "𝕍", vopf: "𝕧", vprop: "∝", vrtri: "⊳", Vscr: "𝒱", vscr: "𝓋", vsubnE: "⫋︀", vsubne: "⊊︀", vsupnE: "⫌︀", vsupne: "⊋︀", Vvdash: "⊪", vzigzag: "⦚", Wcirc: "Ŵ", wcirc: "ŵ", wedbar: "⩟", Wedge: "⋀", wedge: "∧", wedgeq: "≙", weierp: "℘", Wfr: "𝔚", wfr: "𝔴", Wopf: "𝕎", wopf: "𝕨", wp: "℘", wr: "≀", wreath: "≀", Wscr: "𝒲", wscr: "𝓌", xcap: "⋂", xcirc: "◯", xcup: "⋃", xdtri: "▽", Xfr: "𝔛", xfr: "𝔵", xhArr: "⟺", xharr: "⟷", Xi: "Ξ", xi: "ξ", xlArr: "⟸", xlarr: "⟵", xmap: "⟼", xnis: "⋻", xodot: "⨀", Xopf: "𝕏", xopf: "𝕩", xoplus: "⨁", xotime: "⨂", xrArr: "⟹", xrarr: "⟶", Xscr: "𝒳", xscr: "𝓍", xsqcup: "⨆", xuplus: "⨄", xutri: "△", xvee: "⋁", xwedge: "⋀", Yacute: "Ý", yacute: "ý", YAcy: "Я", yacy: "я", Ycirc: "Ŷ", ycirc: "ŷ", Ycy: "Ы", ycy: "ы", yen: "¥", Yfr: "𝔜", yfr: "𝔶", YIcy: "Ї", yicy: "ї", Yopf: "𝕐", yopf: "𝕪", Yscr: "𝒴", yscr: "𝓎", YUcy: "Ю", yucy: "ю", Yuml: "Ÿ", yuml: "ÿ", Zacute: "Ź", zacute: "ź", Zcaron: "Ž", zcaron: "ž", Zcy: "З", zcy: "з", Zdot: "Ż", zdot: "ż", zeetrf: "ℨ", ZeroWidthSpace: "", Zeta: "Ζ", zeta: "ζ", Zfr: "ℨ", zfr: "𝔷", ZHcy: "Ж", zhcy: "ж", zigrarr: "⇝", Zopf: "ℤ", zopf: "𝕫", Zscr: "𝒵", zscr: "𝓏", zwj: "\u200d", zwnj: "\u200c" }; }); enifed('simple-html-tokenizer/index', ['exports', 'simple-html-tokenizer/html5-named-char-refs', 'simple-html-tokenizer/entity-parser', 'simple-html-tokenizer/evented-tokenizer', 'simple-html-tokenizer/tokenizer', 'simple-html-tokenizer/tokenize'], function (exports, _simpleHtmlTokenizerHtml5NamedCharRefs, _simpleHtmlTokenizerEntityParser, _simpleHtmlTokenizerEventedTokenizer, _simpleHtmlTokenizerTokenizer, _simpleHtmlTokenizerTokenize) { 'use strict'; exports.HTML5NamedCharRefs = _simpleHtmlTokenizerHtml5NamedCharRefs.default; exports.EntityParser = _simpleHtmlTokenizerEntityParser.default; exports.EventedTokenizer = _simpleHtmlTokenizerEventedTokenizer.default; exports.Tokenizer = _simpleHtmlTokenizerTokenizer.default; exports.tokenize = _simpleHtmlTokenizerTokenize.default; }); enifed('simple-html-tokenizer/tokenize', ['exports', 'simple-html-tokenizer/tokenizer', 'simple-html-tokenizer/entity-parser', 'simple-html-tokenizer/html5-named-char-refs'], function (exports, _simpleHtmlTokenizerTokenizer, _simpleHtmlTokenizerEntityParser, _simpleHtmlTokenizerHtml5NamedCharRefs) { 'use strict'; exports.default = tokenize; function tokenize(input, options) { var tokenizer = new _simpleHtmlTokenizerTokenizer.default(new _simpleHtmlTokenizerEntityParser.default(_simpleHtmlTokenizerHtml5NamedCharRefs.default), options); return tokenizer.tokenize(input); } }); enifed('simple-html-tokenizer/tokenizer', ['exports', 'simple-html-tokenizer/evented-tokenizer'], function (exports, _simpleHtmlTokenizerEventedTokenizer) { 'use strict'; function Tokenizer(entityParser, options) { this.token = null; this.startLine = 1; this.startColumn = 0; this.options = options || {}; this.tokenizer = new _simpleHtmlTokenizerEventedTokenizer.default(this, entityParser); } Tokenizer.prototype = { tokenize: function (input) { this.tokens = []; this.tokenizer.tokenize(input); return this.tokens; }, tokenizePart: function (input) { this.tokens = []; this.tokenizer.tokenizePart(input); return this.tokens; }, tokenizeEOF: function () { this.tokens = []; this.tokenizer.tokenizeEOF(); return this.tokens[0]; }, reset: function () { this.token = null; this.startLine = 1; this.startColumn = 0; }, addLocInfo: function () { if (this.options.loc) { this.token.loc = { start: { line: this.startLine, column: this.startColumn }, end: { line: this.tokenizer.line, column: this.tokenizer.column } }; } this.startLine = this.tokenizer.line; this.startColumn = this.tokenizer.column; }, // Data beginData: function () { this.token = { type: 'Chars', chars: '' }; this.tokens.push(this.token); }, appendToData: function (char) { this.token.chars += char; }, finishData: function () { this.addLocInfo(); }, // Comment beginComment: function () { this.token = { type: 'Comment', chars: '' }; this.tokens.push(this.token); }, appendToCommentData: function (char) { this.token.chars += char; }, finishComment: function () { this.addLocInfo(); }, // Tags - basic beginStartTag: function () { this.token = { type: 'StartTag', tagName: '', attributes: [], selfClosing: false }; this.tokens.push(this.token); }, beginEndTag: function () { this.token = { type: 'EndTag', tagName: '' }; this.tokens.push(this.token); }, finishTag: function () { this.addLocInfo(); }, markTagAsSelfClosing: function () { this.token.selfClosing = true; }, // Tags - name appendToTagName: function (char) { this.token.tagName += char; }, // Tags - attributes beginAttribute: function () { this._currentAttribute = ["", "", null]; this.token.attributes.push(this._currentAttribute); }, appendToAttributeName: function (char) { this._currentAttribute[0] += char; }, beginAttributeValue: function (isQuoted) { this._currentAttribute[2] = isQuoted; }, appendToAttributeValue: function (char) { this._currentAttribute[1] = this._currentAttribute[1] || ""; this._currentAttribute[1] += char; }, finishAttributeValue: function () {} }; exports.default = Tokenizer; }); enifed("simple-html-tokenizer/utils", ["exports"], function (exports) { "use strict"; exports.isSpace = isSpace; exports.isAlpha = isAlpha; exports.preprocessInput = preprocessInput; var WSP = /[\t\n\f ]/; var ALPHA = /[A-Za-z]/; var CRLF = /\r\n?/g; function isSpace(char) { return WSP.test(char); } function isAlpha(char) { return ALPHA.test(char); } function preprocessInput(input) { return input.replace(CRLF, "\n"); } }); (function (m) { if (typeof module === "object" && module.exports) { module.exports = m } }(requireModule("ember-template-compiler"))); }()); ;/*global define:false */ /** * Copyright 2016 Craig Campbell * * 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. * * Mousetrap is a simple keyboard shortcut library for Javascript with * no external dependencies * * @version 1.6.0 * @url craig.is/killing/mice */ (function(window, document, undefined) { // Check if mousetrap is used inside browser, if not, return if (!window) { return; } /** * mapping of special keycodes to their corresponding keys * * everything in this dictionary cannot use keypress events * so it has to be here to map to the correct keycodes for * keyup/keydown events * * @type {Object} */ var _MAP = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta' }; /** * mapping for special characters so they can support * * this dictionary is only used incase you want to bind a * keyup or keydown event to one of these keys * * @type {Object} */ var _KEYCODE_MAP = { 106: '*', 107: '+', 109: '-', 110: '.', 111 : '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' }; /** * this is a mapping of keys that require shift on a US keypad * back to the non shift equivelents * * this is so you can use keyup events with these keys * * note that this will only work reliably on US keyboards * * @type {Object} */ var _SHIFT_MAP = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '\"': '\'', '<': ',', '>': '.', '?': '/', '|': '\\' }; /** * this is a list of special strings you can use to map * to modifier keys when you specify your keyboard shortcuts * * @type {Object} */ var _SPECIAL_ALIASES = { 'option': 'alt', 'command': 'meta', 'return': 'enter', 'escape': 'esc', 'plus': '+', 'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl' }; /** * variable to store the flipped version of _MAP from above * needed to check if we should use keypress or not when no action * is specified * * @type {Object|undefined} */ var _REVERSE_MAP; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (var i = 1; i < 20; ++i) { _MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (i = 0; i <= 9; ++i) { // This needs to use a string cause otherwise since 0 is falsey // mousetrap will never fire for numpad 0 pressed as part of a keydown // event. // // @see https://github.com/ccampbell/mousetrap/pull/258 _MAP[i + 96] = i.toString(); } /** * cross browser add event method * * @param {Element|HTMLDocument} object * @param {string} type * @param {Function} callback * @returns void */ function _addEvent(object, type, callback) { if (object.addEventListener) { object.addEventListener(type, callback, false); return; } object.attachEvent('on' + type, callback); } /** * takes the event and returns the key character * * @param {Event} e * @return {string} */ function _characterFromEvent(e) { var which = e.which; if ( 'undefined' !== typeof e.synthesizedWhich ) { which = e.synthesizedWhich; } // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion if (typeof which !== 'number') { which = e.keyCode; } // for keypress events we should return the character as is if (e.type == 'keypress') { var character = String.fromCharCode(which); // if the shift key is not pressed then it is safe to assume // that we want the character to be lowercase. this means if // you accidentally have caps lock on then your key bindings // will continue to work // // the only side effect that might not be desired is if you // bind something like 'A' cause you want to trigger an // event when capital A is pressed caps lock will no longer // trigger the event. shift+a will though. if (!e.shiftKey) { character = character.toLowerCase(); } return character; } // for non keypress events the special maps are needed if (_MAP[which]) { return _MAP[which]; } if (_KEYCODE_MAP[which]) { return _KEYCODE_MAP[which]; } // if it is not in the special map // with keydown and keyup events the character seems to always // come in as an uppercase character whether you are pressing shift // or not. we should make sure it is always lowercase for comparisons return String.fromCharCode(which).toLowerCase(); } /** * checks if two arrays are equal * * @param {Array} modifiers1 * @param {Array} modifiers2 * @returns {boolean} */ function _modifiersMatch(modifiers1, modifiers2) { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * takes a key event and figures out what the modifiers are * * @param {Event} e * @returns {Array} */ function _eventModifiers(e) { var modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * prevents default for this event * * @param {Event} e * @returns void */ function _preventDefault(e) { if (e.preventDefault) { e.preventDefault(); return; } e.returnValue = false; } /** * stops propogation for this event * * @param {Event} e * @returns void */ function _stopPropagation(e) { if (e.stopPropagation) { e.stopPropagation(); return; } e.cancelBubble = true; } /** * determines if the keycode specified is a modifier key or not * * @param {string} key * @returns {boolean} */ function _isModifier(key) { return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function _getReverseMap() { if (!_REVERSE_MAP) { _REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { _REVERSE_MAP[_MAP[key]] = key; } } } return _REVERSE_MAP; } /** * picks the best action based on the key combination * * @param {string} key - character for key * @param {Array} modifiers * @param {string=} action passed in */ function _pickBestAction(key, modifiers, action) { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = _getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action == 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * Converts from a string key combination to an array * * @param {string} combination like "command+shift+l" * @return {Array} */ function _keysFromString(combination) { if (combination === '+') { return ['+']; } combination = combination.replace(/\+{2}/g, '+plus'); return combination.split('+'); } /** * Gets info for a specific key combination * * @param {string} combination key combination ("command+s" or "a" or "*") * @param {string=} action * @returns {Object} */ function _getKeyInfo(combination, action) { var keys; var key; var i; var modifiers = []; // take the keys from this pattern and figure out what the actual // pattern is all about keys = _keysFromString(combination); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); return { key: key, modifiers: modifiers, action: action }; } function _belongsTo(element, ancestor) { if (element === null || element === document) { return false; } if (element === ancestor) { return true; } return _belongsTo(element.parentNode, ancestor); } function Mousetrap(targetElement) { var self = this; targetElement = targetElement || document; if (!(self instanceof Mousetrap)) { return new Mousetrap(targetElement); } /** * element to attach key events to * * @type {Element} */ self.target = targetElement; /** * a list of all the callbacks setup via Mousetrap.bind() * * @type {Object} */ self._callbacks = {}; /** * direct map of string combinations to callbacks used for trigger() * * @type {Object} */ self._directMap = {}; /** * keeps track of what level each sequence is at since multiple * sequences can start out with the same sequence * * @type {Object} */ var _sequenceLevels = {}; /** * variable to store the setTimeout call * * @type {null|number} */ var _resetTimer; /** * temporary state where we will ignore the next keyup * * @type {boolean|string} */ var _ignoreNextKeyup = false; /** * temporary state where we will ignore the next keypress * * @type {boolean} */ var _ignoreNextKeypress = false; /** * are we currently inside of a sequence? * type of action ("keyup" or "keydown" or "keypress") or false * * @type {boolean|string} */ var _nextExpectedAction = false; /** * resets all sequence counters except for the ones passed in * * @param {Object} doNotReset * @returns void */ function _resetSequences(doNotReset) { doNotReset = doNotReset || {}; var activeSequences = false, key; for (key in _sequenceLevels) { if (doNotReset[key]) { activeSequences = true; continue; } _sequenceLevels[key] = 0; } if (!activeSequences) { _nextExpectedAction = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action * * @param {string} character * @param {Array} modifiers * @param {Event|Object} e * @param {string=} sequenceName - name of the sequence we are looking for * @param {string=} combination * @param {number=} level * @returns {Array} */ function _getMatches(character, modifiers, e, sequenceName, combination, level) { var i; var callback; var matches = []; var action = e.type; // if there are no events related to this keycode if (!self._callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < self._callbacks[character].length; ++i) { callback = self._callbacks[character][i]; // if a sequence name is not specified, but this is a sequence at // the wrong level then move onto the next match if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event and the meta key and control key // are not pressed that means that we need to only look at the // character, otherwise check the modifiers as well // // chrome will not fire a keypress if meta or control is down // safari will fire a keypress if meta or meta+shift is down // firefox will fire a keypress if meta or control is down if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) { // when you bind a combination or sequence a second time it // should overwrite the first one. if a sequenceName or // combination is specified in this call it does just that // // @todo make deleting its own method? var deleteCombo = !sequenceName && callback.combo == combination; var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level; if (deleteCombo || deleteSequence) { self._callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event * * @param {Function} callback * @param {Event} e * @returns void */ function _fireCallback(callback, e, combo, sequence) { // if this event should not happen stop here if (self.stopCallback(e, e.target || e.srcElement, combo, sequence)) { return; } if (callback(e, combo) === false) { _preventDefault(e); _stopPropagation(e); } } /** * handles a character key event * * @param {string} character * @param {Array} modifiers * @param {Event} e * @returns void */ self._handleKey = function(character, modifiers, e) { var callbacks = _getMatches(character, modifiers, e); var i; var doNotReset = {}; var maxLevel = 0; var processedSequenceCallback = false; // Calculate the maxLevel for sequences so we can only execute the longest callback sequence for (i = 0; i < callbacks.length; ++i) { if (callbacks[i].seq) { maxLevel = Math.max(maxLevel, callbacks[i].level); } } // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { // only fire callbacks for the maxLevel to prevent // subsequences from also firing // // for example 'a option b' should not cause 'option b' to fire // even though 'option b' is part of the other sequence // // any sequences that do not match here will be discarded // below by the _resetSequences call if (callbacks[i].level != maxLevel) { continue; } processedSequenceCallback = true; // keep a list of which sequences were matches for later doNotReset[callbacks[i].seq] = 1; _fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processedSequenceCallback) { _fireCallback(callbacks[i].callback, e, callbacks[i].combo); } } // if the key you pressed matches the type of sequence without // being a modifier (ie "keyup" or "keypress") then we should // reset all sequences that were not matched by this event // // this is so, for example, if you have the sequence "h a t" and you // type "h e a r t" it does not match. in this case the "e" will // cause the sequence to reset // // modifier keys are ignored because you can have a sequence // that contains modifiers such as "enter ctrl+space" and in most // cases the modifier key will be pressed before the next key // // also if you have a sequence such as "ctrl+b a" then pressing the // "b" key will trigger a "keypress" and a "keydown" // // the "keydown" is expected when there is a modifier, but the // "keypress" ends up matching the _nextExpectedAction since it occurs // after and that causes the sequence to reset // // we ignore keypresses in a sequence that directly follow a keydown // for the same character var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress; if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) { _resetSequences(doNotReset); } _ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown'; }; /** * handles a keydown event * * @param {Event} e * @returns void */ function _handleKeyEvent(e) { // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion if (typeof e.which !== 'number') { e.which = e.keyCode; } var character = _characterFromEvent(e); // no character found then stop if (!character) { return; } // need to use === for the character check because the character can be 0 if (e.type == 'keyup' && _ignoreNextKeyup === character) { _ignoreNextKeyup = false; return; } self.handleKey(character, _eventModifiers(e), e); } /** * called to set a 1 second timeout on the specified sequence * * this is so after each key press in the sequence you have 1 second * to press the next key before you have to start over * * @returns void */ function _resetSequenceTimer() { clearTimeout(_resetTimer); _resetTimer = setTimeout(_resetSequences, 1000); } /** * binds a key sequence to an event * * @param {string} combo - combo specified in bind call * @param {Array} keys * @param {Function} callback * @param {string=} action * @returns void */ function _bindSequence(combo, keys, callback, action) { // start off by adding a sequence level record for this combination // and setting the level to 0 _sequenceLevels[combo] = 0; /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {string} nextAction * @returns {Function} */ function _increaseSequence(nextAction) { return function() { _nextExpectedAction = nextAction; ++_sequenceLevels[combo]; _resetSequenceTimer(); }; } /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ function _callbackAndReset(e) { _fireCallback(callback, e, combo); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { _ignoreNextKeyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences, 10); } // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences // // if an action is specified in the original bind call then that will // be used throughout. otherwise we will pass the action that the // next key in the sequence should match. this allows a sequence // to mix and match keypress and keydown events depending on which // ones are better suited to the key provided for (var i = 0; i < keys.length; ++i) { var isFinal = i + 1 === keys.length; var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action); _bindSingle(keys[i], wrappedCallback, action, combo, i); } } /** * binds a single keyboard combination * * @param {string} combination * @param {Function} callback * @param {string=} action * @param {string=} sequenceName - name of sequence if part of sequence * @param {number=} level - what part of the sequence the command is * @returns void */ function _bindSingle(combination, callback, action, sequenceName, level) { // store a direct mapped reference for use with Mousetrap.trigger self._directMap[combination + ':' + action] = callback; // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); var sequence = combination.split(' '); var info; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { _bindSequence(combination, sequence, callback, action); return; } info = _getKeyInfo(combination, action); // make sure to initialize array if this is the first time // a callback is added for this key self._callbacks[info.key] = self._callbacks[info.key] || []; // remove an existing match if there is one _getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first self._callbacks[info.key][sequenceName ? 'unshift' : 'push']({ callback: callback, modifiers: info.modifiers, action: info.action, seq: sequenceName, level: level, combo: combination }); } /** * binds multiple combinations to the same callback * * @param {Array} combinations * @param {Function} callback * @param {string|undefined} action * @returns void */ self._bindMultiple = function(combinations, callback, action) { for (var i = 0; i < combinations.length; ++i) { _bindSingle(combinations[i], callback, action); } }; // start! _addEvent(targetElement, 'keypress', _handleKeyEvent); _addEvent(targetElement, 'keydown', _handleKeyEvent); _addEvent(targetElement, 'keyup', _handleKeyEvent); } /** * binds an event to mousetrap * * can be a single key, a combination of keys separated with +, * an array of keys, or a sequence of keys separated by spaces * * be sure to list the modifier keys first to make sure that the * correct key ends up getting bound (the last key in the pattern) * * @param {string|Array} keys * @param {Function} callback * @param {string=} action - 'keypress', 'keydown', or 'keyup' * @returns void */ Mousetrap.prototype.bind = function(keys, callback, action) { var self = this; keys = keys instanceof Array ? keys : [keys]; self._bindMultiple.call(self, keys, callback, action); return self; }; /** * unbinds an event to mousetrap * * the unbinding sets the callback function of the specified key combo * to an empty function and deletes the corresponding key in the * _directMap dict. * * TODO: actually remove this from the _callbacks dictionary instead * of binding an empty function * * the keycombo+action has to be exactly the same as * it was defined in the bind method * * @param {string|Array} keys * @param {string} action * @returns void */ Mousetrap.prototype.unbind = function(keys, action) { var self = this; return self.bind.call(self, keys, function() {}, action); }; /** * triggers an event that has already been bound * * @param {string} keys * @param {string=} action * @returns void */ Mousetrap.prototype.trigger = function(keys, action) { var self = this; if (self._directMap[keys + ':' + action]) { self._directMap[keys + ':' + action]({}, keys); } return self; }; /** * resets the library back to its initial state. this is useful * if you want to clear out the current keyboard shortcuts and bind * new ones - for example if you switch to another page * * @returns void */ Mousetrap.prototype.reset = function() { var self = this; self._callbacks = {}; self._directMap = {}; return self; }; /** * should we stop this event before firing off callbacks * * @param {Event} e * @param {Element} element * @return {boolean} */ Mousetrap.prototype.stopCallback = function(e, element) { var self = this; // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } if (_belongsTo(element, self.target)) { return false; } // stop for input, select, and textarea return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable; }; /** * exposes _handleKey publicly so it can be overwritten by extensions */ Mousetrap.prototype.handleKey = function() { var self = this; return self._handleKey.apply(self, arguments); }; /** * allow custom key mappings */ Mousetrap.addKeycodes = function(object) { for (var key in object) { if (object.hasOwnProperty(key)) { _MAP[key] = object[key]; } } _REVERSE_MAP = null; }; /** * Init the global mousetrap functions * * This method is needed to allow the global mousetrap functions to work * now that mousetrap is a constructor function. */ Mousetrap.init = function() { var documentMousetrap = Mousetrap(document); for (var method in documentMousetrap) { if (method.charAt(0) !== '_') { Mousetrap[method] = (function(method) { return function() { return documentMousetrap[method].apply(documentMousetrap, arguments); }; } (method)); } } }; Mousetrap.init(); // expose mousetrap to the global object window.Mousetrap = Mousetrap; define('mousetrap', [],function() { return Mousetrap; }); }) (typeof window !== 'undefined' ? window : null, typeof window !== 'undefined' ? document : null); ;define('ember-cli-app-version/components/app-version', ['exports', 'ember', 'ember-cli-app-version/templates/app-version'], function (exports, _ember, _emberCliAppVersionTemplatesAppVersion) { 'use strict'; exports['default'] = _ember['default'].Component.extend({ tagName: 'span', layout: _emberCliAppVersionTemplatesAppVersion['default'] }); }); define('ember-cli-app-version/initializer-factory', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports['default'] = initializerFactory; var classify = _ember['default'].String.classify; function initializerFactory(name, version) { var registered = false; return function () { if (!registered && name && version) { var appName = classify(name); _ember['default'].libraries.register(appName, version); registered = true; } }; } }); define("ember-cli-app-version/templates/app-version", ["exports"], function (exports) { "use strict"; exports["default"] = Ember.HTMLBars.template((function () { return { meta: { "revision": "Ember@2.8.0", "loc": { "source": null, "start": { "line": 1, "column": 0 }, "end": { "line": 2, "column": 0 } }, "moduleName": "modules/ember-cli-app-version/templates/app-version.hbs" }, isEmpty: false, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); var el1 = dom.createTextNode("\n"); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); return morphs; }, statements: [["content", "version", ["loc", [null, [1, 0], [1, 11]]], 0, 0, 0, 0]], locals: [], templates: [] }; })()); }); define('ember-cli-flash/components/flash-message', ['exports', 'ember', 'ember-cli-flash/templates/components/flash-message', 'ember-new-computed'], function (exports, _ember, _emberCliFlashTemplatesComponentsFlashMessage, _emberNewComputed) { 'use strict'; var _Ember$String = _ember['default'].String; var classify = _Ember$String.classify; var htmlSafe = _Ember$String.htmlSafe; var Component = _ember['default'].Component; var getWithDefault = _ember['default'].getWithDefault; var run = _ember['default'].run; var on = _ember['default'].on; var _get = _ember['default'].get; var set = _ember['default'].set; var readOnly = _emberNewComputed['default'].readOnly; var bool = _emberNewComputed['default'].bool; var next = run.next; var cancel = run.cancel; exports['default'] = Component.extend({ layout: _emberCliFlashTemplatesComponentsFlashMessage['default'], active: false, messageStyle: 'bootstrap', classNameBindings: ['alertType', 'active', 'exiting'], showProgressBar: readOnly('flash.showProgress'), exiting: readOnly('flash.exiting'), hasBlock: bool('template').readOnly(), alertType: (0, _emberNewComputed['default'])('flash.type', { get: function get() { var flashType = getWithDefault(this, 'flash.type', ''); var messageStyle = getWithDefault(this, 'messageStyle', ''); var prefix = 'alert alert-'; if (messageStyle === 'foundation') { prefix = 'alert-box '; } return '' + prefix + flashType; } }), flashType: (0, _emberNewComputed['default'])('flash.type', { get: function get() { var flashType = getWithDefault(this, 'flash.type', ''); return classify(flashType); } }), _setActive: on('didInsertElement', function () { var _this = this; var pendingSet = next(this, function () { set(_this, 'active', true); }); set(this, 'pendingSet', pendingSet); }), progressDuration: (0, _emberNewComputed['default'])('flash.showProgress', { get: function get() { if (!_get(this, 'flash.showProgress')) { return false; } var duration = getWithDefault(this, 'flash.timeout', 0); return htmlSafe('transition-duration: ' + duration + 'ms'); } }), click: function click() { var destroyOnClick = getWithDefault(this, 'flash.destroyOnClick', true); if (destroyOnClick) { this._destroyFlashMessage(); } }, willDestroy: function willDestroy() { this._super(); this._destroyFlashMessage(); cancel(_get(this, 'pendingSet')); }, // private _destroyFlashMessage: function _destroyFlashMessage() { var flash = getWithDefault(this, 'flash', false); if (flash) { flash.destroyMessage(); } } }); }); define('ember-cli-flash/flash/object', ['exports', 'ember', 'ember-cli-flash/utils/computed', 'ember-new-computed'], function (exports, _ember, _emberCliFlashUtilsComputed, _emberNewComputed) { 'use strict'; var EmberObject = _ember['default'].Object; var _Ember$run = _ember['default'].run; var later = _Ember$run.later; var cancel = _Ember$run.cancel; var Evented = _ember['default'].Evented; var get = _ember['default'].get; var set = _ember['default'].set; var readOnly = _emberNewComputed['default'].readOnly; exports['default'] = EmberObject.extend(Evented, { timer: null, exitTimer: null, exiting: false, queue: readOnly('flashService.queue'), totalTimeout: _emberCliFlashUtilsComputed['default'].add('timeout', 'extendedTimeout').readOnly(), _guid: _emberCliFlashUtilsComputed['default'].guidFor('message').readOnly(), init: function init() { this._super.apply(this, arguments); if (get(this, 'sticky')) { return; } this._setTimer('exitTimer', 'exitMessage', get(this, 'timeout')); this._setTimer('timer', 'destroyMessage', get(this, 'totalTimeout')); }, destroyMessage: function destroyMessage() { var queue = get(this, 'queue'); if (queue) { queue.removeObject(this); } this.destroy(); this.trigger('didDestroyMessage'); }, exitMessage: function exitMessage() { set(this, 'exiting', true); this._cancelTimer('exitTimer'); this.trigger('didExitMessage'); }, willDestroy: function willDestroy() { var _this = this; var timers = ['timer', 'exitTimer']; timers.forEach(function (timer) { _this._cancelTimer(timer); }); this._super.apply(this, arguments); }, // private _setTimer: function _setTimer(name, methodName, timeout) { return set(this, name, later(this, methodName, timeout)); }, _cancelTimer: function _cancelTimer(name) { var timer = get(this, name); if (timer) { cancel(timer); set(this, name, null); } } }); }); define('ember-cli-flash/services/flash-messages', ['exports', 'ember', 'ember-cli-flash/flash/object', 'ember-cli-flash/utils/object-without', 'ember-new-computed'], function (exports, _ember, _emberCliFlashFlashObject, _emberCliFlashUtilsObjectWithout, _emberNewComputed) { 'use strict'; var Service = _ember['default'].Service; var assert = _ember['default'].assert; var copy = _ember['default'].copy; var getWithDefault = _ember['default'].getWithDefault; var isNone = _ember['default'].isNone; var setProperties = _ember['default'].setProperties; var typeOf = _ember['default'].typeOf; var warn = _ember['default'].warn; var get = _ember['default'].get; var set = _ember['default'].set; var classify = _ember['default'].String.classify; var emberArray = _ember['default'].A; var equal = _emberNewComputed['default'].equal; var sort = _emberNewComputed['default'].sort; var mapBy = _emberNewComputed['default'].mapBy; var merge = _ember['default'].assign || _ember['default'].merge; exports['default'] = Service.extend({ isEmpty: equal('queue.length', 0).readOnly(), _guids: mapBy('queue', '_guid').readOnly(), arrangedQueue: sort('queue', function (a, b) { if (a.priority < b.priority) { return 1; } else if (a.priority > b.priority) { return -1; } return 0; }).readOnly(), init: function init() { this._super.apply(this, arguments); this._setDefaults(); this.queue = emberArray(); }, add: function add() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this._enqueue(this._newFlashMessage(options)); return this; }, clearMessages: function clearMessages() { var flashes = get(this, 'queue'); if (isNone(flashes)) { return; } flashes.clear(); return this; }, registerTypes: function registerTypes() { var _this = this; var types = arguments.length <= 0 || arguments[0] === undefined ? emberArray() : arguments[0]; types.forEach(function (type) { return _this._registerType(type); }); return this; }, _newFlashMessage: function _newFlashMessage() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; assert('The flash message cannot be empty.', options.message); var flashService = this; var allDefaults = getWithDefault(this, 'flashMessageDefaults', {}); var defaults = (0, _emberCliFlashUtilsObjectWithout['default'])(allDefaults, ['types', 'injectionFactories', 'preventDuplicates']); var flashMessageOptions = merge(copy(defaults), { flashService: flashService }); for (var key in options) { var value = get(options, key); var option = this._getOptionOrDefault(key, value); set(flashMessageOptions, key, option); } return _emberCliFlashFlashObject['default'].create(flashMessageOptions); }, _getOptionOrDefault: function _getOptionOrDefault(key, value) { var defaults = getWithDefault(this, 'flashMessageDefaults', {}); var defaultOption = get(defaults, key); if (typeOf(value) === 'undefined') { return defaultOption; } return value; }, _setDefaults: function _setDefaults() { var defaults = getWithDefault(this, 'flashMessageDefaults', {}); for (var key in defaults) { var classifiedKey = classify(key); var defaultKey = 'default' + classifiedKey; set(this, defaultKey, defaults[key]); } this.registerTypes(getWithDefault(this, 'defaultTypes', emberArray())); }, _registerType: function _registerType(type) { var _this2 = this; assert('The flash type cannot be undefined', type); this[type] = function (message) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var flashMessageOptions = copy(options); setProperties(flashMessageOptions, { message: message, type: type }); return _this2.add(flashMessageOptions); }; }, _hasDuplicate: function _hasDuplicate(guid) { return get(this, '_guids').contains(guid); }, _enqueue: function _enqueue(flashInstance) { var preventDuplicates = get(this, 'defaultPreventDuplicates'); var guid = get(flashInstance, '_guid'); if (preventDuplicates && this._hasDuplicate(guid)) { warn('Attempting to add a duplicate message to the Flash Messages Service', false, { id: 'ember-cli-flash.duplicate-message' }); return; } return get(this, 'queue').pushObject(flashInstance); } }); }); define("ember-cli-flash/templates/components/flash-message", ["exports"], function (exports) { "use strict"; exports["default"] = Ember.HTMLBars.template((function () { var child0 = (function () { return { meta: { "revision": "Ember@2.8.0", "loc": { "source": null, "start": { "line": 1, "column": 0 }, "end": { "line": 3, "column": 0 } }, "moduleName": "modules/ember-cli-flash/templates/components/flash-message.hbs" }, isEmpty: false, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createTextNode(" "); dom.appendChild(el0, el1); var el1 = dom.createComment(""); dom.appendChild(el0, el1); var el1 = dom.createTextNode("\n"); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 1, 1, contextualElement); return morphs; }, statements: [["inline", "yield", [["get", "this", ["loc", [null, [2, 10], [2, 14]]], 0, 0, 0, 0], ["get", "flash", ["loc", [null, [2, 15], [2, 20]]], 0, 0, 0, 0]], [], ["loc", [null, [2, 2], [2, 22]]], 0, 0]], locals: [], templates: [] }; })(); var child1 = (function () { var child0 = (function () { return { meta: { "revision": "Ember@2.8.0", "loc": { "source": null, "start": { "line": 5, "column": 2 }, "end": { "line": 9, "column": 2 } }, "moduleName": "modules/ember-cli-flash/templates/components/flash-message.hbs" }, isEmpty: false, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createTextNode(" "); dom.appendChild(el0, el1); var el1 = dom.createElement("div"); dom.setAttribute(el1, "class", "alert-progress"); var el2 = dom.createTextNode("\n "); dom.appendChild(el1, el2); var el2 = dom.createElement("div"); dom.setAttribute(el2, "class", "alert-progressBar"); dom.appendChild(el1, el2); var el2 = dom.createTextNode("\n "); dom.appendChild(el1, el2); dom.appendChild(el0, el1); var el1 = dom.createTextNode("\n"); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var element0 = dom.childAt(fragment, [1, 1]); var morphs = new Array(1); morphs[0] = dom.createAttrMorph(element0, 'style'); return morphs; }, statements: [["attribute", "style", ["get", "progressDuration", ["loc", [null, [7, 45], [7, 61]]], 0, 0, 0, 0], 0, 0, 0, 0]], locals: [], templates: [] }; })(); return { meta: { "revision": "Ember@2.8.0", "loc": { "source": null, "start": { "line": 3, "column": 0 }, "end": { "line": 10, "column": 0 } }, "moduleName": "modules/ember-cli-flash/templates/components/flash-message.hbs" }, isEmpty: false, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createTextNode(" "); dom.appendChild(el0, el1); var el1 = dom.createComment(""); dom.appendChild(el0, el1); var el1 = dom.createTextNode("\n"); dom.appendChild(el0, el1); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(2); morphs[0] = dom.createMorphAt(fragment, 1, 1, contextualElement); morphs[1] = dom.createMorphAt(fragment, 3, 3, contextualElement); dom.insertBoundary(fragment, null); return morphs; }, statements: [["content", "flash.message", ["loc", [null, [4, 2], [4, 19]]], 0, 0, 0, 0], ["block", "if", [["get", "showProgressBar", ["loc", [null, [5, 8], [5, 23]]], 0, 0, 0, 0]], [], 0, null, ["loc", [null, [5, 2], [9, 9]]]]], locals: [], templates: [child0] }; })(); return { meta: { "revision": "Ember@2.8.0", "loc": { "source": null, "start": { "line": 1, "column": 0 }, "end": { "line": 11, "column": 0 } }, "moduleName": "modules/ember-cli-flash/templates/components/flash-message.hbs" }, isEmpty: false, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); dom.insertBoundary(fragment, null); return morphs; }, statements: [["block", "if", [["get", "hasBlock", ["loc", [null, [1, 6], [1, 14]]], 0, 0, 0, 0]], [], 0, 1, ["loc", [null, [1, 0], [10, 7]]]]], locals: [], templates: [child0, child1] }; })()); }); define('ember-cli-flash/utils/computed', ['exports', 'ember', 'ember-new-computed'], function (exports, _ember, _emberNewComputed) { 'use strict'; exports.add = add; exports.guidFor = guidFor; var typeOf = _ember['default'].typeOf; var _get = _ember['default'].get; var emberGuidFor = _ember['default'].guidFor; var emberArray = _ember['default'].A; function add() { for (var _len = arguments.length, dependentKeys = Array(_len), _key = 0; _key < _len; _key++) { dependentKeys[_key] = arguments[_key]; } var computedFunc = (0, _emberNewComputed['default'])({ get: function get() { var _this = this; var values = dependentKeys.map(function (dependentKey) { var value = _get(_this, dependentKey); if (typeOf(value) !== 'number') { return; } return value; }); return emberArray(values).compact().reduce(function (prev, curr) { return prev + curr; }); } }); return computedFunc.property.apply(computedFunc, dependentKeys); } function guidFor(dependentKey) { return (0, _emberNewComputed['default'])(dependentKey, { get: function get() { var value = _get(this, dependentKey); return emberGuidFor(value.toString()); } }); } }); define('ember-cli-flash/utils/object-compact', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports['default'] = objectCompact; var isPresent = _ember['default'].isPresent; function objectCompact(objectInstance) { var compactedObject = {}; for (var key in objectInstance) { var value = objectInstance[key]; if (isPresent(value)) { compactedObject[key] = value; } } return compactedObject; } }); define("ember-cli-flash/utils/object-only", ["exports"], function (exports) { "use strict"; exports["default"] = objectWithout; function objectWithout() { var originalObj = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var keysToRemain = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; var newObj = {}; for (var key in originalObj) { if (keysToRemain.indexOf(key) !== -1) { newObj[key] = originalObj[key]; } } return newObj; } }); define("ember-cli-flash/utils/object-without", ["exports"], function (exports) { "use strict"; exports["default"] = objectWithout; function objectWithout() { var originalObj = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var keysToRemove = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; var newObj = {}; for (var key in originalObj) { if (keysToRemove.indexOf(key) === -1) { newObj[key] = originalObj[key]; } } return newObj; } }); define('ember-cli-selectize/components/ember-selectize', ['exports', 'ember', 'ember-new-computed'], function (exports, _ember, _emberNewComputed) { 'use strict'; var Component = _ember['default'].Component; var computed = _ember['default'].computed; var observer = _ember['default'].observer; var run = _ember['default'].run; var get = _ember['default'].get; var isArray = _ember['default'].isArray; var isEmpty = _ember['default'].isEmpty; var isNone = _ember['default'].isNone; var typeOf = _ember['default'].typeOf; var camelize = _ember['default'].String.camelize; var assert = _ember['default'].assert; var getOwner = _ember['default'].getOwner; var assign = _ember['default'].assign || _ember['default'].merge; /** * Ember.Selectize is an Ember View that encapsulates a Selectize component. * The goal is to use this as a near dropin replacement for Ember.Select. */ exports['default'] = Component.extend({ attributeBindings: ['name', 'multiple', 'autocomplete', 'required', 'tabindex'], classNames: ['ember-selectize'], autocomplete: 'off', multiple: false, tabindex: 0, maxItems: computed('multiple', function () { return this.get('multiple') ? null : 1; }), // Allows to use prompt (like in Ember.Select) or placeholder property placeholder: computed.alias('prompt'), sortField: null, sortDirection: 'asc', tagName: 'select', /** * overrideable object paths for value and label paths */ optionValuePath: 'content', optionLabelPath: 'content', optionGroupPath: 'content.group', selection: null, value: (0, _emberNewComputed['default'])('selection', { get: function get() { var valuePath = this.get('_valuePath'); var selection = this.get('selection'); return valuePath && selection ? _ember['default'].get(selection, valuePath) : selection; }, set: function set(key, value) { return value; } }), /* * Contains optgroups. */ optgroups: computed('content.[]', 'groupedContent.[]', function () { var _this = this; var groupedContent = this.get('groupedContent'); if (groupedContent) { return groupedContent.mapBy('label'); } else { //compute option groups from content var content = this.get('content'); if (!isArray(content)) { return; } return content.reduce(function (previousValue, item) { return previousValue.addObject(get(item, _this.get('_groupPath'))); }, _ember['default'].A()); } }), /** * Computes content from grouped content. * If `content` is set, this computed property is overriden and never executed. */ content: computed('groupedContent.[]', function () { var _this2 = this; var groupedContent = this.get('groupedContent'); if (!groupedContent) { return; } //concatenate all content properties in each group return groupedContent.reduce(function (previousValue, group) { var content = get(group, 'content') || _ember['default'].A(); var groupLabel = get(group, 'label'); //create proxies for each object. Selectize requires the group value to be //set in the object. Use ObjectProxy to keep original object intact. var proxiedContent = content.map(function (item) { var proxy = { content: item }; proxy[_this2.get('_groupPath')] = groupLabel; return _ember['default'].ObjectProxy.create(proxy); }); return previousValue.pushObjects(proxiedContent); }, _ember['default'].A()); }), _optgroupsDidChange: observer('optgroups.[]', function () { var _this3 = this; if (!this._selectize) { return; } //TODO right now we reset option groups. //Ideally we would set up an array observer and use selectize's [add|remove]OptionGroup this._selectize.clearOptionGroups(); var optgroups = this.get('optgroups'); if (!optgroups) { return; } optgroups.forEach(function (group) { _this3._selectize.addOptionGroup(group, { label: group, value: group }); }); }), /** * The array of the default plugins to load into selectize */ plugins: ['remove_button'], /** * Computed properties that hold the processed paths ('content.' replacement), * as it is done on Ember.Select */ _valuePath: computed('optionValuePath', function () { return this.get('optionValuePath').replace(/^content\.?/, ''); }), _labelPath: computed('optionLabelPath', function () { return this.get('optionLabelPath').replace(/^content\.?/, ''); }), _groupPath: computed('optionGroupPath', function () { return this.get('optionGroupPath').replace(/^content\.?/, ''); }), getValueFor: function getValueFor(item) { var valuePath = this.get('_valuePath'); return isEmpty(valuePath) || isEmpty(item) ? item : get(item, valuePath); }, getLabelFor: function getLabelFor(item) { var labelPath = this.get('_labelPath'); return isEmpty(labelPath) || isEmpty(item) ? item : get(item, labelPath); }, /** * Loading feature default values. * If you want to override the css class that is applied, change the `loadingClass` property. */ loading: false, loadingClass: 'loading', /** * The render function names selectize expects. * We will use these to automatically infer the properties with the template and view names. */ functionNames: ['option', 'item', 'option_create', 'optgroup_header', 'optgroup'], templateSuffix: 'Template', componentSuffix: 'Component', functionSuffix: 'Function', renderOptions: computed(function () { var _this4 = this; var functionNames = this.get('functionNames'); //this hash will contain the render functions var renderFunctions = {}; functionNames.forEach(function (item) { // infer the function name by camelizing selectize's function and appending the function suffix (overridable) var functionSuffix = _this4.get('functionSuffix'); var functionPropertyName = camelize(item) + functionSuffix; var renderFunction = _this4.get(functionPropertyName); // functions take precedence if (renderFunction) { renderFunctions[item] = function (data, escape) { return renderFunction.call(_this4.get('targetObject') || _this4, data.data || data, escape); }; } else { // infer the view name by camelizing selectize's function and appending a view suffix (overridable) var componentSuffix = _this4.get('componentSuffix'); var componentPropertyName = camelize(item) + componentSuffix; var componentToRender = _this4.get(componentPropertyName); if (componentToRender) { // we have a view to render. set the function. renderFunctions[item] = function (data) { return _this4._componentToDOM(componentToRender, data.data || data); }; } } }); return renderFunctions; }), selectizeOptions: computed(function () { var _this5 = this; var allowCreate = this.get('create-item'); var multiple = this.get('multiple'); //Split the passed in plugin config into an array. if (typeof this.plugins === 'string') { this.plugins = this.plugins.trim().split(/[\s,]+/); } var plugins = this.plugins.slice(0); if (!multiple) { var index = plugins.indexOf('remove_button'); if (index !== -1) { plugins.splice(index, 1); } } var options = { plugins: plugins, labelField: 'label', valueField: 'value', searchField: 'label', optgroupField: 'optgroup', create: allowCreate ? run.bind(this, '_create') : false, onItemAdd: run.bind(this, '_onItemAdd'), onItemRemove: run.bind(this, '_onItemRemove'), onType: run.bind(this, '_onType'), render: this.get('renderOptions'), placeholder: this.get('placeholder'), score: this.get('score'), onBlur: this._registerAction('on-blur'), onFocus: this._registerAction('on-focus'), onInitialize: this._registerAction('on-init'), onClear: this._registerAction('on-clear') }; var generalOptions = ['delimiter', 'diacritics', 'createOnBlur', 'createFilter', 'highlight', 'persist', 'openOnFocus', 'maxOptions', 'maxItems', 'hideSelected', 'closeAfterSelect', 'allowEmptyOption', 'scrollDuration', 'loadThrottle', 'preload', 'dropdownParent', 'addPrecedence', 'selectOnTab', 'searchField']; generalOptions.forEach(function (option) { options[option] = _this5.getWithDefault(option, options[option]); }); options = this._mergeSortField(options); return options; }), didInsertElement: function didInsertElement() { // ensure selectize is loaded assert('selectize has to be loaded', typeof this.$().selectize === 'function'); //Create Selectize's instance this.$().selectize(this.get('selectizeOptions')); //Save the created selectize instance this._selectize = this.$()[0].selectize; //Some changes to content, selection and disabled could have happened before the Component was inserted into the DOM. //We trigger all the observers manually to account for those changes. this._disabledDidChange(); this._optgroupsDidChange(); if (this.get('groupedContent')) { this._groupedContentDidChange(); } this._contentDidChange(); var selection = this.get('selection'); var value = this.get('value'); if (!isNone(selection)) { this._selectionDidChange(); } if (!isNone(value)) { this._valueDidChange(); } this._loadingDidChange(); }, willDestroyElement: function willDestroyElement() { //Unbind observers this._contentWillChange(this.get('content')); this._selectionWillChange(this.get('selection')); this._groupedContentWillChange(this.get('groupedContent')); //Invoke Selectize's destroy this._selectize.destroy(); //We are no longer in DOM this._selectize = null; }, /** * Event callback that is triggered when user creates a tag */ _create: function _create(input, callback) { // Delete user entered text this._selectize.setTextboxValue(''); // Send create action // allow the observers and computed properties to run first run.schedule('actions', this, function () { this.sendAction('create-item', input); }); // We cancel the creation here, so it's up to you to include the created element // in the content and selection property callback(null); }, /** * Event callback for DOM events */ _registerAction: function _registerAction(action) { return run.bind(this, function () { var args = Array.prototype.slice.call(arguments); args.unshift(action); this.sendAction.apply(this, args); }); }, /** * Event callback that is triggered when user types in the input element */ _onType: function _onType(str) { this.set('filter', str); run.schedule('actions', this, function () { this.sendAction('update-filter', str); }); }, /** * Event callback triggered when an item is added (when something is selected) * Here we need to update our selection property (if single selection) or array (if multiple selection) * We also send an action */ _onItemAdd: function _onItemAdd(value) { var _this6 = this; var content = this.get('content'); var selection = this.get('selection'); var multiple = this.get('multiple'); if (content) { var obj = content.find(function (item) { return this.getValueFor(item) + '' === value; }, this); if (multiple && isArray(selection) && obj) { var selected = selection.find(function (item) { return isEmpty(_this6.get('_valuePath')) ? item === obj : _this6.getValueFor(obj) === _this6.getValueFor(item); }); if (!selected) { this._addSelection(obj); } } else if (obj) { if (!selection || this.getValueFor(obj) !== this.getValueFor(selection)) { this._updateSelection(obj); } } } }, /** * Event callback triggered when an item is removed (when something is deselected) * Here we need to update our selection property (if single selection, here set to null) or remove item from array (if multiple selection) */ _onItemRemove: function _onItemRemove(value) { //in order to know if this event was triggered by observers or if it came from user interaction if (this._removing) { return; } var content = this.get('content'); var selection = this.get('selection'); var multiple = this.get('multiple'); if (content) { var obj = content.find(function (item) { return this.getValueFor(item) + '' === value; }, this); if (multiple && isArray(selection) && obj) { this._removeSelection(obj); } else if (!multiple) { this._updateSelection(null); } } }, /** * Update the selection value and send main actions * In addition to emitting the selection object, a selection value is sent via `select-value` based on `optionValuePath` */ _updateSelection: function _updateSelection(selection) { this.set('selection', selection); // allow the observers and computed properties to run first run.schedule('actions', this, function () { var value = this.get('value'); this.sendAction('select-item', selection, value); this.sendAction('select-value', value); }); }, _addSelection: function _addSelection(obj) { var val = this.getValueFor(obj); this.get('selection').addObject(obj); run.schedule('actions', this, function () { this.sendAction('add-item', obj); this.sendAction('add-value', val); }); }, _removeSelection: function _removeSelection(obj) { var val = this.getValueFor(obj); this.get('selection').removeObject(obj); run.schedule('actions', this, function () { this.sendAction('remove-item', obj); this.sendAction('remove-value', val); }); }, /** * Ember observer triggered before the selection property is changed * We need to unbind any array observers if we're in multiple selection */ _selectionWillChange: function _selectionWillChange(selection) { var multiple = this.get('multiple'); if (selection && isArray(selection) && multiple) { selection.removeArrayObserver(this, { willChange: 'selectionArrayWillChange', didChange: 'selectionArrayDidChange' }); var len = selection ? get(selection, 'length') : 0; this.selectionArrayWillChange(selection, 0, len); } }, /** * Ember observer triggered when the selection property is changed * We need to bind an array observer when selection is multiple */ _selectionDidChange: observer('selection', function () { var _this7 = this; var selection = this.get('selection'); if (this._oldSelection !== selection) { this._selectionWillChange(this._oldSelection); this._oldSelection = selection; } if (!this._selectize) { return; } var multiple = this.get('multiple'); if (selection) { if (multiple) { assert('When ember-selectize is in multiple mode, the provided selection must be an array.', isArray(selection)); //bind array observers to listen for selection changes selection.addArrayObserver(this, { willChange: 'selectionArrayWillChange', didChange: 'selectionArrayDidChange' }); //Trigger a selection change that will update selectize with the new selection var len = selection ? get(selection, 'length') : 0; this.selectionArrayDidChange(selection, 0, null, len); } else { if (selection.then) { selection.then(function (resolved) { if (resolved) { // Ensure that we don't overwrite new value if (get(_this7, 'selection') === selection) { _this7._selectize.addItem(_this7.getValueFor(resolved)); } } else { //selection was changed to a falsy value. Clear selectize. _this7._selectize.clear(); _this7._selectize.showInput(); } }); } else { this._selectize.addItem(this.getValueFor(selection)); } } } else { //selection was changed to a falsy value. Clear selectize. this._selectize.clear(); this._selectize.showInput(); } }), /** * It is possible to control the selected item through its value. */ _valueDidChange: observer('value', function () { var _this8 = this; if (this.get('multiple')) { return; } var content = this.get('content'); var value = this.get('value'); var selectedValue = this.getValueFor(this.get('selection')); var selection; if (value !== selectedValue) { selection = content ? content.find(function (obj) { return value === _this8.getValueFor(obj); }) : null; this.set('selection', selection); } }), /* * Triggered before the selection array changes * Here we process the removed elements */ selectionArrayWillChange: function selectionArrayWillChange(array, idx, removedCount) { this._removing = true; for (var i = idx; i < idx + removedCount; i++) { this.selectionObjectWasRemoved(array.objectAt(i)); } this._removing = false; }, /* * Triggered after the selection array changes * Here we process the inserted elements */ selectionArrayDidChange: function selectionArrayDidChange(array, idx, removedCount, addedCount) { for (var i = idx; i < idx + addedCount; i++) { this.selectionObjectWasAdded(array.objectAt(i), i); } }, /* * Function that is responsible for Selectize's item inserting logic */ selectionObjectWasAdded: function selectionObjectWasAdded(obj) { if (this._selectize) { this._selectize.addItem(this.getValueFor(obj)); } }, /* * Function that is responsible for Selectize's item removing logic */ selectionObjectWasRemoved: function selectionObjectWasRemoved(obj) { if (this._selectize) { this._selectize.removeItem(this.getValueFor(obj)); } }, /** * Ember observer triggered before the content property is changed * We need to unbind any array observers */ _contentWillChange: function _contentWillChange(content) { if (!this._selectize) { return; } if (isArray(content)) { content.removeArrayObserver(this, { willChange: 'contentArrayWillChange', didChange: 'contentArrayDidChange' }); } //Trigger remove logic var len = content ? get(content, 'length') : 0; this._removing = true; this.contentArrayWillChange(content, 0, len); this._removing = false; }, /** * Ember observer triggered when the content property is changed * We need to bind an array observer to become notified of its changes */ _contentDidChange: observer('content', function () { var _this9 = this; var content = this.get('content'); if (this._oldContent !== content) { this._contentWillChange(this._oldContent); this._oldContent = content; } if (!this._selectize) { return; } if (isArray(content)) { content.addArrayObserver(this, { willChange: 'contentArrayWillChange', didChange: 'contentArrayDidChange' }); } else if (content && content.then) { content.then(function (resolved) { // Ensure that we don't overwrite new value if (get(_this9, 'content') === content) { _this9.set('content', resolved); } }); } var len = content ? get(content, 'length') : 0; this.contentArrayDidChange(content, 0, null, len); }), /* * Triggered before the content array changes * Here we process the removed elements */ contentArrayWillChange: function contentArrayWillChange(array, idx, removedCount) { for (var i = idx; i < idx + removedCount; i++) { this.objectWasRemoved(array.objectAt(i)); } if (this._selectize) { this._selectize.refreshOptions(this._selectize.isFocused && !this._selectize.isInputHidden); } }, /* * Triggered after the content array changes * Here we process the inserted elements */ contentArrayDidChange: function contentArrayDidChange(array, idx, removedCount, addedCount) { for (var i = idx; i < idx + addedCount; i++) { this.objectWasAdded(array.objectAt(i)); this.addLabelObserver(array.objectAt(i)); } if (this._selectize) { this._selectize.refreshOptions(this._selectize.isFocused && !this._selectize.isInputHidden); } this._selectionDidChange(); }, _groupedContentWillChange: function _groupedContentWillChange(groupedContent) { var _this10 = this; if (!this._selectize) { return; } if (isEmpty(groupedContent)) { return; } groupedContent.forEach(function (group) { group.get('content').removeArrayObserver(_this10, { willChange: '_groupedContentArrayWillChange', didChange: '_groupedContentArrayDidChange' }); }); }, /** * Ember observer triggered when the groupedContent property is changed * We need to bind an array observer to become notified of each group's array changes, * then notify that the parent array has changed. This is because computed properties * have trouble with nested array changes. */ _groupedContentDidChange: observer('groupedContent', function () { var _this11 = this; var groupedContent = this.get('groupedContent'); if (this._oldGroupedContent !== groupedContent) { this._groupedContentWillChange(this._oldGroupedContent); this._oldGroupedContent = groupedContent; } if (!this._selectize) { return; } if (isEmpty(groupedContent)) { return; } //var willChangeWrapper = run.bind(this, function() { this.groupedContentArrayWillChange.apply(this, arguments); }); //var didChangeWrapper = run.bind(this, function() { this.groupedContentArrayDidChange.apply(this, arguments); }); groupedContent.forEach(function (group) { group.get('content').addArrayObserver(_this11, { willChange: '_groupedContentArrayWillChange', didChange: '_groupedContentArrayDidChange' }); }); var len = groupedContent ? get(groupedContent, 'length') : 0; this._groupedContentArrayDidChange(groupedContent, 0, null, len); }), /* * Triggered before the grouped content array changes * Here we process the removed elements */ _groupedContentArrayWillChange: function _groupedContentArrayWillChange() {}, /* * Triggered after the grouped content array changes * Here we process the inserted elements */ _groupedContentArrayDidChange: function _groupedContentArrayDidChange() { this.notifyPropertyChange('groupedContent.[]'); }, /* * Function that is responsible for Selectize's option inserting logic * If the option is an object or Ember instance, we set an observer on the label value of it. * This way, we can later update the label of it. * Useful for dealing with objects that 'lazy load' some properties/relationships. */ objectWasAdded: function objectWasAdded(obj) { var data = {}; var sortField = this.get('sortField'); if (typeOf(obj) === 'object' || typeOf(obj) === 'instance') { data = { label: this.getLabelFor(obj), value: this.getValueFor(obj), data: obj }; if (sortField) { if (isArray(sortField)) { sortField.forEach(function (field) { data[field.field] = get(obj, field.field); }); } else { data[sortField] = get(obj, sortField); } } if (get(obj, this.get('_groupPath'))) { data.optgroup = get(obj, this.get('_groupPath')); } } else { data = { label: obj, value: obj, data: obj }; if (sortField && !isArray(sortField)) { data[sortField] = obj; } } if (this._selectize && data.label) { this._selectize.addOption(data); } }, addLabelObserver: function addLabelObserver(obj) { //Only attach observer if the label is a property of an object if (typeOf(obj) === 'object' || typeOf(obj) === 'instance') { _ember['default'].addObserver(obj, this.get('_labelPath'), this, '_labelDidChange'); } }, /* * Function that is responsible for Selectize's option removing logic */ objectWasRemoved: function objectWasRemoved(obj) { if (typeOf(obj) === 'object' || typeOf(obj) === 'instance') { _ember['default'].removeObserver(obj, this.get('_labelPath'), this, '_labelDidChange'); } if (this._selectize) { this._selectize.removeOption(this.getValueFor(obj)); } }, /* * Ember Observer that triggers when an option's label changes. * Here we need to update its corresponding option with the new data */ _labelDidChange: function _labelDidChange(sender) { if (!this._selectize) { return; } var data = { label: this.getLabelFor(sender), value: this.getValueFor(sender), data: sender }; if (this._selectize.getOption(data.value).length !== 0) { this._selectize.updateOption(data.value, data); } else { this.objectWasAdded(sender); } }, /* * Observer on the disabled property that enables or disables selectize. */ _disabledDidChange: observer('disabled', function () { if (!this._selectize) { return; } var disable = this.get('disabled'); if (disable) { this._selectize.disable(); } else { this._selectize.enable(); } }), /* * Observer on the placeholder property that updates selectize's placeholder. */ _placeholderDidChange: observer('placeholder', function () { if (!this._selectize) { return; } var placeholder = this.get('placeholder'); this._selectize.settings.placeholder = placeholder; this._selectize.updatePlaceholder(); }), /* * Observer on the loading property. * Here we add/remove a css class, similarly to how selectize does. */ _loadingDidChange: observer('loading', function () { var loading = this.get('loading'); var loadingClass = this.get('loadingClass'); if (loading) { this._selectize.$wrapper.addClass(loadingClass); } else { this._selectize.$wrapper.removeClass(loadingClass); } }), _lookupComponent: function _lookupComponent(name) { var owner = getOwner(this); var componentLookupKey = 'component:' + name; var layoutLookupKey = 'template:components/' + name; var layout = owner._lookupFactory(layoutLookupKey); var component = owner._lookupFactory(componentLookupKey); if (layout && !component) { owner.register(componentLookupKey, Component); component = owner._lookupFactory(componentLookupKey); } return { component: component, layout: layout }; }, _componentToDOM: function _componentToDOM(componentName, data) { var _lookupComponent2 = this._lookupComponent(componentName); var component = _lookupComponent2.component; var layout = _lookupComponent2.layout; assert('ember-selectize could not find a component named "' + componentName + '" in your Ember application.', component); var attrs = { data: data }; if (layout) { attrs.layout = layout; } var componentInstance = component.create(attrs); var container = document.createElement('div'); componentInstance.appendTo(container); return container; }, _mergeSortField: function _mergeSortField(options) { var sortField = this.get('sortField'); if (sortField) { var sortArray = this._getSortArray(sortField); assign(options, { sortField: sortArray }); } return options; }, _getSortArray: function _getSortArray(sortField) { if (isArray(sortField)) { return sortField; } else { return [{ field: sortField, direction: this.get('sortDirection') }]; } } }); }); define('ember-click-outside/components/click-outside', ['exports', 'ember-click-outside/mixins/click-outside', 'ember-click-outside/templates/components/click-outside', 'ember-component', 'ember-evented/on', 'ember-runloop', 'jquery'], function (exports, _emberClickOutsideMixinsClickOutside, _emberClickOutsideTemplatesComponentsClickOutside, _emberComponent, _emberEventedOn, _emberRunloop, _jquery) { 'use strict'; exports['default'] = _emberComponent['default'].extend(_emberClickOutsideMixinsClickOutside['default'], { layout: _emberClickOutsideTemplatesComponentsClickOutside['default'], clickOutside: function clickOutside(e) { var exceptSelector = this.get('except-selector'); if (exceptSelector && (0, _jquery['default'])(e.target).closest(exceptSelector).length > 0) { return; } this.sendAction(); }, _attachClickOutsideHandler: (0, _emberEventedOn['default'])('didInsertElement', function () { this._cancelOutsideListenerSetup = (0, _emberRunloop.next)(this, this.addClickOutsideListener); }), _removeClickOutsideHandler: (0, _emberEventedOn['default'])('willDestroyElement', function () { (0, _emberRunloop.cancel)(this._cancelOutsideListerSetup); this.removeClickOutsideListener(); }) }); }); define('ember-click-outside/mixins/click-outside', ['exports', 'ember', 'jquery'], function (exports, _ember, _jquery) { 'use strict'; var computed = _ember['default'].computed; var K = _ember['default'].K; var bound = function bound(fnName) { return computed(fnName, function () { return this.get(fnName).bind(this); }); }; exports['default'] = _ember['default'].Mixin.create({ clickOutside: K, clickHandler: bound('outsideClickHandler'), outsideClickHandler: function outsideClickHandler(e) { var element = this.get('element'); var $target = (0, _jquery['default'])(e.target); var isInside = $target.closest(element).length === 1; if (!isInside) { this.clickOutside(e); } }, addClickOutsideListener: function addClickOutsideListener() { var clickHandler = this.get('clickHandler'); (0, _jquery['default'])(window).on('click', clickHandler); }, removeClickOutsideListener: function removeClickOutsideListener() { var clickHandler = this.get('clickHandler'); (0, _jquery['default'])(window).off('click', clickHandler); } }); }); define("ember-click-outside/templates/components/click-outside", ["exports"], function (exports) { "use strict"; exports["default"] = Ember.HTMLBars.template((function () { return { meta: { "revision": "Ember@2.8.0", "loc": { "source": null, "start": { "line": 1, "column": 0 }, "end": { "line": 2, "column": 0 } }, "moduleName": "modules/ember-click-outside/templates/components/click-outside.hbs" }, isEmpty: false, arity: 0, cachedFragment: null, hasRendered: false, buildFragment: function buildFragment(dom) { var el0 = dom.createDocumentFragment(); var el1 = dom.createComment(""); dom.appendChild(el0, el1); var el1 = dom.createTextNode("\n"); dom.appendChild(el0, el1); return el0; }, buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { var morphs = new Array(1); morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); dom.insertBoundary(fragment, 0); return morphs; }, statements: [["content", "yield", ["loc", [null, [1, 0], [1, 9]]], 0, 0, 0, 0]], locals: [], templates: [] }; })()); }); define('ember-composable-helpers/-private/closure-action', ['exports', 'ember'], function (exports, _ember) { 'use strict'; var __loader = _ember['default'].__loader; var ClosureActionModule = { ACTION: null }; if ('ember-htmlbars/keywords/closure-action' in __loader.registry) { ClosureActionModule = __loader.require('ember-htmlbars/keywords/closure-action'); } else if ('ember-routing-htmlbars/keywords/closure-action' in __loader.registry) { ClosureActionModule = __loader.require('ember-routing-htmlbars/keywords/closure-action'); } exports['default'] = ClosureActionModule.ACTION; }); define('ember-composable-helpers/-private/create-multi-array-helper', ['exports', 'ember', 'ember-array/utils', 'ember-helper', 'ember-metal/utils', 'ember-metal/observer', 'ember-metal/get', 'ember-metal/set', 'ember-utils'], function (exports, _ember, _emberArrayUtils, _emberHelper, _emberMetalUtils, _emberMetalObserver, _emberMetalGet, _emberMetalSet, _emberUtils) { 'use strict'; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];return arr2; } else { return Array.from(arr); } } function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } var defineProperty = _ember['default'].defineProperty; var idForArray = function idForArray(array) { return '__array-' + (0, _emberMetalUtils.guidFor)(array); }; exports['default'] = function (multiArrayComputed) { return _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _toArray(_ref); var arrays = _ref2; (0, _emberMetalSet['default'])(this, 'arrays', arrays.map(function (obj) { if ((0, _emberArrayUtils.isEmberArray)(obj)) { return (0, _emberArrayUtils.A)(obj); } return obj; })); return (0, _emberMetalGet['default'])(this, 'content'); }, valuesDidChange: (0, _emberMetalObserver['default'])('arrays.[]', function () { this._recomputeArrayKeys(); var arrays = (0, _emberMetalGet['default'])(this, 'arrays'); var arrayKeys = (0, _emberMetalGet['default'])(this, 'arrayKeys'); if ((0, _emberUtils.isEmpty)(arrays)) { defineProperty(this, 'content', []); return; } defineProperty(this, 'content', multiArrayComputed.apply(undefined, _toConsumableArray(arrayKeys))); }), contentDidChange: (0, _emberMetalObserver['default'])('content.[]', function () { this.recompute(); }), _recomputeArrayKeys: function _recomputeArrayKeys() { var _this = this; var arrays = (0, _emberMetalGet['default'])(this, 'arrays'); var oldArrayKeys = (0, _emberMetalGet['default'])(this, 'arrayKeys') || []; var newArrayKeys = arrays.map(idForArray); var keysToRemove = oldArrayKeys.filter(function (key) { return newArrayKeys.indexOf(key) === -1; }); keysToRemove.forEach(function (key) { return (0, _emberMetalSet['default'])(_this, key, null); }); arrays.forEach(function (array) { return (0, _emberMetalSet['default'])(_this, idForArray(array), array); }); (0, _emberMetalSet['default'])(this, 'arrayKeys', newArrayKeys); } }); }; }); define('ember-composable-helpers/-private/create-needle-haystack-helper', ['exports', 'ember', 'ember-computed', 'ember-helper', 'ember-metal/get', 'ember-metal/observer', 'ember-metal/set'], function (exports, _ember, _emberComputed, _emberHelper, _emberMetalGet, _emberMetalObserver, _emberMetalSet) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports['default'] = createNeedleHaystackHelper; var K = _ember['default'].K; var isEmpty = _ember['default'].isEmpty; /** * Creates a generic Helper class implementation that expects a `needle` and * `haystack` as arguments. A `fn` function is required to be passed in * that is invoked with the `needle` and `haystack` arguments. * * @private * @param {Function} fn A function to run against the needle and haystack * @return {Any} */ function createNeedleHaystackHelper() { var fn = arguments.length <= 0 || arguments[0] === undefined ? K : arguments[0]; return _emberHelper['default'].extend({ content: (0, _emberComputed['default'])('needle.[]', 'haystack.[]', 'option', function () { var needle = (0, _emberMetalGet['default'])(this, 'needle'); var haystack = (0, _emberMetalGet['default'])(this, 'haystack'); var option = (0, _emberMetalGet['default'])(this, 'option'); return fn(needle, haystack, option); }).readOnly(), compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 3); var needle = _ref2[0]; var option = _ref2[1]; var haystack = _ref2[2]; if (isEmpty(haystack)) { haystack = option; option = null; } (0, _emberMetalSet['default'])(this, 'needle', needle); (0, _emberMetalSet['default'])(this, 'haystack', haystack); (0, _emberMetalSet['default'])(this, 'option', option); return (0, _emberMetalGet['default'])(this, 'content'); }, contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); } }); define('ember-composable-helpers/-private/create-string-helper', ['exports'], function (exports) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports['default'] = function (stringFunction) { return function (_ref) { var _ref2 = _slicedToArray(_ref, 1); var string = _ref2[0]; string = string || ''; return stringFunction(string); }; }; }); define('ember-composable-helpers/helpers/append', ['exports', 'ember-computed', 'ember-metal/get', 'ember-array/utils', 'ember-composable-helpers/-private/create-multi-array-helper'], function (exports, _emberComputed, _emberMetalGet, _emberArrayUtils, _emberComposableHelpersPrivateCreateMultiArrayHelper) { 'use strict'; exports.append = append; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];return arr2; } else { return Array.from(arr); } } function append() { for (var _len = arguments.length, dependentKeys = Array(_len), _key = 0; _key < _len; _key++) { dependentKeys[_key] = arguments[_key]; } dependentKeys = dependentKeys || []; var arrayKeys = dependentKeys.map(function (dependentKey) { return dependentKey + '.[]'; }); return _emberComputed['default'].apply(undefined, _toConsumableArray(arrayKeys).concat([function () { var _ref, _this = this; var array = dependentKeys.map(function (dependentKey) { var value = (0, _emberMetalGet['default'])(_this, dependentKey); return (0, _emberArrayUtils.isEmberArray)(value) ? value.toArray() : [value]; }); return (_ref = []).concat.apply(_ref, _toConsumableArray(array)); }])); } exports['default'] = (0, _emberComposableHelpersPrivateCreateMultiArrayHelper['default'])(append); }); define('ember-composable-helpers/helpers/array', ['exports', 'ember-helper', 'ember-array/utils'], function (exports, _emberHelper, _emberArrayUtils) { 'use strict'; exports.array = array; function array() { var params = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; // slice params to avoid mutating the provided params return (0, _emberArrayUtils.A)(params.slice()); } exports['default'] = (0, _emberHelper.helper)(array); }); define('ember-composable-helpers/helpers/camelize', ['exports', 'ember-helper', 'ember-string', 'ember-composable-helpers/-private/create-string-helper'], function (exports, _emberHelper, _emberString, _emberComposableHelpersPrivateCreateStringHelper) { 'use strict'; var camelize = (0, _emberComposableHelpersPrivateCreateStringHelper['default'])(_emberString.camelize); exports.camelize = camelize; exports['default'] = (0, _emberHelper.helper)(camelize); }); define('ember-composable-helpers/helpers/capitalize', ['exports', 'ember-helper', 'ember-string', 'ember-composable-helpers/-private/create-string-helper'], function (exports, _emberHelper, _emberString, _emberComposableHelpersPrivateCreateStringHelper) { 'use strict'; var capitalize = (0, _emberComposableHelpersPrivateCreateStringHelper['default'])(_emberString.capitalize); exports.capitalize = capitalize; exports['default'] = (0, _emberHelper.helper)(capitalize); }); define('ember-composable-helpers/helpers/chunk', ['exports', 'ember-array/utils', 'ember-computed', 'ember-helper', 'ember-metal/get', 'ember-metal/observer', 'ember-metal/set'], function (exports, _emberArrayUtils, _emberComputed, _emberHelper, _emberMetalGet, _emberMetalObserver, _emberMetalSet) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports.chunk = chunk; var max = Math.max; var ceil = Math.ceil; function chunk(num, array) { var integer = parseInt(num, 10); var size = max(integer, 0); var length = 0; if ((0, _emberArrayUtils.isEmberArray)(array)) { length = (0, _emberMetalGet['default'])(array, 'length'); } if (!length || size < 1) { return []; } else { var index = 0; var resultIndex = -1; var result = new Array(ceil(length / size)); while (index < length) { result[++resultIndex] = array.slice(index, index += size); } return result; } } exports['default'] = _emberHelper['default'].extend({ content: (0, _emberComputed['default'])('num', 'array.[]', function () { var array = (0, _emberMetalGet['default'])(this, 'array'); var num = (0, _emberMetalGet['default'])(this, 'num'); return chunk(num, array); }), compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 2); var num = _ref2[0]; var array = _ref2[1]; (0, _emberMetalSet['default'])(this, 'array', array); (0, _emberMetalSet['default'])(this, 'num', num); return (0, _emberMetalGet['default'])(this, 'content'); }, contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/classify', ['exports', 'ember-helper', 'ember-string', 'ember-composable-helpers/-private/create-string-helper'], function (exports, _emberHelper, _emberString, _emberComposableHelpersPrivateCreateStringHelper) { 'use strict'; var classify = (0, _emberComposableHelpersPrivateCreateStringHelper['default'])(_emberString.classify); exports.classify = classify; exports['default'] = (0, _emberHelper.helper)(classify); }); define('ember-composable-helpers/helpers/compact', ['exports', 'ember-array/utils', 'ember-computed', 'ember-helper', 'ember-metal/get', 'ember-metal/observer', 'ember-metal/set', 'ember-utils'], function (exports, _emberArrayUtils, _emberComputed, _emberHelper, _emberMetalGet, _emberMetalObserver, _emberMetalSet, _emberUtils) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 1); var array = _ref2[0]; if (!(0, _emberArrayUtils.isEmberArray)(array)) { return (0, _emberArrayUtils.A)([array]); } (0, _emberMetalSet['default'])(this, 'array', array); return (0, _emberMetalGet['default'])(this, 'content'); }, content: (0, _emberComputed.filter)('array', _emberUtils.isPresent), contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/compute', ['exports', 'ember-helper'], function (exports, _emberHelper) { 'use strict'; exports.compute = compute; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];return arr2; } else { return Array.from(arr); } } function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } function compute(_ref) { var _ref2 = _toArray(_ref); var action = _ref2[0]; var params = _ref2.slice(1); return action.apply(undefined, _toConsumableArray(params)); } exports['default'] = (0, _emberHelper.helper)(compute); }); define('ember-composable-helpers/helpers/contains', ['exports', 'ember-array/utils', 'ember-metal/get', 'ember-composable-helpers/-private/create-needle-haystack-helper', 'ember-composable-helpers/utils/includes'], function (exports, _emberArrayUtils, _emberMetalGet, _emberComposableHelpersPrivateCreateNeedleHaystackHelper, _emberComposableHelpersUtilsIncludes) { 'use strict'; exports.contains = contains; function _contains(needle, haystack) { return (0, _emberComposableHelpersUtilsIncludes['default'])((0, _emberArrayUtils.A)(haystack), needle); } function contains(needle, haystack) { if (!(0, _emberArrayUtils.isEmberArray)(haystack)) { return false; } if ((0, _emberArrayUtils.isEmberArray)(needle) && (0, _emberMetalGet['default'])(needle, 'length')) { return needle.reduce(function (acc, val) { return acc && _contains(val, haystack); }, true); } return _contains(needle, haystack); } exports['default'] = (0, _emberComposableHelpersPrivateCreateNeedleHaystackHelper['default'])(contains); }); define('ember-composable-helpers/helpers/dasherize', ['exports', 'ember-helper', 'ember-string', 'ember-composable-helpers/-private/create-string-helper'], function (exports, _emberHelper, _emberString, _emberComposableHelpersPrivateCreateStringHelper) { 'use strict'; var dasherize = (0, _emberComposableHelpersPrivateCreateStringHelper['default'])(_emberString.dasherize); exports.dasherize = dasherize; exports['default'] = (0, _emberHelper.helper)(dasherize); }); define('ember-composable-helpers/helpers/dec', ['exports', 'ember-helper', 'ember-utils'], function (exports, _emberHelper, _emberUtils) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports.dec = dec; function dec(_ref) { var _ref2 = _slicedToArray(_ref, 2); var step = _ref2[0]; var val = _ref2[1]; if ((0, _emberUtils.isEmpty)(val)) { val = step; step = undefined; } val = parseInt(val); if (isNaN(val)) { return; } if (step === undefined) { step = 1; } return val - step; } exports['default'] = (0, _emberHelper.helper)(dec); }); define('ember-composable-helpers/helpers/drop', ['exports', 'ember-helper', 'ember-metal/observer', 'ember-metal/set'], function (exports, _emberHelper, _emberMetalObserver, _emberMetalSet) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 2); var dropAmount = _ref2[0]; var array = _ref2[1]; (0, _emberMetalSet['default'])(this, 'array', array); return array.slice(dropAmount); }, arrayContentDidChange: (0, _emberMetalObserver['default'])('array.[]', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/filter-by', ['exports', 'ember', 'ember-array/utils', 'ember-computed', 'ember-helper', 'ember-metal/get', 'ember-metal/observer', 'ember-metal/set', 'ember-utils'], function (exports, _ember, _emberArrayUtils, _emberComputed, _emberHelper, _emberMetalGet, _emberMetalObserver, _emberMetalSet, _emberUtils) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var defineProperty = _ember['default'].defineProperty; exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 3); var byPath = _ref2[0]; var value = _ref2[1]; var array = _ref2[2]; if (!(0, _emberArrayUtils.isEmberArray)(array) && (0, _emberArrayUtils.isEmberArray)(value)) { array = value; value = undefined; } (0, _emberMetalSet['default'])(this, 'array', array); (0, _emberMetalSet['default'])(this, 'byPath', byPath); (0, _emberMetalSet['default'])(this, 'value', value); return (0, _emberMetalGet['default'])(this, 'content'); }, byPathDidChange: (0, _emberMetalObserver['default'])('byPath', 'value', function () { var byPath = (0, _emberMetalGet['default'])(this, 'byPath'); var value = (0, _emberMetalGet['default'])(this, 'value'); if ((0, _emberUtils.isEmpty)(byPath)) { defineProperty(this, 'content', []); return; } var filterFn = undefined; if ((0, _emberUtils.isPresent)(value)) { if (typeof value === 'function') { filterFn = function (item) { return value((0, _emberMetalGet['default'])(item, byPath)); }; } else { filterFn = function (item) { return (0, _emberMetalGet['default'])(item, byPath) === value; }; } } else { filterFn = function (item) { return (0, _emberUtils.isPresent)((0, _emberMetalGet['default'])(item, byPath)); }; } var cp = (0, _emberComputed.filter)('array.@each.' + byPath, filterFn); defineProperty(this, 'content', cp); }), contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/filter', ['exports', 'ember', 'ember-computed', 'ember-helper', 'ember-metal/get', 'ember-metal/observer', 'ember-metal/set', 'ember-utils'], function (exports, _ember, _emberComputed, _emberHelper, _emberMetalGet, _emberMetalObserver, _emberMetalSet, _emberUtils) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var defineProperty = _ember['default'].defineProperty; exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 2); var callback = _ref2[0]; var array = _ref2[1]; (0, _emberMetalSet['default'])(this, 'array', array); (0, _emberMetalSet['default'])(this, 'callback', callback); return (0, _emberMetalGet['default'])(this, 'content'); }, callbackDidChange: (0, _emberMetalObserver['default'])('callback', function () { var callback = (0, _emberMetalGet['default'])(this, 'callback'); if ((0, _emberUtils.isEmpty)(callback)) { defineProperty(this, 'content', []); return; } var cp = (0, _emberComputed.filter)('array', callback); defineProperty(this, 'content', cp); }), contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/find-by', ['exports', 'ember', 'ember-computed', 'ember-helper', 'ember-metal/get', 'ember-metal/observer', 'ember-metal/set', 'ember-array/utils', 'ember-utils'], function (exports, _ember, _emberComputed, _emberHelper, _emberMetalGet, _emberMetalObserver, _emberMetalSet, _emberArrayUtils, _emberUtils) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var defineProperty = _ember['default'].defineProperty; exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 3); var byPath = _ref2[0]; var value = _ref2[1]; var array = _ref2[2]; (0, _emberMetalSet['default'])(this, 'array', array); (0, _emberMetalSet['default'])(this, 'byPath', byPath); (0, _emberMetalSet['default'])(this, 'value', value); return (0, _emberMetalGet['default'])(this, 'content'); }, byPathDidChange: (0, _emberMetalObserver['default'])('byPath', function () { var byPath = (0, _emberMetalGet['default'])(this, 'byPath'); if ((0, _emberUtils.isEmpty)(byPath)) { defineProperty(this, 'content', []); return; } defineProperty(this, 'content', (0, _emberComputed['default'])('array.@each.' + byPath, 'value', function () { var array = (0, _emberMetalGet['default'])(this, 'array'); var value = (0, _emberMetalGet['default'])(this, 'value'); return (0, _emberArrayUtils.A)(array).findBy(byPath, value); })); }), contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/flatten', ['exports', 'ember-helper', 'ember-array/utils', 'ember-metal/observer', 'ember-metal/set'], function (exports, _emberHelper, _emberArrayUtils, _emberMetalObserver, _emberMetalSet) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports.flatten = flatten; function flatten(array) { if (!(0, _emberArrayUtils.isEmberArray)(array)) { return array; } return array.reduce(function (flattened, el) { return flattened.concat(flatten(el)); }, []); } exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 1); var array = _ref2[0]; (0, _emberMetalSet['default'])(this, 'array', array); return flatten(array); }, arrayContentDidChange: (0, _emberMetalObserver['default'])('array.[]', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/group-by', ['exports', 'ember', 'ember-array/utils', 'ember-computed', 'ember-helper', 'ember-metal/get', 'ember-metal/observer', 'ember-metal/set'], function (exports, _ember, _emberArrayUtils, _emberComputed, _emberHelper, _emberMetalGet, _emberMetalObserver, _emberMetalSet) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var defineProperty = _ember['default'].defineProperty; var emberObject = _ember['default'].Object; var groupFunction = function groupFunction() { var array = (0, _emberMetalGet['default'])(this, 'array'); var byPath = (0, _emberMetalGet['default'])(this, 'byPath'); var groups = emberObject.create(); array.forEach(function (item) { var groupName = (0, _emberMetalGet['default'])(item, byPath); var group = (0, _emberMetalGet['default'])(groups, groupName); if (!(0, _emberArrayUtils.isEmberArray)(group)) { group = (0, _emberArrayUtils.A)(); (0, _emberMetalSet['default'])(groups, groupName, group); } group.push(item); }); return groups; }; exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 2); var byPath = _ref2[0]; var array = _ref2[1]; (0, _emberMetalSet['default'])(this, 'array', array); (0, _emberMetalSet['default'])(this, 'byPath', byPath); return (0, _emberMetalGet['default'])(this, 'content'); }, byPathDidChange: (0, _emberMetalObserver['default'])('byPath', function () { var byPath = (0, _emberMetalGet['default'])(this, 'byPath'); if (byPath) { defineProperty(this, 'content', (0, _emberComputed['default'])('array.@each.' + byPath, groupFunction)); } else { defineProperty(this, 'content', null); } }), contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/has-next', ['exports', 'ember', 'ember-composable-helpers/helpers/next', 'ember-composable-helpers/-private/create-needle-haystack-helper', 'ember-composable-helpers/utils/is-equal'], function (exports, _ember, _emberComposableHelpersHelpersNext, _emberComposableHelpersPrivateCreateNeedleHaystackHelper, _emberComposableHelpersUtilsIsEqual) { 'use strict'; exports.hasNext = hasNext; var isPresent = _ember['default'].isPresent; function hasNext(currentValue, array) { var useDeepEqual = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; var nextValue = (0, _emberComposableHelpersHelpersNext.next)(currentValue, array, useDeepEqual); var isNotSameValue = !(0, _emberComposableHelpersUtilsIsEqual['default'])(nextValue, currentValue, useDeepEqual); return isNotSameValue && isPresent(nextValue); } exports['default'] = (0, _emberComposableHelpersPrivateCreateNeedleHaystackHelper['default'])(hasNext); }); define('ember-composable-helpers/helpers/has-previous', ['exports', 'ember', 'ember-composable-helpers/helpers/previous', 'ember-composable-helpers/-private/create-needle-haystack-helper', 'ember-composable-helpers/utils/is-equal'], function (exports, _ember, _emberComposableHelpersHelpersPrevious, _emberComposableHelpersPrivateCreateNeedleHaystackHelper, _emberComposableHelpersUtilsIsEqual) { 'use strict'; exports.hasPrevious = hasPrevious; var isPresent = _ember['default'].isPresent; function hasPrevious(currentValue, array) { var useDeepEqual = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; var previousValue = (0, _emberComposableHelpersHelpersPrevious.previous)(currentValue, array, useDeepEqual); var isNotSameValue = !(0, _emberComposableHelpersUtilsIsEqual['default'])(previousValue, currentValue, useDeepEqual); return isNotSameValue && isPresent(previousValue); } exports['default'] = (0, _emberComposableHelpersPrivateCreateNeedleHaystackHelper['default'])(hasPrevious); }); define('ember-composable-helpers/helpers/html-safe', ['exports', 'ember-helper', 'ember-string', 'ember-composable-helpers/-private/create-string-helper'], function (exports, _emberHelper, _emberString, _emberComposableHelpersPrivateCreateStringHelper) { 'use strict'; var htmlSafe = (0, _emberComposableHelpersPrivateCreateStringHelper['default'])(_emberString.htmlSafe); exports.htmlSafe = htmlSafe; exports['default'] = (0, _emberHelper.helper)(htmlSafe); }); define('ember-composable-helpers/helpers/inc', ['exports', 'ember-helper', 'ember-utils'], function (exports, _emberHelper, _emberUtils) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports.inc = inc; function inc(_ref) { var _ref2 = _slicedToArray(_ref, 2); var step = _ref2[0]; var val = _ref2[1]; if ((0, _emberUtils.isEmpty)(val)) { val = step; step = undefined; } val = parseInt(val); if (isNaN(val)) { return; } if (step === undefined) { step = 1; } return val + step; } exports['default'] = (0, _emberHelper.helper)(inc); }); define('ember-composable-helpers/helpers/intersect', ['exports', 'ember-computed', 'ember-composable-helpers/-private/create-multi-array-helper'], function (exports, _emberComputed, _emberComposableHelpersPrivateCreateMultiArrayHelper) { 'use strict'; exports['default'] = (0, _emberComposableHelpersPrivateCreateMultiArrayHelper['default'])(_emberComputed.intersect); }); define('ember-composable-helpers/helpers/invoke', ['exports', 'ember-array/utils', 'ember-helper', 'ember-utils', 'rsvp'], function (exports, _emberArrayUtils, _emberHelper, _emberUtils, _rsvp) { 'use strict'; exports.invoke = invoke; function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } var all = _rsvp['default'].all; function invoke(_ref) { var _ref2 = _toArray(_ref); var methodName = _ref2[0]; var args = _ref2.slice(1); var obj = args.pop(); if ((0, _emberArrayUtils.isEmberArray)(obj)) { return function () { var promises = obj.map(function (item) { return (0, _emberUtils.tryInvoke)(item, methodName, args); }); return all(promises); }; } return function () { return (0, _emberUtils.tryInvoke)(obj, methodName, args); }; } exports['default'] = (0, _emberHelper.helper)(invoke); }); define('ember-composable-helpers/helpers/join', ['exports', 'ember-array/utils', 'ember-helper', 'ember-metal/observer', 'ember-metal/set'], function (exports, _emberArrayUtils, _emberHelper, _emberMetalObserver, _emberMetalSet) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 2); var separator = _ref2[0]; var array = _ref2[1]; if ((0, _emberArrayUtils.isEmberArray)(separator)) { array = separator; separator = ','; } (0, _emberMetalSet['default'])(this, 'array', array); return array.join(separator); }, arrayContentDidChange: (0, _emberMetalObserver['default'])('array.[]', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/map-by', ['exports', 'ember', 'ember-computed', 'ember-helper', 'ember-metal/get', 'ember-metal/observer', 'ember-metal/set', 'ember-utils'], function (exports, _ember, _emberComputed, _emberHelper, _emberMetalGet, _emberMetalObserver, _emberMetalSet, _emberUtils) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var defineProperty = _ember['default'].defineProperty; exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 2); var byPath = _ref2[0]; var array = _ref2[1]; (0, _emberMetalSet['default'])(this, 'array', array); (0, _emberMetalSet['default'])(this, 'byPath', byPath); return (0, _emberMetalGet['default'])(this, 'content'); }, byPathDidChange: (0, _emberMetalObserver['default'])('byPath', function () { var byPath = (0, _emberMetalGet['default'])(this, 'byPath'); if ((0, _emberUtils.isEmpty)(byPath)) { defineProperty(this, 'content', []); return; } defineProperty(this, 'content', (0, _emberComputed.mapBy)('array', byPath)); }), contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/map', ['exports', 'ember', 'ember-computed', 'ember-helper', 'ember-metal/get', 'ember-metal/observer', 'ember-metal/set', 'ember-utils'], function (exports, _ember, _emberComputed, _emberHelper, _emberMetalGet, _emberMetalObserver, _emberMetalSet, _emberUtils) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var defineProperty = _ember['default'].defineProperty; exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 2); var callback = _ref2[0]; var array = _ref2[1]; (0, _emberMetalSet['default'])(this, 'array', array); (0, _emberMetalSet['default'])(this, 'callback', callback); return (0, _emberMetalGet['default'])(this, 'content'); }, byPathDidChange: (0, _emberMetalObserver['default'])('callback', function () { var callback = (0, _emberMetalGet['default'])(this, 'callback'); if ((0, _emberUtils.isEmpty)(callback)) { defineProperty(this, 'content', []); return; } defineProperty(this, 'content', (0, _emberComputed.map)('array', callback)); }), contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/next', ['exports', 'ember', 'ember-composable-helpers/utils/get-index', 'ember-composable-helpers/-private/create-needle-haystack-helper'], function (exports, _ember, _emberComposableHelpersUtilsGetIndex, _emberComposableHelpersPrivateCreateNeedleHaystackHelper) { 'use strict'; exports.next = next; var get = _ember['default'].get; var isEmpty = _ember['default'].isEmpty; function next(currentValue, array) { var useDeepEqual = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; var currentIndex = (0, _emberComposableHelpersUtilsGetIndex['default'])(array, currentValue, useDeepEqual); var lastIndex = get(array, 'length') - 1; if (isEmpty(currentIndex)) { return; } return currentIndex === lastIndex ? currentValue : array[currentIndex + 1]; } exports['default'] = (0, _emberComposableHelpersPrivateCreateNeedleHaystackHelper['default'])(next); }); define('ember-composable-helpers/helpers/object-at', ['exports', 'ember-helper', 'ember-array/utils', 'ember-computed', 'ember-metal/observer', 'ember-metal/get', 'ember-metal/set'], function (exports, _emberHelper, _emberArrayUtils, _emberComputed, _emberMetalObserver, _emberMetalGet, _emberMetalSet) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports.objectAt = objectAt; function objectAt(index, array) { if (!(0, _emberArrayUtils.isEmberArray)(array)) { return undefined; } index = parseInt(index, 10); return (0, _emberArrayUtils.A)(array).objectAt(index); } exports['default'] = _emberHelper['default'].extend({ content: (0, _emberComputed['default'])('index', 'array.[]', function () { var index = (0, _emberMetalGet['default'])(this, 'index'); var array = (0, _emberMetalGet['default'])(this, 'array'); return objectAt(index, array); }), compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 2); var index = _ref2[0]; var array = _ref2[1]; (0, _emberMetalSet['default'])(this, 'index', index); (0, _emberMetalSet['default'])(this, 'array', array); return (0, _emberMetalGet['default'])(this, 'content'); }, contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/optional', ['exports', 'ember-helper'], function (exports, _emberHelper) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports.optional = optional; function optional(_ref) { var _ref2 = _slicedToArray(_ref, 1); var action = _ref2[0]; if (typeof action === 'function') { return action; } return function (i) { return i; }; } exports['default'] = (0, _emberHelper.helper)(optional); }); define('ember-composable-helpers/helpers/pipe-action', ['exports', 'ember-helper', 'ember-composable-helpers/helpers/pipe', 'ember-composable-helpers/-private/closure-action'], function (exports, _emberHelper, _emberComposableHelpersHelpersPipe, _emberComposableHelpersPrivateClosureAction) { 'use strict'; var closurePipe = _emberComposableHelpersHelpersPipe.pipe; if (_emberComposableHelpersPrivateClosureAction['default']) { closurePipe[_emberComposableHelpersPrivateClosureAction['default']] = true; } exports['default'] = (0, _emberHelper.helper)(closurePipe); }); define('ember-composable-helpers/helpers/pipe', ['exports', 'ember-helper', 'ember-composable-helpers/utils/is-promise'], function (exports, _emberHelper, _emberComposableHelpersUtilsIsPromise) { 'use strict'; exports.invokeFunction = invokeFunction; exports.pipe = pipe; function invokeFunction(acc, curr) { if ((0, _emberComposableHelpersUtilsIsPromise['default'])(acc)) { return acc.then(curr); } return curr(acc); } function pipe() { var actions = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return actions.reduce(function (acc, curr, idx) { if (idx === 0) { return curr.apply(undefined, args); } return invokeFunction(acc, curr); }, undefined); }; } exports['default'] = (0, _emberHelper.helper)(pipe); }); define('ember-composable-helpers/helpers/previous', ['exports', 'ember', 'ember-composable-helpers/utils/get-index', 'ember-composable-helpers/-private/create-needle-haystack-helper'], function (exports, _ember, _emberComposableHelpersUtilsGetIndex, _emberComposableHelpersPrivateCreateNeedleHaystackHelper) { 'use strict'; exports.previous = previous; var isEmpty = _ember['default'].isEmpty; function previous(currentValue, array) { var useDeepEqual = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; var currentIndex = (0, _emberComposableHelpersUtilsGetIndex['default'])(array, currentValue, useDeepEqual); if (isEmpty(currentIndex)) { return; } return currentIndex === 0 ? currentValue : array[currentIndex - 1]; } exports['default'] = (0, _emberComposableHelpersPrivateCreateNeedleHaystackHelper['default'])(previous); }); define('ember-composable-helpers/helpers/queue', ['exports', 'ember-helper', 'ember-composable-helpers/utils/is-promise'], function (exports, _emberHelper, _emberComposableHelpersUtilsIsPromise) { 'use strict'; exports.queue = queue; function queue() { var actions = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var invokeWithArgs = function invokeWithArgs(acc, curr) { if ((0, _emberComposableHelpersUtilsIsPromise['default'])(acc)) { return acc.then(function () { return curr.apply(undefined, args); }); } return curr.apply(undefined, args); }; return actions.reduce(function (acc, curr, idx) { if (idx === 0) { return curr.apply(undefined, args); } return invokeWithArgs(acc, curr); }, undefined); }; } exports['default'] = (0, _emberHelper.helper)(queue); }); define('ember-composable-helpers/helpers/range', ['exports', 'ember-helper', 'ember-utils', 'ember-composable-helpers/utils/comparison'], function (exports, _emberHelper, _emberUtils, _emberComposableHelpersUtilsComparison) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports.range = range; function range(_ref) { var _ref2 = _slicedToArray(_ref, 3); var min = _ref2[0]; var max = _ref2[1]; var isInclusive = _ref2[2]; isInclusive = (0, _emberUtils.typeOf)(isInclusive) === 'boolean' ? isInclusive : false; var numbers = []; if (min < max) { var testFn = isInclusive ? _emberComposableHelpersUtilsComparison.lte : _emberComposableHelpersUtilsComparison.lt; for (var i = min; testFn(i, max); i++) { numbers.push(i); } } if (min > max) { var testFn = isInclusive ? _emberComposableHelpersUtilsComparison.gte : _emberComposableHelpersUtilsComparison.gt; for (var i = min; testFn(i, max); i--) { numbers.push(i); } } return numbers; } exports['default'] = (0, _emberHelper.helper)(range); }); define('ember-composable-helpers/helpers/reduce', ['exports', 'ember', 'ember-helper', 'ember-metal/get', 'ember-metal/observer', 'ember-metal/set', 'ember-utils', 'ember-computed'], function (exports, _ember, _emberHelper, _emberMetalGet, _emberMetalObserver, _emberMetalSet, _emberUtils, _emberComputed) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var defineProperty = _ember['default'].defineProperty; exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 3); var callback = _ref2[0]; var initialValue = _ref2[1]; var array = _ref2[2]; (0, _emberMetalSet['default'])(this, 'callback', callback); (0, _emberMetalSet['default'])(this, 'array', array); (0, _emberMetalSet['default'])(this, 'initialValue', initialValue); return (0, _emberMetalGet['default'])(this, 'content'); }, callbackDidChange: (0, _emberMetalObserver['default'])('callback', 'initialValue', function () { var _this = this; var callback = (0, _emberMetalGet['default'])(this, 'callback'); var initialValue = (0, _emberMetalGet['default'])(this, 'initialValue'); if ((0, _emberUtils.isEmpty)(callback)) { defineProperty(this, 'content', []); return; } var cp = (0, _emberComputed['default'])('array.[]', function () { var array = (0, _emberMetalGet['default'])(_this, 'array'); return array.reduce(callback, initialValue); }); defineProperty(this, 'content', cp); }), contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/reject-by', ['exports', 'ember', 'ember-array/utils', 'ember-computed', 'ember-helper', 'ember-metal/get', 'ember-metal/observer', 'ember-metal/set', 'ember-utils'], function (exports, _ember, _emberArrayUtils, _emberComputed, _emberHelper, _emberMetalGet, _emberMetalObserver, _emberMetalSet, _emberUtils) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var defineProperty = _ember['default'].defineProperty; exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 3); var byPath = _ref2[0]; var value = _ref2[1]; var array = _ref2[2]; if (!(0, _emberArrayUtils.isEmberArray)(array) && (0, _emberArrayUtils.isEmberArray)(value)) { array = value; value = undefined; } (0, _emberMetalSet['default'])(this, 'array', array); (0, _emberMetalSet['default'])(this, 'byPath', byPath); (0, _emberMetalSet['default'])(this, 'value', value); return (0, _emberMetalGet['default'])(this, 'content'); }, byPathDidChange: (0, _emberMetalObserver['default'])('byPath', 'value', function () { var byPath = (0, _emberMetalGet['default'])(this, 'byPath'); var value = (0, _emberMetalGet['default'])(this, 'value'); if ((0, _emberUtils.isEmpty)(byPath)) { defineProperty(this, 'content', []); return; } var filterFn = undefined; if ((0, _emberUtils.isPresent)(value)) { if (typeof value === 'function') { filterFn = function (item) { return !value((0, _emberMetalGet['default'])(item, byPath)); }; } else { filterFn = function (item) { return (0, _emberMetalGet['default'])(item, byPath) !== value; }; } } else { filterFn = function (item) { return (0, _emberUtils.isEmpty)((0, _emberMetalGet['default'])(item, byPath)); }; } var cp = (0, _emberComputed.filter)('array.@each.' + byPath, filterFn); defineProperty(this, 'content', cp); }), contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/repeat', ['exports', 'ember-helper', 'ember-utils'], function (exports, _emberHelper, _emberUtils) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports.repeat = repeat; function repeat(_ref) { var _ref2 = _slicedToArray(_ref, 2); var length = _ref2[0]; var value = _ref2[1]; if ((0, _emberUtils.typeOf)(length) !== 'number') { return [value]; } return Array.apply(null, { length: length }).map(function () { return value; }); } exports['default'] = (0, _emberHelper.helper)(repeat); }); define('ember-composable-helpers/helpers/reverse', ['exports', 'ember-array/utils', 'ember-helper', 'ember-metal/observer', 'ember-metal/set'], function (exports, _emberArrayUtils, _emberHelper, _emberMetalObserver, _emberMetalSet) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 1); var array = _ref2[0]; if (!(0, _emberArrayUtils.isEmberArray)(array)) { return [array]; } (0, _emberMetalSet['default'])(this, 'array', array); return (0, _emberArrayUtils.A)(array).slice(0).reverse(); }, arrayContentDidChange: (0, _emberMetalObserver['default'])('array.[]', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/shuffle', ['exports', 'ember-array/utils', 'ember-helper', 'ember-metal/observer', 'ember-metal/get', 'ember-metal/set', 'ember-utils'], function (exports, _emberArrayUtils, _emberHelper, _emberMetalObserver, _emberMetalGet, _emberMetalSet, _emberUtils) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports.shuffle = shuffle; function shuffle(array, randomizer) { array = array.slice(0); var count = (0, _emberMetalGet['default'])(array, 'length'); var rand = undefined, temp = undefined; randomizer = (0, _emberUtils.typeOf)(randomizer) === 'function' && randomizer || Math.random; while (count > 1) { rand = Math.floor(randomizer() * count--); temp = array[count]; array[count] = array[rand]; array[rand] = temp; } return array; } exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 2); var random = _ref2[0]; var array = _ref2[1]; if (array === undefined) { array = random; random = undefined; } if (!(0, _emberArrayUtils.isEmberArray)(array)) { return (0, _emberArrayUtils.A)([array]); } (0, _emberMetalSet['default'])(this, 'array', array); return shuffle(array, random); }, arrayContentDidChange: (0, _emberMetalObserver['default'])('array.[]', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/slice', ['exports', 'ember-helper', 'ember-metal/observer', 'ember-metal/set'], function (exports, _emberHelper, _emberMetalObserver, _emberMetalSet) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 3); var start = _ref2[0]; var end = _ref2[1]; var array = _ref2[2]; (0, _emberMetalSet['default'])(this, 'array', array); return array.slice(start, end); }, arrayContentDidChange: (0, _emberMetalObserver['default'])('array.[]', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/sort-by', ['exports', 'ember', 'ember-array/utils', 'ember-computed', 'ember-helper', 'ember-metal/get', 'ember-metal/observer', 'ember-metal/set', 'ember-utils'], function (exports, _ember, _emberArrayUtils, _emberComputed, _emberHelper, _emberMetalGet, _emberMetalObserver, _emberMetalSet, _emberUtils) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var defineProperty = _ember['default'].defineProperty; exports['default'] = _emberHelper['default'].extend({ compute: function compute(params) { // slice params to avoid mutating the provided params var sortProps = params.slice(); var array = sortProps.pop(); var _sortProps = sortProps; var _sortProps2 = _slicedToArray(_sortProps, 1); var firstSortProp = _sortProps2[0]; if ((0, _emberUtils.typeOf)(firstSortProp) === 'function' || (0, _emberArrayUtils.isEmberArray)(firstSortProp)) { sortProps = firstSortProp; } (0, _emberMetalSet['default'])(this, 'array', array); (0, _emberMetalSet['default'])(this, 'sortProps', sortProps); return (0, _emberMetalGet['default'])(this, 'content'); }, sortPropsDidChange: (0, _emberMetalObserver['default'])('sortProps', function () { var sortProps = (0, _emberMetalGet['default'])(this, 'sortProps'); if ((0, _emberUtils.isEmpty)(sortProps)) { defineProperty(this, 'content', []); } if (typeof sortProps === 'function') { defineProperty(this, 'content', (0, _emberComputed.sort)('array', sortProps)); } else { defineProperty(this, 'content', (0, _emberComputed.sort)('array', 'sortProps')); } }), contentDidChange: (0, _emberMetalObserver['default'])('content', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/take', ['exports', 'ember-helper', 'ember-metal/observer', 'ember-metal/set'], function (exports, _emberHelper, _emberMetalObserver, _emberMetalSet) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports['default'] = _emberHelper['default'].extend({ compute: function compute(_ref) { var _ref2 = _slicedToArray(_ref, 2); var takeAmount = _ref2[0]; var array = _ref2[1]; (0, _emberMetalSet['default'])(this, 'array', array); return array.slice(0, takeAmount); }, arrayContentDidChange: (0, _emberMetalObserver['default'])('array.[]', function () { this.recompute(); }) }); }); define('ember-composable-helpers/helpers/titleize', ['exports', 'ember-helper', 'ember-composable-helpers/utils/titleize', 'ember-composable-helpers/-private/create-string-helper'], function (exports, _emberHelper, _emberComposableHelpersUtilsTitleize, _emberComposableHelpersPrivateCreateStringHelper) { 'use strict'; var titleize = (0, _emberComposableHelpersPrivateCreateStringHelper['default'])(_emberComposableHelpersUtilsTitleize['default']); exports.titleize = titleize; exports['default'] = (0, _emberHelper.helper)(titleize); }); define('ember-composable-helpers/helpers/toggle-action', ['exports', 'ember-helper', 'ember-composable-helpers/helpers/toggle', 'ember-composable-helpers/-private/closure-action'], function (exports, _emberHelper, _emberComposableHelpersHelpersToggle, _emberComposableHelpersPrivateClosureAction) { 'use strict'; var closureToggle = _emberComposableHelpersHelpersToggle.toggle; if (_emberComposableHelpersPrivateClosureAction['default']) { closureToggle[_emberComposableHelpersPrivateClosureAction['default']] = true; } exports['default'] = (0, _emberHelper.helper)(closureToggle); }); define('ember-composable-helpers/helpers/toggle', ['exports', 'ember-helper', 'ember-metal/get', 'ember-metal/set', 'ember-utils'], function (exports, _emberHelper, _emberMetalGet, _emberMetalSet, _emberUtils) { 'use strict'; exports.toggle = toggle; function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } function nextIndex(length, currentIdx) { if (currentIdx === -1 || currentIdx + 1 === length) { return 0; } return currentIdx + 1; } function toggle(_ref) { var _ref2 = _toArray(_ref); var prop = _ref2[0]; var obj = _ref2[1]; var values = _ref2.slice(2); return function () { var currentValue = (0, _emberMetalGet['default'])(obj, prop); if ((0, _emberUtils.isPresent)(values)) { var currentIdx = values.indexOf(currentValue); var nextIdx = nextIndex((0, _emberMetalGet['default'])(values, 'length'), currentIdx); return (0, _emberMetalSet['default'])(obj, prop, values[nextIdx]); } return (0, _emberMetalSet['default'])(obj, prop, !currentValue); }; } exports['default'] = (0, _emberHelper.helper)(toggle); }); define('ember-composable-helpers/helpers/truncate', ['exports', 'ember-helper'], function (exports, _emberHelper) { 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports.truncate = truncate; function truncate(_ref) { var _ref2 = _slicedToArray(_ref, 2); var string = _ref2[0]; var _ref2$1 = _ref2[1]; var characterLimit = _ref2$1 === undefined ? 140 : _ref2$1; var limit = characterLimit - 3; if (string && string.length > limit) { return string.substring(0, limit) + '...'; } else { return string; } } exports['default'] = (0, _emberHelper.helper)(truncate); }); define('ember-composable-helpers/helpers/underscore', ['exports', 'ember-helper', 'ember-string', 'ember-composable-helpers/-private/create-string-helper'], function (exports, _emberHelper, _emberString, _emberComposableHelpersPrivateCreateStringHelper) { 'use strict'; var underscore = (0, _emberComposableHelpersPrivateCreateStringHelper['default'])(_emberString.underscore); exports.underscore = underscore; exports['default'] = (0, _emberHelper.helper)(underscore); }); define('ember-composable-helpers/helpers/union', ['exports', 'ember-computed', 'ember-composable-helpers/-private/create-multi-array-helper'], function (exports, _emberComputed, _emberComposableHelpersPrivateCreateMultiArrayHelper) { 'use strict'; exports['default'] = (0, _emberComposableHelpersPrivateCreateMultiArrayHelper['default'])(_emberComputed.union); }); define('ember-composable-helpers/helpers/w', ['exports', 'ember-helper', 'ember-string'], function (exports, _emberHelper, _emberString) { 'use strict'; exports.w = w; function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } function w(_ref) { var _ref2 = _toArray(_ref); var wordStrings = _ref2; return wordStrings.map(_emberString.w).reduce(function (words, moreWords) { return words.concat(moreWords); }); } exports['default'] = (0, _emberHelper.helper)(w); }); define('ember-composable-helpers/helpers/without', ['exports', 'ember-array/utils', 'ember-metal/get', 'ember-utils', 'ember-composable-helpers/-private/create-needle-haystack-helper', 'ember-composable-helpers/utils/includes'], function (exports, _emberArrayUtils, _emberMetalGet, _emberUtils, _emberComposableHelpersPrivateCreateNeedleHaystackHelper, _emberComposableHelpersUtilsIncludes) { 'use strict'; exports.without = without; function contains(needle, haystack) { return (0, _emberComposableHelpersUtilsIncludes['default'])((0, _emberArrayUtils.A)(haystack), needle); } function without(needle, haystack) { if (!(0, _emberArrayUtils.isEmberArray)(haystack)) { return false; } if ((0, _emberUtils.typeOf)(needle) === 'array' && (0, _emberMetalGet['default'])(needle, 'length')) { return haystack.reduce(function (acc, val) { return contains(val, needle) ? acc : acc.concat(val); }, []); } return (0, _emberArrayUtils.A)(haystack).without(needle); } exports['default'] = (0, _emberComposableHelpersPrivateCreateNeedleHaystackHelper['default'])(without); }); define('ember-composable-helpers/index', ['exports', 'ember-composable-helpers/helpers/append', 'ember-composable-helpers/helpers/array', 'ember-composable-helpers/helpers/camelize', 'ember-composable-helpers/helpers/capitalize', 'ember-composable-helpers/helpers/chunk', 'ember-composable-helpers/helpers/classify', 'ember-composable-helpers/helpers/compact', 'ember-composable-helpers/helpers/compute', 'ember-composable-helpers/helpers/contains', 'ember-composable-helpers/helpers/dasherize', 'ember-composable-helpers/helpers/dec', 'ember-composable-helpers/helpers/drop', 'ember-composable-helpers/helpers/filter-by', 'ember-composable-helpers/helpers/filter', 'ember-composable-helpers/helpers/find-by', 'ember-composable-helpers/helpers/group-by', 'ember-composable-helpers/helpers/inc', 'ember-composable-helpers/helpers/intersect', 'ember-composable-helpers/helpers/invoke', 'ember-composable-helpers/helpers/join', 'ember-composable-helpers/helpers/map-by', 'ember-composable-helpers/helpers/map', 'ember-composable-helpers/helpers/optional', 'ember-composable-helpers/helpers/pipe', 'ember-composable-helpers/helpers/pipe-action', 'ember-composable-helpers/helpers/range', 'ember-composable-helpers/helpers/reduce', 'ember-composable-helpers/helpers/reject-by', 'ember-composable-helpers/helpers/repeat', 'ember-composable-helpers/helpers/shuffle', 'ember-composable-helpers/helpers/sort-by', 'ember-composable-helpers/helpers/take', 'ember-composable-helpers/helpers/toggle', 'ember-composable-helpers/helpers/toggle-action', 'ember-composable-helpers/helpers/truncate', 'ember-composable-helpers/helpers/underscore', 'ember-composable-helpers/helpers/union', 'ember-composable-helpers/helpers/w', 'ember-composable-helpers/helpers/without', 'ember-composable-helpers/helpers/flatten', 'ember-composable-helpers/helpers/object-at', 'ember-composable-helpers/helpers/slice', 'ember-composable-helpers/helpers/titleize', 'ember-composable-helpers/helpers/next', 'ember-composable-helpers/helpers/previous', 'ember-composable-helpers/helpers/has-next', 'ember-composable-helpers/helpers/has-previous', 'ember-composable-helpers/helpers/queue'], function (exports, _emberComposableHelpersHelpersAppend, _emberComposableHelpersHelpersArray, _emberComposableHelpersHelpersCamelize, _emberComposableHelpersHelpersCapitalize, _emberComposableHelpersHelpersChunk, _emberComposableHelpersHelpersClassify, _emberComposableHelpersHelpersCompact, _emberComposableHelpersHelpersCompute, _emberComposableHelpersHelpersContains, _emberComposableHelpersHelpersDasherize, _emberComposableHelpersHelpersDec, _emberComposableHelpersHelpersDrop, _emberComposableHelpersHelpersFilterBy, _emberComposableHelpersHelpersFilter, _emberComposableHelpersHelpersFindBy, _emberComposableHelpersHelpersGroupBy, _emberComposableHelpersHelpersInc, _emberComposableHelpersHelpersIntersect, _emberComposableHelpersHelpersInvoke, _emberComposableHelpersHelpersJoin, _emberComposableHelpersHelpersMapBy, _emberComposableHelpersHelpersMap, _emberComposableHelpersHelpersOptional, _emberComposableHelpersHelpersPipe, _emberComposableHelpersHelpersPipeAction, _emberComposableHelpersHelpersRange, _emberComposableHelpersHelpersReduce, _emberComposableHelpersHelpersRejectBy, _emberComposableHelpersHelpersRepeat, _emberComposableHelpersHelpersShuffle, _emberComposableHelpersHelpersSortBy, _emberComposableHelpersHelpersTake, _emberComposableHelpersHelpersToggle, _emberComposableHelpersHelpersToggleAction, _emberComposableHelpersHelpersTruncate, _emberComposableHelpersHelpersUnderscore, _emberComposableHelpersHelpersUnion, _emberComposableHelpersHelpersW, _emberComposableHelpersHelpersWithout, _emberComposableHelpersHelpersFlatten, _emberComposableHelpersHelpersObjectAt, _emberComposableHelpersHelpersSlice, _emberComposableHelpersHelpersTitleize, _emberComposableHelpersHelpersNext, _emberComposableHelpersHelpersPrevious, _emberComposableHelpersHelpersHasNext, _emberComposableHelpersHelpersHasPrevious, _emberComposableHelpersHelpersQueue) { 'use strict'; Object.defineProperty(exports, 'AppendHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersAppend['default']; } }); Object.defineProperty(exports, 'ArrayHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersArray['default']; } }); Object.defineProperty(exports, 'CamelizeHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersCamelize['default']; } }); Object.defineProperty(exports, 'CapitalizeHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersCapitalize['default']; } }); Object.defineProperty(exports, 'ChunkHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersChunk['default']; } }); Object.defineProperty(exports, 'ClassifyHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersClassify['default']; } }); Object.defineProperty(exports, 'CompactHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersCompact['default']; } }); Object.defineProperty(exports, 'ComputeHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersCompute['default']; } }); Object.defineProperty(exports, 'ContainsHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersContains['default']; } }); Object.defineProperty(exports, 'DasherizeHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersDasherize['default']; } }); Object.defineProperty(exports, 'DecHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersDec['default']; } }); Object.defineProperty(exports, 'DropHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersDrop['default']; } }); Object.defineProperty(exports, 'FilterByHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersFilterBy['default']; } }); Object.defineProperty(exports, 'FilterHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersFilter['default']; } }); Object.defineProperty(exports, 'FindByHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersFindBy['default']; } }); Object.defineProperty(exports, 'GroupByHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersGroupBy['default']; } }); Object.defineProperty(exports, 'IncHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersInc['default']; } }); Object.defineProperty(exports, 'IntersectHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersIntersect['default']; } }); Object.defineProperty(exports, 'InvokeHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersInvoke['default']; } }); Object.defineProperty(exports, 'JoinHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersJoin['default']; } }); Object.defineProperty(exports, 'MapByHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersMapBy['default']; } }); Object.defineProperty(exports, 'MapHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersMap['default']; } }); Object.defineProperty(exports, 'OptionalHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersOptional['default']; } }); Object.defineProperty(exports, 'PipeHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersPipe['default']; } }); Object.defineProperty(exports, 'PipeActionHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersPipeAction['default']; } }); Object.defineProperty(exports, 'RangeHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersRange['default']; } }); Object.defineProperty(exports, 'ReduceHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersReduce['default']; } }); Object.defineProperty(exports, 'RejectByHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersRejectBy['default']; } }); Object.defineProperty(exports, 'RepeatHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersRepeat['default']; } }); Object.defineProperty(exports, 'ShuffleHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersShuffle['default']; } }); Object.defineProperty(exports, 'SortByHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersSortBy['default']; } }); Object.defineProperty(exports, 'TakeHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersTake['default']; } }); Object.defineProperty(exports, 'ToggleHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersToggle['default']; } }); Object.defineProperty(exports, 'ToggleActionHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersToggleAction['default']; } }); Object.defineProperty(exports, 'TruncateHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersTruncate['default']; } }); Object.defineProperty(exports, 'UnderscoreHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersUnderscore['default']; } }); Object.defineProperty(exports, 'UnionHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersUnion['default']; } }); Object.defineProperty(exports, 'WHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersW['default']; } }); Object.defineProperty(exports, 'WithoutHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersWithout['default']; } }); Object.defineProperty(exports, 'FlattenHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersFlatten['default']; } }); Object.defineProperty(exports, 'ObjectAtHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersObjectAt['default']; } }); Object.defineProperty(exports, 'SliceHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersSlice['default']; } }); Object.defineProperty(exports, 'TitleizeHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersTitleize['default']; } }); Object.defineProperty(exports, 'NextHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersNext['default']; } }); Object.defineProperty(exports, 'PreviousHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersPrevious['default']; } }); Object.defineProperty(exports, 'HasNextHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersHasNext['default']; } }); Object.defineProperty(exports, 'HasPreviousHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersHasPrevious['default']; } }); Object.defineProperty(exports, 'QueueHelper', { enumerable: true, get: function get() { return _emberComposableHelpersHelpersQueue['default']; } }); }); define("ember-composable-helpers/utils/comparison", ["exports"], function (exports) { "use strict"; exports.lte = lte; exports.lt = lt; exports.gte = gte; exports.gt = gt; function lte(a, b) { return a <= b; } function lt(a, b) { return a < b; } function gte(a, b) { return a >= b; } function gt(a, b) { return a > b; } }); define('ember-composable-helpers/utils/get-index', ['exports', 'ember-array/utils', 'ember-composable-helpers/utils/is-equal'], function (exports, _emberArrayUtils, _emberComposableHelpersUtilsIsEqual) { 'use strict'; exports['default'] = getIndex; function getIndex(array, currentValue, useDeepEqual) { var needle = currentValue; if (useDeepEqual) { needle = (0, _emberArrayUtils.A)(array).find(function (object) { return (0, _emberComposableHelpersUtilsIsEqual['default'])(object, currentValue, useDeepEqual); }); } var index = (0, _emberArrayUtils.A)(array).indexOf(needle); return index >= 0 ? index : null; } }); define("ember-composable-helpers/utils/includes", ["exports"], function (exports) { "use strict"; exports["default"] = includes; function includes(haystack) { var finder = haystack.includes || haystack.contains; for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return finder.apply(haystack, args); } }); define("ember-composable-helpers/utils/is-equal", ["exports"], function (exports) { "use strict"; exports["default"] = isEqual; function isEqual(firstValue, secondValue) { var useDeepEqual = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; if (useDeepEqual) { return JSON.stringify(firstValue) === JSON.stringify(secondValue); } else { return firstValue === secondValue; } } }); define('ember-composable-helpers/utils/is-object', ['exports', 'ember-utils'], function (exports, _emberUtils) { 'use strict'; exports['default'] = isObject; function isObject(val) { return (0, _emberUtils.typeOf)(val) === 'object' || (0, _emberUtils.typeOf)(val) === 'instance'; } }); define('ember-composable-helpers/utils/is-promise', ['exports', 'ember-utils', 'ember-composable-helpers/utils/is-object'], function (exports, _emberUtils, _emberComposableHelpersUtilsIsObject) { 'use strict'; exports['default'] = isPromise; function isPromiseLike() { var obj = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; return (0, _emberUtils.typeOf)(obj.then) === 'function' && (0, _emberUtils.typeOf)(obj['catch']) === 'function' && (0, _emberUtils.typeOf)(obj['finally']) === 'function'; } function isPromise(obj) { return (0, _emberComposableHelpersUtilsIsObject['default'])(obj) && isPromiseLike(obj); } }); define('ember-composable-helpers/utils/titleize', ['exports'], function (exports) { 'use strict'; exports['default'] = titleize; function titleize() { var string = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; if (typeof string !== 'string') { throw new TypeError('Expected a string, got a ' + typeof string); } return string.toLowerCase().replace(/(?:^|\s|-|\/)\S/g, function (m) { return m.toUpperCase(); }); } }); define("ember-data/-private/adapters", ["exports", "ember-data/adapters/json-api", "ember-data/adapters/rest"], function (exports, _emberDataAdaptersJsonApi, _emberDataAdaptersRest) { /** @module ember-data */ "use strict"; exports.JSONAPIAdapter = _emberDataAdaptersJsonApi["default"]; exports.RESTAdapter = _emberDataAdaptersRest["default"]; }); define('ember-data/-private/adapters/build-url-mixin', ['exports', 'ember'], function (exports, _ember) { 'use strict'; var get = _ember['default'].get; /** WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 ## Using BuildURLMixin To use url building, include the mixin when extending an adapter, and call `buildURL` where needed. The default behaviour is designed for RESTAdapter. ### Example ```javascript export default DS.Adapter.extend(BuildURLMixin, { findRecord: function(store, type, id, snapshot) { var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); return this.ajax(url, 'GET'); } }); ``` ### Attributes The `host` and `namespace` attributes will be used if defined, and are optional. @class BuildURLMixin @namespace DS */ exports['default'] = _ember['default'].Mixin.create({ /** Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). To override the pluralization see [pathForType](#method_pathForType). If an ID is specified, it adds the ID to the path generated for the type, separated by a `/`. When called by RESTAdapter.findMany() the `id` and `snapshot` parameters will be arrays of ids and snapshots. @method buildURL @param {String} modelName @param {(String|Array|Object)} id single id or array of ids or query @param {(DS.Snapshot|Array)} snapshot single snapshot or array of snapshots @param {String} requestType @param {Object} query object of query parameters to send for query requests. @return {String} url */ buildURL: function buildURL(modelName, id, snapshot, requestType, query) { switch (requestType) { case 'findRecord': return this.urlForFindRecord(id, modelName, snapshot); case 'findAll': return this.urlForFindAll(modelName, snapshot); case 'query': return this.urlForQuery(query, modelName); case 'queryRecord': return this.urlForQueryRecord(query, modelName); case 'findMany': return this.urlForFindMany(id, modelName, snapshot); case 'findHasMany': return this.urlForFindHasMany(id, modelName, snapshot); case 'findBelongsTo': return this.urlForFindBelongsTo(id, modelName, snapshot); case 'createRecord': return this.urlForCreateRecord(modelName, snapshot); case 'updateRecord': return this.urlForUpdateRecord(id, modelName, snapshot); case 'deleteRecord': return this.urlForDeleteRecord(id, modelName, snapshot); default: return this._buildURL(modelName, id); } }, /** @method _buildURL @private @param {String} modelName @param {String} id @return {String} url */ _buildURL: function _buildURL(modelName, id) { var url = []; var host = get(this, 'host'); var prefix = this.urlPrefix(); var path; if (modelName) { path = this.pathForType(modelName); if (path) { url.push(path); } } if (id) { url.push(encodeURIComponent(id)); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url && url.charAt(0) !== '/') { url = '/' + url; } return url; }, /** * @method urlForFindRecord * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForFindRecord: function urlForFindRecord(id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** * @method urlForFindAll * @param {String} modelName * @param {DS.SnapshotRecordArray} snapshot * @return {String} url */ urlForFindAll: function urlForFindAll(modelName, snapshot) { return this._buildURL(modelName); }, /** * @method urlForQuery * @param {Object} query * @param {String} modelName * @return {String} url */ urlForQuery: function urlForQuery(query, modelName) { return this._buildURL(modelName); }, /** * @method urlForQueryRecord * @param {Object} query * @param {String} modelName * @return {String} url */ urlForQueryRecord: function urlForQueryRecord(query, modelName) { return this._buildURL(modelName); }, /** * @method urlForFindMany * @param {Array} ids * @param {String} modelName * @param {Array} snapshots * @return {String} url */ urlForFindMany: function urlForFindMany(ids, modelName, snapshots) { return this._buildURL(modelName); }, /** * @method urlForFindHasMany * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForFindHasMany: function urlForFindHasMany(id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** * @method urlForFindBelongsTo * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForFindBelongsTo: function urlForFindBelongsTo(id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** * @method urlForCreateRecord * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForCreateRecord: function urlForCreateRecord(modelName, snapshot) { return this._buildURL(modelName); }, /** * @method urlForUpdateRecord * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForUpdateRecord: function urlForUpdateRecord(id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** * @method urlForDeleteRecord * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForDeleteRecord: function urlForDeleteRecord(id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** @method urlPrefix @private @param {String} path @param {String} parentURL @return {String} urlPrefix */ urlPrefix: function urlPrefix(path, parentURL) { var host = get(this, 'host'); var namespace = get(this, 'namespace'); if (!host || host === '/') { host = ''; } if (path) { // Protocol relative url if (/^\/\//.test(path) || /http(s)?:\/\//.test(path)) { // Do nothing, the full host is already included. return path; // Absolute path } else if (path.charAt(0) === '/') { return '' + host + path; // Relative path } else { return parentURL + '/' + path; } } // No path provided var url = []; if (host) { url.push(host); } if (namespace) { url.push(namespace); } return url.join('/'); }, /** Determines the pathname for a given type. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). ### Pathname customization For example if you have an object LineItem with an endpoint of "/line_items/". ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ pathForType: function(modelName) { var decamelized = Ember.String.decamelize(modelName); return Ember.String.pluralize(decamelized); } }); ``` @method pathForType @param {String} modelName @return {String} path **/ pathForType: function pathForType(modelName) { var camelized = _ember['default'].String.camelize(modelName); return _ember['default'].String.pluralize(camelized); } }); }); define('ember-data/-private/core', ['exports', 'ember', 'ember-data/version'], function (exports, _ember, _emberDataVersion) { 'use strict'; /** @module ember-data */ /** All Ember Data classes, methods and functions are defined inside of this namespace. @class DS @static */ /** @property VERSION @type String @static */ var DS = _ember['default'].Namespace.create({ VERSION: _emberDataVersion['default'], name: "DS" }); if (_ember['default'].libraries) { _ember['default'].libraries.registerCoreLibrary('Ember Data', DS.VERSION); } exports['default'] = DS; }); define('ember-data/-private/debug', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.assert = assert; exports.debug = debug; exports.deprecate = deprecate; exports.info = info; exports.runInDebug = runInDebug; exports.warn = warn; exports.debugSeal = debugSeal; exports.assertPolymorphicType = assertPolymorphicType; function assert() { return _ember['default'].assert.apply(_ember['default'], arguments); } function debug() { return _ember['default'].debug.apply(_ember['default'], arguments); } function deprecate() { return _ember['default'].deprecate.apply(_ember['default'], arguments); } function info() { return _ember['default'].info.apply(_ember['default'], arguments); } function runInDebug() { return _ember['default'].runInDebug.apply(_ember['default'], arguments); } function warn() { return _ember['default'].warn.apply(_ember['default'], arguments); } function debugSeal() { return _ember['default'].debugSeal.apply(_ember['default'], arguments); } function checkPolymorphic(typeClass, addedRecord) { if (typeClass.__isMixin) { //TODO Need to do this in order to support mixins, should convert to public api //once it exists in Ember return typeClass.__mixin.detect(addedRecord.type.PrototypeMixin); } if (_ember['default'].MODEL_FACTORY_INJECTIONS) { typeClass = typeClass.superclass; } return typeClass.detect(addedRecord.type); } /* Assert that `addedRecord` has a valid type so it can be added to the relationship of the `record`. The assert basically checks if the `addedRecord` can be added to the relationship (specified via `relationshipMeta`) of the `record`. This utility should only be used internally, as both record parameters must be an InternalModel and the `relationshipMeta` needs to be the meta information about the relationship, retrieved via `record.relationshipFor(key)`. @method assertPolymorphicType @param {InternalModel} record @param {RelationshipMeta} relationshipMeta retrieved via `record.relationshipFor(key)` @param {InternalModel} addedRecord record which should be added/set for the relationship */ function assertPolymorphicType(record, relationshipMeta, addedRecord) { var addedType = addedRecord.type.modelName; var recordType = record.type.modelName; var key = relationshipMeta.key; var typeClass = record.store.modelFor(relationshipMeta.type); var assertionMessage = 'You cannot add a record of type \'' + addedType + '\' to the \'' + recordType + '.' + key + '\' relationship (only \'' + typeClass.modelName + '\' allowed)'; assert(assertionMessage, checkPolymorphic(typeClass, addedRecord)); } }); define('ember-data/-private/ext/date', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { /** @module ember-data */ 'use strict'; /** Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601> © 2011 Colin Snover <http://zetafleet.com> Released under MIT license. @class Date @namespace Ember @static @deprecated */ _ember['default'].Date = _ember['default'].Date || {}; var origParse = Date.parse; var numericKeys = [1, 4, 5, 6, 7, 10, 11]; var parseDate = function parseDate(date) { var timestamp, struct; var minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if (struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?:(\d{2}))?)?)?$/.exec(date)) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; k = numericKeys[i]; ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; exports.parseDate = parseDate; _ember['default'].Date.parse = function (date) { // throw deprecation (0, _emberDataPrivateDebug.deprecate)('Ember.Date.parse is deprecated because Safari 5-, IE8-, and\n Firefox 3.6- are no longer supported (see\n https://github.com/csnover/js-iso8601 for the history of this issue).\n Please use Date.parse instead', false, { id: 'ds.ember.date.parse-deprecate', until: '3.0.0' }); return parseDate(date); }; if (_ember['default'].EXTEND_PROTOTYPES === true || _ember['default'].EXTEND_PROTOTYPES.Date) { (0, _emberDataPrivateDebug.deprecate)('Overriding Date.parse with Ember.Date.parse is deprecated. Please set ENV.EmberENV.EXTEND_PROTOTYPES.Date to false in config/environment.js\n\n\n// config/environment.js\nENV = {\n EmberENV: {\n EXTEND_PROTOTYPES: {\n Date: false,\n }\n }\n}\n', false, { id: 'ds.date.parse-deprecate', until: '3.0.0' }); Date.parse = parseDate; } }); define('ember-data/-private/features', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports['default'] = isEnabled; function isEnabled() { var _Ember$FEATURES; return (_Ember$FEATURES = _ember['default'].FEATURES).isEnabled.apply(_Ember$FEATURES, arguments); } }); define('ember-data/-private/global', ['exports'], function (exports) { /* globals global, window, self */ // originally from https://github.com/emberjs/ember.js/blob/c0bd26639f50efd6a03ee5b87035fd200e313b8e/packages/ember-environment/lib/global.js // from lodash to catch fake globals 'use strict'; function checkGlobal(value) { return value && value.Object === Object ? value : undefined; } // element ids can ruin global miss checks function checkElementIdShadowing(value) { return value && value.nodeType === undefined ? value : undefined; } // export real global exports['default'] = checkGlobal(checkElementIdShadowing(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || new Function('return this')(); // eval outside of strict mode }); define("ember-data/-private/initializers/data-adapter", ["exports", "ember-data/-private/system/debug/debug-adapter"], function (exports, _emberDataPrivateSystemDebugDebugAdapter) { "use strict"; exports["default"] = initializeDebugAdapter; /* Configures a registry with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeDebugAdapter @param {Ember.Registry} registry */ function initializeDebugAdapter(registry) { registry.register('data-adapter:main', _emberDataPrivateSystemDebugDebugAdapter["default"]); } }); define('ember-data/-private/initializers/store-injections', ['exports'], function (exports) { 'use strict'; exports['default'] = initializeStoreInjections; /* Configures a registry with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeStoreInjections @param {Ember.Registry} registry */ function initializeStoreInjections(registry) { // registry.injection for Ember < 2.1.0 // application.inject for Ember 2.1.0+ var inject = registry.inject || registry.injection; inject.call(registry, 'controller', 'store', 'service:store'); inject.call(registry, 'route', 'store', 'service:store'); inject.call(registry, 'data-adapter', 'store', 'service:store'); } }); define("ember-data/-private/initializers/store", ["exports", "ember-data/-private/system/store", "ember-data/-private/serializers", "ember-data/-private/adapters"], function (exports, _emberDataPrivateSystemStore, _emberDataPrivateSerializers, _emberDataPrivateAdapters) { "use strict"; exports["default"] = initializeStore; function has(applicationOrRegistry, fullName) { if (applicationOrRegistry.has) { // < 2.1.0 return applicationOrRegistry.has(fullName); } else { // 2.1.0+ return applicationOrRegistry.hasRegistration(fullName); } } /* Configures a registry for use with an Ember-Data store. Accepts an optional namespace argument. @method initializeStore @param {Ember.Registry} registry */ function initializeStore(registry) { // registry.optionsForType for Ember < 2.1.0 // application.registerOptionsForType for Ember 2.1.0+ var registerOptionsForType = registry.registerOptionsForType || registry.optionsForType; registerOptionsForType.call(registry, 'serializer', { singleton: false }); registerOptionsForType.call(registry, 'adapter', { singleton: false }); registry.register('serializer:-default', _emberDataPrivateSerializers.JSONSerializer); registry.register('serializer:-rest', _emberDataPrivateSerializers.RESTSerializer); registry.register('adapter:-rest', _emberDataPrivateAdapters.RESTAdapter); registry.register('adapter:-json-api', _emberDataPrivateAdapters.JSONAPIAdapter); registry.register('serializer:-json-api', _emberDataPrivateSerializers.JSONAPISerializer); if (!has(registry, 'service:store')) { registry.register('service:store', _emberDataPrivateSystemStore["default"]); } } }); define('ember-data/-private/initializers/transforms', ['exports', 'ember-data/-private/transforms'], function (exports, _emberDataPrivateTransforms) { 'use strict'; exports['default'] = initializeTransforms; /* Configures a registry for use with Ember-Data transforms. @method initializeTransforms @param {Ember.Registry} registry */ function initializeTransforms(registry) { registry.register('transform:boolean', _emberDataPrivateTransforms.BooleanTransform); registry.register('transform:date', _emberDataPrivateTransforms.DateTransform); registry.register('transform:number', _emberDataPrivateTransforms.NumberTransform); registry.register('transform:string', _emberDataPrivateTransforms.StringTransform); } }); define('ember-data/-private/instance-initializers/initialize-store-service', ['exports'], function (exports) { 'use strict'; exports['default'] = initializeStoreService; /* Configures a registry for use with an Ember-Data store. @method initializeStoreService @param {Ember.ApplicationInstance} applicationOrRegistry */ function initializeStoreService(application) { var container = application.lookup ? application : application.container; // Eagerly generate the store so defaultStore is populated. container.lookup('service:store'); } }); define("ember-data/-private/serializers", ["exports", "ember-data/serializers/json-api", "ember-data/serializers/json", "ember-data/serializers/rest"], function (exports, _emberDataSerializersJsonApi, _emberDataSerializersJson, _emberDataSerializersRest) { /** @module ember-data */ "use strict"; exports.JSONAPISerializer = _emberDataSerializersJsonApi["default"]; exports.JSONSerializer = _emberDataSerializersJson["default"]; exports.RESTSerializer = _emberDataSerializersRest["default"]; }); define("ember-data/-private/system/clone-null", ["exports", "ember-data/-private/system/empty-object"], function (exports, _emberDataPrivateSystemEmptyObject) { "use strict"; exports["default"] = cloneNull; function cloneNull(source) { var clone = new _emberDataPrivateSystemEmptyObject["default"](); for (var key in source) { clone[key] = source[key]; } return clone; } }); define('ember-data/-private/system/coerce-id', ['exports'], function (exports) { 'use strict'; exports['default'] = coerceId; // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.findRecord('person', 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. function coerceId(id) { return id === null || id === undefined || id === '' ? null : id + ''; } }); define('ember-data/-private/system/container-proxy', ['exports', 'ember-data/-private/debug'], function (exports, _emberDataPrivateDebug) { 'use strict'; exports['default'] = ContainerProxy; /* This is used internally to enable deprecation of container paths and provide a decent message to the user indicating how to fix the issue. @class ContainerProxy @namespace DS @private */ function ContainerProxy(container) { this.container = container; } ContainerProxy.prototype.aliasedFactory = function (path, preLookup) { var _this = this; return { create: function create() { if (preLookup) { preLookup(); } return _this.container.lookup(path); } }; }; ContainerProxy.prototype.registerAlias = function (source, dest, preLookup) { var factory = this.aliasedFactory(dest, preLookup); return this.container.register(source, factory); }; ContainerProxy.prototype.registerDeprecation = function (deprecated, valid) { var preLookupCallback = function preLookupCallback() { (0, _emberDataPrivateDebug.deprecate)('You tried to look up \'' + deprecated + '\', but this has been deprecated in favor of \'' + valid + '\'.', false, { id: 'ds.store.deprecated-lookup', until: '2.0.0' }); }; return this.registerAlias(deprecated, valid, preLookupCallback); }; ContainerProxy.prototype.registerDeprecations = function (proxyPairs) { var i, proxyPair, deprecated, valid; for (i = proxyPairs.length; i > 0; i--) { proxyPair = proxyPairs[i - 1]; deprecated = proxyPair['deprecated']; valid = proxyPair['valid']; this.registerDeprecation(deprecated, valid); } }; }); define("ember-data/-private/system/debug", ["exports", "ember-data/-private/system/debug/debug-adapter"], function (exports, _emberDataPrivateSystemDebugDebugAdapter) { /** @module ember-data */ "use strict"; exports["default"] = _emberDataPrivateSystemDebugDebugAdapter["default"]; }); define('ember-data/-private/system/debug/debug-adapter', ['exports', 'ember', 'ember-data/model'], function (exports, _ember, _emberDataModel) { /** @module ember-data */ 'use strict'; var get = _ember['default'].get; var capitalize = _ember['default'].String.capitalize; var underscore = _ember['default'].String.underscore; var assert = _ember['default'].assert; /* Extend `Ember.DataAdapter` with ED specific code. @class DebugAdapter @namespace DS @extends Ember.DataAdapter @private */ exports['default'] = _ember['default'].DataAdapter.extend({ getFilters: function getFilters() { return [{ name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' }]; }, detect: function detect(typeClass) { return typeClass !== _emberDataModel['default'] && _emberDataModel['default'].detect(typeClass); }, columnsForType: function columnsForType(typeClass) { var columns = [{ name: 'id', desc: 'Id' }]; var count = 0; var self = this; get(typeClass, 'attributes').forEach(function (meta, name) { if (count++ > self.attributeLimit) { return false; } var desc = capitalize(underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords: function getRecords(modelClass, modelName) { if (arguments.length < 2) { // Legacy Ember.js < 1.13 support var containerKey = modelClass._debugContainerKey; if (containerKey) { var match = containerKey.match(/model:(.*)/); if (match) { modelName = match[1]; } } } assert("Cannot find model name. Please upgrade to Ember.js >= 1.13 for Ember Inspector support", !!modelName); return this.get('store').peekAll(modelName); }, getRecordColumnValues: function getRecordColumnValues(record) { var _this = this; var count = 0; var columnValues = { id: get(record, 'id') }; record.eachAttribute(function (key) { if (count++ > _this.attributeLimit) { return false; } var value = get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords: function getRecordKeywords(record) { var keywords = []; var keys = _ember['default'].A(['id']); record.eachAttribute(function (key) { return keys.push(key); }); keys.forEach(function (key) { return keywords.push(get(record, key)); }); return keywords; }, getRecordFilterValues: function getRecordFilterValues(record) { return { isNew: record.get('isNew'), isModified: record.get('hasDirtyAttributes') && !record.get('isNew'), isClean: !record.get('hasDirtyAttributes') }; }, getRecordColor: function getRecordColor(record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('hasDirtyAttributes')) { color = 'blue'; } return color; }, observeRecord: function observeRecord(record, recordUpdated) { var releaseMethods = _ember['default'].A(); var keysToObserve = _ember['default'].A(['id', 'isNew', 'hasDirtyAttributes']); record.eachAttribute(function (key) { return keysToObserve.push(key); }); var adapter = this; keysToObserve.forEach(function (key) { var handler = function handler() { recordUpdated(adapter.wrapRecord(record)); }; _ember['default'].addObserver(record, key, handler); releaseMethods.push(function () { _ember['default'].removeObserver(record, key, handler); }); }); var release = function release() { releaseMethods.forEach(function (fn) { return fn(); }); }; return release; } }); }); define('ember-data/-private/system/debug/debug-info', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports['default'] = _ember['default'].Mixin.create({ /** Provides info about the model for debugging purposes by grouping the properties into more semantic groups. Meant to be used by debugging tools such as the Chrome Ember Extension. - Groups all attributes in "Attributes" group. - Groups all belongsTo relationships in "Belongs To" group. - Groups all hasMany relationships in "Has Many" group. - Groups all flags in "Flags" group. - Flags relationship CPs as expensive properties. @method _debugInfo @for DS.Model @private */ _debugInfo: function _debugInfo() { var attributes = ['id']; var relationships = { belongsTo: [], hasMany: [] }; var expensiveProperties = []; this.eachAttribute(function (name, meta) { return attributes.push(name); }); this.eachRelationship(function (name, relationship) { relationships[relationship.kind].push(name); expensiveProperties.push(name); }); var groups = [{ name: 'Attributes', properties: attributes, expand: true }, { name: 'Belongs To', properties: relationships.belongsTo, expand: true }, { name: 'Has Many', properties: relationships.hasMany, expand: true }, { name: 'Flags', properties: ['isLoaded', 'hasDirtyAttributes', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] }]; return { propertyInfo: { // include all other mixins / properties (not just the grouped ones) includeOtherProperties: true, groups: groups, // don't pre-calculate unless cached expensiveProperties: expensiveProperties } }; } }); }); define("ember-data/-private/system/empty-object", ["exports"], function (exports) { "use strict"; exports["default"] = EmptyObject; // This exists because `Object.create(null)` is absurdly slow compared // to `new EmptyObject()`. In either case, you want a null prototype // when you're treating the object instances as arbitrary dictionaries // and don't want your keys colliding with build-in methods on the // default object prototype. var proto = Object.create(null, { // without this, we will always still end up with (new // EmptyObject()).constructor === Object constructor: { value: undefined, enumerable: false, writable: true } }); function EmptyObject() {} EmptyObject.prototype = proto; }); define('ember-data/-private/system/is-array-like', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports['default'] = isArrayLike; /* We're using this to detect arrays and "array-like" objects. This is a copy of the `isArray` method found in `ember-runtime/utils` as we're currently unable to import non-exposed modules. This method was previously exposed as `Ember.isArray` but since https://github.com/emberjs/ember.js/pull/11463 `Ember.isArray` is an alias of `Array.isArray` hence removing the "array-like" part. */ function isArrayLike(obj) { if (!obj || obj.setInterval) { return false; } if (Array.isArray(obj)) { return true; } if (_ember['default'].Array.detect(obj)) { return true; } var type = _ember['default'].typeOf(obj); if ('array' === type) { return true; } if (obj.length !== undefined && 'object' === type) { return true; } return false; } }); define("ember-data/-private/system/many-array", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/store/common"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStoreCommon) { /** @module ember-data */ "use strict"; var get = _ember["default"].get; var set = _ember["default"].set; /** A `ManyArray` is a `MutableArray` that represents the contents of a has-many relationship. The `ManyArray` is instantiated lazily the first time the relationship is requested. ### Inverses Often, the relationships in Ember Data applications will have an inverse. For example, imagine the following models are defined: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo('post') }); ``` If you created a new instance of `App.Post` and added a `App.Comment` record to its `comments` has-many relationship, you would expect the comment's `post` property to be set to the post that contained the has-many. We call the record to which a relationship belongs the relationship's _owner_. @class ManyArray @namespace DS @extends Ember.Object @uses Ember.MutableArray, Ember.Evented */ exports["default"] = _ember["default"].Object.extend(_ember["default"].MutableArray, _ember["default"].Evented, { init: function init() { this._super.apply(this, arguments); this.currentState = _ember["default"].A([]); }, record: null, canonicalState: null, currentState: null, length: 0, objectAt: function objectAt(index) { //Ember observers such as 'firstObject', 'lastObject' might do out of bounds accesses if (!this.currentState[index]) { return undefined; } return this.currentState[index].getRecord(); }, flushCanonical: function flushCanonical() { //TODO make this smarter, currently its plenty stupid var toSet = this.canonicalState.filter(function (internalModel) { return !internalModel.isDeleted(); }); //a hack for not removing new records //TODO remove once we have proper diffing var newRecords = this.currentState.filter( // only add new records which are not yet in the canonical state of this // relationship (a new record can be in the canonical state if it has function (internalModel) { return internalModel.isNew() && toSet.indexOf(internalModel) === -1; }); toSet = toSet.concat(newRecords); var oldLength = this.length; this.arrayContentWillChange(0, this.length, toSet.length); // It’s possible the parent side of the relationship may have been unloaded by this point if ((0, _emberDataPrivateSystemStoreCommon._objectIsAlive)(this)) { this.set('length', toSet.length); } this.currentState = toSet; this.arrayContentDidChange(0, oldLength, this.length); //TODO Figure out to notify only on additions and maybe only if unloaded this.relationship.notifyHasManyChanged(); this.record.updateRecordArrays(); }, /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} isPolymorphic @private */ isPolymorphic: false, /** The loading state of this array @property {Boolean} isLoaded */ isLoaded: false, /** The relationship which manages this array. @property {ManyRelationship} relationship @private */ relationship: null, /** Metadata associated with the request for async hasMany relationships. Example Given that the server returns the following JSON payload when fetching a hasMany relationship: ```js { "comments": [{ "id": 1, "comment": "This is the first comment", }, { // ... }], "meta": { "page": 1, "total": 5 } } ``` You can then access the metadata via the `meta` property: ```js post.get('comments').then(function(comments) { var meta = comments.get('meta'); // meta.page => 1 // meta.total => 5 }); ``` @property {Object} meta @public */ meta: null, internalReplace: function internalReplace(idx, amt, objects) { if (!objects) { objects = []; } this.arrayContentWillChange(idx, amt, objects.length); this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects)); this.set('length', this.currentState.length); this.arrayContentDidChange(idx, amt, objects.length); if (objects) { //TODO(Igor) probably needed only for unloaded records this.relationship.notifyHasManyChanged(); } this.record.updateRecordArrays(); }, //TODO(Igor) optimize internalRemoveRecords: function internalRemoveRecords(records) { var index; for (var i = 0; i < records.length; i++) { index = this.currentState.indexOf(records[i]); this.internalReplace(index, 1); } }, //TODO(Igor) optimize internalAddRecords: function internalAddRecords(records, idx) { if (idx === undefined) { idx = this.currentState.length; } this.internalReplace(idx, 0, records); }, replace: function replace(idx, amt, objects) { var records; if (amt > 0) { records = this.currentState.slice(idx, idx + amt); this.get('relationship').removeRecords(records); } if (objects) { this.get('relationship').addRecords(objects.map(function (obj) { return obj._internalModel; }), idx); } }, /** Used for async `hasMany` arrays to keep track of when they will resolve. @property {Ember.RSVP.Promise} promise @private */ promise: null, /** @method loadingRecordsCount @param {Number} count @private */ loadingRecordsCount: function loadingRecordsCount(count) { this.loadingRecordsCount = count; }, /** @method loadedRecord @private */ loadedRecord: function loadedRecord() { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { set(this, 'isLoaded', true); this.trigger('didLoad'); } }, /** @method reload @public */ reload: function reload() { return this.relationship.reload(); }, /** Saves all of the records in the `ManyArray`. Example ```javascript store.findRecord('inbox', 1).then(function(inbox) { inbox.get('messages').then(function(messages) { messages.forEach(function(message) { message.set('isRead', true); }); messages.save() }); }); ``` @method save @return {DS.PromiseArray} promise */ save: function save() { var manyArray = this; var promiseLabel = "DS: ManyArray#save " + get(this, 'type'); var promise = _ember["default"].RSVP.all(this.invoke("save"), promiseLabel).then(function (array) { return manyArray; }, null, "DS: ManyArray#save return ManyArray"); return _emberDataPrivateSystemPromiseProxies.PromiseArray.create({ promise: promise }); }, /** Create a child record within the owner @method createRecord @private @param {Object} hash @return {DS.Model} record */ createRecord: function createRecord(hash) { var store = get(this, 'store'); var type = get(this, 'type'); var record; (0, _emberDataPrivateDebug.assert)("You cannot add '" + type.modelName + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic')); record = store.createRecord(type.modelName, hash); this.pushObject(record); return record; } }); }); // been 'acknowleged' to be in the relationship via a store.push) define("ember-data/-private/system/model", ["exports", "ember-data/-private/system/model/model", "ember-data/attr", "ember-data/-private/system/model/states", "ember-data/-private/system/model/errors"], function (exports, _emberDataPrivateSystemModelModel, _emberDataAttr, _emberDataPrivateSystemModelStates, _emberDataPrivateSystemModelErrors) { /** @module ember-data */ "use strict"; exports.RootState = _emberDataPrivateSystemModelStates["default"]; exports.attr = _emberDataAttr["default"]; exports.Errors = _emberDataPrivateSystemModelErrors["default"]; exports["default"] = _emberDataPrivateSystemModelModel["default"]; }); define("ember-data/-private/system/model/attr", ["exports", "ember", "ember-data/-private/debug"], function (exports, _ember, _emberDataPrivateDebug) { "use strict"; var get = _ember["default"].get; var Map = _ember["default"].Map; /** @module ember-data */ /** @class Model @namespace DS */ var AttrClassMethodsMixin = _ember["default"].Mixin.create({ /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property. Example ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); ``` ```javascript import Ember from 'ember'; import Person from 'app/models/person'; var attributes = Ember.get(Person, 'attributes') attributes.forEach(function(meta, name) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @property attributes @static @type {Ember.Map} @readOnly */ attributes: _ember["default"].computed(function () { var _this = this; var map = Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isAttribute) { (0, _emberDataPrivateDebug.assert)("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + _this.toString(), name !== 'id'); meta.name = name; map.set(name, meta); } }); return map; }).readOnly(), /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type. Example ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); ``` ```javascript import Ember from 'ember'; import Person from 'app/models/person'; var transformedAttributes = Ember.get(Person, 'transformedAttributes') transformedAttributes.forEach(function(field, type) { console.log(field, type); }); // prints: // lastName string // birthday date ``` @property transformedAttributes @static @type {Ember.Map} @readOnly */ transformedAttributes: _ember["default"].computed(function () { var map = Map.create(); this.eachAttribute(function (key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }).readOnly(), /** Iterates through the attributes of the model, calling the passed function on each attribute. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, meta); ``` - `name` the name of the current property in the iteration - `meta` the meta object for the attribute property in the iteration Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript import DS from 'ember-data'; var Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); Person.eachAttribute(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @method eachAttribute @param {Function} callback The callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound @static */ eachAttribute: function eachAttribute(callback, binding) { get(this, 'attributes').forEach(function (meta, name) { callback.call(binding, name, meta); }); }, /** Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, type); ``` - `name` the name of the current property in the iteration - `type` a string containing the name of the type of transformed applied to the attribute Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript import DS from 'ember-data'; var Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); Person.eachTransformedAttribute(function(name, type) { console.log(name, type); }); // prints: // lastName string // birthday date ``` @method eachTransformedAttribute @param {Function} callback The callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound @static */ eachTransformedAttribute: function eachTransformedAttribute(callback, binding) { get(this, 'transformedAttributes').forEach(function (type, name) { callback.call(binding, name, type); }); } }); exports.AttrClassMethodsMixin = AttrClassMethodsMixin; var AttrInstanceMethodsMixin = _ember["default"].Mixin.create({ eachAttribute: function eachAttribute(callback, binding) { this.constructor.eachAttribute(callback, binding); } }); exports.AttrInstanceMethodsMixin = AttrInstanceMethodsMixin; }); define('ember-data/-private/system/model/errors', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { 'use strict'; var get = _ember['default'].get; var set = _ember['default'].set; var isEmpty = _ember['default'].isEmpty; var makeArray = _ember['default'].makeArray; var MapWithDefault = _ember['default'].MapWithDefault; /** @module ember-data */ /** Holds validation errors for a given record, organized by attribute names. Every `DS.Model` has an `errors` property that is an instance of `DS.Errors`. This can be used to display validation error messages returned from the server when a `record.save()` rejects. For Example, if you had a `User` model that looked like this: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ username: attr('string'), email: attr('string') }); ``` And you attempted to save a record that did not validate on the backend: ```javascript var user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save(); ``` Your backend would be expected to return an error response that described the problem, so that error messages can be generated on the app. API responses will be translated into instances of `DS.Errors` differently, depending on the specific combination of adapter and serializer used. You may want to check the documentation or the source code of the libraries that you are using, to know how they expect errors to be communicated. Errors can be displayed to the user by accessing their property name to get an array of all the error objects for that property. Each error object is a JavaScript object with two keys: - `message` A string containing the error message from the backend - `attribute` The name of the property associated with this error message ```handlebars <label>Username: {{input value=username}} </label> {{#each model.errors.username as |error|}} <div class="error"> {{error.message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each model.errors.email as |error|}} <div class="error"> {{error.message}} </div> {{/each}} ``` You can also access the special `messages` property on the error object to get an array of all the error strings. ```handlebars {{#each model.errors.messages as |message|}} <div class="error"> {{message}} </div> {{/each}} ``` @class Errors @namespace DS @extends Ember.Object @uses Ember.Enumerable @uses Ember.Evented */ exports['default'] = _ember['default'].ArrayProxy.extend(_ember['default'].Evented, { /** Register with target handler @method registerHandlers @param {Object} target @param {Function} becameInvalid @param {Function} becameValid @deprecated */ registerHandlers: function registerHandlers(target, becameInvalid, becameValid) { (0, _emberDataPrivateDebug.deprecate)('Record errors will no longer be evented.', false, { id: 'ds.errors.registerHandlers', until: '3.0.0' }); this._registerHandlers(target, becameInvalid, becameValid); }, /** Register with target handler @method _registerHandlers @private */ _registerHandlers: function _registerHandlers(target, becameInvalid, becameValid) { this.on('becameInvalid', target, becameInvalid); this.on('becameValid', target, becameValid); }, /** @property errorsByAttributeName @type {Ember.MapWithDefault} @private */ errorsByAttributeName: _ember['default'].computed(function () { return MapWithDefault.create({ defaultValue: function defaultValue() { return _ember['default'].A(); } }); }), /** Returns errors for a given attribute ```javascript var user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save().catch(function(){ user.get('errors').errorsFor('email'); // returns: // [{attribute: "email", message: "Doesn't look like a valid email."}] }); ``` @method errorsFor @param {String} attribute @return {Array} */ errorsFor: function errorsFor(attribute) { return get(this, 'errorsByAttributeName').get(attribute); }, /** An array containing all of the error messages for this record. This is useful for displaying all errors to the user. ```handlebars {{#each model.errors.messages as |message|}} <div class="error"> {{message}} </div> {{/each}} ``` @property messages @type {Array} */ messages: _ember['default'].computed.mapBy('content', 'message'), /** @property content @type {Array} @private */ content: _ember['default'].computed(function () { return _ember['default'].A(); }), /** @method unknownProperty @private */ unknownProperty: function unknownProperty(attribute) { var errors = this.errorsFor(attribute); if (isEmpty(errors)) { return null; } return errors; }, /** Total number of errors. @property length @type {Number} @readOnly */ /** @property isEmpty @type {Boolean} @readOnly */ isEmpty: _ember['default'].computed.not('length').readOnly(), /** Adds error messages to a given attribute and sends `becameInvalid` event to the record. Example: ```javascript if (!user.get('username') { user.get('errors').add('username', 'This field is required'); } ``` @method add @param {String} attribute @param {(Array|String)} messages @deprecated */ add: function add(attribute, messages) { (0, _emberDataPrivateDebug.warn)('Interacting with a record errors object will no longer change the record state.', false, { id: 'ds.errors.add' }); var wasEmpty = get(this, 'isEmpty'); this._add(attribute, messages); if (wasEmpty && !get(this, 'isEmpty')) { this.trigger('becameInvalid'); } }, /** Adds error messages to a given attribute without sending event. @method _add @private */ _add: function _add(attribute, messages) { messages = this._findOrCreateMessages(attribute, messages); this.addObjects(messages); get(this, 'errorsByAttributeName').get(attribute).addObjects(messages); this.notifyPropertyChange(attribute); }, /** @method _findOrCreateMessages @private */ _findOrCreateMessages: function _findOrCreateMessages(attribute, messages) { var errors = this.errorsFor(attribute); var messagesArray = makeArray(messages); var _messages = new Array(messagesArray.length); for (var i = 0; i < messagesArray.length; i++) { var message = messagesArray[i]; var err = errors.findBy('message', message); if (err) { _messages[i] = err; } else { _messages[i] = { attribute: attribute, message: message }; } } return _messages; }, /** Removes all error messages from the given attribute and sends `becameValid` event to the record if there no more errors left. Example: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ email: DS.attr('string'), twoFactorAuth: DS.attr('boolean'), phone: DS.attr('string') }); ``` ```app/routes/user/edit.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { save: function(user) { if (!user.get('twoFactorAuth')) { user.get('errors').remove('phone'); } user.save(); } } }); ``` @method remove @param {String} attribute @deprecated */ remove: function remove(attribute) { (0, _emberDataPrivateDebug.warn)('Interacting with a record errors object will no longer change the record state.', false, { id: 'ds.errors.remove' }); if (get(this, 'isEmpty')) { return; } this._remove(attribute); if (get(this, 'isEmpty')) { this.trigger('becameValid'); } }, /** Removes all error messages from the given attribute without sending event. @method _remove @private */ _remove: function _remove(attribute) { if (get(this, 'isEmpty')) { return; } var content = this.rejectBy('attribute', attribute); set(this, 'content', content); get(this, 'errorsByAttributeName')['delete'](attribute); this.notifyPropertyChange(attribute); }, /** Removes all error messages and sends `becameValid` event to the record. Example: ```app/routes/user/edit.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { retrySave: function(user) { user.get('errors').clear(); user.save(); } } }); ``` @method clear @deprecated */ clear: function clear() { (0, _emberDataPrivateDebug.warn)('Interacting with a record errors object will no longer change the record state.', false, { id: 'ds.errors.clear' }); if (get(this, 'isEmpty')) { return; } this._clear(); this.trigger('becameValid'); }, /** Removes all error messages. to the record. @method _clear @private */ _clear: function _clear() { if (get(this, 'isEmpty')) { return; } var errorsByAttributeName = get(this, 'errorsByAttributeName'); var attributes = _ember['default'].A(); errorsByAttributeName.forEach(function (_, attribute) { attributes.push(attribute); }); errorsByAttributeName.clear(); attributes.forEach(function (attribute) { this.notifyPropertyChange(attribute); }, this); _ember['default'].ArrayProxy.prototype.clear.call(this); }, /** Checks if there is error messages for the given attribute. ```app/routes/user/edit.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { save: function(user) { if (user.get('errors').has('email')) { return alert('Please update your email before attempting to save.'); } user.save(); } } }); ``` @method has @param {String} attribute @return {Boolean} true if there some errors on given attribute */ has: function has(attribute) { return !isEmpty(this.errorsFor(attribute)); } }); }); define("ember-data/-private/system/model/internal-model", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/model/states", "ember-data/-private/system/relationships/state/create", "ember-data/-private/system/snapshot", "ember-data/-private/system/empty-object", "ember-data/-private/features", "ember-data/-private/utils", "ember-data/-private/system/references"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemModelStates, _emberDataPrivateSystemRelationshipsStateCreate, _emberDataPrivateSystemSnapshot, _emberDataPrivateSystemEmptyObject, _emberDataPrivateFeatures, _emberDataPrivateUtils, _emberDataPrivateSystemReferences) { "use strict"; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; })(); exports["default"] = InternalModel; var Promise = _ember["default"].RSVP.Promise; var get = _ember["default"].get; var set = _ember["default"].set; var copy = _ember["default"].copy; var assign = _ember["default"].assign || _ember["default"].merge; var _extractPivotNameCache = new _emberDataPrivateSystemEmptyObject["default"](); var _splitOnDotCache = new _emberDataPrivateSystemEmptyObject["default"](); function splitOnDot(name) { return _splitOnDotCache[name] || (_splitOnDotCache[name] = name.split('.')); } function extractPivotName(name) { return _extractPivotNameCache[name] || (_extractPivotNameCache[name] = splitOnDot(name)[0]); } function retrieveFromCurrentState(key) { return function () { return get(this.currentState, key); }; } var guid = 0; /* `InternalModel` is the Model class that we use internally inside Ember Data to represent models. Internal ED methods should only deal with `InternalModel` objects. It is a fast, plain Javascript class. We expose `DS.Model` to application code, by materializing a `DS.Model` from `InternalModel` lazily, as a performance optimization. `InternalModel` should never be exposed to application code. At the boundaries of the system, in places like `find`, `push`, etc. we convert between Models and InternalModels. We need to make sure that the properties from `InternalModel` are correctly exposed/proxied on `Model` if they are needed. @private @class InternalModel */ function InternalModel(type, id, store, _, data) { this.type = type; this.id = id; this.store = store; this._data = data || new _emberDataPrivateSystemEmptyObject["default"](); this.modelName = type.modelName; this.dataHasInitialized = false; //Look into making this lazy this._deferredTriggers = []; this._attributes = new _emberDataPrivateSystemEmptyObject["default"](); this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject["default"](); this._relationships = new _emberDataPrivateSystemRelationshipsStateCreate["default"](this); this._recordArrays = undefined; this.currentState = _emberDataPrivateSystemModelStates["default"].empty; this.recordReference = new _emberDataPrivateSystemReferences.RecordReference(store, this); this.references = {}; this.isReloading = false; this.isError = false; this.error = null; this.__ember_meta__ = null; this[_ember["default"].GUID_KEY] = guid++ + 'internal-model'; /* implicit relationships are relationship which have not been declared but the inverse side exists on another record somewhere For example if there was ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr() }) ``` but there is also ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr(), comments: DS.hasMany('comment') }) ``` would have a implicit post relationship in order to be do things like remove ourselves from the post when we are deleted */ this._implicitRelationships = new _emberDataPrivateSystemEmptyObject["default"](); } InternalModel.prototype = { isEmpty: retrieveFromCurrentState('isEmpty'), isLoading: retrieveFromCurrentState('isLoading'), isLoaded: retrieveFromCurrentState('isLoaded'), hasDirtyAttributes: retrieveFromCurrentState('hasDirtyAttributes'), isSaving: retrieveFromCurrentState('isSaving'), isDeleted: retrieveFromCurrentState('isDeleted'), isNew: retrieveFromCurrentState('isNew'), isValid: retrieveFromCurrentState('isValid'), dirtyType: retrieveFromCurrentState('dirtyType'), constructor: InternalModel, materializeRecord: function materializeRecord() { (0, _emberDataPrivateDebug.assert)("Materialized " + this.modelName + " record with id:" + this.id + "more than once", this.record === null || this.record === undefined); // lookupFactory should really return an object that creates // instances with the injections applied var createOptions = { store: this.store, _internalModel: this, id: this.id, currentState: get(this, 'currentState'), isError: this.isError, adapterError: this.error }; if (_ember["default"].setOwner) { // ensure that `Ember.getOwner(this)` works inside a model instance _ember["default"].setOwner(createOptions, (0, _emberDataPrivateUtils.getOwner)(this.store)); } else { createOptions.container = this.store.container; } this.record = this.type._create(createOptions); this._triggerDeferredTriggers(); }, recordObjectWillDestroy: function recordObjectWillDestroy() { this.record = null; }, deleteRecord: function deleteRecord() { this.send('deleteRecord'); }, save: function save(options) { var promiseLabel = "DS: Model#save " + this; var resolver = _ember["default"].RSVP.defer(promiseLabel); this.store.scheduleSave(this, resolver, options); return resolver.promise; }, startedReloading: function startedReloading() { this.isReloading = true; if (this.record) { set(this.record, 'isReloading', true); } }, finishedReloading: function finishedReloading() { this.isReloading = false; if (this.record) { set(this.record, 'isReloading', false); } }, reload: function reload() { this.startedReloading(); var record = this; var promiseLabel = "DS: Model#reload of " + this; return new Promise(function (resolve) { record.send('reloadRecord', resolve); }, promiseLabel).then(function () { record.didCleanError(); return record; }, function (error) { record.didError(error); throw error; }, "DS: Model#reload complete, update flags")["finally"](function () { record.finishedReloading(); record.updateRecordArrays(); }); }, getRecord: function getRecord() { if (!this.record) { this.materializeRecord(); } return this.record; }, unloadRecord: function unloadRecord() { this.send('unloadRecord'); }, eachRelationship: function eachRelationship(callback, binding) { return this.type.eachRelationship(callback, binding); }, eachAttribute: function eachAttribute(callback, binding) { return this.type.eachAttribute(callback, binding); }, inverseFor: function inverseFor(key) { return this.type.inverseFor(key); }, setupData: function setupData(data) { var changedKeys = this._changedKeys(data.attributes); assign(this._data, data.attributes); this.pushedData(); if (this.record) { this.record._notifyProperties(changedKeys); } this.didInitalizeData(); }, becameReady: function becameReady() { _ember["default"].run.schedule('actions', this.store.recordArrayManager, this.store.recordArrayManager.recordWasLoaded, this); }, didInitalizeData: function didInitalizeData() { if (!this.dataHasInitialized) { this.becameReady(); this.dataHasInitialized = true; } }, destroy: function destroy() { if (this.record) { return this.record.destroy(); } }, /* @method createSnapshot @private */ createSnapshot: function createSnapshot(options) { return new _emberDataPrivateSystemSnapshot["default"](this, options); }, /* @method loadingData @private @param {Promise} promise */ loadingData: function loadingData(promise) { this.send('loadingData', promise); }, /* @method loadedData @private */ loadedData: function loadedData() { this.send('loadedData'); this.didInitalizeData(); }, /* @method notFound @private */ notFound: function notFound() { this.send('notFound'); }, /* @method pushedData @private */ pushedData: function pushedData() { this.send('pushedData'); }, flushChangedAttributes: function flushChangedAttributes() { this._inFlightAttributes = this._attributes; this._attributes = new _emberDataPrivateSystemEmptyObject["default"](); }, hasChangedAttributes: function hasChangedAttributes() { return Object.keys(this._attributes).length > 0; }, /* Checks if the attributes which are considered as changed are still different to the state which is acknowledged by the server. This method is needed when data for the internal model is pushed and the pushed data might acknowledge dirty attributes as confirmed. @method updateChangedAttributes @private */ updateChangedAttributes: function updateChangedAttributes() { var changedAttributes = this.changedAttributes(); var changedAttributeNames = Object.keys(changedAttributes); for (var i = 0, _length = changedAttributeNames.length; i < _length; i++) { var attribute = changedAttributeNames[i]; var _changedAttributes$attribute = _slicedToArray(changedAttributes[attribute], 2); var oldData = _changedAttributes$attribute[0]; var newData = _changedAttributes$attribute[1]; if (oldData === newData) { delete this._attributes[attribute]; } } }, /* Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. @method changedAttributes @private */ changedAttributes: function changedAttributes() { var oldData = this._data; var currentData = this._attributes; var inFlightData = this._inFlightAttributes; var newData = assign(copy(inFlightData), currentData); var diffData = new _emberDataPrivateSystemEmptyObject["default"](); var newDataKeys = Object.keys(newData); for (var i = 0, _length2 = newDataKeys.length; i < _length2; i++) { var key = newDataKeys[i]; diffData[key] = [oldData[key], newData[key]]; } return diffData; }, /* @method adapterWillCommit @private */ adapterWillCommit: function adapterWillCommit() { this.send('willCommit'); }, /* @method adapterDidDirty @private */ adapterDidDirty: function adapterDidDirty() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, /* @method send @private @param {String} name @param {Object} context */ send: function send(name, context) { var currentState = get(this, 'currentState'); if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); }, notifyHasManyAdded: function notifyHasManyAdded(key, record, idx) { if (this.record) { this.record.notifyHasManyAdded(key, record, idx); } }, notifyHasManyRemoved: function notifyHasManyRemoved(key, record, idx) { if (this.record) { this.record.notifyHasManyRemoved(key, record, idx); } }, notifyBelongsToChanged: function notifyBelongsToChanged(key, record) { if (this.record) { this.record.notifyBelongsToChanged(key, record); } }, notifyPropertyChange: function notifyPropertyChange(key) { if (this.record) { this.record.notifyPropertyChange(key); } }, rollbackAttributes: function rollbackAttributes() { var dirtyKeys = Object.keys(this._attributes); this._attributes = new _emberDataPrivateSystemEmptyObject["default"](); if (get(this, 'isError')) { this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject["default"](); this.didCleanError(); } //Eventually rollback will always work for relationships //For now we support it only out of deleted state, because we //have an explicit way of knowing when the server acked the relationship change if (this.isDeleted()) { //TODO: Should probably move this to the state machine somehow this.becameReady(); } if (this.isNew()) { this.clearRelationships(); } if (this.isValid()) { this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject["default"](); } this.send('rolledBack'); this.record._notifyProperties(dirtyKeys); }, /* @method transitionTo @private @param {String} name */ transitionTo: function transitionTo(name) { // POSSIBLE TODO: Remove this code and replace with // always having direct reference to state objects var pivotName = extractPivotName(name); var currentState = get(this, 'currentState'); var state = currentState; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state.hasOwnProperty(pivotName)); var path = splitOnDot(name); var setups = []; var enters = []; var i, l; for (i = 0, l = path.length; i < l; i++) { state = state[path[i]]; if (state.enter) { enters.push(state); } if (state.setup) { setups.push(state); } } for (i = 0, l = enters.length; i < l; i++) { enters[i].enter(this); } set(this, 'currentState', state); //TODO Consider whether this is the best approach for keeping these two in sync if (this.record) { set(this.record, 'currentState', state); } for (i = 0, l = setups.length; i < l; i++) { setups[i].setup(this); } this.updateRecordArraysLater(); }, _unhandledEvent: function _unhandledEvent(state, name, context) { var errorMessage = "Attempted to handle event `" + name + "` "; errorMessage += "on " + String(this) + " while in state "; errorMessage += state.stateName + ". "; if (context !== undefined) { errorMessage += "Called with " + _ember["default"].inspect(context) + "."; } throw new _ember["default"].Error(errorMessage); }, triggerLater: function triggerLater() { var length = arguments.length; var args = new Array(length); for (var i = 0; i < length; i++) { args[i] = arguments[i]; } if (this._deferredTriggers.push(args) !== 1) { return; } _ember["default"].run.scheduleOnce('actions', this, '_triggerDeferredTriggers'); }, _triggerDeferredTriggers: function _triggerDeferredTriggers() { //TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record, //but for now, we queue up all the events triggered before the record was materialized, and flush //them once we have the record if (!this.record) { return; } for (var i = 0, l = this._deferredTriggers.length; i < l; i++) { this.record.trigger.apply(this.record, this._deferredTriggers[i]); } this._deferredTriggers.length = 0; }, /* @method clearRelationships @private */ clearRelationships: function clearRelationships() { var _this = this; this.eachRelationship(function (name, relationship) { if (_this._relationships.has(name)) { var rel = _this._relationships.get(name); rel.clear(); rel.destroy(); } }); Object.keys(this._implicitRelationships).forEach(function (key) { _this._implicitRelationships[key].clear(); _this._implicitRelationships[key].destroy(); }); }, /* When a find request is triggered on the store, the user can optionally pass in attributes and relationships to be preloaded. These are meant to behave as if they came back from the server, except the user obtained them out of band and is informing the store of their existence. The most common use case is for supporting client side nested URLs, such as `/posts/1/comments/2` so the user can do `store.findRecord('comment', 2, { preload: { post: 1 } })` without having to fetch the post. Preloaded data can be attributes and relationships passed in either as IDs or as actual models. @method _preloadData @private @param {Object} preload */ _preloadData: function _preloadData(preload) { var _this2 = this; //TODO(Igor) consider the polymorphic case Object.keys(preload).forEach(function (key) { var preloadValue = get(preload, key); var relationshipMeta = _this2.type.metaForProperty(key); if (relationshipMeta.isRelationship) { _this2._preloadRelationship(key, preloadValue); } else { _this2._data[key] = preloadValue; } }); }, _preloadRelationship: function _preloadRelationship(key, preloadValue) { var relationshipMeta = this.type.metaForProperty(key); var type = relationshipMeta.type; if (relationshipMeta.kind === 'hasMany') { this._preloadHasMany(key, preloadValue, type); } else { this._preloadBelongsTo(key, preloadValue, type); } }, _preloadHasMany: function _preloadHasMany(key, preloadValue, type) { (0, _emberDataPrivateDebug.assert)("You need to pass in an array to set a hasMany property on a record", Array.isArray(preloadValue)); var recordsToSet = new Array(preloadValue.length); for (var i = 0; i < preloadValue.length; i++) { var recordToPush = preloadValue[i]; recordsToSet[i] = this._convertStringOrNumberIntoInternalModel(recordToPush, type); } //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships.get(key).updateRecordsFromAdapter(recordsToSet); }, _preloadBelongsTo: function _preloadBelongsTo(key, preloadValue, type) { var recordToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, type); //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships.get(key).setRecord(recordToSet); }, _convertStringOrNumberIntoInternalModel: function _convertStringOrNumberIntoInternalModel(value, type) { if (typeof value === 'string' || typeof value === 'number') { return this.store._internalModelForId(type, value); } if (value._internalModel) { return value._internalModel; } return value; }, /* @method updateRecordArrays @private */ updateRecordArrays: function updateRecordArrays() { this._updatingRecordArraysLater = false; this.store.dataWasUpdated(this.type, this); }, setId: function setId(id) { (0, _emberDataPrivateDebug.assert)('A record\'s id cannot be changed once it is in the loaded state', this.id === null || this.id === id || this.isNew()); this.id = id; if (this.record.get('id') !== id) { this.record.set('id', id); } }, didError: function didError(error) { this.error = error; this.isError = true; if (this.record) { this.record.setProperties({ isError: true, adapterError: error }); } }, didCleanError: function didCleanError() { this.error = null; this.isError = false; if (this.record) { this.record.setProperties({ isError: false, adapterError: null }); } }, /* If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. @method adapterDidCommit */ adapterDidCommit: function adapterDidCommit(data) { if (data) { data = data.attributes; } this.didCleanError(); var changedKeys = this._changedKeys(data); assign(this._data, this._inFlightAttributes); if (data) { assign(this._data, data); } this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject["default"](); this.send('didCommit'); this.updateRecordArraysLater(); if (!data) { return; } this.record._notifyProperties(changedKeys); }, /* @method updateRecordArraysLater @private */ updateRecordArraysLater: function updateRecordArraysLater() { // quick hack (something like this could be pushed into run.once if (this._updatingRecordArraysLater) { return; } this._updatingRecordArraysLater = true; _ember["default"].run.schedule('actions', this, this.updateRecordArrays); }, addErrorMessageToAttribute: function addErrorMessageToAttribute(attribute, message) { var record = this.getRecord(); get(record, 'errors')._add(attribute, message); }, removeErrorMessageFromAttribute: function removeErrorMessageFromAttribute(attribute) { var record = this.getRecord(); get(record, 'errors')._remove(attribute); }, clearErrorMessages: function clearErrorMessages() { var record = this.getRecord(); get(record, 'errors')._clear(); }, hasErrors: function hasErrors() { var record = this.getRecord(); var errors = get(record, 'errors'); return !_ember["default"].isEmpty(errors); }, // FOR USE DURING COMMIT PROCESS /* @method adapterDidInvalidate @private */ adapterDidInvalidate: function adapterDidInvalidate(errors) { var attribute; for (attribute in errors) { if (errors.hasOwnProperty(attribute)) { this.addErrorMessageToAttribute(attribute, errors[attribute]); } } this.send('becameInvalid'); this._saveWasRejected(); }, /* @method adapterDidError @private */ adapterDidError: function adapterDidError(error) { this.send('becameError'); this.didError(error); this._saveWasRejected(); }, _saveWasRejected: function _saveWasRejected() { var keys = Object.keys(this._inFlightAttributes); for (var i = 0; i < keys.length; i++) { if (this._attributes[keys[i]] === undefined) { this._attributes[keys[i]] = this._inFlightAttributes[keys[i]]; } } this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject["default"](); }, /* Ember Data has 3 buckets for storing the value of an attribute on an internalModel. `_data` holds all of the attributes that have been acknowledged by a backend via the adapter. When rollbackAttributes is called on a model all attributes will revert to the record's state in `_data`. `_attributes` holds any change the user has made to an attribute that has not been acknowledged by the adapter. Any values in `_attributes` are have priority over values in `_data`. `_inFlightAttributes`. When a record is being synced with the backend the values in `_attributes` are copied to `_inFlightAttributes`. This way if the backend acknowledges the save but does not return the new state Ember Data can copy the values from `_inFlightAttributes` to `_data`. Without having to worry about changes made to `_attributes` while the save was happenign. Changed keys builds a list of all of the values that may have been changed by the backend after a successful save. It does this by iterating over each key, value pair in the payload returned from the server after a save. If the `key` is found in `_attributes` then the user has a local changed to the attribute that has not been synced with the server and the key is not included in the list of changed keys. If the value, for a key differs from the value in what Ember Data believes to be the truth about the backend state (A merger of the `_data` and `_inFlightAttributes` objects where `_inFlightAttributes` has priority) then that means the backend has updated the value and the key is added to the list of changed keys. @method _changedKeys @private */ _changedKeys: function _changedKeys(updates) { var changedKeys = []; if (updates) { var original, i, value, key; var keys = Object.keys(updates); var length = keys.length; original = assign(new _emberDataPrivateSystemEmptyObject["default"](), this._data); original = assign(original, this._inFlightAttributes); for (i = 0; i < length; i++) { key = keys[i]; value = updates[key]; // A value in _attributes means the user has a local change to // this attributes. We never override this value when merging // updates from the backend so we should not sent a change // notification if the server value differs from the original. if (this._attributes[key] !== undefined) { continue; } if (!_ember["default"].isEqual(original[key], value)) { changedKeys.push(key); } } } return changedKeys; }, toString: function toString() { if (this.record) { return this.record.toString(); } else { return "<" + this.modelName + ":" + this.id + ">"; } }, referenceFor: function referenceFor(type, name) { var reference = this.references[name]; if (!reference) { var relationship = this._relationships.get(name); if (type === "belongsTo") { reference = new _emberDataPrivateSystemReferences.BelongsToReference(this.store, this, relationship); } else if (type === "hasMany") { reference = new _emberDataPrivateSystemReferences.HasManyReference(this.store, this, relationship); } this.references[name] = reference; } return reference; } }; if (false) { /* Returns the latest truth for an attribute - the canonical value, or the in-flight value. @method lastAcknowledgedValue @private */ InternalModel.prototype.lastAcknowledgedValue = function lastAcknowledgedValue(key) { if (key in this._inFlightAttributes) { return this._inFlightAttributes[key]; } else { return this._data[key]; } }; } }); define("ember-data/-private/system/model/model", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/model/errors", "ember-data/-private/system/debug/debug-info", "ember-data/-private/system/relationships/belongs-to", "ember-data/-private/system/relationships/has-many", "ember-data/-private/system/relationships/ext", "ember-data/-private/system/model/attr", "ember-data/-private/features"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemModelErrors, _emberDataPrivateSystemDebugDebugInfo, _emberDataPrivateSystemRelationshipsBelongsTo, _emberDataPrivateSystemRelationshipsHasMany, _emberDataPrivateSystemRelationshipsExt, _emberDataPrivateSystemModelAttr, _emberDataPrivateFeatures) { "use strict"; /** @module ember-data */ var get = _ember["default"].get; function intersection(array1, array2) { var result = []; array1.forEach(function (element) { if (array2.indexOf(element) >= 0) { result.push(element); } }); return result; } var RESERVED_MODEL_PROPS = ['currentState', 'data', 'store']; var retrieveFromCurrentState = _ember["default"].computed('currentState', function (key) { return get(this._internalModel.currentState, key); }).readOnly(); /** The model class that all Ember Data records descend from. This is the public API of Ember Data models. If you are using Ember Data in your application, this is the class you should use. If you are working on Ember Data internals, you most likely want to be dealing with `InternalModel` @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ var Model = _ember["default"].Object.extend(_ember["default"].Evented, { _internalModel: null, store: null, /** If this property is `true` the record is in the `empty` state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the `loading` state if data needs to be fetched from the server or the `created` state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record. @property isEmpty @type {Boolean} @readOnly */ isEmpty: retrieveFromCurrentState, /** If this property is `true` the record is in the `loading` state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data. @property isLoading @type {Boolean} @readOnly */ isLoading: retrieveFromCurrentState, /** If this property is `true` the record is in the `loaded` state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the `loaded` state. Example ```javascript var record = store.createRecord('model'); record.get('isLoaded'); // true store.findRecord('model', 1).then(function(model) { model.get('isLoaded'); // true }); ``` @property isLoaded @type {Boolean} @readOnly */ isLoaded: retrieveFromCurrentState, /** If this property is `true` the record is in the `dirty` state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted. Example ```javascript var record = store.createRecord('model'); record.get('hasDirtyAttributes'); // true store.findRecord('model', 1).then(function(model) { model.get('hasDirtyAttributes'); // false model.set('foo', 'some value'); model.get('hasDirtyAttributes'); // true }); ``` @since 1.13.0 @property hasDirtyAttributes @type {Boolean} @readOnly */ hasDirtyAttributes: _ember["default"].computed('currentState.isDirty', function () { return this.get('currentState.isDirty'); }), /** If this property is `true` the record is in the `saving` state. A record enters the saving state when `save` is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend. Example ```javascript var record = store.createRecord('model'); record.get('isSaving'); // false var promise = record.save(); record.get('isSaving'); // true promise.then(function() { record.get('isSaving'); // false }); ``` @property isSaving @type {Boolean} @readOnly */ isSaving: retrieveFromCurrentState, /** If this property is `true` the record is in the `deleted` state and has been marked for deletion. When `isDeleted` is true and `hasDirtyAttributes` is true, the record is deleted locally but the deletion was not yet persisted. When `isSaving` is true, the change is in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the change has persisted. Example ```javascript var record = store.createRecord('model'); record.get('isDeleted'); // false record.deleteRecord(); // Locally deleted record.get('isDeleted'); // true record.get('hasDirtyAttributes'); // true record.get('isSaving'); // false // Persisting the deletion var promise = record.save(); record.get('isDeleted'); // true record.get('isSaving'); // true // Deletion Persisted promise.then(function() { record.get('isDeleted'); // true record.get('isSaving'); // false record.get('hasDirtyAttributes'); // false }); ``` @property isDeleted @type {Boolean} @readOnly */ isDeleted: retrieveFromCurrentState, /** If this property is `true` the record is in the `new` state. A record will be in the `new` state when it has been created on the client and the adapter has not yet report that it was successfully saved. Example ```javascript var record = store.createRecord('model'); record.get('isNew'); // true record.save().then(function(model) { model.get('isNew'); // false }); ``` @property isNew @type {Boolean} @readOnly */ isNew: retrieveFromCurrentState, /** If this property is `true` the record is in the `valid` state. A record will be in the `valid` state when the adapter did not report any server-side validation failures. @property isValid @type {Boolean} @readOnly */ isValid: retrieveFromCurrentState, /** If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are: - `created` The record has been created by the client and not yet saved to the adapter. - `updated` The record has been updated by the client and not yet saved to the adapter. - `deleted` The record has been deleted by the client and not yet saved to the adapter. Example ```javascript var record = store.createRecord('model'); record.get('dirtyType'); // 'created' ``` @property dirtyType @type {String} @readOnly */ dirtyType: retrieveFromCurrentState, /** If `true` the adapter reported that it was unable to save local changes to the backend for any reason other than a server-side validation error. Example ```javascript record.get('isError'); // false record.set('foo', 'valid value'); record.save().then(null, function() { record.get('isError'); // true }); ``` @property isError @type {Boolean} @readOnly */ isError: false, /** If `true` the store is attempting to reload the record form the adapter. Example ```javascript record.get('isReloading'); // false record.reload(); record.get('isReloading'); // true ``` @property isReloading @type {Boolean} @readOnly */ isReloading: false, /** All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute. ```javascript var record = store.createRecord('model'); record.get('id'); // null store.findRecord('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, /** @property currentState @private @type {Object} */ /** When the record is in the `invalid` state this object will contain any errors returned by the adapter. When present the errors hash contains keys corresponding to the invalid property names and values which are arrays of Javascript objects with two keys: - `message` A string containing the error message from the backend - `attribute` The name of the property associated with this error message ```javascript record.get('errors.length'); // 0 record.set('foo', 'invalid value'); record.save().catch(function() { record.get('errors').get('foo'); // [{message: 'foo should be a number.', attribute: 'foo'}] }); ``` The `errors` property us useful for displaying error messages to the user. ```handlebars <label>Username: {{input value=username}} </label> {{#each model.errors.username as |error|}} <div class="error"> {{error.message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each model.errors.email as |error|}} <div class="error"> {{error.message}} </div> {{/each}} ``` You can also access the special `messages` property on the error object to get an array of all the error strings. ```handlebars {{#each model.errors.messages as |message|}} <div class="error"> {{message}} </div> {{/each}} ``` @property errors @type {DS.Errors} */ errors: _ember["default"].computed(function () { var errors = _emberDataPrivateSystemModelErrors["default"].create(); errors._registerHandlers(this._internalModel, function () { this.send('becameInvalid'); }, function () { this.send('becameValid'); }); return errors; }).readOnly(), /** This property holds the `DS.AdapterError` object with which last adapter operation was rejected. @property adapterError @type {DS.AdapterError} */ adapterError: null, /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. `serialize` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function serialize(options) { return this.store.serialize(this, options); }, /** Use [DS.JSONSerializer](DS.JSONSerializer.html) to get the JSON representation of a record. `toJSON` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method toJSON @param {Object} options @return {Object} A JSON representation of the object. */ toJSON: function toJSON(options) { // container is for lazy transform lookups var serializer = this.store.serializerFor('-default'); var snapshot = this._internalModel.createSnapshot(); return serializer.serialize(snapshot, options); }, /** Fired when the record is ready to be interacted with, that is either loaded from the server or created locally. @event ready */ ready: _ember["default"].K, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: _ember["default"].K, /** Fired when the record is updated. @event didUpdate */ didUpdate: _ember["default"].K, /** Fired when a new record is commited to the server. @event didCreate */ didCreate: _ember["default"].K, /** Fired when the record is deleted. @event didDelete */ didDelete: _ember["default"].K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: _ember["default"].K, /** Fired when the record enters the error state. @event becameError */ becameError: _ember["default"].K, /** Fired when the record is rolled back. @event rolledBack */ rolledBack: _ember["default"].K, //TODO Do we want to deprecate these? /** @method send @private @param {String} name @param {Object} context */ send: function send(name, context) { return this._internalModel.send(name, context); }, /** @method transitionTo @private @param {String} name */ transitionTo: function transitionTo(name) { return this._internalModel.transitionTo(name); }, /** Marks the record as deleted but does not save it. You must call `save` afterwards if you want to persist it. You might use this method if you want to allow the user to still `rollbackAttributes()` after a delete it was made. Example ```app/routes/model/delete.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { softDelete: function() { this.controller.get('model').deleteRecord(); }, confirm: function() { this.controller.get('model').save(); }, undo: function() { this.controller.get('model').rollbackAttributes(); } } }); ``` @method deleteRecord */ deleteRecord: function deleteRecord() { this._internalModel.deleteRecord(); }, /** Same as `deleteRecord`, but saves the record immediately. Example ```app/routes/model/delete.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { delete: function() { var controller = this.controller; controller.get('model').destroyRecord().then(function() { controller.transitionToRoute('model.index'); }); } } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the snapshot ```js record.destroyRecord({ adapterOptions: { subscribe: false } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ deleteRecord: function(store, type, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); ``` @method destroyRecord @param {Object} options @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ destroyRecord: function destroyRecord(options) { this.deleteRecord(); return this.save(options); }, /** @method unloadRecord @private */ unloadRecord: function unloadRecord() { if (this.isDestroyed) { return; } this._internalModel.unloadRecord(); }, /** @method _notifyProperties @private */ _notifyProperties: function _notifyProperties(keys) { _ember["default"].beginPropertyChanges(); var key; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; this.notifyPropertyChange(key); } _ember["default"].endPropertyChanges(); }, /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. The array represents the diff of the canonical state with the local state of the model. Note: if the model is created locally, the canonical state is empty since the adapter hasn't acknowledged the attributes yet: Example ```app/models/mascot.js import DS from 'ember-data'; export default DS.Model.extend({ name: attr('string'), isAdmin: attr('boolean', { defaultValue: false }) }); ``` ```javascript var mascot = store.createRecord('mascot'); mascot.changedAttributes(); // {} mascot.set('name', 'Tomster'); mascot.changedAttributes(); // { name: [undefined, 'Tomster'] } mascot.set('isAdmin', true); mascot.changedAttributes(); // { isAdmin: [undefined, true], name: [undefined, 'Tomster'] } mascot.save().then(function() { mascot.changedAttributes(); // {} mascot.set('isAdmin', false); mascot.changedAttributes(); // { isAdmin: [true, false] } }); ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function changedAttributes() { return this._internalModel.changedAttributes(); }, //TODO discuss with tomhuda about events/hooks //Bring back as hooks? /** @method adapterWillCommit @private adapterWillCommit: function() { this.send('willCommit'); }, /** @method adapterDidDirty @private adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, */ /** If the model `hasDirtyAttributes` this function will discard any unsaved changes. If the model `isNew` it will be removed from the store. Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollbackAttributes(); record.get('name'); // 'Untitled Document' ``` @since 1.13.0 @method rollbackAttributes */ rollbackAttributes: function rollbackAttributes() { this._internalModel.rollbackAttributes(); }, /* @method _createSnapshot @private */ _createSnapshot: function _createSnapshot() { return this._internalModel.createSnapshot(); }, toStringExtension: function toStringExtension() { return get(this, 'id'); }, /** Save the record and persist any changes to the record to an external source via the adapter. Example ```javascript record.set('name', 'Tomster'); record.save().then(function() { // Success callback }, function() { // Error callback }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the snapshot ```js record.save({ adapterOptions: { subscribe: false } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ updateRecord: function(store, type, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); ``` @method save @param {Object} options @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ save: function save(options) { var _this = this; return _emberDataPrivateSystemPromiseProxies.PromiseObject.create({ promise: this._internalModel.save(options).then(function () { return _this; }) }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading. Example ```app/routes/model/view.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { reload: function() { this.controller.get('model').reload().then(function(model) { // do something with the reloaded model }); } } }); ``` @method reload @return {Promise} a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error. */ reload: function reload() { var _this2 = this; return _emberDataPrivateSystemPromiseProxies.PromiseObject.create({ promise: this._internalModel.reload().then(function () { return _this2; }) }); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param {String} name */ trigger: function trigger(name) { var length = arguments.length; var args = new Array(length - 1); for (var i = 1; i < length; i++) { args[i - 1] = arguments[i]; } _ember["default"].tryInvoke(this, name, args); this._super.apply(this, arguments); }, willDestroy: function willDestroy() { //TODO Move! this._super.apply(this, arguments); this._internalModel.clearRelationships(); this._internalModel.recordObjectWillDestroy(); //TODO should we set internalModel to null here? }, // This is a temporary solution until we refactor DS.Model to not // rely on the data property. willMergeMixin: function willMergeMixin(props) { var constructor = this.constructor; (0, _emberDataPrivateDebug.assert)('`' + intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0] + '` is a reserved property name on DS.Model objects. Please choose a different property name for ' + constructor.toString(), !intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0]); (0, _emberDataPrivateDebug.assert)("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + constructor.toString(), Object.keys(props).indexOf('id') === -1); }, attr: function attr() { (0, _emberDataPrivateDebug.assert)("The `attr` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false); }, /** Get the reference for the specified belongsTo relationship. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); var blog = store.push({ type: 'blog', id: 1, relationships: { user: { type: 'user', id: 1 } } }); var userRef = blog.belongsTo('user'); // check if the user relationship is loaded var isLoaded = userRef.value() !== null; // get the record of the reference (null if not yet available) var user = userRef.value(); // get the identifier of the reference if (userRef.remoteType() === "id") { var id = userRef.id(); } else if (userRef.remoteType() === "link") { var link = userRef.link(); } // load user (via store.findRecord or store.findBelongsTo) userRef.load().then(...) // or trigger a reload userRef.reload().then(...) // provide data for reference userRef.push({ type: 'user', id: 1, attributes: { username: "@user" } }).then(function(user) { userRef.value() === user; }); ``` @method belongsTo @param {String} name of the relationship @since 2.5.0 @return {BelongsToReference} reference for this relationship */ belongsTo: function belongsTo(name) { return this._internalModel.referenceFor('belongsTo', name); }, /** Get the reference for the specified hasMany relationship. Example ```javascript // models/blog.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); var blog = store.push({ type: 'blog', id: 1, relationships: { comments: { data: [ { type: 'comment', id: 1 }, { type: 'comment', id: 2 } ] } } }); var commentsRef = blog.hasMany('comments'); // check if the comments are loaded already var isLoaded = commentsRef.value() !== null; // get the records of the reference (null if not yet available) var comments = commentsRef.value(); // get the identifier of the reference if (commentsRef.remoteType() === "ids") { var ids = commentsRef.ids(); } else if (commentsRef.remoteType() === "link") { var link = commentsRef.link(); } // load comments (via store.findMany or store.findHasMany) commentsRef.load().then(...) // or trigger a reload commentsRef.reload().then(...) // provide data for reference commentsRef.push([{ type: 'comment', id: 1 }, { type: 'comment', id: 2 }]).then(function(comments) { commentsRef.value() === comments; }); ``` @method hasMany @param {String} name of the relationship @since 2.5.0 @return {HasManyReference} reference for this relationship */ hasMany: function hasMany(name) { return this._internalModel.referenceFor('hasMany', name); }, setId: _ember["default"].observer('id', function () { this._internalModel.setId(this.get('id')); }) }); /** @property data @private @type {Object} */ Object.defineProperty(Model.prototype, 'data', { get: function get() { return this._internalModel._data; } }); Model.reopenClass({ /** Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. @method _create @private @static */ _create: Model.create, /** Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. To create an instance of a `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). @method create @private @static */ create: function create() { throw new _ember["default"].Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); }, /** Represents the model's class name as a string. This can be used to look up the model through DS.Store's modelFor method. `modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string. For example: ```javascript store.modelFor('post').modelName; // 'post' store.modelFor('blog-post').modelName; // 'blog-post' ``` The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload keys to underscore (instead of dasherized), you might use the following code: ```javascript export default var PostSerializer = DS.RESTSerializer.extend({ payloadKeyFromModelName: function(modelName) { return Ember.String.underscore(modelName); } }); ``` @property modelName @type String @readonly */ modelName: null }); // if `Ember.setOwner` is defined, accessing `this.container` is // deprecated (but functional). In "standard" Ember usage, this // deprecation is actually created via an `.extend` of the factory // inside the container itself, but that only happens on models // with MODEL_FACTORY_INJECTIONS enabled :( if (_ember["default"].setOwner) { Object.defineProperty(Model.prototype, 'container', { configurable: true, enumerable: false, get: function get() { (0, _emberDataPrivateDebug.deprecate)('Using the injected `container` is deprecated. Please use the `getOwner` helper instead to access the owner of this object.', false, { id: 'ember-application.injected-container', until: '3.0.0' }); return this.store.container; } }); } if (false) { Model.reopen({ /** Discards any unsaved changes to the given attribute. Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.resetAttribute('name'); record.get('name'); // 'Untitled Document' ``` @method resetAttribute */ resetAttribute: function resetAttribute(attributeName) { if (attributeName in this._internalModel._attributes) { this.set(attributeName, this._internalModel.lastAcknowledgedValue(attributeName)); } } }); } Model.reopenClass(_emberDataPrivateSystemRelationshipsExt.RelationshipsClassMethodsMixin); Model.reopenClass(_emberDataPrivateSystemModelAttr.AttrClassMethodsMixin); exports["default"] = Model.extend(_emberDataPrivateSystemDebugDebugInfo["default"], _emberDataPrivateSystemRelationshipsBelongsTo.BelongsToMixin, _emberDataPrivateSystemRelationshipsExt.DidDefinePropertyMixin, _emberDataPrivateSystemRelationshipsExt.RelationshipsInstanceMethodsMixin, _emberDataPrivateSystemRelationshipsHasMany.HasManyMixin, _emberDataPrivateSystemModelAttr.AttrInstanceMethodsMixin); }); define('ember-data/-private/system/model/states', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { /** @module ember-data */ 'use strict'; var get = _ember['default'].get; /* This file encapsulates the various states that a record can transition through during its lifecycle. */ /** ### State Each record has a `currentState` property that explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `root.loaded.created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `root.loaded.updated.inFlight` state. (This state paths will be explained in more detail below.) Events are sent by the record or its store to the record's `currentState` property. How the state reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical and every state is a substate of the `RootState`. For example, a record can be in the `root.deleted.uncommitted` state, then transition into the `root.deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting the state's `stateName` property: ```javascript record.get('currentState.stateName'); //=> "root.created.uncommitted" ``` The hierarchy of valid states that ship with ember data looks like this: ```text * root * deleted * saved * uncommitted * inFlight * empty * loaded * created * uncommitted * inFlight * saved * updated * uncommitted * inFlight * loading ``` The `DS.Model` states are themselves stateless. What that means is that, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each record points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass the record instance into the state's event handlers as the first argument. The record passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. ### Events and Flags A state may implement zero or more events and flags. #### Events Events are named functions that are invoked when sent to a record. The record will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: ```javascript aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with", param); } }) ``` To trigger this event: ```javascript record.send('myEvent', 'foo'); //=> "Received myEvent with foo" ``` Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the record's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * uncommitted <-- currentState * inFlight * updated * inFlight If we are currently in the `uncommitted` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: ```javascript var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } ``` You can say: ```javascript if (record.get('isNew') && record.get('isSaving')) { doSomething(); } ``` If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. * [isEmpty](DS.Model.html#property_isEmpty) * [isLoading](DS.Model.html#property_isLoading) * [isLoaded](DS.Model.html#property_isLoaded) * [isDirty](DS.Model.html#property_isDirty) * [isSaving](DS.Model.html#property_isSaving) * [isDeleted](DS.Model.html#property_isDeleted) * [isNew](DS.Model.html#property_isNew) * [isValid](DS.Model.html#property_isValid) @namespace DS @class RootState */ function _didSetProperty(internalModel, context) { if (context.value === context.originalValue) { delete internalModel._attributes[context.name]; internalModel.send('propertyWasReset', context.name); } else if (context.value !== context.oldValue) { internalModel.send('becomeDirty'); } internalModel.updateRecordArraysLater(); } // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: The adapter did not report any server-side validation // failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // sent to the adapter yet. var DirtyState = { initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: { // EVENTS didSetProperty: _didSetProperty, //TODO(Igor) reloading now triggers a //loadingData event, though it seems fine? loadingData: _ember['default'].K, propertyWasReset: function propertyWasReset(internalModel, name) { if (!internalModel.hasChangedAttributes()) { internalModel.send('rolledBack'); } }, pushedData: function pushedData(internalModel) { internalModel.updateChangedAttributes(); if (!internalModel.hasChangedAttributes()) { internalModel.transitionTo('loaded.saved'); } }, becomeDirty: _ember['default'].K, willCommit: function willCommit(internalModel) { internalModel.transitionTo('inFlight'); }, reloadRecord: function reloadRecord(internalModel, resolve) { resolve(internalModel.store.reloadRecord(internalModel)); }, rolledBack: function rolledBack(internalModel) { internalModel.transitionTo('loaded.saved'); }, becameInvalid: function becameInvalid(internalModel) { internalModel.transitionTo('invalid'); }, rollback: function rollback(internalModel) { internalModel.rollbackAttributes(); internalModel.triggerLater('ready'); } }, // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: { // FLAGS isSaving: true, // EVENTS didSetProperty: _didSetProperty, becomeDirty: _ember['default'].K, pushedData: _ember['default'].K, unloadRecord: assertAgainstUnloadRecord, // TODO: More robust semantics around save-while-in-flight willCommit: _ember['default'].K, didCommit: function didCommit(internalModel) { var dirtyType = get(this, 'dirtyType'); internalModel.transitionTo('saved'); internalModel.send('invokeLifecycleCallbacks', dirtyType); }, becameInvalid: function becameInvalid(internalModel) { internalModel.transitionTo('invalid'); internalModel.send('invokeLifecycleCallbacks'); }, becameError: function becameError(internalModel) { internalModel.transitionTo('uncommitted'); internalModel.triggerLater('becameError', internalModel); } }, // A record is in the `invalid` if the adapter has indicated // the the record failed server-side invalidations. invalid: { // FLAGS isValid: false, // EVENTS deleteRecord: function deleteRecord(internalModel) { internalModel.transitionTo('deleted.uncommitted'); }, didSetProperty: function didSetProperty(internalModel, context) { internalModel.removeErrorMessageFromAttribute(context.name); _didSetProperty(internalModel, context); if (!internalModel.hasErrors()) { this.becameValid(internalModel); } }, becameInvalid: _ember['default'].K, becomeDirty: _ember['default'].K, pushedData: _ember['default'].K, willCommit: function willCommit(internalModel) { internalModel.clearErrorMessages(); internalModel.transitionTo('inFlight'); }, rolledBack: function rolledBack(internalModel) { internalModel.clearErrorMessages(); internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('ready'); }, becameValid: function becameValid(internalModel) { internalModel.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function invokeLifecycleCallbacks(internalModel) { internalModel.triggerLater('becameInvalid', internalModel); } } }; // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. function deepClone(object) { var clone = {}; var value; for (var prop in object) { value = object[prop]; if (value && typeof value === 'object') { clone[prop] = deepClone(value); } else { clone[prop] = value; } } return clone; } function mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } function dirtyState(options) { var newState = deepClone(DirtyState); return mixin(newState, options); } var createdState = dirtyState({ dirtyType: 'created', // FLAGS isNew: true }); createdState.invalid.rolledBack = function (internalModel) { internalModel.transitionTo('deleted.saved'); }; createdState.uncommitted.rolledBack = function (internalModel) { internalModel.transitionTo('deleted.saved'); }; var updatedState = dirtyState({ dirtyType: 'updated' }); function createdStateDeleteRecord(internalModel) { internalModel.transitionTo('deleted.saved'); internalModel.send('invokeLifecycleCallbacks'); } createdState.uncommitted.deleteRecord = createdStateDeleteRecord; createdState.invalid.deleteRecord = createdStateDeleteRecord; createdState.uncommitted.rollback = function (internalModel) { DirtyState.uncommitted.rollback.apply(this, arguments); internalModel.transitionTo('deleted.saved'); }; createdState.uncommitted.pushedData = function (internalModel) { internalModel.transitionTo('loaded.updated.uncommitted'); internalModel.triggerLater('didLoad'); }; createdState.uncommitted.propertyWasReset = _ember['default'].K; function assertAgainstUnloadRecord(internalModel) { (0, _emberDataPrivateDebug.assert)("You can only unload a record which is not inFlight. `" + internalModel + "`", false); } updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord; updatedState.uncommitted.deleteRecord = function (internalModel) { internalModel.transitionTo('deleted.uncommitted'); }; var RootState = { // FLAGS isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, // DEFAULT EVENTS // Trying to roll back if you're not in the dirty state // doesn't change your state. For example, if you're in the // in-flight state, rolling back the record doesn't move // you out of the in-flight state. rolledBack: _ember['default'].K, unloadRecord: function unloadRecord(internalModel) { // clear relationships before moving to deleted state // otherwise it fails internalModel.clearRelationships(); internalModel.transitionTo('deleted.saved'); }, propertyWasReset: _ember['default'].K, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: { isEmpty: true, // EVENTS loadingData: function loadingData(internalModel, promise) { internalModel._loadingPromise = promise; internalModel.transitionTo('loading'); }, loadedData: function loadedData(internalModel) { internalModel.transitionTo('loaded.created.uncommitted'); internalModel.triggerLater('ready'); }, pushedData: function pushedData(internalModel) { internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('didLoad'); internalModel.triggerLater('ready'); } }, // A record enters this state when the store asks // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: { // FLAGS isLoading: true, exit: function exit(internalModel) { internalModel._loadingPromise = null; }, // EVENTS pushedData: function pushedData(internalModel) { internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('didLoad'); internalModel.triggerLater('ready'); //TODO this seems out of place here internalModel.didCleanError(); }, becameError: function becameError(internalModel) { internalModel.triggerLater('becameError', internalModel); }, notFound: function notFound(internalModel) { internalModel.transitionTo('empty'); } }, // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: { initialState: 'saved', // FLAGS isLoaded: true, //TODO(Igor) Reloading now triggers a loadingData event, //but it should be ok? loadingData: _ember['default'].K, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function setup(internalModel) { if (internalModel.hasChangedAttributes()) { internalModel.adapterDidDirty(); } }, // EVENTS didSetProperty: _didSetProperty, pushedData: _ember['default'].K, becomeDirty: function becomeDirty(internalModel) { internalModel.transitionTo('updated.uncommitted'); }, willCommit: function willCommit(internalModel) { internalModel.transitionTo('updated.inFlight'); }, reloadRecord: function reloadRecord(internalModel, resolve) { resolve(internalModel.store.reloadRecord(internalModel)); }, deleteRecord: function deleteRecord(internalModel) { internalModel.transitionTo('deleted.uncommitted'); }, unloadRecord: function unloadRecord(internalModel) { // clear relationships before moving to deleted state // otherwise it fails internalModel.clearRelationships(); internalModel.transitionTo('deleted.saved'); }, didCommit: function didCommit(internalModel) { internalModel.send('invokeLifecycleCallbacks', get(internalModel, 'lastDirtyType')); }, // loaded.saved.notFound would be triggered by a failed // `reload()` on an unchanged record notFound: _ember['default'].K }, // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: updatedState }, // A record is in this state if it was deleted from the store. deleted: { initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, // TRANSITIONS setup: function setup(internalModel) { internalModel.updateRecordArrays(); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record // starts to commit. uncommitted: { // EVENTS willCommit: function willCommit(internalModel) { internalModel.transitionTo('inFlight'); }, rollback: function rollback(internalModel) { internalModel.rollbackAttributes(); internalModel.triggerLater('ready'); }, pushedData: _ember['default'].K, becomeDirty: _ember['default'].K, deleteRecord: _ember['default'].K, rolledBack: function rolledBack(internalModel) { internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('ready'); } }, // After a record starts committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: { // FLAGS isSaving: true, // EVENTS unloadRecord: assertAgainstUnloadRecord, // TODO: More robust semantics around save-while-in-flight willCommit: _ember['default'].K, didCommit: function didCommit(internalModel) { internalModel.transitionTo('saved'); internalModel.send('invokeLifecycleCallbacks'); }, becameError: function becameError(internalModel) { internalModel.transitionTo('uncommitted'); internalModel.triggerLater('becameError', internalModel); }, becameInvalid: function becameInvalid(internalModel) { internalModel.transitionTo('invalid'); internalModel.triggerLater('becameInvalid', internalModel); } }, // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: { // FLAGS isDirty: false, setup: function setup(internalModel) { internalModel.clearRelationships(); var store = internalModel.store; store._dematerializeRecord(internalModel); }, invokeLifecycleCallbacks: function invokeLifecycleCallbacks(internalModel) { internalModel.triggerLater('didDelete', internalModel); internalModel.triggerLater('didCommit', internalModel); }, willCommit: _ember['default'].K, didCommit: _ember['default'].K }, invalid: { isValid: false, didSetProperty: function didSetProperty(internalModel, context) { internalModel.removeErrorMessageFromAttribute(context.name); _didSetProperty(internalModel, context); if (!internalModel.hasErrors()) { this.becameValid(internalModel); } }, becameInvalid: _ember['default'].K, becomeDirty: _ember['default'].K, deleteRecord: _ember['default'].K, willCommit: _ember['default'].K, rolledBack: function rolledBack(internalModel) { internalModel.clearErrorMessages(); internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('ready'); }, becameValid: function becameValid(internalModel) { internalModel.transitionTo('uncommitted'); } } }, invokeLifecycleCallbacks: function invokeLifecycleCallbacks(internalModel, dirtyType) { if (dirtyType === 'created') { internalModel.triggerLater('didCreate', internalModel); } else { internalModel.triggerLater('didUpdate', internalModel); } internalModel.triggerLater('didCommit', internalModel); } }; function wireState(object, parent, name) { // TODO: Use Object.create and copy instead object = mixin(parent ? Object.create(parent) : {}, object); object.parentState = parent; object.stateName = name; for (var prop in object) { if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } if (typeof object[prop] === 'object') { object[prop] = wireState(object[prop], object, name + "." + prop); } } return object; } RootState = wireState(RootState, null, "root"); exports['default'] = RootState; }); define('ember-data/-private/system/normalize-link', ['exports'], function (exports) { 'use strict'; exports['default'] = _normalizeLink; /* This method normalizes a link to an "links object". If the passed link is already an object it's returned without any modifications. See http://jsonapi.org/format/#document-links for more information. @method _normalizeLink @private @param {String} link @return {Object|null} @for DS */ function _normalizeLink(link) { switch (typeof link) { case 'object': return link; case 'string': return { href: link }; } return null; } }); define('ember-data/-private/system/normalize-model-name', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports['default'] = normalizeModelName; /** All modelNames are dasherized internally. Changing this function may require changes to other normalization hooks (such as typeForRoot). @method normalizeModelName @public @param {String} modelName @return {String} if the adapter can generate one, an ID @for DS */ function normalizeModelName(modelName) { return _ember['default'].String.dasherize(modelName); } }); define('ember-data/-private/system/ordered-set', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports['default'] = OrderedSet; var EmberOrderedSet = _ember['default'].OrderedSet; var guidFor = _ember['default'].guidFor; function OrderedSet() { this._super$constructor(); } OrderedSet.create = function () { var Constructor = this; return new Constructor(); }; OrderedSet.prototype = Object.create(EmberOrderedSet.prototype); OrderedSet.prototype.constructor = OrderedSet; OrderedSet.prototype._super$constructor = EmberOrderedSet; OrderedSet.prototype.addWithIndex = function (obj, idx) { var guid = guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] === true) { return; } presenceSet[guid] = true; if (idx === undefined || idx === null) { list.push(obj); } else { list.splice(idx, 0, obj); } this.size += 1; return this; }; }); define('ember-data/-private/system/promise-proxies', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { 'use strict'; var Promise = _ember['default'].RSVP.Promise; var get = _ember['default'].get; /** A `PromiseArray` is an object that acts like both an `Ember.Array` and a promise. When the promise is resolved the resulting value will be set to the `PromiseArray`'s `content` property. This makes it easy to create data bindings with the `PromiseArray` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseArray = DS.PromiseArray.create({ promise: $.getJSON('/some/remote/data.json') }); promiseArray.get('length'); // 0 promiseArray.then(function() { promiseArray.get('length'); // 100 }); ``` @class PromiseArray @namespace DS @extends Ember.ArrayProxy @uses Ember.PromiseProxyMixin */ var PromiseArray = _ember['default'].ArrayProxy.extend(_ember['default'].PromiseProxyMixin); /** A `PromiseObject` is an object that acts like both an `Ember.Object` and a promise. When the promise is resolved, then the resulting value will be set to the `PromiseObject`'s `content` property. This makes it easy to create data bindings with the `PromiseObject` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseObject = DS.PromiseObject.create({ promise: $.getJSON('/some/remote/data.json') }); promiseObject.get('name'); // null promiseObject.then(function() { promiseObject.get('name'); // 'Tomster' }); ``` @class PromiseObject @namespace DS @extends Ember.ObjectProxy @uses Ember.PromiseProxyMixin */ var PromiseObject = _ember['default'].ObjectProxy.extend(_ember['default'].PromiseProxyMixin); var promiseObject = function promiseObject(promise, label) { return PromiseObject.create({ promise: Promise.resolve(promise, label) }); }; var promiseArray = function promiseArray(promise, label) { return PromiseArray.create({ promise: Promise.resolve(promise, label) }); }; /** A PromiseManyArray is a PromiseArray that also proxies certain method calls to the underlying manyArray. Right now we proxy: * `reload()` * `createRecord()` * `on()` * `one()` * `trigger()` * `off()` * `has()` @class PromiseManyArray @namespace DS @extends Ember.ArrayProxy */ function proxyToContent(method) { return function () { var content = get(this, 'content'); return content[method].apply(content, arguments); }; } var PromiseManyArray = PromiseArray.extend({ reload: function reload() { //I don't think this should ever happen right now, but worth guarding if we refactor the async relationships (0, _emberDataPrivateDebug.assert)('You are trying to reload an async manyArray before it has been created', get(this, 'content')); return PromiseManyArray.create({ promise: get(this, 'content').reload() }); }, createRecord: proxyToContent('createRecord'), on: proxyToContent('on'), one: proxyToContent('one'), trigger: proxyToContent('trigger'), off: proxyToContent('off'), has: proxyToContent('has') }); var promiseManyArray = function promiseManyArray(promise, label) { return PromiseManyArray.create({ promise: Promise.resolve(promise, label) }); }; exports.PromiseArray = PromiseArray; exports.PromiseObject = PromiseObject; exports.PromiseManyArray = PromiseManyArray; exports.promiseArray = promiseArray; exports.promiseObject = promiseObject; exports.promiseManyArray = promiseManyArray; }); define("ember-data/-private/system/record-array-manager", ["exports", "ember", "ember-data/-private/system/record-arrays", "ember-data/-private/system/ordered-set"], function (exports, _ember, _emberDataPrivateSystemRecordArrays, _emberDataPrivateSystemOrderedSet) { /** @module ember-data */ "use strict"; var MapWithDefault = _ember["default"].MapWithDefault;var get = _ember["default"].get; /** @class RecordArrayManager @namespace DS @private @extends Ember.Object */ exports["default"] = _ember["default"].Object.extend({ init: function init() { var _this = this; this.filteredRecordArrays = MapWithDefault.create({ defaultValue: function defaultValue() { return []; } }); this.liveRecordArrays = MapWithDefault.create({ defaultValue: function defaultValue(typeClass) { return _this.createRecordArray(typeClass); } }); this.changedRecords = []; this._adapterPopulatedRecordArrays = []; }, recordDidChange: function recordDidChange(record) { if (this.changedRecords.push(record) !== 1) { return; } _ember["default"].run.schedule('actions', this, this.updateRecordArrays); }, recordArraysForRecord: function recordArraysForRecord(record) { record._recordArrays = record._recordArrays || _emberDataPrivateSystemOrderedSet["default"].create(); return record._recordArrays; }, /** This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when a record has changed. It updates all record arrays that a record belongs to. To avoid thrashing, it only runs at most once per run loop. @method updateRecordArrays */ updateRecordArrays: function updateRecordArrays() { var _this2 = this; this.changedRecords.forEach(function (internalModel) { if (get(internalModel, 'record.isDestroyed') || get(internalModel, 'record.isDestroying') || get(internalModel, 'currentState.stateName') === 'root.deleted.saved') { _this2._recordWasDeleted(internalModel); } else { _this2._recordWasChanged(internalModel); } }); this.changedRecords.length = 0; }, _recordWasDeleted: function _recordWasDeleted(record) { var recordArrays = record._recordArrays; if (!recordArrays) { return; } recordArrays.forEach(function (array) { return array.removeInternalModel(record); }); record._recordArrays = null; }, _recordWasChanged: function _recordWasChanged(record) { var _this3 = this; var typeClass = record.type; var recordArrays = this.filteredRecordArrays.get(typeClass); var filter; recordArrays.forEach(function (array) { filter = get(array, 'filterFunction'); _this3.updateFilterRecordArray(array, filter, typeClass, record); }); }, //Need to update live arrays on loading recordWasLoaded: function recordWasLoaded(record) { var _this4 = this; var typeClass = record.type; var recordArrays = this.filteredRecordArrays.get(typeClass); var filter; recordArrays.forEach(function (array) { filter = get(array, 'filterFunction'); _this4.updateFilterRecordArray(array, filter, typeClass, record); }); if (this.liveRecordArrays.has(typeClass)) { var liveRecordArray = this.liveRecordArrays.get(typeClass); this._addRecordToRecordArray(liveRecordArray, record); } }, /** Update an individual filter. @method updateFilterRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {DS.Model} typeClass @param {InternalModel} record */ updateFilterRecordArray: function updateFilterRecordArray(array, filter, typeClass, record) { var shouldBeInArray = filter(record.getRecord()); var recordArrays = this.recordArraysForRecord(record); if (shouldBeInArray) { this._addRecordToRecordArray(array, record); } else { recordArrays["delete"](array); array.removeInternalModel(record); } }, _addRecordToRecordArray: function _addRecordToRecordArray(array, record) { var recordArrays = this.recordArraysForRecord(record); if (!recordArrays.has(array)) { array.addInternalModel(record); recordArrays.add(array); } }, populateLiveRecordArray: function populateLiveRecordArray(array, modelName) { var typeMap = this.store.typeMapFor(modelName); var records = typeMap.records; var record; for (var i = 0; i < records.length; i++) { record = records[i]; if (!record.isDeleted() && !record.isEmpty()) { this._addRecordToRecordArray(array, record); } } }, /** This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. @method updateFilter @param {Array} array @param {String} modelName @param {Function} filter */ updateFilter: function updateFilter(array, modelName, filter) { var typeMap = this.store.typeMapFor(modelName); var records = typeMap.records; var record; for (var i = 0; i < records.length; i++) { record = records[i]; if (!record.isDeleted() && !record.isEmpty()) { this.updateFilterRecordArray(array, filter, modelName, record); } } }, /** Get the `DS.RecordArray` for a type, which contains all loaded records of given type. @method liveRecordArrayFor @param {Class} typeClass @return {DS.RecordArray} */ liveRecordArrayFor: function liveRecordArrayFor(typeClass) { return this.liveRecordArrays.get(typeClass); }, /** Create a `DS.RecordArray` for a type. @method createRecordArray @param {Class} typeClass @return {DS.RecordArray} */ createRecordArray: function createRecordArray(typeClass) { var array = _emberDataPrivateSystemRecordArrays.RecordArray.create({ type: typeClass, content: _ember["default"].A(), store: this.store, isLoaded: true, manager: this }); return array; }, /** Create a `DS.FilteredRecordArray` for a type and register it for updates. @method createFilteredRecordArray @param {DS.Model} typeClass @param {Function} filter @param {Object} query (optional @return {DS.FilteredRecordArray} */ createFilteredRecordArray: function createFilteredRecordArray(typeClass, filter, query) { var array = _emberDataPrivateSystemRecordArrays.FilteredRecordArray.create({ query: query, type: typeClass, content: _ember["default"].A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, typeClass, filter); return array; }, /** Create a `DS.AdapterPopulatedRecordArray` for a type with given query. @method createAdapterPopulatedRecordArray @param {DS.Model} typeClass @param {Object} query @return {DS.AdapterPopulatedRecordArray} */ createAdapterPopulatedRecordArray: function createAdapterPopulatedRecordArray(typeClass, query) { var array = _emberDataPrivateSystemRecordArrays.AdapterPopulatedRecordArray.create({ type: typeClass, query: query, content: _ember["default"].A(), store: this.store, manager: this }); this._adapterPopulatedRecordArrays.push(array); return array; }, /** Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @method registerFilteredRecordArray @param {DS.RecordArray} array @param {DS.Model} typeClass @param {Function} filter */ registerFilteredRecordArray: function registerFilteredRecordArray(array, typeClass, filter) { var recordArrays = this.filteredRecordArrays.get(typeClass); recordArrays.push(array); this.updateFilter(array, typeClass, filter); }, /** Unregister a RecordArray. So manager will not update this array. @method unregisterRecordArray @param {DS.RecordArray} array */ unregisterRecordArray: function unregisterRecordArray(array) { var typeClass = array.type; // unregister filtered record array var recordArrays = this.filteredRecordArrays.get(typeClass); var removedFromFiltered = remove(recordArrays, array); // remove from adapter populated record array var removedFromAdapterPopulated = remove(this._adapterPopulatedRecordArrays, array); if (!removedFromFiltered && !removedFromAdapterPopulated) { // unregister live record array if (this.liveRecordArrays.has(typeClass)) { var liveRecordArrayForType = this.liveRecordArrayFor(typeClass); if (array === liveRecordArrayForType) { this.liveRecordArrays["delete"](typeClass); } } } }, willDestroy: function willDestroy() { this._super.apply(this, arguments); this.filteredRecordArrays.forEach(function (value) { return flatten(value).forEach(destroy); }); this.liveRecordArrays.forEach(destroy); this._adapterPopulatedRecordArrays.forEach(destroy); } }); function destroy(entry) { entry.destroy(); } function flatten(list) { var length = list.length; var result = _ember["default"].A(); for (var i = 0; i < length; i++) { result = result.concat(list[i]); } return result; } function remove(array, item) { var index = array.indexOf(item); if (index !== -1) { array.splice(index, 1); return true; } return false; } }); define("ember-data/-private/system/record-arrays", ["exports", "ember-data/-private/system/record-arrays/record-array", "ember-data/-private/system/record-arrays/filtered-record-array", "ember-data/-private/system/record-arrays/adapter-populated-record-array"], function (exports, _emberDataPrivateSystemRecordArraysRecordArray, _emberDataPrivateSystemRecordArraysFilteredRecordArray, _emberDataPrivateSystemRecordArraysAdapterPopulatedRecordArray) { /** @module ember-data */ "use strict"; exports.RecordArray = _emberDataPrivateSystemRecordArraysRecordArray["default"]; exports.FilteredRecordArray = _emberDataPrivateSystemRecordArraysFilteredRecordArray["default"]; exports.AdapterPopulatedRecordArray = _emberDataPrivateSystemRecordArraysAdapterPopulatedRecordArray["default"]; }); define("ember-data/-private/system/record-arrays/adapter-populated-record-array", ["exports", "ember", "ember-data/-private/system/record-arrays/record-array", "ember-data/-private/system/clone-null", "ember-data/-private/features"], function (exports, _ember, _emberDataPrivateSystemRecordArraysRecordArray, _emberDataPrivateSystemCloneNull, _emberDataPrivateFeatures) { "use strict"; /** @module ember-data */ var get = _ember["default"].get; /** Represents an ordered list of records whose order and membership is determined by the adapter. For example, a query sent to the adapter may trigger a search on the server, whose results would be loaded into an instance of the `AdapterPopulatedRecordArray`. @class AdapterPopulatedRecordArray @namespace DS @extends DS.RecordArray */ exports["default"] = _emberDataPrivateSystemRecordArraysRecordArray["default"].extend({ query: null, replace: function replace() { var type = get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, _update: function _update() { var store = get(this, 'store'); var modelName = get(this, 'type.modelName'); var query = get(this, 'query'); return store._query(modelName, query, this); }, /** @method loadRecords @param {Array} records @param {Object} payload normalized payload @private */ loadRecords: function loadRecords(records, payload) { var _this = this; //TODO Optimize var internalModels = _ember["default"].A(records).mapBy('_internalModel'); this.setProperties({ content: _ember["default"].A(internalModels), isLoaded: true, isUpdating: false, meta: (0, _emberDataPrivateSystemCloneNull["default"])(payload.meta) }); if (true) { this.set('links', (0, _emberDataPrivateSystemCloneNull["default"])(payload.links)); } internalModels.forEach(function (record) { _this.manager.recordArraysForRecord(record).add(_this); }); // TODO: should triggering didLoad event be the last action of the runLoop? _ember["default"].run.once(this, 'trigger', 'didLoad'); } }); }); define('ember-data/-private/system/record-arrays/filtered-record-array', ['exports', 'ember', 'ember-data/-private/system/record-arrays/record-array'], function (exports, _ember, _emberDataPrivateSystemRecordArraysRecordArray) { 'use strict'; /** @module ember-data */ var get = _ember['default'].get; /** Represents a list of records whose membership is determined by the store. As records are created, loaded, or modified, the store evaluates them to determine if they should be part of the record array. @class FilteredRecordArray @namespace DS @extends DS.RecordArray */ exports['default'] = _emberDataPrivateSystemRecordArraysRecordArray['default'].extend({ /** The filterFunction is a function used to test records from the store to determine if they should be part of the record array. Example ```javascript var allPeople = store.peekAll('person'); allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"] var people = store.filter('person', function(person) { if (person.get('name').match(/Katz$/)) { return true; } }); people.mapBy('name'); // ["Yehuda Katz"] var notKatzFilter = function(person) { return !person.get('name').match(/Katz$/); }; people.set('filterFunction', notKatzFilter); people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"] ``` @method filterFunction @param {DS.Model} record @return {Boolean} `true` if the record should be in the array */ filterFunction: null, isLoaded: true, replace: function replace() { var type = get(this, 'type').toString(); throw new Error("The result of a client-side filter (on " + type + ") is immutable."); }, /** @method updateFilter @private */ _updateFilter: function _updateFilter() { var manager = get(this, 'manager'); manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction')); }, updateFilter: _ember['default'].observer('filterFunction', function () { _ember['default'].run.once(this, this._updateFilter); }) }); }); define("ember-data/-private/system/record-arrays/record-array", ["exports", "ember", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/snapshot-record-array"], function (exports, _ember, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemSnapshotRecordArray) { /** @module ember-data */ "use strict"; var get = _ember["default"].get; var set = _ember["default"].set; /** A record array is an array that contains records of a certain type. The record array materializes records as needed when they are retrieved for the first time. You should not create record arrays yourself. Instead, an instance of `DS.RecordArray` or its subclasses will be returned by your application's store in response to queries. @class RecordArray @namespace DS @extends Ember.ArrayProxy @uses Ember.Evented */ exports["default"] = _ember["default"].ArrayProxy.extend(_ember["default"].Evented, { /** The model type contained by this record array. @property type @type DS.Model */ type: null, /** The array of client ids backing the record array. When a record is requested from the record array, the record for the client id at the same index is materialized, if necessary, by the store. @property content @private @type Ember.Array */ content: null, /** The flag to signal a `RecordArray` is finished loading data. Example ```javascript var people = store.peekAll('person'); people.get('isLoaded'); // true ``` @property isLoaded @type Boolean */ isLoaded: false, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.peekAll('person'); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @property isUpdating @type Boolean */ isUpdating: false, /** The store that created this record array. @property store @private @type DS.Store */ store: null, /** Retrieves an object from the content by index. @method objectAtContent @private @param {Number} index @return {DS.Model} record */ objectAtContent: function objectAtContent(index) { var content = get(this, 'content'); var internalModel = content.objectAt(index); return internalModel && internalModel.getRecord(); }, /** Used to get the latest version of all of the records in this array from the adapter. Example ```javascript var people = store.peekAll('person'); people.get('isUpdating'); // false people.update().then(function() { people.get('isUpdating'); // false }); people.get('isUpdating'); // true ``` @method update */ update: function update() { if (get(this, 'isUpdating')) { return; } this.set('isUpdating', true); return this._update(); }, /* Update this RecordArray and return a promise which resolves once the update is finished. */ _update: function _update() { var store = get(this, 'store'); var modelName = get(this, 'type.modelName'); return store.findAll(modelName, { reload: true }); }, /** Adds an internal model to the `RecordArray` without duplicates @method addInternalModel @private @param {InternalModel} internalModel @param {number} an optional index to insert at */ addInternalModel: function addInternalModel(internalModel, idx) { var content = get(this, 'content'); if (idx === undefined) { content.addObject(internalModel); } else if (!content.includes(internalModel)) { content.insertAt(idx, internalModel); } }, /** Removes an internalModel to the `RecordArray`. @method removeInternalModel @private @param {InternalModel} internalModel */ removeInternalModel: function removeInternalModel(internalModel) { get(this, 'content').removeObject(internalModel); }, /** Saves all of the records in the `RecordArray`. Example ```javascript var messages = store.peekAll('message'); messages.forEach(function(message) { message.set('hasBeenSeen', true); }); messages.save(); ``` @method save @return {DS.PromiseArray} promise */ save: function save() { var recordArray = this; var promiseLabel = "DS: RecordArray#save " + get(this, 'type'); var promise = _ember["default"].RSVP.all(this.invoke("save"), promiseLabel).then(function (array) { return recordArray; }, null, "DS: RecordArray#save return RecordArray"); return _emberDataPrivateSystemPromiseProxies.PromiseArray.create({ promise: promise }); }, _dissociateFromOwnRecords: function _dissociateFromOwnRecords() { var _this = this; this.get('content').forEach(function (record) { var recordArrays = record._recordArrays; if (recordArrays) { recordArrays["delete"](_this); } }); }, /** @method _unregisterFromManager @private */ _unregisterFromManager: function _unregisterFromManager() { var manager = get(this, 'manager'); manager.unregisterRecordArray(this); }, willDestroy: function willDestroy() { this._unregisterFromManager(); this._dissociateFromOwnRecords(); set(this, 'content', undefined); this._super.apply(this, arguments); }, createSnapshot: function createSnapshot(options) { var meta = this.get('meta'); return new _emberDataPrivateSystemSnapshotRecordArray["default"](this, meta, options); } }); }); define('ember-data/-private/system/references', ['exports', 'ember-data/-private/system/references/record', 'ember-data/-private/system/references/belongs-to', 'ember-data/-private/system/references/has-many'], function (exports, _emberDataPrivateSystemReferencesRecord, _emberDataPrivateSystemReferencesBelongsTo, _emberDataPrivateSystemReferencesHasMany) { 'use strict'; exports.RecordReference = _emberDataPrivateSystemReferencesRecord['default']; exports.BelongsToReference = _emberDataPrivateSystemReferencesBelongsTo['default']; exports.HasManyReference = _emberDataPrivateSystemReferencesHasMany['default']; }); define('ember-data/-private/system/references/belongs-to', ['exports', 'ember-data/model', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/features', 'ember-data/-private/debug'], function (exports, _emberDataModel, _ember, _emberDataPrivateSystemReferencesReference, _emberDataPrivateFeatures, _emberDataPrivateDebug) { 'use strict'; var BelongsToReference = function BelongsToReference(store, parentInternalModel, belongsToRelationship) { this._super$constructor(store, parentInternalModel); this.belongsToRelationship = belongsToRelationship; this.type = belongsToRelationship.relationshipMeta.type; this.parent = parentInternalModel.recordReference; // TODO inverse }; BelongsToReference.prototype = Object.create(_emberDataPrivateSystemReferencesReference['default'].prototype); BelongsToReference.prototype.constructor = BelongsToReference; BelongsToReference.prototype._super$constructor = _emberDataPrivateSystemReferencesReference['default']; BelongsToReference.prototype.remoteType = function () { if (this.belongsToRelationship.link) { return "link"; } return "id"; }; BelongsToReference.prototype.id = function () { var inverseRecord = this.belongsToRelationship.inverseRecord; return inverseRecord && inverseRecord.id; }; BelongsToReference.prototype.link = function () { return this.belongsToRelationship.link; }; BelongsToReference.prototype.meta = function () { return this.belongsToRelationship.meta; }; BelongsToReference.prototype.push = function (objectOrPromise) { var _this = this; return _ember['default'].RSVP.resolve(objectOrPromise).then(function (data) { var record; if (data instanceof _emberDataModel['default']) { if (false) { (0, _emberDataPrivateDebug.deprecate)("BelongsToReference#push(DS.Model) is deprecated. Update relationship via `model.set('relationshipName', value)` instead.", false, { id: 'ds.references.belongs-to.push-record', until: '3.0' }); } record = data; } else { record = _this.store.push(data); } (0, _emberDataPrivateDebug.assertPolymorphicType)(_this.internalModel, _this.belongsToRelationship.relationshipMeta, record._internalModel); _this.belongsToRelationship.setCanonicalRecord(record._internalModel); return record; }); }; BelongsToReference.prototype.value = function () { var inverseRecord = this.belongsToRelationship.inverseRecord; if (inverseRecord && inverseRecord.record) { return inverseRecord.record; } return null; }; BelongsToReference.prototype.load = function () { var _this2 = this; if (this.remoteType() === "id") { return this.belongsToRelationship.getRecord(); } if (this.remoteType() === "link") { return this.belongsToRelationship.findLink().then(function (internalModel) { return _this2.value(); }); } }; BelongsToReference.prototype.reload = function () { var _this3 = this; return this.belongsToRelationship.reload().then(function (internalModel) { return _this3.value(); }); }; exports['default'] = BelongsToReference; }); define('ember-data/-private/system/references/has-many', ['exports', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/debug', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateSystemReferencesReference, _emberDataPrivateDebug, _emberDataPrivateFeatures) { 'use strict'; var get = _ember['default'].get; var HasManyReference = function HasManyReference(store, parentInternalModel, hasManyRelationship) { this._super$constructor(store, parentInternalModel); this.hasManyRelationship = hasManyRelationship; this.type = hasManyRelationship.relationshipMeta.type; this.parent = parentInternalModel.recordReference; // TODO inverse }; HasManyReference.prototype = Object.create(_emberDataPrivateSystemReferencesReference['default'].prototype); HasManyReference.prototype.constructor = HasManyReference; HasManyReference.prototype._super$constructor = _emberDataPrivateSystemReferencesReference['default']; HasManyReference.prototype.remoteType = function () { if (this.hasManyRelationship.link) { return "link"; } return "ids"; }; HasManyReference.prototype.link = function () { return this.hasManyRelationship.link; }; HasManyReference.prototype.ids = function () { var members = this.hasManyRelationship.members; var ids = members.toArray().map(function (internalModel) { return internalModel.id; }); return ids; }; HasManyReference.prototype.meta = function () { return this.hasManyRelationship.manyArray.meta; }; HasManyReference.prototype.push = function (objectOrPromise) { var _this = this; return _ember['default'].RSVP.resolve(objectOrPromise).then(function (payload) { var array = payload; if (false) { (0, _emberDataPrivateDebug.deprecate)("HasManyReference#push(array) is deprecated. Push a JSON-API document instead.", !Array.isArray(payload), { id: 'ds.references.has-many.push-array', until: '3.0' }); } var useLegacyArrayPush = true; if (typeof payload === "object" && payload.data) { array = payload.data; useLegacyArrayPush = array.length && array[0].data; if (false) { (0, _emberDataPrivateDebug.deprecate)("HasManyReference#push() expects a valid JSON-API document.", !useLegacyArrayPush, { id: 'ds.references.has-many.push-invalid-json-api', until: '3.0' }); } } if (!false) { useLegacyArrayPush = true; } var internalModels = undefined; if (useLegacyArrayPush) { internalModels = array.map(function (obj) { var record = _this.store.push(obj); (0, _emberDataPrivateDebug.runInDebug)(function () { var relationshipMeta = _this.hasManyRelationship.relationshipMeta; (0, _emberDataPrivateDebug.assertPolymorphicType)(_this.internalModel, relationshipMeta, record._internalModel); }); return record._internalModel; }); } else { var records = _this.store.push(payload); internalModels = _ember['default'].A(records).mapBy('_internalModel'); (0, _emberDataPrivateDebug.runInDebug)(function () { internalModels.forEach(function (internalModel) { var relationshipMeta = _this.hasManyRelationship.relationshipMeta; (0, _emberDataPrivateDebug.assertPolymorphicType)(_this.internalModel, relationshipMeta, internalModel); }); }); } _this.hasManyRelationship.computeChanges(internalModels); return _this.hasManyRelationship.manyArray; }); }; HasManyReference.prototype._isLoaded = function () { var hasData = get(this.hasManyRelationship, 'hasData'); if (!hasData) { return false; } var members = this.hasManyRelationship.members.toArray(); var isEveryLoaded = members.every(function (internalModel) { return internalModel.isLoaded() === true; }); return isEveryLoaded; }; HasManyReference.prototype.value = function () { if (this._isLoaded()) { return this.hasManyRelationship.manyArray; } return null; }; HasManyReference.prototype.load = function () { if (!this._isLoaded()) { return this.hasManyRelationship.getRecords(); } var manyArray = this.hasManyRelationship.manyArray; return _ember['default'].RSVP.resolve(manyArray); }; HasManyReference.prototype.reload = function () { return this.hasManyRelationship.reload(); }; exports['default'] = HasManyReference; }); define('ember-data/-private/system/references/record', ['exports', 'ember', 'ember-data/-private/system/references/reference'], function (exports, _ember, _emberDataPrivateSystemReferencesReference) { 'use strict'; var RecordReference = function RecordReference(store, internalModel) { this._super$constructor(store, internalModel); this.type = internalModel.modelName; this._id = internalModel.id; }; RecordReference.prototype = Object.create(_emberDataPrivateSystemReferencesReference['default'].prototype); RecordReference.prototype.constructor = RecordReference; RecordReference.prototype._super$constructor = _emberDataPrivateSystemReferencesReference['default']; RecordReference.prototype.id = function () { return this._id; }; RecordReference.prototype.remoteType = function () { return 'identity'; }; RecordReference.prototype.push = function (objectOrPromise) { var _this = this; return _ember['default'].RSVP.resolve(objectOrPromise).then(function (data) { var record = _this.store.push(data); return record; }); }; RecordReference.prototype.value = function () { return this.internalModel.record; }; RecordReference.prototype.load = function () { return this.store.findRecord(this.type, this._id); }; RecordReference.prototype.reload = function () { var record = this.value(); if (record) { return record.reload(); } return this.load(); }; exports['default'] = RecordReference; }); define("ember-data/-private/system/references/reference", ["exports"], function (exports) { "use strict"; var Reference = function Reference(store, internalModel) { this.store = store; this.internalModel = internalModel; }; Reference.prototype = { constructor: Reference }; exports["default"] = Reference; }); define('ember-data/-private/system/relationship-meta', ['exports', 'ember-inflector', 'ember-data/-private/system/normalize-model-name'], function (exports, _emberInflector, _emberDataPrivateSystemNormalizeModelName) { 'use strict'; exports.typeForRelationshipMeta = typeForRelationshipMeta; exports.relationshipFromMeta = relationshipFromMeta; function typeForRelationshipMeta(meta) { var modelName; modelName = meta.type || meta.key; if (meta.kind === 'hasMany') { modelName = (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName['default'])(modelName)); } return modelName; } function relationshipFromMeta(meta) { return { key: meta.key, kind: meta.kind, type: typeForRelationshipMeta(meta), options: meta.options, parentType: meta.parentType, isRelationship: true }; } }); define("ember-data/-private/system/relationships/belongs-to", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/normalize-model-name"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeModelName) { "use strict"; exports["default"] = belongsTo; /** `DS.belongsTo` is used to define One-To-One and One-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.belongsTo` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) #### One-To-One To declare a one-to-one relationship between two models, use `DS.belongsTo`: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ profile: DS.belongsTo('profile') }); ``` ```app/models/profile.js import DS from 'ember-data'; export default DS.Model.extend({ user: DS.belongsTo('user') }); ``` #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo('post') }); ``` You can avoid passing a string as the first parameter. In that case Ember Data will infer the type from the key name. ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo() }); ``` will lookup for a Post type. @namespace @method belongsTo @for DS @param {String} modelName (optional) type of the relationship @param {Object} options (optional) a hash of options @return {Ember.computed} relationship */ function belongsTo(modelName, options) { var opts, userEnteredModelName; if (typeof modelName === 'object') { opts = modelName; userEnteredModelName = undefined; } else { opts = options; userEnteredModelName = modelName; } if (typeof userEnteredModelName === 'string') { userEnteredModelName = (0, _emberDataPrivateSystemNormalizeModelName["default"])(userEnteredModelName); } (0, _emberDataPrivateDebug.assert)("The first argument to DS.belongsTo must be a string representing a model type key, not an instance of " + _ember["default"].inspect(userEnteredModelName) + ". E.g., to define a relation to the Person model, use DS.belongsTo('person')", typeof userEnteredModelName === 'string' || typeof userEnteredModelName === 'undefined'); opts = opts || {}; var meta = { type: userEnteredModelName, isRelationship: true, options: opts, kind: 'belongsTo', key: null }; return _ember["default"].computed({ get: function get(key) { if (opts.hasOwnProperty('serialize')) { (0, _emberDataPrivateDebug.warn)("You provided a serialize option on the \"" + key + "\" property in the \"" + this._internalModel.modelName + "\" class, this belongs in the serializer. See DS.Serializer and it's implementations http://emberjs.com/api/data/classes/DS.Serializer.html", false, { id: 'ds.model.serialize-option-in-belongs-to' }); } if (opts.hasOwnProperty('embedded')) { (0, _emberDataPrivateDebug.warn)("You provided an embedded option on the \"" + key + "\" property in the \"" + this._internalModel.modelName + "\" class, this belongs in the serializer. See DS.EmbeddedRecordsMixin http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html", false, { id: 'ds.model.embedded-option-in-belongs-to' }); } return this._internalModel._relationships.get(key).getRecord(); }, set: function set(key, value) { if (value === undefined) { value = null; } if (value && value.then) { this._internalModel._relationships.get(key).setRecordPromise(value); } else if (value) { this._internalModel._relationships.get(key).setRecord(value._internalModel); } else { this._internalModel._relationships.get(key).setRecord(value); } return this._internalModel._relationships.get(key).getRecord(); } }).meta(meta); } /* These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. */ var BelongsToMixin = _ember["default"].Mixin.create({ notifyBelongsToChanged: function notifyBelongsToChanged(key) { this.notifyPropertyChange(key); } }); exports.BelongsToMixin = BelongsToMixin; }); define("ember-data/-private/system/relationships/ext", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/relationship-meta", "ember-data/-private/system/empty-object"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemRelationshipMeta, _emberDataPrivateSystemEmptyObject) { "use strict"; var get = _ember["default"].get; var Map = _ember["default"].Map; var MapWithDefault = _ember["default"].MapWithDefault; var relationshipsDescriptor = _ember["default"].computed(function () { if (_ember["default"].testing === true && relationshipsDescriptor._cacheable === true) { relationshipsDescriptor._cacheable = false; } var map = new MapWithDefault({ defaultValue: function defaultValue() { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function (name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { meta.key = name; var relationshipsForType = map.get((0, _emberDataPrivateSystemRelationshipMeta.typeForRelationshipMeta)(meta)); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }).readOnly(); var relatedTypesDescriptor = _ember["default"].computed(function () { var _this = this; if (_ember["default"].testing === true && relatedTypesDescriptor._cacheable === true) { relatedTypesDescriptor._cacheable = false; } var modelName; var types = _ember["default"].A(); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { meta.key = name; modelName = (0, _emberDataPrivateSystemRelationshipMeta.typeForRelationshipMeta)(meta); (0, _emberDataPrivateDebug.assert)("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", modelName); if (!types.includes(modelName)) { (0, _emberDataPrivateDebug.assert)("Trying to sideload " + name + " on " + _this.toString() + " but the type doesn't exist.", !!modelName); types.push(modelName); } } }); return types; }).readOnly(); var relationshipsByNameDescriptor = _ember["default"].computed(function () { if (_ember["default"].testing === true && relationshipsByNameDescriptor._cacheable === true) { relationshipsByNameDescriptor._cacheable = false; } var map = Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { meta.key = name; var relationship = (0, _emberDataPrivateSystemRelationshipMeta.relationshipFromMeta)(meta); relationship.type = (0, _emberDataPrivateSystemRelationshipMeta.typeForRelationshipMeta)(meta); map.set(name, relationship); } }); return map; }).readOnly(); /** @module ember-data */ /* This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ /** @class Model @namespace DS */ var DidDefinePropertyMixin = _ember["default"].Mixin.create({ /** This Ember.js hook allows an object to be notified when a property is defined. In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array. This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this: ```javascript DS.Model.extend({ parent: DS.belongsTo('user') }); ``` This hook would be called with "parent" as the key and the computed property returned by `DS.belongsTo` as the value. @method didDefineProperty @param {Object} proto @param {String} key @param {Ember.ComputedProperty} value */ didDefineProperty: function didDefineProperty(proto, key, value) { // Check if the value being set is a computed property. if (value instanceof _ember["default"].ComputedProperty) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); meta.parentType = proto.constructor; } } }); exports.DidDefinePropertyMixin = DidDefinePropertyMixin; /* These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ var RelationshipsClassMethodsMixin = _ember["default"].Mixin.create({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. @method typeForRelationship @static @param {String} name the name of the relationship @param {store} store an instance of DS.Store @return {DS.Model} the type of the relationship, or undefined */ typeForRelationship: function typeForRelationship(name, store) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && store.modelFor(relationship.type); }, inverseMap: _ember["default"].computed(function () { return new _emberDataPrivateSystemEmptyObject["default"](); }), /** Find the relationship which is the inverse of the one asked for. For example, if you define models like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('message') }); ``` ```app/models/message.js import DS from 'ember-data'; export default DS.Model.extend({ owner: DS.belongsTo('post') }); ``` App.Post.inverseFor('comments') -> { type: App.Message, name: 'owner', kind: 'belongsTo' } App.Message.inverseFor('owner') -> { type: App.Post, name: 'comments', kind: 'hasMany' } @method inverseFor @static @param {String} name the name of the relationship @return {Object} the inverse relationship, or null */ inverseFor: function inverseFor(name, store) { var inverseMap = get(this, 'inverseMap'); if (inverseMap[name]) { return inverseMap[name]; } else { var inverse = this._findInverseFor(name, store); inverseMap[name] = inverse; return inverse; } }, //Calculate the inverse, ignoring the cache _findInverseFor: function _findInverseFor(name, store) { var inverseType = this.typeForRelationship(name, store); if (!inverseType) { return null; } var propertyMeta = this.metaForProperty(name); //If inverse is manually specified to be null, like `comments: DS.hasMany('message', { inverse: null })` var options = propertyMeta.options; if (options.inverse === null) { return null; } var inverseName, inverseKind, inverse; //If inverse is specified manually, return the inverse if (options.inverse) { inverseName = options.inverse; inverse = _ember["default"].get(inverseType, 'relationshipsByName').get(inverseName); (0, _emberDataPrivateDebug.assert)("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.modelName + "' model. This is most likely due to a missing attribute on your model definition.", !_ember["default"].isNone(inverse)); inverseKind = inverse.kind; } else { //No inverse was specified manually, we need to use a heuristic to guess one if (propertyMeta.type === propertyMeta.parentType.modelName) { (0, _emberDataPrivateDebug.warn)("Detected a reflexive relationship by the name of '" + name + "' without an inverse option. Look at http://emberjs.com/guides/models/defining-models/#toc_reflexive-relation for how to explicitly specify inverses.", false, { id: 'ds.model.reflexive-relationship-without-inverse' }); } var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } var filteredRelationships = possibleRelationships.filter(function (possibleRelationship) { var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options; return name === optionsForRelationship.inverse; }); (0, _emberDataPrivateDebug.assert)("You defined the '" + name + "' relationship on " + this + ", but you defined the inverse relationships of type " + inverseType.toString() + " multiple times. Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", filteredRelationships.length < 2); if (filteredRelationships.length === 1) { possibleRelationships = filteredRelationships; } (0, _emberDataPrivateDebug.assert)("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", possibleRelationships.length === 1); inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, relationshipsSoFar) { var possibleRelationships = relationshipsSoFar || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return possibleRelationships; } var relationships = relationshipMap.get(type.modelName); relationships = relationships.filter(function (relationship) { var optionsForRelationship = inverseType.metaForProperty(relationship.name).options; if (!optionsForRelationship.inverse) { return true; } return name === optionsForRelationship.inverse; }); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationships); } //Recurse to support polymorphism if (type.superclass) { findPossibleInverses(type.superclass, inverseType, possibleRelationships); } return possibleRelationships; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This computed property would return a map describing these relationships, like this: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; var relationships = Ember.get(Blog, 'relationships'); relationships.get(App.User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(App.Post); //=> [ { name: 'posts', kind: 'hasMany' } ] ``` @property relationships @static @type Ember.Map @readOnly */ relationships: relationshipsDescriptor, /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; var relationshipNames = Ember.get(Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] ``` @property relationshipNames @static @type Object @readOnly */ relationshipNames: _ember["default"].computed(function () { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; var relatedTypes = Ember.get(Blog, 'relatedTypes'); //=> [ App.User, App.Post ] ``` @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: relatedTypesDescriptor, /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; var relationshipsByName = Ember.get(Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: 'user', options: Object, isRelationship: true } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: 'user', options: Object, isRelationship: true } ``` @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: relationshipsByNameDescriptor, /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post'), title: DS.attr('string') }); ``` ```js import Ember from 'ember'; import Blog from 'app/models/blog'; var fields = Ember.get(Blog, 'fields'); fields.forEach(function(kind, field) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute ``` @property fields @static @type Ember.Map @readOnly */ fields: _ember["default"].computed(function () { var map = Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }).readOnly(), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function eachRelationship(callback, binding) { get(this, 'relationshipsByName').forEach(function (relationship, name) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @method eachRelatedType @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function eachRelatedType(callback, binding) { var relationshipTypes = get(this, 'relatedTypes'); for (var i = 0; i < relationshipTypes.length; i++) { var type = relationshipTypes[i]; callback.call(binding, type); } }, determineRelationshipType: function determineRelationshipType(knownSide, store) { var knownKey = knownSide.key; var knownKind = knownSide.kind; var inverse = this.inverseFor(knownKey, store); // let key; var otherKind = undefined; if (!inverse) { return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone'; } // key = inverse.name; otherKind = inverse.kind; if (otherKind === 'belongsTo') { return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne'; } else { return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany'; } } }); exports.RelationshipsClassMethodsMixin = RelationshipsClassMethodsMixin; var RelationshipsInstanceMethodsMixin = _ember["default"].Mixin.create({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, descriptor); ``` - `name` the name of the current property in the iteration - `descriptor` the meta object that describes this relationship The relationship descriptor argument is an object with the following properties. - **key** <span class="type">String</span> the name of this relationship on the Model - **kind** <span class="type">String</span> "hasMany" or "belongsTo" - **options** <span class="type">Object</span> the original options hash passed when the relationship was declared - **parentType** <span class="type">DS.Model</span> the type of the Model that owns this relationship - **type** <span class="type">String</span> the type name of the related Model Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachRelationship(function(name, descriptor) { if (descriptor.kind === 'hasMany') { var serializedHasManyName = name.toUpperCase() + '_IDS'; json[serializedHasManyName] = record.get(name).mapBy('id'); } }); return json; } }); ``` @method eachRelationship @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function eachRelationship(callback, binding) { this.constructor.eachRelationship(callback, binding); }, relationshipFor: function relationshipFor(name) { return get(this.constructor, 'relationshipsByName').get(name); }, inverseFor: function inverseFor(key) { return this.constructor.inverseFor(key, this.store); } }); exports.RelationshipsInstanceMethodsMixin = RelationshipsInstanceMethodsMixin; }); define("ember-data/-private/system/relationships/has-many", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/normalize-model-name", "ember-data/-private/system/is-array-like"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateSystemIsArrayLike) { "use strict"; exports["default"] = hasMany; /** @module ember-data */ /** `DS.hasMany` is used to define One-To-Many and Many-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.hasMany` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model. #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo('post') }); ``` #### Many-To-Many To declare a many-to-many relationship between two models, use `DS.hasMany`: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ tags: DS.hasMany('tag') }); ``` ```app/models/tag.js import DS from 'ember-data'; export default DS.Model.extend({ posts: DS.hasMany('post') }); ``` You can avoid passing a string as the first parameter. In that case Ember Data will infer the type from the singularized key name. ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ tags: DS.hasMany() }); ``` will lookup for a Tag type. #### Explicit Inverses Ember Data will do its best to discover which relationships map to one another. In the one-to-many code above, for example, Ember Data can figure out that changing the `comments` relationship should update the `post` relationship on the inverse because post is the only relationship to that model. However, sometimes you may have multiple `belongsTo`/`hasManys` for the same type. You can specify which property on the related model is the inverse using `DS.hasMany`'s `inverse` option: ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ onePost: DS.belongsTo('post'), twoPost: DS.belongsTo('post'), redPost: DS.belongsTo('post'), bluePost: DS.belongsTo('post') }); ``` ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment', { inverse: 'redPost' }) }); ``` You can also specify an inverse on a `belongsTo`, which works how you'd expect. @namespace @method hasMany @for DS @param {String} type (optional) type of the relationship @param {Object} options (optional) a hash of options @return {Ember.computed} relationship */ function hasMany(type, options) { if (typeof type === 'object') { options = type; type = undefined; } (0, _emberDataPrivateDebug.assert)("The first argument to DS.hasMany must be a string representing a model type key, not an instance of " + _ember["default"].inspect(type) + ". E.g., to define a relation to the Comment model, use DS.hasMany('comment')", typeof type === 'string' || typeof type === 'undefined'); options = options || {}; if (typeof type === 'string') { type = (0, _emberDataPrivateSystemNormalizeModelName["default"])(type); } // Metadata about relationships is stored on the meta of // the relationship. This is used for introspection and // serialization. Note that `key` is populated lazily // the first time the CP is called. var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany', key: null }; return _ember["default"].computed({ get: function get(key) { var relationship = this._internalModel._relationships.get(key); return relationship.getRecords(); }, set: function set(key, records) { (0, _emberDataPrivateDebug.assert)("You must pass an array of records to set a hasMany relationship", (0, _emberDataPrivateSystemIsArrayLike["default"])(records)); (0, _emberDataPrivateDebug.assert)("All elements of a hasMany relationship must be instances of DS.Model, you passed " + _ember["default"].inspect(records), (function () { return _ember["default"].A(records).every(function (record) { return record.hasOwnProperty('_internalModel') === true; }); })()); var relationship = this._internalModel._relationships.get(key); relationship.clear(); relationship.addRecords(_ember["default"].A(records).mapBy('_internalModel')); return relationship.getRecords(); } }).meta(meta); } var HasManyMixin = _ember["default"].Mixin.create({ notifyHasManyAdded: function notifyHasManyAdded(key) { //We need to notifyPropertyChange in the adding case because we need to make sure //we fetch the newly added record in case it is unloaded //TODO(Igor): Consider whether we could do this only if the record state is unloaded //Goes away once hasMany is double promisified this.notifyPropertyChange(key); } }); exports.HasManyMixin = HasManyMixin; }); define("ember-data/-private/system/relationships/state/belongs-to", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/relationships/state/relationship"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemRelationshipsStateRelationship) { "use strict"; exports["default"] = BelongsToRelationship; function BelongsToRelationship(store, record, inverseKey, relationshipMeta) { this._super$constructor(store, record, inverseKey, relationshipMeta); this.record = record; this.key = relationshipMeta.key; this.inverseRecord = null; this.canonicalState = null; } BelongsToRelationship.prototype = Object.create(_emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype); BelongsToRelationship.prototype.constructor = BelongsToRelationship; BelongsToRelationship.prototype._super$constructor = _emberDataPrivateSystemRelationshipsStateRelationship["default"]; BelongsToRelationship.prototype.setRecord = function (newRecord) { if (newRecord) { this.addRecord(newRecord); } else if (this.inverseRecord) { this.removeRecord(this.inverseRecord); } this.setHasData(true); this.setHasLoaded(true); }; BelongsToRelationship.prototype.setCanonicalRecord = function (newRecord) { if (newRecord) { this.addCanonicalRecord(newRecord); } else if (this.canonicalState) { this.removeCanonicalRecord(this.canonicalState); } this.flushCanonicalLater(); this.setHasData(true); this.setHasLoaded(true); }; BelongsToRelationship.prototype._super$addCanonicalRecord = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.addCanonicalRecord; BelongsToRelationship.prototype.addCanonicalRecord = function (newRecord) { if (this.canonicalMembers.has(newRecord)) { return; } if (this.canonicalState) { this.removeCanonicalRecord(this.canonicalState); } this.canonicalState = newRecord; this._super$addCanonicalRecord(newRecord); }; BelongsToRelationship.prototype._super$flushCanonical = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.flushCanonical; BelongsToRelationship.prototype.flushCanonical = function () { //temporary fix to not remove newly created records if server returned null. //TODO remove once we have proper diffing if (this.inverseRecord && this.inverseRecord.isNew() && !this.canonicalState) { return; } this.inverseRecord = this.canonicalState; this.record.notifyBelongsToChanged(this.key); this._super$flushCanonical(); }; BelongsToRelationship.prototype._super$addRecord = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.addRecord; BelongsToRelationship.prototype.addRecord = function (newRecord) { if (this.members.has(newRecord)) { return; } (0, _emberDataPrivateDebug.assertPolymorphicType)(this.record, this.relationshipMeta, newRecord); if (this.inverseRecord) { this.removeRecord(this.inverseRecord); } this.inverseRecord = newRecord; this._super$addRecord(newRecord); this.record.notifyBelongsToChanged(this.key); }; BelongsToRelationship.prototype.setRecordPromise = function (newPromise) { var content = newPromise.get && newPromise.get('content'); (0, _emberDataPrivateDebug.assert)("You passed in a promise that did not originate from an EmberData relationship. You can only pass promises that come from a belongsTo or hasMany relationship to the get call.", content !== undefined); this.setRecord(content ? content._internalModel : content); }; BelongsToRelationship.prototype._super$removeRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.removeRecordFromOwn; BelongsToRelationship.prototype.removeRecordFromOwn = function (record) { if (!this.members.has(record)) { return; } this.inverseRecord = null; this._super$removeRecordFromOwn(record); this.record.notifyBelongsToChanged(this.key); }; BelongsToRelationship.prototype._super$removeCanonicalRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.removeCanonicalRecordFromOwn; BelongsToRelationship.prototype.removeCanonicalRecordFromOwn = function (record) { if (!this.canonicalMembers.has(record)) { return; } this.canonicalState = null; this._super$removeCanonicalRecordFromOwn(record); }; BelongsToRelationship.prototype.findRecord = function () { if (this.inverseRecord) { return this.store._findByInternalModel(this.inverseRecord); } else { return _ember["default"].RSVP.Promise.resolve(null); } }; BelongsToRelationship.prototype.fetchLink = function () { var _this = this; return this.store.findBelongsTo(this.record, this.link, this.relationshipMeta).then(function (record) { if (record) { _this.addRecord(record); } return record; }); }; BelongsToRelationship.prototype.getRecord = function () { var _this2 = this; //TODO(Igor) flushCanonical here once our syncing is not stupid if (this.isAsync) { var promise; if (this.link) { if (this.hasLoaded) { promise = this.findRecord(); } else { promise = this.findLink().then(function () { return _this2.findRecord(); }); } } else { promise = this.findRecord(); } return _emberDataPrivateSystemPromiseProxies.PromiseObject.create({ promise: promise, content: this.inverseRecord ? this.inverseRecord.getRecord() : null }); } else { if (this.inverseRecord === null) { return null; } var toReturn = this.inverseRecord.getRecord(); (0, _emberDataPrivateDebug.assert)("You looked up the '" + this.key + "' relationship on a '" + this.record.type.modelName + "' with id " + this.record.id + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)", toReturn === null || !toReturn.get('isEmpty')); return toReturn; } }; BelongsToRelationship.prototype.reload = function () { // TODO handle case when reload() is triggered multiple times if (this.link) { return this.fetchLink(); } // reload record, if it is already loaded if (this.inverseRecord && this.inverseRecord.record) { return this.inverseRecord.record.reload(); } return this.findRecord(); }; }); define("ember-data/-private/system/relationships/state/create", ["exports", "ember", "ember-data/-private/system/relationships/state/has-many", "ember-data/-private/system/relationships/state/belongs-to", "ember-data/-private/system/empty-object"], function (exports, _ember, _emberDataPrivateSystemRelationshipsStateHasMany, _emberDataPrivateSystemRelationshipsStateBelongsTo, _emberDataPrivateSystemEmptyObject) { "use strict"; exports["default"] = Relationships; var get = _ember["default"].get; function shouldFindInverse(relationshipMeta) { var options = relationshipMeta.options; return !(options && options.inverse === null); } function createRelationshipFor(record, relationshipMeta, store) { var inverseKey = undefined; var inverse = null; if (shouldFindInverse(relationshipMeta)) { inverse = record.type.inverseFor(relationshipMeta.key, store); } if (inverse) { inverseKey = inverse.name; } if (relationshipMeta.kind === 'hasMany') { return new _emberDataPrivateSystemRelationshipsStateHasMany["default"](store, record, inverseKey, relationshipMeta); } else { return new _emberDataPrivateSystemRelationshipsStateBelongsTo["default"](store, record, inverseKey, relationshipMeta); } } function Relationships(record) { this.record = record; this.initializedRelationships = new _emberDataPrivateSystemEmptyObject["default"](); } Relationships.prototype.has = function (key) { return !!this.initializedRelationships[key]; }; Relationships.prototype.get = function (key) { var relationships = this.initializedRelationships; var relationshipsByName = get(this.record.type, 'relationshipsByName'); if (!relationships[key] && relationshipsByName.get(key)) { relationships[key] = createRelationshipFor(this.record, relationshipsByName.get(key), this.record.store); } return relationships[key]; }; }); define("ember-data/-private/system/relationships/state/has-many", ["exports", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/relationships/state/relationship", "ember-data/-private/system/ordered-set", "ember-data/-private/system/many-array"], function (exports, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemRelationshipsStateRelationship, _emberDataPrivateSystemOrderedSet, _emberDataPrivateSystemManyArray) { "use strict"; exports["default"] = ManyRelationship; function ManyRelationship(store, record, inverseKey, relationshipMeta) { this._super$constructor(store, record, inverseKey, relationshipMeta); this.belongsToType = relationshipMeta.type; this.canonicalState = []; this.manyArray = _emberDataPrivateSystemManyArray["default"].create({ canonicalState: this.canonicalState, store: this.store, relationship: this, type: this.store.modelFor(this.belongsToType), record: record }); this.isPolymorphic = relationshipMeta.options.polymorphic; this.manyArray.isPolymorphic = this.isPolymorphic; } ManyRelationship.prototype = Object.create(_emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype); ManyRelationship.prototype.constructor = ManyRelationship; ManyRelationship.prototype._super$constructor = _emberDataPrivateSystemRelationshipsStateRelationship["default"]; ManyRelationship.prototype.destroy = function () { this.manyArray.destroy(); }; ManyRelationship.prototype._super$updateMeta = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.updateMeta; ManyRelationship.prototype.updateMeta = function (meta) { this._super$updateMeta(meta); this.manyArray.set('meta', meta); }; ManyRelationship.prototype._super$addCanonicalRecord = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.addCanonicalRecord; ManyRelationship.prototype.addCanonicalRecord = function (record, idx) { if (this.canonicalMembers.has(record)) { return; } if (idx !== undefined) { this.canonicalState.splice(idx, 0, record); } else { this.canonicalState.push(record); } this._super$addCanonicalRecord(record, idx); }; ManyRelationship.prototype._super$addRecord = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.addRecord; ManyRelationship.prototype.addRecord = function (record, idx) { if (this.members.has(record)) { return; } this._super$addRecord(record, idx); this.manyArray.internalAddRecords([record], idx); }; ManyRelationship.prototype._super$removeCanonicalRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.removeCanonicalRecordFromOwn; ManyRelationship.prototype.removeCanonicalRecordFromOwn = function (record, idx) { var i = idx; if (!this.canonicalMembers.has(record)) { return; } if (i === undefined) { i = this.canonicalState.indexOf(record); } if (i > -1) { this.canonicalState.splice(i, 1); } this._super$removeCanonicalRecordFromOwn(record, idx); }; ManyRelationship.prototype._super$flushCanonical = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.flushCanonical; ManyRelationship.prototype.flushCanonical = function () { this.manyArray.flushCanonical(); this._super$flushCanonical(); }; ManyRelationship.prototype._super$removeRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.removeRecordFromOwn; ManyRelationship.prototype.removeRecordFromOwn = function (record, idx) { if (!this.members.has(record)) { return; } this._super$removeRecordFromOwn(record, idx); if (idx !== undefined) { //TODO(Igor) not used currently, fix this.manyArray.currentState.removeAt(idx); } else { this.manyArray.internalRemoveRecords([record]); } }; ManyRelationship.prototype.notifyRecordRelationshipAdded = function (record, idx) { (0, _emberDataPrivateDebug.assertPolymorphicType)(this.record, this.relationshipMeta, record); this.record.notifyHasManyAdded(this.key, record, idx); }; ManyRelationship.prototype.reload = function () { var _this = this; var manyArrayLoadedState = this.manyArray.get('isLoaded'); if (this._loadingPromise) { if (this._loadingPromise.get('isPending')) { return this._loadingPromise; } if (this._loadingPromise.get('isRejected')) { this.manyArray.set('isLoaded', manyArrayLoadedState); } } if (this.link) { this._loadingPromise = (0, _emberDataPrivateSystemPromiseProxies.promiseManyArray)(this.fetchLink(), 'Reload with link'); return this._loadingPromise; } else { this._loadingPromise = (0, _emberDataPrivateSystemPromiseProxies.promiseManyArray)(this.store.scheduleFetchMany(this.manyArray.toArray()).then(function () { return _this.manyArray; }), 'Reload with ids'); return this._loadingPromise; } }; ManyRelationship.prototype.computeChanges = function (records) { var members = this.canonicalMembers; var recordsToRemove = []; var length; var record; var i; records = setForArray(records); members.forEach(function (member) { if (records.has(member)) { return; } recordsToRemove.push(member); }); this.removeCanonicalRecords(recordsToRemove); // Using records.toArray() since currently using // removeRecord can modify length, messing stuff up // forEach since it directly looks at "length" each // iteration records = records.toArray(); length = records.length; for (i = 0; i < length; i++) { record = records[i]; this.removeCanonicalRecord(record); this.addCanonicalRecord(record, i); } }; ManyRelationship.prototype.fetchLink = function () { var _this2 = this; return this.store.findHasMany(this.record, this.link, this.relationshipMeta).then(function (records) { if (records.hasOwnProperty('meta')) { _this2.updateMeta(records.meta); } _this2.store._backburner.join(function () { _this2.updateRecordsFromAdapter(records); _this2.manyArray.set('isLoaded', true); }); return _this2.manyArray; }); }; ManyRelationship.prototype.findRecords = function () { var _this3 = this; var manyArray = this.manyArray.toArray(); var internalModels = new Array(manyArray.length); for (var i = 0; i < manyArray.length; i++) { internalModels[i] = manyArray[i]._internalModel; } //TODO CLEANUP return this.store.findMany(internalModels).then(function () { if (!_this3.manyArray.get('isDestroyed')) { //Goes away after the manyArray refactor _this3.manyArray.set('isLoaded', true); } return _this3.manyArray; }); }; ManyRelationship.prototype.notifyHasManyChanged = function () { this.record.notifyHasManyAdded(this.key); }; ManyRelationship.prototype.getRecords = function () { var _this4 = this; //TODO(Igor) sync server here, once our syncing is not stupid if (this.isAsync) { var promise; if (this.link) { if (this.hasLoaded) { promise = this.findRecords(); } else { promise = this.findLink().then(function () { return _this4.findRecords(); }); } } else { promise = this.findRecords(); } this._loadingPromise = _emberDataPrivateSystemPromiseProxies.PromiseManyArray.create({ content: this.manyArray, promise: promise }); return this._loadingPromise; } else { (0, _emberDataPrivateDebug.assert)("You looked up the '" + this.key + "' relationship on a '" + this.record.type.modelName + "' with id " + this.record.id + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", this.manyArray.isEvery('isEmpty', false)); //TODO(Igor) WTF DO I DO HERE? if (!this.manyArray.get('isDestroyed')) { this.manyArray.set('isLoaded', true); } return this.manyArray; } }; function setForArray(array) { var set = new _emberDataPrivateSystemOrderedSet["default"](); if (array) { for (var i = 0, l = array.length; i < l; i++) { set.add(array[i]); } } return set; } }); define("ember-data/-private/system/relationships/state/relationship", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/ordered-set"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemOrderedSet) { "use strict"; exports["default"] = Relationship; function Relationship(store, record, inverseKey, relationshipMeta) { var async = relationshipMeta.options.async; this.members = new _emberDataPrivateSystemOrderedSet["default"](); this.canonicalMembers = new _emberDataPrivateSystemOrderedSet["default"](); this.store = store; this.key = relationshipMeta.key; this.inverseKey = inverseKey; this.record = record; this.isAsync = typeof async === 'undefined' ? true : async; this.relationshipMeta = relationshipMeta; //This probably breaks for polymorphic relationship in complex scenarios, due to //multiple possible modelNames this.inverseKeyForImplicit = this.record.constructor.modelName + this.key; this.linkPromise = null; this.meta = null; this.hasData = false; this.hasLoaded = false; } Relationship.prototype = { constructor: Relationship, destroy: _ember["default"].K, updateMeta: function updateMeta(meta) { this.meta = meta; }, clear: function clear() { var members = this.members.list; var member; while (members.length > 0) { member = members[0]; this.removeRecord(member); } }, removeRecords: function removeRecords(records) { var _this = this; records.forEach(function (record) { return _this.removeRecord(record); }); }, addRecords: function addRecords(records, idx) { var _this2 = this; records.forEach(function (record) { _this2.addRecord(record, idx); if (idx !== undefined) { idx++; } }); }, addCanonicalRecords: function addCanonicalRecords(records, idx) { for (var i = 0; i < records.length; i++) { if (idx !== undefined) { this.addCanonicalRecord(records[i], i + idx); } else { this.addCanonicalRecord(records[i]); } } }, addCanonicalRecord: function addCanonicalRecord(record, idx) { if (!this.canonicalMembers.has(record)) { this.canonicalMembers.add(record); if (this.inverseKey) { record._relationships.get(this.inverseKey).addCanonicalRecord(this.record); } else { if (!record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit] = new Relationship(this.store, record, this.key, { options: {} }); } record._implicitRelationships[this.inverseKeyForImplicit].addCanonicalRecord(this.record); } } this.flushCanonicalLater(); this.setHasData(true); }, removeCanonicalRecords: function removeCanonicalRecords(records, idx) { for (var i = 0; i < records.length; i++) { if (idx !== undefined) { this.removeCanonicalRecord(records[i], i + idx); } else { this.removeCanonicalRecord(records[i]); } } }, removeCanonicalRecord: function removeCanonicalRecord(record, idx) { if (this.canonicalMembers.has(record)) { this.removeCanonicalRecordFromOwn(record); if (this.inverseKey) { this.removeCanonicalRecordFromInverse(record); } else { if (record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit].removeCanonicalRecord(this.record); } } } this.flushCanonicalLater(); }, addRecord: function addRecord(record, idx) { if (!this.members.has(record)) { this.members.addWithIndex(record, idx); this.notifyRecordRelationshipAdded(record, idx); if (this.inverseKey) { record._relationships.get(this.inverseKey).addRecord(this.record); } else { if (!record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit] = new Relationship(this.store, record, this.key, { options: {} }); } record._implicitRelationships[this.inverseKeyForImplicit].addRecord(this.record); } this.record.updateRecordArraysLater(); } this.setHasData(true); }, removeRecord: function removeRecord(record) { if (this.members.has(record)) { this.removeRecordFromOwn(record); if (this.inverseKey) { this.removeRecordFromInverse(record); } else { if (record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit].removeRecord(this.record); } } } }, removeRecordFromInverse: function removeRecordFromInverse(record) { var inverseRelationship = record._relationships.get(this.inverseKey); //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeRecordFromOwn(this.record); } }, removeRecordFromOwn: function removeRecordFromOwn(record) { this.members["delete"](record); this.notifyRecordRelationshipRemoved(record); this.record.updateRecordArrays(); }, removeCanonicalRecordFromInverse: function removeCanonicalRecordFromInverse(record) { var inverseRelationship = record._relationships.get(this.inverseKey); //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeCanonicalRecordFromOwn(this.record); } }, removeCanonicalRecordFromOwn: function removeCanonicalRecordFromOwn(record) { this.canonicalMembers["delete"](record); this.flushCanonicalLater(); }, flushCanonical: function flushCanonical() { this.willSync = false; //a hack for not removing new records //TODO remove once we have proper diffing var newRecords = []; for (var i = 0; i < this.members.list.length; i++) { if (this.members.list[i].isNew()) { newRecords.push(this.members.list[i]); } } //TODO(Igor) make this less abysmally slow this.members = this.canonicalMembers.copy(); for (i = 0; i < newRecords.length; i++) { this.members.add(newRecords[i]); } }, flushCanonicalLater: function flushCanonicalLater() { var _this3 = this; if (this.willSync) { return; } this.willSync = true; this.store._backburner.join(function () { return _this3.store._backburner.schedule('syncRelationships', _this3, _this3.flushCanonical); }); }, updateLink: function updateLink(link) { (0, _emberDataPrivateDebug.warn)("You have pushed a record of type '" + this.record.type.modelName + "' with '" + this.key + "' as a link, but the association is not an async relationship.", this.isAsync, { id: 'ds.store.push-link-for-sync-relationship' }); (0, _emberDataPrivateDebug.assert)("You have pushed a record of type '" + this.record.type.modelName + "' with '" + this.key + "' as a link, but the value of that link is not a string.", typeof link === 'string' || link === null); if (link !== this.link) { this.link = link; this.linkPromise = null; this.setHasLoaded(false); this.record.notifyPropertyChange(this.key); } }, findLink: function findLink() { if (this.linkPromise) { return this.linkPromise; } else { var promise = this.fetchLink(); this.linkPromise = promise; return promise.then(function (result) { return result; }); } }, updateRecordsFromAdapter: function updateRecordsFromAdapter(records) { //TODO(Igor) move this to a proper place //TODO Once we have adapter support, we need to handle updated and canonical changes this.computeChanges(records); this.setHasData(true); this.setHasLoaded(true); }, notifyRecordRelationshipAdded: _ember["default"].K, notifyRecordRelationshipRemoved: _ember["default"].K, /* `hasData` for a relationship is a flag to indicate if we consider the content of this relationship "known". Snapshots uses this to tell the difference between unknown (`undefined`) or empty (`null`). The reason for this is that we wouldn't want to serialize unknown relationships as `null` as that might overwrite remote state. All relationships for a newly created (`store.createRecord()`) are considered known (`hasData === true`). */ setHasData: function setHasData(value) { this.hasData = value; }, /* `hasLoaded` is a flag to indicate if we have gotten data from the adapter or not when the relationship has a link. This is used to be able to tell when to fetch the link and when to return the local data in scenarios where the local state is considered known (`hasData === true`). Updating the link will automatically set `hasLoaded` to `false`. */ setHasLoaded: function setHasLoaded(value) { this.hasLoaded = value; } }; }); define('ember-data/-private/system/snapshot-record-array', ['exports'], function (exports) { 'use strict'; exports['default'] = SnapshotRecordArray; /** @module ember-data */ /** @class SnapshotRecordArray @namespace DS @private @constructor @param {Array} snapshots An array of snapshots @param {Object} meta */ function SnapshotRecordArray(recordArray, meta) { var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; /** An array of snapshots @private @property _snapshots @type {Array} */ this._snapshots = null; /** An array of records @private @property _recordArray @type {Array} */ this._recordArray = recordArray; /** Number of records in the array @property length @type {Number} */ this.length = recordArray.get('length'); /** The type of the underlying records for the snapshots in the array, as a DS.Model @property type @type {DS.Model} */ this.type = recordArray.get('type'); /** Meta object @property meta @type {Object} */ this.meta = meta; /** A hash of adapter options @property adapterOptions @type {Object} */ this.adapterOptions = options.adapterOptions; this.include = options.include; } /** Get snapshots of the underlying record array @method snapshots @return {Array} Array of snapshots */ SnapshotRecordArray.prototype.snapshots = function () { if (this._snapshots) { return this._snapshots; } var recordArray = this._recordArray; this._snapshots = recordArray.invoke('createSnapshot'); return this._snapshots; }; }); define("ember-data/-private/system/snapshot", ["exports", "ember", "ember-data/-private/system/empty-object"], function (exports, _ember, _emberDataPrivateSystemEmptyObject) { "use strict"; exports["default"] = Snapshot; /** @module ember-data */ var get = _ember["default"].get; /** @class Snapshot @namespace DS @private @constructor @param {DS.Model} internalModel The model to create a snapshot from */ function Snapshot(internalModel) { var _this = this; var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this._attributes = new _emberDataPrivateSystemEmptyObject["default"](); this._belongsToRelationships = new _emberDataPrivateSystemEmptyObject["default"](); this._belongsToIds = new _emberDataPrivateSystemEmptyObject["default"](); this._hasManyRelationships = new _emberDataPrivateSystemEmptyObject["default"](); this._hasManyIds = new _emberDataPrivateSystemEmptyObject["default"](); var record = internalModel.getRecord(); this.record = record; record.eachAttribute(function (keyName) { return _this._attributes[keyName] = get(record, keyName); }); this.id = internalModel.id; this._internalModel = internalModel; this.type = internalModel.type; this.modelName = internalModel.type.modelName; /** A hash of adapter options @property adapterOptions @type {Object} */ this.adapterOptions = options.adapterOptions; this.include = options.include; this._changedAttributes = record.changedAttributes(); } Snapshot.prototype = { constructor: Snapshot, /** The id of the snapshot's underlying record Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.id; // => '1' ``` @property id @type {String} */ id: null, /** The underlying record for this snapshot. Can be used to access methods and properties defined on the record. Example ```javascript var json = snapshot.record.toJSON(); ``` @property record @type {DS.Model} */ record: null, /** The type of the underlying record for this snapshot, as a DS.Model. @property type @type {DS.Model} */ type: null, /** The name of the type of the underlying record for this snapshot, as a string. @property modelName @type {String} */ modelName: null, /** Returns the value of an attribute. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.attr('author'); // => 'Tomster' postSnapshot.attr('title'); // => 'Ember.js rocks' ``` Note: Values are loaded eagerly and cached when the snapshot is created. @method attr @param {String} keyName @return {Object} The attribute value or undefined */ attr: function attr(keyName) { if (keyName in this._attributes) { return this._attributes[keyName]; } throw new _ember["default"].Error("Model '" + _ember["default"].inspect(this.record) + "' has no attribute named '" + keyName + "' defined."); }, /** Returns all attributes and their corresponding values. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.attributes(); // => { author: 'Tomster', title: 'Ember.js rocks' } ``` @method attributes @return {Object} All attributes of the current snapshot */ attributes: function attributes() { return _ember["default"].copy(this._attributes); }, /** Returns all changed attributes and their old and new values. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postModel.set('title', 'Ember.js rocks!'); postSnapshot.changedAttributes(); // => { title: ['Ember.js rocks', 'Ember.js rocks!'] } ``` @method changedAttributes @return {Object} All changed attributes of the current snapshot */ changedAttributes: function changedAttributes() { var changedAttributes = new _emberDataPrivateSystemEmptyObject["default"](); var changedAttributeKeys = Object.keys(this._changedAttributes); for (var i = 0, _length = changedAttributeKeys.length; i < _length; i++) { var key = changedAttributeKeys[i]; changedAttributes[key] = _ember["default"].copy(this._changedAttributes[key]); } return changedAttributes; }, /** Returns the current value of a belongsTo relationship. `belongsTo` takes an optional hash of options as a second parameter, currently supported options are: - `id`: set to `true` if you only want the ID of the related record to be returned. Example ```javascript // store.push('post', { id: 1, title: 'Hello World' }); // store.createRecord('comment', { body: 'Lorem ipsum', post: post }); commentSnapshot.belongsTo('post'); // => DS.Snapshot commentSnapshot.belongsTo('post', { id: true }); // => '1' // store.push('comment', { id: 1, body: 'Lorem ipsum' }); commentSnapshot.belongsTo('post'); // => undefined ``` Calling `belongsTo` will return a new Snapshot as long as there's any known data for the relationship available, such as an ID. If the relationship is known but unset, `belongsTo` will return `null`. If the contents of the relationship is unknown `belongsTo` will return `undefined`. Note: Relationships are loaded lazily and cached upon first access. @method belongsTo @param {String} keyName @param {Object} [options] @return {(DS.Snapshot|String|null|undefined)} A snapshot or ID of a known relationship or null if the relationship is known but unset. undefined will be returned if the contents of the relationship is unknown. */ belongsTo: function belongsTo(keyName, options) { var id = options && options.id; var relationship, inverseRecord, hasData; var result; if (id && keyName in this._belongsToIds) { return this._belongsToIds[keyName]; } if (!id && keyName in this._belongsToRelationships) { return this._belongsToRelationships[keyName]; } relationship = this._internalModel._relationships.get(keyName); if (!(relationship && relationship.relationshipMeta.kind === 'belongsTo')) { throw new _ember["default"].Error("Model '" + _ember["default"].inspect(this.record) + "' has no belongsTo relationship named '" + keyName + "' defined."); } hasData = get(relationship, 'hasData'); inverseRecord = get(relationship, 'inverseRecord'); if (hasData) { if (inverseRecord && !inverseRecord.isDeleted()) { if (id) { result = get(inverseRecord, 'id'); } else { result = inverseRecord.createSnapshot(); } } else { result = null; } } if (id) { this._belongsToIds[keyName] = result; } else { this._belongsToRelationships[keyName] = result; } return result; }, /** Returns the current value of a hasMany relationship. `hasMany` takes an optional hash of options as a second parameter, currently supported options are: - `ids`: set to `true` if you only want the IDs of the related records to be returned. Example ```javascript // store.push('post', { id: 1, title: 'Hello World', comments: [2, 3] }); postSnapshot.hasMany('comments'); // => [DS.Snapshot, DS.Snapshot] postSnapshot.hasMany('comments', { ids: true }); // => ['2', '3'] // store.push('post', { id: 1, title: 'Hello World' }); postSnapshot.hasMany('comments'); // => undefined ``` Note: Relationships are loaded lazily and cached upon first access. @method hasMany @param {String} keyName @param {Object} [options] @return {(Array|undefined)} An array of snapshots or IDs of a known relationship or an empty array if the relationship is known but unset. undefined will be returned if the contents of the relationship is unknown. */ hasMany: function hasMany(keyName, options) { var ids = options && options.ids; var relationship, members, hasData; var results; if (ids && keyName in this._hasManyIds) { return this._hasManyIds[keyName]; } if (!ids && keyName in this._hasManyRelationships) { return this._hasManyRelationships[keyName]; } relationship = this._internalModel._relationships.get(keyName); if (!(relationship && relationship.relationshipMeta.kind === 'hasMany')) { throw new _ember["default"].Error("Model '" + _ember["default"].inspect(this.record) + "' has no hasMany relationship named '" + keyName + "' defined."); } hasData = get(relationship, 'hasData'); members = get(relationship, 'members'); if (hasData) { results = []; members.forEach(function (member) { if (!member.isDeleted()) { if (ids) { results.push(member.id); } else { results.push(member.createSnapshot()); } } }); } if (ids) { this._hasManyIds[keyName] = results; } else { this._hasManyRelationships[keyName] = results; } return results; }, /** Iterates through all the attributes of the model, calling the passed function on each attribute. Example ```javascript snapshot.eachAttribute(function(name, meta) { // ... }); ``` @method eachAttribute @param {Function} callback the callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound */ eachAttribute: function eachAttribute(callback, binding) { this.record.eachAttribute(callback, binding); }, /** Iterates through all the relationships of the model, calling the passed function on each relationship. Example ```javascript snapshot.eachRelationship(function(name, relationship) { // ... }); ``` @method eachRelationship @param {Function} callback the callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound */ eachRelationship: function eachRelationship(callback, binding) { this.record.eachRelationship(callback, binding); }, /** @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function serialize(options) { return this.record.store.serializerFor(this.modelName).serialize(this, options); } }; }); define('ember-data/-private/system/store', ['exports', 'ember', 'ember-data/model', 'ember-data/-private/debug', 'ember-data/-private/system/normalize-link', 'ember-data/-private/system/normalize-model-name', 'ember-data/adapters/errors', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/store/common', 'ember-data/-private/system/store/serializer-response', 'ember-data/-private/system/store/serializers', 'ember-data/-private/system/store/finders', 'ember-data/-private/utils', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/record-array-manager', 'ember-data/-private/system/store/container-instance-cache', 'ember-data/-private/system/model/internal-model', 'ember-data/-private/system/empty-object', 'ember-data/-private/features'], function (exports, _ember, _emberDataModel, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeLink, _emberDataPrivateSystemNormalizeModelName, _emberDataAdaptersErrors, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStoreCommon, _emberDataPrivateSystemStoreSerializerResponse, _emberDataPrivateSystemStoreSerializers, _emberDataPrivateSystemStoreFinders, _emberDataPrivateUtils, _emberDataPrivateSystemCoerceId, _emberDataPrivateSystemRecordArrayManager, _emberDataPrivateSystemStoreContainerInstanceCache, _emberDataPrivateSystemModelInternalModel, _emberDataPrivateSystemEmptyObject, _emberDataPrivateFeatures) { /** @module ember-data */ 'use strict'; var badIdFormatAssertion = '`id` passed to `findRecord()` has to be non-empty string or number'; exports.badIdFormatAssertion = badIdFormatAssertion; var Backburner = _ember['default']._Backburner; var Map = _ember['default'].Map; //Get the materialized model from the internalModel/promise that returns //an internal model and return it in a promiseObject. Useful for returning //from find methods function promiseRecord(internalModel, label) { var toReturn = internalModel.then(function (model) { return model.getRecord(); }); return (0, _emberDataPrivateSystemPromiseProxies.promiseObject)(toReturn, label); } var get = _ember['default'].get; var set = _ember['default'].set; var once = _ember['default'].run.once; var isNone = _ember['default'].isNone; var isPresent = _ember['default'].isPresent; var Promise = _ember['default'].RSVP.Promise; var copy = _ember['default'].copy; var Store; var Service = _ember['default'].Service; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +internalModel+ means a record internalModel object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a DS.Model. /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of `DS.Model` that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: ```app/services/store.js import DS from 'ember-data'; export default DS.Store.extend({ }); ``` Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Store`'s `findRecord()` method: ```javascript store.findRecord('person', 123).then(function (person) { }); ``` By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ }); ``` You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. ### Store createRecord() vs. push() vs. pushPayload() The store provides multiple ways to create new record objects. They have some subtle differences in their use which are detailed below: [createRecord](#method_createRecord) is used for creating new records on the client side. This will return a new record in the `created.uncommitted` state. In order to persist this record to the backend you will need to call `record.save()`. [push](#method_push) is used to notify Ember Data's store of new or updated records that exist in the backend. This will return a record in the `loaded.saved` state. The primary use-case for `store#push` is to notify Ember Data about record updates (full or partial) that happen outside of the normal adapter methods (for example [SSE](http://dev.w3.org/html5/eventsource/) or [Web Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)). [pushPayload](#method_pushPayload) is a convenience wrapper for `store#push` that will deserialize payloads if the Serializer implements a `pushPayload` method. Note: When creating a new record using any of the above methods Ember Data will update `DS.RecordArray`s such as those returned by `store#peekAll()`, `store#findAll()` or `store#filter()`. This means any data bindings or computed properties that depend on the RecordArray will automatically be synced to include the new or updated record values. @class Store @namespace DS @extends Ember.Service */ exports.Store = Store = Service.extend({ /** @method init @private */ init: function init() { this._super.apply(this, arguments); this._backburner = new Backburner(['normalizeRelationships', 'syncRelationships', 'finished']); // internal bookkeeping; not observable this.typeMaps = {}; this.recordArrayManager = _emberDataPrivateSystemRecordArrayManager['default'].create({ store: this }); this._pendingSave = []; this._instanceCache = new _emberDataPrivateSystemStoreContainerInstanceCache['default']((0, _emberDataPrivateUtils.getOwner)(this)); //Used to keep track of all the find requests that need to be coalesced this._pendingFetch = Map.create(); }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, class, or string. If you want to specify `app/adapters/custom.js` as a string, do: ```js adapter: 'custom' ``` @property adapter @default DS.JSONAPIAdapter @type {(DS.Adapter|String)} */ adapter: '-json-api', /** Returns a JSON representation of the record using a custom type-specific serializer, if one exists. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @method serialize @private @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function serialize(record, options) { var snapshot = record._internalModel.createSnapshot(); return snapshot.serialize(options); }, /** This property returns the adapter, after resolving a possible string key. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @property defaultAdapter @private @return DS.Adapter */ defaultAdapter: _ember['default'].computed('adapter', function () { var adapter = get(this, 'adapter'); (0, _emberDataPrivateDebug.assert)('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name', typeof adapter === 'string'); adapter = this.retrieveManagedInstance('adapter', adapter); return adapter; }), // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. To create a new instance of a `Post`: ```js store.createRecord('post', { title: "Rails is omakase" }); ``` To create a new instance of a `Post` that has a relationship with a `User` record: ```js var user = this.store.peekRecord('user', 1); store.createRecord('post', { title: "Rails is omakase", user: user }); ``` @method createRecord @param {String} modelName @param {Object} inputProperties a hash of properties to set on the newly created record. @return {DS.Model} record */ createRecord: function createRecord(modelName, inputProperties) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's createRecord method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); var properties = copy(inputProperties) || new _emberDataPrivateSystemEmptyObject['default'](); // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (isNone(properties.id)) { properties.id = this._generateId(modelName, properties); } // Coerce ID to a string properties.id = (0, _emberDataPrivateSystemCoerceId['default'])(properties.id); var internalModel = this.buildInternalModel(typeClass, properties.id); var record = internalModel.getRecord(); // Move the record out of its initial `empty` state into // the `loaded` state. internalModel.loadedData(); // Set the properties specified on the record. record.setProperties(properties); internalModel.eachRelationship(function (key, descriptor) { internalModel._relationships.get(key).setHasData(true); }); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} modelName @param {Object} properties from the new record @return {String} if the adapter can generate one, an ID */ _generateId: function _generateId(modelName, properties) { var adapter = this.adapterFor(modelName); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this, modelName, properties); } return null; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. Example ```javascript var post = store.createRecord('post', { title: "Rails is omakase" }); store.deleteRecord(post); ``` @method deleteRecord @param {DS.Model} record */ deleteRecord: function deleteRecord(record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. Only non-dirty records can be unloaded. Example ```javascript store.findRecord('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function unloadRecord(record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** @method find @param {String} modelName @param {String|Integer} id @param {Object} options @return {Promise} promise @private */ find: function find(modelName, id, options) { // The default `model` hook in Ember.Route calls `find(modelName, id)`, // that's why we have to keep this method around even though `findRecord` is // the public way to get a record by modelName and id. if (arguments.length === 1) { (0, _emberDataPrivateDebug.assert)('Using store.find(type) has been removed. Use store.findAll(type) to retrieve all records for a given type.'); } if (_ember['default'].typeOf(id) === 'object') { (0, _emberDataPrivateDebug.assert)('Calling store.find() with a query object is no longer supported. Use store.query() instead.'); } if (options) { (0, _emberDataPrivateDebug.assert)('Calling store.find(type, id, { preload: preload }) is no longer supported. Use store.findRecord(type, id, { preload: preload }) instead.'); } (0, _emberDataPrivateDebug.assert)("You need to pass the model name and id to the store's find method", arguments.length === 2); (0, _emberDataPrivateDebug.assert)("You cannot pass `" + _ember['default'].inspect(id) + "` as id to the store's find method", _ember['default'].typeOf(id) === 'string' || _ember['default'].typeOf(id) === 'number'); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); return this.findRecord(modelName, id); }, /** This method returns a record for a given type and id combination. The `findRecord` method will always resolve its promise with the same object for a given type and `id`. The `findRecord` method will always return a **promise** that will be resolved with the record. Example ```app/routes/post.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id); } }); ``` If the record is not yet available, the store will ask the adapter's `find` method to find the necessary data. If the record is already present in the store, it depends on the reload behavior _when_ the returned promise resolves. ### Reloading The reload behavior is configured either via the passed `options` hash or the result of the adapter's `shouldReloadRecord`. If `{ reload: true }` is passed or `adapter.shouldReloadRecord` evaluates to `true`, then the returned promise resolves once the adapter returns data, regardless if the requested record is already in the store: ```js store.push({ data: { id: 1, type: 'post', revision: 1 } }); // adapter#findRecord resolves with // [ // { // id: 1, // type: 'post', // revision: 2 // } // ] store.findRecord('post', 1, { reload: true }).then(function(post) { post.get("revision"); // 2 }); ``` If no reload is indicated via the abovementioned ways, then the promise immediately resolves with the cached version in the store. ### Background Reloading Optionally, if `adapter.shouldBackgroundReloadRecord` evaluates to `true`, then a background reload is started, which updates the records' data, once it is available: ```js // app/adapters/post.js import ApplicationAdapter from "./application"; export default ApplicationAdapter.extend({ shouldReloadRecord(store, snapshot) { return false; }, shouldBackgroundReloadRecord(store, snapshot) { return true; } }); // ... store.push({ data: { id: 1, type: 'post', revision: 1 } }); var blogPost = store.findRecord('post', 1).then(function(post) { post.get('revision'); // 1 }); // later, once adapter#findRecord resolved with // [ // { // id: 1, // type: 'post', // revision: 2 // } // ] blogPost.get('revision'); // 2 ``` If you would like to force or prevent background reloading, you can set a boolean value for `backgroundReload` in the options object for `findRecord`. ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id, { backgroundReload: false }); } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the snapshot ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id, { adapterOptions: { subscribe: false } }); } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ findRecord: function(store, type, id, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); ``` See [peekRecord](#method_peekRecord) to get the cached version of a record. @since 1.13.0 @method findRecord @param {String} modelName @param {(String|Integer)} id @param {Object} options @return {Promise} promise */ findRecord: function findRecord(modelName, id, options) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's findRecord method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); (0, _emberDataPrivateDebug.assert)(badIdFormatAssertion, typeof id === 'string' && id.length > 0 || typeof id === 'number' && !isNaN(id)); var internalModel = this._internalModelForId(modelName, id); options = options || {}; if (!this.hasRecordForId(modelName, id)) { return this._findByInternalModel(internalModel, options); } var fetchedInternalModel = this._findRecord(internalModel, options); return promiseRecord(fetchedInternalModel, "DS: Store#findRecord " + internalModel.typeKey + " with id: " + get(internalModel, 'id')); }, _findRecord: function _findRecord(internalModel, options) { // Refetch if the reload option is passed if (options.reload) { return this.scheduleFetch(internalModel, options); } var snapshot = internalModel.createSnapshot(options); var typeClass = internalModel.type; var adapter = this.adapterFor(typeClass.modelName); // Refetch the record if the adapter thinks the record is stale if (adapter.shouldReloadRecord(this, snapshot)) { return this.scheduleFetch(internalModel, options); } if (options.backgroundReload === false) { return Promise.resolve(internalModel); } // Trigger the background refetch if backgroundReload option is passed if (options.backgroundReload || adapter.shouldBackgroundReloadRecord(this, snapshot)) { this.scheduleFetch(internalModel, options); } // Return the cached record return Promise.resolve(internalModel); }, _findByInternalModel: function _findByInternalModel(internalModel, options) { options = options || {}; if (options.preload) { internalModel._preloadData(options.preload); } var fetchedInternalModel = this._findEmptyInternalModel(internalModel, options); return promiseRecord(fetchedInternalModel, "DS: Store#findRecord " + internalModel.typeKey + " with id: " + get(internalModel, 'id')); }, _findEmptyInternalModel: function _findEmptyInternalModel(internalModel, options) { if (internalModel.isEmpty()) { return this.scheduleFetch(internalModel, options); } //TODO double check about reloading if (internalModel.isLoading()) { return internalModel._loadingPromise; } return Promise.resolve(internalModel); }, /** This method makes a series of requests to the adapter's `find` method and returns a promise that resolves once they are all loaded. @private @method findByIds @param {String} modelName @param {Array} ids @return {Promise} promise */ findByIds: function findByIds(modelName, ids) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's findByIds method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); var promises = new Array(ids.length); for (var i = 0; i < ids.length; i++) { promises[i] = this.findRecord(modelName, ids[i]); } return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(_ember['default'].RSVP.all(promises).then(_ember['default'].A, null, "DS: Store#findByIds of " + modelName + " complete")); }, /** This method is called by `findRecord` if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter. @method fetchRecord @private @param {InternalModel} internalModel model @return {Promise} promise */ // TODO rename this to have an underscore fetchRecord: function fetchRecord(internalModel, options) { var typeClass = internalModel.type; var id = internalModel.id; var adapter = this.adapterFor(typeClass.modelName); (0, _emberDataPrivateDebug.assert)("You tried to find a record but you have no adapter (for " + typeClass + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to find a record but your adapter (for " + typeClass + ") does not implement 'findRecord'", typeof adapter.findRecord === 'function' || typeof adapter.find === 'function'); var promise = (0, _emberDataPrivateSystemStoreFinders._find)(adapter, this, typeClass, id, internalModel, options); return promise; }, scheduleFetchMany: function scheduleFetchMany(records) { var internalModels = new Array(records.length); var fetches = new Array(records.length); for (var i = 0; i < records.length; i++) { internalModels[i] = records[i]._internalModel; } for (var i = 0; i < internalModels.length; i++) { fetches[i] = this.scheduleFetch(internalModels[i]); } return _ember['default'].RSVP.Promise.all(fetches); }, scheduleFetch: function scheduleFetch(internalModel, options) { var typeClass = internalModel.type; if (internalModel._loadingPromise) { return internalModel._loadingPromise; } var resolver = _ember['default'].RSVP.defer('Fetching ' + typeClass + 'with id: ' + internalModel.id); var pendingFetchItem = { record: internalModel, resolver: resolver, options: options }; var promise = resolver.promise; internalModel.loadingData(promise); if (!this._pendingFetch.get(typeClass)) { this._pendingFetch.set(typeClass, [pendingFetchItem]); } else { this._pendingFetch.get(typeClass).push(pendingFetchItem); } _ember['default'].run.scheduleOnce('afterRender', this, this.flushAllPendingFetches); return promise; }, flushAllPendingFetches: function flushAllPendingFetches() { if (this.isDestroyed || this.isDestroying) { return; } this._pendingFetch.forEach(this._flushPendingFetchForType, this); this._pendingFetch = Map.create(); }, _flushPendingFetchForType: function _flushPendingFetchForType(pendingFetchItems, typeClass) { var store = this; var adapter = store.adapterFor(typeClass.modelName); var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests; var records = _ember['default'].A(pendingFetchItems).mapBy('record'); function _fetchRecord(recordResolverPair) { recordResolverPair.resolver.resolve(store.fetchRecord(recordResolverPair.record, recordResolverPair.options)); // TODO adapter options } function resolveFoundRecords(records) { records.forEach(function (record) { var pair = _ember['default'].A(pendingFetchItems).findBy('record', record); if (pair) { var resolver = pair.resolver; resolver.resolve(record); } }); return records; } function makeMissingRecordsRejector(requestedRecords) { return function rejectMissingRecords(resolvedRecords) { resolvedRecords = _ember['default'].A(resolvedRecords); var missingRecords = requestedRecords.reject(function (record) { return resolvedRecords.includes(record); }); if (missingRecords.length) { (0, _emberDataPrivateDebug.warn)('Ember Data expected to find records with the following ids in the adapter response but they were missing: ' + _ember['default'].inspect(_ember['default'].A(missingRecords).mapBy('id')), false, { id: 'ds.store.missing-records-from-adapter' }); } rejectRecords(missingRecords); }; } function makeRecordsRejector(records) { return function (error) { rejectRecords(records, error); }; } function rejectRecords(records, error) { records.forEach(function (record) { var pair = _ember['default'].A(pendingFetchItems).findBy('record', record); if (pair) { var resolver = pair.resolver; resolver.reject(error); } }); } if (pendingFetchItems.length === 1) { _fetchRecord(pendingFetchItems[0]); } else if (shouldCoalesce) { // TODO: Improve records => snapshots => records => snapshots // // We want to provide records to all store methods and snapshots to all // adapter methods. To make sure we're doing that we're providing an array // of snapshots to adapter.groupRecordsForFindMany(), which in turn will // return grouped snapshots instead of grouped records. // // But since the _findMany() finder is a store method we need to get the // records from the grouped snapshots even though the _findMany() finder // will once again convert the records to snapshots for adapter.findMany() var snapshots = _ember['default'].A(records).invoke('createSnapshot'); var groups = adapter.groupRecordsForFindMany(this, snapshots); groups.forEach(function (groupOfSnapshots) { var groupOfRecords = _ember['default'].A(groupOfSnapshots).mapBy('_internalModel'); var requestedRecords = _ember['default'].A(groupOfRecords); var ids = requestedRecords.mapBy('id'); if (ids.length > 1) { (0, _emberDataPrivateSystemStoreFinders._findMany)(adapter, store, typeClass, ids, requestedRecords).then(resolveFoundRecords).then(makeMissingRecordsRejector(requestedRecords)).then(null, makeRecordsRejector(requestedRecords)); } else if (ids.length === 1) { var pair = _ember['default'].A(pendingFetchItems).findBy('record', groupOfRecords[0]); _fetchRecord(pair); } else { (0, _emberDataPrivateDebug.assert)("You cannot return an empty array from adapter's method groupRecordsForFindMany", false); } }); } else { pendingFetchItems.forEach(_fetchRecord); } }, /** Get the reference for the specified record. Example ```javascript var userRef = store.getReference('user', 1); // check if the user is loaded var isLoaded = userRef.value() !== null; // get the record of the reference (null if not yet available) var user = userRef.value(); // get the identifier of the reference if (userRef.remoteType() === "id") { var id = userRef.id(); } // load user (via store.find) userRef.load().then(...) // or trigger a reload userRef.reload().then(...) // provide data for reference userRef.push({ id: 1, username: "@user" }).then(function(user) { userRef.value() === user; }); ``` @method getReference @param {String} type @param {String|Integer} id @since 2.5.0 @return {RecordReference} */ getReference: function getReference(type, id) { return this._internalModelForId(type, id).recordReference; }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it is available in the store, otherwise it will return `null`. A record is available if it has been fetched earlier, or pushed manually into the store. _Note: This is an synchronous method and does not return a promise._ ```js var post = store.peekRecord('post', 1); post.get('id'); // 1 ``` @since 1.13.0 @method peekRecord @param {String} modelName @param {String|Integer} id @return {DS.Model|null} record */ peekRecord: function peekRecord(modelName, id) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's peekRecord method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); if (this.hasRecordForId(modelName, id)) { return this._internalModelForId(modelName, id).getRecord(); } else { return null; } }, /** This method is called by the record's `reload` method. This method calls the adapter's `find` method, which returns a promise. When **that** promise resolves, `reloadRecord` will resolve the promise returned by the record's `reload`. @method reloadRecord @private @param {DS.Model} internalModel @return {Promise} promise */ reloadRecord: function reloadRecord(internalModel) { var modelName = internalModel.type.modelName; var adapter = this.adapterFor(modelName); var id = internalModel.id; (0, _emberDataPrivateDebug.assert)("You cannot reload a record without an ID", id); (0, _emberDataPrivateDebug.assert)("You tried to reload a record but you have no adapter (for " + modelName + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to reload a record but your adapter does not implement `findRecord`", typeof adapter.findRecord === 'function' || typeof adapter.find === 'function'); return this.scheduleFetch(internalModel); }, /** Returns true if a record for a given type and ID is already loaded. @method hasRecordForId @param {(String|DS.Model)} modelName @param {(String|Integer)} inputId @return {Boolean} */ hasRecordForId: function hasRecordForId(modelName, inputId) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's hasRecordForId method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); var id = (0, _emberDataPrivateSystemCoerceId['default'])(inputId); var internalModel = this.typeMapFor(typeClass).idToRecord[id]; return !!internalModel && internalModel.isLoaded(); }, /** Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the `empty` state. @method recordForId @private @param {String} modelName @param {(String|Integer)} id @return {DS.Model} record */ recordForId: function recordForId(modelName, id) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's recordForId method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); return this._internalModelForId(modelName, id).getRecord(); }, _internalModelForId: function _internalModelForId(typeName, inputId) { var typeClass = this.modelFor(typeName); var id = (0, _emberDataPrivateSystemCoerceId['default'])(inputId); var idToRecord = this.typeMapFor(typeClass).idToRecord; var record = idToRecord[id]; if (!record || !idToRecord[id]) { record = this.buildInternalModel(typeClass, id); } return record; }, /** @method findMany @private @param {Array} internalModels @return {Promise} promise */ findMany: function findMany(internalModels) { var finds = new Array(internalModels.length); for (var i = 0; i < internalModels.length; i++) { finds[i] = this._findByInternalModel(internalModels[i]); } return Promise.all(finds); }, /** If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched. The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants. The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship. @method findHasMany @private @param {DS.Model} owner @param {any} link @param {(Relationship)} relationship @return {Promise} promise */ findHasMany: function findHasMany(owner, link, relationship) { var adapter = this.adapterFor(owner.type.modelName); (0, _emberDataPrivateDebug.assert)("You tried to load a hasMany relationship but you have no adapter (for " + owner.type + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", typeof adapter.findHasMany === 'function'); return (0, _emberDataPrivateSystemStoreFinders._findHasMany)(adapter, this, owner, link, relationship); }, /** @method findBelongsTo @private @param {DS.Model} owner @param {any} link @param {Relationship} relationship @return {Promise} promise */ findBelongsTo: function findBelongsTo(owner, link, relationship) { var adapter = this.adapterFor(owner.type.modelName); (0, _emberDataPrivateDebug.assert)("You tried to load a belongsTo relationship but you have no adapter (for " + owner.type + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", typeof adapter.findBelongsTo === 'function'); return (0, _emberDataPrivateSystemStoreFinders._findBelongsTo)(adapter, this, owner, link, relationship); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. --- If you do something like this: ```javascript store.query('person', { page: 1 }); ``` The call made to the server, using a Rails backend, will look something like this: ``` Started GET "/api/v1/person?page=1" Processing by Api::V1::PersonsController#index as HTML Parameters: { "page"=>"1" } ``` --- If you do something like this: ```javascript store.query('person', { ids: [1, 2, 3] }); ``` The call to the server, using a Rails backend, will look something like this: ``` Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3" Processing by Api::V1::PersonsController#index as HTML Parameters: { "ids" => ["1", "2", "3"] } ``` This method returns a promise, which is resolved with a `RecordArray` once the server returns. @since 1.13.0 @method query @param {String} modelName @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ query: function query(modelName, _query2) { return this._query(modelName, _query2); }, _query: function _query(modelName, query, array) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's query method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)("You need to pass a query hash to the store's query method", query); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); array = array || this.recordArrayManager.createAdapterPopulatedRecordArray(typeClass, query); var adapter = this.adapterFor(modelName); (0, _emberDataPrivateDebug.assert)("You tried to load a query but you have no adapter (for " + typeClass + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to load a query but your adapter does not implement `query`", typeof adapter.query === 'function'); return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._query)(adapter, this, typeClass, query, array)); }, /** This method makes a request for one record, where the `id` is not known beforehand (if the `id` is known, use `findRecord` instead). This method can be used when it is certain that the server will return a single object for the primary data. Let's assume our API provides an endpoint for the currently logged in user via: ``` // GET /api/current_user { user: { id: 1234, username: 'admin' } } ``` Since the specific `id` of the `user` is not known beforehand, we can use `queryRecord` to get the user: ```javascript store.queryRecord('user', {}).then(function(user) { let username = user.get('username'); console.log(`Currently logged in as ${username}`); }); ``` The request is made through the adapters' `queryRecord`: ```javascript // app/adapters/user.js import DS from "ember-data"; export default DS.Adapter.extend({ queryRecord(modelName, query) { return Ember.$.getJSON("/api/current_user"); } }); ``` Note: the primary use case for `store.queryRecord` is when a single record is queried and the `id` is not known beforehand. In all other cases `store.query` and using the first item of the array is likely the preferred way: ``` // GET /users?username=unique { data: [{ id: 1234, type: 'user', attributes: { username: "unique" } }] } ``` ```javascript store.query('user', { username: 'unique' }).then(function(users) { return users.get('firstObject'); }).then(function(user) { let id = user.get('id'); }); ``` This method returns a promise, which resolves with the found record. If the adapter returns no data for the primary data of the payload, then `queryRecord` resolves with `null`: ``` // GET /users?username=unique { data: null } ``` ```javascript store.queryRecord('user', { username: 'unique' }).then(function(user) { console.log(user); // null }); ``` @since 1.13.0 @method queryRecord @param {String} modelName @param {any} query an opaque query to be used by the adapter @return {Promise} promise which resolves with the found record or `null` */ queryRecord: function queryRecord(modelName, query) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's queryRecord method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)("You need to pass a query hash to the store's queryRecord method", query); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); var adapter = this.adapterFor(modelName); (0, _emberDataPrivateDebug.assert)("You tried to make a query but you have no adapter (for " + typeClass + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to make a query but your adapter does not implement `queryRecord`", typeof adapter.queryRecord === 'function'); return (0, _emberDataPrivateSystemPromiseProxies.promiseObject)((0, _emberDataPrivateSystemStoreFinders._queryRecord)(adapter, this, typeClass, query)); }, /** `findAll` asks the adapter's `findAll` method to find the records for the given type, and returns a promise which will resolve with all records of this type present in the store, even if the adapter only returns a subset of them. ```app/routes/authors.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findAll('author'); } }); ``` _When_ the returned promise resolves depends on the reload behavior, configured via the passed `options` hash and the result of the adapter's `shouldReloadAll` method. ### Reloading If `{ reload: true }` is passed or `adapter.shouldReloadAll` evaluates to `true`, then the returned promise resolves once the adapter returns data, regardless if there are already records in the store: ```js store.push({ data: { id: 'first', type: 'author' } }); // adapter#findAll resolves with // [ // { // id: 'second', // type: 'author' // } // ] store.findAll('author', { reload: true }).then(function(authors) { authors.getEach("id"); // ['first', 'second'] }); ``` If no reload is indicated via the abovementioned ways, then the promise immediately resolves with all the records currently loaded in the store. ### Background Reloading Optionally, if `adapter.shouldBackgroundReloadAll` evaluates to `true`, then a background reload is started. Once this resolves, the array with which the promise resolves, is updated automatically so it contains all the records in the store: ```js // app/adapters/application.js export default DS.Adapter.extend({ shouldReloadAll(store, snapshotsArray) { return false; }, shouldBackgroundReloadAll(store, snapshotsArray) { return true; } }); // ... store.push({ data: { id: 'first', type: 'author' } }); var allAuthors; store.findAll('author').then(function(authors) { authors.getEach('id'); // ['first'] allAuthors = authors; }); // later, once adapter#findAll resolved with // [ // { // id: 'second', // type: 'author' // } // ] allAuthors.getEach('id'); // ['first', 'second'] ``` If you would like to force or prevent background reloading, you can set a boolean value for `backgroundReload` in the options object for `findAll`. ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return this.store.findAll('post', { backgroundReload: false }); } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the `snapshotRecordArray` ```app/routes/posts.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findAll('post', { adapterOptions: { subscribe: false } }); } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ findAll: function(store, type, sinceToken, snapshotRecordArray) { if (snapshotRecordArray.adapterOptions.subscribe) { // ... } // ... } }); ``` See [peekAll](#method_peekAll) to get an array of current records in the store, without waiting until a reload is finished. See [query](#method_query) to only get a subset of records from the server. @since 1.13.0 @method findAll @param {String} modelName @param {Object} options @return {Promise} promise */ findAll: function findAll(modelName, options) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's findAll method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); return this._fetchAll(typeClass, this.peekAll(modelName), options); }, /** @method _fetchAll @private @param {DS.Model} typeClass @param {DS.RecordArray} array @return {Promise} promise */ _fetchAll: function _fetchAll(typeClass, array, options) { options = options || {}; var adapter = this.adapterFor(typeClass.modelName); var sinceToken = this.typeMapFor(typeClass).metadata.since; (0, _emberDataPrivateDebug.assert)("You tried to load all records but you have no adapter (for " + typeClass + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to load all records but your adapter does not implement `findAll`", typeof adapter.findAll === 'function'); set(array, 'isUpdating', true); if (options.reload) { return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, typeClass, sinceToken, options)); } var snapshotArray = array.createSnapshot(options); if (adapter.shouldReloadAll(this, snapshotArray)) { return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, typeClass, sinceToken, options)); } if (options.backgroundReload === false) { return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(Promise.resolve(array)); } if (options.backgroundReload || adapter.shouldBackgroundReloadAll(this, snapshotArray)) { (0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, typeClass, sinceToken, options); } return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(Promise.resolve(array)); }, /** @method didUpdateAll @param {DS.Model} typeClass @private */ didUpdateAll: function didUpdateAll(typeClass) { var liveRecordArray = this.recordArrayManager.liveRecordArrayFor(typeClass); set(liveRecordArray, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type in the store. Note that because it's just a filter, the result will contain any locally created records of the type, however, it will not make a request to the backend to retrieve additional records. If you would like to request all the records from the backend please use [store.findAll](#method_findAll). Also note that multiple calls to `peekAll` for a given type will always return the same `RecordArray`. Example ```javascript var localPosts = store.peekAll('post'); ``` @since 1.13.0 @method peekAll @param {String} modelName @return {DS.RecordArray} */ peekAll: function peekAll(modelName) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's peekAll method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); var liveRecordArray = this.recordArrayManager.liveRecordArrayFor(typeClass); this.recordArrayManager.populateLiveRecordArray(liveRecordArray, typeClass); return liveRecordArray; }, /** This method unloads all records in the store. Optionally you can pass a type which unload all records for a given type. ```javascript store.unloadAll(); store.unloadAll('post'); ``` @method unloadAll @param {String=} modelName */ unloadAll: function unloadAll(modelName) { (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), !modelName || typeof modelName === 'string'); if (arguments.length === 0) { var typeMaps = this.typeMaps; var keys = Object.keys(typeMaps); var types = new Array(keys.length); for (var i = 0; i < keys.length; i++) { types[i] = typeMaps[keys[i]]['type'].modelName; } types.forEach(this.unloadAll, this); } else { var typeClass = this.modelFor(modelName); var typeMap = this.typeMapFor(typeClass); var records = typeMap.records.slice(); var record = undefined; for (var i = 0; i < records.length; i++) { record = records[i]; record.unloadRecord(); record.destroy(); // maybe within unloadRecord } typeMap.metadata = new _emberDataPrivateSystemEmptyObject['default'](); } }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The filter function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. Example ```javascript store.filter('post', function(post) { return post.get('unread'); }); ``` The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Optionally you can pass a query, which is the equivalent of calling [query](#method_query) with that same query, to fetch additional records from the server. The results returned by the server could then appear in the filter if they match the filter function. The query itself is not used to filter records, it's only sent to your server for you to be able to do server-side filtering. The filter function will be applied on the returned results regardless. Example ```javascript store.filter('post', { unread: true }, function(post) { return post.get('unread'); }).then(function(unreadPosts) { unreadPosts.get('length'); // 5 var unreadPost = unreadPosts.objectAt(0); unreadPost.set('unread', false); unreadPosts.get('length'); // 4 }); ``` @method filter @private @param {String} modelName @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} @deprecated */ filter: function filter(modelName, query, _filter) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's filter method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); if (!_ember['default'].ENV.ENABLE_DS_FILTER) { (0, _emberDataPrivateDebug.assert)('The filter API has been moved to a plugin. To enable store.filter using an environment flag, or to use an alternative, you can visit the ember-data-filter addon page. https://github.com/ember-data/ember-data-filter', false); } var promise; var length = arguments.length; var array; var hasQuery = length === 3; // allow an optional server query if (hasQuery) { promise = this.query(modelName, query); } else if (arguments.length === 2) { _filter = query; } modelName = this.modelFor(modelName); if (hasQuery) { array = this.recordArrayManager.createFilteredRecordArray(modelName, _filter, query); } else { array = this.recordArrayManager.createFilteredRecordArray(modelName, _filter); } promise = promise || Promise.resolve(array); return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(promise.then(function () { return array; }, null, 'DS: Store#filter of ' + modelName)); }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a findRecord() will result in a request or that it will be a cache hit. Example ```javascript store.recordIsLoaded('post', 1); // false store.findRecord('post', 1).then(function() { store.recordIsLoaded('post', 1); // true }); ``` @method recordIsLoaded @param {String} modelName @param {string} id @return {boolean} */ recordIsLoaded: function recordIsLoaded(modelName, id) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's recordIsLoaded method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); return this.hasRecordForId(modelName, id); }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @method dataWasUpdated @private @param {Class} type @param {InternalModel} internalModel */ dataWasUpdated: function dataWasUpdated(type, internalModel) { this.recordArrayManager.recordDidChange(internalModel); }, // .............. // . PERSISTING . // .............. /** This method is called by `record.save`, and gets passed a resolver for the promise that `record.save` returns. It schedules saving to happen at the end of the run loop. @method scheduleSave @private @param {InternalModel} internalModel @param {Resolver} resolver @param {Object} options */ scheduleSave: function scheduleSave(internalModel, resolver, options) { var snapshot = internalModel.createSnapshot(options); internalModel.flushChangedAttributes(); internalModel.adapterWillCommit(); this._pendingSave.push({ snapshot: snapshot, resolver: resolver }); once(this, 'flushPendingSave'); }, /** This method is called at the end of the run loop, and flushes any records passed into `scheduleSave` @method flushPendingSave @private */ flushPendingSave: function flushPendingSave() { var _this = this; var pending = this._pendingSave.slice(); this._pendingSave = []; pending.forEach(function (pendingItem) { var snapshot = pendingItem.snapshot; var resolver = pendingItem.resolver; var record = snapshot._internalModel; var adapter = _this.adapterFor(record.type.modelName); var operation; if (get(record, 'currentState.stateName') === 'root.deleted.saved') { return resolver.resolve(); } else if (record.isNew()) { operation = 'createRecord'; } else if (record.isDeleted()) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } resolver.resolve(_commit(adapter, _this, operation, snapshot)); }); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is resolved. If the data provides a server-generated ID, it will update the record and the store's indexes. @method didSaveRecord @private @param {InternalModel} internalModel the in-flight internal model @param {Object} data optional data (see above) */ didSaveRecord: function didSaveRecord(internalModel, dataArg) { var data; if (dataArg) { data = dataArg.data; } if (data) { // normalize relationship IDs into records this._backburner.schedule('normalizeRelationships', this, '_setupRelationships', internalModel, data); this.updateId(internalModel, data); } //We first make sure the primary data has been updated //TODO try to move notification to the user to the end of the runloop internalModel.adapterDidCommit(data); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected with a `DS.InvalidError`. @method recordWasInvalid @private @param {InternalModel} internalModel @param {Object} errors */ recordWasInvalid: function recordWasInvalid(internalModel, errors) { internalModel.adapterDidInvalidate(errors); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected (with anything other than a `DS.InvalidError`). @method recordWasError @private @param {InternalModel} internalModel @param {Error} error */ recordWasError: function recordWasError(internalModel, error) { internalModel.adapterDidError(error); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {InternalModel} internalModel @param {Object} data */ updateId: function updateId(internalModel, data) { var oldId = internalModel.id; var id = (0, _emberDataPrivateSystemCoerceId['default'])(data.id); (0, _emberDataPrivateDebug.assert)("An adapter cannot assign a new id to a record that already has an id. " + internalModel + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId); this.typeMapFor(internalModel.type).idToRecord[id] = internalModel; internalModel.setId(id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param {DS.Model} typeClass @return {Object} typeMap */ typeMapFor: function typeMapFor(typeClass) { var typeMaps = get(this, 'typeMaps'); var guid = _ember['default'].guidFor(typeClass); var typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: new _emberDataPrivateSystemEmptyObject['default'](), records: [], metadata: new _emberDataPrivateSystemEmptyObject['default'](), type: typeClass }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {(String|DS.Model)} type @param {Object} data */ _load: function _load(data) { var internalModel = this._internalModelForId(data.type, data.id); internalModel.setupData(data); this.recordArrayManager.recordDidChange(internalModel); return internalModel; }, /* In case someone defined a relationship to a mixin, for example: ``` var Comment = DS.Model.extend({ owner: belongsTo('commentable'. { polymorphic: true}) }); var Commentable = Ember.Mixin.create({ comments: hasMany('comment') }); ``` we want to look up a Commentable class which has all the necessary relationship metadata. Thus, we look up the mixin and create a mock DS.Model, so we can access the relationship CPs of the mixin (`comments`) in this case */ _modelForMixin: function _modelForMixin(modelName) { var normalizedModelName = (0, _emberDataPrivateSystemNormalizeModelName['default'])(modelName); // container.registry = 2.1 // container._registry = 1.11 - 2.0 // container = < 1.11 var owner = (0, _emberDataPrivateUtils.getOwner)(this); var mixin = owner._lookupFactory('mixin:' + normalizedModelName); if (mixin) { //Cache the class as a model owner.register('model:' + normalizedModelName, _emberDataModel['default'].extend(mixin)); } var factory = this.modelFactoryFor(normalizedModelName); if (factory) { factory.__isMixin = true; factory.__mixin = mixin; } return factory; }, /** Returns a model class for a particular key. Used by methods that take a type key (like `find`, `createRecord`, etc.) @method modelFor @param {String} modelName @return {DS.Model} */ modelFor: function modelFor(modelName) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's modelFor method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); var factory = this.modelFactoryFor(modelName); if (!factory) { //Support looking up mixins as base types for polymorphic relationships factory = this._modelForMixin(modelName); } if (!factory) { throw new _ember['default'].Error("No model was found for '" + modelName + "'"); } factory.modelName = factory.modelName || (0, _emberDataPrivateSystemNormalizeModelName['default'])(modelName); return factory; }, modelFactoryFor: function modelFactoryFor(modelName) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's modelFactoryFor method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); var normalizedKey = (0, _emberDataPrivateSystemNormalizeModelName['default'])(modelName); var owner = (0, _emberDataPrivateUtils.getOwner)(this); return owner._lookupFactory('model:' + normalizedKey); }, /** Push some data for a given type into the store. This method expects normalized [JSON API](http://jsonapi.org/) document. This means you have to follow [JSON API specification](http://jsonapi.org/format/) with few minor adjustments: - record's `type` should always be in singular, dasherized form - members (properties) should be camelCased [Your primary data should be wrapped inside `data` property](http://jsonapi.org/format/#document-top-level): ```js store.push({ data: { // primary data for single record of type `Person` id: '1', type: 'person', attributes: { firstName: 'Daniel', lastName: 'Kmak' } } }); ``` [Demo.](http://ember-twiddle.com/fb99f18cd3b4d3e2a4c7) `data` property can also hold an array (of records): ```js store.push({ data: [ // an array of records { id: '1', type: 'person', attributes: { firstName: 'Daniel', lastName: 'Kmak' } }, { id: '2', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' } } ] }); ``` [Demo.](http://ember-twiddle.com/69cdbeaa3702159dc355) There are some typical properties for `JSONAPI` payload: * `id` - mandatory, unique record's key * `type` - mandatory string which matches `model`'s dasherized name in singular form * `attributes` - object which holds data for record attributes - `DS.attr`'s declared in model * `relationships` - object which must contain any of the following properties under each relationships' respective key (example path is `relationships.achievements.data`): - [`links`](http://jsonapi.org/format/#document-links) - [`data`](http://jsonapi.org/format/#document-resource-object-linkage) - place for primary data - [`meta`](http://jsonapi.org/format/#document-meta) - object which contains meta-information about relationship For this model: ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { data: { id: '1', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' }, relationships: { children: { data: [ { id: '2', type: 'person' }, { id: '3', type: 'person' }, { id: '4', type: 'person' } ] } } } } ``` [Demo.](http://ember-twiddle.com/343e1735e034091f5bde) To represent the children relationship as a URL: ```js { data: { id: '1', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' }, relationships: { children: { links: { related: '/people/1/children' } } } } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. The store's [normalize](#method_normalize) method is a convenience helper for converting a json payload into the form Ember Data expects. ```js store.push(store.normalize('person', data)); ``` This method can be used both to push in brand new records, as well as to update existing records. @method push @param {Object} data @return {DS.Model|Array} the record(s) that was created or updated. */ push: function push(data) { var included = data.included; var i, length; if (included) { for (i = 0, length = included.length; i < length; i++) { this._pushInternalModel(included[i]); } } if (Array.isArray(data.data)) { length = data.data.length; var internalModels = new Array(length); for (i = 0; i < length; i++) { internalModels[i] = this._pushInternalModel(data.data[i]).getRecord(); } return internalModels; } if (data.data === null) { return null; } (0, _emberDataPrivateDebug.assert)('Expected an object in the \'data\' property in a call to \'push\' for ' + data.type + ', but was ' + _ember['default'].typeOf(data.data), _ember['default'].typeOf(data.data) === 'object'); var internalModel = this._pushInternalModel(data.data); return internalModel.getRecord(); }, _hasModelFor: function _hasModelFor(type) { return !!(0, _emberDataPrivateUtils.getOwner)(this)._lookupFactory('model:' + type); }, _pushInternalModel: function _pushInternalModel(data) { var _this2 = this; var modelName = data.type; (0, _emberDataPrivateDebug.assert)('You must include an \'id\' for ' + modelName + ' in an object passed to \'push\'', data.id !== null && data.id !== undefined && data.id !== ''); (0, _emberDataPrivateDebug.assert)('You tried to push data with a type \'' + modelName + '\' but no model could be found with that name.', this._hasModelFor(modelName)); (0, _emberDataPrivateDebug.runInDebug)(function () { // If Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload // contains unknown attributes or relationships, log a warning. if (_ember['default'].ENV.DS_WARN_ON_UNKNOWN_KEYS) { (function () { var type = _this2.modelFor(modelName); // Check unknown attributes var unknownAttributes = Object.keys(data.attributes || {}).filter(function (key) { return !get(type, 'fields').has(key); }); var unknownAttributesMessage = 'The payload for \'' + type.modelName + '\' contains these unknown attributes: ' + unknownAttributes + '. Make sure they\'ve been defined in your model.'; (0, _emberDataPrivateDebug.warn)(unknownAttributesMessage, unknownAttributes.length === 0, { id: 'ds.store.unknown-keys-in-payload' }); // Check unknown relationships var unknownRelationships = Object.keys(data.relationships || {}).filter(function (key) { return !get(type, 'fields').has(key); }); var unknownRelationshipsMessage = 'The payload for \'' + type.modelName + '\' contains these unknown relationships: ' + unknownRelationships + '. Make sure they\'ve been defined in your model.'; (0, _emberDataPrivateDebug.warn)(unknownRelationshipsMessage, unknownRelationships.length === 0, { id: 'ds.store.unknown-keys-in-payload' }); })(); } }); // Actually load the record into the store. var internalModel = this._load(data); this._backburner.join(function () { _this2._backburner.schedule('normalizeRelationships', _this2, '_setupRelationships', internalModel, data); }); return internalModel; }, _setupRelationships: function _setupRelationships(record, data) { // This will convert relationships specified as IDs into DS.Model instances // (possibly unloaded) and also create the data structures used to track // relationships. setupRelationships(this, record, data); }, /** Push some raw data into the store. This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer. ```app/serializers/application.js import DS from 'ember-data'; export default DS.ActiveModelSerializer; ``` ```js var pushData = { posts: [ { id: 1, post_title: "Great post", comment_ids: [2] } ], comments: [ { id: 2, comment_body: "Insightful comment" } ] } store.pushPayload(pushData); ``` By default, the data will be deserialized using a default serializer (the application serializer if it exists). Alternatively, `pushPayload` will accept a model type which will determine which serializer will process the payload. ```app/serializers/application.js import DS from 'ember-data'; export default DS.ActiveModelSerializer; ``` ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer; ``` ```js store.pushPayload('comment', pushData); // Will use the application serializer store.pushPayload('post', pushData); // Will use the post serializer ``` @method pushPayload @param {String} modelName Optionally, a model type used to determine which serializer will be used @param {Object} inputPayload */ pushPayload: function pushPayload(modelName, inputPayload) { var _this3 = this; var serializer; var payload; if (!inputPayload) { payload = modelName; serializer = defaultSerializer(this); (0, _emberDataPrivateDebug.assert)("You cannot use `store#pushPayload` without a modelName unless your default serializer defines `pushPayload`", typeof serializer.pushPayload === 'function'); } else { payload = inputPayload; (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); serializer = this.serializerFor(modelName); } if (false) { return this._adapterRun(function () { return serializer.pushPayload(_this3, payload); }); } else { this._adapterRun(function () { return serializer.pushPayload(_this3, payload); }); } }, /** `normalize` converts a json payload into the normalized form that [push](#method_push) expects. Example ```js socket.on('message', function(message) { var modelName = message.model; var data = message.data; store.push(store.normalize(modelName, data)); }); ``` @method normalize @param {String} modelName The name of the model type for this payload @param {Object} payload @return {Object} The normalized payload */ normalize: function normalize(modelName, payload) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's normalize method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); var serializer = this.serializerFor(modelName); var model = this.modelFor(modelName); return serializer.normalize(model, payload); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {DS.Model} type @param {String} id @param {Object} data @return {InternalModel} internal model */ buildInternalModel: function buildInternalModel(type, id, data) { var typeMap = this.typeMapFor(type); var idToRecord = typeMap.idToRecord; (0, _emberDataPrivateDebug.assert)('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]); (0, _emberDataPrivateDebug.assert)('\'' + _ember['default'].inspect(type) + '\' does not appear to be an ember-data model', typeof type._create === 'function'); // lookupFactory should really return an object that creates // instances with the injections applied var internalModel = new _emberDataPrivateSystemModelInternalModel['default'](type, id, this, null, data); // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = internalModel; } typeMap.records.push(internalModel); return internalModel; }, //Called by the state machine to notify the store that the record is ready to be interacted with recordWasLoaded: function recordWasLoaded(record) { this.recordArrayManager.recordWasLoaded(record); }, // ............... // . DESTRUCTION . // ............... /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method _dematerializeRecord @private @param {InternalModel} internalModel */ _dematerializeRecord: function _dematerializeRecord(internalModel) { var type = internalModel.type; var typeMap = this.typeMapFor(type); var id = internalModel.id; internalModel.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = typeMap.records.indexOf(internalModel); typeMap.records.splice(loc, 1); }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns an instance of the adapter for a given type. For example, `adapterFor('person')` will return an instance of `App.PersonAdapter`. If no `App.PersonAdapter` is found, this method will look for an `App.ApplicationAdapter` (the default adapter for your entire application). If no `App.ApplicationAdapter` is found, it will return the value of the `defaultAdapter`. @method adapterFor @public @param {String} modelName @return DS.Adapter */ adapterFor: function adapterFor(modelName) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's adapterFor method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store.adapterFor has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); return this.lookupAdapter(modelName); }, _adapterRun: function _adapterRun(fn) { return this._backburner.run(fn); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. /** Returns an instance of the serializer for a given type. For example, `serializerFor('person')` will return an instance of `App.PersonSerializer`. If no `App.PersonSerializer` is found, this method will look for an `App.ApplicationSerializer` (the default serializer for your entire application). if no `App.ApplicationSerializer` is found, it will attempt to get the `defaultSerializer` from the `PersonAdapter` (`adapterFor('person')`). If a serializer cannot be found on the adapter, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @public @param {String} modelName the record to serialize @return {DS.Serializer} */ serializerFor: function serializerFor(modelName) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's serializerFor method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store.serializerFor has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); var fallbacks = ['application', this.adapterFor(modelName).get('defaultSerializer'), '-default']; var serializer = this.lookupSerializer(modelName, fallbacks); return serializer; }, /** Retrieve a particular instance from the container cache. If not found, creates it and placing it in the cache. Enabled a store to manage local instances of adapters and serializers. @method retrieveManagedInstance @private @param {String} modelName the object modelName @param {String} name the object name @param {Array} fallbacks the fallback objects to lookup if the lookup for modelName or 'application' fails @return {Ember.Object} */ retrieveManagedInstance: function retrieveManagedInstance(type, modelName, fallbacks) { var normalizedModelName = (0, _emberDataPrivateSystemNormalizeModelName['default'])(modelName); var instance = this._instanceCache.get(type, normalizedModelName, fallbacks); set(instance, 'store', this); return instance; }, lookupAdapter: function lookupAdapter(name) { return this.retrieveManagedInstance('adapter', name, this.get('_adapterFallbacks')); }, _adapterFallbacks: _ember['default'].computed('adapter', function () { var adapter = this.get('adapter'); return ['application', adapter, '-json-api']; }), lookupSerializer: function lookupSerializer(name, fallbacks) { return this.retrieveManagedInstance('serializer', name, fallbacks); }, willDestroy: function willDestroy() { this._super.apply(this, arguments); this.recordArrayManager.destroy(); this.unloadAll(); } }); function deserializeRecordId(store, key, relationship, id) { if (isNone(id)) { return; } (0, _emberDataPrivateDebug.assert)('A ' + relationship.parentType + ' record was pushed into the store with the value of ' + key + ' being ' + _ember['default'].inspect(id) + ', but ' + key + ' is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.', !Array.isArray(id)); //TODO:Better asserts return store._internalModelForId(id.type, id.id); } function deserializeRecordIds(store, key, relationship, ids) { if (isNone(ids)) { return; } (0, _emberDataPrivateDebug.assert)('A ' + relationship.parentType + ' record was pushed into the store with the value of ' + key + ' being \'' + _ember['default'].inspect(ids) + '\', but ' + key + ' is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.', Array.isArray(ids)); var _ids = new Array(ids.length); for (var i = 0; i < ids.length; i++) { _ids[i] = deserializeRecordId(store, key, relationship, ids[i]); } return _ids; } // Delegation to the adapter and promise management function defaultSerializer(store) { return store.serializerFor('application'); } function _commit(adapter, store, operation, snapshot) { var internalModel = snapshot._internalModel; var modelName = snapshot.modelName; var typeClass = store.modelFor(modelName); var promise = adapter[operation](store, typeClass, snapshot); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); var label = 'DS: Extract and notify about ' + operation + ' completion of ' + internalModel; (0, _emberDataPrivateDebug.assert)('Your adapter\'s \'' + operation + '\' method must return a value, but it returned \'undefined\'', promise !== undefined); promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { store._adapterRun(function () { var payload, data; if (adapterPayload) { payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, snapshot.id, operation); if (payload.included) { store.push({ data: payload.included }); } data = payload.data; } store.didSaveRecord(internalModel, { data: data }); }); return internalModel; }, function (error) { if (error instanceof _emberDataAdaptersErrors.InvalidError) { var errors = serializer.extractErrors(store, typeClass, error, snapshot.id); store.recordWasInvalid(internalModel, errors); } else { store.recordWasError(internalModel, error); } throw error; }, label); } function setupRelationships(store, record, data) { if (!data.relationships) { return; } record.type.eachRelationship(function (key, descriptor) { var kind = descriptor.kind; if (!data.relationships[key]) { return; } var relationship; if (data.relationships[key].links && data.relationships[key].links.related) { var relatedLink = (0, _emberDataPrivateSystemNormalizeLink['default'])(data.relationships[key].links.related); if (relatedLink && relatedLink.href) { relationship = record._relationships.get(key); relationship.updateLink(relatedLink.href); } } if (data.relationships[key].meta) { relationship = record._relationships.get(key); relationship.updateMeta(data.relationships[key].meta); } // If the data contains a relationship that is specified as an ID (or IDs), // normalizeRelationship will convert them into DS.Model instances // (possibly unloaded) before we push the payload into the store. normalizeRelationship(store, key, descriptor, data.relationships[key]); var value = data.relationships[key].data; if (value !== undefined) { if (kind === 'belongsTo') { relationship = record._relationships.get(key); relationship.setCanonicalRecord(value); } else if (kind === 'hasMany') { relationship = record._relationships.get(key); relationship.updateRecordsFromAdapter(value); } } }); } function normalizeRelationship(store, key, relationship, jsonPayload) { var data = jsonPayload.data; if (data) { var kind = relationship.kind; if (kind === 'belongsTo') { jsonPayload.data = deserializeRecordId(store, key, relationship, data); } else if (kind === 'hasMany') { jsonPayload.data = deserializeRecordIds(store, key, relationship, data); } } } exports.Store = Store; exports['default'] = Store; }); define('ember-data/-private/system/store/common', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports._bind = _bind; exports._guard = _guard; exports._objectIsAlive = _objectIsAlive; var get = _ember['default'].get; function _bind(fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { return fn.apply(undefined, args); }; } function _guard(promise, test) { var guarded = promise['finally'](function () { if (!test()) { guarded._subscribers.length = 0; } }); return guarded; } function _objectIsAlive(object) { return !(get(object, "isDestroyed") || get(object, "isDestroying")); } }); define('ember-data/-private/system/store/container-instance-cache', ['exports', 'ember', 'ember-data/-private/system/empty-object'], function (exports, _ember, _emberDataPrivateSystemEmptyObject) { 'use strict'; exports['default'] = ContainerInstanceCache; var assign = _ember['default'].assign || _ember['default'].merge; /** * The `ContainerInstanceCache` serves as a lazy cache for looking up * instances of serializers and adapters. It has some additional logic for * finding the 'fallback' adapter or serializer. * * The 'fallback' adapter or serializer is an adapter or serializer that is looked up * when the preferred lookup fails. For example, say you try to look up `adapter:post`, * but there is no entry (app/adapters/post.js in EmberCLI) for `adapter:post` in the registry. * * The `fallbacks` array passed will then be used; the first entry in the fallbacks array * that exists in the container will then be cached for `adapter:post`. So, the next time you * look up `adapter:post`, you'll get the `adapter:application` instance (or whatever the fallback * was if `adapter:application` doesn't exist). * * @private * @class ContainerInstanceCache * */ function ContainerInstanceCache(owner) { this._owner = owner; this._cache = new _emberDataPrivateSystemEmptyObject['default'](); } ContainerInstanceCache.prototype = new _emberDataPrivateSystemEmptyObject['default'](); assign(ContainerInstanceCache.prototype, { get: function get(type, preferredKey, fallbacks) { var cache = this._cache; var preferredLookupKey = type + ':' + preferredKey; if (!(preferredLookupKey in cache)) { var instance = this.instanceFor(preferredLookupKey) || this._findInstance(type, fallbacks); if (instance) { cache[preferredLookupKey] = instance; } } return cache[preferredLookupKey]; }, _findInstance: function _findInstance(type, fallbacks) { for (var i = 0, _length = fallbacks.length; i < _length; i++) { var fallback = fallbacks[i]; var lookupKey = type + ':' + fallback; var instance = this.instanceFor(lookupKey); if (instance) { return instance; } } }, instanceFor: function instanceFor(key) { var cache = this._cache; if (!cache[key]) { var instance = this._owner.lookup(key); if (instance) { cache[key] = instance; } } return cache[key]; }, destroy: function destroy() { var cache = this._cache; var cacheEntries = Object.keys(cache); for (var i = 0, _length2 = cacheEntries.length; i < _length2; i++) { var cacheKey = cacheEntries[i]; var cacheEntry = cache[cacheKey]; if (cacheEntry) { cacheEntry.destroy(); } } this._owner = null; }, constructor: ContainerInstanceCache, toString: function toString() { return 'ContainerInstanceCache'; } }); }); define("ember-data/-private/system/store/finders", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/store/common", "ember-data/-private/system/store/serializer-response", "ember-data/-private/system/store/serializers"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemStoreCommon, _emberDataPrivateSystemStoreSerializerResponse, _emberDataPrivateSystemStoreSerializers) { "use strict"; exports._find = _find; exports._findMany = _findMany; exports._findHasMany = _findHasMany; exports._findBelongsTo = _findBelongsTo; exports._findAll = _findAll; exports._query = _query; exports._queryRecord = _queryRecord; var Promise = _ember["default"].RSVP.Promise; function payloadIsNotBlank(adapterPayload) { if (Array.isArray(adapterPayload)) { return true; } else { return Object.keys(adapterPayload || {}).length; } } function _find(adapter, store, typeClass, id, internalModel, options) { var snapshot = internalModel.createSnapshot(options); var promise = adapter.findRecord(store, typeClass, id, snapshot); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, internalModel.type.modelName); var label = "DS: Handle Adapter#findRecord of " + typeClass + " with id: " + id; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { (0, _emberDataPrivateDebug.assert)("You made a `findRecord` request for a " + typeClass.modelName + " with id " + id + ", but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); return store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, id, 'findRecord'); (0, _emberDataPrivateDebug.assert)('Ember Data expected the primary data returned from a `findRecord` response to be an object but instead it found an array.', !Array.isArray(payload.data)); //TODO Optimize var record = store.push(payload); return record._internalModel; }); }, function (error) { internalModel.notFound(); if (internalModel.isEmpty()) { internalModel.unloadRecord(); } throw error; }, "DS: Extract payload of '" + typeClass + "'"); } function _findMany(adapter, store, typeClass, ids, internalModels) { var snapshots = _ember["default"].A(internalModels).invoke('createSnapshot'); var promise = adapter.findMany(store, typeClass, ids, snapshots); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, typeClass.modelName); var label = "DS: Handle Adapter#findMany of " + typeClass; if (promise === undefined) { throw new Error('adapter.findMany returned undefined, this was very likely a mistake'); } promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { (0, _emberDataPrivateDebug.assert)("You made a `findMany` request for " + typeClass.modelName + " records with ids " + ids + ", but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); return store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findMany'); //TODO Optimize, no need to materialize here var records = store.push(payload); var internalModels = new Array(records.length); for (var i = 0; i < records.length; i++) { internalModels[i] = records[i]._internalModel; } return internalModels; }); }, null, "DS: Extract payload of " + typeClass); } function _findHasMany(adapter, store, internalModel, link, relationship) { var snapshot = internalModel.createSnapshot(); var typeClass = store.modelFor(relationship.type); var promise = adapter.findHasMany(store, snapshot, link, relationship); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, relationship.type); var label = "DS: Handle Adapter#findHasMany of " + internalModel + " : " + relationship.type; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { (0, _emberDataPrivateDebug.assert)("You made a `findHasMany` request for a " + internalModel.modelName + "'s `" + relationship.key + "` relationship, using link " + link + ", but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); return store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findHasMany'); //TODO Use a non record creating push var records = store.push(payload); var recordArray = records.map(function (record) { return record._internalModel; }); recordArray.meta = payload.meta; return recordArray; }); }, null, "DS: Extract payload of " + internalModel + " : hasMany " + relationship.type); } function _findBelongsTo(adapter, store, internalModel, link, relationship) { var snapshot = internalModel.createSnapshot(); var typeClass = store.modelFor(relationship.type); var promise = adapter.findBelongsTo(store, snapshot, link, relationship); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, relationship.type); var label = "DS: Handle Adapter#findBelongsTo of " + internalModel + " : " + relationship.type; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { return store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findBelongsTo'); if (!payload.data) { return null; } //TODO Optimize var record = store.push(payload); return record._internalModel; }); }, null, "DS: Extract payload of " + internalModel + " : " + relationship.type); } function _findAll(adapter, store, typeClass, sinceToken, options) { var modelName = typeClass.modelName; var recordArray = store.peekAll(modelName); var snapshotArray = recordArray.createSnapshot(options); var promise = adapter.findAll(store, typeClass, sinceToken, snapshotArray); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); var label = "DS: Handle Adapter#findAll of " + typeClass; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { (0, _emberDataPrivateDebug.assert)("You made a `findAll` request for " + typeClass.modelName + " records, but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findAll'); //TODO Optimize store.push(payload); }); store.didUpdateAll(typeClass); return store.peekAll(modelName); }, null, "DS: Extract payload of findAll " + typeClass); } function _query(adapter, store, typeClass, query, recordArray) { var modelName = typeClass.modelName; var promise = adapter.query(store, typeClass, query, recordArray); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); var label = "DS: Handle Adapter#query of " + typeClass; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { var records, payload; store._adapterRun(function () { payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'query'); //TODO Optimize records = store.push(payload); }); (0, _emberDataPrivateDebug.assert)('The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use `store.queryRecord` to query for a single record.', Array.isArray(records)); recordArray.loadRecords(records, payload); return recordArray; }, null, "DS: Extract payload of query " + typeClass); } function _queryRecord(adapter, store, typeClass, query) { var modelName = typeClass.modelName; var promise = adapter.queryRecord(store, typeClass, query); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); var label = "DS: Handle Adapter#queryRecord of " + typeClass; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { var record; store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'queryRecord'); (0, _emberDataPrivateDebug.assert)("Expected the primary data returned by the serializer for a `queryRecord` response to be a single object or null but instead it was an array.", !Array.isArray(payload.data), { id: 'ds.store.queryRecord-array-response' }); //TODO Optimize record = store.push(payload); }); return record; }, null, "DS: Extract payload of queryRecord " + typeClass); } }); define('ember-data/-private/system/store/serializer-response', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { 'use strict'; exports.validateDocumentStructure = validateDocumentStructure; exports.normalizeResponseHelper = normalizeResponseHelper; /* This is a helper method that validates a JSON API top-level document The format of a document is described here: http://jsonapi.org/format/#document-top-level @method validateDocumentStructure @param {Object} doc JSON API document @return {array} An array of errors found in the document structure */ function validateDocumentStructure(doc) { var errors = []; if (!doc || typeof doc !== 'object') { errors.push('Top level of a JSON API document must be an object'); } else { if (!('data' in doc) && !('errors' in doc) && !('meta' in doc)) { errors.push('One or more of the following keys must be present: "data", "errors", "meta".'); } else { if ('data' in doc && 'errors' in doc) { errors.push('Top level keys "errors" and "data" cannot both be present in a JSON API document'); } } if ('data' in doc) { if (!(doc.data === null || Array.isArray(doc.data) || typeof doc.data === 'object')) { errors.push('data must be null, an object, or an array'); } } if ('meta' in doc) { if (typeof doc.meta !== 'object') { errors.push('meta must be an object'); } } if ('errors' in doc) { if (!Array.isArray(doc.errors)) { errors.push('errors must be an array'); } } if ('links' in doc) { if (typeof doc.links !== 'object') { errors.push('links must be an object'); } } if ('jsonapi' in doc) { if (typeof doc.jsonapi !== 'object') { errors.push('jsonapi must be an object'); } } if ('included' in doc) { if (typeof doc.included !== 'object') { errors.push('included must be an array'); } } } return errors; } /* This is a helper method that always returns a JSON-API Document. @method normalizeResponseHelper @param {DS.Serializer} serializer @param {DS.Store} store @param {subclass of DS.Model} modelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ function normalizeResponseHelper(serializer, store, modelClass, payload, id, requestType) { var normalizedResponse = serializer.normalizeResponse(store, modelClass, payload, id, requestType); var validationErrors = []; (0, _emberDataPrivateDebug.runInDebug)(function () { validationErrors = validateDocumentStructure(normalizedResponse); }); (0, _emberDataPrivateDebug.assert)('normalizeResponse must return a valid JSON API document:\n\t* ' + validationErrors.join('\n\t* '), _ember['default'].isEmpty(validationErrors)); return normalizedResponse; } }); define("ember-data/-private/system/store/serializers", ["exports"], function (exports) { "use strict"; exports.serializerForAdapter = serializerForAdapter; function serializerForAdapter(store, adapter, type) { var serializer = adapter.serializer; if (serializer === undefined) { serializer = store.serializerFor(type); } if (serializer === null || serializer === undefined) { serializer = { extract: function extract(store, type, payload) { return payload; } }; } return serializer; } }); define("ember-data/-private/transforms", ["exports", "ember-data/transform", "ember-data/-private/transforms/number", "ember-data/-private/transforms/date", "ember-data/-private/transforms/string", "ember-data/-private/transforms/boolean"], function (exports, _emberDataTransform, _emberDataPrivateTransformsNumber, _emberDataPrivateTransformsDate, _emberDataPrivateTransformsString, _emberDataPrivateTransformsBoolean) { "use strict"; exports.Transform = _emberDataTransform["default"]; exports.NumberTransform = _emberDataPrivateTransformsNumber["default"]; exports.DateTransform = _emberDataPrivateTransformsDate["default"]; exports.StringTransform = _emberDataPrivateTransformsString["default"]; exports.BooleanTransform = _emberDataPrivateTransformsBoolean["default"]; }); define('ember-data/-private/transforms/boolean', ['exports', 'ember', 'ember-data/transform', 'ember-data/-private/features'], function (exports, _ember, _emberDataTransform, _emberDataPrivateFeatures) { 'use strict'; var isNone = _ember['default'].isNone; /** The `DS.BooleanTransform` class is used to serialize and deserialize boolean attributes on Ember Data record objects. This transform is used when `boolean` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ isAdmin: DS.attr('boolean'), name: DS.attr('string'), email: DS.attr('string') }); ``` @class BooleanTransform @extends DS.Transform @namespace DS */ exports['default'] = _emberDataTransform['default'].extend({ deserialize: function deserialize(serialized, options) { var type = typeof serialized; if (true) { if (isNone(serialized) && options.allowNull === true) { return null; } } if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function serialize(deserialized, options) { if (true) { if (isNone(deserialized) && options.allowNull === true) { return null; } } return Boolean(deserialized); } }); }); define("ember-data/-private/transforms/date", ["exports", "ember-data/-private/ext/date", "ember-data/transform"], function (exports, _emberDataPrivateExtDate, _emberDataTransform) { "use strict"; exports["default"] = _emberDataTransform["default"].extend({ deserialize: function deserialize(serialized) { var type = typeof serialized; if (type === "string") { return new Date((0, _emberDataPrivateExtDate.parseDate)(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is null return null // if the value is not present in the data return undefined return serialized; } else { return null; } }, serialize: function serialize(date) { if (date instanceof Date) { return date.toISOString(); } else { return null; } } }); }); /** The `DS.DateTransform` class is used to serialize and deserialize date attributes on Ember Data record objects. This transform is used when `date` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. ```app/models/score.js import DS from 'ember-data'; export default DS.Model.extend({ value: DS.attr('number'), player: DS.belongsTo('player'), date: DS.attr('date') }); ``` @class DateTransform @extends DS.Transform @namespace DS */ define("ember-data/-private/transforms/number", ["exports", "ember", "ember-data/transform"], function (exports, _ember, _emberDataTransform) { "use strict"; var empty = _ember["default"].isEmpty; function isNumber(value) { return value === value && value !== Infinity && value !== -Infinity; } /** The `DS.NumberTransform` class is used to serialize and deserialize numeric attributes on Ember Data record objects. This transform is used when `number` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```app/models/score.js import DS from 'ember-data'; export default DS.Model.extend({ value: DS.attr('number'), player: DS.belongsTo('player'), date: DS.attr('date') }); ``` @class NumberTransform @extends DS.Transform @namespace DS */ exports["default"] = _emberDataTransform["default"].extend({ deserialize: function deserialize(serialized) { var transformed; if (empty(serialized)) { return null; } else { transformed = Number(serialized); return isNumber(transformed) ? transformed : null; } }, serialize: function serialize(deserialized) { var transformed; if (empty(deserialized)) { return null; } else { transformed = Number(deserialized); return isNumber(transformed) ? transformed : null; } } }); }); define("ember-data/-private/transforms/string", ["exports", "ember", "ember-data/transform"], function (exports, _ember, _emberDataTransform) { "use strict"; var none = _ember["default"].isNone; /** The `DS.StringTransform` class is used to serialize and deserialize string attributes on Ember Data record objects. This transform is used when `string` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ isAdmin: DS.attr('boolean'), name: DS.attr('string'), email: DS.attr('string') }); ``` @class StringTransform @extends DS.Transform @namespace DS */ exports["default"] = _emberDataTransform["default"].extend({ deserialize: function deserialize(serialized) { return none(serialized) ? null : String(serialized); }, serialize: function serialize(deserialized) { return none(deserialized) ? null : String(deserialized); } }); }); define('ember-data/-private/utils', ['exports', 'ember'], function (exports, _ember) { 'use strict'; var get = _ember['default'].get; /* Check if the passed model has a `type` attribute or a relationship named `type`. @method modelHasAttributeOrRelationshipNamedType @param modelClass */ function modelHasAttributeOrRelationshipNamedType(modelClass) { return get(modelClass, 'attributes').has('type') || get(modelClass, 'relationshipsByName').has('type'); } /* ember-container-inject-owner is a new feature in Ember 2.3 that finally provides a public API for looking items up. This function serves as a super simple polyfill to avoid triggering deprecations. */ function getOwner(context) { var owner; if (_ember['default'].getOwner) { owner = _ember['default'].getOwner(context); } if (!owner && context.container) { owner = context.container; } if (owner && owner.lookupFactory && !owner._lookupFactory) { // `owner` is a container, we are just making this work owner._lookupFactory = owner.lookupFactory; owner.register = function () { var registry = owner.registry || owner._registry || owner; return registry.register.apply(registry, arguments); }; } return owner; } exports.modelHasAttributeOrRelationshipNamedType = modelHasAttributeOrRelationshipNamedType; exports.getOwner = getOwner; }); define('ember-data/-private/utils/parse-response-headers', ['exports', 'ember-data/-private/system/empty-object'], function (exports, _emberDataPrivateSystemEmptyObject) { 'use strict'; exports['default'] = parseResponseHeaders; function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } var CLRF = '\r\n'; function parseResponseHeaders(headersString) { var headers = new _emberDataPrivateSystemEmptyObject['default'](); if (!headersString) { return headers; } var headerPairs = headersString.split(CLRF); headerPairs.forEach(function (header) { var _header$split = header.split(':'); var _header$split2 = _toArray(_header$split); var field = _header$split2[0]; var value = _header$split2.slice(1); field = field.trim(); value = value.join(':').trim(); if (value) { headers[field] = value; } }); return headers; } }); define('ember-data/adapter', ['exports', 'ember'], function (exports, _ember) { /** @module ember-data */ 'use strict'; var get = _ember['default'].get; /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. Typically the adapter is not invoked directly instead its functionality is accessed through the `store`. ### Creating an Adapter Create a new subclass of `DS.Adapter` in the `app/adapters` folder: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ // ...your code here }); ``` Model-specific adapters can be created by putting your adapter class in an `app/adapters/` + `model-name` + `.js` file of the application. ```app/adapters/post.js import DS from 'ember-data'; export default DS.Adapter.extend({ // ...Post-specific adapter code goes here }); ``` `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `findRecord()` * `createRecord()` * `updateRecord()` * `deleteRecord()` * `findAll()` * `query()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` For an example implementation, see `DS.RESTAdapter`, the included REST adapter. @class Adapter @namespace DS @extends Ember.Object */ exports['default'] = _ember['default'].Object.extend({ /** If you would like your adapter to use a custom serializer you can set the `defaultSerializer` property to be the name of the custom serializer. Note the `defaultSerializer` serializer has a lower priority than a model specific serializer (i.e. `PostSerializer`) or the `application` serializer. ```app/adapters/django.js import DS from 'ember-data'; export default DS.Adapter.extend({ defaultSerializer: 'django' }); ``` @property defaultSerializer @type {String} */ defaultSerializer: '-default', /** The `findRecord()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `findRecord()` being called, you should query your persistence layer for a record with the given ID. The `findRecord` method should return a promise that will resolve to a JavaScript object that will be normalized by the serializer. Here is an example `findRecord` implementation: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ findRecord: function(store, type, id, snapshot) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}/${id}`).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method findRecord @param {DS.Store} store @param {DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ findRecord: null, /** The `findAll()` method is used to retrieve all records for a given type. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ findAll: function(store, type, sinceToken) { var query = { since: sinceToken }; return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method findAll @param {DS.Store} store @param {DS.Model} type @param {String} sinceToken @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Promise} promise */ findAll: null, /** This method is called when you call `query` on the store. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ query: function(store, type, query) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method query @param {DS.Store} store @param {DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ query: null, /** The `queryRecord()` method is invoked when the store is asked for a single record through a query object. In response to `queryRecord()` being called, you should always fetch fresh data. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `queryRecord` implementation: Example ```app/adapters/application.js import DS from 'ember-data'; import Ember from 'ember'; export default DS.Adapter.extend(DS.BuildURLMixin, { queryRecord: function(store, type, query) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method queryRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @return {Promise} promise */ queryRecord: null, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: ```javascript import DS from 'ember-data'; import { v4 } from 'uuid'; export default DS.Adapter.extend({ generateIdForRecord: function(store, inputProperties) { return v4(); } }); ``` @method generateIdForRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {Object} inputProperties a hash of properties to set on the newly created record. @return {(String|Number)} id */ generateIdForRecord: null, /** Proxies to the serializer's `serialize` method. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ createRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var url = `/${type.modelName}`; // ... } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} serialized snapshot */ serialize: function serialize(snapshot, options) { return get(snapshot.record, 'store').serializerFor(snapshot.modelName).serialize(snapshot, options); }, /** Implement this method in a subclass to handle the creation of new records. Serializes the record and sends it to the server. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ createRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'POST', url: `/${type.modelName}`, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method createRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: null, /** Implement this method in a subclass to handle the updating of a record. Serializes the record update and sends it to the server. The updateRecord method is expected to return a promise that will resolve with the serialized record. This allows the backend to inform the Ember Data store the current state of this record after the update. If it is not possible to return a serialized record the updateRecord promise can also resolve with `undefined` and the Ember Data store will assume all of the updates were successfully applied on the backend. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ updateRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var id = snapshot.id; return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'PUT', url: `/${type.modelName}/${id}`, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method updateRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: null, /** Implement this method in a subclass to handle the deletion of a record. Sends a delete request for the record to the server. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ deleteRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var id = snapshot.id; return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'DELETE', url: `/${type.modelName}/${id}`, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method deleteRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: null, /** By default the store will try to coalesce all `fetchRecord` calls within the same runloop into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. You can opt out of this behaviour by either not implementing the findMany hook or by setting coalesceFindRequests to false. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: true, /** The store will call `findMany` instead of multiple `findRecord` requests to find multiple records at once if coalesceFindRequests is true. ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ findMany(store, type, ids, snapshots) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'GET', url: `/${type.modelName}/`, dataType: 'json', data: { filter: { id: ids.join(',') } } }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method findMany @param {DS.Store} store @param {DS.Model} type the DS.Model class of the records @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: null, /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. For example, if your api has nested URLs that depend on the parent, you will want to group records by their parent. The default implementation returns the records as a single group. @method groupRecordsForFindMany @param {DS.Store} store @param {Array} snapshots @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function groupRecordsForFindMany(store, snapshots) { return [snapshots]; }, /** This method is used by the store to determine if the store should reload a record from the adapter when a record is requested by `store.findRecord`. If this method returns `true`, the store will re-fetch a record from the adapter. If this method returns `false`, the store will resolve immediately using the cached record. For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write: ```javascript shouldReloadRecord: function(store, ticketSnapshot) { var timeDiff = moment().diff(ticketSnapshot.attr('lastAccessedAt')).minutes(); if (timeDiff > 20) { return true; } else { return false; } } ``` This method would ensure that whenever you do `store.findRecord('ticket', id)` you will always get a ticket that is no more than 20 minutes old. In case the cached version is more than 20 minutes old, `findRecord` will not resolve until you fetched the latest version. By default this hook returns `false`, as most UIs should not block user interactions while waiting on data update. @since 1.13.0 @method shouldReloadRecord @param {DS.Store} store @param {DS.Snapshot} snapshot @return {Boolean} */ shouldReloadRecord: function shouldReloadRecord(store, snapshot) { return false; }, /** This method is used by the store to determine if the store should reload all records from the adapter when records are requested by `store.findAll`. If this method returns `true`, the store will re-fetch all records from the adapter. If this method returns `false`, the store will resolve immediately using the cached records. For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write: ```javascript shouldReloadAll: function(store, snapshotArray) { var snapshots = snapshotArray.snapshots(); return snapshots.any(function(ticketSnapshot) { var timeDiff = moment().diff(ticketSnapshot.attr('lastAccessedAt')).minutes(); if (timeDiff > 20) { return true; } else { return false; } }); } ``` This method would ensure that whenever you do `store.findAll('ticket')` you will always get a list of tickets that are no more than 20 minutes old. In case a cached version is more than 20 minutes old, `findAll` will not resolve until you fetched the latest versions. By default this methods returns `true` if the passed `snapshotRecordArray` is empty (meaning that there are no records locally available yet), otherwise it returns `false`. @since 1.13.0 @method shouldReloadAll @param {DS.Store} store @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Boolean} */ shouldReloadAll: function shouldReloadAll(store, snapshotRecordArray) { return !snapshotRecordArray.length; }, /** This method is used by the store to determine if the store should reload a record after the `store.findRecord` method resolves a cached record. This method is *only* checked by the store when the store is returning a cached record. If this method returns `true` the store will re-fetch a record from the adapter. For example, if you do not want to fetch complex data over a mobile connection, or if the network is down, you can implement `shouldBackgroundReloadRecord` as follows: ```javascript shouldBackgroundReloadRecord: function(store, snapshot) { var connection = window.navigator.connection; if (connection === 'cellular' || connection === 'none') { return false; } else { return true; } } ``` By default this hook returns `true` so the data for the record is updated in the background. @since 1.13.0 @method shouldBackgroundReloadRecord @param {DS.Store} store @param {DS.Snapshot} snapshot @return {Boolean} */ shouldBackgroundReloadRecord: function shouldBackgroundReloadRecord(store, snapshot) { return true; }, /** This method is used by the store to determine if the store should reload a record array after the `store.findAll` method resolves with a cached record array. This method is *only* checked by the store when the store is returning a cached record array. If this method returns `true` the store will re-fetch all records from the adapter. For example, if you do not want to fetch complex data over a mobile connection, or if the network is down, you can implement `shouldBackgroundReloadAll` as follows: ```javascript shouldBackgroundReloadAll: function(store, snapshotArray) { var connection = window.navigator.connection; if (connection === 'cellular' || connection === 'none') { return false; } else { return true; } } ``` By default this method returns `true`, indicating that a background reload should always be triggered. @since 1.13.0 @method shouldBackgroundReloadAll @param {DS.Store} store @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Boolean} */ shouldBackgroundReloadAll: function shouldBackgroundReloadAll(store, snapshotRecordArray) { return true; } }); }); define('ember-data/adapters/errors', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateFeatures) { 'use strict'; exports.AdapterError = AdapterError; exports.errorsHashToArray = errorsHashToArray; exports.errorsArrayToHash = errorsArrayToHash; var EmberError = _ember['default'].Error; var SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/; var SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/; var PRIMARY_ATTRIBUTE_KEY = 'base'; /** @class AdapterError @namespace DS */ function AdapterError(errors) { var message = arguments.length <= 1 || arguments[1] === undefined ? 'Adapter operation failed' : arguments[1]; this.isAdapterError = true; EmberError.call(this, message); this.errors = errors || [{ title: 'Adapter Error', detail: message }]; } var extendedErrorsEnabled = false; if (false) { extendedErrorsEnabled = true; } function extendFn(ErrorClass) { return function () { var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var defaultMessage = _ref.message; return extend(ErrorClass, defaultMessage); }; } function extend(ParentErrorClass, defaultMessage) { var ErrorClass = function ErrorClass(errors, message) { (0, _emberDataPrivateDebug.assert)('`AdapterError` expects json-api formatted errors array.', Array.isArray(errors || [])); ParentErrorClass.call(this, errors, message || defaultMessage); }; ErrorClass.prototype = Object.create(ParentErrorClass.prototype); if (extendedErrorsEnabled) { ErrorClass.extend = extendFn(ErrorClass); } return ErrorClass; } AdapterError.prototype = Object.create(EmberError.prototype); if (extendedErrorsEnabled) { AdapterError.extend = extendFn(AdapterError); } /** A `DS.InvalidError` is used by an adapter to signal the external API was unable to process a request because the content was not semantically correct or meaningful per the API. Usually this means a record failed some form of server side validation. When a promise from an adapter is rejected with a `DS.InvalidError` the record will transition to the `invalid` state and the errors will be set to the `errors` property on the record. For Ember Data to correctly map errors to their corresponding properties on the model, Ember Data expects each error to be a valid json-api error object with a `source/pointer` that matches the property name. For example if you had a Post model that looked like this. ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ title: DS.attr('string'), content: DS.attr('string') }); ``` To show an error from the server related to the `title` and `content` properties your adapter could return a promise that rejects with a `DS.InvalidError` object that looks like this: ```app/adapters/post.js import Ember from 'ember'; import DS from 'ember-data'; export default DS.RESTAdapter.extend({ updateRecord: function() { // Fictional adapter that always rejects return Ember.RSVP.reject(new DS.InvalidError([ { detail: 'Must be unique', source: { pointer: '/data/attributes/title' } }, { detail: 'Must not be blank', source: { pointer: '/data/attributes/content'} } ])); } }); ``` Your backend may use different property names for your records the store will attempt extract and normalize the errors using the serializer's `extractErrors` method before the errors get added to the the model. As a result, it is safe for the `InvalidError` to wrap the error payload unaltered. @class InvalidError @namespace DS */ var InvalidError = extend(AdapterError, 'The adapter rejected the commit because it was invalid'); exports.InvalidError = InvalidError; /** @class TimeoutError @namespace DS */ var TimeoutError = extend(AdapterError, 'The adapter operation timed out'); exports.TimeoutError = TimeoutError; /** @class AbortError @namespace DS */ var AbortError = extend(AdapterError, 'The adapter operation was aborted'); exports.AbortError = AbortError; /** @class UnauthorizedError @namespace DS */ var UnauthorizedError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation is unauthorized') : null; exports.UnauthorizedError = UnauthorizedError; /** @class ForbiddenError @namespace DS */ var ForbiddenError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation is forbidden') : null; exports.ForbiddenError = ForbiddenError; /** @class NotFoundError @namespace DS */ var NotFoundError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter could not find the resource') : null; exports.NotFoundError = NotFoundError; /** @class ConflictError @namespace DS */ var ConflictError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation failed due to a conflict') : null; exports.ConflictError = ConflictError; /** @class ServerError @namespace DS */ var ServerError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation failed due to a server error') : null; exports.ServerError = ServerError; /** @method errorsHashToArray @private */ function errorsHashToArray(errors) { var out = []; if (_ember['default'].isPresent(errors)) { Object.keys(errors).forEach(function (key) { var messages = _ember['default'].makeArray(errors[key]); for (var i = 0; i < messages.length; i++) { var title = 'Invalid Attribute'; var pointer = '/data/attributes/' + key; if (key === PRIMARY_ATTRIBUTE_KEY) { title = 'Invalid Document'; pointer = '/data'; } out.push({ title: title, detail: messages[i], source: { pointer: pointer } }); } }); } return out; } /** @method errorsArrayToHash @private */ function errorsArrayToHash(errors) { var out = {}; if (_ember['default'].isPresent(errors)) { errors.forEach(function (error) { if (error.source && error.source.pointer) { var key = error.source.pointer.match(SOURCE_POINTER_REGEXP); if (key) { key = key[2]; } else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) { key = PRIMARY_ATTRIBUTE_KEY; } if (key) { out[key] = out[key] || []; out[key].push(error.detail || error.title); } } }); } return out; } }); define('ember-data/adapters/json-api', ['exports', 'ember', 'ember-data/adapters/rest', 'ember-data/-private/features', 'ember-data/-private/debug'], function (exports, _ember, _emberDataAdaptersRest, _emberDataPrivateFeatures, _emberDataPrivateDebug) { /** @module ember-data */ 'use strict'; /** @since 1.13.0 @class JSONAPIAdapter @constructor @namespace DS @extends DS.RESTAdapter */ var JSONAPIAdapter = _emberDataAdaptersRest['default'].extend({ defaultSerializer: '-json-api', /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Object} */ ajaxOptions: function ajaxOptions(url, type, options) { var hash = this._super.apply(this, arguments); if (hash.contentType) { hash.contentType = 'application/vnd.api+json'; } var beforeSend = hash.beforeSend; hash.beforeSend = function (xhr) { xhr.setRequestHeader('Accept', 'application/vnd.api+json'); if (beforeSend) { beforeSend(xhr); } }; return hash; }, /** By default the JSONAPIAdapter will send each find request coming from a `store.find` or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop. For example, if you have an initial payload of: ```javascript { post: { id: 1, comments: [1, 2] } } ``` By default calling `post.get('comments')` will trigger the following requests(assuming the comments haven't been loaded before): ``` GET /comments/1 GET /comments/2 ``` If you set coalesceFindRequests to `true` it will instead trigger the following request: ``` GET /comments?filter[id]=1,2 ``` Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` relationships accessed within the same runloop. If you set `coalesceFindRequests: true` ```javascript store.findRecord('comment', 1); store.findRecord('comment', 2); ``` will also send a request to: `GET /comments?filter[id]=1,2` Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app `groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: false, /** @method findMany @param {DS.Store} store @param {DS.Model} type @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: function findMany(store, type, ids, snapshots) { if (false && !this._hasCustomizedAjax()) { return this._super.apply(this, arguments); } else { var url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); return this.ajax(url, 'GET', { data: { filter: { id: ids.join(',') } } }); } }, /** @method pathForType @param {String} modelName @return {String} path **/ pathForType: function pathForType(modelName) { var dasherized = _ember['default'].String.dasherize(modelName); return _ember['default'].String.pluralize(dasherized); }, // TODO: Remove this once we have a better way to override HTTP verbs. /** @method updateRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: function updateRecord(store, type, snapshot) { if (false && !this._hasCustomizedAjax()) { return this._super.apply(this, arguments); } else { var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); var id = snapshot.id; var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord'); return this.ajax(url, 'PATCH', { data: data }); } }, _hasCustomizedAjax: function _hasCustomizedAjax() { if (this.ajax !== JSONAPIAdapter.prototype.ajax) { (0, _emberDataPrivateDebug.deprecate)('JSONAPIAdapter#ajax has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.json-api-adapter.ajax', until: '3.0.0' }); return true; } if (this.ajaxOptions !== JSONAPIAdapter.prototype.ajaxOptions) { (0, _emberDataPrivateDebug.deprecate)('JSONAPIAdapterr#ajaxOptions has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.json-api-adapter.ajax-options', until: '3.0.0' }); return true; } return false; } }); if (false) { JSONAPIAdapter.reopen({ methodForRequest: function methodForRequest(params) { if (params.requestType === 'updateRecord') { return 'PATCH'; } return this._super.apply(this, arguments); }, dataForRequest: function dataForRequest(params) { var requestType = params.requestType; var ids = params.ids; if (requestType === 'findMany') { return { filter: { id: ids.join(',') } }; } if (requestType === 'updateRecord') { var store = params.store; var type = params.type; var snapshot = params.snapshot; var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); return data; } return this._super.apply(this, arguments); }, headersForRequest: function headersForRequest() { var headers = this._super.apply(this, arguments) || {}; headers['Accept'] = 'application/vnd.api+json'; return headers; }, _requestToJQueryAjaxHash: function _requestToJQueryAjaxHash() { var hash = this._super.apply(this, arguments); if (hash.contentType) { hash.contentType = 'application/vnd.api+json'; } return hash; } }); } exports['default'] = JSONAPIAdapter; }); define('ember-data/adapters/rest', ['exports', 'ember', 'ember-data/adapter', 'ember-data/adapters/errors', 'ember-data/-private/adapters/build-url-mixin', 'ember-data/-private/features', 'ember-data/-private/debug', 'ember-data/-private/utils/parse-response-headers'], function (exports, _ember, _emberDataAdapter, _emberDataAdaptersErrors, _emberDataPrivateAdaptersBuildUrlMixin, _emberDataPrivateFeatures, _emberDataPrivateDebug, _emberDataPrivateUtilsParseResponseHeaders) { /** @module ember-data */ 'use strict'; var MapWithDefault = _ember['default'].MapWithDefault; var get = _ember['default'].get; var Promise = _ember['default'].RSVP.Promise; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## Success and failure The REST adapter will consider a success any response with a status code of the 2xx family ("Success"), as well as 304 ("Not Modified"). Any other status code will be considered a failure. On success, the request promise will be resolved with the full response payload. Failed responses with status code 422 ("Unprocessable Entity") will be considered "invalid". The response will be discarded, except for the `errors` key. The request promise will be rejected with a `DS.InvalidError`. This error object will encapsulate the saved `errors` value. Any other status codes will be treated as an "adapter error". The request promise will be rejected, similarly to the "invalid" case, but with an instance of `DS.AdapterError` instead. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "post": { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" } } ``` Similarly, in response to a `GET` request for `/posts`, the JSON should look like this: ```js { "posts": [ { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" }, { "id": 2, "title": "Rails is omakase", "author": "D2H" } ] } ``` Note that the object root can be pluralized for both a single-object response and an array response: the REST adapter is not strict on this. Further, if the HTTP server responds to a `GET` request to `/posts/1` (e.g. the response to a `findRecord` query) with more than one object in the array, Ember Data will only display the object with the matching ID. ### Conventional Names Attribute names in your JSON payload should be the camelCased versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "person": { "id": 5, "firstName": "Barack", "lastName": "Obama", "occupation": "President" } } ``` ### Errors If a response is considered a failure, the JSON payload is expected to include a top-level key `errors`, detailing any specific issues. For example: ```js { "errors": { "msg": "Something went wrong" } } ``` This adapter does not make any assumptions as to the format of the `errors` object. It will simply be passed along as is, wrapped in an instance of `DS.InvalidError` or `DS.AdapterError`. The serializer can interpret it afterwards. ## Customization ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api/1' }); ``` Requests for the `Person` model would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: 'https://api.example.com' }); ``` ### Headers customization Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` `headers` can also be used as a computed property to support dynamic headers. In the example below, the `session` object has been injected into an adapter by Ember's container. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: Ember.computed('session.authToken', function() { return { "API_KEY": this.get("session.authToken"), "ANOTHER_HEADER": "Some header value" }; }) }); ``` In some cases, your dynamic headers may require data from some object outside of Ember's observer system (for example `document.cookie`). You can use the [volatile](/api/classes/Ember.ComputedProperty.html#method_volatile) function to set the property into a non-cached mode causing the headers to be recomputed with every request. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: Ember.computed(function() { return { "API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"), "ANOTHER_HEADER": "Some header value" }; }).volatile() }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter @uses DS.BuildURLMixin */ var RESTAdapter = _emberDataAdapter['default'].extend(_emberDataPrivateAdaptersBuildUrlMixin['default'], { defaultSerializer: '-rest', /** By default, the RESTAdapter will send the query params sorted alphabetically to the server. For example: ```js store.query('posts', { sort: 'price', category: 'pets' }); ``` will generate a requests like this `/posts?category=pets&sort=price`, even if the parameters were specified in a different order. That way the generated URL will be deterministic and that simplifies caching mechanisms in the backend. Setting `sortQueryParams` to a falsey value will respect the original order. In case you want to sort the query parameters with a different criteria, set `sortQueryParams` to your custom sort function. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ sortQueryParams: function(params) { var sortedKeys = Object.keys(params).sort().reverse(); var len = sortedKeys.length, newParams = {}; for (var i = 0; i < len; i++) { newParams[sortedKeys[i]] = params[sortedKeys[i]]; } return newParams; } }); ``` @method sortQueryParams @param {Object} obj @return {Object} */ sortQueryParams: function sortQueryParams(obj) { var keys = Object.keys(obj); var len = keys.length; if (len < 2) { return obj; } var newQueryParams = {}; var sortedKeys = keys.sort(); for (var i = 0; i < len; i++) { newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]]; } return newQueryParams; }, /** By default the RESTAdapter will send each find request coming from a `store.find` or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop. For example, if you have an initial payload of: ```javascript { post: { id: 1, comments: [1, 2] } } ``` By default calling `post.get('comments')` will trigger the following requests(assuming the comments haven't been loaded before): ``` GET /comments/1 GET /comments/2 ``` If you set coalesceFindRequests to `true` it will instead trigger the following request: ``` GET /comments?ids[]=1&ids[]=2 ``` Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` relationships accessed within the same runloop. If you set `coalesceFindRequests: true` ```javascript store.findRecord('comment', 1); store.findRecord('comment', 2); ``` will also send a request to: `GET /comments?ids[]=1&ids[]=2` Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app `groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: false, /** Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api/1' }); ``` Requests for the `Post` model would now target `/api/1/post/`. @property namespace @type {String} */ /** An adapter can target other hosts by setting the `host` property. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: 'https://api.example.com' }); ``` Requests for the `Post` model would now target `https://api.example.com/post/`. @property host @type {String} */ /** Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. For dynamic headers see [headers customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @property headers @type {Object} */ /** Called by the store in order to fetch the JSON for a given type and ID. The `findRecord` method makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. This method performs an HTTP `GET` request with the id provided as part of the query string. @since 1.13.0 @method findRecord @param {DS.Store} store @param {DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ findRecord: function findRecord(store, type, id, snapshot) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, id: id, snapshot: snapshot, requestType: 'findRecord' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); var query = this.buildQuery(snapshot); return this.ajax(url, 'GET', { data: query }); } }, /** Called by the store in order to fetch a JSON array for all of the records for a given type. The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findAll @param {DS.Store} store @param {DS.Model} type @param {String} sinceToken @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Promise} promise */ findAll: function findAll(store, type, sinceToken, snapshotRecordArray) { var query = this.buildQuery(snapshotRecordArray); if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, sinceToken: sinceToken, query: query, snapshots: snapshotRecordArray, requestType: 'findAll' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, null, snapshotRecordArray, 'findAll'); if (sinceToken) { query.since = sinceToken; } return this.ajax(url, 'GET', { data: query }); } }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `query` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @method query @param {DS.Store} store @param {DS.Model} type @param {Object} query @return {Promise} promise */ query: function query(store, type, _query) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, query: _query, requestType: 'query' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, null, null, 'query', _query); if (this.sortQueryParams) { _query = this.sortQueryParams(_query); } return this.ajax(url, 'GET', { data: _query }); } }, /** Called by the store in order to fetch a JSON object for the record that matches a particular query. The `queryRecord` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @since 1.13.0 @method queryRecord @param {DS.Store} store @param {DS.Model} type @param {Object} query @return {Promise} promise */ queryRecord: function queryRecord(store, type, query) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, query: query, requestType: 'queryRecord' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, null, null, 'queryRecord', query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, 'GET', { data: query }); } }, /** Called by the store in order to fetch several records together if `coalesceFindRequests` is true For example, if the original payload looks like: ```js { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2, 3 ] } ``` The IDs will be passed as a URL-encoded Array of IDs, in this form: ``` ids[]=1&ids[]=2&ids[]=3 ``` Many servers, such as Rails and PHP, will automatically convert this URL-encoded array into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method. The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findMany @param {DS.Store} store @param {DS.Model} type @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: function findMany(store, type, ids, snapshots) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, ids: ids, snapshots: snapshots, requestType: 'findMany' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); return this.ajax(url, 'GET', { data: { ids: ids } }); } }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "comments": "/posts/1/comments" } } } ``` This method will be called with the parent record and `/posts/1/comments`. The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL. The format of your `links` value will influence the final request URL via the `urlPrefix` method: * Links beginning with `//`, `http://`, `https://`, will be used as is, with no further manipulation. * Links beginning with a single `/` will have the current adapter's `host` value prepended to it. * Links with no beginning `/` will have a parentURL prepended to it, via the current adapter's `buildURL`. @method findHasMany @param {DS.Store} store @param {DS.Snapshot} snapshot @param {String} url @return {Promise} promise */ findHasMany: function findHasMany(store, snapshot, url, relationship) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, snapshot: snapshot, url: url, relationship: relationship, requestType: 'findHasMany' }); return this._makeRequest(request); } else { var id = snapshot.id; var type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findHasMany')); return this.ajax(url, 'GET'); } }, /** Called by the store in order to fetch the JSON for the unloaded record in a belongs-to relationship that was originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "person": { "id": 1, "name": "Tom Dale", "links": { "group": "/people/1/group" } } } ``` This method will be called with the parent record and `/people/1/group`. The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL. The format of your `links` value will influence the final request URL via the `urlPrefix` method: * Links beginning with `//`, `http://`, `https://`, will be used as is, with no further manipulation. * Links beginning with a single `/` will have the current adapter's `host` value prepended to it. * Links with no beginning `/` will have a parentURL prepended to it, via the current adapter's `buildURL`. @method findBelongsTo @param {DS.Store} store @param {DS.Snapshot} snapshot @param {String} url @return {Promise} promise */ findBelongsTo: function findBelongsTo(store, snapshot, url, relationship) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, snapshot: snapshot, url: url, relationship: relationship, requestType: 'findBelongsTo' }); return this._makeRequest(request); } else { var id = snapshot.id; var type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findBelongsTo')); return this.ajax(url, 'GET'); } }, /** Called by the store when a newly created record is saved via the `save` method on a model record instance. The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method createRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: function createRecord(store, type, snapshot) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, snapshot: snapshot, requestType: 'createRecord' }); return this._makeRequest(request); } else { var data = {}; var serializer = store.serializerFor(type.modelName); var url = this.buildURL(type.modelName, null, snapshot, 'createRecord'); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); return this.ajax(url, "POST", { data: data }); } }, /** Called by the store when an existing record is saved via the `save` method on a model record instance. The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method updateRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: function updateRecord(store, type, snapshot) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, snapshot: snapshot, requestType: 'updateRecord' }); return this._makeRequest(request); } else { var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot); var id = snapshot.id; var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord'); return this.ajax(url, "PUT", { data: data }); } }, /** Called by the store when a record is deleted. The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`. @method deleteRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: function deleteRecord(store, type, snapshot) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, snapshot: snapshot, requestType: 'deleteRecord' }); return this._makeRequest(request); } else { var id = snapshot.id; return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE"); } }, _stripIDFromURL: function _stripIDFromURL(store, snapshot) { var url = this.buildURL(snapshot.modelName, snapshot.id, snapshot); var expandedURL = url.split('/'); // Case when the url is of the format ...something/:id // We are decodeURIComponent-ing the lastSegment because if it represents // the id, it has been encodeURIComponent-ified within `buildURL`. If we // don't do this, then records with id having special characters are not // coalesced correctly (see GH #4190 for the reported bug) var lastSegment = expandedURL[expandedURL.length - 1]; var id = snapshot.id; if (decodeURIComponent(lastSegment) === id) { expandedURL[expandedURL.length - 1] = ""; } else if (endsWith(lastSegment, '?id=' + id)) { //Case when the url is of the format ...something?id=:id expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1); } return expandedURL.join('/'); }, // http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers maxURLLength: 2048, /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. This implementation groups together records that have the same base URL but differing ids. For example `/comments/1` and `/comments/2` will be grouped together because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2` It also supports urls where ids are passed as a query param, such as `/comments?id=1` but not those where there is more than 1 query param such as `/comments?id=2&name=David` Currently only the query param of `id` is supported. If you need to support others, please override this or the `_stripIDFromURL` method. It does not group records that have differing base urls, such as for example: `/posts/1/comments/2` and `/posts/2/comments/3` @method groupRecordsForFindMany @param {DS.Store} store @param {Array} snapshots @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function groupRecordsForFindMany(store, snapshots) { var groups = MapWithDefault.create({ defaultValue: function defaultValue() { return []; } }); var adapter = this; var maxURLLength = this.maxURLLength; snapshots.forEach(function (snapshot) { var baseUrl = adapter._stripIDFromURL(store, snapshot); groups.get(baseUrl).push(snapshot); }); function splitGroupToFitInUrl(group, maxURLLength, paramNameLength) { var baseUrl = adapter._stripIDFromURL(store, group[0]); var idsSize = 0; var splitGroups = [[]]; group.forEach(function (snapshot) { var additionalLength = encodeURIComponent(snapshot.id).length + paramNameLength; if (baseUrl.length + idsSize + additionalLength >= maxURLLength) { idsSize = 0; splitGroups.push([]); } idsSize += additionalLength; var lastGroupIndex = splitGroups.length - 1; splitGroups[lastGroupIndex].push(snapshot); }); return splitGroups; } var groupsArray = []; groups.forEach(function (group, key) { var paramNameLength = '&ids%5B%5D='.length; var splitGroups = splitGroupToFitInUrl(group, maxURLLength, paramNameLength); splitGroups.forEach(function (splitGroup) { return groupsArray.push(splitGroup); }); }); return groupsArray; }, /** Takes an ajax response, and returns the json payload or an error. By default this hook just returns the json payload passed to it. You might want to override it in two cases: 1. Your API might return useful results in the response headers. Response headers are passed in as the second argument. 2. Your API might return errors as successful responses with status code 200 and an Errors text or object. You can return a `DS.InvalidError` or a `DS.AdapterError` (or a sub class) from this hook and it will automatically reject the promise and put your record into the invalid or error state. Returning a `DS.InvalidError` from this method will cause the record to transition into the `invalid` state and make the `errors` object available on the record. When returning an `DS.InvalidError` the store will attempt to normalize the error data returned from the server using the serializer's `extractErrors` method. @since 1.13.0 @method handleResponse @param {Number} status @param {Object} headers @param {Object} payload @param {Object} requestData - the original request information @return {Object | DS.AdapterError} response */ handleResponse: function handleResponse(status, headers, payload, requestData) { if (this.isSuccess(status, headers, payload)) { return payload; } else if (this.isInvalid(status, headers, payload)) { return new _emberDataAdaptersErrors.InvalidError(payload.errors); } var errors = this.normalizeErrorResponse(status, headers, payload); var detailedMessage = this.generatedDetailedMessage(status, headers, payload, requestData); if (false) { switch (status) { case 401: return new _emberDataAdaptersErrors.UnauthorizedError(errors, detailedMessage); case 403: return new _emberDataAdaptersErrors.ForbiddenError(errors, detailedMessage); case 404: return new _emberDataAdaptersErrors.NotFoundError(errors, detailedMessage); case 409: return new _emberDataAdaptersErrors.ConflictError(errors, detailedMessage); default: if (status >= 500) { return new _emberDataAdaptersErrors.ServerError(errors, detailedMessage); } } } return new _emberDataAdaptersErrors.AdapterError(errors, detailedMessage); }, /** Default `handleResponse` implementation uses this hook to decide if the response is a success. @since 1.13.0 @method isSuccess @param {Number} status @param {Object} headers @param {Object} payload @return {Boolean} */ isSuccess: function isSuccess(status, headers, payload) { return status >= 200 && status < 300 || status === 304; }, /** Default `handleResponse` implementation uses this hook to decide if the response is a an invalid error. @since 1.13.0 @method isInvalid @param {Number} status @param {Object} headers @param {Object} payload @return {Boolean} */ isInvalid: function isInvalid(status, headers, payload) { return status === 422; }, /** Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into `extractSingle` or `extractArray` (depending on whether the original query was for one record or many records). By default, `ajax` method has the following behavior: * It sets the response `dataType` to `"json"` * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be `application/json; charset=utf-8` * If the HTTP method is not `"GET"`, it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers. @method ajax @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Promise} promise */ ajax: function ajax(url, type, options) { var adapter = this; var requestData = { url: url, method: type }; return new Promise(function (resolve, reject) { var hash = adapter.ajaxOptions(url, type, options); hash.success = function (payload, textStatus, jqXHR) { var response = ajaxSuccess(adapter, jqXHR, payload, requestData); _ember['default'].run.join(null, resolve, response); }; hash.error = function (jqXHR, textStatus, errorThrown) { var responseData = { textStatus: textStatus, errorThrown: errorThrown }; var error = ajaxError(adapter, jqXHR, requestData, responseData); _ember['default'].run.join(null, reject, error); }; adapter._ajaxRequest(hash); }, 'DS: RESTAdapter#ajax ' + type + ' to ' + url); }, /** @method _ajaxRequest @private @param {Object} options jQuery ajax options to be used for the ajax request */ _ajaxRequest: function _ajaxRequest(options) { _ember['default'].$.ajax(options); }, /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Object} */ ajaxOptions: function ajaxOptions(url, type, options) { var hash = options || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } var headers = get(this, 'headers'); if (headers !== undefined) { hash.beforeSend = function (xhr) { Object.keys(headers).forEach(function (key) { return xhr.setRequestHeader(key, headers[key]); }); }; } return hash; }, /** @method parseErrorResponse @private @param {String} responseText @return {Object} */ parseErrorResponse: function parseErrorResponse(responseText) { var json = responseText; try { json = _ember['default'].$.parseJSON(responseText); } catch (e) { // ignored } return json; }, /** @method normalizeErrorResponse @private @param {Number} status @param {Object} headers @param {Object} payload @return {Array} errors payload */ normalizeErrorResponse: function normalizeErrorResponse(status, headers, payload) { if (payload && typeof payload === 'object' && payload.errors) { return payload.errors; } else { return [{ status: '' + status, title: "The backend responded with an error", detail: '' + payload }]; } }, /** Generates a detailed ("friendly") error message, with plenty of information for debugging (good luck!) @method generatedDetailedMessage @private @param {Number} status @param {Object} headers @param {Object} payload @param {Object} requestData @return {String} detailed error message */ generatedDetailedMessage: function generatedDetailedMessage(status, headers, payload, requestData) { var shortenedPayload; var payloadContentType = headers["Content-Type"] || "Empty Content-Type"; if (payloadContentType === "text/html" && payload.length > 250) { shortenedPayload = "[Omitted Lengthy HTML]"; } else { shortenedPayload = payload; } var requestDescription = requestData.method + ' ' + requestData.url; var payloadDescription = 'Payload (' + payloadContentType + ')'; return ['Ember Data Request ' + requestDescription + ' returned a ' + status, payloadDescription, shortenedPayload].join('\n'); }, // @since 2.5.0 buildQuery: function buildQuery(snapshot) { var query = {}; if (snapshot) { var include = snapshot.include; if (include) { query.include = include; } } return query; }, _hasCustomizedAjax: function _hasCustomizedAjax() { if (this.ajax !== RESTAdapter.prototype.ajax) { (0, _emberDataPrivateDebug.deprecate)('RESTAdapter#ajax has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.rest-adapter.ajax', until: '3.0.0' }); return true; } if (this.ajaxOptions !== RESTAdapter.prototype.ajaxOptions) { (0, _emberDataPrivateDebug.deprecate)('RESTAdapter#ajaxOptions has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.rest-adapter.ajax-options', until: '3.0.0' }); return true; } return false; } }); if (false) { RESTAdapter.reopen({ /** * Get the data (body or query params) for a request. * * @public * @method dataForRequest * @param {Object} params * @return {Object} data */ dataForRequest: function dataForRequest(params) { var store = params.store; var type = params.type; var snapshot = params.snapshot; var requestType = params.requestType; var query = params.query; // type is not passed to findBelongsTo and findHasMany type = type || snapshot && snapshot.type; var serializer = store.serializerFor(type.modelName); var data = {}; switch (requestType) { case 'createRecord': serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); break; case 'updateRecord': serializer.serializeIntoHash(data, type, snapshot); break; case 'findRecord': data = this.buildQuery(snapshot); break; case 'findAll': if (params.sinceToken) { query = query || {}; query.since = params.sinceToken; } data = query; break; case 'query': case 'queryRecord': if (this.sortQueryParams) { query = this.sortQueryParams(query); } data = query; break; case 'findMany': data = { ids: params.ids }; break; default: data = undefined; break; } return data; }, /** * Get the HTTP method for a request. * * @public * @method methodForRequest * @param {Object} params * @return {String} HTTP method */ methodForRequest: function methodForRequest(params) { var requestType = params.requestType; switch (requestType) { case 'createRecord': return 'POST'; case 'updateRecord': return 'PUT'; case 'deleteRecord': return 'DELETE'; } return 'GET'; }, /** * Get the URL for a request. * * @public * @method urlForRequest * @param {Object} params * @return {String} URL */ urlForRequest: function urlForRequest(params) { var type = params.type; var id = params.id; var ids = params.ids; var snapshot = params.snapshot; var snapshots = params.snapshots; var requestType = params.requestType; var query = params.query; // type and id are not passed from updateRecord and deleteRecord, hence they // are defined if not set type = type || snapshot && snapshot.type; id = id || snapshot && snapshot.id; switch (requestType) { case 'findAll': return this.buildURL(type.modelName, null, snapshots, requestType); case 'query': case 'queryRecord': return this.buildURL(type.modelName, null, null, requestType, query); case 'findMany': return this.buildURL(type.modelName, ids, snapshots, requestType); case 'findHasMany': case 'findBelongsTo': { var url = this.buildURL(type.modelName, id, snapshot, requestType); return this.urlPrefix(params.url, url); } } return this.buildURL(type.modelName, id, snapshot, requestType, query); }, /** * Get the headers for a request. * * By default the value of the `headers` property of the adapter is * returned. * * @public * @method headersForRequest * @param {Object} params * @return {Object} headers */ headersForRequest: function headersForRequest(params) { return this.get('headers'); }, /** * Get an object which contains all properties for a request which should * be made. * * @private * @method _requestFor * @param {Object} params * @return {Object} request object */ _requestFor: function _requestFor(params) { var method = this.methodForRequest(params); var url = this.urlForRequest(params); var headers = this.headersForRequest(params); var data = this.dataForRequest(params); return { method: method, url: url, headers: headers, data: data }; }, /** * Convert a request object into a hash which can be passed to `jQuery.ajax`. * * @private * @method _requestToJQueryAjaxHash * @param {Object} request * @return {Object} jQuery ajax hash */ _requestToJQueryAjaxHash: function _requestToJQueryAjaxHash(request) { var hash = {}; hash.type = request.method; hash.url = request.url; hash.dataType = 'json'; hash.context = this; if (request.data) { if (request.method !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(request.data); } else { hash.data = request.data; } } var headers = request.headers; if (headers !== undefined) { hash.beforeSend = function (xhr) { Object.keys(headers).forEach(function (key) { return xhr.setRequestHeader(key, headers[key]); }); }; } return hash; }, /** * Make a request using `jQuery.ajax`. * * @private * @method _makeRequest * @param {Object} request * @return {Promise} promise */ _makeRequest: function _makeRequest(request) { var adapter = this; var hash = this._requestToJQueryAjaxHash(request); var method = request.method; var url = request.url; var requestData = { method: method, url: url }; return new _ember['default'].RSVP.Promise(function (resolve, reject) { hash.success = function (payload, textStatus, jqXHR) { var response = ajaxSuccess(adapter, jqXHR, payload, requestData); _ember['default'].run.join(null, resolve, response); }; hash.error = function (jqXHR, textStatus, errorThrown) { var responseData = { textStatus: textStatus, errorThrown: errorThrown }; var error = ajaxError(adapter, jqXHR, requestData, responseData); _ember['default'].run.join(null, reject, error); }; adapter._ajaxRequest(hash); }, 'DS: RESTAdapter#makeRequest: ' + method + ' ' + url); } }); } function ajaxSuccess(adapter, jqXHR, payload, requestData) { var response = undefined; try { response = adapter.handleResponse(jqXHR.status, (0, _emberDataPrivateUtilsParseResponseHeaders['default'])(jqXHR.getAllResponseHeaders()), payload, requestData); } catch (error) { return Promise.reject(error); } if (response && response.isAdapterError) { return Promise.reject(response); } else { return response; } } function ajaxError(adapter, jqXHR, requestData, responseData) { (0, _emberDataPrivateDebug.runInDebug)(function () { var message = 'The server returned an empty string for ' + requestData.method + ' ' + requestData.url + ', which cannot be parsed into a valid JSON. Return either null or {}.'; var validJSONString = !(responseData.textStatus === "parsererror" && jqXHR.responseText === ""); (0, _emberDataPrivateDebug.warn)(message, validJSONString, { id: 'ds.adapter.returned-empty-string-as-JSON' }); }); var error = undefined; if (responseData.errorThrown instanceof Error) { error = responseData.errorThrown; } else if (responseData.textStatus === 'timeout') { error = new _emberDataAdaptersErrors.TimeoutError(); } else if (responseData.textStatus === 'abort') { error = new _emberDataAdaptersErrors.AbortError(); } else { try { error = adapter.handleResponse(jqXHR.status, (0, _emberDataPrivateUtilsParseResponseHeaders['default'])(jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(jqXHR.responseText) || responseData.errorThrown, requestData); } catch (e) { error = e; } } return error; } //From http://stackoverflow.com/questions/280634/endswith-in-javascript function endsWith(string, suffix) { if (typeof String.prototype.endsWith !== 'function') { return string.indexOf(suffix, string.length - suffix.length) !== -1; } else { return string.endsWith(suffix); } } exports['default'] = RESTAdapter; }); define('ember-data/attr', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { 'use strict'; exports['default'] = attr; /** @module ember-data */ function getDefaultValue(record, options, key) { if (typeof options.defaultValue === 'function') { return options.defaultValue.apply(null, arguments); } else { var defaultValue = options.defaultValue; (0, _emberDataPrivateDebug.deprecate)('Non primitive defaultValues are deprecated because they are shared between all instances. If you would like to use a complex object as a default value please provide a function that returns the complex object.', typeof defaultValue !== 'object' || defaultValue === null, { id: 'ds.defaultValue.complex-object', until: '3.0.0' }); return defaultValue; } } function hasValue(record, key) { return key in record._attributes || key in record._inFlightAttributes || key in record._data; } function getValue(record, key) { if (key in record._attributes) { return record._attributes[key]; } else if (key in record._inFlightAttributes) { return record._inFlightAttributes[key]; } else { return record._data[key]; } } /** `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types: `string`, `number`, `boolean` and `date`. You can define your own transforms by subclassing [DS.Transform](/api/data/classes/DS.Transform.html). Note that you cannot use `attr` to define an attribute of `id`. `DS.attr` takes an optional hash as a second parameter, currently supported options are: - `defaultValue`: Pass a string or a function to be called to set the attribute to a default value if none is supplied. Example ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ username: DS.attr('string'), email: DS.attr('string'), verified: DS.attr('boolean', { defaultValue: false }) }); ``` Default value can also be a function. This is useful it you want to return a new object for each attribute. ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ username: attr('string'), email: attr('string'), settings: attr({defaultValue: function() { return {}; }}) }); ``` The `options` hash is passed as second argument to a transforms' `serialize` and `deserialize` method. This allows to configure a transformation and adapt the corresponding value, based on the config: ```app/models/post.js export default DS.Model.extend({ text: DS.attr('text', { uppercase: true }) }); ``` ```app/transforms/text.js export default DS.Transform.extend({ serialize: function(value, options) { if (options.uppercase) { return value.toUpperCase(); } return value; }, deserialize: function(value) { return value; } }) ``` @namespace @method attr @for DS @param {String} type the attribute type @param {Object} options a hash of options @return {Attribute} */ function attr(type, options) { if (typeof type === 'object') { options = type; type = undefined; } else { options = options || {}; } var meta = { type: type, isAttribute: true, options: options }; return _ember['default'].computed({ get: function get(key) { var internalModel = this._internalModel; if (hasValue(internalModel, key)) { return getValue(internalModel, key); } else { return getDefaultValue(this, options, key); } }, set: function set(key, value) { var internalModel = this._internalModel; var oldValue = getValue(internalModel, key); var originalValue; if (value !== oldValue) { // Add the new value to the changed attributes hash; it will get deleted by // the 'didSetProperty' handler if it is no different from the original value internalModel._attributes[key] = value; if (key in internalModel._inFlightAttributes) { originalValue = internalModel._inFlightAttributes[key]; } else { originalValue = internalModel._data[key]; } this._internalModel.send('didSetProperty', { name: key, oldValue: oldValue, originalValue: originalValue, value: value }); } return value; } }).meta(meta); } }); define("ember-data/index", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/features", "ember-data/-private/global", "ember-data/-private/core", "ember-data/-private/system/normalize-model-name", "ember-data/-private/system/model/internal-model", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/store", "ember-data/-private/system/model", "ember-data/model", "ember-data/-private/system/snapshot", "ember-data/adapter", "ember-data/serializer", "ember-data/-private/system/debug", "ember-data/adapters/errors", "ember-data/-private/system/record-arrays", "ember-data/-private/system/many-array", "ember-data/-private/system/record-array-manager", "ember-data/-private/adapters", "ember-data/-private/adapters/build-url-mixin", "ember-data/-private/serializers", "ember-inflector", "ember-data/serializers/embedded-records-mixin", "ember-data/-private/transforms", "ember-data/relationships", "ember-data/setup-container", "ember-data/-private/instance-initializers/initialize-store-service", "ember-data/-private/system/container-proxy", "ember-data/-private/system/relationships/state/relationship"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateFeatures, _emberDataPrivateGlobal, _emberDataPrivateCore, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateSystemModelInternalModel, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStore, _emberDataPrivateSystemModel, _emberDataModel, _emberDataPrivateSystemSnapshot, _emberDataAdapter, _emberDataSerializer, _emberDataPrivateSystemDebug, _emberDataAdaptersErrors, _emberDataPrivateSystemRecordArrays, _emberDataPrivateSystemManyArray, _emberDataPrivateSystemRecordArrayManager, _emberDataPrivateAdapters, _emberDataPrivateAdaptersBuildUrlMixin, _emberDataPrivateSerializers, _emberInflector, _emberDataSerializersEmbeddedRecordsMixin, _emberDataPrivateTransforms, _emberDataRelationships, _emberDataSetupContainer, _emberDataPrivateInstanceInitializersInitializeStoreService, _emberDataPrivateSystemContainerProxy, _emberDataPrivateSystemRelationshipsStateRelationship) { "use strict"; if (_ember["default"].VERSION.match(/^1\.([0-9]|1[0-2])\./)) { throw new _ember["default"].Error("Ember Data requires at least Ember 1.13.0, but you have " + _ember["default"].VERSION + ". Please upgrade your version of Ember, then upgrade Ember Data."); }_emberDataPrivateCore["default"].Store = _emberDataPrivateSystemStore.Store; _emberDataPrivateCore["default"].PromiseArray = _emberDataPrivateSystemPromiseProxies.PromiseArray; _emberDataPrivateCore["default"].PromiseObject = _emberDataPrivateSystemPromiseProxies.PromiseObject; _emberDataPrivateCore["default"].PromiseManyArray = _emberDataPrivateSystemPromiseProxies.PromiseManyArray; _emberDataPrivateCore["default"].Model = _emberDataModel["default"]; _emberDataPrivateCore["default"].RootState = _emberDataPrivateSystemModel.RootState; _emberDataPrivateCore["default"].attr = _emberDataPrivateSystemModel.attr; _emberDataPrivateCore["default"].Errors = _emberDataPrivateSystemModel.Errors; _emberDataPrivateCore["default"].InternalModel = _emberDataPrivateSystemModelInternalModel["default"]; _emberDataPrivateCore["default"].Snapshot = _emberDataPrivateSystemSnapshot["default"]; _emberDataPrivateCore["default"].Adapter = _emberDataAdapter["default"]; _emberDataPrivateCore["default"].AdapterError = _emberDataAdaptersErrors.AdapterError; _emberDataPrivateCore["default"].InvalidError = _emberDataAdaptersErrors.InvalidError; _emberDataPrivateCore["default"].TimeoutError = _emberDataAdaptersErrors.TimeoutError; _emberDataPrivateCore["default"].AbortError = _emberDataAdaptersErrors.AbortError; if (false) { _emberDataPrivateCore["default"].UnauthorizedError = _emberDataAdaptersErrors.UnauthorizedError; _emberDataPrivateCore["default"].ForbiddenError = _emberDataAdaptersErrors.ForbiddenError; _emberDataPrivateCore["default"].NotFoundError = _emberDataAdaptersErrors.NotFoundError; _emberDataPrivateCore["default"].ConflictError = _emberDataAdaptersErrors.ConflictError; _emberDataPrivateCore["default"].ServerError = _emberDataAdaptersErrors.ServerError; } _emberDataPrivateCore["default"].errorsHashToArray = _emberDataAdaptersErrors.errorsHashToArray; _emberDataPrivateCore["default"].errorsArrayToHash = _emberDataAdaptersErrors.errorsArrayToHash; _emberDataPrivateCore["default"].Serializer = _emberDataSerializer["default"]; _emberDataPrivateCore["default"].DebugAdapter = _emberDataPrivateSystemDebug["default"]; _emberDataPrivateCore["default"].RecordArray = _emberDataPrivateSystemRecordArrays.RecordArray; _emberDataPrivateCore["default"].FilteredRecordArray = _emberDataPrivateSystemRecordArrays.FilteredRecordArray; _emberDataPrivateCore["default"].AdapterPopulatedRecordArray = _emberDataPrivateSystemRecordArrays.AdapterPopulatedRecordArray; _emberDataPrivateCore["default"].ManyArray = _emberDataPrivateSystemManyArray["default"]; _emberDataPrivateCore["default"].RecordArrayManager = _emberDataPrivateSystemRecordArrayManager["default"]; _emberDataPrivateCore["default"].RESTAdapter = _emberDataPrivateAdapters.RESTAdapter; _emberDataPrivateCore["default"].BuildURLMixin = _emberDataPrivateAdaptersBuildUrlMixin["default"]; _emberDataPrivateCore["default"].RESTSerializer = _emberDataPrivateSerializers.RESTSerializer; _emberDataPrivateCore["default"].JSONSerializer = _emberDataPrivateSerializers.JSONSerializer; _emberDataPrivateCore["default"].JSONAPIAdapter = _emberDataPrivateAdapters.JSONAPIAdapter; _emberDataPrivateCore["default"].JSONAPISerializer = _emberDataPrivateSerializers.JSONAPISerializer; _emberDataPrivateCore["default"].Transform = _emberDataPrivateTransforms.Transform; _emberDataPrivateCore["default"].DateTransform = _emberDataPrivateTransforms.DateTransform; _emberDataPrivateCore["default"].StringTransform = _emberDataPrivateTransforms.StringTransform; _emberDataPrivateCore["default"].NumberTransform = _emberDataPrivateTransforms.NumberTransform; _emberDataPrivateCore["default"].BooleanTransform = _emberDataPrivateTransforms.BooleanTransform; _emberDataPrivateCore["default"].EmbeddedRecordsMixin = _emberDataSerializersEmbeddedRecordsMixin["default"]; _emberDataPrivateCore["default"].belongsTo = _emberDataRelationships.belongsTo; _emberDataPrivateCore["default"].hasMany = _emberDataRelationships.hasMany; _emberDataPrivateCore["default"].Relationship = _emberDataPrivateSystemRelationshipsStateRelationship["default"]; _emberDataPrivateCore["default"].ContainerProxy = _emberDataPrivateSystemContainerProxy["default"]; _emberDataPrivateCore["default"]._setupContainer = _emberDataSetupContainer["default"]; _emberDataPrivateCore["default"]._initializeStoreService = _emberDataPrivateInstanceInitializersInitializeStoreService["default"]; Object.defineProperty(_emberDataPrivateCore["default"], 'normalizeModelName', { enumerable: true, writable: false, configurable: false, value: _emberDataPrivateSystemNormalizeModelName["default"] }); Object.defineProperty(_emberDataPrivateGlobal["default"], 'DS', { configurable: true, get: function get() { (0, _emberDataPrivateDebug.deprecate)('Using the global version of DS is deprecated. Please either import ' + 'the specific modules needed or `import DS from \'ember-data\';`.', false, { id: 'ember-data.global-ds', until: '3.0.0' }); return _emberDataPrivateCore["default"]; } }); exports["default"] = _emberDataPrivateCore["default"]; }); /** Ember Data @module ember-data @main ember-data */ define("ember-data/model", ["exports", "ember-data/-private/system/model"], function (exports, _emberDataPrivateSystemModel) { "use strict"; exports["default"] = _emberDataPrivateSystemModel["default"]; }); define("ember-data/relationships", ["exports", "ember-data/-private/system/relationships/belongs-to", "ember-data/-private/system/relationships/has-many"], function (exports, _emberDataPrivateSystemRelationshipsBelongsTo, _emberDataPrivateSystemRelationshipsHasMany) { /** @module ember-data */ "use strict"; exports.belongsTo = _emberDataPrivateSystemRelationshipsBelongsTo["default"]; exports.hasMany = _emberDataPrivateSystemRelationshipsHasMany["default"]; }); define('ember-data/serializer', ['exports', 'ember'], function (exports, _ember) { /** @module ember-data */ 'use strict'; /** `DS.Serializer` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `normalizeResponse()` * `serialize()` And you can optionally override the following methods: * `normalize()` For an example implementation, see [DS.JSONSerializer](DS.JSONSerializer.html), the included JSON serializer. @class Serializer @namespace DS @extends Ember.Object */ exports['default'] = _ember['default'].Object.extend({ /** The `store` property is the application's `store` that contains all records. It's injected as a service. It can be used to push records from a non flat data structure server response. @property store @type {DS.Store} @public */ /** The `normalizeResponse` method is used to normalize a payload from the server to a JSON-API Document. http://jsonapi.org/format/#document-structure @since 1.13.0 @method normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeResponse: null, /** The `serialize` method is used when a record is saved in order to convert the record into the form that your external data source expects. `serialize` takes an optional `options` hash with a single option: - `includeId`: If this is `true`, `serialize` should include the ID in the serialized object it builds. @method serialize @param {DS.Model} record @param {Object} [options] @return {Object} */ serialize: null, /** The `normalize` method is used to convert a payload received from your external data source into the normalized form `store.push()` expects. You should override this method, munge the hash and return the normalized payload. @method normalize @param {DS.Model} typeClass @param {Object} hash @return {Object} */ normalize: function normalize(typeClass, hash) { return hash; } }); }); define('ember-data/serializers/embedded-records-mixin', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { 'use strict'; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];return arr2; } else { return Array.from(arr); } } var get = _ember['default'].get; var set = _ember['default'].set; var camelize = _ember['default'].String.camelize; /** ## Using Embedded Records `DS.EmbeddedRecordsMixin` supports serializing embedded records. To set up embedded records, include the mixin when extending a serializer, then define and configure embedded (model) relationships. Below is an example of a per-type serializer (`post` type). ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: { embedded: 'always' }, comments: { serialize: 'ids' } } }); ``` Note that this use of `{ embedded: 'always' }` is unrelated to the `{ embedded: 'always' }` that is defined as an option on `DS.attr` as part of defining a model while working with the `ActiveModelSerializer`. Nevertheless, using `{ embedded: 'always' }` as an option to `DS.attr` is not a valid way to setup embedded records. The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for: ```js { serialize: 'records', deserialize: 'records' } ``` ### Configuring Attrs A resource's `attrs` option may be set to use `ids`, `records` or false for the `serialize` and `deserialize` settings. The `attrs` property can be set on the `ApplicationSerializer` or a per-type serializer. In the case where embedded JSON is expected while extracting a payload (reading) the setting is `deserialize: 'records'`, there is no need to use `ids` when extracting as that is the default behavior without this mixin if you are using the vanilla `EmbeddedRecordsMixin`. Likewise, to embed JSON in the payload while serializing `serialize: 'records'` is the setting to use. There is an option of not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you do not want the relationship sent at all, you can use `serialize: false`. ### EmbeddedRecordsMixin defaults If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin` will behave in the following way: BelongsTo: `{ serialize: 'id', deserialize: 'id' }` HasMany: `{ serialize: false, deserialize: 'ids' }` ### Model Relationships Embedded records must have a model defined to be extracted and serialized. Note that when defining any relationships on your model such as `belongsTo` and `hasMany`, you should not both specify `async: true` and also indicate through the serializer's `attrs` attribute that the related model should be embedded for deserialization. If a model is declared embedded for deserialization (`embedded: 'always'` or `deserialize: 'records'`), then do not use `async: true`. To successfully extract and serialize embedded records the model relationships must be setup correcty. See the [defining relationships](/guides/models/defining-models/#toc_defining-relationships) section of the **Defining Models** guide page. Records without an `id` property are not considered embedded records, model instances must have an `id` property to be used with Ember Data. ### Example JSON payloads, Models and Serializers **When customizing a serializer it is important to grok what the customizations are. Please read the docs for the methods this mixin provides, in case you need to modify it to fit your specific needs.** For example review the docs for each method of this mixin: * [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize) * [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo) * [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany) @class EmbeddedRecordsMixin @namespace DS */ exports['default'] = _ember['default'].Mixin.create({ /** Normalize the record and recursively normalize/extract all the embedded records while pushing them into the store as they are encountered A payload with an attr configured for embedded records needs to be extracted: ```js { "post": { "id": "1" "title": "Rails is omakase", "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` @method normalize @param {DS.Model} typeClass @param {Object} hash to be normalized @param {String} prop the hash has been referenced by @return {Object} the normalized hash **/ normalize: function normalize(typeClass, hash, prop) { var normalizedHash = this._super(typeClass, hash, prop); return this._extractEmbeddedRecords(this, this.store, typeClass, normalizedHash); }, keyForRelationship: function keyForRelationship(key, typeClass, method) { if (method === 'serialize' && this.hasSerializeRecordsOption(key) || method === 'deserialize' && this.hasDeserializeRecordsOption(key)) { return this.keyForAttribute(key, method); } else { return this._super(key, typeClass, method) || key; } }, /** Serialize `belongsTo` relationship when it is configured as an embedded object. This example of an author model belongs to a post model: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), author: DS.belongsTo('author') }); Author = DS.Model.extend({ name: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded author ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: { embedded: 'always' } } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "author": { "id": "2" "name": "dhh" } } } ``` @method serializeBelongsTo @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeBelongsTo: function serializeBelongsTo(snapshot, json, relationship) { var attr = relationship.key; if (this.noSerializeOptionSpecified(attr)) { this._super(snapshot, json, relationship); return; } var includeIds = this.hasSerializeIdsOption(attr); var includeRecords = this.hasSerializeRecordsOption(attr); var embeddedSnapshot = snapshot.belongsTo(attr); if (includeIds) { var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } if (!embeddedSnapshot) { json[serializedKey] = null; } else { json[serializedKey] = embeddedSnapshot.id; if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } } else if (includeRecords) { this._serializeEmbeddedBelongsTo(snapshot, json, relationship); } }, _serializeEmbeddedBelongsTo: function _serializeEmbeddedBelongsTo(snapshot, json, relationship) { var embeddedSnapshot = snapshot.belongsTo(relationship.key); var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } if (!embeddedSnapshot) { json[serializedKey] = null; } else { json[serializedKey] = embeddedSnapshot.serialize({ includeId: true }); this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[serializedKey]); if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } }, /** Serializes `hasMany` relationships when it is configured as embedded objects. This example of a post model has many comments: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), comments: DS.hasMany('comment') }); Comment = DS.Model.extend({ body: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded comments ```app/serializers/post.js import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: { embedded: 'always' } } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` The attrs options object can use more specific instruction for extracting and serializing. When serializing, an option to embed `ids`, `ids-and-types` or `records` can be set. When extracting the only option is `records`. So `{ embedded: 'always' }` is shorthand for: `{ serialize: 'records', deserialize: 'records' }` To embed the `ids` for a related object (using a hasMany relationship): ```app/serializers/post.js import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: { serialize: 'ids', deserialize: 'records' } } }) ``` ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": ["1", "2"] } } ``` To embed the relationship as a collection of objects with `id` and `type` keys, set `ids-and-types` for the related object. This is particularly useful for polymorphic relationships where records don't share the same table and the `id` is not enough information. By example having a user that has many pets: ```js User = DS.Model.extend({ name: DS.attr('string'), pets: DS.hasMany('pet', { polymorphic: true }) }); Pet = DS.Model.extend({ name: DS.attr('string'), }); Cat = Pet.extend({ // ... }); Parrot = Pet.extend({ // ... }); ``` ```app/serializers/user.js import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { pets: { serialize: 'ids-and-types', deserialize: 'records' } } }); ``` ```js { "user": { "id": "1" "name": "Bertin Osborne", "pets": [ { "id": "1", "type": "Cat" }, { "id": "1", "type": "Parrot"} ] } } ``` @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function serializeHasMany(snapshot, json, relationship) { var attr = relationship.key; if (this.noSerializeOptionSpecified(attr)) { this._super(snapshot, json, relationship); return; } if (this.hasSerializeIdsOption(attr)) { var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } json[serializedKey] = snapshot.hasMany(attr, { ids: true }); } else if (this.hasSerializeRecordsOption(attr)) { this._serializeEmbeddedHasMany(snapshot, json, relationship); } else { if (this.hasSerializeIdsAndTypesOption(attr)) { this._serializeHasManyAsIdsAndTypes(snapshot, json, relationship); } } }, /** Serializes a hasMany relationship as an array of objects containing only `id` and `type` keys. This has its use case on polymorphic hasMany relationships where the server is not storing all records in the same table using STI, and therefore the `id` is not enough information TODO: Make the default in Ember-data 3.0?? */ _serializeHasManyAsIdsAndTypes: function _serializeHasManyAsIdsAndTypes(snapshot, json, relationship) { var serializedKey = this.keyForAttribute(relationship.key, 'serialize'); var hasMany = snapshot.hasMany(relationship.key); json[serializedKey] = _ember['default'].A(hasMany).map(function (recordSnapshot) { // // I'm sure I'm being utterly naive here. Propably id is a configurate property and // type too, and the modelName has to be normalized somehow. // return { id: recordSnapshot.id, type: recordSnapshot.modelName }; }); }, _serializeEmbeddedHasMany: function _serializeEmbeddedHasMany(snapshot, json, relationship) { var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } (0, _emberDataPrivateDebug.warn)('The embedded relationship \'' + serializedKey + '\' is undefined for \'' + snapshot.modelName + '\' with id \'' + snapshot.id + '\'. Please include it in your original payload.', _ember['default'].typeOf(snapshot.hasMany(relationship.key)) !== 'undefined', { id: 'ds.serializer.embedded-relationship-undefined' }); json[serializedKey] = this._generateSerializedHasMany(snapshot, relationship); }, /* Returns an array of embedded records serialized to JSON */ _generateSerializedHasMany: function _generateSerializedHasMany(snapshot, relationship) { var hasMany = snapshot.hasMany(relationship.key); var manyArray = _ember['default'].A(hasMany); var ret = new Array(manyArray.length); for (var i = 0; i < manyArray.length; i++) { var embeddedSnapshot = manyArray[i]; var embeddedJson = embeddedSnapshot.serialize({ includeId: true }); this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson); ret[i] = embeddedJson; } return ret; }, /** When serializing an embedded record, modify the property (in the json payload) that refers to the parent record (foreign key for relationship). Serializing a `belongsTo` relationship removes the property that refers to the parent record Serializing a `hasMany` relationship does not remove the property that refers to the parent record. @method removeEmbeddedForeignKey @param {DS.Snapshot} snapshot @param {DS.Snapshot} embeddedSnapshot @param {Object} relationship @param {Object} json */ removeEmbeddedForeignKey: function removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json) { if (relationship.kind === 'hasMany') { return; } else if (relationship.kind === 'belongsTo') { var parentRecord = snapshot.type.inverseFor(relationship.key, this.store); if (parentRecord) { var name = parentRecord.name; var embeddedSerializer = this.store.serializerFor(embeddedSnapshot.modelName); var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind, 'deserialize'); if (parentKey) { delete json[parentKey]; } } } }, // checks config for attrs option to embedded (always) - serialize and deserialize hasEmbeddedAlwaysOption: function hasEmbeddedAlwaysOption(attr) { var option = this.attrsOption(attr); return option && option.embedded === 'always'; }, // checks config for attrs option to serialize ids hasSerializeRecordsOption: function hasSerializeRecordsOption(attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || option && option.serialize === 'records'; }, // checks config for attrs option to serialize records hasSerializeIdsOption: function hasSerializeIdsOption(attr) { var option = this.attrsOption(attr); return option && (option.serialize === 'ids' || option.serialize === 'id'); }, // checks config for attrs option to serialize records as objects containing id and types hasSerializeIdsAndTypesOption: function hasSerializeIdsAndTypesOption(attr) { var option = this.attrsOption(attr); return option && (option.serialize === 'ids-and-types' || option.serialize === 'id-and-type'); }, // checks config for attrs option to serialize records noSerializeOptionSpecified: function noSerializeOptionSpecified(attr) { var option = this.attrsOption(attr); return !(option && (option.serialize || option.embedded)); }, // checks config for attrs option to deserialize records // a defined option object for a resource is treated the same as // `deserialize: 'records'` hasDeserializeRecordsOption: function hasDeserializeRecordsOption(attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || option && option.deserialize === 'records'; }, attrsOption: function attrsOption(attr) { var attrs = this.get('attrs'); return attrs && (attrs[camelize(attr)] || attrs[attr]); }, /** @method _extractEmbeddedRecords @private */ _extractEmbeddedRecords: function _extractEmbeddedRecords(serializer, store, typeClass, partial) { var _this = this; typeClass.eachRelationship(function (key, relationship) { if (serializer.hasDeserializeRecordsOption(key)) { if (relationship.kind === "hasMany") { _this._extractEmbeddedHasMany(store, key, partial, relationship); } if (relationship.kind === "belongsTo") { _this._extractEmbeddedBelongsTo(store, key, partial, relationship); } } }); return partial; }, /** @method _extractEmbeddedHasMany @private */ _extractEmbeddedHasMany: function _extractEmbeddedHasMany(store, key, hash, relationshipMeta) { var relationshipHash = get(hash, 'data.relationships.' + key + '.data'); if (!relationshipHash) { return; } var hasMany = new Array(relationshipHash.length); for (var i = 0; i < relationshipHash.length; i++) { var item = relationshipHash[i]; var _normalizeEmbeddedRelationship2 = this._normalizeEmbeddedRelationship(store, relationshipMeta, item); var data = _normalizeEmbeddedRelationship2.data; var included = _normalizeEmbeddedRelationship2.included; hash.included = hash.included || []; hash.included.push(data); if (included) { var _hash$included; (_hash$included = hash.included).push.apply(_hash$included, _toConsumableArray(included)); } hasMany[i] = { id: data.id, type: data.type }; } var relationship = { data: hasMany }; set(hash, 'data.relationships.' + key, relationship); }, /** @method _extractEmbeddedBelongsTo @private */ _extractEmbeddedBelongsTo: function _extractEmbeddedBelongsTo(store, key, hash, relationshipMeta) { var relationshipHash = get(hash, 'data.relationships.' + key + '.data'); if (!relationshipHash) { return; } var _normalizeEmbeddedRelationship3 = this._normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash); var data = _normalizeEmbeddedRelationship3.data; var included = _normalizeEmbeddedRelationship3.included; hash.included = hash.included || []; hash.included.push(data); if (included) { var _hash$included2; (_hash$included2 = hash.included).push.apply(_hash$included2, _toConsumableArray(included)); } var belongsTo = { id: data.id, type: data.type }; var relationship = { data: belongsTo }; set(hash, 'data.relationships.' + key, relationship); }, /** @method _normalizeEmbeddedRelationship @private */ _normalizeEmbeddedRelationship: function _normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash) { var modelName = relationshipMeta.type; if (relationshipMeta.options.polymorphic) { modelName = relationshipHash.type; } var modelClass = store.modelFor(modelName); var serializer = store.serializerFor(modelName); return serializer.normalize(modelClass, relationshipHash, null); }, isEmbeddedRecordsMixin: true }); }); define('ember-data/serializers/json-api', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/serializers/json', 'ember-data/-private/system/normalize-model-name', 'ember-inflector', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializersJson, _emberDataPrivateSystemNormalizeModelName, _emberInflector, _emberDataPrivateFeatures) { /** @module ember-data */ 'use strict'; var dasherize = _ember['default'].String.dasherize; /** Ember Data 2.0 Serializer: In Ember Data a Serializer is used to serialize and deserialize records when they are transferred in and out of an external source. This process involves normalizing property names, transforming attribute values and serializing relationships. `JSONAPISerializer` supports the http://jsonapi.org/ spec and is the serializer recommended by Ember Data. This serializer normalizes a JSON API payload that looks like: ```js // models/player.js import DS from "ember-data"; export default DS.Model.extend({ name: DS.attr(), skill: DS.attr(), gamesPlayed: DS.attr(), club: DS.belongsTo('club') }); // models/club.js import DS from "ember-data"; export default DS.Model.extend({ name: DS.attr(), location: DS.attr(), players: DS.hasMany('player') }); ``` ```js { "data": [ { "attributes": { "name": "Benfica", "location": "Portugal" }, "id": "1", "relationships": { "players": { "data": [ { "id": "3", "type": "players" } ] } }, "type": "clubs" } ], "included": [ { "attributes": { "name": "Eusebio Silva Ferreira", "skill": "Rocket shot", "games-played": 431 }, "id": "3", "relationships": { "club": { "data": { "id": "1", "type": "clubs" } } }, "type": "players" } ] } ``` to the format that the Ember Data store expects. @since 1.13.0 @class JSONAPISerializer @namespace DS @extends DS.JSONSerializer */ var JSONAPISerializer = _emberDataSerializersJson['default'].extend({ /** @method _normalizeDocumentHelper @param {Object} documentHash @return {Object} @private */ _normalizeDocumentHelper: function _normalizeDocumentHelper(documentHash) { if (_ember['default'].typeOf(documentHash.data) === 'object') { documentHash.data = this._normalizeResourceHelper(documentHash.data); } else if (Array.isArray(documentHash.data)) { var ret = new Array(documentHash.data.length); for (var i = 0; i < documentHash.data.length; i++) { var data = documentHash.data[i]; ret[i] = this._normalizeResourceHelper(data); } documentHash.data = ret; } if (Array.isArray(documentHash.included)) { var ret = new Array(documentHash.included.length); for (var i = 0; i < documentHash.included.length; i++) { var included = documentHash.included[i]; ret[i] = this._normalizeResourceHelper(included); } documentHash.included = ret; } return documentHash; }, /** @method _normalizeRelationshipDataHelper @param {Object} relationshipDataHash @return {Object} @private */ _normalizeRelationshipDataHelper: function _normalizeRelationshipDataHelper(relationshipDataHash) { if (false) { var modelName = this.modelNameFromPayloadType(relationshipDataHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(relationshipDataHash.type); if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { (0, _emberDataPrivateDebug.deprecate)("You are using modelNameFromPayloadKey to normalize the type for a relationship. This has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.json-api-serializer.deprecated-model-name-for-relationship', until: '3.0.0' }); modelName = deprecatedModelNameLookup; } relationshipDataHash.type = modelName; } else { var type = this.modelNameFromPayloadKey(relationshipDataHash.type); relationshipDataHash.type = type; } return relationshipDataHash; }, /** @method _normalizeResourceHelper @param {Object} resourceHash @return {Object} @private */ _normalizeResourceHelper: function _normalizeResourceHelper(resourceHash) { (0, _emberDataPrivateDebug.assert)(this.warnMessageForUndefinedType(), !_ember['default'].isNone(resourceHash.type), { id: 'ds.serializer.type-is-undefined' }); var modelName = undefined, usedLookup = undefined; if (false) { modelName = this.modelNameFromPayloadType(resourceHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(resourceHash.type); usedLookup = 'modelNameFromPayloadType'; if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { (0, _emberDataPrivateDebug.deprecate)("You are using modelNameFromPayloadKey to normalize the type for a resource. This has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.json-api-serializer.deprecated-model-name-for-resource', until: '3.0.0' }); modelName = deprecatedModelNameLookup; usedLookup = 'modelNameFromPayloadKey'; } } else { modelName = this.modelNameFromPayloadKey(resourceHash.type); usedLookup = 'modelNameFromPayloadKey'; } if (!this.store._hasModelFor(modelName)) { (0, _emberDataPrivateDebug.warn)(this.warnMessageNoModelForType(modelName, resourceHash.type, usedLookup), false, { id: 'ds.serializer.model-for-type-missing' }); return null; } var modelClass = this.store.modelFor(modelName); var serializer = this.store.serializerFor(modelName); var _serializer$normalize = serializer.normalize(modelClass, resourceHash); var data = _serializer$normalize.data; return data; }, /** @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function pushPayload(store, payload) { var normalizedPayload = this._normalizeDocumentHelper(payload); if (false) { return store.push(normalizedPayload); } else { store.push(normalizedPayload); } }, /** @method _normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @param {Boolean} isSingle @return {Object} JSON-API Document @private */ _normalizeResponse: function _normalizeResponse(store, primaryModelClass, payload, id, requestType, isSingle) { var normalizedPayload = this._normalizeDocumentHelper(payload); return normalizedPayload; }, normalizeQueryRecordResponse: function normalizeQueryRecordResponse() { var normalized = this._super.apply(this, arguments); (0, _emberDataPrivateDebug.assert)('Expected the primary data returned by the serializer for a `queryRecord` response to be a single object but instead it was an array.', !Array.isArray(normalized.data), { id: 'ds.serializer.json-api.queryRecord-array-response' }); return normalized; }, /** @method extractAttributes @param {DS.Model} modelClass @param {Object} resourceHash @return {Object} */ extractAttributes: function extractAttributes(modelClass, resourceHash) { var _this = this; var attributes = {}; if (resourceHash.attributes) { modelClass.eachAttribute(function (key) { var attributeKey = _this.keyForAttribute(key, 'deserialize'); if (resourceHash.attributes[attributeKey] !== undefined) { attributes[key] = resourceHash.attributes[attributeKey]; } }); } return attributes; }, /** @method extractRelationship @param {Object} relationshipHash @return {Object} */ extractRelationship: function extractRelationship(relationshipHash) { if (_ember['default'].typeOf(relationshipHash.data) === 'object') { relationshipHash.data = this._normalizeRelationshipDataHelper(relationshipHash.data); } if (Array.isArray(relationshipHash.data)) { var ret = new Array(relationshipHash.data.length); for (var i = 0; i < relationshipHash.data.length; i++) { var data = relationshipHash.data[i]; ret[i] = this._normalizeRelationshipDataHelper(data); } relationshipHash.data = ret; } return relationshipHash; }, /** @method extractRelationships @param {Object} modelClass @param {Object} resourceHash @return {Object} */ extractRelationships: function extractRelationships(modelClass, resourceHash) { var _this2 = this; var relationships = {}; if (resourceHash.relationships) { modelClass.eachRelationship(function (key, relationshipMeta) { var relationshipKey = _this2.keyForRelationship(key, relationshipMeta.kind, 'deserialize'); if (resourceHash.relationships[relationshipKey] !== undefined) { var relationshipHash = resourceHash.relationships[relationshipKey]; relationships[key] = _this2.extractRelationship(relationshipHash); } }); } return relationships; }, /** @method _extractType @param {DS.Model} modelClass @param {Object} resourceHash @return {String} @private */ _extractType: function _extractType(modelClass, resourceHash) { if (false) { var modelName = this.modelNameFromPayloadType(resourceHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(resourceHash.type); if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { (0, _emberDataPrivateDebug.deprecate)("You are using modelNameFromPayloadKey to normalize the type for a polymorphic relationship. This has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.json-api-serializer.deprecated-model-name-for-polymorphic-type', until: '3.0.0' }); modelName = deprecatedModelNameLookup; } return modelName; } else { return this.modelNameFromPayloadKey(resourceHash.type); } }, /** @method modelNameFromPayloadKey @param {String} key @return {String} the model's modelName */ // TODO @deprecated Use modelNameFromPayloadType instead modelNameFromPayloadKey: function modelNameFromPayloadKey(key) { return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName['default'])(key)); }, /** @method payloadKeyFromModelName @param {String} modelName @return {String} */ // TODO @deprecated Use payloadTypeFromModelName instead payloadKeyFromModelName: function payloadKeyFromModelName(modelName) { return (0, _emberInflector.pluralize)(modelName); }, /** @method normalize @param {DS.Model} modelClass @param {Object} resourceHash the resource hash from the adapter @return {Object} the normalized resource hash */ normalize: function normalize(modelClass, resourceHash) { if (resourceHash.attributes) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash.attributes); } if (resourceHash.relationships) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash.relationships); } var data = { id: this.extractId(modelClass, resourceHash), type: this._extractType(modelClass, resourceHash), attributes: this.extractAttributes(modelClass, resourceHash), relationships: this.extractRelationships(modelClass, resourceHash) }; this.applyTransforms(modelClass, data.attributes); return { data: data }; }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. By default `JSONAPISerializer` follows the format used on the examples of http://jsonapi.org/format and uses dashes as the word separator in the JSON attribute keys. This behaviour can be easily customized by extending this method. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONAPISerializer.extend({ keyForAttribute: function(attr, method) { return Ember.String.dasherize(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @param {String} method @return {String} normalized key */ keyForAttribute: function keyForAttribute(key, method) { return dasherize(key); }, /** `keyForRelationship` can be used to define a custom key when serializing and deserializing relationship properties. By default `JSONAPISerializer` follows the format used on the examples of http://jsonapi.org/format and uses dashes as word separators in relationship properties. This behaviour can be easily customized by extending this method. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONAPISerializer.extend({ keyForRelationship: function(key, relationship, method) { return Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} typeClass @param {String} method @return {String} normalized key */ keyForRelationship: function keyForRelationship(key, typeClass, method) { return dasherize(key); }, /** @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function serialize(snapshot, options) { var data = this._super.apply(this, arguments); var payloadType = undefined; if (false) { payloadType = this.payloadTypeFromModelName(snapshot.modelName); var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(snapshot.modelName); if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) { (0, _emberDataPrivateDebug.deprecate)("You used payloadKeyFromModelName to customize how a type is serialized. Use payloadTypeFromModelName instead.", false, { id: 'ds.json-api-serializer.deprecated-payload-type-for-model', until: '3.0.0' }); payloadType = deprecatedPayloadTypeLookup; } } else { payloadType = this.payloadKeyFromModelName(snapshot.modelName); } data.type = payloadType; return { data: data }; }, /** @method serializeAttribute @param {DS.Snapshot} snapshot @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function serializeAttribute(snapshot, json, key, attribute) { var type = attribute.type; if (this._canSerialize(key)) { json.attributes = json.attributes || {}; var value = snapshot.attr(key); if (type) { var transform = this.transformFor(type); value = transform.serialize(value, attribute.options); } var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key) { payloadKey = this.keyForAttribute(key, 'serialize'); } json.attributes[payloadKey] = value; } }, /** @method serializeBelongsTo @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeBelongsTo: function serializeBelongsTo(snapshot, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var belongsTo = snapshot.belongsTo(key); if (belongsTo !== undefined) { json.relationships = json.relationships || {}; var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key) { payloadKey = this.keyForRelationship(key, 'belongsTo', 'serialize'); } var data = null; if (belongsTo) { var payloadType = undefined; if (false) { payloadType = this.payloadTypeFromModelName(belongsTo.modelName); var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(belongsTo.modelName); if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) { (0, _emberDataPrivateDebug.deprecate)("You used payloadKeyFromModelName to serialize type for belongs-to relationship. Use payloadTypeFromModelName instead.", false, { id: 'ds.json-api-serializer.deprecated-payload-type-for-belongs-to', until: '3.0.0' }); payloadType = deprecatedPayloadTypeLookup; } } else { payloadType = this.payloadKeyFromModelName(belongsTo.modelName); } data = { type: payloadType, id: belongsTo.id }; } json.relationships[payloadKey] = { data: data }; } } }, /** @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function serializeHasMany(snapshot, json, relationship) { var key = relationship.key; var shouldSerializeHasMany = '_shouldSerializeHasMany'; if (false) { shouldSerializeHasMany = 'shouldSerializeHasMany'; } if (this[shouldSerializeHasMany](snapshot, key, relationship)) { var hasMany = snapshot.hasMany(key); if (hasMany !== undefined) { json.relationships = json.relationships || {}; var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, 'hasMany', 'serialize'); } var data = new Array(hasMany.length); for (var i = 0; i < hasMany.length; i++) { var item = hasMany[i]; var payloadType = undefined; if (false) { payloadType = this.payloadTypeFromModelName(item.modelName); var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(item.modelName); if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) { (0, _emberDataPrivateDebug.deprecate)("You used payloadKeyFromModelName to serialize type for belongs-to relationship. Use payloadTypeFromModelName instead.", false, { id: 'ds.json-api-serializer.deprecated-payload-type-for-has-many', until: '3.0.0' }); payloadType = deprecatedPayloadTypeLookup; } } else { payloadType = this.payloadKeyFromModelName(item.modelName); } data[i] = { type: payloadType, id: item.id }; } json.relationships[payloadKey] = { data: data }; } } } }); if (false) { JSONAPISerializer.reopen({ /** `modelNameFromPayloadType` can be used to change the mapping for a DS model name, taken from the value in the payload. Say your API namespaces the type of a model and returns the following payload for the `post` model: ```javascript // GET /api/posts/1 { "data": { "id": 1, "type: "api::v1::post" } } ``` By overwriting `modelNameFromPayloadType` you can specify that the `posr` model should be used: ```app/serializers/application.js import DS from "ember-data"; export default DS.JSONAPISerializer.extend({ modelNameFromPayloadType(payloadType) { return payloadType.replace('api::v1::', ''); } }); ``` By default the modelName for a model is its singularized name in dasherized form. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `modelNameFromPayloadType` for this purpose. Also take a look at [payloadTypeFromModelName](#method_payloadTypeFromModelName) to customize how the type of a record should be serialized. @method modelNameFromPayloadType @public @param {String} payloadType type from payload @return {String} modelName */ modelNameFromPayloadType: function modelNameFromPayloadType(type) { return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName['default'])(type)); }, /** `payloadTypeFromModelName` can be used to change the mapping for the type in the payload, taken from the model name. Say your API namespaces the type of a model and expects the following payload when you update the `post` model: ```javascript // POST /api/posts/1 { "data": { "id": 1, "type": "api::v1::post" } } ``` By overwriting `payloadTypeFromModelName` you can specify that the namespaces model name for the `post` should be used: ```app/serializers/application.js import DS from "ember-data"; export default JSONAPISerializer.extend({ payloadTypeFromModelName(modelName) { return "api::v1::" + modelName; } }); ``` By default the payload type is the pluralized model name. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `payloadTypeFromModelName` for this purpose. Also take a look at [modelNameFromPayloadType](#method_modelNameFromPayloadType) to customize how the model name from should be mapped from the payload. @method payloadTypeFromModelName @public @param {String} modelname modelName from the record @return {String} payloadType */ payloadTypeFromModelName: function payloadTypeFromModelName(modelName) { return (0, _emberInflector.pluralize)(modelName); }, _hasCustomModelNameFromPayloadKey: function _hasCustomModelNameFromPayloadKey() { return this.modelNameFromPayloadKey !== JSONAPISerializer.prototype.modelNameFromPayloadKey; }, _hasCustomPayloadKeyFromModelName: function _hasCustomPayloadKeyFromModelName() { return this.payloadKeyFromModelName !== JSONAPISerializer.prototype.payloadKeyFromModelName; } }); } (0, _emberDataPrivateDebug.runInDebug)(function () { JSONAPISerializer.reopen({ willMergeMixin: function willMergeMixin(props) { (0, _emberDataPrivateDebug.warn)('The JSONAPISerializer does not work with the EmbeddedRecordsMixin because the JSON API spec does not describe how to format embedded resources.', !props.isEmbeddedRecordsMixin, { id: 'ds.serializer.embedded-records-mixin-not-supported' }); }, warnMessageForUndefinedType: function warnMessageForUndefinedType() { return 'Encountered a resource object with an undefined type (resolved resource using ' + this.constructor.toString() + ')'; }, warnMessageNoModelForType: function warnMessageNoModelForType(modelName, originalType, usedLookup) { return 'Encountered a resource object with type "' + originalType + '", but no model was found for model name "' + modelName + '" (resolved model name using \'' + this.constructor.toString() + '.' + usedLookup + '("' + originalType + '")).'; } }); }); exports['default'] = JSONAPISerializer; }); define('ember-data/serializers/json', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/serializer', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/utils', 'ember-data/-private/features', 'ember-data/adapters/errors'], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializer, _emberDataPrivateSystemCoerceId, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateUtils, _emberDataPrivateFeatures, _emberDataAdaptersErrors) { 'use strict'; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];return arr2; } else { return Array.from(arr); } } var get = _ember['default'].get; var isNone = _ember['default'].isNone; var assign = _ember['default'].assign || _ember['default'].merge; /** Ember Data 2.0 Serializer: In Ember Data a Serializer is used to serialize and deserialize records when they are transferred in and out of an external source. This process involves normalizing property names, transforming attribute values and serializing relationships. By default, Ember Data uses and recommends the `JSONAPISerializer`. `JSONSerializer` is useful for simpler or legacy backends that may not support the http://jsonapi.org/ spec. For example, given the following `User` model and JSON payload: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ friends: DS.hasMany('user'), house: DS.belongsTo('location'), name: DS.attr('string') }); ``` ```js { id: 1, name: 'Sebastian', friends: [3, 4], links: { house: '/houses/lefkada' } } ``` `JSONSerializer` will normalize the JSON payload to the JSON API format that the Ember Data store expects. You can customize how JSONSerializer processes its payload by passing options in the `attrs` hash or by subclassing the `JSONSerializer` and overriding hooks: - To customize how a single record is normalized, use the `normalize` hook. - To customize how `JSONSerializer` normalizes the whole server response, use the `normalizeResponse` hook. - To customize how `JSONSerializer` normalizes a specific response from the server, use one of the many specific `normalizeResponse` hooks. - To customize how `JSONSerializer` normalizes your id, attributes or relationships, use the `extractId`, `extractAttributes` and `extractRelationships` hooks. The `JSONSerializer` normalization process follows these steps: - `normalizeResponse` - entry method to the serializer. - `normalizeCreateRecordResponse` - a `normalizeResponse` for a specific operation is called. - `normalizeSingleResponse`|`normalizeArrayResponse` - for methods like `createRecord` we expect a single record back, while for methods like `findAll` we expect multiple methods back. - `normalize` - `normalizeArray` iterates and calls `normalize` for each of its records while `normalizeSingle` calls it once. This is the method you most likely want to subclass. - `extractId` | `extractAttributes` | `extractRelationships` - `normalize` delegates to these methods to turn the record payload into the JSON API format. @class JSONSerializer @namespace DS @extends DS.Serializer */ var JSONSerializer = _emberDataSerializer['default'].extend({ /** The `primaryKey` is used when serializing and deserializing data. Ember Data always uses the `id` property to store the id of the record. The external source may not always follow this convention. In these cases it is useful to override the `primaryKey` property to match the `primaryKey` of your external store. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ primaryKey: '_id' }); ``` @property primaryKey @type {String} @default 'id' */ primaryKey: 'id', /** The `attrs` object can be used to declare a simple mapping between property names on `DS.Model` records and payload keys in the serialized JSON object representing the record. An object with the property `key` can also be used to designate the attribute's key on the response payload. Example ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string'), admin: DS.attr('boolean') }); ``` ```app/serializers/person.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ attrs: { admin: 'is_admin', occupation: { key: 'career' } } }); ``` You can also remove attributes by setting the `serialize` key to `false` in your mapping object. Example ```app/serializers/person.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ attrs: { admin: { serialize: false }, occupation: { key: 'career' } } }); ``` When serialized: ```javascript { "firstName": "Harry", "lastName": "Houdini", "career": "magician" } ``` Note that the `admin` is now not included in the payload. @property attrs @type {Object} */ mergedProperties: ['attrs'], /** Given a subclass of `DS.Model` and a JSON object this method will iterate through each attribute of the `DS.Model` and invoke the `DS.Transform#deserialize` method on the matching property of the JSON object. This method is typically called after the serializer's `normalize` method. @method applyTransforms @private @param {DS.Model} typeClass @param {Object} data The data to transform @return {Object} data The transformed data object */ applyTransforms: function applyTransforms(typeClass, data) { var _this = this; var attributes = get(typeClass, 'attributes'); typeClass.eachTransformedAttribute(function (key, typeClass) { if (data[key] === undefined) { return; } var transform = _this.transformFor(typeClass); var transformMeta = attributes.get(key); data[key] = transform.deserialize(data[key], transformMeta.options); }); return data; }, /** The `normalizeResponse` method is used to normalize a payload from the server to a JSON-API Document. http://jsonapi.org/format/#document-structure This method delegates to a more specific normalize method based on the `requestType`. To override this method with a custom one, make sure to call `return this._super(store, primaryModelClass, payload, id, requestType)` with your pre-processed data. Here's an example of using `normalizeResponse` manually: ```javascript socket.on('message', function(message) { var data = message.data; var modelClass = store.modelFor(data.modelName); var serializer = store.serializerFor(data.modelName); var normalized = serializer.normalizeSingleResponse(store, modelClass, data, data.id); store.push(normalized); }); ``` @since 1.13.0 @method normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeResponse: function normalizeResponse(store, primaryModelClass, payload, id, requestType) { switch (requestType) { case 'findRecord': return this.normalizeFindRecordResponse.apply(this, arguments); case 'queryRecord': return this.normalizeQueryRecordResponse.apply(this, arguments); case 'findAll': return this.normalizeFindAllResponse.apply(this, arguments); case 'findBelongsTo': return this.normalizeFindBelongsToResponse.apply(this, arguments); case 'findHasMany': return this.normalizeFindHasManyResponse.apply(this, arguments); case 'findMany': return this.normalizeFindManyResponse.apply(this, arguments); case 'query': return this.normalizeQueryResponse.apply(this, arguments); case 'createRecord': return this.normalizeCreateRecordResponse.apply(this, arguments); case 'deleteRecord': return this.normalizeDeleteRecordResponse.apply(this, arguments); case 'updateRecord': return this.normalizeUpdateRecordResponse.apply(this, arguments); } }, /** @since 1.13.0 @method normalizeFindRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindRecordResponse: function normalizeFindRecordResponse(store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeQueryRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeQueryRecordResponse: function normalizeQueryRecordResponse(store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeFindAllResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindAllResponse: function normalizeFindAllResponse(store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeFindBelongsToResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindBelongsToResponse: function normalizeFindBelongsToResponse(store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeFindHasManyResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindHasManyResponse: function normalizeFindHasManyResponse(store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeFindManyResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindManyResponse: function normalizeFindManyResponse(store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeQueryResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeQueryResponse: function normalizeQueryResponse(store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeCreateRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeCreateRecordResponse: function normalizeCreateRecordResponse(store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeDeleteRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeDeleteRecordResponse: function normalizeDeleteRecordResponse(store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeUpdateRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeUpdateRecordResponse: function normalizeUpdateRecordResponse(store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeSaveResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeSaveResponse: function normalizeSaveResponse(store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeSingleResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeSingleResponse: function normalizeSingleResponse(store, primaryModelClass, payload, id, requestType) { return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, true); }, /** @since 1.13.0 @method normalizeArrayResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeArrayResponse: function normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) { return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, false); }, /** @method _normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @param {Boolean} isSingle @return {Object} JSON-API Document @private */ _normalizeResponse: function _normalizeResponse(store, primaryModelClass, payload, id, requestType, isSingle) { var documentHash = { data: null, included: [] }; var meta = this.extractMeta(store, primaryModelClass, payload); if (meta) { (0, _emberDataPrivateDebug.assert)('The `meta` returned from `extractMeta` has to be an object, not "' + _ember['default'].typeOf(meta) + '".', _ember['default'].typeOf(meta) === 'object'); documentHash.meta = meta; } if (isSingle) { var _normalize = this.normalize(primaryModelClass, payload); var data = _normalize.data; var included = _normalize.included; documentHash.data = data; if (included) { documentHash.included = included; } } else { var ret = new Array(payload.length); for (var i = 0, l = payload.length; i < l; i++) { var item = payload[i]; var _normalize2 = this.normalize(primaryModelClass, item); var data = _normalize2.data; var included = _normalize2.included; if (included) { var _documentHash$included; (_documentHash$included = documentHash.included).push.apply(_documentHash$included, _toConsumableArray(included)); } ret[i] = data; } documentHash.data = ret; } return documentHash; }, /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ normalize: function(typeClass, hash) { var fields = Ember.get(typeClass, 'fields'); fields.forEach(function(field) { var payloadField = Ember.String.underscore(field); if (field === payloadField) { return; } hash[field] = hash[payloadField]; delete hash[payloadField]; }); return this._super.apply(this, arguments); } }); ``` @method normalize @param {DS.Model} typeClass @param {Object} hash @return {Object} */ normalize: function normalize(modelClass, resourceHash) { var data = null; if (resourceHash) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash); if (_ember['default'].typeOf(resourceHash.links) === 'object') { this.normalizeUsingDeclaredMapping(modelClass, resourceHash.links); } data = { id: this.extractId(modelClass, resourceHash), type: modelClass.modelName, attributes: this.extractAttributes(modelClass, resourceHash), relationships: this.extractRelationships(modelClass, resourceHash) }; this.applyTransforms(modelClass, data.attributes); } return { data: data }; }, /** Returns the resource's ID. @method extractId @param {Object} modelClass @param {Object} resourceHash @return {String} */ extractId: function extractId(modelClass, resourceHash) { var primaryKey = get(this, 'primaryKey'); var id = resourceHash[primaryKey]; return (0, _emberDataPrivateSystemCoerceId['default'])(id); }, /** Returns the resource's attributes formatted as a JSON-API "attributes object". http://jsonapi.org/format/#document-resource-object-attributes @method extractAttributes @param {Object} modelClass @param {Object} resourceHash @return {Object} */ extractAttributes: function extractAttributes(modelClass, resourceHash) { var _this2 = this; var attributeKey; var attributes = {}; modelClass.eachAttribute(function (key) { attributeKey = _this2.keyForAttribute(key, 'deserialize'); if (resourceHash[attributeKey] !== undefined) { attributes[key] = resourceHash[attributeKey]; } }); return attributes; }, /** Returns a relationship formatted as a JSON-API "relationship object". http://jsonapi.org/format/#document-resource-object-relationships @method extractRelationship @param {Object} relationshipModelName @param {Object} relationshipHash @return {Object} */ extractRelationship: function extractRelationship(relationshipModelName, relationshipHash) { if (_ember['default'].isNone(relationshipHash)) { return null; } /* When `relationshipHash` is an object it usually means that the relationship is polymorphic. It could however also be embedded resources that the EmbeddedRecordsMixin has be able to process. */ if (_ember['default'].typeOf(relationshipHash) === 'object') { if (relationshipHash.id) { relationshipHash.id = (0, _emberDataPrivateSystemCoerceId['default'])(relationshipHash.id); } var modelClass = this.store.modelFor(relationshipModelName); if (relationshipHash.type && !(0, _emberDataPrivateUtils.modelHasAttributeOrRelationshipNamedType)(modelClass)) { if (false) { var modelName = this.modelNameFromPayloadType(relationshipHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(relationshipHash.type); if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { (0, _emberDataPrivateDebug.deprecate)("You used modelNameFromPayloadKey to customize how a type is normalized. Use modelNameFromPayloadType instead", false, { id: 'ds.json-serializer.deprecated-type-for-polymorphic-relationship', until: '3.0.0' }); modelName = deprecatedModelNameLookup; } relationshipHash.type = modelName; } else { relationshipHash.type = this.modelNameFromPayloadKey(relationshipHash.type); } } return relationshipHash; } return { id: (0, _emberDataPrivateSystemCoerceId['default'])(relationshipHash), type: relationshipModelName }; }, /** Returns a polymorphic relationship formatted as a JSON-API "relationship object". http://jsonapi.org/format/#document-resource-object-relationships `relationshipOptions` is a hash which contains more information about the polymorphic relationship which should be extracted: - `resourceHash` complete hash of the resource the relationship should be extracted from - `relationshipKey` key under which the value for the relationship is extracted from the resourceHash - `relationshipMeta` meta information about the relationship @method extractPolymorphicRelationship @param {Object} relationshipModelName @param {Object} relationshipHash @param {Object} relationshipOptions @return {Object} */ extractPolymorphicRelationship: function extractPolymorphicRelationship(relationshipModelName, relationshipHash, relationshipOptions) { return this.extractRelationship(relationshipModelName, relationshipHash); }, /** Returns the resource's relationships formatted as a JSON-API "relationships object". http://jsonapi.org/format/#document-resource-object-relationships @method extractRelationships @param {Object} modelClass @param {Object} resourceHash @return {Object} */ extractRelationships: function extractRelationships(modelClass, resourceHash) { var _this3 = this; var relationships = {}; modelClass.eachRelationship(function (key, relationshipMeta) { var relationship = null; var relationshipKey = _this3.keyForRelationship(key, relationshipMeta.kind, 'deserialize'); if (resourceHash[relationshipKey] !== undefined) { var data = null; var relationshipHash = resourceHash[relationshipKey]; if (relationshipMeta.kind === 'belongsTo') { if (relationshipMeta.options.polymorphic) { // extracting a polymorphic belongsTo may need more information // than the type and the hash (which might only be an id) for the // relationship, hence we pass the key, resource and // relationshipMeta too data = _this3.extractPolymorphicRelationship(relationshipMeta.type, relationshipHash, { key: key, resourceHash: resourceHash, relationshipMeta: relationshipMeta }); } else { data = _this3.extractRelationship(relationshipMeta.type, relationshipHash); } } else if (relationshipMeta.kind === 'hasMany') { if (!_ember['default'].isNone(relationshipHash)) { data = new Array(relationshipHash.length); for (var i = 0, l = relationshipHash.length; i < l; i++) { var item = relationshipHash[i]; data[i] = _this3.extractRelationship(relationshipMeta.type, item); } } } relationship = { data: data }; } var linkKey = _this3.keyForLink(key, relationshipMeta.kind); if (resourceHash.links && resourceHash.links[linkKey] !== undefined) { var related = resourceHash.links[linkKey]; relationship = relationship || {}; relationship.links = { related: related }; } if (relationship) { relationships[key] = relationship; } }); return relationships; }, /** @method modelNameFromPayloadKey @param {String} key @return {String} the model's modelName */ // TODO @deprecated Use modelNameFromPayloadType instead modelNameFromPayloadKey: function modelNameFromPayloadKey(key) { return (0, _emberDataPrivateSystemNormalizeModelName['default'])(key); }, /** @method normalizeAttributes @private */ normalizeAttributes: function normalizeAttributes(typeClass, hash) { var _this4 = this; var payloadKey; if (this.keyForAttribute) { typeClass.eachAttribute(function (key) { payloadKey = _this4.keyForAttribute(key, 'deserialize'); if (key === payloadKey) { return; } if (hash[payloadKey] === undefined) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }); } }, /** @method normalizeRelationships @private */ normalizeRelationships: function normalizeRelationships(typeClass, hash) { var _this5 = this; var payloadKey; if (this.keyForRelationship) { typeClass.eachRelationship(function (key, relationship) { payloadKey = _this5.keyForRelationship(key, relationship.kind, 'deserialize'); if (key === payloadKey) { return; } if (hash[payloadKey] === undefined) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }); } }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function normalizeUsingDeclaredMapping(modelClass, hash) { var attrs = get(this, 'attrs'); var normalizedKey, payloadKey, key; if (attrs) { for (key in attrs) { normalizedKey = payloadKey = this._getMappedKey(key, modelClass); if (hash[payloadKey] === undefined) { continue; } if (get(modelClass, 'attributes').has(key)) { normalizedKey = this.keyForAttribute(key); } if (get(modelClass, 'relationshipsByName').has(key)) { normalizedKey = this.keyForRelationship(key); } if (payloadKey !== normalizedKey) { hash[normalizedKey] = hash[payloadKey]; delete hash[payloadKey]; } } } }, /** Looks up the property key that was set by the custom `attr` mapping passed to the serializer. @method _getMappedKey @private @param {String} key @return {String} key */ _getMappedKey: function _getMappedKey(key, modelClass) { (0, _emberDataPrivateDebug.warn)('There is no attribute or relationship with the name `' + key + '` on `' + modelClass.modelName + '`. Check your serializers attrs hash.', get(modelClass, 'attributes').has(key) || get(modelClass, 'relationshipsByName').has(key), { id: 'ds.serializer.no-mapped-attrs-key' }); var attrs = get(this, 'attrs'); var mappedKey; if (attrs && attrs[key]) { mappedKey = attrs[key]; //We need to account for both the { title: 'post_title' } and //{ title: { key: 'post_title' }} forms if (mappedKey.key) { mappedKey = mappedKey.key; } if (typeof mappedKey === 'string') { key = mappedKey; } } return key; }, /** Check attrs.key.serialize property to inform if the `key` can be serialized @method _canSerialize @private @param {String} key @return {boolean} true if the key can be serialized */ _canSerialize: function _canSerialize(key) { var attrs = get(this, 'attrs'); return !attrs || !attrs[key] || attrs[key].serialize !== false; }, /** When attrs.key.serialize is set to true then it takes priority over the other checks and the related attribute/relationship will be serialized @method _mustSerialize @private @param {String} key @return {boolean} true if the key must be serialized */ _mustSerialize: function _mustSerialize(key) { var attrs = get(this, 'attrs'); return attrs && attrs[key] && attrs[key].serialize === true; }, /** Check if the given hasMany relationship should be serialized @method shouldSerializeHasMany @param {DS.Snapshot} snapshot @param {String} key @param {String} relationshipType @return {boolean} true if the hasMany relationship should be serialized */ shouldSerializeHasMany: function shouldSerializeHasMany(snapshot, key, relationship) { if (this._shouldSerializeHasMany !== JSONSerializer.prototype._shouldSerializeHasMany) { (0, _emberDataPrivateDebug.deprecate)('The private method _shouldSerializeHasMany has been promoted to the public API. Please remove the underscore to use the public shouldSerializeHasMany method.', false, { id: 'ds.serializer.private-should-serialize-has-many', until: '3.0.0' }); } return this._shouldSerializeHasMany(snapshot, key, relationship); }, /** Check if the given hasMany relationship should be serialized @method _shouldSerializeHasMany @private @param {DS.Snapshot} snapshot @param {String} key @param {String} relationshipType @return {boolean} true if the hasMany relationship should be serialized */ _shouldSerializeHasMany: function _shouldSerializeHasMany(snapshot, key, relationship) { var relationshipType = snapshot.type.determineRelationshipType(relationship, this.store); if (this._mustSerialize(key)) { return true; } return this._canSerialize(key) && (relationshipType === 'manyToNone' || relationshipType === 'manyToMany'); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```javascript { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = { POST_TTL: snapshot.attr('title'), POST_BDY: snapshot.attr('body'), POST_CMS: snapshot.hasMany('comments', { ids: true }) } if (options.includeId) { json.POST_ID_ = snapshot.id; } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = {}; snapshot.eachAttribute(function(name) { json[serverAttributeName(name)] = snapshot.attr(name); }) snapshot.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true }); } }); if (options.includeId) { json.ID_ = snapshot.id; } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```javascript { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = this._super.apply(this, arguments); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function serialize(snapshot, options) { var _this6 = this; var json = {}; if (options && options.includeId) { var id = snapshot.id; if (id) { json[get(this, 'primaryKey')] = id; } } snapshot.eachAttribute(function (key, attribute) { _this6.serializeAttribute(snapshot, json, key, attribute); }); snapshot.eachRelationship(function (key, relationship) { if (relationship.kind === 'belongsTo') { _this6.serializeBelongsTo(snapshot, json, relationship); } else if (relationship.kind === 'hasMany') { _this6.serializeHasMany(snapshot, json, relationship); } }); return json; }, /** You can use this method to customize how a serialized record is added to the complete JSON hash to be sent to the server. By default the JSON Serializer does not namespace the payload and just sends the raw serialized JSON object. If your server expects namespaced keys, you should consider using the RESTSerializer. Otherwise you can override this method to customize how the record is added to the hash. The hash property should be modified by reference. For example, your server may expect underscored root objects. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, snapshot, options) { var root = Ember.String.decamelize(type.modelName); data[root] = this.serialize(snapshot, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {DS.Model} typeClass @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function serializeIntoHash(hash, typeClass, snapshot, options) { assign(hash, this.serialize(snapshot, options)); }, /** `serializeAttribute` can be used to customize how `DS.attr` properties are serialized For example if you wanted to ensure all your attributes were always serialized as properties on an `attributes` object you could write: ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeAttribute: function(snapshot, json, key, attributes) { json.attributes = json.attributes || {}; this._super(snapshot, json.attributes, key, attributes); } }); ``` @method serializeAttribute @param {DS.Snapshot} snapshot @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function serializeAttribute(snapshot, json, key, attribute) { var type = attribute.type; if (this._canSerialize(key)) { var value = snapshot.attr(key); if (type) { var transform = this.transformFor(type); value = transform.serialize(value, attribute.options); } // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForAttribute) { payloadKey = this.keyForAttribute(key, 'serialize'); } json[payloadKey] = value; } }, /** `serializeBelongsTo` can be used to customize how `DS.belongsTo` properties are serialized. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeBelongsTo: function(snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo", "serialize") : key; json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.record.toJSON(); } }); ``` @method serializeBelongsTo @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeBelongsTo: function serializeBelongsTo(snapshot, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var belongsToId = snapshot.belongsTo(key, { id: true }); // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "belongsTo", "serialize"); } //Need to check whether the id is there for new&async records if (isNone(belongsToId)) { json[payloadKey] = null; } else { json[payloadKey] = belongsToId; } if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } }, /** `serializeHasMany` can be used to customize how `DS.hasMany` properties are serialized. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeHasMany: function(snapshot, json, relationship) { var key = relationship.key; if (key === 'comments') { return; } else { this._super.apply(this, arguments); } } }); ``` @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function serializeHasMany(snapshot, json, relationship) { var key = relationship.key; var shouldSerializeHasMany = '_shouldSerializeHasMany'; if (false) { shouldSerializeHasMany = 'shouldSerializeHasMany'; } if (this[shouldSerializeHasMany](snapshot, key, relationship)) { var hasMany = snapshot.hasMany(key, { ids: true }); if (hasMany !== undefined) { // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "hasMany", "serialize"); } json[payloadKey] = hasMany; // TODO support for polymorphic manyToNone and manyToMany relationships } } }, /** You can use this method to customize how polymorphic objects are serialized. Objects are considered to be polymorphic if `{ polymorphic: true }` is pass as the second argument to the `DS.belongsTo` function. Example ```app/serializers/comment.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializePolymorphicType: function(snapshot, json, relationship) { var key = relationship.key, belongsTo = snapshot.belongsTo(key); key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key; if (Ember.isNone(belongsTo)) { json[key + "_type"] = null; } else { json[key + "_type"] = belongsTo.modelName; } } }); ``` @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializePolymorphicType: _ember['default'].K, /** `extractMeta` is used to deserialize any meta information in the adapter payload. By default Ember Data expects meta information to be located on the `meta` property of the payload object. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ extractMeta: function(store, typeClass, payload) { if (payload && payload.hasOwnProperty('_pagination')) { let meta = payload._pagination; delete payload._pagination; return meta; } } }); ``` @method extractMeta @param {DS.Store} store @param {DS.Model} modelClass @param {Object} payload */ extractMeta: function extractMeta(store, modelClass, payload) { if (payload && payload['meta'] !== undefined) { var meta = payload.meta; delete payload.meta; return meta; } }, /** `extractErrors` is used to extract model errors when a call to `DS.Model#save` fails with an `InvalidError`. By default Ember Data expects error information to be located on the `errors` property of the payload object. This serializer expects this `errors` object to be an Array similar to the following, compliant with the JSON-API specification: ```js { "errors": [ { "detail": "This username is already taken!", "source": { "pointer": "data/attributes/username" } }, { "detail": "Doesn't look like a valid email.", "source": { "pointer": "data/attributes/email" } } ] } ``` The key `detail` provides a textual description of the problem. Alternatively, the key `title` can be used for the same purpose. The nested keys `source.pointer` detail which specific element of the request data was invalid. Note that JSON-API also allows for object-level errors to be placed in an object with pointer `data`, signifying that the problem cannot be traced to a specific attribute: ```javascript { "errors": [ { "detail": "Some generic non property error message", "source": { "pointer": "data" } } ] } ``` When turn into a `DS.Errors` object, you can read these errors through the property `base`: ```handlebars {{#each model.errors.base as |error|}} <div class="error"> {{error.message}} </div> {{/each}} ``` Example of alternative implementation, overriding the default behavior to deal with a different format of errors: ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ extractErrors: function(store, typeClass, payload, id) { if (payload && typeof payload === 'object' && payload._problems) { payload = payload._problems; this.normalizeErrors(typeClass, payload); } return payload; } }); ``` @method extractErrors @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @return {Object} json The deserialized errors */ extractErrors: function extractErrors(store, typeClass, payload, id) { var _this7 = this; if (payload && typeof payload === 'object' && payload.errors) { payload = (0, _emberDataAdaptersErrors.errorsArrayToHash)(payload.errors); this.normalizeUsingDeclaredMapping(typeClass, payload); typeClass.eachAttribute(function (name) { var key = _this7.keyForAttribute(name, 'deserialize'); if (key !== name && payload[key] !== undefined) { payload[name] = payload[key]; delete payload[key]; } }); typeClass.eachRelationship(function (name) { var key = _this7.keyForRelationship(name, 'deserialize'); if (key !== name && payload[key] !== undefined) { payload[name] = payload[key]; delete payload[key]; } }); } return payload; }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ keyForAttribute: function(attr, method) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @param {String} method @return {String} normalized key */ keyForAttribute: function keyForAttribute(key, method) { return key; }, /** `keyForRelationship` can be used to define a custom key when serializing and deserializing relationship properties. By default `JSONSerializer` does not provide an implementation of this method. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ keyForRelationship: function(key, relationship, method) { return 'rel_' + Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} typeClass @param {String} method @return {String} normalized key */ keyForRelationship: function keyForRelationship(key, typeClass, method) { return key; }, /** `keyForLink` can be used to define a custom key when deserializing link properties. @method keyForLink @param {String} key @param {String} kind `belongsTo` or `hasMany` @return {String} normalized key */ keyForLink: function keyForLink(key, kind) { return key; }, // HELPERS /** @method transformFor @private @param {String} attributeType @param {Boolean} skipAssertion @return {DS.Transform} transform */ transformFor: function transformFor(attributeType, skipAssertion) { var transform = (0, _emberDataPrivateUtils.getOwner)(this).lookup('transform:' + attributeType); (0, _emberDataPrivateDebug.assert)("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform); return transform; } }); if (false) { JSONSerializer.reopen({ /** @method modelNameFromPayloadType @public @param {String} type @return {String} the model's modelName */ modelNameFromPayloadType: function modelNameFromPayloadType(type) { return (0, _emberDataPrivateSystemNormalizeModelName['default'])(type); }, _hasCustomModelNameFromPayloadKey: function _hasCustomModelNameFromPayloadKey() { return this.modelNameFromPayloadKey !== JSONSerializer.prototype.modelNameFromPayloadKey; } }); } exports['default'] = JSONSerializer; }); define("ember-data/serializers/rest", ["exports", "ember", "ember-data/-private/debug", "ember-data/serializers/json", "ember-data/-private/system/normalize-model-name", "ember-inflector", "ember-data/-private/system/coerce-id", "ember-data/-private/utils", "ember-data/-private/features"], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializersJson, _emberDataPrivateSystemNormalizeModelName, _emberInflector, _emberDataPrivateSystemCoerceId, _emberDataPrivateUtils, _emberDataPrivateFeatures) { "use strict"; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];return arr2; } else { return Array.from(arr); } } /** @module ember-data */ var camelize = _ember["default"].String.camelize; /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method. This allows you to do whatever kind of munging you need, and is especially useful if your server is inconsistent and you need to do munging differently for many different kinds of responses. See the `normalize` documentation for more information. ## Across the Board Normalization There are also a number of hooks that you might find useful to define across-the-board rules for your payload. These rules will be useful if your server is consistent, or if you're building an adapter for an infrastructure service, like Firebase, and want to encode service conventions. For example, if all of your keys are underscored and all-caps, but otherwise consistent with the names you use in your models, you can implement across-the-board rules for how to convert an attribute name in your model to a key in your JSON. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ keyForAttribute: function(attr, method) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, the kind of relationship (`hasMany` or `belongsTo`) as the second parameter, and the method (`serialize` or `deserialize`) as the third parameter. @class RESTSerializer @namespace DS @extends DS.JSONSerializer */ var RESTSerializer = _emberDataSerializersJson["default"].extend({ /** `keyForPolymorphicType` can be used to define a custom key when serializing and deserializing a polymorphic type. By default, the returned key is `${key}Type`. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ keyForPolymorphicType: function(key, relationship) { var relationshipKey = this.keyForRelationship(key); return 'type-' + relationshipKey; } }); ``` @method keyForPolymorphicType @param {String} key @param {String} typeClass @param {String} method @return {String} normalized key */ keyForPolymorphicType: function keyForPolymorphicType(key, typeClass, method) { var relationshipKey = this.keyForRelationship(key); return relationshipKey + "Type"; }, /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. For example, if you have a payload that looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "id": 1, "body": "FIRST" }, { "id": 2, "body": "Rails is unagi" }] } ``` The `normalize` method will be called three times: * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }` * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }` * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }` You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. You will only need to implement `normalize` and manipulate the payload as desired. For example, if the `IDs` under `"comments"` are provided as `_id` instead of `id`, you can specify how to normalize just the comments: ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ normalize(model, hash, prop) { if (prop === 'comments') { hash.id = hash._id; delete hash._id; } return this._super(...arguments); } }); ``` On each call to the `normalize` method, the third parameter (`prop`) is always one of the keys that were in the original payload or in the result of another normalization as `normalizeResponse`. @method normalize @param {DS.Model} modelClass @param {Object} resourceHash @param {String} prop @return {Object} */ normalize: function normalize(modelClass, resourceHash, prop) { if (this.normalizeHash && this.normalizeHash[prop]) { (0, _emberDataPrivateDebug.deprecate)('`RESTSerializer.normalizeHash` has been deprecated. Please use `serializer.normalize` to modify the payload of single resources.', false, { id: 'ds.serializer.normalize-hash-deprecated', until: '3.0.0' }); this.normalizeHash[prop](resourceHash); } return this._super(modelClass, resourceHash); }, /** Normalizes an array of resource payloads and returns a JSON-API Document with primary data and, if any, included data as `{ data, included }`. @method _normalizeArray @param {DS.Store} store @param {String} modelName @param {Object} arrayHash @param {String} prop @return {Object} @private */ _normalizeArray: function _normalizeArray(store, modelName, arrayHash, prop) { var _this = this; var documentHash = { data: [], included: [] }; var modelClass = store.modelFor(modelName); var serializer = store.serializerFor(modelName); _ember["default"].makeArray(arrayHash).forEach(function (hash) { var _normalizePolymorphicRecord2 = _this._normalizePolymorphicRecord(store, hash, prop, modelClass, serializer); var data = _normalizePolymorphicRecord2.data; var included = _normalizePolymorphicRecord2.included; documentHash.data.push(data); if (included) { var _documentHash$included; (_documentHash$included = documentHash.included).push.apply(_documentHash$included, _toConsumableArray(included)); } }); return documentHash; }, _normalizePolymorphicRecord: function _normalizePolymorphicRecord(store, hash, prop, primaryModelClass, primarySerializer) { var serializer = primarySerializer; var modelClass = primaryModelClass; var primaryHasTypeAttribute = (0, _emberDataPrivateUtils.modelHasAttributeOrRelationshipNamedType)(primaryModelClass); if (!primaryHasTypeAttribute && hash.type) { // Support polymorphic records in async relationships var modelName = undefined; if (false) { modelName = this.modelNameFromPayloadType(hash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(hash.type); if (modelName !== deprecatedModelNameLookup && !this._hasCustomModelNameFromPayloadType() && this._hasCustomModelNameFromPayloadKey()) { (0, _emberDataPrivateDebug.deprecate)("You are using modelNameFromPayloadKey to normalize the type for a polymorphic relationship. This is has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.rest-serializer.deprecated-model-name-for-polymorphic-type', until: '3.0.0' }); modelName = deprecatedModelNameLookup; } } else { modelName = this.modelNameFromPayloadKey(hash.type); } if (store._hasModelFor(modelName)) { serializer = store.serializerFor(modelName); modelClass = store.modelFor(modelName); } } return serializer.normalize(modelClass, hash, prop); }, /* @method _normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @param {Boolean} isSingle @return {Object} JSON-API Document @private */ _normalizeResponse: function _normalizeResponse(store, primaryModelClass, payload, id, requestType, isSingle) { var documentHash = { data: null, included: [] }; var meta = this.extractMeta(store, primaryModelClass, payload); if (meta) { (0, _emberDataPrivateDebug.assert)('The `meta` returned from `extractMeta` has to be an object, not "' + _ember["default"].typeOf(meta) + '".', _ember["default"].typeOf(meta) === 'object'); documentHash.meta = meta; } var keys = Object.keys(payload); for (var i = 0, _length = keys.length; i < _length; i++) { var prop = keys[i]; var modelName = prop; var forcedSecondary = false; /* If you want to provide sideloaded records of the same type that the primary data you can do that by prefixing the key with `_`. Example ``` { users: [ { id: 1, title: 'Tom', manager: 3 }, { id: 2, title: 'Yehuda', manager: 3 } ], _users: [ { id: 3, title: 'Tomster' } ] } ``` This forces `_users` to be added to `included` instead of `data`. */ if (prop.charAt(0) === '_') { forcedSecondary = true; modelName = prop.substr(1); } var typeName = this.modelNameFromPayloadKey(modelName); if (!store.modelFactoryFor(typeName)) { (0, _emberDataPrivateDebug.warn)(this.warnMessageNoModelForKey(modelName, typeName), false, { id: 'ds.serializer.model-for-key-missing' }); continue; } var isPrimary = !forcedSecondary && this.isPrimaryType(store, typeName, primaryModelClass); var value = payload[prop]; if (value === null) { continue; } (0, _emberDataPrivateDebug.runInDebug)(function () { var isQueryRecordAnArray = requestType === 'queryRecord' && isPrimary && Array.isArray(value); var message = "The adapter returned an array for the primary data of a `queryRecord` response. This is deprecated as `queryRecord` should return a single record."; (0, _emberDataPrivateDebug.deprecate)(message, !isQueryRecordAnArray, { id: 'ds.serializer.rest.queryRecord-array-response', until: '3.0' }); }); /* Support primary data as an object instead of an array. Example ``` { user: { id: 1, title: 'Tom', manager: 3 } } ``` */ if (isPrimary && _ember["default"].typeOf(value) !== 'array') { var _normalizePolymorphicRecord3 = this._normalizePolymorphicRecord(store, value, prop, primaryModelClass, this); var _data = _normalizePolymorphicRecord3.data; var _included = _normalizePolymorphicRecord3.included; documentHash.data = _data; if (_included) { var _documentHash$included2; (_documentHash$included2 = documentHash.included).push.apply(_documentHash$included2, _toConsumableArray(_included)); } continue; } var _normalizeArray2 = this._normalizeArray(store, typeName, value, prop); var data = _normalizeArray2.data; var included = _normalizeArray2.included; if (included) { var _documentHash$included3; (_documentHash$included3 = documentHash.included).push.apply(_documentHash$included3, _toConsumableArray(included)); } if (isSingle) { data.forEach(function (resource) { /* Figures out if this is the primary record or not. It's either: 1. The record with the same ID as the original request 2. If it's a newly created record without an ID, the first record in the array */ var isUpdatedRecord = isPrimary && (0, _emberDataPrivateSystemCoerceId["default"])(resource.id) === id; var isFirstCreatedRecord = isPrimary && !id && !documentHash.data; if (isFirstCreatedRecord || isUpdatedRecord) { documentHash.data = resource; } else { documentHash.included.push(resource); } }); } else { if (isPrimary) { documentHash.data = data; } else { if (data) { var _documentHash$included4; (_documentHash$included4 = documentHash.included).push.apply(_documentHash$included4, _toConsumableArray(data)); } } } } return documentHash; }, isPrimaryType: function isPrimaryType(store, typeName, primaryTypeClass) { var typeClass = store.modelFor(typeName); return typeClass.modelName === primaryTypeClass.modelName; }, /** This method allows you to push a payload containing top-level collections of records organized per type. ```js { "posts": [{ "id": "1", "title": "Rails is omakase", "author", "1", "comments": [ "1" ] }], "comments": [{ "id": "1", "body": "FIRST" }], "users": [{ "id": "1", "name": "@d2h" }] } ``` It will first normalize the payload, so you can use this to push in data streaming in from your server structured the same way that fetches and saves are structured. @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function pushPayload(store, payload) { var documentHash = { data: [], included: [] }; for (var prop in payload) { var modelName = this.modelNameFromPayloadKey(prop); if (!store.modelFactoryFor(modelName)) { (0, _emberDataPrivateDebug.warn)(this.warnMessageNoModelForKey(prop, modelName), false, { id: 'ds.serializer.model-for-key-missing' }); continue; } var type = store.modelFor(modelName); var typeSerializer = store.serializerFor(type.modelName); _ember["default"].makeArray(payload[prop]).forEach(function (hash) { var _typeSerializer$normalize = typeSerializer.normalize(type, hash, prop); var data = _typeSerializer$normalize.data; var included = _typeSerializer$normalize.included; documentHash.data.push(data); if (included) { var _documentHash$included5; (_documentHash$included5 = documentHash.included).push.apply(_documentHash$included5, _toConsumableArray(included)); } }); } if (false) { return store.push(documentHash); } else { store.push(documentHash); } }, /** This method is used to convert each JSON root key in the payload into a modelName that it can use to look up the appropriate model for that part of the payload. For example, your server may send a model name that does not correspond with the name of the model in your app. Let's take a look at an example model, and an example payload: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ }); ``` ```javascript { "blog/post": { "id": "1 } } ``` Ember Data is going to normalize the payload's root key for the modelName. As a result, it will try to look up the "blog/post" model. Since we don't have a model called "blog/post" (or a file called app/models/blog/post.js in ember-cli), Ember Data will throw an error because it cannot find the "blog/post" model. Since we want to remove this namespace, we can define a serializer for the application that will remove "blog/" from the payload key whenver it's encountered by Ember Data: ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ modelNameFromPayloadKey: function(payloadKey) { if (payloadKey === 'blog/post') { return this._super(payloadKey.replace('blog/', '')); } else { return this._super(payloadKey); } } }); ``` After refreshing, Ember Data will appropriately look up the "post" model. By default the modelName for a model is its name in dasherized form. This means that a payload key like "blogPost" would be normalized to "blog-post" when Ember Data looks up the model. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `modelNameFromPayloadKey` for this purpose. @method modelNameFromPayloadKey @param {String} key @return {String} the model's modelName */ modelNameFromPayloadKey: function modelNameFromPayloadKey(key) { return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName["default"])(key)); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```js { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = { POST_TTL: snapshot.attr('title'), POST_BDY: snapshot.attr('body'), POST_CMS: snapshot.hasMany('comments', { ids: true }) } if (options.includeId) { json.POST_ID_ = snapshot.id; } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = {}; snapshot.eachAttribute(function(name) { json[serverAttributeName(name)] = snapshot.attr(name); }) snapshot.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true }); } }); if (options.includeId) { json.ID_ = snapshot.id; } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```js { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = this._super(snapshot, options); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function serialize(snapshot, options) { return this._super.apply(this, arguments); }, /** You can use this method to customize the root keys serialized into the JSON. The hash property should be modified by reference (possibly using something like _.extend) By default the REST Serializer sends the modelName of a model, which is a camelized version of the name. For example, your server may expect underscored root objects. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.modelName); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {DS.Model} typeClass @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function serializeIntoHash(hash, typeClass, snapshot, options) { var normalizedRootKey = this.payloadKeyFromModelName(typeClass.modelName); hash[normalizedRootKey] = this.serialize(snapshot, options); }, /** You can use `payloadKeyFromModelName` to override the root key for an outgoing request. By default, the RESTSerializer returns a camelized version of the model's name. For a model called TacoParty, its `modelName` would be the string `taco-party`. The RESTSerializer will send it to the server with `tacoParty` as the root key in the JSON payload: ```js { "tacoParty": { "id": "1", "location": "Matthew Beale's House" } } ``` For example, your server may expect dasherized root objects: ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ payloadKeyFromModelName: function(modelName) { return Ember.String.dasherize(modelName); } }); ``` Given a `TacoParty` model, calling `save` on it would produce an outgoing request like: ```js { "taco-party": { "id": "1", "location": "Matthew Beale's House" } } ``` @method payloadKeyFromModelName @param {String} modelName @return {String} */ payloadKeyFromModelName: function payloadKeyFromModelName(modelName) { return camelize(modelName); }, /** You can use this method to customize how polymorphic objects are serialized. By default the REST Serializer creates the key by appending `Type` to the attribute and value from the model's camelcased model name. @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializePolymorphicType: function serializePolymorphicType(snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); var typeKey = this.keyForPolymorphicType(key, relationship.type, 'serialize'); // old way of getting the key for the polymorphic type key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key; key = key + "Type"; // The old way of serializing the type of a polymorphic record used // `keyForAttribute`, which is not correct. The next code checks if the old // way is used and if it differs from the new way of using // `keyForPolymorphicType`. If this is the case, a deprecation warning is // logged and the old way is restored (so nothing breaks). if (key !== typeKey && this.keyForPolymorphicType === RESTSerializer.prototype.keyForPolymorphicType) { (0, _emberDataPrivateDebug.deprecate)("The key to serialize the type of a polymorphic record is created via keyForAttribute which has been deprecated. Use the keyForPolymorphicType hook instead.", false, { id: 'ds.rest-serializer.deprecated-key-for-polymorphic-type', until: '3.0.0' }); typeKey = key; } if (_ember["default"].isNone(belongsTo)) { json[typeKey] = null; } else { if (false) { json[typeKey] = this.payloadTypeFromModelName(belongsTo.modelName); } else { json[typeKey] = camelize(belongsTo.modelName); } } }, /** You can use this method to customize how a polymorphic relationship should be extracted. @method extractPolymorphicRelationship @param {Object} relationshipType @param {Object} relationshipHash @param {Object} relationshipOptions @return {Object} */ extractPolymorphicRelationship: function extractPolymorphicRelationship(relationshipType, relationshipHash, relationshipOptions) { var key = relationshipOptions.key; var resourceHash = relationshipOptions.resourceHash; var relationshipMeta = relationshipOptions.relationshipMeta; // A polymorphic belongsTo relationship can be present in the payload // either in the form where the `id` and the `type` are given: // // { // message: { id: 1, type: 'post' } // } // // or by the `id` and a `<relationship>Type` attribute: // // { // message: 1, // messageType: 'post' // } // // The next code checks if the latter case is present and returns the // corresponding JSON-API representation. The former case is handled within // the base class JSONSerializer. var isPolymorphic = relationshipMeta.options.polymorphic; var typeProperty = this.keyForPolymorphicType(key, relationshipType, 'deserialize'); if (isPolymorphic && resourceHash[typeProperty] !== undefined && typeof relationshipHash !== 'object') { if (false) { var payloadType = resourceHash[typeProperty]; var type = this.modelNameFromPayloadType(payloadType); var deprecatedTypeLookup = this.modelNameFromPayloadKey(payloadType); if (payloadType !== deprecatedTypeLookup && !this._hasCustomModelNameFromPayloadType() && this._hasCustomModelNameFromPayloadKey()) { (0, _emberDataPrivateDebug.deprecate)("You are using modelNameFromPayloadKey to normalize the type for a polymorphic relationship. This has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.rest-serializer.deprecated-model-name-for-polymorphic-type', until: '3.0.0' }); type = deprecatedTypeLookup; } return { id: relationshipHash, type: type }; } else { var type = this.modelNameFromPayloadKey(resourceHash[typeProperty]); return { id: relationshipHash, type: type }; } } return this._super.apply(this, arguments); } }); if (false) { RESTSerializer.reopen({ /** `modelNameFromPayloadType` can be used to change the mapping for a DS model name, taken from the value in the payload. Say your API namespaces the type of a model and returns the following payload for the `post` model, which has a polymorphic `user` relationship: ```javascript // GET /api/posts/1 { "post": { "id": 1, "user": 1, "userType: "api::v1::administrator" } } ``` By overwriting `modelNameFromPayloadType` you can specify that the `administrator` model should be used: ```app/serializers/application.js import DS from "ember-data"; export default DS.RESTSerializer.extend({ modelNameFromPayloadType(payloadType) { return payloadType.replace('api::v1::', ''); } }); ``` By default the modelName for a model is its name in dasherized form. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `modelNameFromPayloadType` for this purpose. Also take a look at [payloadTypeFromModelName](#method_payloadTypeFromModelName) to customize how the type of a record should be serialized. @method modelNameFromPayloadType @public @param {String} payloadType type from payload @return {String} modelName */ modelNameFromPayloadType: function modelNameFromPayloadType(payloadType) { return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName["default"])(payloadType)); }, /** `payloadTypeFromModelName` can be used to change the mapping for the type in the payload, taken from the model name. Say your API namespaces the type of a model and expects the following payload when you update the `post` model, which has a polymorphic `user` relationship: ```javascript // POST /api/posts/1 { "post": { "id": 1, "user": 1, "userType": "api::v1::administrator" } } ``` By overwriting `payloadTypeFromModelName` you can specify that the namespaces model name for the `administrator` should be used: ```app/serializers/application.js import DS from "ember-data"; export default DS.RESTSerializer.extend({ payloadTypeFromModelName(modelName) { return "api::v1::" + modelName; } }); ``` By default the payload type is the camelized model name. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `payloadTypeFromModelName` for this purpose. Also take a look at [modelNameFromPayloadType](#method_modelNameFromPayloadType) to customize how the model name from should be mapped from the payload. @method payloadTypeFromModelName @public @param {String} modelname modelName from the record @return {String} payloadType */ payloadTypeFromModelName: function payloadTypeFromModelName(modelName) { return camelize(modelName); }, _hasCustomModelNameFromPayloadKey: function _hasCustomModelNameFromPayloadKey() { return this.modelNameFromPayloadKey !== RESTSerializer.prototype.modelNameFromPayloadKey; }, _hasCustomModelNameFromPayloadType: function _hasCustomModelNameFromPayloadType() { return this.modelNameFromPayloadType !== RESTSerializer.prototype.modelNameFromPayloadType; }, _hasCustomPayloadTypeFromModelName: function _hasCustomPayloadTypeFromModelName() { return this.payloadTypeFromModelName !== RESTSerializer.prototype.payloadTypeFromModelName; }, _hasCustomPayloadKeyFromModelName: function _hasCustomPayloadKeyFromModelName() { return this.payloadKeyFromModelName !== RESTSerializer.prototype.payloadKeyFromModelName; } }); } (0, _emberDataPrivateDebug.runInDebug)(function () { RESTSerializer.reopen({ warnMessageNoModelForKey: function warnMessageNoModelForKey(prop, typeKey) { return 'Encountered "' + prop + '" in payload, but no model was found for model name "' + typeKey + '" (resolved model name using ' + this.constructor.toString() + '.modelNameFromPayloadKey("' + prop + '"))'; } }); }); exports["default"] = RESTSerializer; }); define('ember-data/setup-container', ['exports', 'ember-data/-private/initializers/store', 'ember-data/-private/initializers/transforms', 'ember-data/-private/initializers/store-injections', 'ember-data/-private/initializers/data-adapter'], function (exports, _emberDataPrivateInitializersStore, _emberDataPrivateInitializersTransforms, _emberDataPrivateInitializersStoreInjections, _emberDataPrivateInitializersDataAdapter) { 'use strict'; exports['default'] = setupContainer; function setupContainer(application) { (0, _emberDataPrivateInitializersDataAdapter['default'])(application); (0, _emberDataPrivateInitializersTransforms['default'])(application); (0, _emberDataPrivateInitializersStoreInjections['default'])(application); (0, _emberDataPrivateInitializersStore['default'])(application); } }); define("ember-data/store", ["exports", "ember-data/-private/system/store"], function (exports, _emberDataPrivateSystemStore) { "use strict"; exports["default"] = _emberDataPrivateSystemStore["default"]; }); define('ember-data/transform', ['exports', 'ember'], function (exports, _ember) { 'use strict'; /** The `DS.Transform` class is used to serialize and deserialize model attributes when they are saved or loaded from an adapter. Subclassing `DS.Transform` is useful for creating custom attributes. All subclasses of `DS.Transform` must implement a `serialize` and a `deserialize` method. Example ```app/transforms/temperature.js import DS from 'ember-data'; // Converts centigrade in the JSON to fahrenheit in the app export default DS.Transform.extend({ deserialize: function(serialized) { return (serialized * 1.8) + 32; }, serialize: function(deserialized) { return (deserialized - 32) / 1.8; } }); ``` Usage ```app/models/requirement.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr('string'), temperature: DS.attr('temperature') }); ``` @class Transform @namespace DS */ exports['default'] = _ember['default'].Object.extend({ /** When given a deserialized value from a record attribute this method must return the serialized value. Example ```javascript serialize: function(deserialized, options) { return Ember.isEmpty(deserialized) ? null : Number(deserialized); } ``` @method serialize @param deserialized The deserialized value @param options hash of options passed to `DS.attr` @return The serialized value */ serialize: null, /** When given a serialize value from a JSON object this method must return the deserialized value for the record attribute. Example ```javascript deserialize: function(serialized, options) { return empty(serialized) ? null : Number(serialized); } ``` @method deserialize @param serialized The serialized value @param options hash of options passed to `DS.attr` @return The deserialized value */ deserialize: null }); }); define("ember-data/version", ["exports"], function (exports) { "use strict"; exports["default"] = "2.8.1"; }); define("ember-getowner-polyfill/index", ["exports", "ember"], function (exports, _ember) { "use strict"; _ember["default"].deprecate("ember-getowner-polyfill is now a true polyfill. Use Ember.getOwner directly instead of importing from ember-getowner-polyfill", false, { id: "ember-getowner-polyfill.import", until: '2.0.0' }); exports["default"] = _ember["default"].getOwner; }); define('ember-i18n/config/ar', ['exports', 'ember-i18n/config/constants'], function (exports, _emberI18nConfigConstants) { 'use strict'; exports['default'] = { rtl: true, pluralForm: function pluralForm(n) { var mod100 = n % 100; if (n === 0) { return _emberI18nConfigConstants.ZERO; } if (n === 1) { return _emberI18nConfigConstants.ONE; } if (n === 2) { return _emberI18nConfigConstants.TWO; } if (mod100 >= 3 && mod100 <= 10) { return _emberI18nConfigConstants.FEW; } if (mod100 >= 11 && mod100 <= 99) { return _emberI18nConfigConstants.MANY; } return _emberI18nConfigConstants.OTHER; } }; }); define('ember-i18n/config/bn', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define('ember-i18n/config/constants', ['exports'], function (exports) { 'use strict'; var ZERO = 'zero'; exports.ZERO = ZERO; var ONE = 'one'; exports.ONE = ONE; var TWO = 'two'; exports.TWO = TWO; var FEW = 'few'; exports.FEW = FEW; var MANY = 'many'; exports.MANY = MANY; var OTHER = 'other'; exports.OTHER = OTHER; }); define('ember-i18n/config/de', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define("ember-i18n/config/en", ["exports", "ember-i18n/config/constants"], function (exports, _emberI18nConfigConstants) { "use strict"; exports["default"] = { rtl: false, pluralForm: function pluralForm(n) { if (n === 1) { return _emberI18nConfigConstants.ONE; } return _emberI18nConfigConstants.OTHER; } }; }); define('ember-i18n/config/es', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define('ember-i18n/config/fa', ['exports', 'ember-i18n/config/zh'], function (exports, _emberI18nConfigZh) { 'use strict'; exports['default'] = _emberI18nConfigZh['default']; }); define("ember-i18n/config/fr", ["exports", "ember-i18n/config/constants"], function (exports, _emberI18nConfigConstants) { "use strict"; exports["default"] = { rtl: false, pluralForm: function pluralForm(n) { if (n >= 0 && n < 2) { return _emberI18nConfigConstants.ONE; } return _emberI18nConfigConstants.OTHER; } }; }); define('ember-i18n/config/fy', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define('ember-i18n/config/he', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = { rtl: true, pluralForm: _emberI18nConfigEn['default'].pluralForm }; }); define("ember-i18n/config/hi", ["exports", "ember-i18n/config/constants"], function (exports, _emberI18nConfigConstants) { "use strict"; exports["default"] = { rtl: false, pluralForm: function pluralForm(n) { if (n === 0) { return _emberI18nConfigConstants.ONE; } if (n === 1) { return _emberI18nConfigConstants.ONE; } return _emberI18nConfigConstants.OTHER; } }; }); define('ember-i18n/config/it', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define("ember-i18n/config/iw", ["exports", "ember-i18n/config/he"], function (exports, _emberI18nConfigHe) { "use strict"; exports["default"] = _emberI18nConfigHe["default"]; }); define('ember-i18n/config/ja', ['exports', 'ember-i18n/config/zh'], function (exports, _emberI18nConfigZh) { 'use strict'; exports['default'] = _emberI18nConfigZh['default']; }); define('ember-i18n/config/jv', ['exports', 'ember-i18n/config/zh'], function (exports, _emberI18nConfigZh) { 'use strict'; exports['default'] = _emberI18nConfigZh['default']; }); define('ember-i18n/config/ko', ['exports', 'ember-i18n/config/zh'], function (exports, _emberI18nConfigZh) { 'use strict'; exports['default'] = _emberI18nConfigZh['default']; }); define('ember-i18n/config/mr', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define('ember-i18n/config/ms', ['exports', 'ember-i18n/config/zh'], function (exports, _emberI18nConfigZh) { 'use strict'; exports['default'] = _emberI18nConfigZh['default']; }); define('ember-i18n/config/nl', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define('ember-i18n/config/no', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define('ember-i18n/config/pa', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define('ember-i18n/config/pl', ['exports', 'ember-i18n/config/constants'], function (exports, _emberI18nConfigConstants) { 'use strict'; exports['default'] = { rtl: false, pluralForm: function pluralForm(n) { var mod1 = n % 1; var mod10 = n % 10; var mod100 = n % 100; if (n === 1) { return _emberI18nConfigConstants.ONE; } if (mod1 === 0 && mod10 >= 2 && mod10 <= 4 && !(mod100 >= 12 && mod100 <= 14)) { return _emberI18nConfigConstants.FEW; } if (mod1 === 0 && (mod10 === 0 || mod10 === 1 || mod10 >= 5 && mod10 <= 9 || mod100 >= 12 && mod100 <= 14)) { return _emberI18nConfigConstants.MANY; } return _emberI18nConfigConstants.OTHER; } }; }); define('ember-i18n/config/pt', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define('ember-i18n/config/ru', ['exports', 'ember-i18n/config/constants'], function (exports, _emberI18nConfigConstants) { 'use strict'; exports['default'] = { rtl: false, pluralForm: function pluralForm(n) { var mod1 = n % 1; var mod10 = n % 10; var mod100 = n % 100; if (mod10 === 1 && mod100 !== 11) { return _emberI18nConfigConstants.ONE; } if (mod1 === 0 && mod10 >= 2 && mod10 <= 4 && !(mod100 >= 12 && mod100 <= 14)) { return _emberI18nConfigConstants.FEW; } if (mod1 === 0 && (mod10 === 0 || mod10 >= 5 && mod10 <= 9 || mod100 >= 11 && mod100 <= 14)) { return _emberI18nConfigConstants.MANY; } return _emberI18nConfigConstants.OTHER; } }; }); define('ember-i18n/config/sv', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define('ember-i18n/config/ta', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define('ember-i18n/config/te', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define('ember-i18n/config/tr', ['exports', 'ember-i18n/config/zh'], function (exports, _emberI18nConfigZh) { 'use strict'; exports['default'] = _emberI18nConfigZh['default']; }); define('ember-i18n/config/ur', ['exports', 'ember-i18n/config/en'], function (exports, _emberI18nConfigEn) { 'use strict'; exports['default'] = _emberI18nConfigEn['default']; }); define('ember-i18n/config/vi', ['exports', 'ember-i18n/config/zh'], function (exports, _emberI18nConfigZh) { 'use strict'; exports['default'] = _emberI18nConfigZh['default']; }); define('ember-i18n/config/zh', ['exports', 'ember-i18n/config/constants'], function (exports, _emberI18nConfigConstants) { 'use strict'; exports['default'] = { rtl: false, pluralForm: function pluralForm() /* n */{ return _emberI18nConfigConstants.OTHER; } }; }); define('ember-i18n/helper', ['exports', 'ember'], function (exports, _ember) { 'use strict'; function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } var get = _ember['default'].get; var inject = _ember['default'].inject; var Helper = _ember['default'].Helper; var EmberObject = _ember['default'].Object; var observer = _ember['default'].observer; function mergedContext(objectContext, hashContext) { return EmberObject.extend({ unknownProperty: function unknownProperty(key) { var fromHash = get(hashContext, key); return fromHash === undefined ? get(objectContext, key) : fromHash; } }).create(); } exports['default'] = Helper.extend({ i18n: inject.service(), compute: function compute(_ref, interpolations) { var _ref2 = _toArray(_ref); var key = _ref2[0]; var _ref2$1 = _ref2[1]; var contextObject = _ref2$1 === undefined ? {} : _ref2$1; var rest = _ref2.slice(2); var mergedInterpolations = mergedContext(contextObject, interpolations); var i18n = get(this, 'i18n'); return i18n.t(key, mergedInterpolations); }, _recomputeOnLocaleChange: observer('i18n.locale', function () { this.recompute(); }) }); }); define("ember-i18n/index", ["exports", "ember-i18n/utils/i18n/compile-template", "ember-i18n/services/i18n", "ember-i18n/utils/macro"], function (exports, _emberI18nUtilsI18nCompileTemplate, _emberI18nServicesI18n, _emberI18nUtilsMacro) { "use strict"; exports.compileTemplate = _emberI18nUtilsI18nCompileTemplate["default"]; exports.Service = _emberI18nServicesI18n["default"]; exports.translationMacro = _emberI18nUtilsMacro["default"]; }); define('ember-i18n/initializers/ember-i18n', ['exports'], function (exports) { // As of 4.3.0 using the ember-i18n initializer is no longer necessary. // // This is a no-op initializer to prevent applications that relied on the // 'ember-i18n' initializer in their own workflow from breaking. 'use strict'; exports['default'] = { name: 'ember-i18n', initialize: function initialize() { // No-op. } }; }); define('ember-i18n/instance-initializers/ember-i18n', ['exports'], function (exports) { // As of 4.3.0 using the ember-i18n instance initializer is no longer // necessary. // // This is a no-op initializer to prevent applications that relied on the // 'ember-i18n' instance initializer in their own workflow from breaking. 'use strict'; exports['default'] = { name: 'ember-i18n', initialize: function initialize() { // No-op. } }; }); define("ember-i18n/services/i18n", ["exports", "ember", "ember-i18n/utils/locale", "ember-i18n/utils/add-translations", "ember-i18n/utils/get-locales"], function (exports, _ember, _emberI18nUtilsLocale, _emberI18nUtilsAddTranslations, _emberI18nUtilsGetLocales) { "use strict"; var assert = _ember["default"].assert; var computed = _ember["default"].computed; var get = _ember["default"].get; var Evented = _ember["default"].Evented; var makeArray = _ember["default"].makeArray; var on = _ember["default"].on; var typeOf = _ember["default"].typeOf; var warn = _ember["default"].warn; var getOwner = _ember["default"].getOwner; var Parent = _ember["default"].Service || _ember["default"].Object; // @public exports["default"] = Parent.extend(Evented, { // @public // The user's locale. locale: null, // @public // A list of found locales. locales: computed(_emberI18nUtilsGetLocales["default"]), // @public // // Returns the translation `key` interpolated with `data` // in the current `locale`. t: function t(key) { var data = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _ember["default"].deprecate('locale is a reserved attribute', data['locale'] === undefined, { id: 'ember-i18n.reserve-locale', until: '5.0.0' }); _ember["default"].deprecate('htmlSafe is a reserved attribute', data['htmlSafe'] === undefined, { id: 'ember-i18n.reserve-htmlSafe', until: '5.0.0' }); var locale = this.get('_locale'); assert("I18n: Cannot translate when locale is null", locale); var count = get(data, 'count'); var defaults = makeArray(get(data, 'default')); defaults.unshift(key); var template = locale.getCompiledTemplate(defaults, count); if (template._isMissing) { this.trigger('missing', this.get('locale'), key, data); } return template(data); }, // @public exists: function exists(key) { var data = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var locale = this.get('_locale'); assert("I18n: Cannot check existance when locale is null", locale); var count = get(data, 'count'); var translation = locale.findTranslation(makeArray(key), count); return typeOf(translation.result) !== 'undefined' && !translation.result._isMissing; }, // @public addTranslations: function addTranslations(locale, translations) { (0, _emberI18nUtilsAddTranslations["default"])(locale, translations, getOwner(this)); this._addLocale(locale); if (this.get('locale').indexOf(locale) === 0) { this.get('_locale').rebuild(); } }, // @private _initDefaults: on('init', function () { var ENV = getOwner(this)._lookupFactory('config:environment'); if (this.get('locale') == null) { var defaultLocale = (ENV.i18n || {}).defaultLocale; if (defaultLocale == null) { warn('ember-i18n did not find a default locale; falling back to "en".', false, { id: 'ember-i18n.default-locale' }); defaultLocale = 'en'; } this.set('locale', defaultLocale); } }), // @private // // adds a runtime locale to the array of locales on disk _addLocale: function _addLocale(locale) { this.get('locales').addObject(locale); }, _locale: computed('locale', function () { var locale = this.get('locale'); return locale ? new _emberI18nUtilsLocale["default"](this.get('locale'), getOwner(this)) : null; }) }); }); define("ember-i18n/utils/add-translations", ["exports", "ember"], function (exports, _ember) { "use strict"; exports["default"] = addTranslations; var assign = _ember["default"].assign || _ember["default"].merge; function addTranslations(locale, newTranslations, owner) { var key = "locale:" + locale + "/translations"; var existingTranslations = owner._lookupFactory(key); if (existingTranslations == null) { existingTranslations = {}; owner.register(key, existingTranslations); } assign(existingTranslations, newTranslations); } }); define('ember-i18n/utils/get-locales', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports['default'] = getLocales; var matchKey = '/locales/(.+)/translations$'; function getLocales() { return Object.keys(requirejs.entries).reduce(function (locales, module) { var match = module.match(matchKey); if (match) { locales.pushObject(match[1]); } return locales; }, _ember['default'].A()).sort(); } }); define("ember-i18n/utils/i18n/compile-template", ["exports", "ember"], function (exports, _ember) { "use strict"; exports["default"] = compileTemplate; var htmlSafe = _ember["default"].String.htmlSafe; var get = _ember["default"].get; var escapeExpression = _ember["default"].Handlebars.Utils.escapeExpression; var tripleStache = /\{\{\{\s*(.*?)\s*\}\}\}/g; var doubleStache = /\{\{\s*(.*?)\s*\}\}/g; // @public // // Compile a translation template. // // To override this, define `util:i18n/compile-template` with // the signature // `Function(String, Boolean) -> Function(Object) -> String`. function compileTemplate(template) { var rtl = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; return function renderTemplate(data) { var result = template.replace(tripleStache, function (i, match) { return get(data, match); }).replace(doubleStache, function (i, match) { return escapeExpression(get(data, match)); }); var wrapped = rtl ? "" + result + "" : result; return htmlSafe(wrapped); }; } }); define("ember-i18n/utils/i18n/missing-message", ["exports"], function (exports) { "use strict"; exports["default"] = missingMessage; // @public // // Generate a "missing template" message that will be used // as a translation. // // To override this, define `util:i18n/missing-message` with // the signature // // `Function(String, String, Object) -> String`. function missingMessage(locale, key /*, data */) { return "Missing translation: " + key; } }); define('ember-i18n/utils/locale', ['exports', 'ember'], function (exports, _ember) { 'use strict'; var assert = _ember['default'].assert; var typeOf = _ember['default'].typeOf; var warn = _ember['default'].warn; var assign = _ember['default'].assign || _ember['default'].merge; // @private // // This class is the work-horse of localization look-up. function Locale(id, owner) { // On Construction: // 1. look for translations in the locale (e.g. pt-BR) and all parent // locales (e.g. pt), flatten any nested keys, and then merge them. // 2. walk through the configs from most specific to least specific // and use the first value for `rtl` and `pluralForm` // 3. Default `rtl` to `false` // 4. Ensure `pluralForm` is defined this.id = id; this.owner = owner; this.rebuild(); } Locale.prototype = { rebuild: function rebuild() { this.translations = getFlattenedTranslations(this.id, this.owner); this._setConfig(); }, _setConfig: function _setConfig() { var _this = this; walkConfigs(this.id, this.owner, function (config) { if (_this.rtl === undefined) { _this.rtl = config.rtl; } if (_this.pluralForm === undefined) { _this.pluralForm = config.pluralForm; } }); var defaultConfig = this.owner._lookupFactory('ember-i18n@config:zh'); if (this.rtl === undefined) { warn('ember-i18n: No RTL configuration found for ' + this.id + '.', false, { id: 'ember-i18n.no-rtl-configuration' }); this.rtl = defaultConfig.rtl; } if (this.pluralForm === undefined) { warn('ember-i18n: No pluralForm configuration found for ' + this.id + '.', false, { id: 'ember-i18n.no-plural-form' }); this.pluralForm = defaultConfig.pluralForm; } }, getCompiledTemplate: function getCompiledTemplate(fallbackChain, count) { var translation = this.findTranslation(fallbackChain, count); var result = translation.result; if (typeOf(result) === 'string') { result = this._compileTemplate(translation.key, result); } if (result == null) { result = this._defineMissingTranslationTemplate(fallbackChain[0]); } assert('Template for ' + translation.key + ' in ' + this.id + ' is not a function', typeOf(result) === 'function'); return result; }, findTranslation: function findTranslation(fallbackChain, count) { if (this.translations === undefined) { this._init(); } var result = undefined; var i = undefined; for (i = 0; i < fallbackChain.length; i++) { var key = fallbackChain[i]; if (count != null) { var inflection = this.pluralForm(+count); result = this.translations[key + '.' + inflection]; } if (result == null) { result = this.translations[key]; } if (result) { break; } } return { key: fallbackChain[i], result: result }; }, _defineMissingTranslationTemplate: function _defineMissingTranslationTemplate(key) { var i18n = this.owner.lookup('service:i18n'); var missingMessage = this.owner._lookupFactory('util:i18n/missing-message'); var locale = this.id; function missingTranslation(data) { return missingMessage.call(i18n, locale, key, data); } missingTranslation._isMissing = true; this.translations[key] = missingTranslation; return missingTranslation; }, _compileTemplate: function _compileTemplate(key, string) { var compile = this.owner._lookupFactory('util:i18n/compile-template'); var template = compile(string, this.rtl); this.translations[key] = template; return template; } }; function getFlattenedTranslations(id, owner) { var result = {}; var parentId = parentLocale(id); if (parentId) { assign(result, getFlattenedTranslations(parentId, owner)); } var translations = owner._lookupFactory('locale:' + id + '/translations') || {}; assign(result, withFlattenedKeys(translations)); return result; } // Walk up confiugration objects from most specific to least. function walkConfigs(id, owner, fn) { var appConfig = owner._lookupFactory('locale:' + id + '/config'); if (appConfig) { fn(appConfig); } var addonConfig = owner._lookupFactory('ember-i18n@config:' + id); if (addonConfig) { fn(addonConfig); } var parentId = parentLocale(id); if (parentId) { walkConfigs(parentId, owner, fn); } } function parentLocale(id) { var lastDash = id.lastIndexOf('-'); return lastDash > 0 ? id.substr(0, lastDash) : null; } function withFlattenedKeys(object) { var result = {}; Object.keys(object).forEach(function (key) { var value = object[key]; if (typeOf(value) === 'object') { value = withFlattenedKeys(value); Object.keys(value).forEach(function (suffix) { result[key + '.' + suffix] = value[suffix]; }); } else { result[key] = value; } }); return result; } exports['default'] = Locale; }); define('ember-i18n/utils/macro', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports['default'] = createTranslatedComputedProperty; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];return arr2; } else { return Array.from(arr); } } var keys = Object.keys; var get = _ember['default'].get; // @public function createTranslatedComputedProperty(key) { var interpolations = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var dependencies = ['i18n.locale'].concat(values(interpolations)); return _ember['default'].computed.apply(_ember['default'], _toConsumableArray(dependencies).concat([function () { var i18n = get(this, 'i18n'); _ember['default'].assert('Cannot translate ' + key + '. ' + this + ' does not have an i18n.', i18n); return i18n.t(key, mapPropertiesByHash(this, interpolations)); }])); } function values(object) { return keys(object).map(function (key) { return object[key]; }); } function mapPropertiesByHash(object, hash) { var result = {}; keys(hash).forEach(function (key) { result[key] = get(object, hash[key]); }); return result; } }); define("ember-inflector/index", ["exports", "ember", "ember-inflector/lib/system", "ember-inflector/lib/ext/string"], function (exports, _ember, _emberInflectorLibSystem, _emberInflectorLibExtString) { /* global define, module */ "use strict"; _emberInflectorLibSystem.Inflector.defaultRules = _emberInflectorLibSystem.defaultRules; _ember["default"].Inflector = _emberInflectorLibSystem.Inflector; _ember["default"].String.pluralize = _emberInflectorLibSystem.pluralize; _ember["default"].String.singularize = _emberInflectorLibSystem.singularize;exports["default"] = _emberInflectorLibSystem.Inflector; exports.pluralize = _emberInflectorLibSystem.pluralize; exports.singularize = _emberInflectorLibSystem.singularize; exports.defaultRules = _emberInflectorLibSystem.defaultRules; if (typeof define !== 'undefined' && define.amd) { define('ember-inflector', ['exports'], function (__exports__) { __exports__['default'] = _emberInflectorLibSystem.Inflector; __exports__.pluralize = _emberInflectorLibSystem.pluralize; __exports__.singularize = _emberInflectorLibSystem.singularize; return __exports__; }); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = _emberInflectorLibSystem.Inflector; _emberInflectorLibSystem.Inflector.singularize = _emberInflectorLibSystem.singularize; _emberInflectorLibSystem.Inflector.pluralize = _emberInflectorLibSystem.pluralize; } }); define('ember-inflector/lib/ext/string', ['exports', 'ember', 'ember-inflector/lib/system/string'], function (exports, _ember, _emberInflectorLibSystemString) { 'use strict'; if (_ember['default'].EXTEND_PROTOTYPES === true || _ember['default'].EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function () { return (0, _emberInflectorLibSystemString.pluralize)(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function () { return (0, _emberInflectorLibSystemString.singularize)(this); }; } }); define('ember-inflector/lib/helpers/pluralize', ['exports', 'ember-inflector', 'ember-inflector/lib/utils/make-helper'], function (exports, _emberInflector, _emberInflectorLibUtilsMakeHelper) { 'use strict'; /** * * If you have Ember Inflector (such as if Ember Data is present), * pluralize a word. For example, turn "ox" into "oxen". * * Example: * * {{pluralize count myProperty}} * {{pluralize 1 "oxen"}} * {{pluralize myProperty}} * {{pluralize "ox"}} * * @for Ember.HTMLBars.helpers * @method pluralize * @param {Number|Property} [count] count of objects * @param {String|Property} word word to pluralize */ exports['default'] = (0, _emberInflectorLibUtilsMakeHelper['default'])(function (params, hash) { var count = undefined, word = undefined, withoutCount = false; if (params.length === 1) { word = params[0]; return (0, _emberInflector.pluralize)(word); } else { count = params[0]; word = params[1]; if (hash["without-count"]) { withoutCount = hash["without-count"]; } if (parseFloat(count) !== 1) { word = (0, _emberInflector.pluralize)(word); } return withoutCount ? word : count + " " + word; } }); }); define('ember-inflector/lib/helpers/singularize', ['exports', 'ember-inflector', 'ember-inflector/lib/utils/make-helper'], function (exports, _emberInflector, _emberInflectorLibUtilsMakeHelper) { 'use strict'; /** * * If you have Ember Inflector (such as if Ember Data is present), * singularize a word. For example, turn "oxen" into "ox". * * Example: * * {{singularize myProperty}} * {{singularize "oxen"}} * * @for Ember.HTMLBars.helpers * @method singularize * @param {String|Property} word word to singularize */ exports['default'] = (0, _emberInflectorLibUtilsMakeHelper['default'])(function (params) { return (0, _emberInflector.singularize)(params[0]); }); }); define("ember-inflector/lib/system", ["exports", "ember-inflector/lib/system/inflector", "ember-inflector/lib/system/string", "ember-inflector/lib/system/inflections"], function (exports, _emberInflectorLibSystemInflector, _emberInflectorLibSystemString, _emberInflectorLibSystemInflections) { "use strict"; _emberInflectorLibSystemInflector["default"].inflector = new _emberInflectorLibSystemInflector["default"](_emberInflectorLibSystemInflections["default"]); exports.Inflector = _emberInflectorLibSystemInflector["default"]; exports.singularize = _emberInflectorLibSystemString.singularize; exports.pluralize = _emberInflectorLibSystemString.pluralize; exports.defaultRules = _emberInflectorLibSystemInflections["default"]; }); define('ember-inflector/lib/system/inflections', ['exports'], function (exports) { 'use strict'; exports['default'] = { plurals: [[/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status|bonus)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes']], singular: [[/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status|bonus)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1']], irregularPairs: [['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies']], uncountable: ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police'] }; }); define('ember-inflector/lib/system/inflector', ['exports', 'ember'], function (exports, _ember) { 'use strict'; var capitalize = _ember['default'].String.capitalize; var BLANK_REGEX = /^\s*$/; var LAST_WORD_DASHED_REGEX = /([\w/-]+[_/\s-])([a-z\d]+$)/; var LAST_WORD_CAMELIZED_REGEX = /([\w/\s-]+)([A-Z][a-z\d]*$)/; var CAMELIZED_REGEX = /[A-Z][a-z\d]*$/; function loadUncountable(rules, uncountable) { for (var i = 0, length = uncountable.length; i < length; i++) { rules.uncountable[uncountable[i].toLowerCase()] = true; } } function loadIrregular(rules, irregularPairs) { var pair; for (var i = 0, length = irregularPairs.length; i < length; i++) { pair = irregularPairs[i]; //pluralizing rules.irregular[pair[0].toLowerCase()] = pair[1]; rules.irregular[pair[1].toLowerCase()] = pair[1]; //singularizing rules.irregularInverse[pair[1].toLowerCase()] = pair[0]; rules.irregularInverse[pair[0].toLowerCase()] = pair[0]; } } /** Inflector.Ember provides a mechanism for supplying inflection rules for your application. Ember includes a default set of inflection rules, and provides an API for providing additional rules. Examples: Creating an inflector with no rules. ```js var inflector = new Ember.Inflector(); ``` Creating an inflector with the default ember ruleset. ```js var inflector = new Ember.Inflector(Ember.Inflector.defaultRules); inflector.pluralize('cow'); //=> 'kine' inflector.singularize('kine'); //=> 'cow' ``` Creating an inflector and adding rules later. ```javascript var inflector = Ember.Inflector.inflector; inflector.pluralize('advice'); // => 'advices' inflector.uncountable('advice'); inflector.pluralize('advice'); // => 'advice' inflector.pluralize('formula'); // => 'formulas' inflector.irregular('formula', 'formulae'); inflector.pluralize('formula'); // => 'formulae' // you would not need to add these as they are the default rules inflector.plural(/$/, 's'); inflector.singular(/s$/i, ''); ``` Creating an inflector with a nondefault ruleset. ```javascript var rules = { plurals: [ [ /$/, 's' ] ], singular: [ [ /\s$/, '' ] ], irregularPairs: [ [ 'cow', 'kine' ] ], uncountable: [ 'fish' ] }; var inflector = new Ember.Inflector(rules); ``` @class Inflector @namespace Ember */ function Inflector(ruleSet) { ruleSet = ruleSet || {}; ruleSet.uncountable = ruleSet.uncountable || makeDictionary(); ruleSet.irregularPairs = ruleSet.irregularPairs || makeDictionary(); var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: makeDictionary(), irregularInverse: makeDictionary(), uncountable: makeDictionary() }; loadUncountable(rules, ruleSet.uncountable); loadIrregular(rules, ruleSet.irregularPairs); this.enableCache(); } if (!Object.create && !Object.create(null).hasOwnProperty) { throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg"); } function makeDictionary() { var cache = Object.create(null); cache['_dict'] = null; delete cache['_dict']; return cache; } Inflector.prototype = { /** @public As inflections can be costly, and commonly the same subset of words are repeatedly inflected an optional cache is provided. @method enableCache */ enableCache: function enableCache() { this.purgeCache(); this.singularize = function (word) { this._cacheUsed = true; return this._sCache[word] || (this._sCache[word] = this._singularize(word)); }; this.pluralize = function (word) { this._cacheUsed = true; return this._pCache[word] || (this._pCache[word] = this._pluralize(word)); }; }, /** @public @method purgedCache */ purgeCache: function purgeCache() { this._cacheUsed = false; this._sCache = makeDictionary(); this._pCache = makeDictionary(); }, /** @public disable caching @method disableCache; */ disableCache: function disableCache() { this._sCache = null; this._pCache = null; this.singularize = function (word) { return this._singularize(word); }; this.pluralize = function (word) { return this._pluralize(word); }; }, /** @method plural @param {RegExp} regex @param {String} string */ plural: function plural(regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.plurals.push([regex, string.toLowerCase()]); }, /** @method singular @param {RegExp} regex @param {String} string */ singular: function singular(regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.singular.push([regex, string.toLowerCase()]); }, /** @method uncountable @param {String} regex */ uncountable: function uncountable(string) { if (this._cacheUsed) { this.purgeCache(); } loadUncountable(this.rules, [string.toLowerCase()]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function irregular(singular, plural) { if (this._cacheUsed) { this.purgeCache(); } loadIrregular(this.rules, [[singular, plural]]); }, /** @method pluralize @param {String} word */ pluralize: function pluralize(word) { return this._pluralize(word); }, _pluralize: function _pluralize(word) { return this.inflect(word, this.rules.plurals, this.rules.irregular); }, /** @method singularize @param {String} word */ singularize: function singularize(word) { return this._singularize(word); }, _singularize: function _singularize(word) { return this.inflect(word, this.rules.singular, this.rules.irregularInverse); }, /** @protected @method inflect @param {String} word @param {Object} typeRules @param {Object} irregular */ inflect: function inflect(word, typeRules, irregular) { var inflection, substitution, result, lowercase, wordSplit, firstPhrase, lastWord, isBlank, isCamelized, rule, isUncountable; isBlank = !word || BLANK_REGEX.test(word); isCamelized = CAMELIZED_REGEX.test(word); firstPhrase = ""; if (isBlank) { return word; } lowercase = word.toLowerCase(); wordSplit = LAST_WORD_DASHED_REGEX.exec(word) || LAST_WORD_CAMELIZED_REGEX.exec(word); if (wordSplit) { firstPhrase = wordSplit[1]; lastWord = wordSplit[2].toLowerCase(); } isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord]; if (isUncountable) { return word; } for (rule in irregular) { if (lowercase.match(rule + "$")) { substitution = irregular[rule]; if (isCamelized && irregular[lastWord]) { substitution = capitalize(substitution); rule = capitalize(rule); } return word.replace(new RegExp(rule, 'i'), substitution); } } for (var i = typeRules.length, min = 0; i > min; i--) { inflection = typeRules[i - 1]; rule = inflection[0]; if (rule.test(word)) { break; } } inflection = inflection || []; rule = inflection[0]; substitution = inflection[1]; result = word.replace(rule, substitution); return result; } }; exports['default'] = Inflector; }); define('ember-inflector/lib/system/string', ['exports', 'ember-inflector/lib/system/inflector'], function (exports, _emberInflectorLibSystemInflector) { 'use strict'; function pluralize(word) { return _emberInflectorLibSystemInflector['default'].inflector.pluralize(word); } function singularize(word) { return _emberInflectorLibSystemInflector['default'].inflector.singularize(word); } exports.pluralize = pluralize; exports.singularize = singularize; }); define('ember-inflector/lib/utils/make-helper', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports['default'] = makeHelper; function makeHelper(helperFunction) { if (_ember['default'].Helper) { return _ember['default'].Helper.helper(helperFunction); } if (_ember['default'].HTMLBars) { return _ember['default'].HTMLBars.makeBoundHelper(helperFunction); } return _ember['default'].Handlebars.makeBoundHelper(helperFunction); } }); define('ember-load-initializers/index', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports['default'] = function (app, prefix) { var regex = new RegExp('^' + prefix + '\/((?:instance-)?initializers)\/'); var getKeys = Object.keys || _ember['default'].keys; getKeys(requirejs._eak_seen).map(function (moduleName) { return { moduleName: moduleName, matches: regex.exec(moduleName) }; }).filter(function (dep) { return dep.matches && dep.matches.length === 2; }).forEach(function (dep) { var moduleName = dep.moduleName; var module = require(moduleName, null, null, true); if (!module) { throw new Error(moduleName + ' must export an initializer.'); } var initializerType = _ember['default'].String.camelize(dep.matches[1].substring(0, dep.matches[1].length - 1)); var initializer = module['default']; if (!initializer.name) { var initializerName = moduleName.match(/[^\/]+\/?$/)[0]; initializer.name = initializerName; } if (app[initializerType]) { app[initializerType](initializer); } }); }; }); define('ember-new-computed/index', ['exports', 'ember', 'ember-new-computed/utils/can-use-new-syntax'], function (exports, _ember, _emberNewComputedUtilsCanUseNewSyntax) { 'use strict'; exports['default'] = newComputed; var computed = _ember['default'].computed; function newComputed() { var polyfillArguments = []; var config = arguments[arguments.length - 1]; if (typeof config === 'function' || _emberNewComputedUtilsCanUseNewSyntax['default']) { return computed.apply(undefined, arguments); } for (var i = 0, l = arguments.length - 1; i < l; i++) { polyfillArguments.push(arguments[i]); } var func; if (config.set) { func = function (key, value) { if (arguments.length > 1) { return config.set.call(this, key, value); } else { return config.get.call(this, key); } }; } else { func = function (key) { return config.get.call(this, key); }; } polyfillArguments.push(func); return computed.apply(undefined, polyfillArguments); } var getKeys = Object.keys || _ember['default'].keys; var computedKeys = getKeys(computed); for (var i = 0, l = computedKeys.length; i < l; i++) { newComputed[computedKeys[i]] = computed[computedKeys[i]]; } }); define('ember-new-computed/utils/can-use-new-syntax', ['exports', 'ember'], function (exports, _ember) { 'use strict'; var supportsSetterGetter; try { _ember['default'].computed({ set: function set() {}, get: function get() {} }); supportsSetterGetter = true; } catch (e) { supportsSetterGetter = false; } exports['default'] = supportsSetterGetter; }); define('ember-resolver/container-debug-adapter', ['exports', 'ember', 'ember-resolver/utils/module-registry'], function (exports, _ember, _emberResolverUtilsModuleRegistry) { 'use strict'; var ContainerDebugAdapter = _ember['default'].ContainerDebugAdapter; var ModulesContainerDebugAdapter = null; function getPod(type, key, prefix) { var match = key.match(new RegExp('^/?' + prefix + '/(.+)/' + type + '$')); if (match) { return match[1]; } } // Support Ember < 1.5-beta.4 // TODO: Remove this after 1.5.0 is released if (typeof ContainerDebugAdapter !== 'undefined') { /* * This module defines a subclass of Ember.ContainerDebugAdapter that adds two * important features: * * 1) is able provide injections to classes that implement `extend` * (as is typical with Ember). */ ModulesContainerDebugAdapter = ContainerDebugAdapter.extend({ _moduleRegistry: null, init: function init() { this._super.apply(this, arguments); if (!this._moduleRegistry) { this._moduleRegistry = new _emberResolverUtilsModuleRegistry['default'](); } }, /** The container of the application being debugged. This property will be injected on creation. @property container @default null */ /** The resolver instance of the application being debugged. This property will be injected on creation. @property resolver @default null */ /** Returns true if it is possible to catalog a list of available classes in the resolver for a given type. @method canCatalogEntriesByType @param {string} type The type. e.g. "model", "controller", "route" @return {boolean} whether a list is available for this type. */ canCatalogEntriesByType: function canCatalogEntriesByType() /* type */{ return true; }, /** Returns the available classes a given type. @method catalogEntriesByType @param {string} type The type. e.g. "model", "controller", "route" @return {Array} An array of classes. */ catalogEntriesByType: function catalogEntriesByType(type) { var moduleNames = this._moduleRegistry.moduleNames(); var types = _ember['default'].A(); var prefix = this.namespace.modulePrefix; for (var i = 0, l = moduleNames.length; i < l; i++) { var key = moduleNames[i]; if (key.indexOf(type) !== -1) { // Check if it's a pod module var name = getPod(type, key, this.namespace.podModulePrefix || prefix); if (!name) { // Not pod name = key.split(type + 's/').pop(); // Support for different prefix (such as ember-cli addons). // Uncomment the code below when // https://github.com/ember-cli/ember-resolver/pull/80 is merged. //var match = key.match('^/?(.+)/' + type); //if (match && match[1] !== prefix) { // Different prefix such as an addon //name = match[1] + '@' + name; //} } types.addObject(name); } } return types; } }); } exports['default'] = ModulesContainerDebugAdapter; }); define('ember-resolver/index', ['exports', 'ember-resolver/resolver'], function (exports, _emberResolverResolver) { 'use strict'; Object.defineProperty(exports, 'default', { enumerable: true, get: function get() { return _emberResolverResolver['default']; } }); }); define('ember-resolver/resolver', ['exports', 'ember', 'ember-resolver/utils/module-registry', 'ember-resolver/utils/class-factory', 'ember-resolver/utils/make-dictionary'], function (exports, _ember, _emberResolverUtilsModuleRegistry, _emberResolverUtilsClassFactory, _emberResolverUtilsMakeDictionary) { /*globals require */ 'use strict'; /* * This module defines a subclass of Ember.DefaultResolver that adds two * important features: * * 1) The resolver makes the container aware of es6 modules via the AMD * output. The loader's _moduleEntries is consulted so that classes can be * resolved directly via the module loader, without needing a manual * `import`. * 2) is able to provide injections to classes that implement `extend` * (as is typical with Ember). */ var _Ember$String = _ember['default'].String; var underscore = _Ember$String.underscore; var classify = _Ember$String.classify; var dasherize = _Ember$String.dasherize; var get = _ember['default'].get; var DefaultResolver = _ember['default'].DefaultResolver; function parseName(fullName) { /*jshint validthis:true */ if (fullName.parsedName === true) { return fullName; } var prefix, type, name; var fullNameParts = fullName.split('@'); // HTMLBars uses helper:@content-helper which collides // with ember-cli namespace detection. // This will be removed in a future release of HTMLBars. if (fullName !== 'helper:@content-helper' && fullNameParts.length === 2) { var prefixParts = fullNameParts[0].split(':'); if (prefixParts.length === 2) { prefix = prefixParts[1]; type = prefixParts[0]; name = fullNameParts[1]; } else { var nameParts = fullNameParts[1].split(':'); prefix = fullNameParts[0]; type = nameParts[0]; name = nameParts[1]; } } else { fullNameParts = fullName.split(':'); type = fullNameParts[0]; name = fullNameParts[1]; } var fullNameWithoutType = name; var namespace = get(this, 'namespace'); var root = namespace; return { parsedName: true, fullName: fullName, prefix: prefix || this.prefix({ type: type }), type: type, fullNameWithoutType: fullNameWithoutType, name: name, root: root, resolveMethodName: "resolve" + classify(type) }; } function resolveOther(parsedName) { /*jshint validthis:true */ _ember['default'].assert('`modulePrefix` must be defined', this.namespace.modulePrefix); var normalizedModuleName = this.findModuleName(parsedName); if (normalizedModuleName) { var defaultExport = this._extractDefaultExport(normalizedModuleName, parsedName); if (defaultExport === undefined) { throw new Error(" Expected to find: '" + parsedName.fullName + "' within '" + normalizedModuleName + "' but got 'undefined'. Did you forget to `export default` within '" + normalizedModuleName + "'?"); } if (this.shouldWrapInClassFactory(defaultExport, parsedName)) { defaultExport = (0, _emberResolverUtilsClassFactory['default'])(defaultExport); } return defaultExport; } else { return this._super(parsedName); } } // Ember.DefaultResolver docs: // https://github.com/emberjs/ember.js/blob/master/packages/ember-application/lib/system/resolver.js var Resolver = DefaultResolver.extend({ resolveOther: resolveOther, parseName: parseName, resolveTemplate: resolveOther, pluralizedTypes: null, moduleRegistry: null, makeToString: function makeToString(factory, fullName) { return '' + this.namespace.modulePrefix + '@' + fullName + ':'; }, shouldWrapInClassFactory: function shouldWrapInClassFactory() /* module, parsedName */{ return false; }, init: function init() { this._super(); this.moduleBasedResolver = true; if (!this._moduleRegistry) { this._moduleRegistry = new _emberResolverUtilsModuleRegistry['default'](); } this._normalizeCache = (0, _emberResolverUtilsMakeDictionary['default'])(); this.pluralizedTypes = this.pluralizedTypes || (0, _emberResolverUtilsMakeDictionary['default'])(); if (!this.pluralizedTypes.config) { this.pluralizedTypes.config = 'config'; } this._deprecatedPodModulePrefix = false; }, normalize: function normalize(fullName) { return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this._normalize(fullName)); }, _normalize: function _normalize(fullName) { // A) Convert underscores to dashes // B) Convert camelCase to dash-case, except for helpers where we want to avoid shadowing camelCase expressions // C) replace `.` with `/` in order to make nested controllers work in the following cases // 1. `needs: ['posts/post']` // 2. `{{render "posts/post"}}` // 3. `this.render('posts/post')` from Route var split = fullName.split(':'); if (split.length > 1) { if (split[0] === 'helper') { return split[0] + ':' + split[1].replace(/_/g, '-'); } else { return split[0] + ':' + dasherize(split[1].replace(/\./g, '/')); } } else { return fullName; } }, pluralize: function pluralize(type) { return this.pluralizedTypes[type] || (this.pluralizedTypes[type] = type + 's'); }, podBasedLookupWithPrefix: function podBasedLookupWithPrefix(podPrefix, parsedName) { var fullNameWithoutType = parsedName.fullNameWithoutType; if (parsedName.type === 'template') { fullNameWithoutType = fullNameWithoutType.replace(/^components\//, ''); } return podPrefix + '/' + fullNameWithoutType + '/' + parsedName.type; }, podBasedModuleName: function podBasedModuleName(parsedName) { var podPrefix = this.namespace.podModulePrefix || this.namespace.modulePrefix; return this.podBasedLookupWithPrefix(podPrefix, parsedName); }, podBasedComponentsInSubdir: function podBasedComponentsInSubdir(parsedName) { var podPrefix = this.namespace.podModulePrefix || this.namespace.modulePrefix; podPrefix = podPrefix + '/components'; if (parsedName.type === 'component' || parsedName.fullNameWithoutType.match(/^components/)) { return this.podBasedLookupWithPrefix(podPrefix, parsedName); } }, resolveEngine: function resolveEngine(parsedName) { var engineName = parsedName.fullNameWithoutType; var engineModule = engineName + '/engine'; if (this._moduleRegistry.has(engineModule)) { return this._extractDefaultExport(engineModule); } }, resolveRouteMap: function resolveRouteMap(parsedName) { var engineName = parsedName.fullNameWithoutType; var engineRoutesModule = engineName + '/routes'; if (this._moduleRegistry.has(engineRoutesModule)) { var routeMap = this._extractDefaultExport(engineRoutesModule); _ember['default'].assert('The route map for ' + engineName + ' should be wrapped by \'buildRoutes\' before exporting.', routeMap.isRouteMap); return routeMap; } }, mainModuleName: function mainModuleName(parsedName) { // if router:main or adapter:main look for a module with just the type first var tmpModuleName = parsedName.prefix + '/' + parsedName.type; if (parsedName.fullNameWithoutType === 'main') { return tmpModuleName; } }, defaultModuleName: function defaultModuleName(parsedName) { return parsedName.prefix + '/' + this.pluralize(parsedName.type) + '/' + parsedName.fullNameWithoutType; }, prefix: function prefix(parsedName) { var tmpPrefix = this.namespace.modulePrefix; if (this.namespace[parsedName.type + 'Prefix']) { tmpPrefix = this.namespace[parsedName.type + 'Prefix']; } return tmpPrefix; }, /** A listing of functions to test for moduleName's based on the provided `parsedName`. This allows easy customization of additional module based lookup patterns. @property moduleNameLookupPatterns @returns {Ember.Array} */ moduleNameLookupPatterns: _ember['default'].computed(function () { return [this.podBasedModuleName, this.podBasedComponentsInSubdir, this.mainModuleName, this.defaultModuleName]; }), findModuleName: function findModuleName(parsedName, loggingDisabled) { var moduleNameLookupPatterns = this.get('moduleNameLookupPatterns'); var moduleName; for (var index = 0, _length = moduleNameLookupPatterns.length; index < _length; index++) { var item = moduleNameLookupPatterns[index]; var tmpModuleName = item.call(this, parsedName); // allow treat all dashed and all underscored as the same thing // supports components with dashes and other stuff with underscores. if (tmpModuleName) { tmpModuleName = this.chooseModuleName(tmpModuleName, parsedName); } if (tmpModuleName && this._moduleRegistry.has(tmpModuleName)) { moduleName = tmpModuleName; } if (!loggingDisabled) { this._logLookup(moduleName, parsedName, tmpModuleName); } if (moduleName) { return moduleName; } } }, chooseModuleName: function chooseModuleName(moduleName, parsedName) { var _this = this; var underscoredModuleName = underscore(moduleName); if (moduleName !== underscoredModuleName && this._moduleRegistry.has(moduleName) && this._moduleRegistry.has(underscoredModuleName)) { throw new TypeError("Ambiguous module names: `" + moduleName + "` and `" + underscoredModuleName + "`"); } if (this._moduleRegistry.has(moduleName)) { return moduleName; } else if (this._moduleRegistry.has(underscoredModuleName)) { return underscoredModuleName; } // workaround for dasherized partials: // something/something/-something => something/something/_something var partializedModuleName = moduleName.replace(/\/-([^\/]*)$/, '/_$1'); if (this._moduleRegistry.has(partializedModuleName)) { _ember['default'].deprecate('Modules should not contain underscores. ' + 'Attempted to lookup "' + moduleName + '" which ' + 'was not found. Please rename "' + partializedModuleName + '" ' + 'to "' + moduleName + '" instead.', false, { id: 'ember-resolver.underscored-modules', until: '3.0.0' }); return partializedModuleName; } _ember['default'].runInDebug(function () { var isCamelCaseHelper = parsedName.type === 'helper' && !!moduleName.match(/[a-z]+[A-Z]+/); if (isCamelCaseHelper) { _this._camelCaseHelperWarnedNames = _this._camelCaseHelperWarnedNames || []; var alreadyWarned = _this._camelCaseHelperWarnedNames.indexOf(parsedName.fullName) > -1; if (!alreadyWarned && _this._moduleRegistry.has(dasherize(moduleName))) { _this._camelCaseHelperWarnedNames.push(parsedName.fullName); _ember['default'].warn('Attempted to lookup "' + parsedName.fullName + '" which ' + 'was not found. In previous versions of ember-resolver, a bug would have ' + 'caused the module at "' + dasherize(moduleName) + '" to be ' + 'returned for this camel case helper name. This has been fixed. ' + 'Use the dasherized name to resolve the module that would have been ' + 'returned in previous versions.', false, { id: 'ember-resolver.camelcase-helper-names', until: '3.0.0' }); } } }); }, // used by Ember.DefaultResolver.prototype._logLookup lookupDescription: function lookupDescription(fullName) { var parsedName = this.parseName(fullName); var moduleName = this.findModuleName(parsedName, true); return moduleName; }, // only needed until 1.6.0-beta.2 can be required _logLookup: function _logLookup(found, parsedName, description) { if (!_ember['default'].ENV.LOG_MODULE_RESOLVER && !parsedName.root.LOG_RESOLVER) { return; } var symbol, padding; if (found) { symbol = '[✓]'; } else { symbol = '[ ]'; } if (parsedName.fullName.length > 60) { padding = '.'; } else { padding = new Array(60 - parsedName.fullName.length).join('.'); } if (!description) { description = this.lookupDescription(parsedName); } _ember['default'].Logger.info(symbol, parsedName.fullName, padding, description); }, knownForType: function knownForType(type) { var moduleKeys = this._moduleRegistry.moduleNames(); var items = (0, _emberResolverUtilsMakeDictionary['default'])(); for (var index = 0, length = moduleKeys.length; index < length; index++) { var moduleName = moduleKeys[index]; var fullname = this.translateToContainerFullname(type, moduleName); if (fullname) { items[fullname] = true; } } return items; }, translateToContainerFullname: function translateToContainerFullname(type, moduleName) { var prefix = this.prefix({ type: type }); // Note: using string manipulation here rather than regexes for better performance. // pod modules // '^' + prefix + '/(.+)/' + type + '$' var podPrefix = prefix + '/'; var podSuffix = '/' + type; var start = moduleName.indexOf(podPrefix); var end = moduleName.indexOf(podSuffix); if (start === 0 && end === moduleName.length - podSuffix.length && moduleName.length > podPrefix.length + podSuffix.length) { return type + ':' + moduleName.slice(start + podPrefix.length, end); } // non-pod modules // '^' + prefix + '/' + pluralizedType + '/(.+)$' var pluralizedType = this.pluralize(type); var nonPodPrefix = prefix + '/' + pluralizedType + '/'; if (moduleName.indexOf(nonPodPrefix) === 0 && moduleName.length > nonPodPrefix.length) { return type + ':' + moduleName.slice(nonPodPrefix.length); } }, _extractDefaultExport: function _extractDefaultExport(normalizedModuleName) { var module = require(normalizedModuleName, null, null, true /* force sync */); if (module && module['default']) { module = module['default']; } return module; } }); Resolver.reopenClass({ moduleBasedResolver: true }); exports['default'] = Resolver; }); define('ember-resolver/utils/class-factory', ['exports'], function (exports) { 'use strict'; exports['default'] = classFactory; function classFactory(klass) { return { create: function create(injections) { if (typeof klass.extend === 'function') { return klass.extend(injections); } else { return klass; } } }; } }); define("ember-resolver/utils/create", ["exports", "ember"], function (exports, _ember) { "use strict"; var create = Object.create || _ember["default"].create; if (!(create && !create(null).hasOwnProperty)) { throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg"); } exports["default"] = create; }); define('ember-resolver/utils/make-dictionary', ['exports', 'ember-resolver/utils/create'], function (exports, _emberResolverUtilsCreate) { 'use strict'; exports['default'] = makeDictionary; function makeDictionary() { var cache = (0, _emberResolverUtilsCreate['default'])(null); cache['_dict'] = null; delete cache['_dict']; return cache; } }); define('ember-resolver/utils/module-registry', ['exports', 'ember'], function (exports, _ember) { /*globals requirejs, require */ 'use strict'; if (typeof requirejs.entries === 'undefined') { requirejs.entries = requirejs._eak_seen; } function ModuleRegistry(entries) { this._entries = entries || requirejs.entries; } ModuleRegistry.prototype.moduleNames = function ModuleRegistry_moduleNames() { return (Object.keys || _ember['default'].keys)(this._entries); }; ModuleRegistry.prototype.has = function ModuleRegistry_has(moduleName) { return moduleName in this._entries; }; ModuleRegistry.prototype.get = function ModuleRegistry_get(moduleName) { var exportName = arguments.length <= 1 || arguments[1] === undefined ? 'default' : arguments[1]; var module = require(moduleName); return module && module[exportName]; }; exports['default'] = ModuleRegistry; }); define('ember-route-action-helper/-private/internals', ['exports', 'ember'], function (exports, _ember) { 'use strict'; var ClosureActionModule = undefined; if ('ember-htmlbars/keywords/closure-action' in _ember['default'].__loader.registry) { ClosureActionModule = _ember['default'].__loader.require('ember-htmlbars/keywords/closure-action'); } else if ('ember-routing-htmlbars/keywords/closure-action' in _ember['default'].__loader.registry) { ClosureActionModule = _ember['default'].__loader.require('ember-routing-htmlbars/keywords/closure-action'); } else { ClosureActionModule = {}; } var ACTION = ClosureActionModule.ACTION; exports.ACTION = ACTION; }); define('ember-route-action-helper/helpers/route-action', ['exports', 'ember', 'ember-route-action-helper/-private/internals'], function (exports, _ember, _emberRouteActionHelperPrivateInternals) { 'use strict'; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];return arr2; } else { return Array.from(arr); } } function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } var emberArray = _ember['default'].A; var Helper = _ember['default'].Helper; var assert = _ember['default'].assert; var computed = _ember['default'].computed; var typeOf = _ember['default'].typeOf; var get = _ember['default'].get; var getOwner = _ember['default'].getOwner; var run = _ember['default'].run; var runInDebug = _ember['default'].runInDebug; function getCurrentHandlerInfos(router) { var routerLib = router._routerMicrolib || router.router; return routerLib.currentHandlerInfos; } function getRoutes(router) { return emberArray(getCurrentHandlerInfos(router)).mapBy('handler').reverse(); } function getRouteWithAction(router, actionName) { var action = undefined; var handler = emberArray(getRoutes(router)).find(function (route) { var actions = route.actions || route._actions; action = actions[actionName]; return typeOf(action) === 'function'; }); return { action: action, handler: handler }; } exports['default'] = Helper.extend({ router: computed(function () { return getOwner(this).lookup('router:main'); }).readOnly(), compute: function compute(_ref) { var _ref2 = _toArray(_ref); var actionName = _ref2[0]; var params = _ref2.slice(1); var router = get(this, 'router'); assert('[ember-route-action-helper] Unable to lookup router', router); runInDebug(function () { var _getRouteWithAction = getRouteWithAction(router, actionName); var handler = _getRouteWithAction.handler; assert('[ember-route-action-helper] Unable to find action ' + actionName, handler); }); var routeAction = function routeAction() { var _getRouteWithAction2 = getRouteWithAction(router, actionName); var action = _getRouteWithAction2.action; var handler = _getRouteWithAction2.handler; for (var _len = arguments.length, invocationArgs = Array(_len), _key = 0; _key < _len; _key++) { invocationArgs[_key] = arguments[_key]; } var args = params.concat(invocationArgs); return run.join.apply(run, [handler, action].concat(_toConsumableArray(args))); }; routeAction[_emberRouteActionHelperPrivateInternals.ACTION] = true; return routeAction; } }); }); ;/* jshint ignore:start */ /* jshint ignore:end */ //# sourceMappingURL=cs-vendor.map