(function() { /*! * @overview Ember - JavaScript Application Framework * @copyright Copyright 2011-2018 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 3.6.0 */ /*globals process */ var enifed, requireModule, Ember; // Used in @ember/-internals/environment/lib/global.js mainContext = this; // eslint-disable-line no-undef (function() { 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] = requireModule; } else { reified[i] = internalRequire(deps[i], name); } } callback.apply(this, reified); return exports; } 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 = Object.create(null); var seen = Object.create(null); enifed = function(name, deps, callback) { var value = {}; if (!callback) { value.deps = []; value.callback = deps; } else { value.deps = deps; value.callback = callback; } registry[name] = value; }; requireModule = function(name) { return internalRequire(name, null); }; // setup `require` module requireModule['default'] = requireModule; requireModule.has = function registryHas(moduleName) { return !!registry[moduleName] || !!registry[moduleName + '/index']; }; requireModule._eak_seen = registry; Ember.__loader = { define: enifed, require: requireModule, registry: registry, }; } else { enifed = Ember.__loader.define; requireModule = Ember.__loader.require; } })(); enifed('@ember/-internals/browser-environment', ['exports'], function (exports) { 'use strict'; // check if window exists and actually is the global var hasDom = typeof self === 'object' && self !== null && self.Object === Object && typeof Window !== 'undefined' && self.constructor === Window && typeof document === 'object' && document !== null && self.document === document && typeof location === 'object' && location !== null && self.location === location && typeof history === 'object' && history !== null && self.history === history && typeof navigator === 'object' && navigator !== null && self.navigator === navigator && typeof navigator.userAgent === 'string'; const window = hasDom ? self : null; const location$1 = hasDom ? self.location : null; const history$1 = hasDom ? self.history : null; const userAgent = hasDom ? self.navigator.userAgent : 'Lynx (textmode)'; const isChrome = hasDom ? !!window.chrome && !window.opera : false; const isFirefox = hasDom ? typeof InstallTrigger !== 'undefined' : false; exports.window = window; exports.location = location$1; exports.history = history$1; exports.userAgent = userAgent; exports.isChrome = isChrome; exports.isFirefox = isFirefox; exports.hasDOM = hasDom; }); enifed('@ember/-internals/console/index', ['exports', '@ember/debug', '@ember/deprecated-features'], function (exports, _debug, _deprecatedFeatures) { 'use strict'; // Deliver message that the function is deprecated const DEPRECATION_MESSAGE = 'Use of Ember.Logger is deprecated. Please use `console` for logging.'; const DEPRECATION_ID = 'ember-console.deprecate-logger'; const DEPRECATION_URL = 'https://emberjs.com/deprecations/v3.x#toc_use-console-rather-than-ember-logger'; /** @module ember */ /** Inside Ember-Metal, simply uses the methods from `imports.console`. Override this to provide more robust logging functionality. @class Logger @deprecated Use 'console' instead @namespace Ember @public */ let DEPRECATED_LOGGER; if (_deprecatedFeatures.LOGGER) { DEPRECATED_LOGGER = { /** 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() { true && !false && (0, _debug.deprecate)(DEPRECATION_MESSAGE, false, { id: DEPRECATION_ID, until: '4.0.0', url: DEPRECATION_URL }); return console.log(...arguments); // eslint-disable-line no-console }, /** 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() { true && !false && (0, _debug.deprecate)(DEPRECATION_MESSAGE, false, { id: DEPRECATION_ID, until: '4.0.0', url: DEPRECATION_URL }); return console.warn(...arguments); // eslint-disable-line no-console }, /** 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() { true && !false && (0, _debug.deprecate)(DEPRECATION_MESSAGE, false, { id: DEPRECATION_ID, until: '4.0.0', url: DEPRECATION_URL }); return console.error(...arguments); // eslint-disable-line no-console }, /** 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() { true && !false && (0, _debug.deprecate)(DEPRECATION_MESSAGE, false, { id: DEPRECATION_ID, until: '4.0.0', url: DEPRECATION_URL }); return console.info(...arguments); // eslint-disable-line no-console }, /** 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() { true && !false && (0, _debug.deprecate)(DEPRECATION_MESSAGE, false, { id: DEPRECATION_ID, until: '4.0.0', url: DEPRECATION_URL }); /* eslint-disable no-console */ if (console.debug) { return console.debug(...arguments); } return console.info(...arguments); /* eslint-enable no-console */ }, /** 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() { true && !false && (0, _debug.deprecate)(DEPRECATION_MESSAGE, false, { id: DEPRECATION_ID, until: '4.0.0', url: DEPRECATION_URL }); return console.assert(...arguments); // eslint-disable-line no-console } }; } exports.default = DEPRECATED_LOGGER; }); enifed('@ember/-internals/container', ['exports', '@ember/-internals/owner', '@ember/-internals/utils', '@ember/debug', '@ember/polyfills'], function (exports, _owner, _utils, _debug, _polyfills) { 'use strict'; exports.FACTORY_FOR = exports.Container = exports.privatize = exports.Registry = undefined; let leakTracking; let containers; if (true /* DEBUG */) { // requires v8 // chrome --js-flags="--allow-natives-syntax --expose-gc" // node --allow-natives-syntax --expose-gc try { if (typeof gc === 'function') { leakTracking = (() => { // avoid syntax errors when --allow-natives-syntax not present let GetWeakSetValues = new Function('weakSet', 'return %GetWeakSetValues(weakSet, 0)'); containers = new WeakSet(); return { hasContainers() { gc(); return GetWeakSetValues(containers).length > 0; }, reset() { let values = GetWeakSetValues(containers); for (let i = 0; i < values.length; i++) { containers.delete(values[i]); } } }; })(); } } catch (e) { // ignore } } /** 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 */ class Container { constructor(registry, options = {}) { this.registry = registry; this.owner = options.owner || null; this.cache = (0, _utils.dictionary)(options.cache || null); this.factoryManagerCache = (0, _utils.dictionary)(options.factoryManagerCache || null); this.isDestroyed = false; this.isDestroying = false; if (true /* DEBUG */) { this.validationCache = (0, _utils.dictionary)(options.validationCache || null); if (containers !== undefined) { containers.add(this); } } } /** @private @property registry @type Registry @since 1.11.0 */ /** @private @property cache @type InheritingDict */ /** @private @property validationCache @type InheritingDict */ /** Given a fullName return a corresponding instance. The default behavior 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(fullName, options) { true && !!this.isDestroyed && (0, _debug.assert)('expected container not to be destroyed', !this.isDestroyed); true && !this.registry.isValidFullName(fullName) && (0, _debug.assert)('fullName must be a proper full name', this.registry.isValidFullName(fullName)); return lookup(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() { destroyDestroyables(this); this.isDestroying = true; } finalizeDestroy() { resetCache(this); 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(fullName) { if (this.isDestroyed) return; if (fullName === undefined) { destroyDestroyables(this); resetCache(this); } else { resetMember(this, this.registry.normalize(fullName)); } } /** Returns an object that can be used to provide an owner to a manually created instance. @private @method ownerInjection @returns { Object } */ ownerInjection() { return { [_owner.OWNER]: this.owner }; } /** Given a fullName, return the corresponding factory. The consumer of the factory is responsible for the destruction of any factory instances, as there is no way for the container to ensure instances are destroyed when it itself is destroyed. @public @method factoryFor @param {String} fullName @param {Object} [options] @param {String} [options.source] The fullname of the request source (used for local lookup) @return {any} */ factoryFor(fullName, options = {}) { true && !!this.isDestroyed && (0, _debug.assert)('expected container not to be destroyed', !this.isDestroyed); let normalizedName = this.registry.normalize(fullName); true && !this.registry.isValidFullName(normalizedName) && (0, _debug.assert)('fullName must be a proper full name', this.registry.isValidFullName(normalizedName)); true && !(false /* EMBER_MODULE_UNIFICATION */ || !options.namespace) && (0, _debug.assert)('EMBER_MODULE_UNIFICATION must be enabled to pass a namespace option to factoryFor', false || !options.namespace); if (options.source || options.namespace) { normalizedName = this.registry.expandLocalLookup(fullName, options); if (!normalizedName) { return; } } return factoryFor(this, normalizedName, fullName); } } if (true /* DEBUG */) { Container._leakTracking = leakTracking; } /* * Wrap a factory manager in a proxy which will not permit properties to be * set on the manager. */ function wrapManagerInDeprecationProxy(manager) { if (_utils.HAS_NATIVE_PROXY) { let validator = { set(_obj, prop) { 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. let m = manager; let proxiedManager = { class: m.class, create(props) { return m.create(props); } }; let proxy = new Proxy(proxiedManager, validator); FACTORY_FOR.set(proxy, manager); } return manager; } function isSingleton(container, fullName) { return container.registry.getOption(fullName, 'singleton') !== false; } function isInstantiatable(container, fullName) { return container.registry.getOption(fullName, 'instantiate') !== false; } function lookup(container, fullName, options = {}) { true && !(false /* EMBER_MODULE_UNIFICATION */ || !options.namespace) && (0, _debug.assert)('EMBER_MODULE_UNIFICATION must be enabled to pass a namespace option to lookup', false || !options.namespace); let normalizedName = fullName; if (options.source || options.namespace) { normalizedName = container.registry.expandLocalLookup(fullName, options); if (!normalizedName) { return; } } if (options.singleton !== false) { let cached = container.cache[normalizedName]; if (cached !== undefined) { return cached; } } return instantiateFactory(container, normalizedName, fullName, options); } function factoryFor(container, normalizedName, fullName) { let cached = container.factoryManagerCache[normalizedName]; if (cached !== undefined) { return cached; } let factory = container.registry.resolve(normalizedName); if (factory === undefined) { return; } if (true /* DEBUG */ && factory && typeof factory._onLookup === 'function') { factory._onLookup(fullName); } let manager = new FactoryManager(container, factory, fullName, normalizedName); if (true /* DEBUG */) { manager = wrapManagerInDeprecationProxy(manager); } container.factoryManagerCache[normalizedName] = manager; return manager; } function isSingletonClass(container, fullName, { instantiate, singleton }) { return singleton !== false && !instantiate && isSingleton(container, fullName) && !isInstantiatable(container, fullName); } function isSingletonInstance(container, fullName, { instantiate, singleton }) { return singleton !== false && instantiate !== false && isSingleton(container, fullName) && isInstantiatable(container, fullName); } function isFactoryClass(container, fullname, { instantiate, singleton }) { return instantiate === false && (singleton === false || !isSingleton(container, fullname)) && !isInstantiatable(container, fullname); } function isFactoryInstance(container, fullName, { instantiate, singleton }) { return instantiate !== false && (singleton !== false || isSingleton(container, fullName)) && isInstantiatable(container, fullName); } function instantiateFactory(container, normalizedName, fullName, options) { let factoryManager = factoryFor(container, normalizedName, fullName); if (factoryManager === undefined) { return; } // SomeClass { singleton: true, instantiate: true } | { singleton: true } | { instantiate: true } | {} // By default majority of objects fall into this case if (isSingletonInstance(container, fullName, options)) { return container.cache[normalizedName] = factoryManager.create(); } // SomeClass { singleton: false, instantiate: true } if (isFactoryInstance(container, fullName, options)) { return factoryManager.create(); } // SomeClass { singleton: true, instantiate: false } | { instantiate: false } | { singleton: false, instantiation: false } if (isSingletonClass(container, fullName, options) || isFactoryClass(container, fullName, options)) { return factoryManager.class; } throw new Error('Could not create factory'); } function processInjections(container, injections, result) { if (true /* DEBUG */) { container.registry.validateInjections(injections); } let hash = result.injections; if (hash === undefined) { hash = result.injections = {}; } for (let i = 0; i < injections.length; i++) { let { property, specifier, source } = injections[i]; if (source) { hash[property] = lookup(container, specifier, { source }); } else { hash[property] = lookup(container, specifier); } if (!result.isDynamic) { result.isDynamic = !isSingleton(container, specifier); } } } function buildInjections(container, typeInjections, injections) { let result = { injections: undefined, isDynamic: false }; if (typeInjections !== undefined) { processInjections(container, typeInjections, result); } if (injections !== undefined) { processInjections(container, injections, result); } return result; } function injectionsFor(container, fullName) { let registry = container.registry; let [type] = fullName.split(':'); let typeInjections = registry.getTypeInjections(type); let injections = registry.getInjections(fullName); return buildInjections(container, typeInjections, injections); } function destroyDestroyables(container) { let cache = container.cache; let keys = Object.keys(cache); for (let i = 0; i < keys.length; i++) { let key = keys[i]; let value = cache[key]; if (value.destroy) { value.destroy(); } } } function resetCache(container) { container.cache = (0, _utils.dictionary)(null); container.factoryManagerCache = (0, _utils.dictionary)(null); } function resetMember(container, fullName) { let member = container.cache[fullName]; delete container.factoryManagerCache[fullName]; if (member) { delete container.cache[fullName]; if (member.destroy) { member.destroy(); } } } const FACTORY_FOR = new WeakMap(); class FactoryManager { constructor(container, factory, fullName, normalizedName) { this.container = container; this.owner = container.owner; this.class = factory; this.fullName = fullName; this.normalizedName = normalizedName; this.madeToString = undefined; this.injections = undefined; FACTORY_FOR.set(this, this); } toString() { if (this.madeToString === undefined) { this.madeToString = this.container.registry.makeToString(this.class, this.fullName); } return this.madeToString; } create(options) { let injectionsCache = this.injections; if (injectionsCache === undefined) { let { injections, isDynamic } = injectionsFor(this.container, this.normalizedName); injectionsCache = injections; if (!isDynamic) { this.injections = injections; } } let props = injectionsCache; if (options !== undefined) { props = (0, _polyfills.assign)({}, injectionsCache, options); } if (true /* DEBUG */) { let lazyInjections; let validationCache = this.container.validationCache; // Ensure that all lazy injections are valid at instantiation time if (!validationCache[this.fullName] && this.class && typeof this.class._lazyInjections === 'function') { lazyInjections = this.class._lazyInjections(); lazyInjections = this.container.registry.normalizeInjectionsHash(lazyInjections); this.container.registry.validateInjections(lazyInjections); } validationCache[this.fullName] = true; } if (!this.class.create) { throw new Error(`Failed to create an instance of '${this.normalizedName}'. Most likely an improperly defined class or` + ` an invalid module export.`); } // required to allow access to things like // the customized toString, _debugContainerKey, // owner, etc. without a double extend and without // modifying the objects properties if (typeof this.class._initFactory === 'function') { this.class._initFactory(this); } else { // in the non-EmberObject case we need to still setOwner // this is required for supporting glimmer environment and // template instantiation which rely heavily on // `options[OWNER]` being passed into `create` // TODO: clean this up, and remove in future versions if (options === undefined || props === undefined) { // avoid mutating `props` here since they are the cached injections props = (0, _polyfills.assign)({}, props); } (0, _owner.setOwner)(props, this.owner); } let instance = this.class.create(props); FACTORY_FOR.set(instance, this); return instance; } } const 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 */ class Registry { constructor(options = {}) { this.fallback = options.fallback || null; this.resolver = options.resolver || null; this.registrations = (0, _utils.dictionary)(options.registrations || null); this._typeInjections = (0, _utils.dictionary)(null); this._injections = (0, _utils.dictionary)(null); this._localLookupCache = Object.create(null); this._normalizeCache = (0, _utils.dictionary)(null); this._resolveCache = (0, _utils.dictionary)(null); this._failSet = new Set(); this._options = (0, _utils.dictionary)(null); this._typeOptions = (0, _utils.dictionary)(null); } /** A backup registry for resolving registrations when no matches can be found. @private @property fallback @type Registry */ /** An object that has a `resolve` method that resolves a name. @private @property resolver @type Resolver */ /** @private @property registrations @type InheritingDict */ /** @private @property _typeInjections @type InheritingDict */ /** @private @property _injections @type InheritingDict */ /** @private @property _normalizeCache @type InheritingDict */ /** @private @property _resolveCache @type InheritingDict */ /** @private @property _options @type InheritingDict */ /** @private @property _typeOptions @type InheritingDict */ /** Creates a container based on this registry. @private @method container @param {Object} options @return {Container} created container */ container(options) { return new Container(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(fullName, factory, options = {}) { true && !this.isValidFullName(fullName) && (0, _debug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)); true && !(factory !== undefined) && (0, _debug.assert)(`Attempting to register an unknown factory: '${fullName}'`, factory !== undefined); let normalizedName = this.normalize(fullName); true && !!this._resolveCache[normalizedName] && (0, _debug.assert)(`Cannot re-register: '${fullName}', as it has already been resolved.`, !this._resolveCache[normalizedName]); this._failSet.delete(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(fullName) { true && !this.isValidFullName(fullName) && (0, _debug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)); let normalizedName = this.normalize(fullName); this._localLookupCache = Object.create(null); delete this.registrations[normalizedName]; delete this._resolveCache[normalizedName]; delete this._options[normalizedName]; this._failSet.delete(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(fullName, options) { let factory = resolve(this, this.normalize(fullName), options); if (factory === undefined && this.fallback !== null) { factory = this.fallback.resolve(...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(fullName) { if (this.resolver !== null && this.resolver.lookupDescription) { return this.resolver.lookupDescription(fullName); } else if (this.fallback !== null) { return this.fallback.describe(fullName); } else { return fullName; } } /** A hook to enable custom fullName normalization behavior @private @method normalizeFullName @param {String} fullName @return {string} normalized fullName */ normalizeFullName(fullName) { if (this.resolver !== null && this.resolver.normalize) { return this.resolver.normalize(fullName); } else if (this.fallback !== null) { 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(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(factory, fullName) { if (this.resolver !== null && this.resolver.makeToString) { return this.resolver.makeToString(factory, fullName); } else if (this.fallback !== null) { 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(fullName, options) { if (!this.isValidFullName(fullName)) { return false; } let source = options && options.source && this.normalize(options.source); let namespace = options && options.namespace || undefined; return has(this, this.normalize(fullName), source, namespace); } /** 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(type, options) { this._typeOptions[type] = options; } getOptionsForType(type) { let optionsForType = this._typeOptions[type]; if (optionsForType === undefined && this.fallback !== null) { optionsForType = this.fallback.getOptionsForType(type); } return optionsForType; } /** @private @method options @param {String} fullName @param {Object} options */ options(fullName, options) { let normalizedName = this.normalize(fullName); this._options[normalizedName] = options; } getOptions(fullName) { let normalizedName = this.normalize(fullName); let options = this._options[normalizedName]; if (options === undefined && this.fallback !== null) { options = this.fallback.getOptions(fullName); } return options; } getOption(fullName, optionName) { let options = this._options[fullName]; if (options !== undefined && options[optionName] !== undefined) { return options[optionName]; } let type = fullName.split(':')[0]; options = this._typeOptions[type]; if (options && options[optionName] !== undefined) { return options[optionName]; } else if (this.fallback !== null) { return this.fallback.getOption(fullName, optionName); } return undefined; } /** 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(type, property, fullName) { true && !this.isValidFullName(fullName) && (0, _debug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)); let fullNameType = fullName.split(':')[0]; true && !(fullNameType !== type) && (0, _debug.assert)(`Cannot inject a '${fullName}' on other ${type}(s).`, fullNameType !== type); let injections = this._typeInjections[type] || (this._typeInjections[type] = []); injections.push({ property, specifier: 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(fullName, property, injectionName) { true && !this.isValidFullName(injectionName) && (0, _debug.assert)(`Invalid injectionName, expected: 'type:name' got: ${injectionName}`, this.isValidFullName(injectionName)); let normalizedInjectionName = this.normalize(injectionName); if (fullName.indexOf(':') === -1) { return this.typeInjection(fullName, property, normalizedInjectionName); } true && !this.isValidFullName(fullName) && (0, _debug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)); let normalizedName = this.normalize(fullName); let injections = this._injections[normalizedName] || (this._injections[normalizedName] = []); injections.push({ property, specifier: normalizedInjectionName }); } /** @private @method knownForType @param {String} type the type to iterate over */ knownForType(type) { let localKnown = (0, _utils.dictionary)(null); let registeredNames = Object.keys(this.registrations); for (let index = 0; index < registeredNames.length; index++) { let fullName = registeredNames[index]; let itemType = fullName.split(':')[0]; if (itemType === type) { localKnown[fullName] = true; } } let fallbackKnown, resolverKnown; if (this.fallback !== null) { fallbackKnown = this.fallback.knownForType(type); } if (this.resolver !== null && this.resolver.knownForType) { resolverKnown = this.resolver.knownForType(type); } return (0, _polyfills.assign)({}, fallbackKnown, localKnown, resolverKnown); } isValidFullName(fullName) { return VALID_FULL_NAME_REGEXP.test(fullName); } getInjections(fullName) { let injections = this._injections[fullName]; if (this.fallback !== null) { let fallbackInjections = this.fallback.getInjections(fullName); if (fallbackInjections !== undefined) { injections = injections === undefined ? fallbackInjections : injections.concat(fallbackInjections); } } return injections; } getTypeInjections(type) { let injections = this._typeInjections[type]; if (this.fallback !== null) { let fallbackInjections = this.fallback.getTypeInjections(type); if (fallbackInjections !== undefined) { injections = injections === undefined ? fallbackInjections : injections.concat(fallbackInjections); } } return injections; } /** 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 */ expandLocalLookup(fullName, options) { if (this.resolver !== null && this.resolver.expandLocalLookup) { true && !this.isValidFullName(fullName) && (0, _debug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)); true && !(!options.source || this.isValidFullName(options.source)) && (0, _debug.assert)('options.source must be a proper full name', !options.source || this.isValidFullName(options.source)); let normalizedFullName = this.normalize(fullName); let normalizedSource = this.normalize(options.source); return expandLocalLookup(this, normalizedFullName, normalizedSource, options.namespace); } else if (this.fallback !== null) { return this.fallback.expandLocalLookup(fullName, options); } else { return null; } } } if (true /* DEBUG */) { const proto = Registry.prototype; proto.normalizeInjectionsHash = function (hash) { let injections = []; for (let key in hash) { if (hash.hasOwnProperty(key)) { let { specifier, source, namespace } = hash[key]; true && !this.isValidFullName(specifier) && (0, _debug.assert)(`Expected a proper full name, given '${specifier}'`, this.isValidFullName(specifier)); injections.push({ property: key, specifier, source, namespace }); } } return injections; }; proto.validateInjections = function (injections) { if (!injections) { return; } for (let i = 0; i < injections.length; i++) { let { specifier, source, namespace } = injections[i]; true && !this.has(specifier, { source, namespace }) && (0, _debug.assert)(`Attempting to inject an unknown injection: '${specifier}'`, this.has(specifier, { source, namespace })); } }; } function expandLocalLookup(registry, normalizedName, normalizedSource, namespace) { let cache = registry._localLookupCache; let normalizedNameCache = cache[normalizedName]; if (!normalizedNameCache) { normalizedNameCache = cache[normalizedName] = Object.create(null); } let cacheKey = namespace || normalizedSource; let cached = normalizedNameCache[cacheKey]; if (cached !== undefined) { return cached; } let expanded = registry.resolver.expandLocalLookup(normalizedName, normalizedSource, namespace); return normalizedNameCache[cacheKey] = expanded; } function resolve(registry, _normalizedName, options) { let normalizedName = _normalizedName; // when `source` is provided expand normalizedName // and source into the full normalizedName if (options !== undefined && (options.source || options.namespace)) { normalizedName = registry.expandLocalLookup(_normalizedName, options); if (!normalizedName) { return; } } let cached = registry._resolveCache[normalizedName]; if (cached !== undefined) { return cached; } if (registry._failSet.has(normalizedName)) { return; } let resolved; if (registry.resolver) { resolved = registry.resolver.resolve(normalizedName); } if (resolved === undefined) { resolved = registry.registrations[normalizedName]; } if (resolved === undefined) { registry._failSet.add(normalizedName); } else { registry._resolveCache[normalizedName] = resolved; } return resolved; } function has(registry, fullName, source, namespace) { return registry.resolve(fullName, { source, namespace }) !== undefined; } const privateNames = (0, _utils.dictionary)(null); const privateSuffix = `${Math.random()}${Date.now()}`.replace('.', ''); function privatize([fullName]) { let name = privateNames[fullName]; if (name) { return name; } let [type, rawName] = fullName.split(':'); return privateNames[fullName] = (0, _utils.intern)(`${type}:${rawName}-${privateSuffix}`); } /* 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 */ exports.Registry = Registry; exports.privatize = privatize; exports.Container = Container; exports.FACTORY_FOR = FACTORY_FOR; }); enifed('@ember/-internals/environment', ['exports'], function (exports) { 'use strict'; // from lodash to catch fake globals 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 var global$1 = checkGlobal(checkElementIdShadowing(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || typeof mainContext !== 'undefined' && mainContext || // set before strict mode in Ember loader/wrapper new Function('return this')(); // eval outside of strict mode // legacy imports/exports/lookup stuff (should we keep this??) const context = function (global, Ember) { return Ember === undefined ? { imports: global, exports: global, lookup: global } : { // import jQuery imports: Ember.imports || global, // export Ember exports: Ember.exports || global, // search for Namespaces lookup: Ember.lookup || global }; }(global$1, global$1.Ember); function getLookup() { return context.lookup; } function setLookup(value) { context.lookup = value; } /** 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 */ const ENV = { ENABLE_OPTIONAL_FEATURES: false, /** 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 */ EXTEND_PROTOTYPES: { Array: true, Function: true, String: true }, /** 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 */ LOG_STACKTRACE_ON_DEPRECATION: true, /** 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 */ LOG_VERSION: true, RAISE_ON_DEPRECATION: false, STRUCTURED_PROFILE: false, /** Whether to insert a `
` wrapper around the application template. See RFC #280. This is not intended to be set directly, as the implementation may change in the future. Use `@ember/optional-features` instead. @property _APPLICATION_TEMPLATE_WRAPPER @for EmberENV @type Boolean @default true @private */ _APPLICATION_TEMPLATE_WRAPPER: true, /** Whether to use Glimmer Component semantics (as opposed to the classic "Curly" components semantics) for template-only components. See RFC #278. This is not intended to be set directly, as the implementation may change in the future. Use `@ember/optional-features` instead. @property _TEMPLATE_ONLY_GLIMMER_COMPONENTS @for EmberENV @type Boolean @default false @private */ _TEMPLATE_ONLY_GLIMMER_COMPONENTS: false, /** Whether the app is using jQuery. See RFC #294. This is not intended to be set directly, as the implementation may change in the future. Use `@ember/optional-features` instead. @property _JQUERY_INTEGRATION @for EmberENV @type Boolean @default true @private */ _JQUERY_INTEGRATION: true, EMBER_LOAD_HOOKS: {}, FEATURES: {} }; (EmberENV => { if (typeof EmberENV !== 'object' || EmberENV === null) return; for (let flag in EmberENV) { if (!EmberENV.hasOwnProperty(flag) || flag === 'EXTEND_PROTOTYPES' || flag === 'EMBER_LOAD_HOOKS') continue; let defaultValue = ENV[flag]; if (defaultValue === true) { ENV[flag] = EmberENV[flag] !== false; } else if (defaultValue === false) { ENV[flag] = EmberENV[flag] === true; } } let { EXTEND_PROTOTYPES } = EmberENV; if (EXTEND_PROTOTYPES !== undefined) { if (typeof EXTEND_PROTOTYPES === 'object' && EXTEND_PROTOTYPES !== null) { ENV.EXTEND_PROTOTYPES.String = EXTEND_PROTOTYPES.String !== false; ENV.EXTEND_PROTOTYPES.Function = EXTEND_PROTOTYPES.Function !== false; ENV.EXTEND_PROTOTYPES.Array = EXTEND_PROTOTYPES.Array !== false; } else { let isEnabled = EXTEND_PROTOTYPES !== false; ENV.EXTEND_PROTOTYPES.String = isEnabled; ENV.EXTEND_PROTOTYPES.Function = isEnabled; ENV.EXTEND_PROTOTYPES.Array = isEnabled; } } // TODO this does not seem to be used by anything, // can we remove it? do we need to deprecate it? let { EMBER_LOAD_HOOKS } = EmberENV; if (typeof EMBER_LOAD_HOOKS === 'object' && EMBER_LOAD_HOOKS !== null) { for (let hookName in EMBER_LOAD_HOOKS) { if (!EMBER_LOAD_HOOKS.hasOwnProperty(hookName)) continue; let hooks = EMBER_LOAD_HOOKS[hookName]; if (Array.isArray(hooks)) { ENV.EMBER_LOAD_HOOKS[hookName] = hooks.filter(hook => typeof hook === 'function'); } } } let { FEATURES } = EmberENV; if (typeof FEATURES === 'object' && FEATURES !== null) { for (let feature in FEATURES) { if (!FEATURES.hasOwnProperty(feature)) continue; ENV.FEATURES[feature] = FEATURES[feature] === true; } } })(global$1.EmberENV || global$1.ENV); function getENV() { return ENV; } exports.global = global$1; exports.context = context; exports.getLookup = getLookup; exports.setLookup = setLookup; exports.ENV = ENV; exports.getENV = getENV; }); enifed("@ember/-internals/error-handling/index", ["exports"], function (exports) { "use strict"; exports.getOnerror = getOnerror; exports.setOnerror = setOnerror; exports.getDispatchOverride = getDispatchOverride; exports.setDispatchOverride = setDispatchOverride; let onerror; const onErrorTarget = exports.onErrorTarget = { get onerror() { return onerror; } }; // Ember.onerror getter function getOnerror() { return onerror; } // Ember.onerror setter function setOnerror(handler) { onerror = handler; } let dispatchOverride; // allows testing adapter to override dispatch function getDispatchOverride() { return dispatchOverride; } function setDispatchOverride(handler) { dispatchOverride = handler; } }); enifed('@ember/-internals/extension-support/index', ['exports', '@ember/-internals/extension-support/lib/data_adapter', '@ember/-internals/extension-support/lib/container_debug_adapter'], function (exports, _data_adapter, _container_debug_adapter) { 'use strict'; Object.defineProperty(exports, 'DataAdapter', { enumerable: true, get: function () { return _data_adapter.default; } }); Object.defineProperty(exports, 'ContainerDebugAdapter', { enumerable: true, get: function () { return _container_debug_adapter.default; } }); }); enifed('@ember/-internals/extension-support/lib/container_debug_adapter', ['exports', '@ember/string', '@ember/-internals/runtime'], function (exports, _string, _runtime) { 'use strict'; exports.default = _runtime.Object.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(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(type) { let namespaces = (0, _runtime.A)(_runtime.Namespace.NAMESPACES); let types = (0, _runtime.A)(); let typeSuffixRegex = new RegExp(`${(0, _string.classify)(type)}$`); namespaces.forEach(namespace => { for (let key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } if (typeSuffixRegex.test(key)) { let klass = namespace[key]; if ((0, _runtime.typeOf)(klass) === 'class') { types.push((0, _string.dasherize)(key.replace(typeSuffixRegex, ''))); } } } }); return types; } }); }); enifed('@ember/-internals/extension-support/lib/data_adapter', ['exports', '@ember/-internals/owner', '@ember/runloop', '@ember/-internals/metal', '@ember/string', '@ember/-internals/runtime'], function (exports, _owner, _runloop, _metal, _string, _runtime) { 'use strict'; exports.default = _runtime.Object.extend({ init() { this._super(...arguments); this.releaseMethods = (0, _runtime.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: (0, _runtime.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() { return (0, _runtime.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(typesAdded, typesUpdated) { let modelTypes = this.getModelTypes(); let releaseMethods = (0, _runtime.A)(); let typesToSend; typesToSend = modelTypes.map(type => { let klass = type.klass; let wrapped = this.wrapModelType(klass, type.name); releaseMethods.push(this.observeModelType(type.name, typesUpdated)); return wrapped; }); typesAdded(typesToSend); let release = () => { releaseMethods.forEach(fn => fn()); this.releaseMethods.removeObject(release); }; this.releaseMethods.pushObject(release); return release; }, _nameToClass(type) { if (typeof type === 'string') { let owner = (0, _owner.getOwner)(this); let Factory = owner.factoryFor(`model:${type}`); type = Factory && Factory.class; } 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(modelName, recordsAdded, recordsUpdated, recordsRemoved) { let releaseMethods = (0, _runtime.A)(); let klass = this._nameToClass(modelName); let records = this.getRecords(klass, modelName); let release; function recordUpdated(updatedRecord) { recordsUpdated([updatedRecord]); } let recordsToSend = records.map(record => { releaseMethods.push(this.observeRecord(record, recordUpdated)); return this.wrapRecord(record); }); let contentDidChange = (array, idx, removedCount, addedCount) => { for (let i = idx; i < idx + addedCount; i++) { let record = (0, _metal.objectAt)(array, i); let wrapped = this.wrapRecord(record); releaseMethods.push(this.observeRecord(record, recordUpdated)); recordsAdded([wrapped]); } if (removedCount) { recordsRemoved(idx, removedCount); } }; let observer = { didChange: contentDidChange, willChange() { return this; } }; (0, _metal.addArrayObserver)(records, this, observer); release = () => { releaseMethods.forEach(fn => fn()); (0, _metal.removeArrayObserver)(records, this, observer); this.releaseMethods.removeObject(release); }; recordsAdded(recordsToSend); this.releaseMethods.pushObject(release); return release; }, /** Clear all observers before destruction @private @method willDestroy */ willDestroy() { this._super(...arguments); this.releaseMethods.forEach(fn => fn()); }, /** Detect whether a class is a model. Test that against the model class of your persistence library. @private @method detect @return boolean Whether the class is a model class or not. */ detect() { return false; }, /** Get the columns for a given model type. @private @method columnsForType @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() { return (0, _runtime.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(modelName, typesUpdated) { let klass = this._nameToClass(modelName); let records = this.getRecords(klass, modelName); function onChange() { typesUpdated([this.wrapModelType(klass, modelName)]); } let observer = { didChange(array, idx, removedCount, addedCount) { // Only re-fetch records if the record count changed // (which is all we care about as far as model types are concerned). if (removedCount > 0 || addedCount > 0) { (0, _runloop.scheduleOnce)('actions', this, onChange); } }, willChange() { return this; } }; (0, _metal.addArrayObserver)(records, this, observer); let release = () => (0, _metal.removeArrayObserver)(records, this, 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(klass, name) { let records = this.getRecords(klass, name); let typeToSend; typeToSend = { name, count: (0, _metal.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() { let containerDebugAdapter = this.get('containerDebugAdapter'); let types; if (containerDebugAdapter.canCatalogEntriesByType('model')) { types = containerDebugAdapter.catalogEntriesByType('model'); } else { types = this._getObjectsOnNamespaces(); } // New adapters return strings instead of classes. types = (0, _runtime.A)(types).map(name => { return { klass: this._nameToClass(name), name }; }); types = (0, _runtime.A)(types).filter(type => this.detect(type.klass)); return (0, _runtime.A)(types); }, /** Loops over all namespaces and all objects attached to them. @private @method _getObjectsOnNamespaces @return {Array} Array of model type strings. */ _getObjectsOnNamespaces() { let namespaces = (0, _runtime.A)(_runtime.Namespace.NAMESPACES); let types = (0, _runtime.A)(); namespaces.forEach(namespace => { for (let key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } // Even though we will filter again in `getModelTypes`, // we should not call `lookupFactory` on non-models if (!this.detect(namespace[key])) { continue; } let name = (0, _string.dasherize)(key); 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() { return (0, _runtime.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(record) { let 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() { return {}; }, /** Returns keywords to match when searching records. @private @method getRecordKeywords @return {Array} Relevant keywords for search. */ getRecordKeywords() { return (0, _runtime.A)(); }, /** Returns the values of filters defined by `getFilters`. @private @method getRecordFilterValues @param {Object} record The record instance. @return {Object} The filter values. */ getRecordFilterValues() { 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() { return null; }, /** Observes all relevant properties and re-sends the wrapped record when a change occurs. @private @method observerRecord @return {Function} The function to call to remove all observers. */ observeRecord() { return function () {}; } }); }); enifed('@ember/-internals/glimmer', ['exports', '@glimmer/runtime', '@glimmer/util', '@glimmer/node', 'node-module', '@ember/-internals/owner', '@glimmer/opcode-compiler', '@ember/-internals/runtime', '@ember/-internals/utils', '@glimmer/reference', '@ember/-internals/metal', '@ember/-internals/views', '@ember/debug', '@ember/-internals/browser-environment', '@ember/instrumentation', '@ember/service', '@ember/-internals/environment', '@ember/polyfills', '@ember/string', '@glimmer/wire-format', '@ember/-internals/container', '@ember/deprecated-features', '@ember/runloop', 'rsvp', '@ember/-internals/routing'], function (exports, _runtime, _util, _node, _nodeModule, _owner, _opcodeCompiler, _runtime2, _utils, _reference, _metal, _views, _debug, _browserEnvironment, _instrumentation, _service, _environment2, _polyfills, _string, _wireFormat, _container, _deprecatedFeatures, _runloop, _rsvp, _routing) { 'use strict'; exports.getComponentManager = exports.setComponentManager = exports.capabilities = exports.OutletView = exports.DebugStack = exports.iterableFor = exports.INVOKE = exports.UpdatableReference = exports.AbstractComponentManager = exports._experimentalMacros = exports._registerMacros = exports.setupApplicationRegistry = exports.setupEngineRegistry = exports.setTemplates = exports.getTemplates = exports.hasTemplate = exports.setTemplate = exports.getTemplate = exports.renderSettled = exports._resetRenderers = exports.InteractiveRenderer = exports.InertRenderer = exports.Renderer = exports.isHTMLSafe = exports.htmlSafe = exports.escapeExpression = exports.SafeString = exports.Environment = exports.helper = exports.Helper = exports.ROOT_REF = exports.Component = exports.LinkComponent = exports.TextArea = exports.TextField = exports.Checkbox = exports.template = exports.RootTemplate = exports.NodeDOMTreeConstruction = exports.isSerializationFirstNode = exports.DOMTreeConstruction = exports.DOMChanges = undefined; Object.defineProperty(exports, 'DOMChanges', { enumerable: true, get: function () { return _runtime.DOMChanges; } }); Object.defineProperty(exports, 'DOMTreeConstruction', { enumerable: true, get: function () { return _runtime.DOMTreeConstruction; } }); Object.defineProperty(exports, 'isSerializationFirstNode', { enumerable: true, get: function () { return _util.isSerializationFirstNode; } }); Object.defineProperty(exports, 'NodeDOMTreeConstruction', { enumerable: true, get: function () { return _node.NodeDOMTreeConstruction; } }); function template(json) { return new FactoryWrapper((0, _opcodeCompiler.templateFactory)(json)); } class FactoryWrapper { constructor(factory) { this.factory = factory; this.id = factory.id; this.meta = factory.meta; } create(injections) { const owner = (0, _owner.getOwner)(injections); return this.factory.create(injections.compiler, { owner }); } } var RootTemplate = template({ "id": "HlDcU23A", "block": "{\"symbols\":[],\"statements\":[[1,[27,\"component\",[[22,0,[]]],null],false]],\"hasEval\":false}", "meta": { "moduleName": "packages/@ember/-internals/glimmer/lib/templates/root.hbs" } }); /** @module @ember/component */ const RECOMPUTE_TAG = (0, _utils.symbol)('RECOMPUTE_TAG'); function isHelperFactory(helper) { return typeof helper === 'object' && helper !== null && helper.class && helper.class.isHelperFactory; } function isSimpleHelper(helper) { return helper.destroy === undefined; } /** Ember Helpers are functions that can compute values, and are used in templates. For example, this code calls a helper named `format-currency`: ```handlebars
{{format-currency cents currency="$"}}
``` 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: ```app/helpers/format-currency.js import Helper from '@ember/component/helper'; export default Helper.extend({ compute([cents], { 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. @class Helper @public @since 1.13.0 */ let Helper = _runtime2.FrameworkObject.extend({ init() { this._super(...arguments); this[RECOMPUTE_TAG] = _reference.DirtyableTag.create(); }, /** 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: ```app/helpers/current-user-email.js import Helper from '@ember/component/helper' import { inject as service } from '@ember/service' import { observer } from '@ember/object' export default Helper.extend({ session: service(), onNewUser: observer('session.currentUser', function() { this.recompute(); }), compute() { return this.get('session.currentUser.email'); } }); ``` @method recompute @public @since 1.13.0 */ recompute() { this[RECOMPUTE_TAG].inner.dirty(); } }); Helper.isHelperFactory = true; class Wrapper { constructor(compute) { this.compute = compute; this.isHelperFactory = true; } create() { // needs new instance or will leak containers return { compute: this.compute }; } } /** In many cases, the ceremony of a full `Helper` class is not required. The `helper` method create pure-function helpers without instances. For example: ```app/helpers/format-currency.js import { helper } from '@ember/component/helper'; export default helper(function(params, hash) { let cents = params[0]; let currency = hash.currency; return `${currency}${cents * 0.01}`; }); ``` @static @param {Function} helper The helper function @method helper @for @ember/component/helper @public @since 1.13.0 */ function helper(helperFn) { return new Wrapper(helperFn); } function toBool(predicate) { if ((0, _runtime2.isArray)(predicate)) { return predicate.length !== 0; } else { return !!predicate; } } const UPDATE = (0, _utils.symbol)('UPDATE'); const INVOKE = (0, _utils.symbol)('INVOKE'); const ACTION = (0, _utils.symbol)('ACTION'); let maybeFreeze; if (true /* DEBUG */) { // gaurding this in a DEBUG gaurd (as well as all invocations) // so that it is properly stripped during the minification's // dead code elimination maybeFreeze = obj => { // re-freezing an already frozen object introduces a significant // performance penalty on Chrome (tested through 59). // // See: https://bugs.chromium.org/p/v8/issues/detail?id=6450 if (!Object.isFrozen(obj)) { Object.freeze(obj); } }; } class EmberPathReference { get(key) { return PropertyReference.create(this, key); } } class CachedReference$1 extends EmberPathReference { constructor() { super(); this._lastRevision = null; this._lastValue = null; } value() { let { tag, _lastRevision, _lastValue } = this; if (_lastRevision === null || !tag.validate(_lastRevision)) { _lastValue = this._lastValue = this.compute(); this._lastRevision = tag.value(); } return _lastValue; } } class RootReference extends _reference.ConstReference { constructor(value) { super(value); this.children = Object.create(null); } get(propertyKey) { let ref = this.children[propertyKey]; if (ref === undefined) { ref = this.children[propertyKey] = new RootPropertyReference(this.inner, propertyKey); } return ref; } } let TwoWayFlushDetectionTag; if (true /* DEBUG */) { TwoWayFlushDetectionTag = class { static create(tag, key, ref) { return new _reference.TagWrapper(tag.type, new TwoWayFlushDetectionTag(tag, key, ref)); } constructor(tag, key, ref) { this.tag = tag; this.parent = null; this.key = key; this.ref = ref; } value() { return this.tag.value(); } validate(ticket) { let { parent, key } = this; let isValid = this.tag.validate(ticket); if (isValid && parent) { (0, _metal.didRender)(parent, key, this.ref); } return isValid; } didCompute(parent) { this.parent = parent; (0, _metal.didRender)(parent, this.key, this.ref); } }; } class PropertyReference extends CachedReference$1 { static create(parentReference, propertyKey) { if ((0, _reference.isConst)(parentReference)) { return new RootPropertyReference(parentReference.value(), propertyKey); } else { return new NestedPropertyReference(parentReference, propertyKey); } } get(key) { return new NestedPropertyReference(this, key); } } class RootPropertyReference extends PropertyReference { constructor(parentValue, propertyKey) { super(); this._parentValue = parentValue; this._propertyKey = propertyKey; if (true /* DEBUG */) { this.tag = TwoWayFlushDetectionTag.create((0, _metal.tagForProperty)(parentValue, propertyKey), propertyKey, this); } else { this.tag = (0, _metal.tagForProperty)(parentValue, propertyKey); } if (true /* DEBUG */) { (0, _metal.watchKey)(parentValue, propertyKey); } } compute() { let { _parentValue, _propertyKey } = this; if (true /* DEBUG */) { this.tag.inner.didCompute(_parentValue); } return (0, _metal.get)(_parentValue, _propertyKey); } [UPDATE](value) { (0, _metal.set)(this._parentValue, this._propertyKey, value); } } class NestedPropertyReference extends PropertyReference { constructor(parentReference, propertyKey) { super(); let parentReferenceTag = parentReference.tag; let parentObjectTag = _reference.UpdatableTag.create(_reference.CONSTANT_TAG); this._parentReference = parentReference; this._parentObjectTag = parentObjectTag; this._propertyKey = propertyKey; if (true /* DEBUG */) { let tag = (0, _reference.combine)([parentReferenceTag, parentObjectTag]); this.tag = TwoWayFlushDetectionTag.create(tag, propertyKey, this); } else { this.tag = (0, _reference.combine)([parentReferenceTag, parentObjectTag]); } } compute() { let { _parentReference, _parentObjectTag, _propertyKey } = this; let parentValue = _parentReference.value(); _parentObjectTag.inner.update((0, _metal.tagForProperty)(parentValue, _propertyKey)); let parentValueType = typeof parentValue; if (parentValueType === 'string' && _propertyKey === 'length') { return parentValue.length; } if (parentValueType === 'object' && parentValue !== null || parentValueType === 'function') { if (true /* DEBUG */) { (0, _metal.watchKey)(parentValue, _propertyKey); } if (true /* DEBUG */) { this.tag.inner.didCompute(parentValue); } return (0, _metal.get)(parentValue, _propertyKey); } else { return undefined; } } [UPDATE](value) { let parent = this._parentReference.value(); (0, _metal.set)(parent, this._propertyKey, value); } } class UpdatableReference extends EmberPathReference { constructor(value) { super(); this.tag = _reference.DirtyableTag.create(); this._value = value; } value() { return this._value; } update(value) { let { _value } = this; if (value !== _value) { this.tag.inner.dirty(); this._value = value; } } } class ConditionalReference$1 extends _runtime.ConditionalReference { static create(reference) { if ((0, _reference.isConst)(reference)) { let value = reference.value(); if ((0, _utils.isProxy)(value)) { return new RootPropertyReference(value, 'isTruthy'); } else { return _runtime.PrimitiveReference.create(toBool(value)); } } return new ConditionalReference$1(reference); } constructor(reference) { super(reference); this.objectTag = _reference.UpdatableTag.create(_reference.CONSTANT_TAG); this.tag = (0, _reference.combine)([reference.tag, this.objectTag]); } toBool(predicate) { if ((0, _utils.isProxy)(predicate)) { this.objectTag.inner.update((0, _metal.tagForProperty)(predicate, 'isTruthy')); return (0, _metal.get)(predicate, 'isTruthy'); } else { this.objectTag.inner.update((0, _metal.tagFor)(predicate)); return toBool(predicate); } } } class SimpleHelperReference extends CachedReference$1 { static create(helper$$1, args) { if ((0, _reference.isConst)(args)) { let { positional, named } = args; let positionalValue = positional.value(); let namedValue = named.value(); if (true /* DEBUG */) { maybeFreeze(positionalValue); maybeFreeze(namedValue); } let result = helper$$1(positionalValue, namedValue); return valueToRef(result); } else { return new SimpleHelperReference(helper$$1, args); } } constructor(helper$$1, args) { super(); this.tag = args.tag; this.helper = helper$$1; this.args = args; } compute() { let { helper: helper$$1, args: { positional, named } } = this; let positionalValue = positional.value(); let namedValue = named.value(); if (true /* DEBUG */) { maybeFreeze(positionalValue); maybeFreeze(namedValue); } return helper$$1(positionalValue, namedValue); } } class ClassBasedHelperReference extends CachedReference$1 { static create(instance, args) { return new ClassBasedHelperReference(instance, args); } constructor(instance, args) { super(); this.tag = (0, _reference.combine)([instance[RECOMPUTE_TAG], args.tag]); this.instance = instance; this.args = args; } compute() { let { instance, args: { positional, named } } = this; let positionalValue = positional.value(); let namedValue = named.value(); if (true /* DEBUG */) { maybeFreeze(positionalValue); maybeFreeze(namedValue); } return instance.compute(positionalValue, namedValue); } } class InternalHelperReference extends CachedReference$1 { constructor(helper$$1, args) { super(); this.tag = args.tag; this.helper = helper$$1; this.args = args; } compute() { let { helper: helper$$1, args } = this; return helper$$1(args); } } class UnboundReference extends _reference.ConstReference { static create(value) { return valueToRef(value, false); } get(key) { return valueToRef((0, _metal.get)(this.inner, key), false); } } class ReadonlyReference extends CachedReference$1 { constructor(inner) { super(); this.inner = inner; } get tag() { return this.inner.tag; } get [INVOKE]() { return this.inner[INVOKE]; } compute() { return this.inner.value(); } get(key) { return this.inner.get(key); } } function referenceFromParts(root, parts) { let reference = root; for (let i = 0; i < parts.length; i++) { reference = reference.get(parts[i]); } return reference; } function valueToRef(value, bound = true) { if (value !== null && typeof value === 'object') { // root of interop with ember objects return bound ? new RootReference(value) : new UnboundReference(value); } // ember doesn't do observing with functions if (typeof value === 'function') { return new UnboundReference(value); } return _runtime.PrimitiveReference.create(value); } const DIRTY_TAG = (0, _utils.symbol)('DIRTY_TAG'); const ARGS = (0, _utils.symbol)('ARGS'); const ROOT_REF = (0, _utils.symbol)('ROOT_REF'); const IS_DISPATCHING_ATTRS = (0, _utils.symbol)('IS_DISPATCHING_ATTRS'); const HAS_BLOCK = (0, _utils.symbol)('HAS_BLOCK'); const BOUNDS = (0, _utils.symbol)('BOUNDS'); /** @module @ember/component */ /** A `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 a `Component` is via a template. If you name a template `app/templates/components/my-foo.hbs`, you will be able to use `{{my-foo}}` in other templates, which will make an instance of the isolated component. ```app/templates/components/my-foo.hbs {{person-profile person=currentUser}} ``` ```app/templates/components/person-profile.hbs

{{person.title}}

{{person.signature}}

``` 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 {{#person-profile person=currentUser}}

Admin mode

{{! Executed in the controller's context. }} {{/person-profile}} ``` ```app/templates/components/person-profile.hbs

{{person.title}}

{{! 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 `Component` named after the name of the component. For example, you could implement the action `hello` for the `person-profile` component: ```app/components/person-profile.js import Component from '@ember/component'; export default Component.extend({ actions: { hello(name) { console.log("Hello", name); } } }); ``` And then use it in the component's template: ```app/templates/components/person-profile.hbs

{{person.title}}

{{yield}} ``` 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. ## HTML Tag The default HTML tag name used for a component's DOM representation is `div`. This can be customized by setting the `tagName` property. The following component class: ```app/components/emphasized-paragraph.js import Component from '@ember/component'; export default Component.extend({ tagName: 'em' }); ``` Would result in instances with the following HTML: ```html ``` ## HTML `class` Attribute The HTML `class` attribute of a component's tag can be set by providing a `classNames` property that is set to an array of strings: ```app/components/my-widget.js import Component from '@ember/component'; export default Component.extend({ classNames: ['my-class', 'my-other-class'] }); ``` Will result in component instances with an HTML representation of: ```html
``` `class` attribute values can also be set by providing a `classNameBindings` property set to an array of properties names for the component. The return value of these properties will be added as part of the value for the components's `class` attribute. These properties can be computed properties: ```app/components/my-widget.js import Component from '@ember/component'; import { computed } from '@ember/object'; export default Component.extend({ classNameBindings: ['propertyA', 'propertyB'], propertyA: 'from-a', propertyB: computed(function() { if (someLogic) { return 'from-b'; } }) }); ``` Will result in component instances with an HTML representation of: ```html
``` 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`. ```app/components/my-widget.js import Component from '@ember/component'; export default Component.extend({ classNameBindings: ['hovered'], hovered: true }); ``` Will result in component instances with an HTML representation of: ```html
``` 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: ```app/components/my-widget.js import Component from '@ember/component'; export default Component.extend({ classNameBindings: ['awesome:so-very-cool'], awesome: true }); ``` Will result in component instances with an HTML representation of: ```html
``` Boolean value class name bindings whose property names are in a camelCase-style format will be converted to a dasherized format: ```app/components/my-widget.js import Component from '@ember/component'; export default Component.extend({ classNameBindings: ['isUrgent'], isUrgent: true }); ``` Will result in component instances with an HTML representation of: ```html
``` Class name bindings can also refer to object values that are found by traversing a path relative to the component itself: ```app/components/my-widget.js import Component from '@ember/component'; import EmberObject from '@ember/object'; export default Component.extend({ classNameBindings: ['messages.empty'], messages: EmberObject.create({ empty: true }) }); ``` Will result in component instances with an HTML representation of: ```html
``` 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: ```app/components/my-widget.js import Component from '@ember/component'; export default Component.extend({ classNameBindings: ['isEnabled:enabled:disabled'], isEnabled: true }); ``` Will result in component instances with an HTML representation of: ```html
``` When isEnabled is `false`, the resulting HTML representation looks like this: ```html
``` This syntax offers the convenience to add a class if a property is `false`: ```app/components/my-widget.js import Component from '@ember/component'; // Applies no class when isEnabled is true and class 'disabled' when isEnabled is false export default Component.extend({ classNameBindings: ['isEnabled::disabled'], isEnabled: true }); ``` Will result in component instances with an HTML representation of: ```html
``` When the `isEnabled` property on the component is set to `false`, it will result in component instances with an HTML representation of: ```html
``` Updates to the value of a class name binding will result in automatic update of the HTML `class` attribute in the component'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 [EmberObject](/api/ember/release/classes/EmberObject) documentation for more information about concatenated properties. ## HTML Attributes The HTML attribute section of a component's tag can be set by providing an `attributeBindings` property set to an array of property names on the component. The return value of these properties will be used as the value of the component's HTML associated attribute: ```app/components/my-anchor.js import Component from '@ember/component'; export default Component.extend({ tagName: 'a', attributeBindings: ['href'], href: 'http://google.com' }); ``` Will result in component instances with an HTML representation of: ```html ``` One property can be mapped on to another by placing a ":" between the source property and the destination property: ```app/components/my-anchor.js import Component from '@ember/component'; export default Component.extend({ tagName: 'a', attributeBindings: ['url:href'], url: 'http://google.com' }); ``` Will result in component instances with an HTML representation of: ```html ``` Namespaced attributes (e.g. `xlink:href`) are supported, but have to be mapped, since `:` is not a valid character for properties in Javascript: ```app/components/my-use.js import Component from '@ember/component'; export default Component.extend({ tagName: 'use', attributeBindings: ['xlinkHref:xlink:href'], xlinkHref: '#triangle' }); ``` Will result in component instances with an HTML representation of: ```html ``` If the return value of an `attributeBindings` monitored property is a boolean the attribute will be present or absent depending on the value: ```app/components/my-text-input.js import Component from '@ember/component'; export default Component.extend({ tagName: 'input', attributeBindings: ['disabled'], disabled: false }); ``` Will result in a component instance with an HTML representation of: ```html ``` `attributeBindings` can refer to computed properties: ```app/components/my-text-input.js import Component from '@ember/component'; import { computed } from '@ember/object'; export default Component.extend({ tagName: 'input', attributeBindings: ['disabled'], disabled: 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: ```app/components/my-text-input.js import Component from '@ember/component'; export default Component.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 component's rendered HTML representation. `attributeBindings` is a concatenated property. See [EmberObject](/api/ember/release/classes/EmberObject) documentation for more information about concatenated properties. ## Layouts See [Ember.Templates.helpers.yield](/api/ember/release/classes/Ember.Templates.helpers/methods/yield?anchor=yield) for more information. Layout can be used to wrap content in a component. In addition to wrapping content in a Component's template, you can also use the public layout API in your Component JavaScript. ```app/templates/components/person-profile.hbs

Person's Title

{{yield}}
``` ```app/components/person-profile.js import Component from '@ember/component'; import layout from '../templates/components/person-profile'; export default Component.extend({ layout }); ``` If you call the `person-profile` component like so: ``` {{#person-profile}}

Chief Basket Weaver

Fisherman Industries

{{/person-profile}} It will result in the following HTML output: ```html

Person's Title

Chief Basket Weaver

Fisherman Industries

``` ## Responding to Browser Events Components 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 Components 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. ```app/components/my-widget.js import Component from '@ember/component'; export default Component.extend({ click(event) { // will be called when an instance's // rendered element is clicked } }); ``` ### `{{action}}` Helper See [Ember.Templates.helpers.action](/api/ember/release/classes/Ember.Templates.helpers/methods/yield?anchor=yield). ### 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 `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 Component @extends Ember.CoreView @uses Ember.TargetActionSupport @uses Ember.ClassNamesSupport @uses Ember.ActionSupport @uses Ember.ViewMixin @uses Ember.ViewStateSupport @public */ const Component = _views.CoreView.extend(_views.ChildViewsSupport, _views.ViewStateSupport, _views.ClassNamesSupport, _runtime2.TargetActionSupport, _views.ActionSupport, _views.ViewMixin, { isComponent: true, init() { this._super(...arguments); this[IS_DISPATCHING_ATTRS] = false; this[DIRTY_TAG] = _reference.DirtyableTag.create(); this[ROOT_REF] = new RootReference(this); this[BOUNDS] = null; // If in a tagless component, assert that no event handlers are defined true && !(this.tagName !== '' || !this.renderer._destinedForDOM || !(() => { let eventDispatcher = (0, _owner.getOwner)(this).lookup('event_dispatcher:main'); let events = eventDispatcher && eventDispatcher._finalEvents || {}; // tslint:disable-next-line:forin for (let key in events) { let methodName = events[key]; if (typeof this[methodName] === 'function') { return true; // indicate that the assertion should be triggered } } return false; })()) && (0, _debug.assert)( // tslint:disable-next-line:max-line-length `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 !== '' || !this.renderer._destinedForDOM || !(() => { let eventDispatcher = (0, _owner.getOwner)(this).lookup('event_dispatcher:main');let events = eventDispatcher && eventDispatcher._finalEvents || {};for (let key in events) { let methodName = events[key];if (typeof this[methodName] === 'function') { return true; } }return false; })()); }, rerender() { this[DIRTY_TAG].inner.dirty(); this._super(); }, [_metal.PROPERTY_DID_CHANGE](key) { if (this[IS_DISPATCHING_ATTRS]) { return; } let args = this[ARGS]; let reference = args !== undefined ? args[key] : undefined; if (reference !== undefined && reference[UPDATE] !== undefined) { reference[UPDATE]((0, _metal.get)(this, key)); } }, getAttr(key) { // TODO Intimate API should be deprecated return this.get(key); }, /** 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 `` 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(name) { // TODO revisit this let element = (0, _views.getViewElement)(this); let isSVG = element.namespaceURI === _runtime.SVG_NAMESPACE; let { type, normalized } = (0, _runtime.normalizeProperty)(element, name); if (isSVG || type === 'attr') { return element.getAttribute(normalized); } return element[normalized]; }, /** 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 */ /** Enables components to take a list of parameters as arguments. For example, a component that takes two parameters with the names `name` and `age`: ```app/components/my-component.js import Component from '@ember/component'; let MyComponent = Component.extend(); MyComponent.reopenClass({ positionalParams: ['name', 'age'] }); export default MyComponent; ``` It can then be invoked like this: ```hbs {{my-component "John" 38}} ``` The parameters can be referred to just like named parameters: ```hbs Name: {{name}}, Age: {{age}}. ``` Using a string instead of an array allows for an arbitrary number of parameters: ```app/components/my-component.js import Component from '@ember/component'; let MyComponent = Component.extend(); MyComponent.reopenClass({ positionalParams: 'names' }); export default MyComponent; ``` 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 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() {}, /** 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() {}, /** 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() {}, /** 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() {}, /** 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() {}, /** 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() {} }); Component.toString = () => '@ember/component'; Component.reopenClass({ isComponentFactory: true, positionalParams: [] }); var layout = template({ "id": "hvtsz7RF", "block": "{\"symbols\":[],\"statements\":[],\"hasEval\":false}", "meta": { "moduleName": "packages/@ember/-internals/glimmer/lib/templates/empty.hbs" } }); /** @module @ember/component */ /** The internal class used to create text inputs when the `{{input}}` helper is used with `type` of `checkbox`. See [Ember.Templates.helpers.input](/api/ember/release/classes/Ember.Templates.helpers/methods/input?anchor=input) for usage details. ## Direct manipulation of `checked` The `checked` attribute of an `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. @class Checkbox @extends Component @public */ const Checkbox = Component.extend({ layout, classNames: ['ember-checkbox'], tagName: 'input', attributeBindings: ['type', 'checked', 'indeterminate', 'disabled', 'tabindex', 'name', 'autofocus', 'required', 'form'], type: 'checkbox', disabled: false, indeterminate: false, didInsertElement() { this._super(...arguments); (0, _metal.get)(this, 'element').indeterminate = !!(0, _metal.get)(this, 'indeterminate'); }, change() { (0, _metal.set)(this, 'checked', this.element.checked); } }); Checkbox.toString = () => '@ember/component/checkbox'; /** @module @ember/component */ const inputTypes = Object.create(null); function canSetTypeOfInput(type) { if (type in inputTypes) { return inputTypes[type]; } // if running in outside of a browser always return the // original type if (!_browserEnvironment.hasDOM) { inputTypes[type] = type; return type; } let inputTypeTestElement = document.createElement('input'); try { inputTypeTestElement.type = type; } catch (e) { // ignored } 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/ember/release/classes/Ember.Templates.helpers/methods/input?anchor=input) for usage details. ## Layout and LayoutName properties Because HTML `input` elements are self closing `layout` and `layoutName` properties will not be applied. @class TextField @extends Component @uses Ember.TextSupport @public */ const TextField = Component.extend(_views.TextSupport, { layout, classNames: ['ember-text-field'], tagName: 'input', attributeBindings: ['accept', 'autocomplete', 'autosave', 'dir', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'height', 'inputmode', 'lang', 'list', 'type', 'max', 'min', 'multiple', 'name', 'pattern', 'size', 'step', 'value', 'width'], /** 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: (0, _metal.computed)({ get() { return 'text'; }, set(_key, value) { let 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 }); TextField.toString = () => '@ember/component/text-field'; /** @module @ember/component */ /** `{{textarea}}` inserts a new instance of ` ``` Bound: In the following example, the `writtenWords` property on the application Controller will be updated live as the user types 'Lots of text that IS bound' into the text area of their browser's window. ```app/controllers/application.js import Controller from '@ember/controller'; export default Controller.extend({ writtenWords: "Lots of text that IS bound" }); ``` ```handlebars {{textarea value=writtenWords}} ``` Would result in the following HTML: ```html ``` If you wanted a one way binding between the text area and a div tag somewhere else on your screen, you could use `oneWay`: ```app/controllers/application.js import Controller from '@ember/controller'; import { oneWay } from '@ember/object/computed'; export default Controller.extend({ writtenWords: "Lots of text that IS bound", outputWrittenWords: oneWay("writtenWords") }); ``` ```handlebars {{textarea value=writtenWords}}
{{outputWrittenWords}}
``` Would result in the following HTML: ```html <-- the following div will be updated in real time as you type -->
Lots of text that IS bound
``` Finally, this example really shows the power and ease of Ember when two properties are bound to eachother via `alias`. Type into either text area box and they'll both stay in sync. Note that `alias` costs more in terms of performance, so only use it when your really binding in both directions: ```app/controllers/application.js import Controller from '@ember/controller'; import { alias } from '@ember/object/computed'; export default Controller.extend({ writtenWords: "Lots of text that IS bound", twoWayWrittenWords: alias("writtenWords") }); ``` ```handlebars {{textarea value=writtenWords}} {{textarea value=twoWayWrittenWords}} ``` ```html <-- both updated in real time --> ``` ### 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-out="alertMessage"}} ``` See more about [Text Support Actions](/api/ember/release/classes/TextArea) ### Extension Internally, `{{textarea}}` creates an instance of `TextArea`, passing arguments from the helper to `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 `TextArea` or `TextSupport` and adding it to the `attributeBindings` concatenated property: ```javascript import TextArea from '@ember/component/text-area'; TextArea.reopen({ attributeBindings: ['data-error'] }); ``` Keep in mind when writing `TextArea` subclasses that `TextArea` itself extends `Component`. Expect isolated component semantics, not legacy 1.x view semantics (like `controller` being present). See more about [Ember components](/api/ember/release/classes/Component) @method textarea @for Ember.Templates.helpers @param {Hash} options @public */ /** The internal class used to create textarea element when the `{{textarea}}` helper is used. See [Ember.Templates.helpers.textarea](/api/ember/release/classes/Ember.Templates.helpers/methods/textarea?anchor=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. @class TextArea @extends Component @uses Ember.TextSupport @public */ const TextArea = Component.extend(_views.TextSupport, { classNames: ['ember-text-area'], layout, tagName: 'textarea', attributeBindings: ['rows', 'cols', 'name', 'selectionEnd', 'selectionStart', 'autocomplete', 'wrap', 'lang', 'dir', 'value'], rows: null, cols: null }); TextArea.toString = () => '@ember/component/text-area'; var layout$1 = template({ "id": "r9g6x1y/", "block": "{\"symbols\":[\"&default\"],\"statements\":[[4,\"if\",[[23,[\"linkTitle\"]]],null,{\"statements\":[[1,[21,\"linkTitle\"],false]],\"parameters\":[]},{\"statements\":[[14,1]],\"parameters\":[]}]],\"hasEval\":false}", "meta": { "moduleName": "packages/@ember/-internals/glimmer/lib/templates/link-to.hbs" } }); /** @module ember */ /** @module @ember/routing */ /** `LinkComponent` renders an element whose `click` event triggers a transition of the application's instance of `Router` to a supplied route by name. `LinkComponent` components are invoked with {{#link-to}}. Properties of this class can be overridden with `reopen` to customize application-wide behavior. @class LinkComponent @extends Component @see {Ember.Templates.helpers.link-to} @public **/ const LinkComponent = Component.extend({ layout: layout$1, tagName: 'a', /** Used to determine when this `LinkComponent` is active. @property current-when @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 @public **/ 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', /** 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: ```app/components/my-link.js import LinkComponent from '@ember/routing/link-component'; export default LinkComponent.extend({ init() { this._super(...arguments); console.log('Event is ' + this.get('eventName')); } }); ``` NOTE: If you do override `init` for a framework class like `Component`, 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() { this._super(...arguments); // Map desired event name to invoke function let eventName = (0, _metal.get)(this, 'eventName'); this.on(eventName, this, this._invoke); }, _routing: (0, _service.inject)('-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: (0, _metal.computed)({ get(_key) { // always returns false for `get` because (due to the `set` just below) // the cached return value from the set will prevent this getter from _ever_ // being called after a set has occured return false; }, set(_key, value) { this._isDisabled = value; return value ? (0, _metal.get)(this, 'disabledClass') : false; } }), _isActive(routerState) { if ((0, _metal.get)(this, 'loading')) { return false; } let currentWhen = (0, _metal.get)(this, 'current-when'); if (typeof currentWhen === 'boolean') { return currentWhen; } let isCurrentWhenSpecified = !!currentWhen; currentWhen = currentWhen || (0, _metal.get)(this, 'qualifiedRouteName'); currentWhen = currentWhen.split(' '); let routing = (0, _metal.get)(this, '_routing'); let models = (0, _metal.get)(this, 'models'); let resolvedQueryParams = (0, _metal.get)(this, 'resolvedQueryParams'); for (let i = 0; i < currentWhen.length; i++) { if (routing.isActiveForRoute(models, resolvedQueryParams, currentWhen[i], routerState, isCurrentWhenSpecified)) { return true; } } 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: (0, _metal.computed)('activeClass', '_active', function computeLinkToComponentActiveClass() { return this.get('_active') ? (0, _metal.get)(this, 'activeClass') : false; }), _active: (0, _metal.computed)('_routing.currentState', 'attrs.params', function computeLinkToComponentActive() { let currentState = (0, _metal.get)(this, '_routing.currentState'); if (!currentState) { return false; } return this._isActive(currentState); }), willBeActive: (0, _metal.computed)('_routing.targetState', function computeLinkToComponentWillBeActive() { let routing = (0, _metal.get)(this, '_routing'); let targetState = (0, _metal.get)(routing, 'targetState'); if ((0, _metal.get)(routing, 'currentState') === targetState) { return; } return this._isActive(targetState); }), transitioningIn: (0, _metal.computed)('active', 'willBeActive', function computeLinkToComponentTransitioningIn() { if ((0, _metal.get)(this, 'willBeActive') === true && !(0, _metal.get)(this, '_active')) { return 'ember-transitioning-in'; } else { return false; } }), transitioningOut: (0, _metal.computed)('active', 'willBeActive', function computeLinkToComponentTransitioningOut() { if ((0, _metal.get)(this, 'willBeActive') === false && (0, _metal.get)(this, '_active')) { return 'ember-transitioning-out'; } else { return false; } }), /** Event handler that invokes the link, activating the associated route. @method _invoke @param {Event} event @private */ _invoke(event) { if (!(0, _views.isSimpleClick)(event)) { return true; } let preventDefault = (0, _metal.get)(this, 'preventDefault'); let targetAttribute = (0, _metal.get)(this, 'target'); if (preventDefault !== false && (!targetAttribute || targetAttribute === '_self')) { event.preventDefault(); } if ((0, _metal.get)(this, 'bubbles') === false) { event.stopPropagation(); } if (this._isDisabled) { return false; } if ((0, _metal.get)(this, 'loading')) { // tslint:disable-next-line:max-line-length true && (0, _debug.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.', false, { id: 'ember-glimmer.link-to.inactive-loading-state' }); return false; } if (targetAttribute && targetAttribute !== '_self') { return false; } let qualifiedRouteName = (0, _metal.get)(this, 'qualifiedRouteName'); let models = (0, _metal.get)(this, 'models'); let queryParams = (0, _metal.get)(this, 'queryParams.values'); let shouldReplace = (0, _metal.get)(this, 'replace'); let payload = { queryParams, routeName: qualifiedRouteName }; // tslint:disable-next-line:max-line-length (0, _instrumentation.flaggedInstrument)('interaction.link-to', payload, this._generateTransition(payload, qualifiedRouteName, models, queryParams, shouldReplace)); return false; }, _generateTransition(payload, qualifiedRouteName, models, queryParams, shouldReplace) { let routing = (0, _metal.get)(this, '_routing'); return () => { payload.transition = routing.transitionTo(qualifiedRouteName, models, queryParams, shouldReplace); }; }, queryParams: null, qualifiedRouteName: (0, _metal.computed)('targetRouteName', '_routing.currentState', function computeLinkToComponentQualifiedRouteName() { let params = (0, _metal.get)(this, 'params'); let paramsLength = params.length; let lastParam = params[paramsLength - 1]; if (lastParam && lastParam.isQueryParams) { paramsLength--; } let onlyQueryParamsSupplied = this[HAS_BLOCK] ? paramsLength === 0 : paramsLength === 1; if (onlyQueryParamsSupplied) { return (0, _metal.get)(this, '_routing.currentRouteName'); } return (0, _metal.get)(this, 'targetRouteName'); }), resolvedQueryParams: (0, _metal.computed)('queryParams', function computeLinkToComponentResolvedQueryParams() { let resolvedQueryParams = {}; let queryParams = (0, _metal.get)(this, 'queryParams'); if (!queryParams) { return resolvedQueryParams; } let values = queryParams.values; for (let 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: (0, _metal.computed)('models', 'qualifiedRouteName', function computeLinkToComponentHref() { if ((0, _metal.get)(this, 'tagName') !== 'a') { return; } let qualifiedRouteName = (0, _metal.get)(this, 'qualifiedRouteName'); let models = (0, _metal.get)(this, 'models'); if ((0, _metal.get)(this, 'loading')) { return (0, _metal.get)(this, 'loadingHref'); } let routing = (0, _metal.get)(this, '_routing'); let queryParams = (0, _metal.get)(this, 'queryParams.values'); if (true /* DEBUG */) { /* * Unfortunately, to get decent error messages, we need to do this. * In some future state we should be able to use a "feature flag" * which allows us to strip this without needing to call it twice. * * if (isDebugBuild()) { * // Do the useful debug thing, probably including try/catch. * } else { * // Do the performant thing. * } */ try { routing.generateURL(qualifiedRouteName, models, queryParams); } catch (e) { // tslint:disable-next-line:max-line-length true && !false && (0, _debug.assert)('You attempted to define a `{{link-to "' + qualifiedRouteName + '"}}` but did not pass the parameters required for generating its dynamic segments. ' + e.message); } } return routing.generateURL(qualifiedRouteName, models, queryParams); }), loading: (0, _metal.computed)('_modelsAreLoaded', 'qualifiedRouteName', function computeLinkToComponentLoading() { let qualifiedRouteName = (0, _metal.get)(this, 'qualifiedRouteName'); let modelsAreLoaded = (0, _metal.get)(this, '_modelsAreLoaded'); if (!modelsAreLoaded || qualifiedRouteName === null || qualifiedRouteName === undefined) { return (0, _metal.get)(this, 'loadingClass'); } }), _modelsAreLoaded: (0, _metal.computed)('models', function computeLinkToComponentModelsAreLoaded() { let models = (0, _metal.get)(this, 'models'); for (let i = 0; i < models.length; i++) { let model = models[i]; if (model === null || model === undefined) { return false; } } return true; }), _getModels(params) { let modelCount = params.length - 1; let models = new Array(modelCount); for (let i = 0; i < modelCount; i++) { let value = params[i + 1]; 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: '#', didReceiveAttrs() { let queryParams; let params = (0, _metal.get)(this, 'params'); if (params) { // Do not mutate params in place params = params.slice(); } true && !(params && params.length) && (0, _debug.assert)('You must provide one or more parameters to the link-to component.', params && params.length); let disabledWhen = (0, _metal.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[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. let 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 = () => '@ember/routing/link-component'; LinkComponent.reopenClass({ positionalParams: 'params' }); // @ts-check let DebugStack; if (true /* DEBUG */) { class Element { constructor(name) { this.name = name; } } class TemplateElement extends Element {} class EngineElement extends Element {} // tslint:disable-next-line:no-shadowed-variable DebugStack = class DebugStack { constructor() { this._stack = []; } push(name) { this._stack.push(new TemplateElement(name)); } pushEngine(name) { this._stack.push(new EngineElement(name)); } pop() { let element = this._stack.pop(); if (element) { return element.name; } } peek() { let template = this._currentTemplate(); let engine = this._currentEngine(); if (engine) { return `"${template}" (in "${engine}")`; } else if (template) { return `"${template}"`; } } _currentTemplate() { return this._getCurrentByType(TemplateElement); } _currentEngine() { return this._getCurrentByType(EngineElement); } _getCurrentByType(type) { for (let i = this._stack.length; i >= 0; i--) { let element = this._stack[i]; if (element instanceof type) { return element.name; } } } }; } var DebugStack$1 = DebugStack; /** @module ember */ /** 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 ``` ### 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}}

Sorry, nobody is available for this task.

{{/each}} ``` @method each @for Ember.Templates.helpers @public */ /** The `{{each-in}}` helper loops over properties on an object. 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 ``` Outputting their name and age. @method each-in @for Ember.Templates.helpers @public @since 2.1.0 */ const EACH_IN_REFERENCE = (0, _utils.symbol)('EACH_IN'); class EachInReference { constructor(inner) { this.inner = inner; this.tag = inner.tag; this[EACH_IN_REFERENCE] = true; } value() { return this.inner.value(); } get(key) { return this.inner.get(key); } } function isEachIn(ref) { return ref !== null && typeof ref === 'object' && ref[EACH_IN_REFERENCE]; } function eachIn(_vm, args) { return new EachInReference(args.positional.at(0)); } const ITERATOR_KEY_GUID = 'be277757-bbbe-4620-9fcb-213ef433cca2'; function iterableFor(ref, keyPath) { if (isEachIn(ref)) { return new EachInIterable(ref, keyPath || '@key'); } else { return new EachIterable(ref, keyPath || '@identity'); } } class BoundedIterator { constructor(length, keyFor) { this.length = length; this.keyFor = keyFor; this.position = 0; } isEmpty() { return false; } memoFor(position) { return position; } next() { let { length, keyFor, position } = this; if (position >= length) { return null; } let value = this.valueFor(position); let memo = this.memoFor(position); let key = keyFor(value, memo, position); this.position++; return { key, value, memo }; } } class ArrayIterator extends BoundedIterator { constructor(array, length, keyFor) { super(length, keyFor); this.array = array; } static from(array, keyFor) { let { length } = array; if (length === 0) { return EMPTY_ITERATOR; } else { return new this(array, length, keyFor); } } static fromForEachable(object, keyFor) { let array = []; object.forEach(item => array.push(item)); return this.from(array, keyFor); } valueFor(position) { return this.array[position]; } } class EmberArrayIterator extends BoundedIterator { constructor(array, length, keyFor) { super(length, keyFor); this.array = array; } static from(array, keyFor) { let { length } = array; if (length === 0) { return EMPTY_ITERATOR; } else { return new this(array, length, keyFor); } } valueFor(position) { return (0, _metal.objectAt)(this.array, position); } } class ObjectIterator extends BoundedIterator { constructor(keys, values, length, keyFor) { super(length, keyFor); this.keys = keys; this.values = values; } static fromIndexable(obj, keyFor) { let keys = Object.keys(obj); let values = []; let { length } = keys; for (let i = 0; i < length; i++) { values.push((0, _metal.get)(obj, keys[i])); } if (length === 0) { return EMPTY_ITERATOR; } else { return new this(keys, values, length, keyFor); } } static fromForEachable(obj, keyFor) { let keys = []; let values = []; let length = 0; let isMapLike = false; obj.forEach((value, key) => { isMapLike = isMapLike || arguments.length >= 2; if (isMapLike) { keys.push(key); } values.push(value); length++; }); if (length === 0) { return EMPTY_ITERATOR; } else if (isMapLike) { return new this(keys, values, length, keyFor); } else { return new ArrayIterator(values, length, keyFor); } } valueFor(position) { return this.values[position]; } memoFor(position) { return this.keys[position]; } } class NativeIterator { constructor(iterable, result, keyFor) { this.iterable = iterable; this.result = result; this.keyFor = keyFor; this.position = 0; } static from(iterable, keyFor) { let iterator = iterable[Symbol.iterator](); let result = iterator.next(); let { value, done } = result; if (done) { return EMPTY_ITERATOR; } else if (Array.isArray(value) && value.length === 2) { return new this(iterator, result, keyFor); } else { return new ArrayLikeNativeIterator(iterator, result, keyFor); } } isEmpty() { return false; } next() { let { iterable, result, position, keyFor } = this; if (result.done) { return null; } let value = this.valueFor(result, position); let memo = this.memoFor(result, position); let key = keyFor(value, memo, position); this.position++; this.result = iterable.next(); return { key, value, memo }; } } class ArrayLikeNativeIterator extends NativeIterator { valueFor(result) { return result.value; } memoFor(_result, position) { return position; } } class MapLikeNativeIterator extends NativeIterator { valueFor(result) { return result.value[1]; } memoFor(result) { return result.value[0]; } } const EMPTY_ITERATOR = { isEmpty() { return true; }, next() { true && !false && (0, _debug.assert)('Cannot call next() on an empty iterator'); return null; } }; class EachInIterable { constructor(ref, keyPath) { this.ref = ref; this.keyPath = keyPath; this.valueTag = _reference.UpdatableTag.create(_reference.CONSTANT_TAG); this.tag = (0, _reference.combine)([ref.tag, this.valueTag]); } iterate() { let { ref, valueTag } = this; let iterable = ref.value(); let tag = (0, _metal.tagFor)(iterable); if ((0, _utils.isProxy)(iterable)) { // this is because the each-in doesn't actually get(proxy, 'key') but bypasses it // and the proxy's tag is lazy updated on access iterable = (0, _runtime2._contentFor)(iterable); } valueTag.inner.update(tag); if (!isIndexable(iterable)) { return EMPTY_ITERATOR; } if (Array.isArray(iterable) || (0, _runtime2.isEmberArray)(iterable)) { return ObjectIterator.fromIndexable(iterable, this.keyFor(true)); } else if (_utils.HAS_NATIVE_SYMBOL && isNativeIterable(iterable)) { return MapLikeNativeIterator.from(iterable, this.keyFor()); } else if (hasForEach(iterable)) { return ObjectIterator.fromForEachable(iterable, this.keyFor()); } else { return ObjectIterator.fromIndexable(iterable, this.keyFor(true)); } } valueReferenceFor(item) { return new UpdatableReference(item.value); } updateValueReference(ref, item) { ref.update(item.value); } memoReferenceFor(item) { return new UpdatableReference(item.memo); } updateMemoReference(ref, item) { ref.update(item.memo); } keyFor(hasUniqueKeys = false) { let { keyPath } = this; switch (keyPath) { case '@key': return hasUniqueKeys ? ObjectKey : Unique(MapKey); case '@index': return Index; case '@identity': return Unique(Identity); default: true && !(keyPath[0] !== '@') && (0, _debug.assert)(`Invalid key: ${keyPath}`, keyPath[0] !== '@'); return Unique(KeyPath(keyPath)); } } } class EachIterable { constructor(ref, keyPath) { this.ref = ref; this.keyPath = keyPath; this.valueTag = _reference.UpdatableTag.create(_reference.CONSTANT_TAG); this.tag = (0, _reference.combine)([ref.tag, this.valueTag]); } iterate() { let { ref, valueTag } = this; let iterable = ref.value(); valueTag.inner.update((0, _metal.tagForProperty)(iterable, '[]')); if (iterable === null || typeof iterable !== 'object') { return EMPTY_ITERATOR; } let keyFor = this.keyFor(); if (Array.isArray(iterable)) { return ArrayIterator.from(iterable, keyFor); } else if ((0, _runtime2.isEmberArray)(iterable)) { return EmberArrayIterator.from(iterable, keyFor); } else if (_utils.HAS_NATIVE_SYMBOL && isNativeIterable(iterable)) { return ArrayLikeNativeIterator.from(iterable, keyFor); } else if (hasForEach(iterable)) { return ArrayIterator.fromForEachable(iterable, keyFor); } else { return EMPTY_ITERATOR; } } valueReferenceFor(item) { return new UpdatableReference(item.value); } updateValueReference(ref, item) { ref.update(item.value); } memoReferenceFor(item) { return new UpdatableReference(item.memo); } updateMemoReference(ref, item) { ref.update(item.memo); } keyFor() { let { keyPath } = this; switch (keyPath) { case '@index': return Index; case '@identity': return Unique(Identity); default: true && !(keyPath[0] !== '@') && (0, _debug.assert)(`Invalid key: ${keyPath}`, keyPath[0] !== '@'); return Unique(KeyPath(keyPath)); } } } function hasForEach(value) { return typeof value['forEach'] === 'function'; } function isNativeIterable(value) { return typeof value[Symbol.iterator] === 'function'; } function isIndexable(value) { return value !== null && (typeof value === 'object' || typeof value === 'function'); } // Position in an array is guarenteed to be unique function Index(_value, _memo, position) { return String(position); } // Object.keys(...) is guarenteed to be strings and unique function ObjectKey(_value, memo) { return memo; } // Map keys can be any objects function MapKey(_value, memo) { return Identity(memo); } function Identity(value) { switch (typeof value) { case 'string': return value; case 'number': return String(value); default: return (0, _utils.guidFor)(value); } } function KeyPath(keyPath) { return value => String((0, _metal.get)(value, keyPath)); } function Unique(func) { let seen = {}; return (value, memo, position) => { let key = func(value, memo, position); let count = seen[key]; if (count === undefined) { seen[key] = 0; return key; } else { seen[key] = ++count; return `${key}${ITERATOR_KEY_GUID}${count}`; } }; } /** @module @ember/string */ class SafeString { constructor(string) { this.string = string; } toString() { return `${this.string}`; } toHTML() { return this.toString(); } } const escape = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`', '=': '=' }; const possible = /[&<>"'`=]/; const 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 || string === undefined) { 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 import { htmlSafe } from '@ember/string'; htmlSafe('
someString
') ``` @method htmlSafe @for @ember/template @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 `htmlSafe`. ```javascript import { htmlSafe, isHTMLSafe } from '@ember/string'; var plainString = 'plain string', safeString = htmlSafe('
someValue
'); isHTMLSafe(plainString); // false isHTMLSafe(safeString); // true ``` @method isHTMLSafe @for @ember/template @static @return {Boolean} `true` if the string was decorated with `htmlSafe`, `false` otherwise. @public */ function isHTMLSafe(str) { return str !== null && typeof str === 'object' && typeof str.toHTML === 'function'; } /* globals module, URL */ let nodeURL; let parsingNode; function installProtocolForURL(environment) { let protocol; if (_browserEnvironment.hasDOM) { protocol = browserProtocolForURL.call(environment, '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. environment.protocolForURL = browserProtocolForURL; } else if (typeof URL === 'object') { // URL globally provided, likely from FastBoot's sandbox nodeURL = URL; environment.protocolForURL = nodeProtocolForURL; } else if (typeof _nodeModule.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`. // tslint:disable-next-line:no-require-imports nodeURL = (0, _nodeModule.require)('url'); environment.protocolForURL = nodeProtocolForURL; } else { throw new Error('Could not find valid URL parsing mechanism for URL Sanitization'); } } function browserProtocolForURL(url) { if (!parsingNode) { parsingNode = document.createElement('a'); } parsingNode.href = url; return parsingNode.protocol; } function nodeProtocolForURL(url) { let protocol = null; if (typeof url === 'string') { protocol = nodeURL.parse(url).protocol; } return protocol === null ? ':' : protocol; } class Environment$1 extends _runtime.Environment { constructor(injections) { super(injections); this.inTransaction = false; this.owner = injections[_owner.OWNER]; this.isInteractive = this.owner.lookup('-environment:main').isInteractive; // can be removed once https://github.com/tildeio/glimmer/pull/305 lands this.destroyedComponents = []; installProtocolForURL(this); if (true /* DEBUG */) { this.debugStack = new DebugStack$1(); } } static create(options) { return new this(options); } // this gets clobbered by installPlatformSpecificProtocolForURL // it really should just delegate to a platform specific injection protocolForURL(s) { return s; } lookupComponent(name, meta) { return (0, _views.lookupComponent)(meta.owner, name, meta); } toConditionalReference(reference) { return ConditionalReference$1.create(reference); } iterableFor(ref, key) { return iterableFor(ref, key); } scheduleInstallModifier(modifier, manager) { if (this.isInteractive) { super.scheduleInstallModifier(modifier, manager); } } scheduleUpdateModifier(modifier, manager) { if (this.isInteractive) { super.scheduleUpdateModifier(modifier, manager); } } didDestroy(destroyable) { destroyable.destroy(); } begin() { this.inTransaction = true; super.begin(); } commit() { let destroyedComponents = this.destroyedComponents; this.destroyedComponents = []; // components queued for destruction must be destroyed before firing // `didCreate` to prevent errors when removing and adding a component // with the same name (would throw an error when added to view registry) for (let i = 0; i < destroyedComponents.length; i++) { destroyedComponents[i].destroy(); } try { super.commit(); } finally { this.inTransaction = false; } } } if (true /* DEBUG */) { class StyleAttributeManager extends _runtime.SimpleDynamicAttribute { set(dom, value, env) { true && (0, _debug.warn)((0, _views.constructStyleDeprecationMessage)(value), (() => { if (value === null || value === undefined || isHTMLSafe(value)) { return true; } return false; })(), { id: 'ember-htmlbars.style-xss-warning' }); super.set(dom, value, env); } update(value, env) { true && (0, _debug.warn)((0, _views.constructStyleDeprecationMessage)(value), (() => { if (value === null || value === undefined || isHTMLSafe(value)) { return true; } return false; })(), { id: 'ember-htmlbars.style-xss-warning' }); super.update(value, env); } } Environment$1.prototype.attributeFor = function (element, attribute, isTrusting, namespace) { if (attribute === 'style' && !isTrusting) { return new StyleAttributeManager({ element, name: attribute, namespace }); } return _runtime.Environment.prototype.attributeFor.call(this, element, attribute, isTrusting, namespace); }; } // implements the ComponentManager interface as defined in glimmer: // tslint:disable-next-line:max-line-length // https://github.com/glimmerjs/glimmer-vm/blob/v0.24.0-beta.4/packages/%40glimmer/runtime/lib/component/interfaces.ts#L21 class AbstractManager { constructor() { this.debugStack = undefined; } prepareArgs(_state, _args) { return null; } didCreateElement(_component, _element, _operations) {} // noop // inheritors should also call `this.debugStack.pop()` to // ensure the rerendering assertion messages are properly // maintained didRenderLayout(_component, _bounds) { // noop } didCreate(_bucket) {} // noop // inheritors should also call `this._pushToDebugStack` // to ensure the rerendering assertion messages are // properly maintained update(_bucket, _dynamicScope) {} // noop // inheritors should also call `this.debugStack.pop()` to // ensure the rerendering assertion messages are properly // maintained didUpdateLayout(_bucket, _bounds) { // noop } didUpdate(_bucket) { // noop } } if (true /* DEBUG */) { AbstractManager.prototype._pushToDebugStack = function (name, environment) { this.debugStack = environment.debugStack; this.debugStack.push(name); }; AbstractManager.prototype._pushEngineToDebugStack = function (name, environment) { this.debugStack = environment.debugStack; this.debugStack.pushEngine(name); }; } function instrumentationPayload(def) { return { object: `${def.name}:${def.outlet}` }; } const CAPABILITIES = { dynamicLayout: false, dynamicTag: false, prepareArgs: false, createArgs: false, attributeHook: false, elementHook: false, createCaller: true, dynamicScope: true, updateHook: true, createInstance: true }; class OutletComponentManager extends AbstractManager { create(environment, definition, _args, dynamicScope) { if (true /* DEBUG */) { this._pushToDebugStack(`template:${definition.template.referrer.moduleName}`, environment); } dynamicScope.outletState = definition.ref; let controller = definition.controller; let self = controller === undefined ? _runtime.UNDEFINED_REFERENCE : new RootReference(controller); return { self, finalize: (0, _instrumentation._instrumentStart)('render.outlet', instrumentationPayload, definition) }; } layoutFor(_state, _component, _env) { throw new Error('Method not implemented.'); } getLayout({ template }, _resolver) { // The router has already resolved the template const layout = template.asLayout(); return { handle: layout.compile(), symbolTable: layout.symbolTable }; } getCapabilities() { return CAPABILITIES; } getSelf({ self }) { return self; } getTag() { // an outlet has no hooks return _reference.CONSTANT_TAG; } didRenderLayout(state) { state.finalize(); if (true /* DEBUG */) { this.debugStack.pop(); } } getDestructor() { return null; } } const OUTLET_MANAGER = new OutletComponentManager(); class OutletComponentDefinition { constructor(state, manager = OUTLET_MANAGER) { this.state = state; this.manager = manager; } } function createRootOutlet(outletView) { if (_environment2.ENV._APPLICATION_TEMPLATE_WRAPPER) { const WRAPPED_CAPABILITIES = (0, _polyfills.assign)({}, CAPABILITIES, { dynamicTag: true, elementHook: true }); const WrappedOutletComponentManager = class extends OutletComponentManager { getTagName(_component) { return 'div'; } getLayout(state) { // The router has already resolved the template const template = state.template; const layout = template.asWrappedLayout(); return { handle: layout.compile(), symbolTable: layout.symbolTable }; } getCapabilities() { return WRAPPED_CAPABILITIES; } didCreateElement(component, element, _operations) { // to add GUID id and class element.setAttribute('class', 'ember-view'); element.setAttribute('id', (0, _utils.guidFor)(component)); } }; const WRAPPED_OUTLET_MANAGER = new WrappedOutletComponentManager(); return new OutletComponentDefinition(outletView.state, WRAPPED_OUTLET_MANAGER); } else { return new OutletComponentDefinition(outletView.state); } } // tslint:disable-next-line:no-empty function NOOP() {} /** @module ember */ /** Represents the internal state of the component. @class ComponentStateBucket @private */ class ComponentStateBucket { constructor(environment, component, args, finalizer, hasWrappedElement) { this.environment = environment; this.component = component; this.args = args; this.finalizer = finalizer; this.hasWrappedElement = hasWrappedElement; this.classRef = null; this.classRef = null; this.argsRevision = args === null ? 0 : args.tag.value(); } destroy() { let { component, environment } = this; if (environment.isInteractive) { component.trigger('willDestroyElement'); component.trigger('willClearRender'); } environment.destroyedComponents.push(component); } finalize() { let { finalizer } = this; finalizer(); this.finalizer = NOOP; } } function referenceForKey(component, key) { return component[ROOT_REF].get(key); } function referenceForParts(component, parts) { let isAttrs = parts[0] === 'attrs'; // TODO deprecate this if (isAttrs) { parts.shift(); if (parts.length === 1) { return referenceForKey(component, parts[0]); } } return referenceFromParts(component[ROOT_REF], parts); } // TODO we should probably do this transform at build time function wrapComponentClassAttribute(hash) { if (hash === null) { return; } let [keys, values] = hash; let index = keys === null ? -1 : keys.indexOf('class'); if (index !== -1) { let value = values[index]; if (!Array.isArray(value)) { return; } let [type] = value; if (type === _wireFormat.Ops.Get || type === _wireFormat.Ops.MaybeLocal) { let path = value[value.length - 1]; let propName = path[path.length - 1]; values[index] = [_wireFormat.Ops.Helper, '-class', [value, propName], null]; } } } const AttributeBinding = { parse(microsyntax) { let colonIndex = microsyntax.indexOf(':'); if (colonIndex === -1) { true && !(microsyntax !== 'class') && (0, _debug.assert)('You cannot use class as an attributeBinding, use classNameBindings instead.', microsyntax !== 'class'); return [microsyntax, microsyntax, true]; } else { let prop = microsyntax.substring(0, colonIndex); let attribute = microsyntax.substring(colonIndex + 1); true && !(attribute !== 'class') && (0, _debug.assert)('You cannot use class as an attributeBinding, use classNameBindings instead.', attribute !== 'class'); return [prop, attribute, false]; } }, install(_element, component, parsed, operations) { let [prop, attribute, isSimple] = parsed; if (attribute === 'id') { let elementId = (0, _metal.get)(component, prop); if (elementId === undefined || elementId === null) { elementId = component.elementId; } elementId = _runtime.PrimitiveReference.create(elementId); operations.setAttribute('id', elementId, true, null); // operations.addStaticAttribute(element, 'id', elementId); return; } let isPath = prop.indexOf('.') > -1; let reference = isPath ? referenceForParts(component, prop.split('.')) : referenceForKey(component, prop); true && !!(isSimple && isPath) && (0, _debug.assert)(`Illegal attributeBinding: '${prop}' is not a valid attribute name.`, !(isSimple && isPath)); if (attribute === 'style') { reference = new StyleBindingReference(reference, referenceForKey(component, 'isVisible')); } operations.setAttribute(attribute, reference, false, null); // operations.addDynamicAttribute(element, attribute, reference, false); } }; const DISPLAY_NONE = 'display: none;'; const SAFE_DISPLAY_NONE = htmlSafe(DISPLAY_NONE); class StyleBindingReference extends _reference.CachedReference { constructor(inner, isVisible) { super(); this.inner = inner; this.isVisible = isVisible; this.tag = (0, _reference.combine)([inner.tag, isVisible.tag]); } compute() { let value = this.inner.value(); let isVisible = this.isVisible.value(); if (isVisible !== false) { return value; } else if (!value) { return SAFE_DISPLAY_NONE; } else { let style = value + ' ' + DISPLAY_NONE; return isHTMLSafe(value) ? htmlSafe(style) : style; } } } const IsVisibleBinding = { install(_element, component, operations) { operations.setAttribute('style', (0, _reference.map)(referenceForKey(component, 'isVisible'), this.mapStyleValue), false, null); // // the upstream type for addDynamicAttribute's `value` argument // // appears to be incorrect. It is currently a Reference, I // // think it should be a Reference. // operations.addDynamicAttribute(element, 'style', ref as any as Reference, false); }, mapStyleValue(isVisible) { return isVisible === false ? SAFE_DISPLAY_NONE : null; } }; const ClassNameBinding = { install(_element, component, microsyntax, operations) { let [prop, truthy, falsy] = microsyntax.split(':'); let isStatic = prop === ''; if (isStatic) { operations.setAttribute('class', _runtime.PrimitiveReference.create(truthy), true, null); } else { let isPath = prop.indexOf('.') > -1; let parts = isPath ? prop.split('.') : []; let value = isPath ? referenceForParts(component, parts) : referenceForKey(component, prop); let ref; if (truthy === undefined) { ref = new SimpleClassNameBindingReference(value, isPath ? parts[parts.length - 1] : prop); } else { ref = new ColonClassNameBindingReference(value, truthy, falsy); } operations.setAttribute('class', ref, false, null); // // the upstream type for addDynamicAttribute's `value` argument // // appears to be incorrect. It is currently a Reference, I // // think it should be a Reference. // operations.addDynamicAttribute(element, 'class', ref as any as Reference, false); } } }; class SimpleClassNameBindingReference extends _reference.CachedReference { constructor(inner, path) { super(); this.inner = inner; this.path = path; this.tag = inner.tag; this.inner = inner; this.path = path; this.dasherizedPath = null; } compute() { let value = this.inner.value(); if (value === true) { let { path, dasherizedPath } = this; return dasherizedPath || (this.dasherizedPath = (0, _string.dasherize)(path)); } else if (value || value === 0) { return String(value); } else { return null; } } } class ColonClassNameBindingReference extends _reference.CachedReference { constructor(inner, truthy = null, falsy = null) { super(); this.inner = inner; this.truthy = truthy; this.falsy = falsy; this.tag = inner.tag; } compute() { let { inner, truthy, falsy } = this; return inner.value() ? truthy : falsy; } } // ComponentArgs takes EvaluatedNamedArgs and converts them into the // inputs needed by CurlyComponents (attrs and props, with mutable // cells, etc). function processComponentArgs(namedArgs) { let keys = namedArgs.names; let attrs = namedArgs.value(); let props = Object.create(null); let args = Object.create(null); props[ARGS] = args; for (let i = 0; i < keys.length; i++) { let name = keys[i]; let ref = namedArgs.get(name); let value = attrs[name]; if (typeof value === 'function' && value[ACTION]) { attrs[name] = value; } else if (ref[UPDATE]) { attrs[name] = new MutableCell(ref, value); } args[name] = ref; props[name] = value; } props.attrs = attrs; return props; } const REF = (0, _utils.symbol)('REF'); class MutableCell { constructor(ref, value) { this[_views.MUTABLE_CELL] = true; this[REF] = ref; this.value = value; } update(val) { this[REF][UPDATE](val); } } function aliasIdToElementId(args, props) { if (args.named.has('id')) { // tslint:disable-next-line:max-line-length true && !!args.named.has('elementId') && (0, _debug.assert)(`You cannot invoke a component with both 'id' and 'elementId' at the same time.`, !args.named.has('elementId')); props.elementId = props.id; } } function isTemplateFactory(template) { return typeof template.create === 'function'; } // We must traverse the attributeBindings in reverse keeping track of // what has already been applied. This is essentially refining the concatenated // properties applying right to left. function applyAttributeBindings(element, attributeBindings, component, operations) { let seen = []; let i = attributeBindings.length - 1; while (i !== -1) { let binding = attributeBindings[i]; let parsed = AttributeBinding.parse(binding); let attribute = parsed[1]; if (seen.indexOf(attribute) === -1) { seen.push(attribute); AttributeBinding.install(element, component, parsed, operations); } i--; } if (seen.indexOf('id') === -1) { let id = component.elementId ? component.elementId : (0, _utils.guidFor)(component); operations.setAttribute('id', _runtime.PrimitiveReference.create(id), false, null); } if (seen.indexOf('style') === -1) { IsVisibleBinding.install(element, component, operations); } } const DEFAULT_LAYOUT = _container.privatize`template:components/-default`; class CurlyComponentManager extends AbstractManager { getLayout(state, _resolver) { return { // TODO fix handle: state.handle, symbolTable: state.symbolTable }; } templateFor(component, resolver) { let layout = (0, _metal.get)(component, 'layout'); if (layout !== undefined) { // This needs to be cached by template.id if (isTemplateFactory(layout)) { return resolver.createTemplate(layout, (0, _owner.getOwner)(component)); } else { // we were provided an instance already return layout; } } let owner = (0, _owner.getOwner)(component); let layoutName = (0, _metal.get)(component, 'layoutName'); if (layoutName) { let template = owner.lookup('template:' + layoutName); if (template) { return template; } } return owner.lookup(DEFAULT_LAYOUT); } getDynamicLayout({ component }, resolver) { const template = this.templateFor(component, resolver); const layout = template.asWrappedLayout(); return { handle: layout.compile(), symbolTable: layout.symbolTable }; } getTagName(state) { const { component, hasWrappedElement } = state; if (!hasWrappedElement) { return null; } return component && component.tagName || 'div'; } getCapabilities(state) { return state.capabilities; } prepareArgs(state, args) { const { positionalParams } = state.ComponentClass.class; // early exits if (positionalParams === undefined || positionalParams === null || args.positional.length === 0) { return null; } let named; if (typeof positionalParams === 'string') { true && !!args.named.has(positionalParams) && (0, _debug.assert)(`You cannot specify positional parameters and the hash argument \`${positionalParams}\`.`, !args.named.has(positionalParams)); named = { [positionalParams]: args.positional.capture() }; (0, _polyfills.assign)(named, args.named.capture().map); } else if (Array.isArray(positionalParams) && positionalParams.length > 0) { const count = Math.min(positionalParams.length, args.positional.length); named = {}; (0, _polyfills.assign)(named, args.named.capture().map); if (_deprecatedFeatures.POSITIONAL_PARAM_CONFLICT) { for (let i = 0; i < count; i++) { const name = positionalParams[i]; true && !!args.named.has(name) && (0, _debug.deprecate)(`You cannot specify both a positional param (at position ${i}) and the hash argument \`${name}\`.`, !args.named.has(name), { id: 'ember-glimmer.positional-param-conflict', until: '3.5.0' }); named[name] = args.positional.at(i); } } } else { return null; } return { positional: _util.EMPTY_ARRAY, named }; } /* * This hook is responsible for actually instantiating the component instance. * It also is where we perform additional bookkeeping to support legacy * features like exposed by view mixins like ChildViewSupport, ActionSupport, * etc. */ create(environment, state, args, dynamicScope, callerSelfRef, hasBlock) { if (true /* DEBUG */) { this._pushToDebugStack(`component:${state.name}`, environment); } // Get the nearest concrete component instance from the scope. "Virtual" // components will be skipped. let parentView = dynamicScope.view; // Get the Ember.Component subclass to instantiate for this component. let factory = state.ComponentClass; // Capture the arguments, which tells Glimmer to give us our own, stable // copy of the Arguments object that is safe to hold on to between renders. let capturedArgs = args.named.capture(); let props = processComponentArgs(capturedArgs); // Alias `id` argument to `elementId` property on the component instance. aliasIdToElementId(args, props); // Set component instance's parentView property to point to nearest concrete // component. props.parentView = parentView; // Set whether this component was invoked with a block // (`{{#my-component}}{{/my-component}}`) or without one // (`{{my-component}}`). props[HAS_BLOCK] = hasBlock; // Save the current `this` context of the template as the component's // `_targetObject`, so bubbled actions are routed to the right place. props._targetObject = callerSelfRef.value(); // static layout asserts CurriedDefinition if (state.template) { props.layout = state.template; } // Now that we've built up all of the properties to set on the component instance, // actually create it. let component = factory.create(props); let finalizer = (0, _instrumentation._instrumentStart)('render.component', initialRenderInstrumentDetails, component); // We become the new parentView for downstream components, so save our // component off on the dynamic scope. dynamicScope.view = component; // Unless we're the root component, we need to add ourselves to our parent // component's childViews array. if (parentView !== null && parentView !== undefined) { (0, _views.addChildView)(parentView, component); } component.trigger('didReceiveAttrs'); let hasWrappedElement = component.tagName !== ''; // We usually do this in the `didCreateElement`, but that hook doesn't fire for tagless components if (!hasWrappedElement) { if (environment.isInteractive) { component.trigger('willRender'); } component._transitionTo('hasElement'); if (environment.isInteractive) { component.trigger('willInsertElement'); } } // Track additional lifecycle metadata about this component in a state bucket. // Essentially we're saving off all the state we'll need in the future. let bucket = new ComponentStateBucket(environment, component, capturedArgs, finalizer, hasWrappedElement); if (args.named.has('class')) { bucket.classRef = args.named.get('class'); } if (true /* DEBUG */) { processComponentInitializationAssertions(component, props); } if (environment.isInteractive && hasWrappedElement) { component.trigger('willRender'); } return bucket; } getSelf({ component }) { return component[ROOT_REF]; } didCreateElement({ component, classRef, environment }, element, operations) { (0, _views.setViewElement)(component, element); let { attributeBindings, classNames, classNameBindings } = component; if (attributeBindings && attributeBindings.length) { applyAttributeBindings(element, attributeBindings, component, operations); } else { let id = component.elementId ? component.elementId : (0, _utils.guidFor)(component); operations.setAttribute('id', _runtime.PrimitiveReference.create(id), false, null); IsVisibleBinding.install(element, component, operations); } if (classRef) { const ref = new SimpleClassNameBindingReference(classRef, classRef['_propertyKey']); operations.setAttribute('class', ref, false, null); } if (classNames && classNames.length) { classNames.forEach(name => { operations.setAttribute('class', _runtime.PrimitiveReference.create(name), false, null); }); } if (classNameBindings && classNameBindings.length) { classNameBindings.forEach(binding => { ClassNameBinding.install(element, component, binding, operations); }); } operations.setAttribute('class', _runtime.PrimitiveReference.create('ember-view'), false, null); if ('ariaRole' in component) { operations.setAttribute('role', referenceForKey(component, 'ariaRole'), false, null); } component._transitionTo('hasElement'); if (environment.isInteractive) { component.trigger('willInsertElement'); } } didRenderLayout(bucket, bounds) { bucket.component[BOUNDS] = bounds; bucket.finalize(); if (true /* DEBUG */) { this.debugStack.pop(); } } getTag({ args, component }) { return args ? (0, _reference.combine)([args.tag, component[DIRTY_TAG]]) : component[DIRTY_TAG]; } didCreate({ component, environment }) { if (environment.isInteractive) { component._transitionTo('inDOM'); component.trigger('didInsertElement'); component.trigger('didRender'); } } update(bucket) { let { component, args, argsRevision, environment } = bucket; if (true /* DEBUG */) { this._pushToDebugStack(component._debugContainerKey, environment); } bucket.finalizer = (0, _instrumentation._instrumentStart)('render.component', rerenderInstrumentDetails, component); if (args && !args.tag.validate(argsRevision)) { let props = processComponentArgs(args); bucket.argsRevision = args.tag.value(); component[IS_DISPATCHING_ATTRS] = true; component.setProperties(props); component[IS_DISPATCHING_ATTRS] = false; component.trigger('didUpdateAttrs'); component.trigger('didReceiveAttrs'); } if (environment.isInteractive) { component.trigger('willUpdate'); component.trigger('willRender'); } } didUpdateLayout(bucket) { bucket.finalize(); if (true /* DEBUG */) { this.debugStack.pop(); } } didUpdate({ component, environment }) { if (environment.isInteractive) { component.trigger('didUpdate'); component.trigger('didRender'); } } getDestructor(stateBucket) { return stateBucket; } } function processComponentInitializationAssertions(component, props) { true && !(() => { let { classNameBindings } = component; for (let i = 0; i < classNameBindings.length; i++) { let binding = classNameBindings[i]; if (typeof binding !== 'string' || binding.length === 0) { return false; } } return true; })() && (0, _debug.assert)(`classNameBindings must be non-empty strings: ${component}`, (() => { let { classNameBindings } = component;for (let i = 0; i < classNameBindings.length; i++) { let binding = classNameBindings[i];if (typeof binding !== 'string' || binding.length === 0) { return false; } }return true; })()); true && !(() => { let { classNameBindings } = component; for (let i = 0; i < classNameBindings.length; i++) { let binding = classNameBindings[i]; if (binding.split(' ').length > 1) { return false; } } return true; })() && (0, _debug.assert)(`classNameBindings must not have spaces in them: ${component}`, (() => { let { classNameBindings } = component;for (let i = 0; i < classNameBindings.length; i++) { let binding = classNameBindings[i];if (binding.split(' ').length > 1) { return false; } }return true; })()); true && !(component.tagName !== '' || !component.classNameBindings || component.classNameBindings.length === 0) && (0, _debug.assert)(`You cannot use \`classNameBindings\` on a tag-less component: ${component}`, component.tagName !== '' || !component.classNameBindings || component.classNameBindings.length === 0); true && !(component.tagName !== '' || props.id === component.elementId || !component.elementId && component.elementId !== '') && (0, _debug.assert)(`You cannot use \`elementId\` on a tag-less component: ${component}`, component.tagName !== '' || props.id === component.elementId || !component.elementId && component.elementId !== ''); true && !(component.tagName !== '' || !component.attributeBindings || component.attributeBindings.length === 0) && (0, _debug.assert)(`You cannot use \`attributeBindings\` on a tag-less component: ${component}`, component.tagName !== '' || !component.attributeBindings || component.attributeBindings.length === 0); } function initialRenderInstrumentDetails(component) { return component.instrumentDetails({ initialRender: true }); } function rerenderInstrumentDetails(component) { return component.instrumentDetails({ initialRender: false }); } const CURLY_CAPABILITIES = { dynamicLayout: true, dynamicTag: true, prepareArgs: true, createArgs: true, attributeHook: true, elementHook: true, createCaller: true, dynamicScope: true, updateHook: true, createInstance: true }; const CURLY_COMPONENT_MANAGER = new CurlyComponentManager(); class CurlyComponentDefinition { // tslint:disable-next-line:no-shadowed-variable constructor(name, ComponentClass, handle, template, args) { this.name = name; this.ComponentClass = ComponentClass; this.handle = handle; this.manager = CURLY_COMPONENT_MANAGER; const layout = template && template.asLayout(); const symbolTable = layout ? layout.symbolTable : undefined; this.symbolTable = symbolTable; this.template = template; this.args = args; this.state = { name, ComponentClass, handle, template, capabilities: CURLY_CAPABILITIES, symbolTable }; } } class RootComponentManager extends CurlyComponentManager { constructor(component) { super(); this.component = component; } getLayout(_state, resolver) { const template = this.templateFor(this.component, resolver); const layout = template.asWrappedLayout(); return { handle: layout.compile(), symbolTable: layout.symbolTable }; } create(environment, _state, _args, dynamicScope) { let component = this.component; if (true /* DEBUG */) { this._pushToDebugStack(component._debugContainerKey, environment); } let finalizer = (0, _instrumentation._instrumentStart)('render.component', initialRenderInstrumentDetails, component); dynamicScope.view = component; let hasWrappedElement = component.tagName !== ''; // We usually do this in the `didCreateElement`, but that hook doesn't fire for tagless components if (!hasWrappedElement) { if (environment.isInteractive) { component.trigger('willRender'); } component._transitionTo('hasElement'); if (environment.isInteractive) { component.trigger('willInsertElement'); } } if (true /* DEBUG */) { processComponentInitializationAssertions(component, {}); } return new ComponentStateBucket(environment, component, null, finalizer, hasWrappedElement); } } // ROOT is the top-level template it has nothing but one yield. // it is supposed to have a dummy element const ROOT_CAPABILITIES = { dynamicLayout: false, dynamicTag: true, prepareArgs: false, createArgs: false, attributeHook: true, elementHook: true, createCaller: true, dynamicScope: true, updateHook: true, createInstance: false }; class RootComponentDefinition { constructor(component) { this.component = component; let manager = new RootComponentManager(component); this.manager = manager; let factory = _container.FACTORY_FOR.get(component); this.state = { name: factory.fullName.slice(10), capabilities: ROOT_CAPABILITIES, ComponentClass: factory, handle: null }; } getTag({ component }) { return component[DIRTY_TAG]; } } class DynamicScope { constructor(view, outletState) { this.view = view; this.outletState = outletState; } child() { return new DynamicScope(this.view, this.outletState); } get(key) { // tslint:disable-next-line:max-line-length true && !(key === 'outletState') && (0, _debug.assert)(`Using \`-get-dynamic-scope\` is only supported for \`outletState\` (you used \`${key}\`).`, key === 'outletState'); return this.outletState; } set(key, value) { // tslint:disable-next-line:max-line-length true && !(key === 'outletState') && (0, _debug.assert)(`Using \`-with-dynamic-scope\` is only supported for \`outletState\` (you used \`${key}\`).`, key === 'outletState'); this.outletState = value; return value; } } class RootState { constructor(root, env, template, self, parentElement, dynamicScope, builder) { true && !(template !== undefined) && (0, _debug.assert)(`You cannot render \`${self.value()}\` without a template.`, template !== undefined); this.id = (0, _views.getViewId)(root); this.env = env; this.root = root; this.result = undefined; this.shouldReflush = false; this.destroyed = false; let options = this.options = { alwaysRevalidate: false }; this.render = () => { let layout = template.asLayout(); let handle = layout.compile(); let iterator = (0, _runtime.renderMain)(layout['compiler'].program, env, self, dynamicScope, builder(env, { element: parentElement, nextSibling: null }), handle); let iteratorResult; do { iteratorResult = iterator.next(); } while (!iteratorResult.done); let result = this.result = iteratorResult.value; // override .render function after initial render this.render = () => result.rerender(options); }; } isFor(possibleRoot) { return this.root === possibleRoot; } destroy() { let { result, env } = this; this.destroyed = true; this.env = undefined; this.root = null; this.result = undefined; this.render = undefined; if (result) { /* Handles these scenarios: * When roots are removed during standard rendering process, a transaction exists already `.begin()` / `.commit()` are not needed. * When roots are being destroyed manually (`component.append(); component.destroy() case), no transaction exists already. * When roots are being destroyed during `Renderer#destroy`, no transaction exists */ let needsTransaction = !env.inTransaction; if (needsTransaction) { env.begin(); } try { result.destroy(); } finally { if (needsTransaction) { env.commit(); } } } } } const renderers = []; function _resetRenderers() { renderers.length = 0; } (0, _metal.setHasViews)(() => renderers.length > 0); function register(renderer) { true && !(renderers.indexOf(renderer) === -1) && (0, _debug.assert)('Cannot register the same renderer twice', renderers.indexOf(renderer) === -1); renderers.push(renderer); } function deregister(renderer) { let index = renderers.indexOf(renderer); true && !(index !== -1) && (0, _debug.assert)('Cannot deregister unknown unregistered renderer', index !== -1); renderers.splice(index, 1); } function loopBegin() { for (let i = 0; i < renderers.length; i++) { renderers[i]._scheduleRevalidate(); } } function K() { /* noop */ } let renderSettledDeferred = null; /* Returns a promise which will resolve when rendering has settled. Settled in this context is defined as when all of the tags in use are "current" (e.g. `renderers.every(r => r._isValid())`). When this is checked at the _end_ of the run loop, this essentially guarantees that all rendering is completed. @method renderSettled @returns {Promise} a promise which fulfills when rendering has settled */ function renderSettled() { if (renderSettledDeferred === null) { renderSettledDeferred = _rsvp.default.defer(); // if there is no current runloop, the promise created above will not have // a chance to resolve (because its resolved in backburner's "end" event) if (!(0, _runloop.getCurrentRunLoop)()) { // ensure a runloop has been kicked off _runloop.backburner.schedule('actions', null, K); } } return renderSettledDeferred.promise; } function resolveRenderPromise() { if (renderSettledDeferred !== null) { let resolve = renderSettledDeferred.resolve; renderSettledDeferred = null; _runloop.backburner.join(null, resolve); } } let loops = 0; function loopEnd() { for (let i = 0; i < renderers.length; i++) { if (!renderers[i]._isValid()) { if (loops > 10) { loops = 0; // TODO: do something better renderers[i].destroy(); throw new Error('infinite rendering invalidation detected'); } loops++; return _runloop.backburner.join(null, K); } } loops = 0; resolveRenderPromise(); } _runloop.backburner.on('begin', loopBegin); _runloop.backburner.on('end', loopEnd); class Renderer { constructor(env, rootTemplate, _viewRegistry = _views.fallbackViewRegistry, destinedForDOM = false, builder = _runtime.clientBuilder) { this._env = env; this._rootTemplate = rootTemplate; this._viewRegistry = _viewRegistry; this._destinedForDOM = destinedForDOM; this._destroyed = false; this._roots = []; this._lastRevision = -1; this._isRenderingRoots = false; this._removedRoots = []; this._builder = builder; } // renderer HOOKS appendOutletView(view, target) { let definition = createRootOutlet(view); this._appendDefinition(view, (0, _runtime.curry)(definition), target); } appendTo(view, target) { let definition = new RootComponentDefinition(view); this._appendDefinition(view, (0, _runtime.curry)(definition), target); } _appendDefinition(root, definition, target) { let self = new UnboundReference(definition); let dynamicScope = new DynamicScope(null, _runtime.UNDEFINED_REFERENCE); let rootState = new RootState(root, this._env, this._rootTemplate, self, target, dynamicScope, this._builder); this._renderRoot(rootState); } rerender() { this._scheduleRevalidate(); } register(view) { let id = (0, _views.getViewId)(view); true && !!this._viewRegistry[id] && (0, _debug.assert)('Attempted to register a view with an id already in use: ' + id, !this._viewRegistry[id]); this._viewRegistry[id] = view; } unregister(view) { delete this._viewRegistry[(0, _views.getViewId)(view)]; } remove(view) { view._transitionTo('destroying'); this.cleanupRootFor(view); (0, _views.setViewElement)(view, null); if (this._destinedForDOM) { view.trigger('didDestroyElement'); } if (!view.isDestroying) { view.destroy(); } } cleanupRootFor(view) { // no need to cleanup roots if we have already been destroyed if (this._destroyed) { return; } let roots = this._roots; // traverse in reverse so we can remove items // without mucking up the index let i = this._roots.length; while (i--) { let root = roots[i]; if (root.isFor(view)) { root.destroy(); roots.splice(i, 1); } } } destroy() { if (this._destroyed) { return; } this._destroyed = true; this._clearAllRoots(); } getBounds(view) { let bounds = view[BOUNDS]; let parentElement = bounds.parentElement(); let firstNode = bounds.firstNode(); let lastNode = bounds.lastNode(); return { parentElement, firstNode, lastNode }; } createElement(tagName) { return this._env.getAppendOperations().createElement(tagName); } _renderRoot(root) { let { _roots: roots } = this; roots.push(root); if (roots.length === 1) { register(this); } this._renderRootsTransaction(); } _renderRoots() { let { _roots: roots, _env: env, _removedRoots: removedRoots } = this; let globalShouldReflush; let initialRootsLength; do { env.begin(); try { // ensure that for the first iteration of the loop // each root is processed initialRootsLength = roots.length; globalShouldReflush = false; for (let i = 0; i < roots.length; i++) { let root = roots[i]; if (root.destroyed) { // add to the list of roots to be removed // they will be removed from `this._roots` later removedRoots.push(root); // skip over roots that have been marked as destroyed continue; } let { shouldReflush } = root; // when processing non-initial reflush loops, // do not process more roots than needed if (i >= initialRootsLength && !shouldReflush) { continue; } root.options.alwaysRevalidate = shouldReflush; // track shouldReflush based on this roots render result shouldReflush = root.shouldReflush = (0, _metal.runInTransaction)(root, 'render'); // globalShouldReflush should be `true` if *any* of // the roots need to reflush globalShouldReflush = globalShouldReflush || shouldReflush; } this._lastRevision = _reference.CURRENT_TAG.value(); } finally { env.commit(); } } while (globalShouldReflush || roots.length > initialRootsLength); // remove any roots that were destroyed during this transaction while (removedRoots.length) { let root = removedRoots.pop(); let rootIndex = roots.indexOf(root); roots.splice(rootIndex, 1); } if (this._roots.length === 0) { deregister(this); } } _renderRootsTransaction() { if (this._isRenderingRoots) { // currently rendering roots, a new root was added and will // be processed by the existing _renderRoots invocation return; } // used to prevent calling _renderRoots again (see above) // while we are actively rendering roots this._isRenderingRoots = true; let completedWithoutError = false; try { this._renderRoots(); completedWithoutError = true; } finally { if (!completedWithoutError) { this._lastRevision = _reference.CURRENT_TAG.value(); if (this._env.inTransaction === true) { this._env.commit(); } } this._isRenderingRoots = false; } } _clearAllRoots() { let roots = this._roots; for (let i = 0; i < roots.length; i++) { let root = roots[i]; root.destroy(); } this._removedRoots.length = 0; this._roots = []; // if roots were present before destroying // deregister this renderer instance if (roots.length) { deregister(this); } } _scheduleRevalidate() { _runloop.backburner.scheduleOnce('render', this, this._revalidate); } _isValid() { return this._destroyed || this._roots.length === 0 || _reference.CURRENT_TAG.validate(this._lastRevision); } _revalidate() { if (this._isValid()) { return; } this._renderRootsTransaction(); } } class InertRenderer extends Renderer { static create({ env, rootTemplate, _viewRegistry, builder }) { return new this(env, rootTemplate, _viewRegistry, false, builder); } getElement(_view) { throw new Error('Accessing `this.element` is not allowed in non-interactive environments (such as FastBoot).'); } } class InteractiveRenderer extends Renderer { static create({ env, rootTemplate, _viewRegistry, builder }) { return new this(env, rootTemplate, _viewRegistry, true, builder); } getElement(view) { return (0, _views.getViewElement)(view); } } let TEMPLATES = {}; function setTemplates(templates) { TEMPLATES = templates; } function getTemplates() { return TEMPLATES; } function getTemplate(name) { if (TEMPLATES.hasOwnProperty(name)) { return TEMPLATES[name]; } } function hasTemplate(name) { return TEMPLATES.hasOwnProperty(name); } function setTemplate(name, template) { return TEMPLATES[name] = template; } /// /** @module ember */ /** Calls [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
{{loc '_welcome_'}}
``` ```html
Bonjour
``` See [String.loc](/api/ember/release/classes/String/methods/loc?anchor=loc) for how to set up localized string references. @method loc @for Ember.Templates.helpers @param {String} str The string to format. @see {String#loc} @public */ var loc$1 = helper(function (params) { return _string.loc.apply(null, params); }); class CompileTimeLookup { constructor(resolver) { this.resolver = resolver; } getCapabilities(handle) { let definition = this.resolver.resolve(handle); let { manager, state } = definition; return manager.getCapabilities(state); } getLayout(handle) { const { manager, state } = this.resolver.resolve(handle); const capabilities = manager.getCapabilities(state); if (capabilities.dynamicLayout) { return null; } const invocation = manager.getLayout(state, this.resolver); return { // TODO: this seems weird, it already is compiled compile() { return invocation.handle; }, symbolTable: invocation.symbolTable }; } lookupHelper(name, referrer) { return this.resolver.lookupHelper(name, referrer); } lookupModifier(name, referrer) { return this.resolver.lookupModifier(name, referrer); } lookupComponentDefinition(name, referrer) { return this.resolver.lookupComponentHandle(name, referrer); } lookupPartial(name, referrer) { return this.resolver.lookupPartial(name, referrer); } } const CAPABILITIES$1 = { dynamicLayout: false, dynamicTag: false, prepareArgs: false, createArgs: true, attributeHook: false, elementHook: false, createCaller: false, dynamicScope: true, updateHook: true, createInstance: true }; function capabilities(managerAPI, options = {}) { true && !(managerAPI === '3.4') && (0, _debug.assert)('Invalid component manager compatibility specified', managerAPI === '3.4'); return { asyncLifeCycleCallbacks: !!options.asyncLifecycleCallbacks, destructor: !!options.destructor }; } function hasAsyncLifeCycleCallbacks(delegate) { return delegate.capabilities.asyncLifeCycleCallbacks; } function hasDestructors(delegate) { return delegate.capabilities.destructor; } function valueForCapturedArgs(args) { return { named: args.named.value(), positional: args.positional.value() }; } /** The CustomComponentManager allows addons to provide custom component implementations that integrate seamlessly into Ember. This is accomplished through a delegate, registered with the custom component manager, which implements a set of hooks that determine component behavior. To create a custom component manager, instantiate a new CustomComponentManager class and pass the delegate as the first argument: ```js let manager = new CustomComponentManager({ // ...delegate implementation... }); ``` ## Delegate Hooks Throughout the lifecycle of a component, the component manager will invoke delegate hooks that are responsible for surfacing those lifecycle changes to the end developer. * `create()` - invoked when a new instance of a component should be created * `update()` - invoked when the arguments passed to a component change * `getContext()` - returns the object that should be */ class CustomComponentManager extends AbstractManager { create(_env, definition, args) { const { delegate } = definition; const capturedArgs = args.capture(); let invocationArgs = valueForCapturedArgs(capturedArgs); const component = delegate.createComponent(definition.ComponentClass.class, invocationArgs); return new CustomComponentState(delegate, component, capturedArgs); } update({ delegate, component, args }) { delegate.updateComponent(component, valueForCapturedArgs(args)); } didCreate({ delegate, component }) { if (hasAsyncLifeCycleCallbacks(delegate)) { delegate.didCreateComponent(component); } } didUpdate({ delegate, component }) { if (hasAsyncLifeCycleCallbacks(delegate)) { delegate.didUpdateComponent(component); } } getContext({ delegate, component }) { delegate.getContext(component); } getSelf({ delegate, component }) { const context = delegate.getContext(component); return new RootReference(context); } getDestructor(state) { if (hasDestructors(state.delegate)) { return state; } else { return null; } } getCapabilities() { return CAPABILITIES$1; } getTag({ args }) { return args.tag; } didRenderLayout() {} getLayout(state) { return { handle: state.template.asLayout().compile(), symbolTable: state.symbolTable }; } } const CUSTOM_COMPONENT_MANAGER = new CustomComponentManager(); /** * Stores internal state about a component instance after it's been created. */ class CustomComponentState { constructor(delegate, component, args) { this.delegate = delegate; this.component = component; this.args = args; } destroy() { const { delegate, component } = this; if (hasDestructors(delegate)) { delegate.destroyComponent(component); } } } class CustomManagerDefinition { constructor(name, ComponentClass, delegate, template) { this.name = name; this.ComponentClass = ComponentClass; this.delegate = delegate; this.template = template; this.manager = CUSTOM_COMPONENT_MANAGER; const layout = template.asLayout(); const symbolTable = layout.symbolTable; this.symbolTable = symbolTable; this.state = { name, ComponentClass, template, symbolTable, delegate }; } } const CAPABILITIES$2 = { dynamicLayout: false, dynamicTag: false, prepareArgs: false, createArgs: false, attributeHook: false, elementHook: false, createCaller: true, dynamicScope: true, updateHook: true, createInstance: true }; class TemplateOnlyComponentManager extends AbstractManager { getLayout(template) { const layout = template.asLayout(); return { handle: layout.compile(), symbolTable: layout.symbolTable }; } getCapabilities() { return CAPABILITIES$2; } create() { return null; } getSelf() { return _runtime.NULL_REFERENCE; } getTag() { return _reference.CONSTANT_TAG; } getDestructor() { return null; } } const MANAGER = new TemplateOnlyComponentManager(); class TemplateOnlyComponentDefinition { constructor(state) { this.state = state; this.manager = MANAGER; } } class ComponentAssertionReference { constructor(component, message) { this.component = component; this.message = message; this.tag = component.tag; } value() { let value = this.component.value(); if (typeof value === 'string') { throw new TypeError(this.message); } return value; } get(property) { return this.component.get(property); } } var componentAssertionHelper = (_vm, args) => { if (true /* DEBUG */) { return new ComponentAssertionReference(args.positional.at(0), args.positional.at(1).value()); } else { return args.positional.at(0); } }; function classHelper({ positional }) { let path = positional.at(0); let args = positional.length; let value = path.value(); if (value === true) { if (args > 1) { return (0, _string.dasherize)(positional.at(1).value()); } return null; } if (value === false) { if (args > 2) { return (0, _string.dasherize)(positional.at(2).value()); } return null; } return value; } function classHelper$1(_vm, args) { return new InternalHelperReference(classHelper, args.capture()); } function htmlSafe$1({ positional }) { let path = positional.at(0); return new SafeString(path.value()); } function htmlSafeHelper(_vm, args) { return new InternalHelperReference(htmlSafe$1, args.capture()); } function inputTypeHelper({ positional }) { let type = positional.at(0).value(); if (type === 'checkbox') { return '-checkbox'; } return '-text-field'; } function inputTypeHelper$1(_vm, args) { return new InternalHelperReference(inputTypeHelper, args.capture()); } function normalizeClass({ positional }) { let classNameParts = positional.at(0).value().split('.'); let className = classNameParts[classNameParts.length - 1]; let value = positional.at(1).value(); if (value === true) { return (0, _string.dasherize)(className); } else if (!value && value !== 0) { return ''; } else { return String(value); } } function normalizeClassHelper(_vm, args) { return new InternalHelperReference(normalizeClass, args.capture()); } /** @module ember */ /** 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 }}
{{! 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 immediately 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 }}
``` 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: ```app/components/my-component.js import Component from '@ember/component'; export default 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 targeting 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/ember/release/classes/Component/methods/sendAction?anchor=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: ```app/components/my-component.js import Component from '@ember/component'; export default 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: ```app/components/my-input.js import Component from '@ember/component'; export default Component.extend({ actions: { setName(model, name) { model.set('name', name); } } }); ``` ```handlebars {{my-input submit=(action 'setName' model)}} ``` ```app/components/my-component.js import Component from '@ember/component'; export default 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 }}
``` 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
``` To disable bubbling, pass `bubbles=false` to the helper: ```handlebars ``` To disable bubbling with closure style actions you must create your own wrapper helper that makes use of `event.stopPropagation()`: ```handlebars
Hello
``` ```app/helpers/disable-bubbling.js import { helper } from '@ember/component/helper'; export function disableBubbling([action]) { return function(event) { event.stopPropagation(); return action(event); }; } export default 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/ember/release/classes/Component) in the documentation for `Component` 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
click me
``` See ["Event Names"](/api/ember/release/classes/Component) 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
click me
``` 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
click me with any key pressed
``` ### 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: ```app/templates/application.hbs
click me
``` ```app/controllers/application.js import Controller from '@ember/controller'; import { inject as service } from '@ember/service'; export default Controller.extend({ someService: service() }); ``` @method action @for Ember.Templates.helpers @public */ function action(_vm, args) { let { named, positional } = args; let capturedArgs = positional.capture(); // The first two argument slots are reserved. // pos[0] is the context (or `this`) // pos[1] is the action name or function // Anything else is an action argument. let [context, action, ...restArgs] = capturedArgs.references; // TODO: Is there a better way of doing this? let debugKey = action._propertyKey; let target = named.has('target') ? named.get('target') : context; let processArgs = makeArgsProcessor(named.has('value') && named.get('value'), restArgs); let fn; if (typeof action[INVOKE] === 'function') { fn = makeClosureAction(action, action, action[INVOKE], processArgs, debugKey); } else if ((0, _reference.isConst)(target) && (0, _reference.isConst)(action)) { fn = makeClosureAction(context.value(), target.value(), action.value(), processArgs, debugKey); } else { fn = makeDynamicClosureAction(context.value(), target, action, processArgs, debugKey); } fn[ACTION] = true; return new UnboundReference(fn); } function NOOP$1(args) { return args; } function makeArgsProcessor(valuePathRef, actionArgsRef) { let mergeArgs; if (actionArgsRef.length > 0) { mergeArgs = args => { return actionArgsRef.map(ref => ref.value()).concat(args); }; } let readValue; if (valuePathRef) { readValue = args => { let valuePath = valuePathRef.value(); if (valuePath && args.length > 0) { args[0] = (0, _metal.get)(args[0], valuePath); } return args; }; } if (mergeArgs && readValue) { return args => { return readValue(mergeArgs(args)); }; } else { return mergeArgs || readValue || NOOP$1; } } function makeDynamicClosureAction(context, targetRef, actionRef, processArgs, debugKey) { // We don't allow undefined/null values, so this creates a throw-away action to trigger the assertions if (true /* DEBUG */) { makeClosureAction(context, targetRef.value(), actionRef.value(), processArgs, debugKey); } return (...args) => { return makeClosureAction(context, targetRef.value(), actionRef.value(), processArgs, debugKey)(...args); }; } function makeClosureAction(context, target, action, processArgs, debugKey) { let self; let fn; true && !(action !== undefined && action !== null) && (0, _debug.assert)(`Action passed is null or undefined in (action) from ${target}.`, action !== undefined && action !== null); if (typeof action[INVOKE] === 'function') { self = action; fn = action[INVOKE]; } else { let typeofAction = typeof action; if (typeofAction === 'string') { self = target; fn = target.actions && target.actions[action]; true && !fn && (0, _debug.assert)(`An action named '${action}' was not found in ${target}`, fn); } else if (typeofAction === 'function') { self = context; fn = action; } else { // tslint:disable-next-line:max-line-length true && !false && (0, _debug.assert)(`An action could not be made for \`${debugKey || action}\` in ${target}. Please confirm that you are using either a quoted action name (i.e. \`(action '${debugKey || 'myAction'}')\`) or a function available in ${target}.`, false); } } return (...args) => { let payload = { target: self, args, label: '@glimmer/closure-action' }; return (0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => { return (0, _runloop.join)(self, fn, ...processArgs(args)); }); }; } const isEmpty = value => { return value === null || value === undefined || typeof value.toString !== 'function'; }; const normalizeTextValue = value => { if (isEmpty(value)) { return ''; } return String(value); }; /** @module ember */ /** Concatenates the given arguments into a string. Example: ```handlebars {{some-component name=(concat firstName " " lastName)}} {{! would pass name=" " to the component}} ``` @public @method concat @for Ember.Templates.helpers @since 1.13.0 */ function concat({ positional }) { return positional.value().map(normalizeTextValue).join(''); } function concat$1(_vm, args) { return new InternalHelperReference(concat, args.capture()); } /** @module ember */ /** 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 equivalent: ```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}} ``` The `{{get}}` helper can also respect mutable values itself. For example: ```handlebars {{input value=(mut (get person factName)) type="text"}} ``` 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 get$1(_vm, args) { return GetHelperReference.create(args.positional.at(0), args.positional.at(1)); } function referenceFromPath(source, path) { let innerReference; if (path === undefined || path === null || path === '') { innerReference = _runtime.NULL_REFERENCE; } else if (typeof path === 'string' && path.indexOf('.') > -1) { innerReference = referenceFromParts(source, path.split('.')); } else { innerReference = source.get(path); } return innerReference; } class GetHelperReference extends CachedReference$1 { static create(sourceReference, pathReference) { if ((0, _reference.isConst)(pathReference)) { let path = pathReference.value(); return referenceFromPath(sourceReference, path); } else { return new GetHelperReference(sourceReference, pathReference); } } constructor(sourceReference, pathReference) { super(); this.sourceReference = sourceReference; this.pathReference = pathReference; this.lastPath = null; this.innerReference = _runtime.NULL_REFERENCE; let innerTag = this.innerTag = _reference.UpdatableTag.create(_reference.CONSTANT_TAG); this.tag = (0, _reference.combine)([sourceReference.tag, pathReference.tag, innerTag]); } compute() { let { lastPath, innerReference, innerTag } = this; let path = this.pathReference.value(); if (path !== lastPath) { innerReference = referenceFromPath(this.sourceReference, path); innerTag.inner.update(innerReference.tag); this.innerReference = innerReference; this.lastPath = path; } return innerReference.value(); } [UPDATE](value) { (0, _metal.set)(this.sourceReference.value(), this.pathReference.value(), value); } } /** @module ember */ /** 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. Note that the hash is an empty object with no prototype chain, therefore common methods like `toString` are not available in the resulting hash. If you need to use such a method, you can use the `call` or `apply` approach: ```js function toString(obj) { return Object.prototype.toString.apply(obj); } ``` @method hash @for Ember.Templates.helpers @param {Object} options @return {Object} Hash @since 2.3.0 @public */ function hash(_vm, args) { return args.named.capture(); } /** @module ember */ class ConditionalHelperReference extends CachedReference$1 { static create(_condRef, truthyRef, falsyRef) { let condRef = ConditionalReference$1.create(_condRef); if ((0, _reference.isConst)(condRef)) { return condRef.value() ? truthyRef : falsyRef; } else { return new ConditionalHelperReference(condRef, truthyRef, falsyRef); } } constructor(cond, truthy, falsy) { super(); this.branchTag = _reference.UpdatableTag.create(_reference.CONSTANT_TAG); this.tag = (0, _reference.combine)([cond.tag, this.branchTag]); this.cond = cond; this.truthy = truthy; this.falsy = falsy; } compute() { let branch = this.cond.value() ? this.truthy : this.falsy; this.branchTag.inner.update(branch.tag); return branch.value(); } } /** The `if` helper allows you to conditionally render one of two branches, depending on the "truthiness" of a property. For example the following values are all falsey: `false`, `undefined`, `null`, `""`, `0`, `NaN` or an empty array. This helper has two forms, block and inline. ## Block form You can use the block form of `if` to conditionally render a section of the template. To use it, pass the conditional value to the `if` helper, using the block form to wrap the section of template you want to conditionally render. Like so: ```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}} ``` ## Inline form The inline `if` helper conditionally renders a single property or string. In this form, the `if` helper receives three arguments, the conditional value, the value to render when truthy, and the value to render when falsey. For example, if `useLongGreeting` is truthy, the following: ```handlebars {{if useLongGreeting "Hello" "Hi"}} Alex ``` Will render: ```html Hello Alex ``` ### Nested `if` You can use the `if` helper inside another helper as a nested helper: ```handlebars {{some-component height=(if isBig "100" "10")}} ``` One detail to keep in mind is that both branches of the `if` helper will be evaluated, so if you have `{{if condition "foo" (expensive-operation "bar")`, `expensive-operation` will always calculate. @method if @for Ember.Templates.helpers @public */ function inlineIf(_vm, { positional }) { true && !(positional.length === 3 || positional.length === 2) && (0, _debug.assert)('The inline form of the `if` helper expects two or three arguments, e.g. ' + '`{{if trialExpired "Expired" expiryDate}}`.', positional.length === 3 || positional.length === 2); return ConditionalHelperReference.create(positional.at(0), positional.at(1), positional.at(2)); } /** The inline `unless` helper conditionally renders a single property or string. This helper acts like a ternary operator. If the first property is falsy, the second argument will be displayed, otherwise, the third argument will be displayed ```handlebars {{unless useLongGreeting "Hi" "Hello"}} Ben ``` You can use the `unless` helper inside another helper as a subexpression. ```handlebars {{some-component height=(unless isBig "10" "100")}} ``` @method unless @for Ember.Templates.helpers @public */ function inlineUnless(_vm, { positional }) { true && !(positional.length === 3 || positional.length === 2) && (0, _debug.assert)('The inline form of the `unless` helper expects two or three arguments, e.g. ' + '`{{unless isFirstLogin "Welcome back!"}}`.', positional.length === 3 || positional.length === 2); return ConditionalHelperReference.create(positional.at(0), positional.at(2), positional.at(1)); } /** @module ember */ /** `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 {Array} params @public */ function log({ positional }) { /* eslint-disable no-console */ console.log(...positional.value()); /* eslint-enable no-console */ } function log$1(_vm, args) { return new InternalHelperReference(log, args.capture()); } /** @module ember */ /** 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__. 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 just by modifying its own property: ```javascript // my-child.js export default Component.extend({ click() { this.incrementProperty('childClickCount'); } }); ``` Note that for curly components (`{{my-component}}`) the bindings are already mutable, making the `mut` unnecessary. 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('click-count-change')(this.get('childClickCount') + 1); } }); ``` The `mut` helper changes the `totalClicks` value to what was provided as the action argument. The `mut` helper, when used with `action`, will return a function that sets the value passed to `mut` to its first argument. This works like any other closure action and interacts with the other features `action` provides. As an example, we can create a button that increments a value passing the value directly to the `action`: ```handlebars {{! inc helper is not provided by Ember }} ``` You can also use the `value` option: ```handlebars ``` @method mut @param {Object} [attr] the "two-way" attribute that can be modified. @for Ember.Templates.helpers @public */ const MUT_REFERENCE = (0, _utils.symbol)('MUT'); const SOURCE = (0, _utils.symbol)('SOURCE'); function isMut(ref) { return ref && ref[MUT_REFERENCE]; } function unMut(ref) { return ref[SOURCE] || ref; } function mut(_vm, args) { let rawRef = args.positional.at(0); if (isMut(rawRef)) { return rawRef; } // TODO: Improve this error message. This covers at least two distinct // cases: // // 1. (mut "not a path") – passing a literal, result from a helper // invocation, etc // // 2. (mut receivedValue) – passing a value received from the caller // that was originally derived from a literal, result from a helper // invocation, etc // // This message is alright for the first case, but could be quite // confusing for the second case. true && !rawRef[UPDATE] && (0, _debug.assert)('You can only pass a path to mut', rawRef[UPDATE]); let wrappedRef = Object.create(rawRef); wrappedRef[SOURCE] = rawRef; wrappedRef[INVOKE] = rawRef[UPDATE]; wrappedRef[MUT_REFERENCE] = true; return wrappedRef; } /** @module ember */ /** 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 queryParams({ positional, named }) { // tslint:disable-next-line:max-line-length true && !(positional.value().length === 0) && (0, _debug.assert)("The `query-params` helper only accepts hash parameters, e.g. (query-params queryParamPropertyName='foo') as opposed to just (query-params 'foo')", positional.value().length === 0); return new _routing.QueryParams((0, _polyfills.assign)({}, named.value())); } function queryParams$1(_vm, args) { return new InternalHelperReference(queryParams, args.capture()); } /** The `readonly` helper let's you specify that a binding is one-way only, instead of two-way. When you pass a `readonly` binding from an outer context (e.g. parent component), to to an inner context (e.g. child component), you are saying that changing that property in the inner context does not change the value in the outer context. To specify that a binding is read-only, when invoking the child `Component`: ```app/components/my-parent.js export default Component.extend({ totalClicks: 3 }); ``` ```app/templates/components/my-parent.hbs {{log totalClicks}} // -> 3 {{my-child childClickCount=(readonly totalClicks)}} ``` Now, when you update `childClickCount`: ```app/components/my-child.js export default Component.extend({ click() { this.incrementProperty('childClickCount'); } }); ``` The value updates in the child component, but not the parent component: ```app/templates/components/my-child.hbs {{log childClickCount}} //-> 4 ``` ```app/templates/components/my-parent.hbs {{log totalClicks}} //-> 3 {{my-child childClickCount=(readonly totalClicks)}} ``` ### Objects and Arrays When passing a property that is a complex object (e.g. object, array) instead of a primitive object (e.g. number, string), only the reference to the object is protected using the readonly helper. This means that you can change properties of the object both on the parent component, as well as the child component. The `readonly` binding behaves similar to the `const` keyword in JavaScript. Let's look at an example: First let's set up the parent component: ```app/components/my-parent.js import Component from '@ember/component'; export default Component.extend({ clicks: null, init() { this._super(...arguments); this.set('clicks', { total: 3 }); } }); ``` ```app/templates/components/my-parent.hbs {{log clicks.total}} //-> 3 {{my-child childClicks=(readonly clicks)}} ``` Now, if you update the `total` property of `childClicks`: ```app/components/my-child.js import Component from '@ember/component'; export default Component.extend({ click() { this.get('clicks').incrementProperty('total'); } }); ``` You will see the following happen: ```app/templates/components/my-parent.hbs {{log clicks.total}} //-> 4 {{my-child childClicks=(readonly clicks)}} ``` ```app/templates/components/my-child.hbs {{log childClicks.total}} //-> 4 ``` @method readonly @param {Object} [attr] the read-only attribute. @for Ember.Templates.helpers @private */ function readonly(_vm, args) { let ref = unMut(args.positional.at(0)); return new ReadonlyReference(ref); } /** @module ember */ /** 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 */ function unbound(_vm, args) { true && !(args.positional.length === 1 && args.named.length === 0) && (0, _debug.assert)('unbound helper cannot be called with multiple params or hash params', args.positional.length === 1 && args.named.length === 0); return UnboundReference.create(args.positional.at(0).value()); } const MODIFIERS = ['alt', 'shift', 'meta', 'ctrl']; const POINTER_EVENT_TYPE_REGEX = /^click|mouse|touch/; function isAllowedEvent(event, allowedKeys) { if (allowedKeys === null || allowedKeys === undefined) { if (POINTER_EVENT_TYPE_REGEX.test(event.type)) { return (0, _views.isSimpleClick)(event); } else { allowedKeys = ''; } } if (allowedKeys.indexOf('any') >= 0) { return true; } for (let i = 0; i < MODIFIERS.length; i++) { if (event[MODIFIERS[i] + 'Key'] && allowedKeys.indexOf(MODIFIERS[i]) === -1) { return false; } } return true; } let ActionHelper = { // registeredActions is re-exported for compatibility with older plugins // that were using this undocumented API. registeredActions: _views.ActionManager.registeredActions, registerAction(actionState) { let { actionId } = actionState; _views.ActionManager.registeredActions[actionId] = actionState; return actionId; }, unregisterAction(actionState) { let { actionId } = actionState; delete _views.ActionManager.registeredActions[actionId]; } }; class ActionState { constructor(element, actionId, actionName, actionArgs, namedArgs, positionalArgs, implicitTarget, dom, tag) { this.element = element; this.actionId = actionId; this.actionName = actionName; this.actionArgs = actionArgs; this.namedArgs = namedArgs; this.positional = positionalArgs; this.implicitTarget = implicitTarget; this.dom = dom; this.eventName = this.getEventName(); this.tag = tag; } getEventName() { return this.namedArgs.get('on').value() || 'click'; } getActionArgs() { let result = new Array(this.actionArgs.length); for (let i = 0; i < this.actionArgs.length; i++) { result[i] = this.actionArgs[i].value(); } return result; } getTarget() { let { implicitTarget, namedArgs } = this; let target; if (namedArgs.has('target')) { target = namedArgs.get('target').value(); } else { target = implicitTarget.value(); } return target; } handler(event) { let { actionName, namedArgs } = this; let bubbles = namedArgs.get('bubbles'); let preventDefault = namedArgs.get('preventDefault'); let allowedKeys = namedArgs.get('allowedKeys'); let target = this.getTarget(); let shouldBubble = bubbles.value() !== false; if (!isAllowedEvent(event, allowedKeys.value())) { return true; } if (preventDefault.value() !== false) { event.preventDefault(); } if (!shouldBubble) { event.stopPropagation(); } (0, _runloop.join)(() => { let args = this.getActionArgs(); let payload = { args, target, name: null }; if (typeof actionName[INVOKE] === 'function') { (0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => { actionName[INVOKE].apply(actionName, args); }); return; } if (typeof actionName === 'function') { (0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => { actionName.apply(target, args); }); return; } payload.name = actionName; if (target.send) { (0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => { target.send.apply(target, [actionName, ...args]); }); } else { true && !(typeof target[actionName] === 'function') && (0, _debug.assert)(`The action '${actionName}' did not exist on ${target}`, typeof target[actionName] === 'function'); (0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => { target[actionName].apply(target, args); }); } }); return shouldBubble; } destroy() { ActionHelper.unregisterAction(this); } } // implements ModifierManager class ActionModifierManager { create(element, _state, args, _dynamicScope, dom) { let { named, positional, tag } = args.capture(); let implicitTarget; let actionName; let actionNameRef; if (positional.length > 1) { implicitTarget = positional.at(0); actionNameRef = positional.at(1); if (actionNameRef[INVOKE]) { actionName = actionNameRef; } else { let actionLabel = actionNameRef._propertyKey; actionName = actionNameRef.value(); true && !(typeof actionName === 'string' || typeof actionName === 'function') && (0, _debug.assert)('You specified a quoteless path, `' + actionLabel + '`, 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 "' + actionLabel + '"}}).', typeof actionName === 'string' || typeof actionName === 'function'); } } let actionArgs = []; // The first two arguments are (1) `this` and (2) the action name. // Everything else is a param. for (let i = 2; i < positional.length; i++) { actionArgs.push(positional.at(i)); } let actionId = (0, _utils.uuid)(); return new ActionState(element, actionId, actionName, actionArgs, named, positional, implicitTarget, dom, tag); } install(actionState) { let { dom, element, actionId } = actionState; ActionHelper.registerAction(actionState); dom.setAttribute(element, 'data-ember-action', ''); dom.setAttribute(element, `data-ember-action-${actionId}`, actionId); } update(actionState) { let { positional } = actionState; let actionNameRef = positional.at(1); if (!actionNameRef[INVOKE]) { actionState.actionName = actionNameRef.value(); } actionState.eventName = actionState.getEventName(); } getTag(actionState) { return actionState.tag; } getDestructor(modifier) { return modifier; } } function hashToArgs(hash) { if (hash === null) return null; let names = hash[0].map(key => `@${key}`); return [names, hash[1]]; } function textAreaMacro(_name, params, hash, builder) { let definition = builder.compiler['resolver'].lookupComponentDefinition('-text-area', builder.referrer); wrapComponentClassAttribute(hash); builder.component.static(definition, [params || [], hashToArgs(hash), null, null]); return true; } function buildSyntax(type, params, hash, builder) { let definition = builder.compiler['resolver'].lookupComponentDefinition(type, builder.referrer); builder.component.static(definition, [params, hashToArgs(hash), null, null]); return true; } /** The `{{input}}` helper lets you create an HTML `` component. It causes an `TextField` component to be rendered. For more info, see the [TextField](/api/ember/release/classes/TextField) docs and the [templates guide](https://guides.emberjs.com/release/templates/input-helpers/). ```handlebars {{input value="987"}} ``` renders as: ```HTML ``` ### 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.
`readonly``required``autofocus`
`value``placeholder``disabled`
`size``tabindex``maxlength`
`name``min``max`
`pattern``accept``autocomplete`
`autosave``formaction``formenctype`
`formmethod``formnovalidate``formtarget`
`height``inputmode``multiple`
`step``width``form`
`selectionDirection``spellcheck` 
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 initial value in the `` 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/ember/release/classes/TextField) ### Extending `TextField` Internally, `{{input type="text"}}` creates an instance of `TextField`, passing arguments from the helper to `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 import TextField from '@ember/component/text-field'; TextField.reopen({ attributeBindings: ['data-error'] }); ``` Keep in mind when writing `TextField` subclasses that `TextField` itself extends `Component`. Expect isolated component semantics, not legacy 1.x view semantics (like `controller` being present). See more about [Ember components](/api/ember/release/classes/Component) ### Checkbox Checkboxes are special forms of the `{{input}}` helper. To create a ``: ```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 `Checkbox` Internally, `{{input type="checkbox"}}` creates an instance of `Checkbox`, passing arguments from the helper to `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 import Checkbox from '@ember/component/checkbox'; Checkbox.reopen({ classNames: ['my-app-checkbox'] }); ``` @method input @for Ember.Templates.helpers @param {Hash} options @public */ function inputMacro(_name, params, hash, builder) { if (params === null) { params = []; } if (hash !== null) { let keys = hash[0]; let values = hash[1]; let typeIndex = keys.indexOf('type'); if (typeIndex > -1) { let typeArg = values[typeIndex]; if (Array.isArray(typeArg)) { // there is an AST plugin that converts this to an expression // it really should just compile in the component call too. let inputTypeExpr = params[0]; builder.dynamicComponent(inputTypeExpr, null, params.slice(1), hash, true, null, null); return true; } if (typeArg === 'checkbox') { true && !(keys.indexOf('value') === -1) && (0, _debug.assert)("{{input type='checkbox'}} does not support setting `value=someBooleanValue`; " + 'you must use `checked=someBooleanValue` instead.', keys.indexOf('value') === -1); wrapComponentClassAttribute(hash); return buildSyntax('-checkbox', params, hash, builder); } } } return buildSyntax('-text-field', params, hash, builder); } /** @module ember */ /** The `let` helper receives one or more positional arguments and yields them out as block params. This allows the developer to introduce shorter names for certain computations in the template. This is especially useful if you are passing properties to a component that receives a lot of options and you want to clean up the invocation. For the following example, the template receives a `post` object with `content` and `title` properties. We are going to call the `my-post` component, passing a title which is the title of the post suffixed with the name of the blog, the content of the post, and a series of options defined in-place. ```handlebars {{#let (concat post.title ' | The Ember.js Blog') post.content (hash theme="high-contrast" enableComments=true ) as |title content options| }} {{my-post title=title content=content options=options}} {{/let}} ``` @method let @for Ember.Templates.helpers @public */ function blockLetMacro(params, _hash, template, _inverse, builder) { if (template !== null) { if (params !== null) { builder.compileParams(params); builder.invokeStaticBlock(template, params.length); } else { builder.invokeStatic(template); } } return true; } const CAPABILITIES$3 = { dynamicLayout: true, dynamicTag: false, prepareArgs: false, createArgs: false, attributeHook: false, elementHook: false, createCaller: true, dynamicScope: true, updateHook: true, createInstance: true }; class MountManager extends AbstractManager { getDynamicLayout(state, _) { let template = state.engine.lookup('template:application'); let layout = template.asLayout(); return { handle: layout.compile(), symbolTable: layout.symbolTable }; } getCapabilities() { return CAPABILITIES$3; } create(environment, state) { if (true /* DEBUG */) { this._pushEngineToDebugStack(`engine:${state.name}`, environment); } // TODO // mount is a runtime helper, this shouldn't use dynamic layout // we should resolve the engine app template in the helper // it also should use the owner that looked up the mount helper. let engine = environment.owner.buildChildEngineInstance(state.name); engine.boot(); let applicationFactory = engine.factoryFor(`controller:application`); let controllerFactory = applicationFactory || (0, _routing.generateControllerFactory)(engine, 'application'); let controller; let self; let bucket; let tag; if (true /* EMBER_ENGINES_MOUNT_PARAMS */) { let modelRef = state.modelRef; if (modelRef === undefined) { controller = controllerFactory.create(); self = new RootReference(controller); tag = _reference.CONSTANT_TAG; bucket = { engine, controller, self, tag }; } else { let model = modelRef.value(); let modelRev = modelRef.tag.value(); controller = controllerFactory.create({ model }); self = new RootReference(controller); tag = modelRef.tag; bucket = { engine, controller, self, tag, modelRef, modelRev }; } } else { controller = controllerFactory.create(); self = new RootReference(controller); tag = _reference.CONSTANT_TAG; bucket = { engine, controller, self, tag }; } return bucket; } getSelf({ self }) { return self; } getTag(state) { return state.tag; } getDestructor({ engine }) { return engine; } didRenderLayout() { if (true /* DEBUG */) { this.debugStack.pop(); } } update(bucket) { if (true /* EMBER_ENGINES_MOUNT_PARAMS */) { let { controller, modelRef, modelRev } = bucket; if (!modelRef.tag.validate(modelRev)) { let model = modelRef.value(); bucket.modelRev = modelRef.tag.value(); controller.set('model', model); } } } } const MOUNT_MANAGER = new MountManager(); class MountDefinition { constructor(name, modelRef) { this.manager = MOUNT_MANAGER; this.state = { name, modelRef }; } } function mountHelper(vm, args) { let env = vm.env; let nameRef = args.positional.at(0); let modelRef = args.named.has('model') ? args.named.get('model') : undefined; return new DynamicEngineReference(nameRef, env, modelRef); } /** 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"}} ``` Additionally, you can also pass in a `model` argument that will be set as the engines model. This can be an existing object: ```
{{mount 'admin' model=userSettings}}
``` Or an inline `hash`, and you can even pass components: ```

Application template!

{{mount 'admin' model=(hash title='Secret Admin' signInButton=(component 'sign-in-button') )}}
``` @method mount @param {String} name Name of the engine to mount. @param {Object} [model] Object that will be set as the model of the engine. @for Ember.Templates.helpers @category ember-application-engines @public */ function mountMacro(_name, params, hash, builder) { if (true /* EMBER_ENGINES_MOUNT_PARAMS */) { true && !(params.length === 1) && (0, _debug.assert)('You can only pass a single positional argument to the {{mount}} helper, e.g. {{mount "chat-engine"}}.', params.length === 1); } else { true && !(params.length === 1 && hash === null) && (0, _debug.assert)('You can only pass a single argument to the {{mount}} helper, e.g. {{mount "chat-engine"}}.', params.length === 1 && hash === null); } let expr = [_wireFormat.Ops.Helper, '-mount', params || [], hash]; builder.dynamicComponent(expr, null, [], null, false, null, null); return true; } class DynamicEngineReference { constructor(nameRef, env, modelRef) { this.tag = nameRef.tag; this.nameRef = nameRef; this.modelRef = modelRef; this.env = env; this._lastName = null; this._lastDef = null; } value() { let { env, nameRef, modelRef } = this; let name = nameRef.value(); if (typeof name === 'string') { if (this._lastName === name) { return this._lastDef; } true && !env.owner.hasRegistration(`engine:${name}`) && (0, _debug.assert)(`You used \`{{mount '${name}'}}\`, but the engine '${name}' can not be found.`, env.owner.hasRegistration(`engine:${name}`)); if (!env.owner.hasRegistration(`engine:${name}`)) { return null; } this._lastName = name; this._lastDef = (0, _runtime.curry)(new MountDefinition(name, modelRef)); return this._lastDef; } else { true && !(name === null || name === undefined) && (0, _debug.assert)(`Invalid engine name '${name}' specified, engine name must be either a string, null or undefined.`, name === null || name === undefined); this._lastDef = null; this._lastName = null; return null; } } get() { return _runtime.UNDEFINED_REFERENCE; } } /** * Represents the root outlet. */ class RootOutletReference { constructor(outletState) { this.outletState = outletState; this.tag = _reference.DirtyableTag.create(); } get(key) { return new PathReference(this, key); } value() { return this.outletState; } update(state) { this.outletState.outlets.main = state; this.tag.inner.dirty(); } } /** * Represents the connected outlet. */ class OutletReference { constructor(parentStateRef, outletNameRef) { this.parentStateRef = parentStateRef; this.outletNameRef = outletNameRef; this.tag = (0, _reference.combine)([parentStateRef.tag, outletNameRef.tag]); } value() { let outletState = this.parentStateRef.value(); let outlets = outletState === undefined ? undefined : outletState.outlets; return outlets === undefined ? undefined : outlets[this.outletNameRef.value()]; } get(key) { return new PathReference(this, key); } } /** * Outlet state is dirtied from root. * This just using the parent tag for dirtiness. */ class PathReference { constructor(parent, key) { this.parent = parent; this.key = key; this.tag = parent.tag; } get(key) { return new PathReference(this, key); } value() { let parent = this.parent.value(); return parent && parent[this.key]; } } /** 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 }} {{my-header}}
{{outlet}}
{{my-footer}} ``` 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: ```app/routes/menu.js import Route from '@ember/routing/route'; export default Route.extend({ renderTemplate() { this.render({ outlet: 'menu' }); } }); ``` See the [routing guide](https://guides.emberjs.com/release/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 */ function outletHelper(vm, args) { let scope = vm.dynamicScope(); let nameRef; if (args.positional.length === 0) { nameRef = new _reference.ConstReference('main'); } else { nameRef = args.positional.at(0); } return new OutletComponentReference(new OutletReference(scope.outletState, nameRef)); } function outletMacro(_name, params, hash, builder) { let expr = [_wireFormat.Ops.Helper, '-outlet', params || [], hash]; builder.dynamicComponent(expr, null, [], null, false, null, null); return true; } class OutletComponentReference { constructor(outletRef) { this.outletRef = outletRef; this.definition = null; this.lastState = null; // The router always dirties the root state. this.tag = outletRef.tag; } value() { let state = stateFor(this.outletRef); if (validate(state, this.lastState)) { return this.definition; } this.lastState = state; let definition = null; if (state !== null) { definition = (0, _runtime.curry)(new OutletComponentDefinition(state)); } return this.definition = definition; } get(_key) { return _runtime.UNDEFINED_REFERENCE; } } function stateFor(ref) { let outlet = ref.value(); if (outlet === undefined) return null; let render = outlet.render; if (render === undefined) return null; let template = render.template; if (template === undefined) return null; return { ref, name: render.name, outlet: render.outlet, template, controller: render.controller }; } function validate(state, lastState) { if (state === null) { return lastState === null; } if (lastState === null) { return false; } return state.template === lastState.template && state.controller === lastState.controller; } function refineInlineSyntax(name, params, hash, builder) { true && !!(builder.compiler['resolver']['resolver']['builtInHelpers'][name] && builder.referrer.owner.hasRegistration(`helper:${name}`)) && (0, _debug.assert)(`You attempted to overwrite the built-in helper "${name}" which is not allowed. Please rename the helper.`, !(builder.compiler['resolver']['resolver']['builtInHelpers'][name] && builder.referrer.owner.hasRegistration(`helper:${name}`))); if (name.indexOf('-') === -1) { return false; } let handle = builder.compiler['resolver'].lookupComponentDefinition(name, builder.referrer); if (handle !== null) { builder.component.static(handle, [params === null ? [] : params, hashToArgs(hash), null, null]); return true; } return false; } function refineBlockSyntax(name, params, hash, template, inverse, builder) { if (name.indexOf('-') === -1) { return false; } let handle = builder.compiler['resolver'].lookupComponentDefinition(name, builder.referrer); if (handle !== null) { wrapComponentClassAttribute(hash); builder.component.static(handle, [params, hashToArgs(hash), template, inverse]); return true; } true && !builder.referrer.owner.hasRegistration(`helper:${name}`) && (0, _debug.assert)(`A component or helper named "${name}" could not be found`, builder.referrer.owner.hasRegistration(`helper:${name}`)); true && !!(() => { const resolver = builder.compiler['resolver']['resolver']; const { owner, moduleName } = builder.referrer; if (name === 'component' || resolver['builtInHelpers'][name]) { return true; } let options = { source: `template:${moduleName}` }; return owner.hasRegistration(`helper:${name}`, options) || owner.hasRegistration(`helper:${name}`); })() && (0, _debug.assert)(`Helpers may not be used in the block form, for example {{#${name}}}{{/${name}}}. Please use a component, or alternatively use the helper in combination with a built-in Ember helper, for example {{#if (${name})}}{{/if}}.`, !(() => { const resolver = builder.compiler['resolver']['resolver'];const { owner, moduleName } = builder.referrer;if (name === 'component' || resolver['builtInHelpers'][name]) { return true; }let options = { source: `template:${moduleName}` };return owner.hasRegistration(`helper:${name}`, options) || owner.hasRegistration(`helper:${name}`); })()); return false; } const experimentalMacros = []; // This is a private API to allow for experimental macros // to be created in user space. Registering a macro should // should be done in an initializer. function registerMacros(macro) { experimentalMacros.push(macro); } function populateMacros(macros) { let { inlines, blocks } = macros; inlines.add('outlet', outletMacro); inlines.add('mount', mountMacro); inlines.add('input', inputMacro); inlines.add('textarea', textAreaMacro); inlines.addMissing(refineInlineSyntax); if (true /* EMBER_TEMPLATE_BLOCK_LET_HELPER */ === true) { blocks.add('let', blockLetMacro); } blocks.addMissing(refineBlockSyntax); for (let i = 0; i < experimentalMacros.length; i++) { let macro = experimentalMacros[i]; macro(blocks, inlines); } return { blocks, inlines }; } const getPrototypeOf = Object.getPrototypeOf; const MANAGERS = new WeakMap(); function setComponentManager(managerId, obj) { MANAGERS.set(obj, managerId); return obj; } function getComponentManager(obj) { if (!true /* GLIMMER_CUSTOM_COMPONENT_MANAGER */) { return; } let pointer = obj; while (pointer !== undefined && pointer !== null) { if (MANAGERS.has(pointer)) { return MANAGERS.get(pointer); } pointer = getPrototypeOf(pointer); } return; } function instrumentationPayload$1(name) { return { object: `component:${name}` }; } function makeOptions(moduleName, namespace) { return { source: moduleName !== undefined ? `template:${moduleName}` : undefined, namespace }; } const BUILTINS_HELPERS = { if: inlineIf, action, concat: concat$1, get: get$1, hash, log: log$1, mut, 'query-params': queryParams$1, readonly, unbound, unless: inlineUnless, '-class': classHelper$1, '-each-in': eachIn, '-input-type': inputTypeHelper$1, '-normalize-class': normalizeClassHelper, '-html-safe': htmlSafeHelper, '-get-dynamic-var': _runtime.getDynamicVar, '-mount': mountHelper, '-outlet': outletHelper, '-assert-implicit-component-helper-argument': componentAssertionHelper }; const BUILTIN_MODIFIERS = { action: { manager: new ActionModifierManager(), state: null } }; class RuntimeResolver { constructor() { this.handles = [undefined]; this.objToHandle = new WeakMap(); this.builtInHelpers = BUILTINS_HELPERS; this.builtInModifiers = BUILTIN_MODIFIERS; // supports directly imported late bound layouts on component.prototype.layout this.templateCache = new Map(); this.componentDefinitionCache = new Map(); this.customManagerCache = new Map(); this.templateCacheHits = 0; this.templateCacheMisses = 0; this.componentDefinitionCount = 0; this.helperDefinitionCount = 0; let macros = new _opcodeCompiler.Macros(); populateMacros(macros); this.compiler = new _opcodeCompiler.LazyCompiler(new CompileTimeLookup(this), this, macros); } /*** IRuntimeResolver ***/ /** * public componentDefHandleCount = 0; * Called while executing Append Op.PushDynamicComponentManager if string */ lookupComponentDefinition(name, meta) { true && !(name !== 'textarea') && (0, _debug.assert)('You cannot use `textarea` as a component name.', name !== 'textarea'); true && !(name !== 'input') && (0, _debug.assert)('You cannot use `input` as a component name.', name !== 'input'); let handle = this.lookupComponentHandle(name, meta); if (handle === null) { true && !false && (0, _debug.assert)(`Could not find component named "${name}" (no component or template with that name was found)`); return null; } return this.resolve(handle); } lookupComponentHandle(name, meta) { let nextHandle = this.handles.length; let handle = this.handle(this._lookupComponentDefinition(name, meta)); if (nextHandle === handle) { this.componentDefinitionCount++; } return handle; } /** * Called by RuntimeConstants to lookup unresolved handles. */ resolve(handle) { return this.handles[handle]; } // End IRuntimeResolver /** * Called by CompileTimeLookup compiling Unknown or Helper OpCode */ lookupHelper(name, meta) { let nextHandle = this.handles.length; let helper$$1 = this._lookupHelper(name, meta); if (helper$$1 !== null) { let handle = this.handle(helper$$1); if (nextHandle === handle) { this.helperDefinitionCount++; } return handle; } return null; } /** * Called by CompileTimeLookup compiling the */ lookupModifier(name, _meta) { return this.handle(this._lookupModifier(name)); } /** * Called by CompileTimeLookup to lookup partial */ lookupPartial(name, meta) { let partial = this._lookupPartial(name, meta); return this.handle(partial); } // end CompileTimeLookup /** * Creates a template with injections from a directly imported template factory. * @param templateFactory the directly imported template factory. * @param owner the owner the template instance would belong to if resolved */ createTemplate(factory, owner) { let cache = this.templateCache.get(owner); if (cache === undefined) { cache = new Map(); this.templateCache.set(owner, cache); } let template = cache.get(factory); if (template === undefined) { const { compiler } = this; const injections = { compiler }; (0, _owner.setOwner)(injections, owner); template = factory.create(injections); cache.set(factory, template); this.templateCacheMisses++; } else { this.templateCacheHits++; } return template; } // needed for lazy compile time lookup handle(obj) { if (obj === undefined || obj === null) { return null; } let handle = this.objToHandle.get(obj); if (handle === undefined) { handle = this.handles.push(obj) - 1; this.objToHandle.set(obj, handle); } return handle; } _lookupHelper(_name, meta) { const helper$$1 = this.builtInHelpers[_name]; if (helper$$1 !== undefined) { return helper$$1; } const { owner, moduleName } = meta; let name = _name; let namespace = undefined; if (false /* EMBER_MODULE_UNIFICATION */) { const parsed = this._parseNameForNamespace(_name); name = parsed.name; namespace = parsed.namespace; } const options = makeOptions(moduleName, namespace); const factory = owner.factoryFor(`helper:${name}`, options) || owner.factoryFor(`helper:${name}`); if (!isHelperFactory(factory)) { return null; } return (vm, args) => { const helper$$1 = factory.create(); if (isSimpleHelper(helper$$1)) { return new SimpleHelperReference(helper$$1.compute, args.capture()); } vm.newDestroyable(helper$$1); return ClassBasedHelperReference.create(helper$$1, args.capture()); }; } _lookupPartial(name, meta) { const template = (0, _views.lookupPartial)(name, meta.owner); if (template) { return new _opcodeCompiler.PartialDefinition(name, template); } else { throw new Error(`${name} is not a partial`); } } _lookupModifier(name) { return this.builtInModifiers[name]; } _parseNameForNamespace(_name) { let name = _name; let namespace = undefined; let namespaceDelimiterOffset = _name.indexOf('::'); if (namespaceDelimiterOffset !== -1) { name = _name.slice(namespaceDelimiterOffset + 2); namespace = _name.slice(0, namespaceDelimiterOffset); } return { name, namespace }; } _lookupComponentDefinition(_name, meta) { let name = _name; let namespace = undefined; if (false /* EMBER_MODULE_UNIFICATION */) { const parsed = this._parseNameForNamespace(_name); name = parsed.name; namespace = parsed.namespace; } let { layout, component } = (0, _views.lookupComponent)(meta.owner, name, makeOptions(meta.moduleName, namespace)); let key = component === undefined ? layout : component; if (key === undefined) { return null; } let cachedComponentDefinition = this.componentDefinitionCache.get(key); if (cachedComponentDefinition !== undefined) { return cachedComponentDefinition; } let finalizer = (0, _instrumentation._instrumentStart)('render.getComponentDefinition', instrumentationPayload$1, name); if (layout && !component && _environment2.ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS) { let definition = new TemplateOnlyComponentDefinition(layout); finalizer(); this.componentDefinitionCache.set(key, definition); return definition; } if (true /* GLIMMER_CUSTOM_COMPONENT_MANAGER */ && component && component.class) { let managerId = getComponentManager(component.class); if (managerId) { let manager = this._lookupComponentManager(meta.owner, managerId); true && !!!manager && (0, _debug.assert)(`Could not find custom component manager '${managerId}' which was specified by ${component.class}`, !!manager); let definition = new CustomManagerDefinition(name, component, manager, layout || meta.owner.lookup(_container.privatize`template:components/-default`)); finalizer(); this.componentDefinitionCache.set(key, definition); return definition; } } let definition = layout || component ? new CurlyComponentDefinition(name, component || meta.owner.factoryFor(_container.privatize`component:-default`), null, layout // TODO fix type ) : null; finalizer(); this.componentDefinitionCache.set(key, definition); return definition; } _lookupComponentManager(owner, managerId) { if (this.customManagerCache.has(managerId)) { return this.customManagerCache.get(managerId); } let delegate = owner.lookup(`component-manager:${managerId}`); this.customManagerCache.set(managerId, delegate); return delegate; } } // factory for DI var TemplateCompiler = { create() { return new RuntimeResolver().compiler; } }; var ComponentTemplate = template({ "id": "chfQcH83", "block": "{\"symbols\":[\"&default\"],\"statements\":[[14,1]],\"hasEval\":false}", "meta": { "moduleName": "packages/@ember/-internals/glimmer/lib/templates/component.hbs" } }); var OutletTemplate = template({ "id": "gK7R0/52", "block": "{\"symbols\":[],\"statements\":[[1,[21,\"outlet\"],false]],\"hasEval\":false}", "meta": { "moduleName": "packages/@ember/-internals/glimmer/lib/templates/outlet.hbs" } }); const TOP_LEVEL_NAME = '-top-level'; const TOP_LEVEL_OUTLET = 'main'; class OutletView { constructor(_environment, renderer, owner, template) { this._environment = _environment; this.renderer = renderer; this.owner = owner; this.template = template; let ref = this.ref = new RootOutletReference({ outlets: { main: undefined }, render: { owner: owner, into: undefined, outlet: TOP_LEVEL_OUTLET, name: TOP_LEVEL_NAME, controller: undefined, template } }); this.state = { ref, name: TOP_LEVEL_NAME, outlet: TOP_LEVEL_OUTLET, template, controller: undefined }; } static extend(injections) { return class extends OutletView { static create(options) { if (options) { return super.create((0, _polyfills.assign)({}, injections, options)); } else { return super.create(injections); } } }; } static reopenClass(injections) { (0, _polyfills.assign)(this, injections); } static create(options) { let { _environment, renderer, template } = options; let owner = options[_owner.OWNER]; return new OutletView(_environment, renderer, owner, template); } appendTo(selector) { let target; if (this._environment.hasDOM) { target = typeof selector === 'string' ? document.querySelector(selector) : selector; } else { target = selector; } (0, _runloop.schedule)('render', this.renderer, 'appendOutletView', this, target); } rerender() { /**/ } setOutletState(state) { this.ref.update(state); } destroy() { /**/ } } function setupApplicationRegistry(registry) { registry.injection('service:-glimmer-environment', 'appendOperations', 'service:-dom-tree-construction'); registry.injection('renderer', 'env', 'service:-glimmer-environment'); // because we are using injections we can't use instantiate false // we need to use bind() to copy the function so factory for // association won't leak registry.register('service:-dom-builder', { create({ bootOptions }) { let { _renderMode } = bootOptions; switch (_renderMode) { case 'serialize': return _node.serializeBuilder.bind(null); case 'rehydrate': return _runtime.rehydrationBuilder.bind(null); default: return _runtime.clientBuilder.bind(null); } } }); registry.injection('service:-dom-builder', 'bootOptions', '-environment:main'); registry.injection('renderer', 'builder', 'service:-dom-builder'); registry.register(_container.privatize`template:-root`, RootTemplate); registry.injection('renderer', 'rootTemplate', _container.privatize`template:-root`); registry.register('renderer:-dom', InteractiveRenderer); registry.register('renderer:-inert', InertRenderer); if (_browserEnvironment.hasDOM) { registry.injection('service:-glimmer-environment', 'updateOperations', 'service:-dom-changes'); } registry.register('service:-dom-changes', { create({ document }) { return new _runtime.DOMChanges(document); } }); registry.register('service:-dom-tree-construction', { create({ document }) { let Implementation = _browserEnvironment.hasDOM ? _runtime.DOMTreeConstruction : _node.NodeDOMTreeConstruction; return new Implementation(document); } }); } function setupEngineRegistry(registry) { registry.register('view:-outlet', OutletView); registry.register('template:-outlet', OutletTemplate); registry.injection('view:-outlet', 'template', 'template:-outlet'); registry.injection('service:-dom-changes', 'document', 'service:-document'); registry.injection('service:-dom-tree-construction', 'document', 'service:-document'); registry.register(_container.privatize`template:components/-default`, ComponentTemplate); registry.register('service:-glimmer-environment', Environment$1); registry.register(_container.privatize`template-compiler:main`, TemplateCompiler); registry.injection('template', 'compiler', _container.privatize`template-compiler:main`); registry.optionsForType('helper', { instantiate: false }); registry.register('helper:loc', loc$1); registry.register('component:-text-field', TextField); registry.register('component:-text-area', TextArea); registry.register('component:-checkbox', Checkbox); registry.register('component:link-to', LinkComponent); if (!_environment2.ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS) { registry.register(_container.privatize`component:-default`, Component); } } /** [Glimmer](https://github.com/tildeio/glimmer) is a templating engine used by Ember.js that is compatible with a subset of the [Handlebars](http://handlebarsjs.com/) syntax. ### 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: ```app/components/person-profile.js import Component from '@ember/component'; export default Component.extend({ name: 'Jill' }); ``` ```app/templates/components/person-profile.hbs {{name}}
{{name}}
``` Any time the "name" property on the component changes, the DOM will be updated. Properties can be chained as well: ```handlebars {{aUserModel.name}}
{{listOfUsers.firstObject.name}}
``` ### 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"}} ``` 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 ``` Ember's built-in helpers are described under the [Ember.Templates.helpers](/api/ember/release/classes/Ember.Templates.helpers) namespace. Documentation on creating custom helpers can be found under [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 [Component](/api/ember/release/classes/Component). @module @ember/component @main @ember/component @public */ exports.RootTemplate = RootTemplate; exports.template = template; exports.Checkbox = Checkbox; exports.TextField = TextField; exports.TextArea = TextArea; exports.LinkComponent = LinkComponent; exports.Component = Component; exports.ROOT_REF = ROOT_REF; exports.Helper = Helper; exports.helper = helper; exports.Environment = Environment$1; exports.SafeString = SafeString; exports.escapeExpression = escapeExpression; exports.htmlSafe = htmlSafe; exports.isHTMLSafe = isHTMLSafe; exports.Renderer = Renderer; exports.InertRenderer = InertRenderer; exports.InteractiveRenderer = InteractiveRenderer; exports._resetRenderers = _resetRenderers; exports.renderSettled = renderSettled; exports.getTemplate = getTemplate; exports.setTemplate = setTemplate; exports.hasTemplate = hasTemplate; exports.getTemplates = getTemplates; exports.setTemplates = setTemplates; exports.setupEngineRegistry = setupEngineRegistry; exports.setupApplicationRegistry = setupApplicationRegistry; exports._registerMacros = registerMacros; exports._experimentalMacros = experimentalMacros; exports.AbstractComponentManager = AbstractManager; exports.UpdatableReference = UpdatableReference; exports.INVOKE = INVOKE; exports.iterableFor = iterableFor; exports.DebugStack = DebugStack$1; exports.OutletView = OutletView; exports.capabilities = capabilities; exports.setComponentManager = setComponentManager; exports.getComponentManager = getComponentManager; }); enifed('@ember/-internals/meta/index', ['exports', '@ember/-internals/meta/lib/meta'], function (exports, _meta) { 'use strict'; Object.defineProperty(exports, 'counters', { enumerable: true, get: function () { return _meta.counters; } }); Object.defineProperty(exports, 'deleteMeta', { enumerable: true, get: function () { return _meta.deleteMeta; } }); Object.defineProperty(exports, 'descriptorFor', { enumerable: true, get: function () { return _meta.descriptorFor; } }); Object.defineProperty(exports, 'isDescriptor', { enumerable: true, get: function () { return _meta.isDescriptor; } }); Object.defineProperty(exports, 'Meta', { enumerable: true, get: function () { return _meta.Meta; } }); Object.defineProperty(exports, 'meta', { enumerable: true, get: function () { return _meta.meta; } }); Object.defineProperty(exports, 'peekMeta', { enumerable: true, get: function () { return _meta.peekMeta; } }); Object.defineProperty(exports, 'setMeta', { enumerable: true, get: function () { return _meta.setMeta; } }); Object.defineProperty(exports, 'UNDEFINED', { enumerable: true, get: function () { return _meta.UNDEFINED; } }); }); enifed('@ember/-internals/meta/lib/meta', ['exports', '@ember/-internals/utils', '@ember/debug'], function (exports, _utils, _debug) { 'use strict'; exports.counters = exports.meta = exports.Meta = exports.UNDEFINED = undefined; exports.setMeta = setMeta; exports.peekMeta = peekMeta; exports.deleteMeta = deleteMeta; exports.descriptorFor = descriptorFor; exports.isDescriptor = isDescriptor; const objectPrototype = Object.prototype; let counters; if (true /* DEBUG */) { exports.counters = counters = { peekCalls: 0, peekPrototypeWalks: 0, setCalls: 0, deleteCalls: 0, metaCalls: 0, metaInstantiated: 0, matchingListenersCalls: 0, addToListenersCalls: 0, removeFromListenersCalls: 0, removeAllListenersCalls: 0, listenersInherited: 0, listenersFlattened: 0, parentListenersUsed: 0, flattenedListenersCalls: 0, reopensAfterFlatten: 0 }; } /** @module ember */ const UNDEFINED = exports.UNDEFINED = (0, _utils.symbol)('undefined'); let currentListenerVersion = 1; class Meta { constructor(obj) { this._listenersVersion = 1; this._inheritedEnd = -1; this._flattenedVersion = 0; if (true /* DEBUG */) { counters.metaInstantiated++; this._values = undefined; } this._parent = undefined; this._descriptors = undefined; this._watching = undefined; this._mixins = undefined; this._deps = undefined; this._chainWatchers = undefined; this._chains = undefined; this._tag = undefined; this._tags = undefined; // initial value for all flags right now is false // see FLAGS const for detailed list of flags used this._flags = 0 /* NONE */; // used only internally this.source = obj; this.proto = obj.constructor === undefined ? undefined : obj.constructor.prototype; this._listeners = undefined; } get parent() { let parent = this._parent; if (parent === undefined) { let proto = getPrototypeOf(this.source); this._parent = parent = proto === null || proto === objectPrototype ? null : meta(proto); } return parent; } setInitializing() { this._flags |= 8 /* INITIALIZING */; } unsetInitializing() { this._flags ^= 8 /* INITIALIZING */; } isInitializing() { return this._hasFlag(8 /* INITIALIZING */); } isPrototypeMeta(obj) { return this.proto === this.source && this.source === obj; } destroy() { if (this.isMetaDestroyed()) { return; } this.setMetaDestroyed(); // remove chainWatchers to remove circular references that would prevent GC let chains = this.readableChains(); if (chains !== undefined) { chains.destroy(); } } isSourceDestroying() { return this._hasFlag(1 /* SOURCE_DESTROYING */); } setSourceDestroying() { this._flags |= 1 /* SOURCE_DESTROYING */; } isSourceDestroyed() { return this._hasFlag(2 /* SOURCE_DESTROYED */); } setSourceDestroyed() { this._flags |= 2 /* SOURCE_DESTROYED */; } isMetaDestroyed() { return this._hasFlag(4 /* META_DESTROYED */); } setMetaDestroyed() { this._flags |= 4 /* META_DESTROYED */; } _hasFlag(flag) { return (this._flags & flag) === flag; } _getOrCreateOwnMap(key) { return this[key] || (this[key] = Object.create(null)); } _getOrCreateOwnSet(key) { return this[key] || (this[key] = new Set()); } _findInherited1(key) { let pointer = this; while (pointer !== null) { let map = pointer[key]; if (map !== undefined) { return map; } pointer = pointer.parent; } } _findInherited2(key, subkey) { let pointer = this; while (pointer !== null) { let map = pointer[key]; if (map !== undefined) { let value = map[subkey]; if (value !== undefined) { return value; } } pointer = pointer.parent; } } _findInherited3(key, subkey, subsubkey) { let pointer = this; while (pointer !== null) { let map = pointer[key]; if (map !== undefined) { let submap = map[subkey]; if (submap !== undefined) { let value = submap[subsubkey]; if (value !== undefined) { return value; } } } pointer = pointer.parent; } } _hasInInheritedSet(key, value) { let pointer = this; while (pointer !== null) { let set = pointer[key]; if (set !== undefined && set.has(value)) { return true; } pointer = pointer.parent; } return false; } // Implements a member that provides a lazily created map of maps, // with inheritance at both levels. writeDeps(subkey, itemkey, count) { true && !!this.isMetaDestroyed() && (0, _debug.assert)(this.isMetaDestroyed() ? `Cannot modify dependent keys for \`${itemkey}\` on \`${(0, _utils.toString)(this.source)}\` after it has been destroyed.` : '', !this.isMetaDestroyed()); let outerMap = this._getOrCreateOwnMap('_deps'); let innerMap = outerMap[subkey]; if (innerMap === undefined) { innerMap = outerMap[subkey] = Object.create(null); } innerMap[itemkey] = count; } peekDeps(subkey, itemkey) { let val = this._findInherited3('_deps', subkey, itemkey); return val === undefined ? 0 : val; } hasDeps(subkey) { let val = this._findInherited2('_deps', subkey); return val !== undefined; } forEachInDeps(subkey, fn) { let pointer = this; let seen; let calls; while (pointer !== null) { let map = pointer._deps; if (map !== undefined) { let innerMap = map[subkey]; if (innerMap !== undefined) { for (let innerKey in innerMap) { seen = seen === undefined ? new Set() : seen; if (!seen.has(innerKey)) { seen.add(innerKey); if (innerMap[innerKey] > 0) { calls = calls || []; calls.push(innerKey); } } } } } pointer = pointer.parent; } if (calls !== undefined) { for (let i = 0; i < calls.length; i++) { fn(calls[i]); } } } writableTags() { return this._getOrCreateOwnMap('_tags'); } readableTags() { return this._tags; } writableTag(create) { true && !!this.isMetaDestroyed() && (0, _debug.assert)(this.isMetaDestroyed() ? `Cannot create a new tag for \`${(0, _utils.toString)(this.source)}\` after it has been destroyed.` : '', !this.isMetaDestroyed()); let ret = this._tag; if (ret === undefined) { ret = this._tag = create(this.source); } return ret; } readableTag() { return this._tag; } writableChainWatchers(create) { true && !!this.isMetaDestroyed() && (0, _debug.assert)(this.isMetaDestroyed() ? `Cannot create a new chain watcher for \`${(0, _utils.toString)(this.source)}\` after it has been destroyed.` : '', !this.isMetaDestroyed()); let ret = this._chainWatchers; if (ret === undefined) { ret = this._chainWatchers = create(this.source); } return ret; } readableChainWatchers() { return this._chainWatchers; } writableChains(create) { true && !!this.isMetaDestroyed() && (0, _debug.assert)(this.isMetaDestroyed() ? `Cannot create a new chains for \`${(0, _utils.toString)(this.source)}\` after it has been destroyed.` : '', !this.isMetaDestroyed()); let { _chains: ret } = this; if (ret === undefined) { this._chains = ret = create(this.source); let { parent } = this; if (parent !== null) { let parentChains = parent.writableChains(create); parentChains.copyTo(ret); } } return ret; } readableChains() { return this._findInherited1('_chains'); } writeWatching(subkey, value) { true && !!this.isMetaDestroyed() && (0, _debug.assert)(this.isMetaDestroyed() ? `Cannot update watchers for \`${subkey}\` on \`${(0, _utils.toString)(this.source)}\` after it has been destroyed.` : '', !this.isMetaDestroyed()); let map = this._getOrCreateOwnMap('_watching'); map[subkey] = value; } peekWatching(subkey) { let count = this._findInherited2('_watching', subkey); return count === undefined ? 0 : count; } addMixin(mixin) { true && !!this.isMetaDestroyed() && (0, _debug.assert)(this.isMetaDestroyed() ? `Cannot add mixins of \`${(0, _utils.toString)(mixin)}\` on \`${(0, _utils.toString)(this.source)}\` call addMixin after it has been destroyed.` : '', !this.isMetaDestroyed()); let set = this._getOrCreateOwnSet('_mixins'); set.add(mixin); } hasMixin(mixin) { return this._hasInInheritedSet('_mixins', mixin); } forEachMixins(fn) { let pointer = this; let seen; while (pointer !== null) { let set = pointer._mixins; if (set !== undefined) { seen = seen === undefined ? new Set() : seen; // TODO cleanup typing here set.forEach(mixin => { if (!seen.has(mixin)) { seen.add(mixin); fn(mixin); } }); } pointer = pointer.parent; } } writeDescriptors(subkey, value) { true && !!this.isMetaDestroyed() && (0, _debug.assert)(this.isMetaDestroyed() ? `Cannot update descriptors for \`${subkey}\` on \`${(0, _utils.toString)(this.source)}\` after it has been destroyed.` : '', !this.isMetaDestroyed()); let map = this._getOrCreateOwnMap('_descriptors'); map[subkey] = value; } peekDescriptors(subkey) { let possibleDesc = this._findInherited2('_descriptors', subkey); return possibleDesc === UNDEFINED ? undefined : possibleDesc; } removeDescriptors(subkey) { this.writeDescriptors(subkey, UNDEFINED); } forEachDescriptors(fn) { let pointer = this; let seen; while (pointer !== null) { let map = pointer._descriptors; if (map !== undefined) { for (let key in map) { seen = seen === undefined ? new Set() : seen; if (!seen.has(key)) { seen.add(key); let value = map[key]; if (value !== UNDEFINED) { fn(key, value); } } } } pointer = pointer.parent; } } addToListeners(eventName, target, method, once) { if (true /* DEBUG */) { counters.addToListenersCalls++; } this.pushListener(eventName, target, method, once ? 1 /* ONCE */ : 0 /* ADD */); } removeFromListeners(eventName, target, method) { if (true /* DEBUG */) { counters.removeFromListenersCalls++; } this.pushListener(eventName, target, method, 2 /* REMOVE */); } removeAllListeners(event) { true && !false && (0, _debug.deprecate)('The remove all functionality of removeListener and removeObserver has been deprecated. Remove each listener/observer individually instead.', false, { id: 'events.remove-all-listeners', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_events-remove-all-listeners' }); if (true /* DEBUG */) { counters.removeAllListenersCalls++; } let listeners = this.writableListeners(); let inheritedEnd = this._inheritedEnd; // remove all listeners of event name // adjusting the inheritedEnd if listener is below it for (let i = listeners.length - 1; i >= 0; i--) { let listener = listeners[i]; if (listener.event === event) { listeners.splice(i, 1); if (i < inheritedEnd) { inheritedEnd--; } } } this._inheritedEnd = inheritedEnd; // we put remove alls at start because rare and easy to check there listeners.splice(inheritedEnd, 0, { event, target: null, method: null, kind: 3 /* REMOVE_ALL */ }); } pushListener(event, target, method, kind) { let listeners = this.writableListeners(); let i = indexOfListener(listeners, event, target, method); // remove if found listener was inherited if (i !== -1 && i < this._inheritedEnd) { listeners.splice(i, 1); this._inheritedEnd--; i = -1; } // if not found, push. Note that we must always push if a listener is not // found, even in the case of a function listener remove, because we may be // attempting to add or remove listeners _before_ flattening has occured. if (i === -1) { true && !!(this.isPrototypeMeta(this.source) && typeof method === 'function') && (0, _debug.deprecate)('Adding function listeners to prototypes has been deprecated. Convert the listener to a string listener, or add it to the instance instead.', !(this.isPrototypeMeta(this.source) && typeof method === 'function'), { id: 'events.inherited-function-listeners', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_events-inherited-function-listeners' }); true && !!(!this.isPrototypeMeta(this.source) && typeof method === 'function' && kind === 2 /* REMOVE */) && (0, _debug.deprecate)('You attempted to remove a function listener which did not exist on the instance, which means it was an inherited prototype listener, or you attempted to remove it before it was added. Prototype function listeners have been deprecated, and attempting to remove a non-existent function listener this will error in the future.', !(!this.isPrototypeMeta(this.source) && typeof method === 'function' && kind === 2), { id: 'events.inherited-function-listeners', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_events-inherited-function-listeners' }); listeners.push({ event, target, method, kind }); } else { let listener = listeners[i]; // If the listener is our own function listener and we are trying to // remove it, we want to splice it out entirely so we don't hold onto a // reference. if (kind === 2 /* REMOVE */ && listener.kind !== 2 /* REMOVE */ && typeof method === 'function') { listeners.splice(i, 1); } else { // update own listener listener.kind = kind; // TODO: Remove this when removing REMOVE_ALL, it won't be necessary listener.target = target; listener.method = method; } } } writableListeners() { // Check if we need to invalidate and reflatten. We need to do this if we // have already flattened (flattened version is the current version) and // we are either writing to a prototype meta OR we have never inherited, and // may have cached the parent's listeners. if (this._flattenedVersion === currentListenerVersion && (this.source === this.proto || this._inheritedEnd === -1)) { if (true /* DEBUG */) { counters.reopensAfterFlatten++; } currentListenerVersion++; } // Inherited end has not been set, then we have never created our own // listeners, but may have cached the parent's if (this._inheritedEnd === -1) { this._inheritedEnd = 0; this._listeners = []; } return this._listeners; } /** Flattening is based on a global revision counter. If the revision has bumped it means that somewhere in a class inheritance chain something has changed, so we need to reflatten everything. This can only happen if: 1. A meta has been flattened (listener has been called) 2. The meta is a prototype meta with children who have inherited its listeners 3. A new listener is subsequently added to the meta (e.g. via `.reopen()`) This is a very rare occurence, so while the counter is global it shouldn't be updated very often in practice. */ flattenedListeners() { if (true /* DEBUG */) { counters.flattenedListenersCalls++; } if (this._flattenedVersion < currentListenerVersion) { if (true /* DEBUG */) { counters.listenersFlattened++; } let parent = this.parent; if (parent !== null) { // compute let parentListeners = parent.flattenedListeners(); if (parentListeners !== undefined) { if (this._listeners === undefined) { // If this instance doesn't have any of its own listeners (writableListeners // has never been called) then we don't need to do any flattening, return // the parent's listeners instead. if (true /* DEBUG */) { counters.parentListenersUsed++; } this._listeners = parentListeners; } else { let listeners = this._listeners; if (this._inheritedEnd > 0) { listeners.splice(0, this._inheritedEnd); this._inheritedEnd = 0; } for (let i = 0; i < parentListeners.length; i++) { let listener = parentListeners[i]; let index = indexOfListener(listeners, listener.event, listener.target, listener.method); if (index === -1) { if (true /* DEBUG */) { counters.listenersInherited++; } listeners.unshift(listener); this._inheritedEnd++; } } } } } this._flattenedVersion = currentListenerVersion; } return this._listeners; } matchingListeners(eventName) { let listeners = this.flattenedListeners(); let result; if (true /* DEBUG */) { counters.matchingListenersCalls++; } if (listeners !== undefined) { for (let index = 0; index < listeners.length; index++) { let listener = listeners[index]; // REMOVE and REMOVE_ALL listeners are placeholders that tell us not to // inherit, so they never match. Only ADD and ONCE can match. if (listener.event === eventName && (listener.kind === 0 /* ADD */ || listener.kind === 1 /* ONCE */)) { if (result === undefined) { // we create this array only after we've found a listener that // matches to avoid allocations when no matches are found. result = []; } result.push(listener.target, listener.method, listener.kind === 1 /* ONCE */); } } } return result; } } exports.Meta = Meta; if (true /* DEBUG */) { Meta.prototype.writeValues = function (subkey, value) { true && !!this.isMetaDestroyed() && (0, _debug.assert)(this.isMetaDestroyed() ? `Cannot set the value of \`${subkey}\` on \`${(0, _utils.toString)(this.source)}\` after it has been destroyed.` : '', !this.isMetaDestroyed()); let map = this._getOrCreateOwnMap('_values'); map[subkey] = value; }; Meta.prototype.peekValues = function (subkey) { return this._findInherited2('_values', subkey); }; Meta.prototype.deleteFromValues = function (subkey) { delete this._getOrCreateOwnMap('_values')[subkey]; }; Meta.prototype.readInheritedValue = function (key, subkey) { let internalKey = `_${key}`; let pointer = this; while (pointer !== null) { let map = pointer[internalKey]; if (map !== undefined) { let value = map[subkey]; if (value !== undefined || subkey in map) { return value; } } pointer = pointer.parent; } return UNDEFINED; }; Meta.prototype.writeValue = function (obj, key, value) { let descriptor = (0, _utils.lookupDescriptor)(obj, key); let isMandatorySetter = descriptor !== null && descriptor.set && descriptor.set.isMandatorySetter; if (isMandatorySetter) { this.writeValues(key, value); } else { obj[key] = value; } }; } const getPrototypeOf = Object.getPrototypeOf; const metaStore = new WeakMap(); function setMeta(obj, meta) { true && !(obj !== null) && (0, _debug.assert)('Cannot call `setMeta` on null', obj !== null); true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `setMeta` on undefined', obj !== undefined); true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`setMeta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'); if (true /* DEBUG */) { counters.setCalls++; } metaStore.set(obj, meta); } function peekMeta(obj) { true && !(obj !== null) && (0, _debug.assert)('Cannot call `peekMeta` on null', obj !== null); true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `peekMeta` on undefined', obj !== undefined); true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`peekMeta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'); if (true /* DEBUG */) { counters.peekCalls++; } let meta = metaStore.get(obj); if (meta !== undefined) { return meta; } let pointer = getPrototypeOf(obj); while (pointer !== undefined && pointer !== null) { if (true /* DEBUG */) { counters.peekPrototypeWalks++; } meta = metaStore.get(pointer); if (meta !== undefined) { if (meta.proto !== pointer) { // The meta was a prototype meta which was not marked as initializing. // This can happen when a prototype chain was created manually via // Object.create() and the source object does not have a constructor. meta.proto = pointer; } return meta; } pointer = getPrototypeOf(pointer); } } /** Tears down the meta on an object so that it can be garbage collected. Multiple calls will have no effect. @method deleteMeta @for Ember @param {Object} obj the object to destroy @return {void} @private */ function deleteMeta(obj) { true && !(obj !== null) && (0, _debug.assert)('Cannot call `deleteMeta` on null', obj !== null); true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `deleteMeta` on undefined', obj !== undefined); true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`deleteMeta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'); if (true /* DEBUG */) { counters.deleteCalls++; } let meta = peekMeta(obj); if (meta !== undefined) { meta.destroy(); } } /** 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 */ const meta = exports.meta = function meta(obj) { true && !(obj !== null) && (0, _debug.assert)('Cannot call `meta` on null', obj !== null); true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `meta` on undefined', obj !== undefined); true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`meta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'); if (true /* DEBUG */) { counters.metaCalls++; } let maybeMeta = peekMeta(obj); // remove this code, in-favor of explicit parent if (maybeMeta !== undefined && maybeMeta.source === obj) { return maybeMeta; } let newMeta = new Meta(obj); setMeta(obj, newMeta); return newMeta; }; if (true /* DEBUG */) { meta._counters = counters; } /** Returns the CP descriptor assocaited with `obj` and `keyName`, if any. @method descriptorFor @param {Object} obj the object to check @param {String} keyName the key to check @return {Descriptor} @private */ function descriptorFor(obj, keyName, _meta) { true && !(obj !== null) && (0, _debug.assert)('Cannot call `descriptorFor` on null', obj !== null); true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `descriptorFor` on undefined', obj !== undefined); true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`descriptorFor\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'); let meta = _meta === undefined ? peekMeta(obj) : _meta; if (meta !== undefined) { return meta.peekDescriptors(keyName); } } /** Check whether a value is a CP descriptor. @method descriptorFor @param {any} possibleDesc the value to check @return {boolean} @private */ function isDescriptor(possibleDesc) { // TODO make this return `possibleDesc is Descriptor` return possibleDesc !== undefined && possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor === true; } exports.counters = counters; function indexOfListener(listeners, event, target, method) { for (let i = listeners.length - 1; i >= 0; i--) { let listener = listeners[i]; if (listener.event === event && (listener.target === target && listener.method === method || listener.kind === 3 /* REMOVE_ALL */)) { return i; } } return -1; } }); enifed('@ember/-internals/metal', ['exports', '@ember/-internals/utils', '@ember/-internals/meta', '@ember/debug', '@ember/runloop', '@glimmer/reference', '@ember/deprecated-features', '@ember/error', 'ember/version', '@ember/-internals/environment', '@ember/polyfills', '@ember/-internals/owner'], function (exports, _utils, _meta2, _debug, _runloop, _reference, _deprecatedFeatures, _error, _version, _environment, _polyfills, _owner) { 'use strict'; exports.setNamespaceSearchDisabled = exports.isNamespaceSearchDisabled = exports.removeNamespace = exports.processAllNamespaces = exports.processNamespace = exports.findNamespaces = exports.findNamespace = exports.classToString = exports.addNamespace = exports.NAMESPACES_BY_ID = exports.NAMESPACES = exports.tracked = exports.descriptor = exports.assertNotRendered = exports.didRender = exports.runInTransaction = exports.markObjectAsDirty = exports.tagFor = exports.tagForProperty = exports.setHasViews = exports.InjectedProperty = exports.applyMixin = exports.observer = exports.mixin = exports.aliasMethod = exports.Mixin = exports.removeObserver = exports.addObserver = exports.expandProperties = exports.setProperties = exports.getProperties = exports.Libraries = exports.libraries = exports.watcherCount = exports.watch = exports.unwatch = exports.isWatching = exports.unwatchPath = exports.watchPath = exports.removeChainWatcher = exports.finishChains = exports.ChainNode = exports.unwatchKey = exports.watchKey = exports.Descriptor = exports.defineProperty = exports.PROPERTY_DID_CHANGE = exports.propertyWillChange = exports.propertyDidChange = exports.overrideChains = exports.notifyPropertyChange = exports.endPropertyChanges = exports.changeProperties = exports.beginPropertyChanges = exports.isPresent = exports.isBlank = exports.isEmpty = exports.isNone = exports.sendEvent = exports.removeListener = exports.on = exports.hasListeners = exports.addListener = exports.eachProxyArrayDidChange = exports.eachProxyArrayWillChange = exports.eachProxyFor = exports.arrayContentDidChange = exports.arrayContentWillChange = exports.removeArrayObserver = exports.addArrayObserver = exports.replaceInNativeArray = exports.replace = exports.objectAt = exports.trySet = exports.set = exports.getWithDefault = exports.get = exports._getPath = exports.PROXY_CONTENT = exports.deprecateProperty = exports.alias = exports.peekCacheFor = exports.getCachedValueFor = exports.getCacheFor = exports._globalsComputed = exports.ComputedProperty = exports.computed = undefined; const COMPUTED_PROPERTY_CACHED_VALUES = new WeakMap(); const COMPUTED_PROPERTY_LAST_REVISION = false /* EMBER_METAL_TRACKED_PROPERTIES */ ? new WeakMap() : undefined; /** 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 @static @for @ember/object/internals @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 getCacheFor(obj) { let cache = COMPUTED_PROPERTY_CACHED_VALUES.get(obj); if (cache === undefined) { cache = new Map(); if (false /* EMBER_METAL_TRACKED_PROPERTIES */) { COMPUTED_PROPERTY_LAST_REVISION.set(obj, new Map()); } COMPUTED_PROPERTY_CACHED_VALUES.set(obj, cache); } return cache; } function getCachedValueFor(obj, key) { let cache = COMPUTED_PROPERTY_CACHED_VALUES.get(obj); if (cache !== undefined) { return cache.get(key); } } let setLastRevisionFor; let getLastRevisionFor; if (false /* EMBER_METAL_TRACKED_PROPERTIES */) { setLastRevisionFor = (obj, key, revision) => { let lastRevision = COMPUTED_PROPERTY_LAST_REVISION.get(obj); lastRevision.set(key, revision); }; getLastRevisionFor = (obj, key) => { let cache = COMPUTED_PROPERTY_LAST_REVISION.get(obj); if (cache === undefined) { return 0; } else { let revision = cache.get(key); return revision === undefined ? 0 : revision; } }; } function peekCacheFor(obj) { return COMPUTED_PROPERTY_CACHED_VALUES.get(obj); } const firstDotIndexCache = new _utils.Cache(1000, key => key.indexOf('.')); function isPath(path) { return typeof path === 'string' && firstDotIndexCache.get(path) !== -1; } const AFTER_OBSERVERS = ':change'; function changeEvent(keyName) { return keyName + AFTER_OBSERVERS; } /** @module @ember/object */ /* 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:change": [ // variable name: `actions` target, method, once ] } } */ /** Add an event listener @method addListener @static @for @ember/object/events @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) { true && !(!!obj && !!eventName) && (0, _debug.assert)('You must pass at least an object and event name to addListener', !!obj && !!eventName); if (!method && 'function' === typeof target) { method = target; target = null; } (0, _meta2.meta)(obj).addToListeners(eventName, target, method, once === true); } /** Remove an event listener Arguments should match those passed to `addListener`. @method removeListener @static @for @ember/object/events @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) { true && !(!!obj && !!eventName) && (0, _debug.assert)('You must pass at least an object and event name to removeListener', !!obj && !!eventName); if (!method && 'function' === typeof target) { method = target; target = null; } let m = (0, _meta2.meta)(obj); if (method === undefined) { m.removeAllListeners(eventName); } else { m.removeFromListeners(eventName, target, method); } } /** 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 @static @for @ember/object/events @param obj @param {String} eventName @param {Array} params Optional parameters for each listener. @return true @public */ function sendEvent(obj, eventName, params, actions, _meta) { if (actions === undefined) { let meta$$1 = _meta === undefined ? (0, _meta2.peekMeta)(obj) : _meta; actions = typeof meta$$1 === 'object' && meta$$1 !== null && meta$$1.matchingListeners(eventName); } if (actions === undefined || actions.length === 0) { return false; } for (let i = actions.length - 3; i >= 0; i -= 3) { // looping in reverse for once listeners let target = actions[i]; let method = actions[i + 1]; let once = actions[i + 2]; if (!method) { continue; } if (once) { removeListener(obj, eventName, target, method); } if (!target) { target = obj; } if ('string' === typeof method) { method = target[method]; } method.apply(target, params); } return true; } /** @private @method hasListeners @static @for @ember/object/events @param obj @param {String} eventName */ function hasListeners(obj, eventName) { let meta$$1 = (0, _meta2.peekMeta)(obj); if (meta$$1 === undefined) { return false; } let matched = meta$$1.matchingListeners(eventName); return matched !== undefined && matched.length > 0; } /** Define a property as a function that should be executed when a specified event or events are triggered. ``` javascript import EmberObject from '@ember/object'; import { on } from '@ember/object/evented'; import { sendEvent } from '@ember/object/events'; let Job = EmberObject.extend({ logCompleted: on('completed', function() { console.log('Job completed!'); }) }); let job = Job.create(); sendEvent(job, 'completed'); // Logs 'Job completed!' ``` @method on @static @for @ember/object/evented @param {String} eventNames* @param {Function} func @return func @public */ function on(...args) { let func = args.pop(); let events = args; true && !(typeof func === 'function') && (0, _debug.assert)('on expects function as last argument', typeof func === 'function'); true && !(events.length > 0 && events.every(p => typeof p === 'string' && p.length > 0)) && (0, _debug.assert)('on called without valid event names', events.length > 0 && events.every(p => typeof p === 'string' && p.length > 0)); (0, _utils.setListeners)(func, events); return func; } /** ObserverSet is a data structure used to keep track of observers that have been deferred. It ensures that observers are called in the same order that they were initially triggered. It also ensures that observers for any object-key pairs are called only once, even if they were triggered multiple times while deferred. In this case, the order that the observer is called in will depend on the first time the observer was triggered. @private @class ObserverSet */ class ObserverSet { constructor() { this.added = new Map(); this.queue = []; } add(object, key, event) { let keys = this.added.get(object); if (keys === undefined) { keys = new Set(); this.added.set(object, keys); } if (!keys.has(key)) { this.queue.push(object, key, event); keys.add(key); } } flush() { // The queue is saved off to support nested flushes. let queue = this.queue; this.added.clear(); this.queue = []; for (let i = 0; i < queue.length; i += 3) { let object = queue[i]; let key = queue[i + 1]; let event = queue[i + 2]; if (object.isDestroying || object.isDestroyed) { continue; } sendEvent(object, event, [object, key]); } } } let hasViews = () => false; function setHasViews(fn) { hasViews = fn; } function makeTag() { return _reference.DirtyableTag.create(); } function tagForProperty(object, propertyKey, _meta) { if (typeof object !== 'object' || object === null) { return _reference.CONSTANT_TAG; } let meta$$1 = _meta === undefined ? (0, _meta2.meta)(object) : _meta; if ((0, _utils.isProxy)(object)) { return tagFor(object, meta$$1); } let tags = meta$$1.writableTags(); let tag = tags[propertyKey]; if (tag) { return tag; } if (false /* EMBER_METAL_TRACKED_PROPERTIES */) { let pair = (0, _reference.combine)([makeTag(), _reference.UpdatableTag.create(_reference.CONSTANT_TAG)]); return tags[propertyKey] = pair; } else { return tags[propertyKey] = makeTag(); } } function tagFor(object, _meta) { if (typeof object === 'object' && object !== null) { let meta$$1 = _meta === undefined ? (0, _meta2.meta)(object) : _meta; return meta$$1.writableTag(makeTag); } else { return _reference.CONSTANT_TAG; } } let dirty; let update; if (false /* EMBER_METAL_TRACKED_PROPERTIES */) { dirty = tag => { tag.inner.first.inner.dirty(); }; update = (outer, inner) => { outer.inner.second.inner.update(inner); }; } else { dirty = tag => { tag.inner.dirty(); }; } function markObjectAsDirty(obj, propertyKey, meta$$1) { let objectTag = meta$$1.readableTag(); if (objectTag !== undefined) { if ((0, _utils.isProxy)(obj)) { objectTag.inner.first.inner.dirty(); } else { objectTag.inner.dirty(); } } let tags = meta$$1.readableTags(); let propertyTag = tags !== undefined ? tags[propertyKey] : undefined; if (propertyTag !== undefined) { dirty(propertyTag); } if (objectTag !== undefined || propertyTag !== undefined) { ensureRunloop(); } } function ensureRunloop() { if (hasViews()) { _runloop.backburner.ensureInstance(); } } let runInTransaction; let didRender; let assertNotRendered; // detect-backtracking-rerender by default is debug build only if (true /* DEBUG */) { // there are 2 states // DEBUG // tracks lastRef and lastRenderedIn per rendered object and key during a transaction // release everything via normal weakmap semantics by just derefencing the weakmap // RELEASE // tracks transactionId per rendered object and key during a transaction // release everything via normal weakmap semantics by just derefencing the weakmap class TransactionRunner { constructor() { this.transactionId = 0; this.inTransaction = false; this.shouldReflush = false; this.weakMap = new WeakMap(); if (true /* DEBUG */) { // track templates this.debugStack = undefined; } } runInTransaction(context$$1, methodName) { this.before(context$$1); try { context$$1[methodName](); } finally { this.after(); } return this.shouldReflush; } didRender(object, key, reference) { if (!this.inTransaction) { return; } if (true /* DEBUG */) { this.setKey(object, key, { lastRef: reference, lastRenderedIn: this.debugStack.peek() }); } else { this.setKey(object, key, this.transactionId); } } assertNotRendered(object, key) { if (!this.inTransaction) { return; } if (this.hasRendered(object, key)) { if (true /* DEBUG */) { let { lastRef, lastRenderedIn } = this.getKey(object, key); let currentlyIn = this.debugStack.peek(); let parts = []; let label; if (lastRef !== undefined) { while (lastRef && lastRef._propertyKey) { parts.unshift(lastRef._propertyKey); lastRef = lastRef._parentReference; } label = parts.join('.'); } else { label = 'the same value'; } true && !false && (0, _debug.assert)(`You modified "${label}" twice on ${object} in a single render. It was rendered in ${lastRenderedIn} and modified in ${currentlyIn}. This was unreliable and slow in Ember 1.x and is no longer supported. See https://github.com/emberjs/ember.js/issues/13948 for more details.`, false); } this.shouldReflush = true; } } hasRendered(object, key) { if (!this.inTransaction) { return false; } if (true /* DEBUG */) { return this.getKey(object, key) !== undefined; } return this.getKey(object, key) === this.transactionId; } before(context$$1) { this.inTransaction = true; this.shouldReflush = false; if (true /* DEBUG */) { this.debugStack = context$$1.env.debugStack; } } after() { this.transactionId++; this.inTransaction = false; if (true /* DEBUG */) { this.debugStack = undefined; } this.clearObjectMap(); } createMap(object) { let map = Object.create(null); this.weakMap.set(object, map); return map; } getOrCreateMap(object) { let map = this.weakMap.get(object); if (map === undefined) { map = this.createMap(object); } return map; } setKey(object, key, value) { let map = this.getOrCreateMap(object); map[key] = value; } getKey(object, key) { let map = this.weakMap.get(object); if (map !== undefined) { return map[key]; } } clearObjectMap() { this.weakMap = new WeakMap(); } } let runner = new TransactionRunner(); exports.runInTransaction = runInTransaction = runner.runInTransaction.bind(runner); exports.didRender = didRender = runner.didRender.bind(runner); exports.assertNotRendered = assertNotRendered = runner.assertNotRendered.bind(runner); } else { // in production do nothing to detect reflushes exports.runInTransaction = runInTransaction = (context$$1, methodName) => { context$$1[methodName](); return false; }; } /** @module ember @private */ const PROPERTY_DID_CHANGE$1 = (0, _utils.symbol)('PROPERTY_DID_CHANGE'); const observerSet = new ObserverSet(); let deferred = 0; // .......................................................... // PROPERTY CHANGES // /** @method propertyWillChange @for Ember @private */ let propertyWillChange; if (_deprecatedFeatures.PROPERTY_WILL_CHANGE) { exports.propertyWillChange = propertyWillChange = function propertyWillChange() { true && !false && (0, _debug.deprecate)(`'propertyWillChange' is deprecated and has no effect. It is safe to remove this call.`, false, { id: 'ember-metal.deprecate-propertyWillChange', until: '3.5.0', url: 'https://emberjs.com/deprecations/v3.x/#toc_use-notifypropertychange-instead-of-propertywillchange-and-propertydidchange' }); }; } /** @method propertyDidChange @for Ember @private */ let propertyDidChange; if (_deprecatedFeatures.PROPERTY_DID_CHANGE) { exports.propertyDidChange = propertyDidChange = function propertyDidChange(obj, keyName, _meta) { true && !false && (0, _debug.deprecate)(`'propertyDidChange' is deprecated in favor of 'notifyPropertyChange'. It is safe to change this call to 'notifyPropertyChange'.`, false, { id: 'ember-metal.deprecate-propertyDidChange', until: '3.5.0', url: 'https://emberjs.com/deprecations/v3.x/#toc_use-notifypropertychange-instead-of-propertywillchange-and-propertydidchange' }); notifyPropertyChange(obj, keyName, _meta); }; } /** 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. @method notifyPropertyChange @for Ember @param {Object} obj The object with the property that will change @param {String} keyName The property key (or path) that will change. @param {Meta} meta The objects meta. @return {void} @public */ function notifyPropertyChange(obj, keyName, _meta) { let meta$$1 = _meta === undefined ? (0, _meta2.peekMeta)(obj) : _meta; let hasMeta = meta$$1 !== undefined; if (hasMeta && (meta$$1.isInitializing() || meta$$1.isPrototypeMeta(obj))) { return; } let possibleDesc = (0, _meta2.descriptorFor)(obj, keyName, meta$$1); if (possibleDesc !== undefined && typeof possibleDesc.didChange === 'function') { possibleDesc.didChange(obj, keyName); } if (hasMeta && meta$$1.peekWatching(keyName) > 0) { dependentKeysDidChange(obj, keyName, meta$$1); chainsDidChange(obj, keyName, meta$$1); notifyObservers(obj, keyName, meta$$1); } if (PROPERTY_DID_CHANGE$1 in obj) { obj[PROPERTY_DID_CHANGE$1](keyName); } if (hasMeta) { if (meta$$1.isSourceDestroying()) { return; } markObjectAsDirty(obj, keyName, meta$$1); } if (true /* DEBUG */) { assertNotRendered(obj, keyName); } } const SEEN_MAP = new Map(); let IS_TOP_SEEN_MAP = true; // called whenever a property has just changed to update dependent keys function dependentKeysDidChange(obj, depKey, meta$$1) { if (meta$$1.isSourceDestroying() || !meta$$1.hasDeps(depKey)) { return; } let seen = SEEN_MAP; let isTop = IS_TOP_SEEN_MAP; if (isTop) { IS_TOP_SEEN_MAP = false; } iterDeps(notifyPropertyChange, obj, depKey, seen, meta$$1); if (isTop) { SEEN_MAP.clear(); IS_TOP_SEEN_MAP = true; } } function iterDeps(method, obj, depKey, seen, meta$$1) { let current = seen.get(obj); if (current === undefined) { current = new Set(); seen.set(obj, current); } if (current.has(depKey)) { return; } let possibleDesc; meta$$1.forEachInDeps(depKey, key => { possibleDesc = (0, _meta2.descriptorFor)(obj, key, meta$$1); if (possibleDesc !== undefined && possibleDesc._suspended === obj) { return; } method(obj, key, meta$$1); }); } function chainsDidChange(_obj, keyName, meta$$1) { let chainWatchers = meta$$1.readableChainWatchers(); if (chainWatchers !== undefined) { chainWatchers.notify(keyName, true, notifyPropertyChange); } } function overrideChains(_obj, keyName, meta$$1) { let chainWatchers = meta$$1.readableChainWatchers(); if (chainWatchers !== undefined) { chainWatchers.revalidate(keyName); } } /** @method beginPropertyChanges @chainable @private */ function beginPropertyChanges() { deferred++; } /** @method endPropertyChanges @private */ function endPropertyChanges() { deferred--; if (deferred <= 0) { 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 @private */ function changeProperties(callback) { beginPropertyChanges(); try { callback(); } finally { endPropertyChanges(); } } function notifyObservers(obj, keyName, meta$$1) { if (meta$$1.isSourceDestroying()) { return; } let eventName = changeEvent(keyName); if (deferred > 0) { observerSet.add(obj, keyName, eventName); } else { sendEvent(obj, eventName, [obj, keyName]); } } /** @module @ember/object */ // .......................................................... // 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 */ class Descriptor { constructor() { this.isDescriptor = true; this.enumerable = true; this.configurable = true; } setup(obj, keyName, meta$$1) { Object.defineProperty(obj, keyName, { enumerable: this.enumerable, configurable: this.configurable, get: DESCRIPTOR_GETTER_FUNCTION(keyName, this) }); meta$$1.writeDescriptors(keyName, this); } teardown(_obj, keyName, meta$$1) { meta$$1.removeDescriptors(keyName); } } // .......................................................... // DEFINING PROPERTIES API // function MANDATORY_SETTER_FUNCTION(name) { function SETTER_FUNCTION(value) { let m = (0, _meta2.peekMeta)(this); if (m.isInitializing() || m.isPrototypeMeta(this)) { m.writeValues(name, value); } else { true && !false && (0, _debug.assert)(`You must use set() to set the \`${name}\` property (of ${this}) to \`${value}\`.`, false); } } return Object.assign(SETTER_FUNCTION, { isMandatorySetter: true }); } function DEFAULT_GETTER_FUNCTION(name) { return function GETTER_FUNCTION() { let meta$$1 = (0, _meta2.peekMeta)(this); if (meta$$1 !== undefined) { return meta$$1.peekValues(name); } }; } function INHERITING_GETTER_FUNCTION(name) { function IGETTER_FUNCTION() { let meta$$1 = (0, _meta2.peekMeta)(this); let val; if (meta$$1 !== undefined) { val = meta$$1.readInheritedValue('values', name); } if (val === _meta2.UNDEFINED) { let proto = Object.getPrototypeOf(this); return proto && proto[name]; } else { return val; } } return Object.assign(IGETTER_FUNCTION, { isInheritingGetter: true }); } function DESCRIPTOR_GETTER_FUNCTION(name, descriptor) { return function CPGETTER_FUNCTION() { return descriptor.get(this, name); }; } /** 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 `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 import { defineProperty, computed } from '@ember/object'; // ES5 compatible mode defineProperty(contact, 'firstName', { writable: true, configurable: false, enumerable: true, value: 'Charles' }); // define a simple property defineProperty(contact, 'lastName', undefined, 'Jolley'); // define a computed property defineProperty(contact, 'fullName', computed('firstName', 'lastName', function() { return this.firstName+' '+this.lastName; })); ``` @private @method defineProperty @static @for @ember/object @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$$1) { if (meta$$1 === undefined) { meta$$1 = (0, _meta2.meta)(obj); } let watching = meta$$1.peekWatching(keyName) > 0; let previousDesc = (0, _meta2.descriptorFor)(obj, keyName, meta$$1); let wasDescriptor = previousDesc !== undefined; if (wasDescriptor) { previousDesc.teardown(obj, keyName, meta$$1); } // used to track if the the property being defined be enumerable let enumerable = true; // Ember.NativeArray is a normal Ember.Mixin that we mix into `Array.prototype` when prototype extensions are enabled // mutating a native object prototype like this should _not_ result in enumerable properties being added (or we have significant // issues with things like deep equality checks from test frameworks, or things like jQuery.extend(true, [], [])). // // this is a hack, and we should stop mutating the array prototype by default 😫 if (obj === Array.prototype) { enumerable = false; } let value; if (desc instanceof Descriptor) { value = desc; desc.setup(obj, keyName, meta$$1); } else if (desc === undefined || desc === null) { value = data; if (true /* DEBUG */ && watching) { meta$$1.writeValues(keyName, data); let defaultDescriptor = { configurable: true, enumerable, set: MANDATORY_SETTER_FUNCTION(keyName), get: DEFAULT_GETTER_FUNCTION(keyName) }; Object.defineProperty(obj, keyName, defaultDescriptor); } else if (wasDescriptor || enumerable === false) { Object.defineProperty(obj, keyName, { configurable: true, enumerable, writable: true, value }); } 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) { overrideChains(obj, keyName, meta$$1); } // The `value` passed to the `didDefineProperty` hook is // either the descriptor or data, whichever was passed. if (typeof obj.didDefineProperty === 'function') { obj.didDefineProperty(obj, keyName, value); } } let handleMandatorySetter; function watchKey(obj, keyName, _meta) { let meta$$1 = _meta === undefined ? (0, _meta2.meta)(obj) : _meta; let count = meta$$1.peekWatching(keyName); meta$$1.writeWatching(keyName, count + 1); if (count === 0) { // activate watching first time let possibleDesc = (0, _meta2.descriptorFor)(obj, keyName, meta$$1); if (possibleDesc !== undefined && possibleDesc.willWatch !== undefined) { possibleDesc.willWatch(obj, keyName, meta$$1); } if (typeof obj.willWatchProperty === 'function') { obj.willWatchProperty(keyName); } if (true /* DEBUG */) { // NOTE: this is dropped for prod + minified builds handleMandatorySetter(meta$$1, obj, keyName); } } } if (true /* DEBUG */) { let hasOwnProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key); let propertyIsEnumerable = (obj, key) => 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) { let descriptor = (0, _utils.lookupDescriptor)(obj, keyName); let hasDescriptor = descriptor !== null; let possibleDesc = hasDescriptor && descriptor.value; if ((0, _meta2.isDescriptor)(possibleDesc)) { return; } let configurable = hasDescriptor ? descriptor.configurable : true; let isWritable = hasDescriptor ? descriptor.writable : true; let hasValue = hasDescriptor ? 'value' in descriptor : true; // this x in Y deopts, so keeping it in this function is better; if (configurable && isWritable && hasValue && keyName in obj) { let desc = { configurable: true, set: MANDATORY_SETTER_FUNCTION(keyName), enumerable: propertyIsEnumerable(obj, keyName), get: undefined }; if (hasOwnProperty(obj, keyName)) { m.writeValues(keyName, obj[keyName]); desc.get = DEFAULT_GETTER_FUNCTION(keyName); } else { desc.get = INHERITING_GETTER_FUNCTION(keyName); } Object.defineProperty(obj, keyName, desc); } }; } function unwatchKey(obj, keyName, _meta) { let meta$$1 = _meta === undefined ? (0, _meta2.peekMeta)(obj) : _meta; // do nothing of this object has already been destroyed if (meta$$1 === undefined || meta$$1.isSourceDestroyed()) { return; } let count = meta$$1.peekWatching(keyName); if (count === 1) { meta$$1.writeWatching(keyName, 0); let possibleDesc = (0, _meta2.descriptorFor)(obj, keyName, meta$$1); let isDescriptor$$1 = possibleDesc !== undefined; if (isDescriptor$$1 && possibleDesc.didUnwatch !== undefined) { possibleDesc.didUnwatch(obj, keyName, meta$$1); } if (typeof obj.didUnwatchProperty === 'function') { obj.didUnwatchProperty(keyName); } if (true /* DEBUG */) { // 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 (!isDescriptor$$1 && keyName in obj) { let maybeMandatoryDescriptor = (0, _utils.lookupDescriptor)(obj, keyName); if (maybeMandatoryDescriptor && maybeMandatoryDescriptor.set && maybeMandatoryDescriptor.set.isMandatorySetter) { if (maybeMandatoryDescriptor.get && maybeMandatoryDescriptor.get.isInheritingGetter) { let possibleValue = meta$$1.readInheritedValue('values', keyName); if (possibleValue === _meta2.UNDEFINED) { delete obj[keyName]; return; } } Object.defineProperty(obj, keyName, { configurable: true, enumerable: Object.prototype.propertyIsEnumerable.call(obj, keyName), writable: true, value: meta$$1.peekValues(keyName) }); meta$$1.deleteFromValues(keyName); } } } } else if (count > 1) { meta$$1.writeWatching(keyName, count - 1); } } const EACH_PROXIES = new WeakMap(); function eachProxyArrayWillChange(array, idx, removedCnt, addedCnt) { let eachProxy = EACH_PROXIES.get(array); if (eachProxy !== undefined) { eachProxy.arrayWillChange(array, idx, removedCnt, addedCnt); } } function eachProxyArrayDidChange(array, idx, removedCnt, addedCnt) { let eachProxy = EACH_PROXIES.get(array); if (eachProxy !== undefined) { eachProxy.arrayDidChange(array, idx, removedCnt, addedCnt); } } function arrayContentWillChange(array, startIdx, removeAmt, addAmt) { // 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; } } eachProxyArrayWillChange(array, startIdx, removeAmt, addAmt); sendEvent(array, '@array:before', [array, startIdx, removeAmt, addAmt]); return array; } function arrayContentDidChange(array, startIdx, removeAmt, addAmt) { // 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; } } let meta$$1 = (0, _meta2.peekMeta)(array); if (addAmt < 0 || removeAmt < 0 || addAmt - removeAmt !== 0) { notifyPropertyChange(array, 'length', meta$$1); } notifyPropertyChange(array, '[]', meta$$1); eachProxyArrayDidChange(array, startIdx, removeAmt, addAmt); sendEvent(array, '@array:change', [array, startIdx, removeAmt, addAmt]); let cache = peekCacheFor(array); if (cache !== undefined) { let length = array.length; let addedAmount = addAmt === -1 ? 0 : addAmt; let removedAmount = removeAmt === -1 ? 0 : removeAmt; let delta = addedAmount - removedAmount; let previousLength = length - delta; let normalStartIdx = startIdx < 0 ? previousLength + startIdx : startIdx; if (cache.has('firstObject') && normalStartIdx === 0) { notifyPropertyChange(array, 'firstObject', meta$$1); } if (cache.has('lastObject')) { let previousLastIndex = previousLength - 1; let lastAffectedIndex = normalStartIdx + removedAmount; if (previousLastIndex < lastAffectedIndex) { notifyPropertyChange(array, 'lastObject', meta$$1); } } } return array; } /** An object that that tracks @tracked properties that were consumed. @private */ class Tracker { constructor() { this.tags = new Set(); this.last = null; } add(tag) { this.tags.add(tag); this.last = tag; } get size() { return this.tags.size; } combine() { if (this.tags.size === 0) { return _reference.CONSTANT_TAG; } else if (this.tags.size === 1) { return this.last; } else { let tags = []; this.tags.forEach(tag => tags.push(tag)); return (0, _reference.combine)(tags); } } } function tracked(...dependencies) { let [, key, descriptor] = dependencies; if (descriptor === undefined || 'initializer' in descriptor) { return descriptorForDataProperty(key, descriptor); } else { return descriptorForAccessor(key, descriptor); } } /** @private Whenever a tracked computed property is entered, the current tracker is saved off and a new tracker is replaced. Any tracked properties consumed are added to the current tracker. When a tracked computed property is exited, the tracker's tags are combined and added to the parent tracker. The consequence is that each tracked computed property has a tag that corresponds to the tracked properties consumed inside of itself, including child tracked computed properties. */ let CURRENT_TRACKER = null; function getCurrentTracker() { return CURRENT_TRACKER; } function setCurrentTracker(tracker = new Tracker()) { return CURRENT_TRACKER = tracker; } function descriptorForAccessor(key, descriptor) { let get = descriptor.get; let set = descriptor.set; function getter() { // Swap the parent tracker for a new tracker let old = CURRENT_TRACKER; let tracker = CURRENT_TRACKER = new Tracker(); // Call the getter let ret = get.call(this); // Swap back the parent tracker CURRENT_TRACKER = old; // Combine the tags in the new tracker and add them to the parent tracker let tag = tracker.combine(); if (CURRENT_TRACKER) CURRENT_TRACKER.add(tag); // Update the UpdatableTag for this property with the tag for all of the // consumed dependencies. update(tagForProperty(this, key), tag); return ret; } function setter() { dirty(tagForProperty(this, key)); set.apply(this, arguments); } return { enumerable: true, configurable: false, get: get && getter, set: set && setter }; } /** @private A getter/setter for change tracking for a particular key. The accessor acts just like a normal property, but it triggers the `propertyDidChange` hook when written to. Values are saved on the object using a "shadow key," or a symbol based on the tracked property name. Sets write the value to the shadow key, and gets read from it. */ function descriptorForDataProperty(key, descriptor) { let shadowKey = Symbol(key); return { enumerable: true, configurable: true, get() { if (CURRENT_TRACKER) CURRENT_TRACKER.add(tagForProperty(this, key)); if (!(shadowKey in this)) { this[shadowKey] = descriptor.value; } return this[shadowKey]; }, set(newValue) { tagFor(this).inner['dirty'](); dirty(tagForProperty(this, key)); this[shadowKey] = newValue; propertyDidChange$1(); } }; } let propertyDidChange$1 = function () {}; /** @module @ember/object */ const PROXY_CONTENT = (0, _utils.symbol)('PROXY_CONTENT'); let getPossibleMandatoryProxyValue; if (true /* DEBUG */ && _utils.HAS_NATIVE_PROXY) { getPossibleMandatoryProxyValue = function getPossibleMandatoryProxyValue(obj, keyName) { let content = obj[PROXY_CONTENT]; if (content === undefined) { return obj[keyName]; } else { /* global Reflect */ return Reflect.get(content, keyName, obj); } }; } // .......................................................... // 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. ```javascript import { get } from '@ember/object'; get(obj, "name"); ``` 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/object @static @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) { true && !(arguments.length === 2) && (0, _debug.assert)(`Get must be called with two arguments; an object and a property key`, arguments.length === 2); true && !(obj !== undefined && obj !== null) && (0, _debug.assert)(`Cannot call get with '${keyName}' on an undefined object.`, obj !== undefined && obj !== null); true && !(typeof keyName === 'string' || typeof keyName === 'number' && !isNaN(keyName)) && (0, _debug.assert)(`The key provided to get must be a string or number, you passed ${keyName}`, typeof keyName === 'string' || typeof keyName === 'number' && !isNaN(keyName)); true && !(typeof keyName !== 'string' || keyName.lastIndexOf('this.', 0) !== 0) && (0, _debug.assert)(`'this' in paths is not supported`, typeof keyName !== 'string' || keyName.lastIndexOf('this.', 0) !== 0); let type = typeof obj; let isObject = type === 'object'; let isFunction = type === 'function'; let isObjectLike = isObject || isFunction; let descriptor; let value; if (isObjectLike) { if (false /* EMBER_METAL_TRACKED_PROPERTIES */) { let tracker = getCurrentTracker(); if (tracker) tracker.add(tagForProperty(obj, keyName)); } descriptor = (0, _meta2.descriptorFor)(obj, keyName); if (descriptor !== undefined) { return descriptor.get(obj, keyName); } if (true /* DEBUG */ && _utils.HAS_NATIVE_PROXY) { value = getPossibleMandatoryProxyValue(obj, keyName); } else { value = obj[keyName]; } } else { value = obj[keyName]; } if (value === undefined) { if (isPath(keyName)) { return _getPath(obj, keyName); } if (isObject && !(keyName in obj) && typeof obj.unknownProperty === 'function') { return obj.unknownProperty(keyName); } } return value; } function _getPath(root, path) { let obj = root; let parts = path.split('.'); for (let i = 0; i < parts.length; i++) { if (obj === undefined || obj === null || obj.isDestroyed) { return undefined; } obj = get(obj, parts[i]); } return obj; } /** Retrieves the value of a property from an Object, or a default value in the case that the property returns `undefined`. ```javascript import { getWithDefault } from '@ember/object'; getWithDefault(person, 'lastName', 'Doe'); ``` @method getWithDefault @for @ember/object @static @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) { let value = get(root, key); if (value === undefined) { return defaultValue; } return value; } const EMPTY_ARRAY = Object.freeze([]); function objectAt(array, index) { if (Array.isArray(array)) { return array[index]; } else { return array.objectAt(index); } } function replace(array, start, deleteCount, items = EMPTY_ARRAY) { if (Array.isArray(array)) { replaceInNativeArray(array, start, deleteCount, items); } else { array.replace(start, deleteCount, items); } } const CHUNK_SIZE = 60000; // To avoid overflowing the stack, we splice up to CHUNK_SIZE items at a time. // See https://code.google.com/p/chromium/issues/detail?id=56588 for more details. function replaceInNativeArray(array, start, deleteCount, items) { arrayContentWillChange(array, start, deleteCount, items.length); if (items.length <= CHUNK_SIZE) { array.splice(start, deleteCount, ...items); } else { array.splice(start, deleteCount); for (let i = 0; i < items.length; i += CHUNK_SIZE) { let chunk = items.slice(i, i + CHUNK_SIZE); array.splice(start + i, 0, ...chunk); } } arrayContentDidChange(array, start, deleteCount, items.length); } function arrayObserversHelper(obj, target, opts, operation, notify) { let willChange = opts && opts.willChange || 'arrayWillChange'; let didChange = opts && opts.didChange || 'arrayDidChange'; let hasObservers = get(obj, 'hasArrayObservers'); operation(obj, '@array:before', target, willChange); operation(obj, '@array:change', target, didChange); if (hasObservers === notify) { notifyPropertyChange(obj, 'hasArrayObservers'); } return obj; } function addArrayObserver(array, target, opts) { return arrayObserversHelper(array, target, opts, addListener, false); } function removeArrayObserver(array, target, opts) { return arrayObserversHelper(array, target, opts, removeListener, true); } /** @module @ember/object */ /** @method addObserver @static @for @ember/object/observers @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @public */ function addObserver(obj, path, target, method) { addListener(obj, changeEvent(path), target, method); watch(obj, path); } /** @method removeObserver @static @for @ember/object/observers @param obj @param {String} path @param {Object|Function} target @param {Function|String} [method] @public */ function removeObserver(obj, path, target, method) { unwatch(obj, path); removeListener(obj, changeEvent(path), target, method); } function eachProxyFor(array) { let eachProxy = EACH_PROXIES.get(array); if (eachProxy === undefined) { eachProxy = new EachProxy(array); EACH_PROXIES.set(array, eachProxy); } return eachProxy; } class EachProxy { constructor(content) { this._content = content; this._keys = undefined; (0, _meta2.meta)(this); } // .......................................................... // ARRAY CHANGES // Invokes whenever the content array itself changes. arrayWillChange(content, idx, removedCnt /*, addedCnt */) { // eslint-disable-line no-unused-vars let keys = this._keys; if (!keys) { return; } let lim = removedCnt > 0 ? idx + removedCnt : -1; if (lim > 0) { for (let key in keys) { removeObserverForContentKey(content, key, this, idx, lim); } } } arrayDidChange(content, idx, _removedCnt, addedCnt) { let keys = this._keys; if (!keys) { return; } let lim = addedCnt > 0 ? idx + addedCnt : -1; let meta$$1 = (0, _meta2.peekMeta)(this); for (let key in keys) { if (lim > 0) { addObserverForContentKey(content, key, this, idx, lim); } notifyPropertyChange(this, key, meta$$1); } } // .......................................................... // LISTEN FOR NEW OBSERVERS AND OTHER EVENT LISTENERS // Start monitoring keys based on who is listening... willWatchProperty(property) { this.beginObservingContentKey(property); } didUnwatchProperty(property) { this.stopObservingContentKey(property); } // .......................................................... // CONTENT KEY OBSERVING // Actual watch keys on the source content. beginObservingContentKey(keyName) { let keys = this._keys; if (keys === undefined) { keys = this._keys = Object.create(null); } if (!keys[keyName]) { keys[keyName] = 1; let content = this._content; let len = content.length; addObserverForContentKey(content, keyName, this, 0, len); } else { keys[keyName]++; } } stopObservingContentKey(keyName) { let keys = this._keys; if (keys !== undefined && keys[keyName] > 0 && --keys[keyName] <= 0) { let content = this._content; let len = content.length; removeObserverForContentKey(content, keyName, this, 0, len); } } contentKeyDidChange(_obj, keyName) { notifyPropertyChange(this, keyName); } } function addObserverForContentKey(content, keyName, proxy, idx, loc) { while (--loc >= idx) { let item = objectAt(content, loc); if (item) { true && !(typeof item === 'object') && (0, _debug.assert)(`When using @each to observe the array \`${content.toString()}\`, the array must return an object`, typeof item === 'object'); addObserver(item, keyName, proxy, 'contentKeyDidChange'); } } } function removeObserverForContentKey(content, keyName, proxy, idx, loc) { while (--loc >= idx) { let item = objectAt(content, loc); if (item) { removeObserver(item, keyName, proxy, 'contentKeyDidChange'); } } } function isObject(obj) { return typeof obj === 'object' && obj !== null; } function isVolatile(obj, keyName, meta$$1) { let desc = (0, _meta2.descriptorFor)(obj, keyName, meta$$1); return !(desc !== undefined && desc._volatile === false); } class ChainWatchers { constructor() { // 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 = Object.create(null); } add(key, node) { let nodes = this.chains[key]; if (nodes === undefined) { this.chains[key] = [node]; } else { nodes.push(node); } } remove(key, node) { let nodes = this.chains[key]; if (nodes !== undefined) { for (let i = 0; i < nodes.length; i++) { if (nodes[i] === node) { nodes.splice(i, 1); break; } } } } has(key, node) { let nodes = this.chains[key]; if (nodes !== undefined) { for (let i = 0; i < nodes.length; i++) { if (nodes[i] === node) { return true; } } } return false; } revalidateAll() { for (let key in this.chains) { this.notify(key, true, undefined); } } revalidate(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(key, revalidate, callback) { let nodes = this.chains[key]; if (nodes === undefined || nodes.length === 0) { return; } let affected = undefined; if (callback !== undefined) { affected = []; } for (let 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 (let i = 0; i < affected.length; i += 2) { let obj = affected[i]; let path = affected[i + 1]; callback(obj, path); } } } function makeChainWatcher() { return new ChainWatchers(); } function makeChainNode(obj) { return new ChainNode(null, null, obj); } function addChainWatcher(obj, keyName, node) { let m = (0, _meta2.meta)(obj); m.writableChainWatchers(makeChainWatcher).add(keyName, node); watchKey(obj, keyName, m); } function removeChainWatcher(obj, keyName, node, _meta) { if (!isObject(obj)) { return; } let meta$$1 = _meta === undefined ? (0, _meta2.peekMeta)(obj) : _meta; if (meta$$1 === undefined || meta$$1.isSourceDestroying() || meta$$1.isMetaDestroyed() || meta$$1.readableChainWatchers() === undefined) { return; } // make meta writable meta$$1 = (0, _meta2.meta)(obj); meta$$1.readableChainWatchers().remove(keyName, node); unwatchKey(obj, keyName, meta$$1); } const NODE_STACK = []; function destroyRoot(root) { pushChildren(root); while (NODE_STACK.length > 0) { let node = NODE_STACK.pop(); pushChildren(node); destroyOne(node); } } function destroyOne(node) { if (node.isWatching) { removeChainWatcher(node.object, node.key, node); node.isWatching = false; } } function pushChildren(node) { let nodes = node.chains; if (nodes !== undefined) { for (let key in nodes) { if (nodes[key] !== undefined) { NODE_STACK.push(nodes[key]); } } } } // 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. class ChainNode { constructor(parent, key, value) { this.paths = undefined; this.isWatching = false; this.chains = undefined; this.object = undefined; this.count = 0; this.parent = parent; this.key = key; this.content = value; // It is false for the root of a chain (because we have no parent) let isWatching = this.isWatching = parent !== null; if (isWatching) { let parentValue = parent.value(); if (isObject(parentValue)) { this.object = parentValue; addChainWatcher(parentValue, key, this); } } } value() { if (this.content === undefined && this.isWatching) { let obj = this.parent.value(); this.content = lazyGet(obj, this.key); } return this.content; } destroy() { // check if root if (this.parent === null) { destroyRoot(this); } else { destroyOne(this); } } // copies a top level object only copyTo(target) { let paths = this.paths; if (paths !== undefined) { let path; for (path in paths) { if (paths[path] > 0) { target.add(path); } } } } // called on the root node of a chain to setup watchers on the specified // path. add(path) { let paths = this.paths || (this.paths = {}); paths[path] = (paths[path] || 0) + 1; let tails = path.split('.'); this.chain(tails.shift(), tails); } // called on the root node of a chain to teardown watcher on the specified // path remove(path) { let paths = this.paths; if (paths === undefined) { return; } if (paths[path] > 0) { paths[path]--; } let tails = path.split('.'); this.unchain(tails.shift(), tails); } chain(key, tails) { let chains = this.chains; if (chains === undefined) { chains = this.chains = Object.create(null); } let 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 (tails.length > 0) { node.chain(tails.shift(), tails); } } unchain(key, tails) { let chains = this.chains; let node = chains[key]; // unchain rest of path first... if (tails.length > 0) { node.unchain(tails.shift(), tails); } // delete node if needed. node.count--; if (node.count <= 0) { chains[node.key] = undefined; node.destroy(); } } notify(revalidate, affected) { if (revalidate && this.isWatching) { let parentValue = this.parent.value(); if (parentValue !== this.object) { removeChainWatcher(this.object, this.key, this); if (isObject(parentValue)) { this.object = parentValue; addChainWatcher(parentValue, this.key, this); } else { this.object = undefined; } } this.content = undefined; } // then notify chains... let chains = this.chains; if (chains !== undefined) { let node; for (let key in chains) { node = chains[key]; if (node !== undefined) { node.notify(revalidate, affected); } } } if (affected !== undefined && this.parent !== null) { this.parent.populateAffected(this.key, 1, affected); } } populateAffected(path, depth, affected) { if (this.key) { path = `${this.key}.${path}`; } if (this.parent !== null) { this.parent.populateAffected(path, depth + 1, affected); } else if (depth > 1) { affected.push(this.value(), path); } } } function lazyGet(obj, key) { if (!isObject(obj)) { return; } let meta$$1 = (0, _meta2.peekMeta)(obj); // check if object meant only to be a prototype if (meta$$1 !== undefined && meta$$1.proto === obj) { return; } // Use `get` if the return value is an EachProxy or an uncacheable value. if (key === '@each') { return eachProxyFor(obj); } else if (isVolatile(obj, key, meta$$1)) { return get(obj, key); // Otherwise attempt to get the cached value of the computed property } else { return getCachedValueFor(obj, key); } } function finishChains(meta$$1) { // finish any current chains node watchers that reference obj let chainWatchers = meta$$1.readableChainWatchers(); if (chainWatchers !== undefined) { chainWatchers.revalidateAll(); } // ensure that if we have inherited any chains they have been // copied onto our own meta. if (meta$$1.readableChains() !== undefined) { meta$$1.writableChains(makeChainNode); } } function watchPath(obj, keyPath, meta$$1) { let m = meta$$1 === undefined ? (0, _meta2.meta)(obj) : meta$$1; let counter = m.peekWatching(keyPath); m.writeWatching(keyPath, counter + 1); if (counter === 0) { // activate watching first time m.writableChains(makeChainNode).add(keyPath); } } function unwatchPath(obj, keyPath, meta$$1) { let m = meta$$1 === undefined ? (0, _meta2.peekMeta)(obj) : meta$$1; if (m === undefined) { return; } let counter = m.peekWatching(keyPath); if (counter > 0) { m.writeWatching(keyPath, counter - 1); if (counter === 1) { m.writableChains(makeChainNode).remove(keyPath); } } } /** @module ember */ /** Starts watching a property on an object. Whenever the property changes, invokes `Ember.notifyPropertyChange`. 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 `addObserver()`. @private @method watch @for Ember @param obj @param {String} keyPath @param {Object} meta */ function watch(obj, keyPath, meta$$1) { if (isPath(keyPath)) { watchPath(obj, keyPath, meta$$1); } else { watchKey(obj, keyPath, meta$$1); } } function isWatching(obj, key) { return watcherCount(obj, key) > 0; } function watcherCount(obj, key) { let meta$$1 = (0, _meta2.peekMeta)(obj); return meta$$1 !== undefined && meta$$1.peekWatching(key) || 0; } /** Stops watching a property on an object. Usually you will never call this method directly but instead use higher level methods like `removeObserver()`. @private @method unwatch @for Ember @param obj @param {String} keyPath @param {Object} meta */ function unwatch(obj, keyPath, meta$$1) { if (isPath(keyPath)) { unwatchPath(obj, keyPath, meta$$1); } else { unwatchKey(obj, keyPath, meta$$1); } } // .......................................................... // DEPENDENT KEYS // function addDependentKeys(desc, obj, keyName, meta$$1) { // the descriptor has a list of dependent keys, so // add all of its dependent keys. let depKeys = desc._dependentKeys; if (depKeys === null || depKeys === undefined) { return; } for (let idx = 0; idx < depKeys.length; idx++) { let depKey = depKeys[idx]; // Increment the number of times depKey depends on keyName. meta$$1.writeDeps(depKey, keyName, meta$$1.peekDeps(depKey, keyName) + 1); // Watch the depKey watch(obj, depKey, meta$$1); } } function removeDependentKeys(desc, obj, keyName, meta$$1) { // the descriptor has a list of dependent keys, so // remove all of its dependent keys. let depKeys = desc._dependentKeys; if (depKeys === null || depKeys === undefined) { return; } for (let idx = 0; idx < depKeys.length; idx++) { let depKey = depKeys[idx]; // Decrement the number of times depKey depends on keyName. meta$$1.writeDeps(depKey, keyName, meta$$1.peekDeps(depKey, keyName) - 1); // Unwatch the depKey unwatch(obj, depKey, meta$$1); } } /** @module @ember/object */ const 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 import { expandProperties } from '@ember/object/computed'; function echo(arg){ console.log(arg); } expandProperties('foo.bar', echo); //=> 'foo.bar' expandProperties('{foo,bar}', echo); //=> 'foo', 'bar' expandProperties('foo.{bar,baz}', echo); //=> 'foo.bar', 'foo.baz' expandProperties('{foo,bar}.baz', echo); //=> 'foo.baz', 'bar.baz' expandProperties('foo.{bar,baz}.[]', echo) //=> 'foo.bar.[]', 'foo.baz.[]' expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs' expandProperties('{foo}.bar.{baz}') //=> 'foo.bar.baz' ``` @method expandProperties @static @for @ember/object/computed @public @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) { true && !(typeof pattern === 'string') && (0, _debug.assert)(`A computed property key must be a string, you passed ${typeof pattern} ${pattern}`, typeof pattern === 'string'); true && !(pattern.indexOf(' ') === -1) && (0, _debug.assert)('Brace expanded properties cannot contain spaces, e.g. "user.{firstName, lastName}" should be "user.{firstName,lastName}"', pattern.indexOf(' ') === -1); // regex to look for double open, double close, or unclosed braces true && !(pattern.match(/\{[^}{]*\{|\}[^}{]*\}|\{[^}]*$/g) === null) && (0, _debug.assert)(`Brace expanded properties have to be balanced and cannot be nested, pattern: ${pattern}`, pattern.match(/\{[^}{]*\{|\}[^}{]*\}|\{[^}]*$/g) === null); let start = pattern.indexOf('{'); if (start < 0) { callback(pattern.replace(END_WITH_EACH_REGEX, '.[]')); } else { dive('', pattern, start, callback); } } function dive(prefix, pattern, start, callback) { let end = pattern.indexOf('}'), i = 0, newStart, arrayLength; let tempArr = pattern.substring(start + 1, end).split(','); let after = pattern.substring(end + 1); prefix = prefix + pattern.substring(0, start); arrayLength = tempArr.length; while (i < arrayLength) { newStart = after.indexOf('{'); if (newStart < 0) { callback((prefix + tempArr[i++] + after).replace(END_WITH_EACH_REGEX, '.[]')); } else { dive(prefix + tempArr[i++], after, newStart, callback); } } } let setWithMandatorySetter; let makeEnumerable; /** @module @ember/object */ /** Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the specified property is not defined on the object and the object implements the `setUnknownProperty` method, then instead of setting the value of the property on the object, its `setUnknownProperty` handler will be invoked with the two parameters `keyName` and `value`. ```javascript import { set } from '@ember/object'; set(obj, "name", value); ``` @method set @static @for @ember/object @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) { true && !(arguments.length === 3 || arguments.length === 4) && (0, _debug.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); true && !(obj && typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call set with '${keyName}' on an undefined object.`, obj && typeof obj === 'object' || typeof obj === 'function'); true && !(typeof keyName === 'string' || typeof keyName === 'number' && !isNaN(keyName)) && (0, _debug.assert)(`The key provided to set must be a string or number, you passed ${keyName}`, typeof keyName === 'string' || typeof keyName === 'number' && !isNaN(keyName)); true && !(typeof keyName !== 'string' || keyName.lastIndexOf('this.', 0) !== 0) && (0, _debug.assert)(`'this' in paths is not supported`, typeof keyName !== 'string' || keyName.lastIndexOf('this.', 0) !== 0); if (obj.isDestroyed) { true && !tolerant && (0, _debug.assert)(`calling set on destroyed object: ${(0, _utils.toString)(obj)}.${keyName} = ${(0, _utils.toString)(value)}`, tolerant); return; } if (isPath(keyName)) { return setPath(obj, keyName, value, tolerant); } let possibleDesc = (0, _meta2.descriptorFor)(obj, keyName); if (possibleDesc !== undefined) { /* computed property */ possibleDesc.set(obj, keyName, value); return value; } let currentValue; if (true /* DEBUG */ && _utils.HAS_NATIVE_PROXY) { currentValue = getPossibleMandatoryProxyValue(obj, keyName); } else { currentValue = obj[keyName]; } if (currentValue === undefined && 'object' === typeof obj && !(keyName in obj) && typeof obj.setUnknownProperty === 'function') { /* unknown property */ obj.setUnknownProperty(keyName, value); } else { let meta$$1 = (0, _meta2.peekMeta)(obj); if (true /* DEBUG */) { setWithMandatorySetter(meta$$1, obj, keyName, value); } else { obj[keyName] = value; } if (currentValue !== value) { notifyPropertyChange(obj, keyName, meta$$1); } } return value; } if (true /* DEBUG */) { setWithMandatorySetter = (meta$$1, obj, keyName, value) => { if (meta$$1 !== undefined && meta$$1.peekWatching(keyName) > 0) { makeEnumerable(obj, keyName); meta$$1.writeValue(obj, keyName, value); } else { obj[keyName] = value; } }; makeEnumerable = (obj, key) => { let 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) { let parts = path.split('.'); let keyName = parts.pop(); true && !(keyName.trim().length > 0) && (0, _debug.assert)('Property set failed: You passed an empty path', keyName.trim().length > 0); let newPath = parts.join('.'); let newRoot = _getPath(root, newPath); if (newRoot !== null && newRoot !== undefined) { return set(newRoot, keyName, value); } else if (!tolerant) { throw new _error.default(`Property set failed: object in path "${newPath}" could not be found.`); } } /** Error-tolerant form of `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. ```javascript import { trySet } from '@ember/object'; let obj = { name: "Zoey" }; trySet(obj, "contacts.twitter", "@emberjs"); ``` @method trySet @static @for @ember/object @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); } /** @module @ember/object */ const DEEP_EACH_REGEX = /\.@each\.[^.]+\./; function noop() {} /** 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 `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 import EmberObject, { computed } from '@ember/object'; let Person = EmberObject.extend({ // these will be supplied by `create` firstName: null, lastName: null, fullName: 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 import EmberObject, { computed } from '@ember/object'; let Person = EmberObject.extend({ // these will be supplied by `create` firstName: null, lastName: null, fullName: 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 import EmberObject, { computed } from '@ember/object'; let Person = EmberObject.extend({ // these will be supplied by `create` firstName: null, lastName: null, fullName: 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" ](https://emberjs.com/blog/2015/05/13/ember-1-12-released.html#toc_new-computed-syntax) @class ComputedProperty @public */ class ComputedProperty extends Descriptor { constructor(config, opts) { super(); let hasGetterOnly = typeof config === 'function'; if (hasGetterOnly) { this._getter = config; } else { const objectConfig = config; true && !(typeof objectConfig === 'object' && !Array.isArray(objectConfig)) && (0, _debug.assert)('computed expects a function or an object as last argument.', typeof objectConfig === 'object' && !Array.isArray(objectConfig)); true && !Object.keys(objectConfig).every(key => key === 'get' || key === 'set') && (0, _debug.assert)('Config object passed to computed can only contain `get` and `set` keys.', Object.keys(objectConfig).every(key => key === 'get' || key === 'set')); true && !(!!objectConfig.get || !!objectConfig.set) && (0, _debug.assert)('Computed properties must receive a getter or a setter, you passed none.', !!objectConfig.get || !!objectConfig.set); this._getter = objectConfig.get || noop; this._setter = objectConfig.set; } this._suspended = undefined; this._meta = undefined; this._volatile = false; if (false /* EMBER_METAL_TRACKED_PROPERTIES */) { this._auto = false; } this._dependentKeys = opts && opts.dependentKeys; this._readOnly = !!opts && hasGetterOnly && opts.readOnly === true; } /** 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 import EmberObject, { computed } from '@ember/object'; let outsideService = EmberObject.extend({ value: computed(function() { return OutsideService.getValue(); }).volatile() }).create(); ``` @method volatile @return {ComputedProperty} this @chainable @public */ volatile() { 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 import EmberObject, { computed } from '@ember/object'; let Person = EmberObject.extend({ guid: computed(function() { return 'guid-guid-guid'; }).readOnly() }); let person = Person.create(); person.set('guid', 'new-guid'); // will throw an exception ``` @method readOnly @return {ComputedProperty} this @chainable @public */ readOnly() { this._readOnly = true; true && !!(this._readOnly && this._setter && this._setter !== this._getter) && (0, _debug.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 import EmberObject, { computed } from '@ember/object'; let President = EmberObject.extend({ fullName: computed('firstName', 'lastName', function() { return this.get('firstName') + ' ' + this.get('lastName'); // Tell Ember that this computed property depends on firstName // and 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 {ComputedProperty} this @chainable @public */ property(...passedArgs) { let args = []; function addArg(property) { true && (0, _debug.warn)(`Dependent keys containing @each only work one level deep. ` + `You used the key "${property}" which is invalid. ` + `Please create an intermediary computed property.`, DEEP_EACH_REGEX.test(property) === false, { id: 'ember-metal.computed-deep-each' }); args.push(property); } for (let i = 0; i < passedArgs.length; i++) { expandProperties(passedArgs[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: ``` import { computed } from '@ember/object'; import Person from 'my-app/utils/person'; person: computed(function() { let personId = this.get('personId'); return Person.create({ id: personId }); }).meta({ type: 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 */ meta(meta$$1) { if (arguments.length === 0) { return this._meta || {}; } else { this._meta = meta$$1; return this; } } // invalidate cache when CP key changes didChange(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 let meta$$1 = (0, _meta2.peekMeta)(obj); if (meta$$1 === undefined || meta$$1.source !== obj) { return; } let cache = peekCacheFor(obj); if (cache !== undefined && cache.delete(keyName)) { removeDependentKeys(this, obj, keyName, meta$$1); } } get(obj, keyName) { if (this._volatile) { return this._getter.call(obj, keyName); } let cache = getCacheFor(obj); let propertyTag; if (false /* EMBER_METAL_TRACKED_PROPERTIES */) { propertyTag = tagForProperty(obj, keyName); if (cache.has(keyName)) { // special-case for computed with no dependent keys used to // trigger cacheable behavior. if (!this._auto && (!this._dependentKeys || this._dependentKeys.length === 0)) { return cache.get(keyName); } let lastRevision = getLastRevisionFor(obj, keyName); if (propertyTag.validate(lastRevision)) { return cache.get(keyName); } } } else { if (cache.has(keyName)) { return cache.get(keyName); } } let parent; let tracker; if (false /* EMBER_METAL_TRACKED_PROPERTIES */) { parent = getCurrentTracker(); tracker = setCurrentTracker(); } let ret = this._getter.call(obj, keyName); if (false /* EMBER_METAL_TRACKED_PROPERTIES */) { setCurrentTracker(parent); let tag = tracker.combine(); if (parent) parent.add(tag); update(propertyTag, tag); setLastRevisionFor(obj, keyName, propertyTag.value()); } cache.set(keyName, ret); let meta$$1 = (0, _meta2.meta)(obj); let chainWatchers = meta$$1.readableChainWatchers(); if (chainWatchers !== undefined) { chainWatchers.revalidate(keyName); } addDependentKeys(this, obj, keyName, meta$$1); return ret; } set(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); } _throwReadOnlyError(obj, keyName) { throw new _error.default(`Cannot set read-only property "${keyName}" on object: ${(0, _utils.inspect)(obj)}`); } clobberSet(obj, keyName, value) { let cachedValue = getCachedValueFor(obj, keyName); defineProperty(obj, keyName, null, cachedValue); set(obj, keyName, value); return value; } volatileSet(obj, keyName, value) { return this._setter.call(obj, keyName, value); } setWithSuspend(obj, keyName, value) { let oldSuspended = this._suspended; this._suspended = obj; try { return this._set(obj, keyName, value); } finally { this._suspended = oldSuspended; } } _set(obj, keyName, value) { let cache = getCacheFor(obj); let hadCachedValue = cache.has(keyName); let cachedValue = cache.get(keyName); let 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; } let meta$$1 = (0, _meta2.meta)(obj); if (!hadCachedValue) { addDependentKeys(this, obj, keyName, meta$$1); } cache.set(keyName, ret); notifyPropertyChange(obj, keyName, meta$$1); if (false /* EMBER_METAL_TRACKED_PROPERTIES */) { let propertyTag = tagForProperty(obj, keyName); setLastRevisionFor(obj, keyName, propertyTag.value()); } return ret; } /* called before property is overridden */ teardown(obj, keyName, meta$$1) { if (this._volatile) { return; } let cache = peekCacheFor(obj); if (cache !== undefined && cache.delete(keyName)) { removeDependentKeys(this, obj, keyName, meta$$1); } super.teardown(obj, keyName, meta$$1); } } if (false /* EMBER_METAL_TRACKED_PROPERTIES */) { ComputedProperty.prototype.auto = function () { this._auto = true; return this; }; } /** 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 `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 import EmberObject, { computed } from '@ember/object'; let Person = EmberObject.extend({ init() { this._super(...arguments); this.firstName = 'Betty'; this.lastName = 'Jones'; }, fullName: 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 import EmberObject, { computed } from '@ember/object'; let Person = EmberObject.extend({ init() { this._super(...arguments); this.firstName = 'Betty'; this.lastName = 'Jones'; }, fullName: 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](https://guides.emberjs.com/release/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') ``` @method computed @for @ember/object @static @param {String} [dependentKeys*] Optional dependent keys that trigger this computed property. @param {Function} func The computed property function. @return {ComputedProperty} property descriptor instance @public */ function computed(...args) { let func = args.pop(); let cp = new ComputedProperty(func); if (args.length > 0) { cp.property(...args); } return cp; } // used for the Ember.computed global only const _globalsComputed = computed.bind(null); const CONSUMED = Object.freeze({}); function alias(altKey) { return new AliasedProperty(altKey); } class AliasedProperty extends Descriptor { constructor(altKey) { super(); this.altKey = altKey; this._dependentKeys = [altKey]; } setup(obj, keyName, meta$$1) { true && !(this.altKey !== keyName) && (0, _debug.assert)(`Setting alias '${keyName}' on self`, this.altKey !== keyName); super.setup(obj, keyName, meta$$1); if (meta$$1.peekWatching(keyName) > 0) { this.consume(obj, keyName, meta$$1); } } teardown(obj, keyName, meta$$1) { this.unconsume(obj, keyName, meta$$1); super.teardown(obj, keyName, meta$$1); } willWatch(obj, keyName, meta$$1) { this.consume(obj, keyName, meta$$1); } didUnwatch(obj, keyName, meta$$1) { this.unconsume(obj, keyName, meta$$1); } get(obj, keyName) { let ret = get(obj, this.altKey); this.consume(obj, keyName, (0, _meta2.meta)(obj)); return ret; } unconsume(obj, keyName, meta$$1) { let wasConsumed = getCachedValueFor(obj, keyName) === CONSUMED; if (wasConsumed || meta$$1.peekWatching(keyName) > 0) { removeDependentKeys(this, obj, keyName, meta$$1); } if (wasConsumed) { getCacheFor(obj).delete(keyName); } } consume(obj, keyName, meta$$1) { let cache = getCacheFor(obj); if (cache.get(keyName) !== CONSUMED) { cache.set(keyName, CONSUMED); addDependentKeys(this, obj, keyName, meta$$1); } } set(obj, _keyName, value) { return set(obj, this.altKey, value); } readOnly() { this.set = AliasedProperty_readOnlySet; return this; } oneWay() { this.set = AliasedProperty_oneWaySet; return this; } } function AliasedProperty_readOnlySet(obj, keyName) { // eslint-disable-line no-unused-vars throw new _error.default(`Cannot set read-only property '${keyName}' on object: ${(0, _utils.inspect)(obj)}`); } function AliasedProperty_oneWaySet(obj, keyName, value) { defineProperty(obj, keyName, null); return set(obj, keyName, value); } // Backwards compatibility with Ember Data. AliasedProperty.prototype._meta = undefined; AliasedProperty.prototype.meta = ComputedProperty.prototype.meta; /** @module ember */ /** 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() { true && !false && (0, _debug.deprecate)(`Usage of \`${deprecatedKey}\` is deprecated, use \`${newKey}\` instead.`, false, options); } Object.defineProperty(object, deprecatedKey, { configurable: true, enumerable: false, set(value) { _deprecate(); set(this, newKey, value); }, get() { _deprecate(); return get(this, newKey); } }); } /** @module @ember/utils */ /** 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 isNone(); // true isNone(null); // true isNone(undefined); // true isNone(''); // false isNone([]); // false isNone(function() {}); // false ``` @method isNone @static @for @ember/utils @param {Object} obj Value to test @return {Boolean} @public */ function isNone(obj) { return obj === null || obj === undefined; } /** @module @ember/utils */ /** Verifies that a value is `null` or `undefined`, an empty string, or an empty array. Constrains the rules on `isNone` by returning true for empty strings and empty arrays. If the value is an object with a `size` property of type number, it is used to check emptiness. ```javascript isEmpty(); // true isEmpty(null); // true isEmpty(undefined); // true isEmpty(''); // true isEmpty([]); // true isEmpty({ size: 0}); // true isEmpty({}); // false isEmpty('Adam Hawkins'); // false isEmpty([0,1,2]); // false isEmpty('\n\t'); // false isEmpty(' '); // false isEmpty({ size: 1 }) // false isEmpty({ size: () => 0 }) // false ``` @method isEmpty @static @for @ember/utils @param {Object} obj Value to test @return {Boolean} @public */ function isEmpty(obj) { let none = obj === null || obj === undefined; if (none) { return none; } if (typeof obj.size === 'number') { return !obj.size; } let objectType = typeof obj; if (objectType === 'object') { let size = get(obj, 'size'); if (typeof size === 'number') { return !size; } } if (typeof obj.length === 'number' && objectType !== 'function') { return !obj.length; } if (objectType === 'object') { let length = get(obj, 'length'); if (typeof length === 'number') { return !length; } } return false; } /** @module @ember/utils */ /** A value is blank if it is empty or a whitespace string. ```javascript import { isBlank } from '@ember/utils'; isBlank(); // true isBlank(null); // true isBlank(undefined); // true isBlank(''); // true isBlank([]); // true isBlank('\n\t'); // true isBlank(' '); // true isBlank({}); // false isBlank('\n\t Hello'); // false isBlank('Hello world'); // false isBlank([1,2,3]); // false ``` @method isBlank @static @for @ember/utils @param {Object} obj Value to test @return {Boolean} @since 1.5.0 @public */ function isBlank(obj) { return isEmpty(obj) || typeof obj === 'string' && /\S/.test(obj) === false; } /** @module @ember/utils */ /** A value is present if it not `isBlank`. ```javascript isPresent(); // false isPresent(null); // false isPresent(undefined); // false isPresent(''); // false isPresent(' '); // false isPresent('\n\t'); // false isPresent([]); // false isPresent({ length: 0 }); // false isPresent(false); // true isPresent(true); // true isPresent('string'); // true isPresent(0); // true isPresent(function() {}); // true isPresent({}); // true isPresent('\n\t Hello'); // true isPresent([1, 2, 3]); // true ``` @method isPresent @static @for @ember/utils @param {Object} obj Value to test @return {Boolean} @since 1.8.0 @public */ function isPresent(obj) { return !isBlank(obj); } /** @module ember */ /** Helper class that allows you to register your library with Ember. Singleton created at `Ember.libraries`. @class Libraries @constructor @private */ class Libraries { constructor() { this._registry = []; this._coreLibIndex = 0; } _getLibraryByName(name) { let libs = this._registry; let count = libs.length; for (let i = 0; i < count; i++) { if (libs[i].name === name) { return libs[i]; } } return undefined; } register(name, version, isCoreLibrary) { let index = this._registry.length; if (!this._getLibraryByName(name)) { if (isCoreLibrary) { index = this._coreLibIndex++; } this._registry.splice(index, 0, { name, version }); } else { true && (0, _debug.warn)(`Library "${name}" is already registered with Ember.`, false, { id: 'ember-metal.libraries-register' }); } } registerCoreLibrary(name, version) { this.register(name, version, true); } deRegister(name) { let lib = this._getLibraryByName(name); let index; if (lib) { index = this._registry.indexOf(lib); this._registry.splice(index, 1); } } } if (false /* EMBER_LIBRARIES_ISREGISTERED */) { Libraries.prototype.isRegistered = function (name) { return !!this._getLibraryByName(name); }; } if (true /* DEBUG */) { Libraries.prototype.logVersions = function () { let libs = this._registry; let nameLengths = libs.map(item => get(item, 'name.length')); let maxNameLength = Math.max.apply(null, nameLengths); (0, _debug.debug)('-------------------------------'); for (let i = 0; i < libs.length; i++) { let lib = libs[i]; let spaces = new Array(maxNameLength - lib.name.length + 1).join(' '); (0, _debug.debug)([lib.name, spaces, ' : ', lib.version].join('')); } (0, _debug.debug)('-------------------------------'); }; } const LIBRARIES = new Libraries(); LIBRARIES.registerCoreLibrary('Ember', _version.default); /** @module @ember/object */ /** To get multiple properties at once, call `getProperties` with an object followed by a list of strings or an array: ```javascript import { getProperties } from '@ember/object'; getProperties(record, 'firstName', 'lastName', 'zipCode'); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` is equivalent to: ```javascript import { getProperties } from '@ember/object'; getProperties(record, ['firstName', 'lastName', 'zipCode']); // { firstName: 'John', lastName: 'Doe', zipCode: '10011' } ``` @method getProperties @static @for @ember/object @param {Object} obj @param {String...|Array} list of keys to get @return {Object} @public */ function getProperties(obj, keys) { let ret = {}; let propertyNames = arguments; let i = 1; if (arguments.length === 2 && Array.isArray(keys)) { i = 0; propertyNames = arguments[1]; } for (; i < propertyNames.length; i++) { ret[propertyNames[i]] = get(obj, propertyNames[i]); } return ret; } /** @module @ember/object */ /** 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 import EmberObject from '@ember/object'; let anObject = EmberObject.create(); anObject.setProperties({ firstName: 'Stanley', lastName: 'Stuart', age: 21 }); ``` @method setProperties @static @for @ember/object @param obj @param {Object} properties @return properties @public */ function setProperties(obj, properties) { if (properties === null || typeof properties !== 'object') { return properties; } changeProperties(() => { let props = Object.keys(properties); let propertyName; for (let i = 0; i < props.length; i++) { propertyName = props[i]; set(obj, propertyName, properties[propertyName]); } }); return properties; } // TODO, this only depends on context, otherwise it could be in utils // move into its own package // it is needed by Mixin for classToString // maybe move it into environment const hasOwnProperty = Object.prototype.hasOwnProperty; let searchDisabled = false; const flags = { _set: 0, _unprocessedNamespaces: false, get unprocessedNamespaces() { return this._unprocessedNamespaces; }, set unprocessedNamespaces(v) { this._set++; this._unprocessedNamespaces = v; } }; let unprocessedMixins = false; const NAMESPACES = []; const NAMESPACES_BY_ID = Object.create(null); function addNamespace(namespace) { flags.unprocessedNamespaces = true; NAMESPACES.push(namespace); } function removeNamespace(namespace) { let name = (0, _utils.getName)(namespace); delete NAMESPACES_BY_ID[name]; NAMESPACES.splice(NAMESPACES.indexOf(namespace), 1); if (name in _environment.context.lookup && namespace === _environment.context.lookup[name]) { _environment.context.lookup[name] = undefined; } } function findNamespaces() { if (!flags.unprocessedNamespaces) { return; } let lookup = _environment.context.lookup; let keys = Object.keys(lookup); for (let i = 0; i < keys.length; i++) { let key = keys[i]; // Only process entities that start with uppercase A-Z if (!isUppercase(key.charCodeAt(0))) { continue; } let obj = tryIsNamespace(lookup, key); if (obj) { (0, _utils.setName)(obj, key); } } } function findNamespace(name) { if (!searchDisabled) { processAllNamespaces(); } return NAMESPACES_BY_ID[name]; } function processNamespace(namespace) { _processNamespace([namespace.toString()], namespace, new Set()); } function processAllNamespaces() { let unprocessedNamespaces = flags.unprocessedNamespaces; if (unprocessedNamespaces) { findNamespaces(); flags.unprocessedNamespaces = false; } if (unprocessedNamespaces || unprocessedMixins) { let namespaces = NAMESPACES; for (let i = 0; i < namespaces.length; i++) { processNamespace(namespaces[i]); } unprocessedMixins = false; } } function classToString() { let name = (0, _utils.getName)(this); if (name !== void 0) { return name; } name = calculateToString(this); (0, _utils.setName)(this, name); return name; } function isSearchDisabled() { return searchDisabled; } function setSearchDisabled(flag) { searchDisabled = !!flag; } function setUnprocessedMixins() { unprocessedMixins = true; } function _processNamespace(paths, root, seen) { let idx = paths.length; let id = paths.join('.'); NAMESPACES_BY_ID[id] = root; (0, _utils.setName)(root, id); // Loop over all of the keys in the namespace, looking for classes for (let key in root) { if (!hasOwnProperty.call(root, key)) { continue; } let 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 && (0, _utils.getName)(obj) === void 0) { // Replace the class' `toString` with the dot-separated path (0, _utils.setName)(obj, paths.join('.')); // Support nested namespaces } else if (obj && obj.isNamespace) { // Skip aliased namespaces if (seen.has(obj)) { continue; } seen.add(obj); // Process the child namespace _processNamespace(paths, obj, seen); } } paths.length = idx; // cut out last item } function isUppercase(code) { return code >= 65 && code <= 90 // A ; // Z } function tryIsNamespace(lookup, prop) { try { let obj = lookup[prop]; return (obj !== null && typeof obj === 'object' || typeof obj === 'function') && obj.isNamespace && obj; } catch (e) { // continue } } function calculateToString(target) { let str; if (!searchDisabled) { processAllNamespaces(); str = (0, _utils.getName)(target); if (str !== void 0) { return str; } let superclass = target; do { superclass = Object.getPrototypeOf(superclass); if (superclass === Function.prototype || superclass === Object.prototype) { break; } str = (0, _utils.getName)(target); if (str !== void 0) { str = `(subclass of ${str})`; break; } } while (str === void 0); } return str || '(unknown)'; } /** @module @ember/object */ const a_concat = Array.prototype.concat; const { isArray } = Array; function isMethod(obj) { return 'function' === typeof obj && obj.isMethod !== false && obj !== Boolean && obj !== Object && obj !== Number && obj !== Array && obj !== Date && obj !== String; } const CONTINUE = {}; function mixinProperties(mixinsMeta, mixin) { if (mixin instanceof Mixin) { if (mixinsMeta.hasMixin(mixin)) { return CONTINUE; } mixinsMeta.addMixin(mixin); return mixin.properties; } else { return mixin; // apply anonymous mixin properties } } function concatenatedMixinProperties(concatProp, props, values, base) { // reset before adding each new mixin to pickup concats from previous let concats = values[concatProp] || base[concatProp]; if (props[concatProp]) { concats = concats ? a_concat.call(concats, props[concatProp]) : props[concatProp]; } return concats; } function giveDescriptorSuper(meta$$1, key, property, values, descs, base) { let superProperty; // 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) { superProperty = (0, _meta2.descriptorFor)(base, key, meta$$1); } if (superProperty === undefined || !(superProperty instanceof 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 = (0, _utils.wrap)(property._getter, superProperty._getter); if (superProperty._setter) { if (property._setter) { property._setter = (0, _utils.wrap)(property._setter, superProperty._setter); } else { property._setter = superProperty._setter; } } return property; } function giveMethodSuper(obj, key, method, values, descs) { // Methods overwrite computed properties, and do not call super to them. if (descs[key] !== undefined) { return method; } // Find the original method in a parent mixin let superMethod = values[key]; // If we didn't find the original value in a parent mixin, find it in // the original object if (superMethod === undefined && (0, _meta2.descriptorFor)(obj, key) === undefined) { superMethod = obj[key]; } // Only wrap the new method if the original method was a function if (typeof superMethod === 'function') { return (0, _utils.wrap)(method, superMethod); } return method; } function applyConcatenatedProperties(obj, key, value, values) { let baseValue = values[key] || obj[key]; let ret = (0, _utils.makeArray)(baseValue).concat((0, _utils.makeArray)(value)); if (true /* DEBUG */) { // it is possible to use concatenatedProperties with strings (which cannot be frozen) // only freeze objects... if (typeof ret === 'object' && ret !== null) { // prevent mutating `concatenatedProperties` array after it is applied Object.freeze(ret); } } return ret; } function applyMergedProperties(obj, key, value, values) { let baseValue = values[key] || obj[key]; true && !!isArray(value) && (0, _debug.assert)(`You passed in \`${JSON.stringify(value)}\` as the value for \`${key}\` but \`${key}\` cannot be an Array`, !isArray(value)); if (!baseValue) { return value; } let newBase = (0, _polyfills.assign)({}, baseValue); let hasFunction = false; for (let prop in value) { if (!value.hasOwnProperty(prop)) { continue; } let 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 = _utils.ROOT; } return newBase; } function addNormalizedProperty(base, key, value, meta$$1, descs, values, concats, mergings) { if (value instanceof Descriptor) { // Wrap descriptor function to implement // _super() if needed if (value._getter) { value = giveDescriptorSuper(meta$$1, 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) > -1) { 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, meta$$1, descs, values, base, keys) { let currentMixin, props, key, concats, mergings; function removeKeys(keyName) { delete descs[keyName]; delete values[keyName]; } for (let i = 0; i < mixins.length; i++) { currentMixin = mixins[i]; true && !(typeof currentMixin === 'object' && currentMixin !== null && Object.prototype.toString.call(currentMixin) !== '[object Array]') && (0, _debug.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(meta$$1, currentMixin); if (props === CONTINUE) { continue; } if (props) { // remove willMergeMixin after 3.4 as it was used for _actions 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$$1, 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, meta$$1, descs, values, base, keys); if (currentMixin._without) { currentMixin._without.forEach(removeKeys); } } } } function followAlias(obj, desc, descs, values) { let altKey = desc.methodName; let value; let possibleDesc; if (descs[altKey] || values[altKey]) { value = values[altKey]; desc = descs[altKey]; } else if ((possibleDesc = (0, _meta2.descriptorFor)(obj, altKey)) !== undefined) { desc = possibleDesc; value = undefined; } else { desc = undefined; value = obj[altKey]; } return { desc, value }; } function updateObserversAndListeners(obj, key, paths, updateMethod) { if (paths) { for (let i = 0; i < paths.length; i++) { updateMethod(obj, paths[i], null, key); } } } function replaceObserversAndListeners(obj, key, prev, next) { if (typeof prev === 'function') { updateObserversAndListeners(obj, key, (0, _utils.getObservers)(prev), removeObserver); updateObserversAndListeners(obj, key, (0, _utils.getListeners)(prev), removeListener); } if (typeof next === 'function') { updateObserversAndListeners(obj, key, (0, _utils.getObservers)(next), addObserver); updateObserversAndListeners(obj, key, (0, _utils.getListeners)(next), addListener); } } function applyMixin(obj, mixins) { let descs = {}; let values = {}; let meta$$1 = (0, _meta2.meta)(obj); let keys = []; let key, value, desc; obj._super = _utils.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, meta$$1, descs, values, obj, keys); for (let i = 0; i < keys.length; i++) { key = keys[i]; if (key === 'constructor' || !values.hasOwnProperty(key)) { continue; } desc = descs[key]; value = values[key]; while (desc && desc instanceof Alias) { let followed = followAlias(obj, desc, descs, values); desc = followed.desc; value = followed.value; } if (desc === undefined && value === undefined) { continue; } if ((0, _meta2.descriptorFor)(obj, key) !== undefined) { replaceObserversAndListeners(obj, key, null, value); } else { replaceObserversAndListeners(obj, key, obj[key], value); } defineProperty(obj, key, desc, value, meta$$1); } return obj; } /** @method mixin @param obj @param mixins* @return obj @private */ function mixin(obj, ...args) { applyMixin(obj, args); return obj; } /** The `Mixin` class allows you to create mixins, whose properties can be added to other classes. For instance, ```javascript import Mixin from '@ember/object/mixin'; const EditableMixin = Mixin.create({ edit() { console.log('starting to edit'); this.set('isEditing', true); }, isEditing: false }); ``` ```javascript import EmberObject from '@ember/object'; import EditableMixin from '../mixins/editable'; // Mix mixins into classes by passing them as the first arguments to // `.extend.` const Comment = EmberObject.extend(EditableMixin, { post: null }); let comment = Comment.create({ post: somePost }); comment.edit(); // outputs 'starting to edit' ``` Note that Mixins are created with `Mixin.create`, not `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 import Mixin from '@ember/object/mixin'; import { A } from '@ember/array'; const FilterableMixin = Mixin.create({ filters: A() }); ``` ```javascript import Mixin from '@ember/object/mixin'; import { A } from '@ember/array'; import { computed } from '@ember/object'; // filters will be a separate array for every object implementing the mixin const FilterableMixin = Mixin.create({ filters: computed(function() { return A(); }) }); ``` ```javascript import Mixin from '@ember/object/mixin'; import { A } from '@ember/array'; // filters will be created as a separate array during the object's initialization const Filterable = Mixin.create({ filters: null, init() { this._super(...arguments); this.set("filters", A()); } }); ``` @class Mixin @public */ class Mixin { constructor(mixins, properties) { this.properties = properties; this.mixins = buildMixinsArray(mixins); this.ownerConstructor = undefined; this._without = undefined; if (true /* DEBUG */) { this[_utils.NAME_KEY] = undefined; /* In debug builds, we seal mixins to help avoid performance pitfalls. In IE11 there is a quirk that prevents sealed objects from being added to a WeakMap. Unfortunately, the mixin system currently relies on weak maps in `guidFor`, so we need to prime the guid cache weak map. */ (0, _utils.guidFor)(this); Object.seal(this); } } /** @method create @for @ember/object/mixin @static @param arguments* @public */ static create(...args) { // ES6TODO: this relies on a global state? setUnprocessedMixins(); let M = this; return new M(args, undefined); } // returns the mixins currently applied to the specified object // TODO: Make `mixin` static mixins(obj) { let meta$$1 = (0, _meta2.peekMeta)(obj); let ret = []; if (meta$$1 === undefined) { return ret; } meta$$1.forEachMixins(currentMixin => { // skip primitive mixins since these are always anonymous if (!currentMixin.properties) { ret.push(currentMixin); } }); return ret; } /** @method reopen @param arguments* @private */ reopen(...args) { if (args.length === 0) { return; } if (this.properties) { let currentMixin = new Mixin(undefined, this.properties); this.properties = undefined; this.mixins = [currentMixin]; } else if (!this.mixins) { this.mixins = []; } this.mixins = this.mixins.concat(buildMixinsArray(args)); return this; } /** @method apply @param obj @return applied object @private */ apply(obj) { return applyMixin(obj, [this]); } applyPartial(obj) { return applyMixin(obj, [this]); } /** @method detect @param obj @return {Boolean} @private */ detect(obj) { if (typeof obj !== 'object' || obj === null) { return false; } if (obj instanceof Mixin) { return _detect(obj, this); } let meta$$1 = (0, _meta2.peekMeta)(obj); if (meta$$1 === undefined) { return false; } return meta$$1.hasMixin(this); } without(...args) { let ret = new Mixin([this]); ret._without = args; return ret; } keys() { return _keys(this); } toString() { return '(unknown mixin)'; } } function buildMixinsArray(mixins) { let length = mixins && mixins.length || 0; let m = undefined; if (length > 0) { m = new Array(length); for (let i = 0; i < length; i++) { let x = mixins[i]; true && !(typeof x === 'object' && x !== null && Object.prototype.toString.call(x) !== '[object Array]') && (0, _debug.assert)(`Expected hash or Mixin instance, got ${Object.prototype.toString.call(x)}`, typeof x === 'object' && x !== null && Object.prototype.toString.call(x) !== '[object Array]'); if (x instanceof Mixin) { m[i] = x; } else { m[i] = new Mixin(undefined, x); } } } return m; } Mixin.prototype.toString = classToString; if (true /* DEBUG */) { Mixin.prototype[_utils.NAME_KEY] = undefined; Object.seal(Mixin.prototype); } function _detect(curMixin, targetMixin, seen = new Set()) { if (seen.has(curMixin)) { return false; } seen.add(curMixin); if (curMixin === targetMixin) { return true; } let mixins = curMixin.mixins; if (mixins) { return mixins.some(mixin => _detect(mixin, targetMixin, seen)); } return false; } function _keys(mixin, ret = new Set(), seen = new Set()) { if (seen.has(mixin)) { return; } seen.add(mixin); if (mixin.properties) { let props = Object.keys(mixin.properties); for (let i = 0; i < props.length; i++) { ret.add(props[i]); } } else if (mixin.mixins) { mixin.mixins.forEach(x => _keys(x, ret, seen)); } return ret; } class Alias extends Descriptor { constructor(methodName) { super(); this.methodName = methodName; } teardown(_obj, _keyName, _meta) { throw new Error('Method not implemented.'); } get(_obj, _keyName) { throw new Error('Method not implemented.'); } set(_obj, _keyName, _value) { throw new Error('Method not implemented.'); } } /** Makes a method available via an additional name. ```app/utils/person.js import EmberObject, { aliasMethod } from '@ember/object'; export default EmberObject.extend({ name() { return 'Tomhuda Katzdale'; }, moniker: aliasMethod('name') }); ``` ```javascript let goodGuy = Person.create(); goodGuy.name(); // 'Tomhuda Katzdale' goodGuy.moniker(); // 'Tomhuda Katzdale' ``` @method aliasMethod @static @for @ember/object @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 import EmberObject from '@ember/object'; import { observer } from '@ember/object'; export default EmberObject.extend({ valueObserver: observer('value', function() { // Executes whenever the "value" property changes }) }); ``` Also available as `Function.prototype.observes` if prototype extensions are enabled. @method observer @for @ember/object @param {String} propertyNames* @param {Function} func @return func @public @static */ function observer(...args) { let func = args.pop(); let _paths = args; true && !(typeof func === 'function') && (0, _debug.assert)('observer called without a function', typeof func === 'function'); true && !(_paths.length > 0 && _paths.every(p => typeof p === 'string' && !!p.length)) && (0, _debug.assert)('observer called without valid path', _paths.length > 0 && _paths.every(p => typeof p === 'string' && !!p.length)); let paths = []; let addWatchedProperty = path => paths.push(path); for (let i = 0; i < _paths.length; ++i) { expandProperties(_paths[i], addWatchedProperty); } (0, _utils.setObservers)(func, paths); return func; } /** @module ember @private */ /** 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 */ class InjectedProperty extends ComputedProperty { constructor(type, name, options) { super(injectedPropertyGet); this.type = type; this.name = name; if (false /* EMBER_MODULE_UNIFICATION */) { this.source = options ? options.source : undefined; this.namespace = undefined; if (name) { let namespaceDelimiterOffset = name.indexOf('::'); if (namespaceDelimiterOffset === -1) { this.name = name; this.namespace = undefined; } else { this.name = name.slice(namespaceDelimiterOffset + 2); this.namespace = name.slice(0, namespaceDelimiterOffset); } } } } } function injectedPropertyGet(keyName) { let desc = (0, _meta2.descriptorFor)(this, keyName); let owner = (0, _owner.getOwner)(this) || this.container; // fallback to `container` for backwards compat true && !(desc && desc.type) && (0, _debug.assert)(`InjectedProperties should be defined with the inject computed property macros.`, desc && desc.type); true && !!!owner && (0, _debug.assert)(`Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container.`, !!owner); let specifier = `${desc.type}:${desc.name || keyName}`; return owner.lookup(specifier, { source: desc.source, namespace: desc.namespace }); } function descriptor(desc) { return new NativeDescriptor(desc); } /** A wrapper for a native ES5 descriptor. In an ideal world, we wouldn't need this at all, however, the way we currently flatten/merge our mixins require a special value to denote a descriptor. @class NativeDescriptor @private */ class NativeDescriptor extends Descriptor { constructor(desc) { super(); this.desc = desc; this.enumerable = desc.enumerable !== false; this.configurable = desc.configurable !== false; } setup(obj, key, meta$$1) { Object.defineProperty(obj, key, this.desc); meta$$1.writeDescriptors(key, this); } get(obj, key) { return obj[key]; } set(obj, key, value) { return obj[key] = value; } } exports.computed = computed; exports.ComputedProperty = ComputedProperty; exports._globalsComputed = _globalsComputed; exports.getCacheFor = getCacheFor; exports.getCachedValueFor = getCachedValueFor; exports.peekCacheFor = peekCacheFor; exports.alias = alias; exports.deprecateProperty = deprecateProperty; exports.PROXY_CONTENT = PROXY_CONTENT; exports._getPath = _getPath; exports.get = get; exports.getWithDefault = getWithDefault; exports.set = set; exports.trySet = trySet; exports.objectAt = objectAt; exports.replace = replace; exports.replaceInNativeArray = replaceInNativeArray; exports.addArrayObserver = addArrayObserver; exports.removeArrayObserver = removeArrayObserver; exports.arrayContentWillChange = arrayContentWillChange; exports.arrayContentDidChange = arrayContentDidChange; exports.eachProxyFor = eachProxyFor; exports.eachProxyArrayWillChange = eachProxyArrayWillChange; exports.eachProxyArrayDidChange = eachProxyArrayDidChange; exports.addListener = addListener; exports.hasListeners = hasListeners; exports.on = on; exports.removeListener = removeListener; exports.sendEvent = sendEvent; exports.isNone = isNone; exports.isEmpty = isEmpty; exports.isBlank = isBlank; exports.isPresent = isPresent; exports.beginPropertyChanges = beginPropertyChanges; exports.changeProperties = changeProperties; exports.endPropertyChanges = endPropertyChanges; exports.notifyPropertyChange = notifyPropertyChange; exports.overrideChains = overrideChains; exports.propertyDidChange = propertyDidChange; exports.propertyWillChange = propertyWillChange; exports.PROPERTY_DID_CHANGE = PROPERTY_DID_CHANGE$1; exports.defineProperty = defineProperty; exports.Descriptor = Descriptor; exports.watchKey = watchKey; exports.unwatchKey = unwatchKey; exports.ChainNode = ChainNode; exports.finishChains = finishChains; exports.removeChainWatcher = removeChainWatcher; exports.watchPath = watchPath; exports.unwatchPath = unwatchPath; exports.isWatching = isWatching; exports.unwatch = unwatch; exports.watch = watch; exports.watcherCount = watcherCount; exports.libraries = LIBRARIES; exports.Libraries = Libraries; exports.getProperties = getProperties; exports.setProperties = setProperties; exports.expandProperties = expandProperties; exports.addObserver = addObserver; exports.removeObserver = removeObserver; exports.Mixin = Mixin; exports.aliasMethod = aliasMethod; exports.mixin = mixin; exports.observer = observer; exports.applyMixin = applyMixin; exports.InjectedProperty = InjectedProperty; exports.setHasViews = setHasViews; exports.tagForProperty = tagForProperty; exports.tagFor = tagFor; exports.markObjectAsDirty = markObjectAsDirty; exports.runInTransaction = runInTransaction; exports.didRender = didRender; exports.assertNotRendered = assertNotRendered; exports.descriptor = descriptor; exports.tracked = tracked; exports.NAMESPACES = NAMESPACES; exports.NAMESPACES_BY_ID = NAMESPACES_BY_ID; exports.addNamespace = addNamespace; exports.classToString = classToString; exports.findNamespace = findNamespace; exports.findNamespaces = findNamespaces; exports.processNamespace = processNamespace; exports.processAllNamespaces = processAllNamespaces; exports.removeNamespace = removeNamespace; exports.isNamespaceSearchDisabled = isSearchDisabled; exports.setNamespaceSearchDisabled = setSearchDisabled; }); enifed('@ember/-internals/owner/index', ['exports', '@ember/-internals/utils'], function (exports, _utils) { 'use strict'; exports.OWNER = undefined; exports.getOwner = getOwner; exports.setOwner = setOwner; const OWNER = exports.OWNER = (0, _utils.symbol)('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 Component from '@ember/component'; import { computed } from '@ember/object'; import { getOwner } from '@ember/application'; // Usage: // // {{play-audio audioType=model.audioType audioFile=model.file}} // export default Component.extend({ audioService: computed('audioType', function() { let owner = getOwner(this); return owner.lookup(`service:${this.get('audioType')}`); }), click() { let player = this.get('audioService'); player.play(this.get('audioFile')); } }); ``` @method getOwner @static @for @ember/application @param {Object} object An object with an owner. @return {Object} An owner object. @since 2.3.0 @public */ /** @module @ember/application */ 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 @static @for @ember/application @param {Object} object An object instance. @param {Object} object The new owner object of the object instance. @since 2.3.0 @public */ function setOwner(object, owner) { object[OWNER] = owner; } }); enifed('@ember/-internals/routing/index', ['exports', '@ember/-internals/routing/lib/location/api', '@ember/-internals/routing/lib/location/none_location', '@ember/-internals/routing/lib/location/hash_location', '@ember/-internals/routing/lib/location/history_location', '@ember/-internals/routing/lib/location/auto_location', '@ember/-internals/routing/lib/system/generate_controller', '@ember/-internals/routing/lib/system/controller_for', '@ember/-internals/routing/lib/system/dsl', '@ember/-internals/routing/lib/system/router', '@ember/-internals/routing/lib/system/route', '@ember/-internals/routing/lib/system/query_params', '@ember/-internals/routing/lib/services/routing', '@ember/-internals/routing/lib/services/router', '@ember/-internals/routing/lib/system/cache', '@ember/-internals/routing/lib/ext/controller'], function (exports, _api, _none_location, _hash_location, _history_location, _auto_location, _generate_controller, _controller_for, _dsl, _router, _route, _query_params, _routing, _router2, _cache) { 'use strict'; exports.BucketCache = exports.RouterService = exports.RoutingService = exports.QueryParams = exports.Route = exports.Router = exports.RouterDSL = exports.controllerFor = exports.generateControllerFactory = exports.generateController = exports.AutoLocation = exports.HistoryLocation = exports.HashLocation = exports.NoneLocation = exports.Location = undefined; Object.defineProperty(exports, 'Location', { enumerable: true, get: function () { return _api.default; } }); Object.defineProperty(exports, 'NoneLocation', { enumerable: true, get: function () { return _none_location.default; } }); Object.defineProperty(exports, 'HashLocation', { enumerable: true, get: function () { return _hash_location.default; } }); Object.defineProperty(exports, 'HistoryLocation', { enumerable: true, get: function () { return _history_location.default; } }); Object.defineProperty(exports, 'AutoLocation', { enumerable: true, get: function () { return _auto_location.default; } }); Object.defineProperty(exports, 'generateController', { enumerable: true, get: function () { return _generate_controller.default; } }); Object.defineProperty(exports, 'generateControllerFactory', { enumerable: true, get: function () { return _generate_controller.generateControllerFactory; } }); Object.defineProperty(exports, 'controllerFor', { enumerable: true, get: function () { return _controller_for.default; } }); Object.defineProperty(exports, 'RouterDSL', { enumerable: true, get: function () { return _dsl.default; } }); Object.defineProperty(exports, 'Router', { enumerable: true, get: function () { return _router.default; } }); Object.defineProperty(exports, 'Route', { enumerable: true, get: function () { return _route.default; } }); Object.defineProperty(exports, 'QueryParams', { enumerable: true, get: function () { return _query_params.default; } }); Object.defineProperty(exports, 'RoutingService', { enumerable: true, get: function () { return _routing.default; } }); Object.defineProperty(exports, 'RouterService', { enumerable: true, get: function () { return _router2.default; } }); Object.defineProperty(exports, 'BucketCache', { enumerable: true, get: function () { return _cache.default; } }); }); enifed('@ember/-internals/routing/lib/ext/controller', ['exports', '@ember/-internals/metal', '@ember/controller/lib/controller_mixin', '@ember/-internals/routing/lib/utils'], function (exports, _metal, _controller_mixin, _utils) { 'use strict'; /** @module ember */ _controller_mixin.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`. By default, Ember coerces query parameter values using `toggleProperty`. This behavior may lead to unexpected results. To explicitly configure a query parameter property so it coerces as expected, you must define a type property: ```javascript queryParams: [{ category: { type: 'boolean' } }] ``` @for Ember.ControllerMixin @property queryParams @public */ queryParams: null, /** This property is updated to various different callback functions depending on the current "state" of the backing route. It is used by `Controller.prototype._qpChanged`. The methods backing each state can be found in the `Route.prototype._qp` computed property return value (the `.states` property). The current values are listed here for the sanity of future travelers: * `inactive` - This state is used when this controller instance is not part of the active route hierarchy. Set in `Route.prototype._reset` (a `router.js` microlib hook) and `Route.prototype.actions.finalizeQueryParamChange`. * `active` - This state is used when this controller instance is part of the active route hierarchy. Set in `Route.prototype.actions.finalizeQueryParamChange`. * `allowOverrides` - This state is used in `Route.prototype.setup` (`route.js` microlib hook). @method _qpDelegate @private */ _qpDelegate: null, /** During `Route#setup` observers are created to invoke this method when any of the query params declared in `Controller#queryParams` property are changed. When invoked this method uses the currently active query param update delegate (see `Controller.prototype._qpDelegate` for details) and invokes it with the QP key/value being changed. @method _qpChanged @private */ _qpChanged(controller, _prop) { let prop = _prop.substr(0, _prop.length - 3); let delegate = controller._qpDelegate; let value = (0, _metal.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. ```app/router.js Router.map(function() { this.route('blogPost', { path: ':blogPostId' }, function() { this.route('blogComment', { path: ':blogCommentId', resetNamespace: true }); }); }); ``` ```javascript 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/ember/release/classes/Ember.ControllerMixin/methods/replaceRoute?anchor=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(...args) { // target may be either another controller or a router let target = (0, _metal.get)(this, 'target'); let method = target.transitionToRoute || target.transitionTo; return method.apply(target, (0, _utils.prefixRouteNameArg)(this, args)); }, /** 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. ```app/router.js 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 @public */ replaceRoute(...args) { // target may be either another controller or a router let target = (0, _metal.get)(this, 'target'); let method = target.replaceRoute || target.replaceWith; return method.apply(target, (0, _utils.prefixRouteNameArg)(this, args)); } }); exports.default = _controller_mixin.default; }); enifed('@ember/-internals/routing/lib/location/api', ['exports', '@ember/-internals/browser-environment', '@ember/debug'], function (exports, _browserEnvironment, _debug) { 'use strict'; 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(options) { let implementation = options && options.implementation; true && !!!implementation && (0, _debug.assert)("Location.create: you must specify a 'implementation' option", !!implementation); let implementationClass = this.implementations[implementation]; true && !!!implementationClass && (0, _debug.assert)(`Location.create: ${implementation} is not a valid implementation`, !!implementationClass); return implementationClass.create(...arguments); }, implementations: {}, _location: _browserEnvironment.location }; }); enifed('@ember/-internals/routing/lib/location/auto_location', ['exports', '@ember/-internals/browser-environment', '@ember/-internals/metal', '@ember/-internals/owner', '@ember/-internals/runtime', '@ember/-internals/utils', '@ember/debug', '@ember/-internals/routing/lib/location/util'], function (exports, _browserEnvironment, _metal, _owner, _runtime, _utils, _debug, _util) { 'use strict'; exports.getHistoryPath = getHistoryPath; exports.getHashPath = getHashPath; /** @module @ember/routing */ /** 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. 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: ```app/router.js Router.map(function() { this.route('posts', function() { this.route('new'); }); }); 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. @class AutoLocation @static @protected */ class AutoLocation extends _runtime.Object { constructor() { super(...arguments); this.implementation = 'auto'; } /** 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() { let rootURL = this.rootURL; true && !(rootURL.charAt(rootURL.length - 1) === '/') && (0, _debug.assert)('rootURL must end with a trailing forward slash e.g. "/app/"', rootURL.charAt(rootURL.length - 1) === '/'); let implementation = detectImplementation({ location: this.location, history: this.history, userAgent: this.userAgent, rootURL, documentMode: this.documentMode, global: this.global }); if (implementation === false) { (0, _metal.set)(this, 'cancelRouterSetup', true); implementation = 'none'; } let concrete = (0, _owner.getOwner)(this).lookup(`location:${implementation}`); (0, _metal.set)(concrete, 'rootURL', rootURL); true && !!!concrete && (0, _debug.assert)(`Could not find location '${implementation}'.`, !!concrete); (0, _metal.set)(this, 'concreteImplementation', concrete); } willDestroy() { let concreteImplementation = (0, _metal.get)(this, 'concreteImplementation'); if (concreteImplementation) { concreteImplementation.destroy(); } } } exports.default = AutoLocation; AutoLocation.reopen({ /** @private Will be pre-pended to path upon state change. @since 1.5.1 @property rootURL @default '/' */ rootURL: '/', initState: delegateToConcreteImplementation('initState'), getURL: delegateToConcreteImplementation('getURL'), setURL: delegateToConcreteImplementation('setURL'), replaceURL: delegateToConcreteImplementation('replaceURL'), onUpdateURL: delegateToConcreteImplementation('onUpdateURL'), formatURL: delegateToConcreteImplementation('formatURL'), /** @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: _browserEnvironment.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: _browserEnvironment.history, /** @private The user agent's global variable. In browsers, this will be `window`. @since 1.11 @property global @default window */ global: _browserEnvironment.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: _browserEnvironment.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 }); function delegateToConcreteImplementation(methodName) { return function (...args) { let concreteImplementation = (0, _metal.get)(this, 'concreteImplementation'); true && !!!concreteImplementation && (0, _debug.assert)("AutoLocation's detect() method should be called before calling any other hooks.", !!concreteImplementation); return (0, _utils.tryInvoke)(concreteImplementation, methodName, args); }; } function detectImplementation(options) { let { location, userAgent, history, documentMode, global, rootURL } = options; let implementation = 'none'; let cancelRouterSetup = false; let currentPath = (0, _util.getFullPath)(location); if ((0, _util.supportsHistory)(userAgent, history)) { let 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) { implementation = 'history'; } else if (currentPath.substr(0, 2) === '/#') { history.replaceState({ path: historyPath }, undefined, historyPath); implementation = 'history'; } else { cancelRouterSetup = true; (0, _util.replacePath)(location, historyPath); } } else if ((0, _util.supportsHashChange)(documentMode, global)) { let 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; (0, _util.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) { let path = (0, _util.getPath)(location); let hash = (0, _util.getHash)(location); let query = (0, _util.getQuery)(location); let rootURLIndex = path.indexOf(rootURL); let routeHash, hashParts; true && !(rootURLIndex === 0) && (0, _debug.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.charAt(path.length - 1) === '/') { routeHash = routeHash.substr(1); } // This is the "expected" final order path += routeHash + query; if (hashParts.length) { path += `#${hashParts.join('#')}`; } } else { 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) { let path = rootURL; let historyPath = getHistoryPath(rootURL, location); let routePath = historyPath.substr(rootURL.length); if (routePath !== '') { if (routePath[0] !== '/') { routePath = `/${routePath}`; } path += `#${routePath}`; } return path; } }); enifed('@ember/-internals/routing/lib/location/hash_location', ['exports', '@ember/-internals/metal', '@ember/runloop', '@ember/-internals/runtime', '@ember/-internals/routing/lib/location/util'], function (exports, _metal, _runloop, _runtime, _util) { 'use strict'; /** @module @ember/routing */ /** `HashLocation` implements the location API using the browser's hash. At present, it relies on a `hashchange` event existing in the browser. 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. Example: ```app/router.js Router.map(function() { this.route('posts', function() { this.route('new'); }); }); Router.reopen({ location: 'hash' }); ``` This will result in a posts.new url of `/#/posts/new`. @class HashLocation @extends EmberObject @protected */ class HashLocation extends _runtime.Object { constructor() { super(...arguments); this.implementation = 'hash'; } init() { (0, _metal.set)(this, 'location', (0, _metal.get)(this, '_location') || window.location); this._hashchangeHandler = undefined; } /** @private Returns normalized location.hash @since 1.5.1 @method getHash */ getHash() { return (0, _util.getHash)((0, _metal.get)(this, 'location')); } /** 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() { let originalPath = this.getHash().substr(1); let outPath = originalPath; if (outPath[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(path) { (0, _metal.get)(this, 'location').hash = path; (0, _metal.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(path) { (0, _metal.get)(this, 'location').replace(`#${path}`); (0, _metal.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(callback) { this._removeEventListener(); this._hashchangeHandler = (0, _runloop.bind)(this, function () { let path = this.getURL(); if ((0, _metal.get)(this, 'lastSetURL') === path) { return; } (0, _metal.set)(this, 'lastSetURL', null); callback(path); }); window.addEventListener('hashchange', this._hashchangeHandler); } /** 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(url) { return `#${url}`; } /** Cleans up the HashLocation event listener. @private @method willDestroy */ willDestroy() { this._removeEventListener(); } _removeEventListener() { if (this._hashchangeHandler) { window.removeEventListener('hashchange', this._hashchangeHandler); } } } exports.default = HashLocation; }); enifed('@ember/-internals/routing/lib/location/history_location', ['exports', '@ember/-internals/metal', '@ember/-internals/runtime', '@ember/-internals/routing/lib/location/util'], function (exports, _metal, _runtime, _util) { 'use strict'; /** @module @ember/routing */ let popstateFired = false; function _uuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { let r, v; r = Math.random() * 16 | 0; v = c === 'x' ? r : r & 3 | 8; return v.toString(16); }); } /** HistoryLocation implements the location API using the browser's history.pushState API. Using `HistoryLocation` results in URLs that are indistinguishable from a standard URL. This relies upon the browser's `history` API. Example: ```app/router.js Router.map(function() { this.route('posts', function() { this.route('new'); }); }); 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. @class HistoryLocation @extends EmberObject @protected */ class HistoryLocation extends _runtime.Object { constructor() { super(...arguments); this.implementation = 'history'; /** Will be pre-pended to path upon state change @property rootURL @default '/' @private */ this.rootURL = '/'; } /** @private Returns normalized location.hash @method getHash */ getHash() { return (0, _util.getHash)((0, _metal.get)(this, 'location')); } init() { this._super(...arguments); let base = document.querySelector('base'); let baseURL = ''; if (base) { baseURL = base.getAttribute('href'); } (0, _metal.set)(this, 'baseURL', baseURL); (0, _metal.set)(this, 'location', (0, _metal.get)(this, 'location') || window.location); this._popstateHandler = undefined; } /** Used to set state on first call to setURL @private @method initState */ initState() { let history = (0, _metal.get)(this, 'history') || window.history; (0, _metal.set)(this, 'history', history); if (history && 'state' in history) { this.supportsHistory = true; } let state = this.getState(); let path = this.formatURL(this.getURL()); if (state && state.path === path) { // preserve existing state // used for webkit workaround, since there will be no initial popstate event this._previousURL = this.getURL(); } else { this.replaceState(path); } } /** Returns the current `location.pathname` without `rootURL` or `baseURL` @private @method getURL @return url {String} */ getURL() { let location = (0, _metal.get)(this, 'location'); let path = location.pathname; let rootURL = (0, _metal.get)(this, 'rootURL'); let baseURL = (0, _metal.get)(this, 'baseURL'); // remove trailing slashes if they exists rootURL = rootURL.replace(/\/$/, ''); baseURL = baseURL.replace(/\/$/, ''); // remove baseURL and rootURL from start of path let url = path.replace(new RegExp(`^${baseURL}(?=/|$)`), '').replace(new RegExp(`^${rootURL}(?=/|$)`), '').replace(/\/\/$/g, '/'); // remove extra slashes let search = location.search || ''; url += search + this.getHash(); return url; } /** Uses `history.pushState` to update the url without a page reload. @private @method setURL @param path {String} */ setURL(path) { let 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(path) { let 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. The object returned will contain a `path` for the given state as well as a unique state `id`. The state index will allow the app to distinguish between two states with similar paths but should be unique from one another. @private @method getState @return state {Object} */ getState() { if (this.supportsHistory) { return (0, _metal.get)(this, 'history').state; } return this._historyState; } /** Pushes a new state. @private @method pushState @param path {String} */ pushState(path) { let state = { path, uuid: _uuid() }; (0, _metal.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(path) { let state = { path, uuid: _uuid() }; (0, _metal.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(callback) { this._removeEventListener(); this._popstateHandler = () => { // Ignore initial page load popstate event in Chrome if (!popstateFired) { popstateFired = true; if (this.getURL() === this._previousURL) { return; } } callback(this.getURL()); }; window.addEventListener('popstate', this._popstateHandler); } /** Used when using `{{action}}` helper. The url is always appended to the rootURL. @private @method formatURL @param url {String} @return formatted url {String} */ formatURL(url) { let rootURL = (0, _metal.get)(this, 'rootURL'); let baseURL = (0, _metal.get)(this, 'baseURL'); if (url !== '') { // remove trailing slashes if they exists rootURL = rootURL.replace(/\/$/, ''); baseURL = baseURL.replace(/\/$/, ''); } else if (baseURL[0] === '/' && rootURL[0] === '/') { // 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() { this._removeEventListener(); } _removeEventListener() { if (this._popstateHandler) { window.removeEventListener('popstate', this._popstateHandler); } } } exports.default = HistoryLocation; }); enifed('@ember/-internals/routing/lib/location/none_location', ['exports', '@ember/-internals/metal', '@ember/-internals/runtime', '@ember/debug'], function (exports, _metal, _runtime, _debug) { 'use strict'; /** @module @ember/routing */ /** 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). 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()`. @class NoneLocation @extends EmberObject @protected */ class NoneLocation extends _runtime.Object { constructor() { super(...arguments); this.implementation = 'none'; } detect() { let rootURL = this.rootURL; true && !(rootURL.charAt(rootURL.length - 1) === '/') && (0, _debug.assert)('rootURL must end with a trailing forward slash e.g. "/app/"', rootURL.charAt(rootURL.length - 1) === '/'); } /** Returns the current path without `rootURL`. @private @method getURL @return {String} path */ getURL() { let path = (0, _metal.get)(this, 'path'); let rootURL = (0, _metal.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(path) { (0, _metal.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(callback) { this.updateCallback = callback; } /** Sets the path and calls the `updateURL` callback. @private @method handleURL @param url {String} */ handleURL(url) { (0, _metal.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(url) { let rootURL = (0, _metal.get)(this, 'rootURL'); if (url !== '') { // remove trailing slashes if they exists rootURL = rootURL.replace(/\/$/, ''); } return rootURL + url; } } exports.default = NoneLocation; NoneLocation.reopen({ path: '', /** Will be pre-pended to path. @private @property rootURL @default '/' */ rootURL: '/' }); }); enifed('@ember/-internals/routing/lib/location/util', ['exports'], function (exports) { '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; /** @private Returns the current `location.pathname`, normalized for IE inconsistencies. */ function getPath(location) { let pathname = location.pathname; // Various versions of IE/Opera don't always return a leading slash if (pathname[0] !== '/') { pathname = `/${pathname}`; } return pathname; } /** @private Returns the current `location.search`. */ function getQuery(location) { return location.search; } /** @private Returns the hash or empty string */ function getHash(location) { if (location.hash !== undefined) { return location.hash.substr(0); } return ''; } function getFullPath(location) { return getPath(location) + getQuery(location) + getHash(location); } function getOrigin(location) { let 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 global && '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/-internals/routing/lib/services/router', ['exports', '@ember/-internals/runtime', '@ember/debug', '@ember/object/computed', '@ember/service', '@ember/-internals/routing/lib/utils'], function (exports, _runtime, _debug, _computed, _service, _utils) { 'use strict'; let freezeRouteInfo; if (true /* DEBUG */) { freezeRouteInfo = transition => { if (transition.from !== null && !Object.isFrozen(transition.from)) { Object.freeze(transition.from); } if (transition.to !== null && !Object.isFrozen(transition.to)) { Object.freeze(transition.to); } }; } /** The Router service is the public API that provides access to the router. The immediate benefit of the Router service is that you can inject it into components, giving them a friendly way to initiate transitions and ask questions about the current global router state. In this example, the Router service is injected into a component to initiate a transition to a dedicated route: ```javascript import Component from '@ember/component'; import { inject as service } from '@ember/service'; export default Component.extend({ router: service(), actions: { next() { this.get('router').transitionTo('other.route'); } } }); ``` Like any service, it can also be injected into helpers, routes, etc. @public @class RouterService */ class RouterService extends _service.default { /** Transition the application into another route. The route may be either a single route or route path: See [transitionTo](/api/ember/release/classes/Route/methods/transitionTo?anchor=transitionTo) for more info. Calling `transitionTo` from the Router service will cause default query parameter values to be included in the URL. This behavior is different from calling `transitionTo` on a route or `transitionToRoute` on a controller. See the [Router Service RFC](https://github.com/emberjs/rfcs/blob/master/text/0095-router-service.md#query-parameter-semantics) for more info. @method transitionTo @param {String} routeNameOrUrl 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(...args) { if ((0, _utils.resemblesURL)(args[0])) { return this._router._doURLTransition('transitionTo', args[0]); } let { routeName, models, queryParams } = (0, _utils.extractRouteArgs)(args); let transition = this._router._doTransition(routeName, models, queryParams, true); transition['_keepDefaultQueryParamValues'] = true; return transition; } /** Transition into another route while replacing the current URL, if possible. The route may be either a single route or route path: See [replaceWith](/api/ember/release/classes/Route/methods/replaceWith?anchor=replaceWith) for more info. Calling `replaceWith` from the Router service will cause default query parameter values to be included in the URL. This behavior is different from calling `replaceWith` on a route. See the [Router Service RFC](https://github.com/emberjs/rfcs/blob/master/text/0095-router-service.md#query-parameter-semantics) for more info. @method replaceWith @param {String} routeNameOrUrl 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 */ replaceWith() /* routeNameOrUrl, ...models, options */{ return this.transitionTo(...arguments).method('replace'); } /** Generate a URL based on the supplied route name. @method urlFor @param {String} routeName the name of the route @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 {String} the string representing the generated URL @public */ urlFor(routeName, ...args) { return this._router.generate(routeName, ...args); } /** Determines whether a route is active. @method isActive @param {String} routeName the name of the route @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 {boolean} true if the provided routeName/models/queryParams are active @public */ isActive(...args) { let { routeName, models, queryParams } = (0, _utils.extractRouteArgs)(args); let routerMicrolib = this._router._routerMicrolib; if (!routerMicrolib.isActiveIntent(routeName, models)) { return false; } let hasQueryParams = Object.keys(queryParams).length > 0; if (hasQueryParams) { this._router._prepareQueryParams(routeName, models, queryParams, true /* fromRouterService */); return (0, _utils.shallowEqual)(queryParams, routerMicrolib.state.queryParams); } return true; } } exports.default = RouterService; RouterService.reopen({ /** Name of the current route. This property represents the logical name of the route, which is comma separated. For the following router: ```app/router.js Router.map(function() { this.route('about'); this.route('blog', function () { this.route('post', { path: ':post_id' }); }); }); ``` It will return: * `index` when you visit `/` * `about` when you visit `/about` * `blog.index` when you visit `/blog` * `blog.post` when you visit `/blog/some-post-id` @property currentRouteName @type String @public */ currentRouteName: (0, _computed.readOnly)('_router.currentRouteName'), /** Current URL for the application. This property represents the URL path for this route. For the following router: ```app/router.js Router.map(function() { this.route('about'); this.route('blog', function () { this.route('post', { path: ':post_id' }); }); }); ``` It will return: * `/` when you visit `/` * `/about` when you visit `/about` * `/blog` when you visit `/blog` * `/blog/some-post-id` when you visit `/blog/some-post-id` @property currentURL @type String @public */ currentURL: (0, _computed.readOnly)('_router.currentURL'), /** The `location` property determines the type of URL's that your application will use. The following location types are currently available: * `auto` * `hash` * `history` * `none` @property location @default 'hash' @see {Location} @public */ location: (0, _computed.readOnly)('_router.location'), /** The `rootURL` property represents the URL of the root of the application, '/' by default. This prefix is assumed on all routes defined on this app. IF you change the `rootURL` in your environment configuration like so: ```config/environment.js 'use strict'; module.exports = function(environment) { let ENV = { modulePrefix: 'router-service', environment, rootURL: '/my-root', … } ] ``` This property will return `/my-root`. @property rootURL @default '/' @public */ rootURL: (0, _computed.readOnly)('_router.rootURL') }); if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { RouterService.reopen(_runtime.Evented, { init() { this._super(...arguments); this._router.on('routeWillChange', transition => { if (true /* DEBUG */) { freezeRouteInfo(transition); } this.trigger('routeWillChange', transition); }); this._router.on('routeDidChange', transition => { if (true /* DEBUG */) { freezeRouteInfo(transition); } this.trigger('routeDidChange', transition); }); }, /** A RouteInfo that represents the current leaf route. It is guaranteed to change whenever a route transition happens (even when that transition only changes parameters and doesn't change the active route) @property currentRoute @type RouteInfo @category ember-routing-router-service @public */ currentRoute: (0, _computed.readOnly)('_router.currentRoute'), /** Takes a string URL and returns a `RouteInfo` for the leafmost route represented by the URL. Returns `null` if the URL is not recognized. This method expects to receive the actual URL as seen by the browser including the app's `rootURL`. @method recognize @param {String} url @category ember-routing-router-service @public */ recognize(url) { true && !(url.indexOf(this.rootURL) === 0) && (0, _debug.assert)(`You must pass a url that begins with the application's rootURL "${this.rootURL}"`, url.indexOf(this.rootURL) === 0); let internalURL = cleanURL(url, this.rootURL); return this._router._routerMicrolib.recognize(internalURL); }, /** Takes a string URL and returns a promise that resolves to a `RouteInfoWithAttributes` for the leafmost route represented by the URL. The promise rejects if the URL is not recognized or an unhandled exception is encountered. This method expects to receive the actual URL as seen by the browser including the app's `rootURL`. @method recognizeAndLoad @param {String} url @category ember-routing-router-service @public */ recognizeAndLoad(url) { true && !(url.indexOf(this.rootURL) === 0) && (0, _debug.assert)(`You must pass a url that begins with the application's rootURL "${this.rootURL}"`, url.indexOf(this.rootURL) === 0); let internalURL = cleanURL(url, this.rootURL); return this._router._routerMicrolib.recognizeAndLoad(internalURL); } }); function cleanURL(url, rootURL) { if (rootURL === '/') { return url; } return url.substr(rootURL.length, url.length); } } }); enifed('@ember/-internals/routing/lib/services/routing', ['exports', '@ember/-internals/metal', '@ember/object/computed', '@ember/polyfills', '@ember/service'], function (exports, _metal, _computed, _polyfills, _service) { 'use strict'; /** The Routing service is used by LinkComponent, and provides facilities for the component/view layer to interact with the router. This is a private service for internal usage only. For public usage, refer to the `Router` service. @private @class RoutingService */ /** @module ember */ class RoutingService extends _service.default { hasRoute(routeName) { return (0, _metal.get)(this, 'router').hasRoute(routeName); } transitionTo(routeName, models, queryParams, shouldReplace) { let router = (0, _metal.get)(this, 'router'); let transition = router._doTransition(routeName, models, queryParams); if (shouldReplace) { transition.method('replace'); } return transition; } normalizeQueryParams(routeName, models, queryParams) { (0, _metal.get)(this, 'router')._prepareQueryParams(routeName, models, queryParams); } generateURL(routeName, models, queryParams) { let router = (0, _metal.get)(this, 'router'); // return early when the router microlib is not present, which is the case for {{link-to}} in integration tests if (!router._routerMicrolib) { return; } let visibleQueryParams = {}; if (queryParams) { (0, _polyfills.assign)(visibleQueryParams, queryParams); this.normalizeQueryParams(routeName, models, visibleQueryParams); } return router.generate(routeName, ...models, { queryParams: visibleQueryParams }); } isActiveForRoute(contexts, queryParams, routeName, routerState, isCurrentWhenSpecified) { let router = (0, _metal.get)(this, 'router'); let handlers = router._routerMicrolib.recognizer.handlersFor(routeName); let leafName = handlers[handlers.length - 1].handler; let 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); } } exports.default = RoutingService; RoutingService.reopen({ targetState: (0, _computed.readOnly)('router.targetState'), currentState: (0, _computed.readOnly)('router.currentState'), currentRouteName: (0, _computed.readOnly)('router.currentRouteName'), currentPath: (0, _computed.readOnly)('router.currentPath') }); function numberOfContextsAcceptedByHandler(handlerName, handlerInfos) { let req = 0; for (let i = 0; i < handlerInfos.length; i++) { req += handlerInfos[i].names.length; if (handlerInfos[i].handler === handlerName) { break; } } return req; } }); enifed("@ember/-internals/routing/lib/system/cache", ["exports"], function (exports) { "use strict"; /** A two-tiered cache with support for fallback values when doing lookups. Uses "buckets" and then "keys" to cache values. @private @class BucketCache */ class BucketCache { constructor() { this.cache = new Map(); } has(bucketKey) { return this.cache.has(bucketKey); } stash(bucketKey, key, value) { let bucket = this.cache.get(bucketKey); if (bucket === undefined) { bucket = new Map(); this.cache.set(bucketKey, bucket); } bucket.set(key, value); } lookup(bucketKey, prop, defaultValue) { if (!this.has(bucketKey)) { return defaultValue; } let bucket = this.cache.get(bucketKey); if (bucket.has(prop)) { return bucket.get(prop); } else { return defaultValue; } } } exports.default = BucketCache; }); enifed("@ember/-internals/routing/lib/system/controller_for", ["exports"], function (exports) { "use strict"; exports.default = controllerFor; /** @module ember */ /** Finds a controller instance. @for Ember @method controllerFor @private */ function controllerFor(container, controllerName, lookupOptions) { return container.lookup(`controller:${controllerName}`, lookupOptions); } }); enifed('@ember/-internals/routing/lib/system/dsl', ['exports', '@ember/debug', '@ember/polyfills'], function (exports, _debug, _polyfills) { 'use strict'; let uuid = 0; class DSL { constructor(name = null, options) { this.explicitIndex = false; this.parent = name; this.enableLoadingSubstates = !!(options && options.enableLoadingSubstates); this.matches = []; this.options = options; } route(name, options = {}, callback) { let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`; if (arguments.length === 2 && typeof options === 'function') { callback = options; options = {}; } true && !(() => { if (options.overrideNameAssertion === true) { return true; } return ['basic', 'application'].indexOf(name) === -1; })() && (0, _debug.assert)(`'${name}' cannot be used as a route name.`, (() => { if (options.overrideNameAssertion === true) { return true; }return ['basic', 'application'].indexOf(name) === -1; })()); true && !(name.indexOf(':') === -1) && (0, _debug.assert)(`'${name}' is not a valid route name. It cannot contain a ':'. You may want to use the 'path' option instead.`, name.indexOf(':') === -1); if (this.enableLoadingSubstates) { createRoute(this, `${name}_loading`, { resetNamespace: options.resetNamespace }); createRoute(this, `${name}_error`, { resetNamespace: options.resetNamespace, path: dummyErrorRoute }); } if (callback) { let fullName = getFullName(this, name, options.resetNamespace); let 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(url, name, callback, serialize) { let parts = name.split('.'); if (this.options.engineInfo) { let localFullName = name.slice(this.options.engineInfo.fullName.length + 1); let routeInfo = (0, _polyfills.assign)({ 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); } generate() { let dslMatches = this.matches; if (!this.explicitIndex) { this.route('index', { path: '/' }); } return match => { for (let i = 0; i < dslMatches.length; i += 3) { match(dslMatches[i]).to(dslMatches[i + 1], dslMatches[i + 2]); } }; } mount(_name, options = {}) { let engineRouteMap = this.options.resolveRouteMap(_name); let name = _name; if (options.as) { name = options.as; } let fullName = getFullName(this, name, options.resetNamespace); let engineInfo = { name: _name, instanceId: uuid++, mountPoint: fullName, fullName }; let path = options.path; if (typeof path !== 'string') { path = `/${name}`; } let callback; let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`; if (engineRouteMap) { let shouldResetEngineInfo = false; let oldEngineInfo = this.options.engineInfo; if (oldEngineInfo) { shouldResetEngineInfo = true; this.options.engineInfo = engineInfo; } let optionsForChild = (0, _polyfills.assign)({ engineInfo }, this.options); let childDSL = new DSL(fullName, optionsForChild); createRoute(childDSL, 'loading'); createRoute(childDSL, 'error', { path: dummyErrorRoute }); engineRouteMap.class.call(childDSL); callback = childDSL.generate(); if (shouldResetEngineInfo) { this.options.engineInfo = oldEngineInfo; } } let localFullName = 'application'; let routeInfo = (0, _polyfills.assign)({ localFullName }, engineInfo); if (this.enableLoadingSubstates) { // These values are important to register the loading routes under their // proper names for the Router and within the Engine's registry. let substateName = `${name}_loading`; let localFullName = `application_loading`; let routeInfo = (0, _polyfills.assign)({ localFullName }, engineInfo); createRoute(this, substateName, { resetNamespace: options.resetNamespace }); this.options.addRouteForEngine(substateName, routeInfo); substateName = `${name}_error`; localFullName = `application_error`; routeInfo = (0, _polyfills.assign)({ localFullName }, engineInfo); createRoute(this, substateName, { resetNamespace: options.resetNamespace, path: dummyErrorRoute }); this.options.addRouteForEngine(substateName, routeInfo); } this.options.addRouteForEngine(fullName, routeInfo); this.push(path, fullName, callback); } } exports.default = DSL; function canNest(dsl) { return 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) { let fullName = getFullName(dsl, name, options.resetNamespace); if (typeof options.path !== 'string') { options.path = `/${name}`; } dsl.push(options.path, fullName, callback, options.serialize); } }); enifed("@ember/-internals/routing/lib/system/engines", [], function () { "use strict"; }); enifed('@ember/-internals/routing/lib/system/generate_controller', ['exports', '@ember/-internals/metal', '@ember/debug'], function (exports, _metal, _debug) { 'use strict'; exports.generateControllerFactory = generateControllerFactory; exports.default = generateController; /** @module ember */ /** Generates a controller factory @for Ember @method generateControllerFactory @private */ function generateControllerFactory(owner, controllerName) { let Factory = owner.factoryFor('controller:basic').class; Factory = Factory.extend({ toString() { return `(generated ${controllerName} controller)`; } }); let fullName = `controller:${controllerName}`; owner.register(fullName, Factory); return Factory; } /** Generates and instantiates a controller extending from `controller:basic` if present, or `Controller` if not. @for Ember @method generateController @private @since 1.3.0 */ function generateController(owner, controllerName) { generateControllerFactory(owner, controllerName); let fullName = `controller:${controllerName}`; let instance = owner.lookup(fullName); if (true /* DEBUG */) { if ((0, _metal.get)(instance, 'namespace.LOG_ACTIVE_GENERATION')) { (0, _debug.info)(`generated -> ${fullName}`, { fullName }); } } return instance; } }); enifed("@ember/-internals/routing/lib/system/query_params", ["exports"], function (exports) { "use strict"; class QueryParams { constructor(values = null) { this.isQueryParams = true; this.values = values; } } exports.default = QueryParams; }); enifed("@ember/-internals/routing/lib/system/route-info", [], function () { "use strict"; /** A `RouteInfoWithAttributes` is an object that contains metadata, including the resolved value from the routes `model` hook. Like `RouteInfo`, a `RouteInfoWithAttributes` represents a specific route with in a Transition. It is read-only and internally immutable. It is also not observable, because a Transition instance is never changed after creation. @class RouteInfoWithAttributes @category ember-routing-router-service @public */ /** The dot-separated, fully-qualified name of the route, like "people.index". @property {String} name @category ember-routing-router-service @public */ /** The final segment of the fully-qualified name of the route, like "index" @property {String} localName @category ember-routing-router-service @public */ /** The values of the route's parametes. These are the same params that are recieved as arguments to the route's model hook. Contains only the parameters valid for this route, if any (params for parent or child routes are not merged). @property {Object} params @category ember-routing-router-service @public */ /** The ordered list of the names of the params required for this route. It will contain the same strings as Object.keys(params), but here the order is significant. This allows users to correctly pass params into routes programmatically. @property {Array} paramNames @category ember-routing-router-service @public */ /** The values of any queryParams on this route. @property {Object} queryParams @category ember-routing-router-service @public */ /** This is the resolved return value from the route's model hook. @property {Object|Array|String} attributes @category ember-routing-router-service @public */ /** A reference to the parent route's RouteInfo. This can be used to traverse upward to the topmost `RouteInfo`. @property {RouteInfo|null} parent @category ember-routing-router-service @public */ /** A reference to the child route's RouteInfo. This can be used to traverse downward to the leafmost `RouteInfo`. @property {RouteInfo|null} child @category ember-routing-router-service @public Allows you to traverse through the linked list of `RouteInfo`s from the topmost to leafmost. Returns the first `RouteInfo` in the linked list for which the callback returns true. This method is similar to the `find()` method defined in ECMAScript 2015. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, array); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `array` is the array 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. @method find @param {Function} callback the callback to execute @param {Object} [target*] optional target to use @returns {Object} Found item or undefined @category ember-routing-router-service @public */ /** A RouteInfo is an object that contains metadata about a specific route with in a Transition. It is read-only and internally immutable. It is also not observable, because a Transition instance is never changed after creation. @class RouteInfo @category ember-routing-router-service @public */ /** The dot-separated, fully-qualified name of the route, like "people.index". @property {String} name @category ember-routing-router-service @public */ /** The final segment of the fully-qualified name of the route, like "index" @property {String} localName @category ember-routing-router-service @public */ /** The values of the route's parametes. These are the same params that are recieved as arguments to the route's model hook. Contains only the parameters valid for this route, if any (params for parent or child routes are not merged). @property {Object} params @category ember-routing-router-service @public */ /** The ordered list of the names of the params required for this route. It will contain the same strings as Object.keys(params), but here the order is significant. This allows users to correctly pass params into routes programmatically. @property {Array} paramNames @category ember-routing-router-service @public */ /** The values of any queryParams on this route. @property {Object} queryParams @category ember-routing-router-service @public */ /** A reference to the parent route's RouteInfo. This can be used to traverse upward to the topmost `RouteInfo`. @property {RouteInfo|null} parent @category ember-routing-router-service @public */ /** A reference to the child route's RouteInfo. This can be used to traverse downward to the leafmost `RouteInfo`. @property {RouteInfo|null} child @category ember-routing-router-service @public Allows you to traverse through the linked list of `RouteInfo`s from the topmost to leafmost. Returns the first `RouteInfo` in the linked list for which the callback returns true. This method is similar to the `find()` method defined in ECMAScript 2015. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, array); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `array` is the array 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. @method find @param {Function} callback the callback to execute @param {Object} [target*] optional target to use @returns {Object} Found item or undefined @category ember-routing-router-service @public */ }); enifed('@ember/-internals/routing/lib/system/route', ['exports', '@ember/-internals/metal', '@ember/-internals/owner', '@ember/-internals/runtime', '@ember/debug', '@ember/deprecated-features', '@ember/polyfills', '@ember/runloop', '@ember/string', 'router_js', '@ember/-internals/routing/lib/utils', '@ember/-internals/routing/lib/system/generate_controller'], function (exports, _metal, _owner, _runtime, _debug, _deprecatedFeatures, _polyfills, _runloop, _string, _router_js, _utils, _generate_controller) { 'use strict'; exports.ROUTER_EVENT_DEPRECATIONS = undefined; exports.defaultSerialize = defaultSerialize; exports.hasDefaultSerialize = hasDefaultSerialize; function defaultSerialize(model, params) { if (params.length < 1 || !model) { return; } let object = {}; if (params.length === 1) { let [name] = params; if (name in model) { object[name] = (0, _metal.get)(model, name); } else if (/_id$/.test(name)) { object[name] = (0, _metal.get)(model, 'id'); } } else { object = (0, _metal.getProperties)(model, params); } return object; } function hasDefaultSerialize(route) { return route.serialize === defaultSerialize; } /** @module @ember/routing */ /** The `Route` class is used to define individual routes. Refer to the [routing guide](https://guides.emberjs.com/release/routing/) for documentation. @class Route @extends EmberObject @uses ActionHandler @uses Evented @since 1.0.0 @public */ class Route extends _runtime.Object { constructor() { super(...arguments); this.context = {}; } /** The name of the route, dot-delimited. For example, a route found at `app/routes/posts/post.js` will have a `routeName` of `posts.post`. @property routeName @for Route @type String @since 1.0.0 @public */ /** The name of the route, dot-delimited, including the engine prefix if applicable. For example, a route found at `addon/routes/posts/post.js` within an engine named `admin` will have a `fullRouteName` of `admin.posts.post`. @property fullRouteName @for Route @type String @since 2.10.0 @public */ /** Sets the name for this route, including a fully resolved name for routes inside engines. @private @method _setRouteName @param {String} name */ _setRouteName(name) { this.routeName = name; this.fullRouteName = getEngineRouteName((0, _owner.getOwner)(this), name); } /** @private @method _stashNames */ _stashNames(routeInfo, dynamicParent) { if (this._names) { return; } let names = this._names = routeInfo['_names']; if (!names.length) { routeInfo = dynamicParent; names = routeInfo && routeInfo['_names'] || []; } let qps = (0, _metal.get)(this, '_qp.qps'); let namePaths = new Array(names.length); for (let a = 0; a < names.length; ++a) { namePaths[a] = `${routeInfo.name}.${names[a]}`; } for (let i = 0; i < qps.length; ++i) { let qp = qps[i]; if (qp.scope === 'model') { qp.parts = namePaths; } } } /** @private @property _activeQPChanged */ _activeQPChanged(qp, value) { this._router._activeQPChanged(qp.scopedPropertyName, value); } /** @private @method _updatingQPChanged */ _updatingQPChanged(qp) { this._router._updatingQPChanged(qp.urlKey); } /** Returns a hash containing the parameters of an ancestor route. Example ```app/router.js // ... Router.map(function() { this.route('member', { path: ':name' }, function() { this.route('interest', { path: ':interest' }); }); }); ``` ```app/routes/member.js import Route from '@ember/routing/route'; export default Route.extend({ queryParams: { memberQp: { refreshModel: true } } }); ``` ```app/routes/member/interest.js import Route from '@ember/routing/route'; export default Route.extend({ queryParams: { interestQp: { refreshModel: true } }, model() { return this.paramsFor('member'); } }); ``` If we visit `/turing/maths?memberQp=member&interestQp=interest` the model for the `member.interest` route is a hash with: * `name`: `turing` * `memberQp`: `member` @method paramsFor @param {String} name @return {Object} hash containing the parameters of the route `name` @since 1.4.0 @public */ paramsFor(name) { let route = (0, _owner.getOwner)(this).lookup(`route:${name}`); if (!route) { return {}; } let transition = this._router._routerMicrolib.activeTransition; let state = transition ? transition[_router_js.STATE_SYMBOL] : this._router._routerMicrolib.state; let fullName = route.fullRouteName; let params = (0, _polyfills.assign)({}, state.params[fullName]); let queryParams = getQueryParamsFor(route, state); return Object.keys(queryParams).reduce((params, key) => { true && !!params[key] && (0, _debug.assert)(`The route '${this.routeName}' has both a dynamic segment and query param with name '${key}'. Please rename one to avoid collisions.`, !params[key]); params[key] = queryParams[key]; return params; }, params); } /** Serializes the query parameter key @method serializeQueryParamKey @param {String} controllerPropertyName @private */ serializeQueryParamKey(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(value, _urlKey, defaultValueType) { // urlKey isn't used here, but anyone overriding // can use it to provide serialization specific // to a certain query param. return this._router._serializeQueryParam(value, defaultValueType); } /** Deserializes value of the query parameter based on defaultValueType @method deserializeQueryParam @param {Object} value @param {String} urlKey @param {String} defaultValueType @private */ deserializeQueryParam(value, _urlKey, defaultValueType) { // urlKey isn't used here, but anyone overriding // can use it to provide deserialization specific // to a certain query param. return this._router._deserializeQueryParam(value, defaultValueType); } /** @private @property _optionsForQueryParam */ _optionsForQueryParam(qp) { return (0, _metal.get)(this, `queryParams.${qp.urlKey}`) || (0, _metal.get)(this, `queryParams.${qp.prop}`) || {}; } /** A hook you can use to reset controller values either when the model changes or the route is exiting. ```app/routes/articles.js import Route from '@ember/routing/route'; export default Route.extend({ resetController(controller, isExiting, transition) { if (isExiting && transition.targetName !== 'error') { controller.set('page', 1); } } }); ``` @method resetController @param {Controller} controller instance @param {Boolean} isExiting @param {Object} transition @since 1.7.0 @public */ resetController(_controller, _isExiting, _transition) { return this; } /** @private @method exit */ exit() { this.deactivate(); this.trigger('deactivate'); this.teardownViews(); } /** @private @method _internalReset @since 3.6.0 */ _internalReset(isExiting, transition) { let controller = this.controller; controller._qpDelegate = (0, _metal.get)(this, '_qp.states.inactive'); this.resetController(controller, isExiting, transition); } /** @private @method enter */ enter() { this.connections = []; this.activate(); this.trigger('activate'); } /** 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: ```app/routes/contact-form.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { willTransition(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 @since 1.0.0 @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. ```app/routes/login.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { didTransition() { 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. ```app/routes/application.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { loading(transition, route) { let controller = this.controllerFor('foo'); controller.set('currentlyLoading', true); transition.finally(function() { controller.set('currentlyLoading', false); }); } } }); ``` @event loading @param {Transition} transition @param {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: ```app/routes/admin.js import { reject } from 'rsvp'; import Route from '@ember/routing/route'; export default Route.extend({ beforeModel() { return reject('bad things!'); }, actions: { error(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`: ```app/routes/application.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { error(error, transition) { this.controllerFor('banner').displayError(error.message); } } }); ``` @event error @param {Error} error @param {Transition} transition @since 1.0.0 @public */ /** This event is triggered when the router enters the route. It is not executed when the model for the route changes. ```app/routes/application.js import { on } from '@ember/object/evented'; import Route from '@ember/routing/route'; export default Route.extend({ collectAnalytics: on('activate', function(){ collectAnalytics(); }) }); ``` @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. ```app/routes/index.js import { on } from '@ember/object/evented'; import Route from '@ember/routing/route'; export default Route.extend({ trackPageLeaveAnalytics: on('deactivate', function(){ trackPageLeaveAnalytics(); }) }); ``` @event deactivate @since 1.9.0 @public */ /** This hook is executed when the router completely exits this route. It is not executed when the model for the route changes. @method deactivate @since 1.0.0 @public */ deactivate() {} /** This hook is executed when the router enters the route. It is not executed when the model for the route changes. @method activate @since 1.0.0 @public */ activate() {} /** 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. ```app/routes.js // ... Router.map(function() { this.route('blogPost', { path:':blogPostId' }, function() { this.route('blogComment', { path: ':blogCommentId' }); }); }); export default Router; ``` ```javascript 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 ```app/routes.js // ... Router.map(function() { this.route('index'); this.route('secret'); this.route('fourOhFour', { path: '*:' }); }); export default Router; ``` ```app/routes/index.js import Route from '@ember/routing/route'; export Route.extend({ actions: { moveToSecret(context) { if (authorized()) { this.transitionTo('secret', context); } else { this.transitionTo('fourOhFour'); } } } }); ``` Transition to a nested route ```app/router.js // ... Router.map(function() { this.route('articles', { path: '/articles' }, function() { this.route('new'); }); }); export default Router; ``` ```app/routes/index.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { transitionToNewArticle() { this.transitionTo('articles.new'); } } }); ``` Multiple Models Example ```app/router.js // ... Router.map(function() { this.route('index'); this.route('breakfast', { path: ':breakfastId' }, function() { this.route('cereal', { path: ':cerealId' }); }); }); export default Router; ``` ```app/routes/index.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { moveToChocolateCereal() { let cereal = { cerealId: 'ChocolateYumminess' }; let breakfast = { breakfastId: 'CerealAndMilk' }; this.transitionTo('breakfast.cereal', breakfast, cereal); } } }); ``` Nested Route with Query String Example ```app/routes.js // ... Router.map(function() { this.route('fruits', function() { this.route('apples'); }); }); export default Router; ``` ```app/routes/index.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { transitionToApples() { 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 @since 1.0.0 @public */ transitionTo(...args) { // eslint-disable-line no-unused-vars return this._router.transitionTo(...(0, _utils.prefixRouteNameArg)(this, args)); } /** 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(...args) { let [name, ...preparedArgs] = (0, _utils.prefixRouteNameArg)(this, args); this._router.intermediateTransitionTo(name, ...preparedArgs); } /** 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() { return this._router._routerMicrolib.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 ```app/router.js // ... Router.map(function() { this.route('index'); this.route('secret'); }); export default Router; ``` ```app/routes/secret.js import Route from '@ember/routing/route'; export default Route.extend({ afterModel() { 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. @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 @since 1.0.0 @public */ replaceWith(...args) { return this._router.replaceWith(...(0, _utils.prefixRouteNameArg)(this, args)); } /** This hook is the entry point for router.js @private @method setup */ setup(context, transition) { let controller; let controllerName = this.controllerName || this.routeName; let definedController = this.controllerFor(controllerName, true); if (definedController) { controller = definedController; } else { controller = this.generateController(controllerName); } // Assign the route's controller so that it can more easily be // referenced in action handlers. Side effects. Side effects everywhere. if (!this.controller) { let qp = (0, _metal.get)(this, '_qp'); let propNames = qp !== undefined ? (0, _metal.get)(qp, 'propertyNames') : []; addQueryParamsObservers(controller, propNames); this.controller = controller; } let queryParams = (0, _metal.get)(this, '_qp'); let states = queryParams.states; controller._qpDelegate = states.allowOverrides; if (transition) { // Update the model dep values used to calculate cache keys. (0, _utils.stashParamNames)(this._router, transition[_router_js.STATE_SYMBOL].routeInfos); let cache = this._bucketCache; let params = transition[_router_js.PARAMS_SYMBOL]; let allParams = queryParams.propertyNames; allParams.forEach(prop => { let aQp = queryParams.map[prop]; aQp.values = params; let cacheKey = (0, _utils.calculateCacheKey)(aQp.route.fullRouteName, aQp.parts, aQp.values); let value = cache.lookup(cacheKey, prop, aQp.undecoratedDefaultValue); (0, _metal.set)(controller, prop, value); }); let qpValues = getQueryParamsFor(this, transition[_router_js.STATE_SYMBOL]); (0, _metal.setProperties)(controller, qpValues); } this.setupController(controller, context, transition); if (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(prop, value, qp) { if (!qp) { return; } // Update model-dep cache let cache = this._bucketCache; let cacheKey = (0, _utils.calculateCacheKey)(qp.route.fullRouteName, qp.parts, qp.values); 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. @method beforeModel @param {Transition} transition @return {any | 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. @since 1.0.0 @public */ beforeModel() {} /** 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. ```app/routes/posts.js import Route from '@ember/routing/route'; export default Route.extend({ afterModel(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 {any | 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. @since 1.0.0 @public */ afterModel() {} /** 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 @since 1.0.0 @public */ redirect() {} /** Called when the context is changed by router.js. @private @method contextDidChange */ contextDidChange() { this.currentModel = this.context; } /** A hook you can implement to convert the URL into the model for this route. ```app/router.js // ... Router.map(function() { this.route('post', { path: '/posts/:post_id' }); }); export default Router; ``` 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 `Route`. Example ```app/routes/post.js import Route from '@ember/routing/route'; export default Route.extend({ model(params) { return this.store.findRecord('post', params.post_id); } }); ``` @method model @param {Object} params the parameters extracted from the URL @param {Transition} transition @return {any | 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. @since 1.0.0 @public */ model(params, transition) { let name, sawParams, value; let queryParams = (0, _metal.get)(this, '_qp.map'); for (let prop in params) { if (prop === 'queryParams' || queryParams && prop in queryParams) { continue; } let match = prop.match(/^(.*)_id$/); if (match !== null) { name = match[1]; value = params[prop]; } sawParams = true; } if (!name) { if (sawParams) { return Object.assign({}, params); } else { if (transition.resolveIndex < 1) { return; } return transition[_router_js.STATE_SYMBOL].routeInfos[transition.resolveIndex - 1].context; } } return this.findModel(name, value); } /** @private @method deserialize @param {Object} params the parameters extracted from the URL @param {Transition} transition @return {any | Promise} the model for this route. Router.js hook. */ deserialize(_params, transition) { if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { return this.model(this._paramsFor(this.routeName, _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(...args) { return (0, _metal.get)(this, 'store').find(...args); } /** 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 specified `model` when it is not `undefined`. 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`: ```app/routes/photos.js import Route from '@ember/routing/route'; export default Route.extend({ model() { return this.store.findAll('photo'); }, setupController(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: ```app/router.js // ... Router.map(function() { this.route('post', { path: '/posts/:post_id' }); }); export default Router; ``` For the `post` route, a controller named `App.PostController` would be used if it is defined. If it is not defined, a basic `Controller` instance would be used. Example ```app/routes/post.js import Route from '@ember/routing/route'; export default Route.extend({ setupController(controller, model) { controller.set('model', model); } }); ``` @method setupController @param {Controller} controller instance @param {Object} model @since 1.0.0 @public */ setupController(controller, context, _transition) { // eslint-disable-line no-unused-vars if (controller && context !== undefined) { (0, _metal.set)(controller, 'model', context); } } /** Returns the controller of the current route, or a parent (or any ancestor) route in a route hierarchy. The controller instance must already have been created, either through entering the associated route or using `generateController`. ```app/routes/post.js import Route from '@ember/routing/route'; export default Route.extend({ setupController(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 {Controller} @since 1.0.0 @public */ controllerFor(name, _skipAssert) { let owner = (0, _owner.getOwner)(this); let route = owner.lookup(`route:${name}`); let controller; 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. true && !(!!controller || _skipAssert === true) && (0, _debug.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 ```app/routes/post.js import Route from '@ember/routing/route'; export default Route.extend({ setupController(controller, post) { this._super(controller, post); this.generateController('posts'); } }); ``` @method generateController @param {String} name the name of the controller @private */ generateController(name) { let owner = (0, _owner.getOwner)(this); return (0, _generate_controller.default)(owner, name); } /** 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 ```app/router.js // ... Router.map(function() { this.route('post', { path: '/posts/:post_id' }, function() { this.route('comments'); }); }); export default Router; ``` ```app/routes/post/comments.js import Route from '@ember/routing/route'; export default Route.extend({ model() { let post = this.modelFor('post'); return post.get('comments'); } }); ``` @method modelFor @param {String} name the name of the route @return {Object} the model object @since 1.0.0 @public */ modelFor(_name) { let name; let owner = (0, _owner.getOwner)(this); let transition = this._router && this._router._routerMicrolib ? this._router._routerMicrolib.activeTransition : undefined; // Only change the route name when there is an active transition. // Otherwise, use the passed in route name. if (owner.routable && transition !== undefined) { name = getEngineRouteName(owner, _name); } else { name = _name; } let route = owner.lookup(`route:${name}`); // If we are mid-transition, we want to try and look up // resolved parent contexts on the current transitionEvent. if (transition !== undefined && transition !== null) { let 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. ```app/routes/posts.js import Route from '@ember/routing/route'; export default Route.extend({ renderTemplate(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 @since 1.0.0 @public */ renderTemplate(_controller, _model) { // eslint-disable-line no-unused-vars 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: ```app/router.js // ... Router.map(function() { this.route('photos'); }); export default Router; ``` ```handlebars
{{outlet "anOutletName"}}
``` ```handlebars

Photos

``` You can render `photos.hbs` into the `"anOutletName"` outlet of `application.hbs` by calling `render`: ```app/routes/post.js import Route from '@ember/routing/route'; export default Route.extend({ renderTemplate() { 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. ```app/routes/posts.js import Route from '@ember/routing/route'; export default Route.extend({ renderTemplate(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.into` 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 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: ```app/router.js // ... Router.map(function() { this.route('index'); this.route('post', { path: '/posts/:post_id' }); }); export default Router; ``` ```app/routes/post.js import Route from '@ember/routing/route'; export default Route.extend({ renderTemplate() { this.render(); // all defaults apply } }); ``` The name of the route, 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.into` 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 @since 1.0.0 @public */ render(_name, options) { let name; let isDefaultRender = arguments.length === 0; if (!isDefaultRender) { if (typeof _name === 'object' && !options) { name = this.templateName || this.routeName; options = _name; } else { true && !!(0, _metal.isEmpty)(_name) && (0, _debug.assert)('The name in the given arguments is undefined or empty string', !(0, _metal.isEmpty)(_name)); name = _name; } } let renderOptions = buildRenderOptions(this, isDefaultRender, name, options); this.connections.push(renderOptions); (0, _runloop.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: ```app/routes/application.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { showModal(evt) { this.render(evt.modalName, { outlet: 'modal', into: 'application' }); }, hideModal(evt) { this.disconnectOutlet({ outlet: 'modal', parentView: 'application' }); } } }); ``` Alternatively, you can pass the `outlet` name directly as a string. Example: ```app/routes/application.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { showModal(evt) { // ... }, hideModal(evt) { this.disconnectOutlet('modal'); } } }); ``` @method disconnectOutlet @param {Object|String} options the options hash or outlet name @since 1.0.0 @public */ disconnectOutlet(options) { let outletName; let parentView; if (options) { if (typeof options === 'string') { outletName = options; } else { outletName = options.outlet; parentView = options.parentView ? options.parentView.replace(/\//g, '.') : undefined; true && !!('outlet' in options && options.outlet === undefined) && (0, _debug.assert)('You passed undefined as the outlet name.', !('outlet' in options && options.outlet === undefined)); } } outletName = outletName || 'main'; this._disconnectOutlet(outletName, parentView); let routeInfos = this._router._routerMicrolib.currentRouteInfos; for (let i = 0; i < routeInfos.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. routeInfos[i].route._disconnectOutlet(outletName, parentView); } } _disconnectOutlet(outletName, parentView) { let parent = parentRoute(this); if (parent && parentView === parent.routeName) { parentView = undefined; } for (let i = 0; i < this.connections.length; i++) { let 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 }; (0, _runloop.once)(this._router, '_setOutlets'); } } } willDestroy() { this.teardownViews(); } /** @private @method teardownViews */ teardownViews() { if (this.connections && this.connections.length > 0) { this.connections = []; (0, _runloop.once)(this._router, '_setOutlets'); } } } Route.reopenClass({ isRouteFactory: true }); function parentRoute(route) { let routeInfo = routeInfoFor(route, route._router._routerMicrolib.state.routeInfos, -1); return routeInfo && routeInfo.route; } function routeInfoFor(route, routeInfos, offset = 0) { if (!routeInfos) { return; } let current; for (let i = 0; i < routeInfos.length; i++) { current = routeInfos[i].route; if (current === route) { return routeInfos[i + offset]; } } return; } function buildRenderOptions(route, isDefaultRender, _name, options) { true && !(isDefaultRender || !(options && 'outlet' in options && options.outlet === undefined)) && (0, _debug.assert)('You passed undefined as the outlet name.', isDefaultRender || !(options && 'outlet' in options && options.outlet === undefined)); let owner = (0, _owner.getOwner)(route); let name, templateName, into, outlet, controller, model; if (options) { into = options.into && options.into.replace(/\//g, '.'); outlet = options.outlet; controller = options.controller; model = options.model; } outlet = outlet || 'main'; if (isDefaultRender) { name = route.routeName; templateName = route.templateName || name; } else { name = _name.replace(/\//g, '.'); templateName = name; } if (!controller) { if (isDefaultRender) { controller = route.controllerName || owner.lookup(`controller:${name}`); } else { controller = owner.lookup(`controller:${name}`) || route.controllerName || route.routeName; } } if (typeof controller === 'string') { let controllerName = controller; controller = owner.lookup(`controller:${controllerName}`); true && !(isDefaultRender || !!controller) && (0, _debug.assert)(`You passed \`controller: '${controllerName}'\` into the \`render\` method, but no such controller could be found.`, isDefaultRender || !!controller); } if (model) { controller.set('model', model); } let template = owner.lookup(`template:${templateName}`); true && !(isDefaultRender || !!template) && (0, _debug.assert)(`Could not find "${templateName}" template, view, or component.`, isDefaultRender || !!template); let parent; if (into && (parent = parentRoute(route)) && into === parent.routeName) { into = undefined; } let renderOptions = { owner, into, outlet, name, controller: controller, template: template || route._topLevelViewTemplate }; if (true /* DEBUG */) { let LOG_VIEW_LOOKUPS = (0, _metal.get)(route._router, 'namespace.LOG_VIEW_LOOKUPS'); if (LOG_VIEW_LOOKUPS && !template) { (0, _debug.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'] = {}; (0, _polyfills.assign)(state['fullQueryParams'], state.queryParams); router._deserializeQueryParams(state.routeInfos, state['fullQueryParams']); return state['fullQueryParams']; } function getQueryParamsFor(route, state) { state['queryParamsFor'] = state['queryParamsFor'] || {}; let name = route.fullRouteName; if (state['queryParamsFor'][name]) { return state['queryParamsFor'][name]; } let fullQueryParams = getFullQueryParams(route._router, state); let params = state['queryParamsFor'][name] = {}; // Copy over all the query params for this route/controller into params hash. let qpMeta = (0, _metal.get)(route, '_qp'); let qps = qpMeta.qps; for (let i = 0; i < qps.length; ++i) { // Put deserialized qp on params hash. let qp = qps[i]; let 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 (0, _runtime.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) { let qps = {}; let 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 (let cqpName in controllerQP) { if (!controllerQP.hasOwnProperty(cqpName)) { continue; } let newControllerParameterConfiguration = {}; (0, _polyfills.assign)(newControllerParameterConfiguration, controllerQP[cqpName], 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 (let rqpName in routeQP) { if (!routeQP.hasOwnProperty(rqpName) || keysAlreadyMergedOrSkippable[rqpName]) { continue; } let newRouteParameterConfiguration = {}; (0, _polyfills.assign)(newRouteParameterConfiguration, routeQP[rqpName], controllerQP[rqpName]); qps[rqpName] = newRouteParameterConfiguration; } return qps; } function addQueryParamsObservers(controller, propNames) { propNames.forEach(prop => { controller.addObserver(`${prop}.[]`, controller, controller._qpChanged); }); } function getEngineRouteName(engine, routeName) { if (engine.routable) { let prefix = engine.mountPoint; if (routeName === 'application') { return prefix; } else { return `${prefix}.${routeName}`; } } return routeName; } /** A hook you can implement to convert the route's model into parameters for the URL. ```app/router.js // ... Router.map(function() { this.route('post', { path: '/posts/:post_id' }); }); ``` ```app/routes/post.js import $ from 'jquery'; import Route from '@ember/routing/route'; export default Route.extend({ model(params) { // the server returns `{ id: 12 }` return $.getJSON('/posts/' + params.post_id); }, serialize(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 `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 @since 1.0.0 @public */ Route.prototype.serialize = defaultSerialize; Route.reopen(_runtime.ActionHandler, _runtime.Evented, { mergedProperties: ['queryParams'], /** 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 Route @type Object @since 1.6.0 @public */ queryParams: {}, /** The name of the template to use by default when rendering this routes template. ```app/routes/posts/list.js import Route from '@ember/routing/route'; export default Route.extend({ templateName: 'posts/list' }); ``` ```app/routes/posts/index.js import PostsList from '../posts/list'; export default PostsList.extend(); ``` ```app/routes/posts/archived.js import PostsList from '../posts/list'; export default PostsList.extend(); ``` @property templateName @type String @default null @since 1.4.0 @public */ templateName: null, /** @private @property _names */ _names: 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. `posts.new`). 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, /** 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: (0, _metal.computed)(function () { let owner = (0, _owner.getOwner)(this); let routeName = this.routeName; let namespace = (0, _metal.get)(this, '_router.namespace'); return { find(name, value) { let modelClass = owner.factoryFor(`model:${name}`); true && !!!modelClass && (0, _debug.assert)(`You used the dynamic segment ${name}_id in your route ${routeName}, but ${namespace}.${(0, _string.classify)(name)} did not exist and you did not override your route's \`model\` hook.`, !!modelClass); if (!modelClass) { return; } modelClass = modelClass.class; true && !(typeof modelClass.find === 'function') && (0, _debug.assert)(`${(0, _string.classify)(name)} has no method \`find\`.`, typeof modelClass.find === 'function'); return modelClass.find(value); } }; }), router: _deprecatedFeatures.ROUTER_ROUTER ? (0, _metal.computed)('_router', function () { true && !false && (0, _debug.deprecate)('Route#router is an intimate API that has been renamed to Route#_router. However you might want to consider using the router service', false, { id: 'ember-routing.route-router', until: '3.5.0', url: 'https://emberjs.com/deprecations/v3.x#toc_ember-routing-route-router' }); return this._router; }) : undefined, /** @private @property _qp */ _qp: (0, _metal.computed)(function () { let combinedQueryParameterConfiguration; let controllerName = this.controllerName || this.routeName; let owner = (0, _owner.getOwner)(this); let controller = owner.lookup(`controller:${controllerName}`); let queryParameterConfiguraton = (0, _metal.get)(this, 'queryParams'); let hasRouterDefinedQueryParams = Object.keys(queryParameterConfiguraton).length > 0; if (controller) { // the developer has authored a controller class in their application for // this route 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 `{}` let controllerDefinedQueryParameterConfiguration = (0, _metal.get)(controller, 'queryParams') || {}; let normalizedControllerQueryParameterConfiguration = (0, _utils.normalizeControllerQueryParams)(controllerDefinedQueryParameterConfiguration); combinedQueryParameterConfiguration = mergeEachQueryParams(normalizedControllerQueryParameterConfiguration, queryParameterConfiguraton); } 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 controller = (0, _generate_controller.default)(owner, controllerName); combinedQueryParameterConfiguration = queryParameterConfiguraton; } let qps = []; let map = {}; let propertyNames = []; for (let 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; } let desc = combinedQueryParameterConfiguration[propName]; let scope = desc.scope || 'model'; let parts; if (scope === 'controller') { parts = []; } let urlKey = desc.as || this.serializeQueryParamKey(propName); let defaultValue = (0, _metal.get)(controller, propName); if (Array.isArray(defaultValue)) { defaultValue = (0, _runtime.A)(defaultValue.slice()); } let type = desc.type || (0, _runtime.typeOf)(defaultValue); let defaultValueSerialized = this.serializeQueryParam(defaultValue, urlKey, type); let scopedPropertyName = `${controllerName}:${propName}`; let qp = { undecoratedDefaultValue: (0, _metal.get)(controller, propName), defaultValue, serializedDefaultValue: defaultValueSerialized, serializedValue: defaultValueSerialized, type, urlKey, prop: propName, scopedPropertyName, controllerName, route: this, parts, values: null, scope }; map[propName] = map[urlKey] = map[scopedPropertyName] = qp; qps.push(qp); propertyNames.push(propName); } return { qps, map, 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: (prop, value) => { let 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: (prop, value) => { let qp = map[prop]; this._qpChanged(prop, value, qp); return this._activeQPChanged(qp, 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: (prop, value) => { let qp = map[prop]; this._qpChanged(prop, value, qp); return this._updatingQPChanged(qp); } } }; }), /** Sends an action to the router, which will delegate it to the currently active route hierarchy per the bubbling rules explained under `actions`. Example ```app/router.js // ... Router.map(function() { this.route('index'); }); export default Router; ``` ```app/routes/application.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { track(arg) { console.log(arg, 'was clicked'); } } }); ``` ```app/routes/index.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { trackIfDebug(arg) { if (debug) { this.send('track', arg); } } } }); ``` @method send @param {String} name the name of the action to trigger @param {...*} args @since 1.0.0 @public */ send(...args) { true && !(!this.isDestroying && !this.isDestroyed) && (0, _debug.assert)(`Attempted to call .send() with the action '${args[0]}' on the destroyed route '${this.routeName}'.`, !this.isDestroying && !this.isDestroyed); if (this._router && this._router._routerMicrolib || !(0, _debug.isTesting)()) { this._router.send(...args); } else { let name = args.shift(); let action = this.actions[name]; if (action) { return action.apply(this, args); } } }, /** The controller associated with this route. Example ```app/routes/form.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { willTransition(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 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(changed, _totalPresent, removed) { let qpMap = (0, _metal.get)(this, '_qp').map; let totalChanged = Object.keys(changed).concat(Object.keys(removed)); for (let i = 0; i < totalChanged.length; ++i) { let qp = qpMap[totalChanged[i]]; if (qp && (0, _metal.get)(this._optionsForQueryParam(qp), 'refreshModel') && this._router.currentState) { this.refresh(); break; } } return true; }, finalizeQueryParamChange(params, finalParams, transition) { if (this.fullRouteName !== 'application') { return true; } // Transition object is absent for intermediate transitions. if (!transition) { return; } let routeInfos = transition[_router_js.STATE_SYMBOL].routeInfos; let router = this._router; let qpMeta = router._queryParamsFor(routeInfos); let changes = router._qpUpdates; let replaceUrl; (0, _utils.stashParamNames)(router, routeInfos); for (let i = 0; i < qpMeta.qps.length; ++i) { let qp = qpMeta.qps[i]; let route = qp.route; let controller = route.controller; let 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. let value, svalue; if (changes.has(qp.urlKey)) { // Value updated in/before setupController value = (0, _metal.get)(controller, qp.prop); svalue = route.serializeQueryParam(value, qp.urlKey, qp.type); } else { if (presentKey) { svalue = params[presentKey]; if (svalue !== undefined) { value = route.deserializeQueryParam(svalue, qp.urlKey, qp.type); } } else { // No QP provided; use default value. svalue = qp.serializedDefaultValue; value = copyDefaultValue(qp.defaultValue); } } controller._qpDelegate = (0, _metal.get)(route, '_qp.states.inactive'); let thisQueryParamChanged = svalue !== qp.serializedValue; if (thisQueryParamChanged) { if (transition.queryParamsOnly && replaceUrl !== false) { let options = route._optionsForQueryParam(qp); let replaceConfigValue = (0, _metal.get)(options, 'replace'); if (replaceConfigValue) { replaceUrl = true; } else if (replaceConfigValue === false) { // Explicit pushState wins over any other replaceStates. replaceUrl = false; } } (0, _metal.set)(controller, qp.prop, value); } // Stash current serialized value of controller. qp.serializedValue = svalue; let thisQueryParamHasDefaultValue = qp.serializedDefaultValue === svalue; if (!thisQueryParamHasDefaultValue || transition._keepDefaultQueryParamValues) { finalParams.push({ value: svalue, visible: true, key: presentKey || qp.urlKey }); } } if (replaceUrl) { transition.method('replace'); } qpMeta.qps.forEach(qp => { let routeQpMeta = (0, _metal.get)(qp.route, '_qp'); let finalizedController = qp.route.controller; finalizedController._qpDelegate = (0, _metal.get)(routeQpMeta, 'states.active'); }); router._qpUpdates.clear(); return; } } }); let ROUTER_EVENT_DEPRECATIONS = exports.ROUTER_EVENT_DEPRECATIONS = undefined; if (true /* EMBER_ROUTING_ROUTER_SERVICE */ && _deprecatedFeatures.ROUTER_EVENTS) { exports.ROUTER_EVENT_DEPRECATIONS = ROUTER_EVENT_DEPRECATIONS = { on(name) { this._super(...arguments); let hasDidTransition = name === 'didTransition'; let hasWillTransition = name === 'willTransition'; if (hasDidTransition) { true && !false && (0, _debug.deprecate)('You attempted to listen to the "didTransition" event which is deprecated. Please inject the router service and listen to the "routeDidChange" event.', false, { id: 'deprecate-router-events', until: '4.0.0', url: 'https://emberjs.com/deprecations/v3.x#toc_deprecate-router-events' }); } if (hasWillTransition) { true && !false && (0, _debug.deprecate)('You attempted to listen to the "willTransition" event which is deprecated. Please inject the router service and listen to the "routeWillChange" event.', false, { id: 'deprecate-router-events', until: '4.0.0', url: 'https://emberjs.com/deprecations/v3.x#toc_deprecate-router-events' }); } } }; Route.reopen(ROUTER_EVENT_DEPRECATIONS, { _paramsFor(routeName, params) { let transition = this._router._routerMicrolib.activeTransition; if (transition !== undefined) { return this.paramsFor(routeName); } return params; } }); } exports.default = Route; }); enifed('@ember/-internals/routing/lib/system/router', ['exports', '@ember/-internals/metal', '@ember/-internals/owner', '@ember/-internals/runtime', '@ember/debug', '@ember/deprecated-features', '@ember/error', '@ember/polyfills', '@ember/runloop', '@ember/-internals/routing/lib/location/api', '@ember/-internals/routing/lib/utils', '@ember/-internals/routing/lib/system/dsl', '@ember/-internals/routing/lib/system/route', '@ember/-internals/routing/lib/system/router_state', 'router_js'], function (exports, _metal, _owner, _runtime, _debug, _deprecatedFeatures, _error2, _polyfills, _runloop, _api, _utils, _dsl, _route, _router_state, _router_js) { 'use strict'; exports.triggerEvent = triggerEvent; function defaultDidTransition(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. (0, _runloop.once)(this, this.trigger, 'didTransition'); if (true /* DEBUG */) { if ((0, _metal.get)(this, 'namespace').LOG_TRANSITIONS) { // eslint-disable-next-line no-console console.log(`Transitioned into '${EmberRouter._routePath(infos)}'`); } } } function defaultWillTransition(oldInfos, newInfos, transition) { (0, _runloop.once)(this, this.trigger, 'willTransition', transition); if (true /* DEBUG */) { if ((0, _metal.get)(this, 'namespace').LOG_TRANSITIONS) { // eslint-disable-next-line no-console console.log(`Preparing to transition from '${EmberRouter._routePath(oldInfos)}' to '${EmberRouter._routePath(newInfos)}'`); } } } if (_deprecatedFeatures.TRANSITION_STATE) { Object.defineProperty(_router_js.InternalTransition.prototype, 'state', { get() { if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { true && !false && (0, _debug.deprecate)('You attempted to read "transition.state" which is a private API. You should read the `RouteInfo` object on "transition.to" or "transition.from" which has the public state on it.', false, { id: 'transition-state', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_transition-state' }); } return this[_router_js.STATE_SYMBOL]; } }); Object.defineProperty(_router_js.InternalTransition.prototype, 'queryParams', { get() { if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { true && !false && (0, _debug.deprecate)('You attempted to read "transition.queryParams" which is a private API. You should read the `RouteInfo` object on "transition.to" or "transition.from" which has the queryParams on it.', false, { id: 'transition-state', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_transition-state' }); } return this[_router_js.QUERY_PARAMS_SYMBOL]; } }); Object.defineProperty(_router_js.InternalTransition.prototype, 'params', { get() { if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { true && !false && (0, _debug.deprecate)('You attempted to read "transition.params" which is a private API. You should read the `RouteInfo` object on "transition.to" or "transition.from" which has the params on it.', false, { id: 'transition-state', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_transition-state' }); } return this[_router_js.PARAMS_SYMBOL]; } }); } if (_deprecatedFeatures.HANDLER_INFOS) { Object.defineProperty(_router_js.InternalRouteInfo.prototype, 'handler', { get() { if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { true && !false && (0, _debug.deprecate)('You attempted to read "handlerInfo.handler" which is a private API that will be removed.', false, { id: 'remove-handler-infos', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_remove-handler-infos' }); } return this.route; }, set(value) { if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { true && !false && (0, _debug.deprecate)('You attempted to set "handlerInfo.handler" which is a private API that will be removed.', false, { id: 'remove-handler-infos', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_remove-handler-infos' }); } this.route = value; } }); Object.defineProperty(_router_js.InternalTransition.prototype, 'handlerInfos', { get() { if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { true && !false && (0, _debug.deprecate)('You attempted to use "transition.handlerInfos" which is a private API that will be removed.', false, { id: 'remove-handler-infos', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_remove-handler-infos' }); } return this.routeInfos; } }); Object.defineProperty(_router_js.TransitionState.prototype, 'handlerInfos', { get() { if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { true && !false && (0, _debug.deprecate)('You attempted to use "transition.state.handlerInfos" which is a private API that will be removed.', false, { id: 'remove-handler-infos', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_remove-handler-infos' }); } return this.routeInfos; } }); Object.defineProperty(_router_js.default.prototype, 'currentHandlerInfos', { get() { if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { true && !false && (0, _debug.deprecate)('You attempted to use "_routerMicrolib.currentHandlerInfos" which is a private API that will be removed.', false, { id: 'remove-handler-infos', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_remove-handler-infos' }); } return this.currentRouteInfos; } }); _router_js.default.prototype['getHandler'] = function (name) { if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { true && !false && (0, _debug.deprecate)('You attempted to use "_routerMicrolib.getHandler" which is a private API that will be removed.', false, { id: 'remove-handler-infos', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_remove-handler-infos' }); } return this.getRoute(name); }; } function K() { return this; } const { slice } = Array.prototype; /** The `EmberRouter` class manages the application state and URLs. Refer to the [routing guide](https://guides.emberjs.com/release/routing/) for documentation. @class EmberRouter @extends EmberObject @uses Evented @public */ class EmberRouter extends _runtime.Object { constructor() { super(...arguments); this.currentState = null; this.targetState = null; } _initRouterJs() { let location = (0, _metal.get)(this, 'location'); let router = this; let owner = (0, _owner.getOwner)(this); let seen = Object.create(null); class PrivateRouter extends _router_js.default { getRoute(name) { let routeName = name; let routeOwner = owner; let engineInfo = router._engineInfoByRoute[routeName]; if (engineInfo) { let engineInstance = router._getEngineInstance(engineInfo); routeOwner = engineInstance; routeName = engineInfo.localFullName; } let fullRouteName = `route:${routeName}`; let route = routeOwner.lookup(fullRouteName); if (seen[name]) { return route; } seen[name] = true; if (!route) { let DefaultRoute = routeOwner.factoryFor('route:basic').class; routeOwner.register(fullRouteName, DefaultRoute.extend()); route = routeOwner.lookup(fullRouteName); if (true /* DEBUG */) { if ((0, _metal.get)(router, 'namespace.LOG_ACTIVE_GENERATION')) { (0, _debug.info)(`generated -> ${fullRouteName}`, { fullName: fullRouteName }); } } } route._setRouteName(routeName); if (engineInfo && !(0, _route.hasDefaultSerialize)(route)) { throw new Error('Defining a custom serialize method on an Engine route is not supported.'); } return route; } getSerializer(name) { let engineInfo = router._engineInfoByRoute[name]; // If this is not an Engine route, we fall back to the handler for serialization if (!engineInfo) { return; } return engineInfo.serializeMethod || _route.defaultSerialize; } updateURL(path) { (0, _runloop.once)(() => { location.setURL(path); (0, _metal.set)(router, 'currentURL', path); }); } didTransition(infos) { if (true /* EMBER_ROUTING_ROUTER_SERVICE */ && _deprecatedFeatures.ROUTER_EVENTS) { if (router.didTransition !== defaultDidTransition) { true && !false && (0, _debug.deprecate)('You attempted to override the "didTransition" method which is deprecated. Please inject the router service and listen to the "routeDidChange" event.', false, { id: 'deprecate-router-events', until: '4.0.0', url: 'https://emberjs.com/deprecations/v3.x#toc_deprecate-router-events' }); } } router.didTransition(infos); } willTransition(oldInfos, newInfos, transition) { if (true /* EMBER_ROUTING_ROUTER_SERVICE */ && _deprecatedFeatures.ROUTER_EVENTS) { if (router.willTransition !== defaultWillTransition) { true && !false && (0, _debug.deprecate)('You attempted to override the "willTransition" method which is deprecated. Please inject the router service and listen to the "routeWillChange" event.', false, { id: 'deprecate-router-events', until: '4.0.0', url: 'https://emberjs.com/deprecations/v3.x#toc_deprecate-router-events' }); } } router.willTransition(oldInfos, newInfos, transition); } triggerEvent(routeInfos, ignoreFailure, name, args) { return triggerEvent.bind(router)(routeInfos, ignoreFailure, name, args); } routeWillChange(transition) { if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { router.trigger('routeWillChange', transition); } } routeDidChange(transition) { if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { router.set('currentRoute', transition.to); (0, _runloop.once)(() => { router.trigger('routeDidChange', transition); }); } } transitionDidError(error, transition) { if (error.wasAborted || transition.isAborted) { // If the error was a transition erorr or the transition aborted // log the abort. return (0, _router_js.logAbort)(transition); } else { // Otherwise trigger the "error" event to attempt an intermediate // transition into an error substate transition.trigger(false, 'error', error.error, transition, error.route); if (router._isErrorHandled(error.error)) { // If we handled the error with a substate just roll the state back on // the transition and send the "routeDidChange" event for landing on // the error substate and return the error. transition.rollback(); this.routeDidChange(transition); return error.error; } else { // If it was not handled, abort the transition completely and return // the error. transition.abort(); return error.error; } } } _triggerWillChangeContext() { return router; } _triggerWillLeave() { return router; } replaceURL(url) { if (location.replaceURL) { let doReplaceURL = () => { location.replaceURL(url); (0, _metal.set)(router, 'currentURL', url); }; (0, _runloop.once)(doReplaceURL); } else { this.updateURL(url); } } } let routerMicrolib = this._routerMicrolib = new PrivateRouter(); let dslCallbacks = this.constructor.dslCallbacks || [K]; let dsl = this._buildDSL(); dsl.route('application', { path: '/', resetNamespace: true, overrideNameAssertion: true }, function () { for (let i = 0; i < dslCallbacks.length; i++) { dslCallbacks[i].call(this); } }); if (true /* DEBUG */) { if ((0, _metal.get)(this, 'namespace.LOG_TRANSITIONS_INTERNAL')) { routerMicrolib.log = console.log.bind(console); // eslint-disable-line no-console } } routerMicrolib.map(dsl.generate()); } _buildDSL() { let enableLoadingSubstates = this._hasModuleBasedResolver(); let router = this; let owner = (0, _owner.getOwner)(this); let options = { enableLoadingSubstates, resolveRouteMap(name) { return owner.factoryFor(`route-map:${name}`); }, addRouteForEngine(name, engineInfo) { if (!router._engineInfoByRoute[name]) { router._engineInfoByRoute[name] = engineInfo; } } }; return new _dsl.default(null, options); } init() { this._super(...arguments); this.currentURL = null; this.currentRouteName = null; this.currentPath = null; if (true /* EMBER_ROUTING_ROUTER_SERVICE */) { this.currentRoute = null; } this._qpCache = Object.create(null); this._qpUpdates = new Set(); this._resetQueuedQueryParameterChanges(); this._handledErrors = new Set(); this._engineInstances = Object.create(null); this._engineInfoByRoute = Object.create(null); } /* Resets all pending query parameter changes. Called after transitioning to a new route based on query parameter changes. */ _resetQueuedQueryParameterChanges() { this._queuedQPChanges = {}; } _hasModuleBasedResolver() { let owner = (0, _owner.getOwner)(this); if (!owner) { return false; } let resolver = (0, _metal.get)(owner, 'application.__registry__.resolver.moduleBasedResolver'); return !!resolver; } /** 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() { let initialURL = (0, _metal.get)(this, 'initialURL'); if (this.setupRouter()) { if (initialURL === undefined) { initialURL = (0, _metal.get)(this, 'location').getURL(); } let initialTransition = this.handleURL(initialURL); if (initialTransition && initialTransition.error) { throw initialTransition.error; } } } setupRouter() { this._setupLocation(); let location = (0, _metal.get)(this, 'location'); // Allow the Location class to cancel the router setup while it refreshes // the page if ((0, _metal.get)(location, 'cancelRouterSetup')) { return false; } this._initRouterJs(); location.onUpdateURL(url => { this.handleURL(url); }); return true; } _setOutlets() { // This is triggered async during 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; } let routeInfos = this._routerMicrolib.currentRouteInfos; let route; let defaultParentState; let liveRoutes = null; if (!routeInfos) { return; } for (let i = 0; i < routeInfos.length; i++) { route = routeInfos[i].route; let connections = route.connections; let ownState; for (let j = 0; j < connections.length; j++) { let 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; } // when a transitionTo happens after the validation phase // during the initial transition _setOutlets is called // when no routes are active. However, it will get called // again with the correct values during the next turn of // the runloop if (!liveRoutes) { return; } if (!this._toplevelView) { let owner = (0, _owner.getOwner)(this); let OutletView = owner.factoryFor('view:-outlet'); this._toplevelView = OutletView.create(); this._toplevelView.setOutletState(liveRoutes); let instance = owner.lookup('-application-instance:main'); instance.didCreateRootView(this._toplevelView); } else { this._toplevelView.setOutletState(liveRoutes); } } handleURL(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. let _url = url.split(/#(.+)?/)[0]; return this._doURLTransition('handleURL', _url); } _doURLTransition(routerJsMethod, url) { let transition = this._routerMicrolib[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 [transitionTo](/api/ember/release/classes/Route/methods/transitionTo?anchor=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(...args) { if ((0, _utils.resemblesURL)(args[0])) { true && !(!this.isDestroying && !this.isDestroyed) && (0, _debug.assert)(`A transition was attempted from '${this.currentRouteName}' to '${args[0]}' but the application instance has already been destroyed.`, !this.isDestroying && !this.isDestroyed); return this._doURLTransition('transitionTo', args[0]); } let { routeName, models, queryParams } = (0, _utils.extractRouteArgs)(args); true && !(!this.isDestroying && !this.isDestroyed) && (0, _debug.assert)(`A transition was attempted from '${this.currentRouteName}' to '${routeName}' but the application instance has already been destroyed.`, !this.isDestroying && !this.isDestroyed); return this._doTransition(routeName, models, queryParams); } intermediateTransitionTo(name, ...args) { this._routerMicrolib.intermediateTransitionTo(name, ...args); updatePaths(this); if (true /* DEBUG */) { let infos = this._routerMicrolib.currentRouteInfos; if ((0, _metal.get)(this, 'namespace').LOG_TRANSITIONS) { // eslint-disable-next-line no-console console.log(`Intermediate-transitioned into '${EmberRouter._routePath(infos)}'`); } } } replaceWith(...args) { return this.transitionTo(...args).method('replace'); } generate(name, ...args) { let url = this._routerMicrolib.generate(name, ...args); return this.location.formatURL(url); } /** Determines if the supplied route is currently active. @method isActive @param routeName @return {Boolean} @private */ isActive(routeName) { return this._routerMicrolib.isActive(routeName); } /** 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(routeName, models, queryParams) { return this.currentState.isActiveIntent(routeName, models, queryParams); } send(name, ...args) { /*name, context*/ this._routerMicrolib.trigger(name, ...args); } /** Does this router instance have the given route. @method hasRoute @return {Boolean} @private */ hasRoute(route) { return this._routerMicrolib.hasRoute(route); } /** Resets the state of the router by clearing the current route handlers and deactivating them. @private @method reset */ reset() { if (this._routerMicrolib) { this._routerMicrolib.reset(); } } willDestroy() { if (this._toplevelView) { this._toplevelView.destroy(); this._toplevelView = null; } this._super(...arguments); this.reset(); let instances = this._engineInstances; for (let name in instances) { for (let id in instances[name]) { (0, _runloop.run)(instances[name][id], 'destroy'); } } } /* Called when an active route's query parameter has changed. These changes are batched into a runloop run and trigger a single transition. */ _activeQPChanged(queryParameterName, newValue) { this._queuedQPChanges[queryParameterName] = newValue; (0, _runloop.once)(this, this._fireQueryParamTransition); } _updatingQPChanged(queryParameterName) { this._qpUpdates.add(queryParameterName); } /* 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() { this.transitionTo({ queryParams: this._queuedQPChanges }); this._resetQueuedQueryParameterChanges(); } _setupLocation() { let location = (0, _metal.get)(this, 'location'); let rootURL = (0, _metal.get)(this, 'rootURL'); let owner = (0, _owner.getOwner)(this); if ('string' === typeof location && owner) { let resolvedLocation = owner.lookup(`location:${location}`); if (resolvedLocation !== undefined) { location = (0, _metal.set)(this, 'location', resolvedLocation); } else { // Allow for deprecated registration of custom location API's let options = { implementation: location }; location = (0, _metal.set)(this, 'location', _api.default.create(options)); } } if (location !== null && typeof location === 'object') { if (rootURL) { (0, _metal.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(); } } } /** Serializes the given query params according to their QP meta information. @private @method _serializeQueryParams @param {Arrray} routeInfos @param {Object} queryParams @return {Void} */ _serializeQueryParams(routeInfos, queryParams) { forEachQueryParam(this, routeInfos, queryParams, (key, value, qp) => { if (qp) { delete queryParams[key]; queryParams[qp.urlKey] = qp.route.serializeQueryParam(value, qp.urlKey, qp.type); } else if (value === undefined) { return; // We don't serialize undefined values } else { queryParams[key] = this._serializeQueryParam(value, (0, _runtime.typeOf)(value)); } }); } /** Serializes the value of a query parameter based on a type @private @method _serializeQueryParam @param {Object} value @param {String} type */ _serializeQueryParam(value, type) { if (value === null || value === undefined) { return value; } else if (type === 'array') { return JSON.stringify(value); } return `${value}`; } /** Deserializes the given query params according to their QP meta information. @private @method _deserializeQueryParams @param {Array} routeInfos @param {Object} queryParams @return {Void} */ _deserializeQueryParams(routeInfos, queryParams) { forEachQueryParam(this, routeInfos, queryParams, (key, value, qp) => { // If we don't have QP meta info for a given key, then we do nothing // because all values will be treated as strings if (qp) { delete queryParams[key]; queryParams[qp.prop] = qp.route.deserializeQueryParam(value, qp.urlKey, qp.type); } }); } /** Deserializes the value of a query parameter based on a default type @private @method _deserializeQueryParam @param {Object} value @param {String} defaultType */ _deserializeQueryParam(value, defaultType) { if (value === null || value === undefined) { return value; } else if (defaultType === 'boolean') { return value === 'true'; } else if (defaultType === 'number') { return Number(value).valueOf(); } else if (defaultType === 'array') { return (0, _runtime.A)(JSON.parse(value)); } return value; } /** Removes (prunes) any query params with default values from the given QP object. Default values are determined from the QP meta information per key. @private @method _pruneDefaultQueryParamValues @param {Array} routeInfos @param {Object} queryParams @return {Void} */ _pruneDefaultQueryParamValues(routeInfos, queryParams) { let qps = this._queryParamsFor(routeInfos); for (let key in queryParams) { let qp = qps.map[key]; if (qp && qp.serializedDefaultValue === queryParams[key]) { delete queryParams[key]; } } } _doTransition(_targetRouteName, models, _queryParams, _keepDefaultQueryParamValues) { let targetRouteName = _targetRouteName || (0, _utils.getActiveTargetName)(this._routerMicrolib); true && !(!!targetRouteName && this._routerMicrolib.hasRoute(targetRouteName)) && (0, _debug.assert)(`The route ${targetRouteName} was not found`, !!targetRouteName && this._routerMicrolib.hasRoute(targetRouteName)); let queryParams = {}; this._processActiveTransitionQueryParams(targetRouteName, models, queryParams, _queryParams); (0, _polyfills.assign)(queryParams, _queryParams); this._prepareQueryParams(targetRouteName, models, queryParams, !!_keepDefaultQueryParamValues); let transition = this._routerMicrolib.transitionTo(targetRouteName, ...models, { queryParams }); didBeginTransition(transition, this); return transition; } _processActiveTransitionQueryParams(targetRouteName, models, queryParams, _queryParams) { // merge in any queryParams from the active transition which could include // queryParams from the url on initial load. if (!this._routerMicrolib.activeTransition) { return; } let unchangedQPs = {}; let qpUpdates = this._qpUpdates; let params = this._routerMicrolib.activeTransition[_router_js.QUERY_PARAMS_SYMBOL]; for (let key in params) { if (!qpUpdates.has(key)) { unchangedQPs[key] = params[key]; } } // We need to fully scope queryParams so that we can create one object // that represents both passed-in queryParams and ones that aren't changed // from the active transition. this._fullyScopeQueryParams(targetRouteName, models, _queryParams); this._fullyScopeQueryParams(targetRouteName, models, unchangedQPs); (0, _polyfills.assign)(queryParams, unchangedQPs); } /** Prepares the query params for a URL or Transition. Restores any undefined QP keys/values, serializes all values, and then prunes any default values. @private @method _prepareQueryParams @param {String} targetRouteName @param {Array} models @param {Object} queryParams @param {boolean} keepDefaultQueryParamValues @return {Void} */ _prepareQueryParams(targetRouteName, models, queryParams, _fromRouterService) { let state = calculatePostTransitionState(this, targetRouteName, models); this._hydrateUnsuppliedQueryParams(state, queryParams, !!_fromRouterService); this._serializeQueryParams(state.routeInfos, queryParams); if (!_fromRouterService) { this._pruneDefaultQueryParamValues(state.routeInfos, queryParams); } } /** Returns the meta information for the query params of a given route. This will be overridden to allow support for lazy routes. @private @method _getQPMeta @param {RouteInfo} routeInfo @return {Object} */ _getQPMeta(routeInfo) { let route = routeInfo.route; return route && (0, _metal.get)(route, '_qp'); } /** Returns a merged query params meta object for a given set of routeInfos. Useful for knowing what query params are available for a given route hierarchy. @private @method _queryParamsFor @param {Array} routeInfos @return {Object} */ _queryParamsFor(routeInfos) { let routeInfoLength = routeInfos.length; let leafRouteName = routeInfos[routeInfoLength - 1].name; let cached = this._qpCache[leafRouteName]; if (cached !== undefined) { return cached; } let shouldCache = true; let map = {}; let qps = []; let qpsByUrlKey = true /* DEBUG */ ? {} : null; let qpMeta; let qp; let urlKey; let qpOther; for (let i = 0; i < routeInfoLength; ++i) { qpMeta = this._getQPMeta(routeInfos[i]); if (!qpMeta) { shouldCache = false; continue; } // Loop over each QP to make sure we don't have any collisions by urlKey for (let i = 0; i < qpMeta.qps.length; i++) { qp = qpMeta.qps[i]; if (true /* DEBUG */) { urlKey = qp.urlKey; qpOther = qpsByUrlKey[urlKey]; if (qpOther && qpOther.controllerName !== qp.controllerName) { true && !false && (0, _debug.assert)(`You're not allowed to have more than one controller property map to the same query param key, but both \`${qpOther.scopedPropertyName}\` and \`${qp.scopedPropertyName}\` map to \`${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. \`${qpOther.prop}: { as: \'other-${qpOther.prop}\' }\``, false); } qpsByUrlKey[urlKey] = qp; } qps.push(qp); } (0, _polyfills.assign)(map, qpMeta.map); } let finalQPMeta = { qps, map }; if (shouldCache) { this._qpCache[leafRouteName] = finalQPMeta; } return finalQPMeta; } /** Maps all query param keys to their fully scoped property name of the form `controllerName:propName`. @private @method _fullyScopeQueryParams @param {String} leafRouteName @param {Array} contexts @param {Object} queryParams @return {Void} */ _fullyScopeQueryParams(leafRouteName, contexts, queryParams) { let state = calculatePostTransitionState(this, leafRouteName, contexts); let routeInfos = state.routeInfos; let qpMeta; for (let i = 0, len = routeInfos.length; i < len; ++i) { qpMeta = this._getQPMeta(routeInfos[i]); if (!qpMeta) { continue; } let qp; let presentProp; for (let j = 0, qpLen = qpMeta.qps.length; j < qpLen; ++j) { qp = qpMeta.qps[j]; 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]; } } } } } /** Hydrates (adds/restores) any query params that have pre-existing values into the given queryParams hash. This is what allows query params to be "sticky" and restore their last known values for their scope. @private @method _hydrateUnsuppliedQueryParams @param {TransitionState} state @param {Object} queryParams @return {Void} */ _hydrateUnsuppliedQueryParams(state, queryParams, _fromRouterService) { let routeInfos = state.routeInfos; let appCache = this._bucketCache; let qpMeta; let qp; let presentProp; for (let i = 0; i < routeInfos.length; ++i) { qpMeta = this._getQPMeta(routeInfos[i]); if (!qpMeta) { continue; } for (let j = 0, qpLen = qpMeta.qps.length; j < qpLen; ++j) { qp = qpMeta.qps[j]; presentProp = qp.prop in queryParams && qp.prop || qp.scopedPropertyName in queryParams && qp.scopedPropertyName || qp.urlKey in queryParams && qp.urlKey; true && !function () { if (qp.urlKey === presentProp) { return true; } if (_fromRouterService && presentProp !== false) { return false; } return true; }() && (0, _debug.assert)(`You passed the \`${presentProp}\` query parameter during a transition into ${qp.route.routeName}, please update to ${qp.urlKey}`, function () { if (qp.urlKey === presentProp) { return true; }if (_fromRouterService && presentProp !== false) { return false; }return true; }()); if (presentProp) { if (presentProp !== qp.scopedPropertyName) { queryParams[qp.scopedPropertyName] = queryParams[presentProp]; delete queryParams[presentProp]; } } else { let cacheKey = (0, _utils.calculateCacheKey)(qp.route.fullRouteName, qp.parts, state.params); queryParams[qp.scopedPropertyName] = appCache.lookup(cacheKey, qp.prop, qp.defaultValue); } } } } _scheduleLoadingEvent(transition, originRoute) { this._cancelSlowTransitionTimer(); this._slowTransitionTimer = (0, _runloop.scheduleOnce)('routerTransitions', this, '_handleSlowTransition', transition, originRoute); } _handleSlowTransition(transition, originRoute) { if (!this._routerMicrolib.activeTransition) { // Don't fire an event if we've since moved on from // the transition that put us in a loading state. return; } let targetState = new _router_state.default(this, this._routerMicrolib, this._routerMicrolib.activeTransition[_router_js.STATE_SYMBOL]); this.set('targetState', targetState); transition.trigger(true, 'loading', transition, originRoute); } _cancelSlowTransitionTimer() { if (this._slowTransitionTimer) { (0, _runloop.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(error) { this._handledErrors.add(error); } _isErrorHandled(error) { return this._handledErrors.has(error); } _clearHandledError(error) { this._handledErrors.delete(error); } _getEngineInstance({ name, instanceId, mountPoint }) { let engineInstances = this._engineInstances; if (!engineInstances[name]) { engineInstances[name] = Object.create(null); } let engineInstance = engineInstances[name][instanceId]; if (!engineInstance) { let owner = (0, _owner.getOwner)(this); true && !owner.hasRegistration(`engine:${name}`) && (0, _debug.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 }); engineInstance.boot(); engineInstances[name][instanceId] = engineInstance; } return engineInstance; } } /* Helper function for iterating over routes in a set of routeInfos that are at or above the given origin route. Example: if `originRoute` === 'foo.bar' and the routeInfos given were for 'foo.bar.baz', then the given callback will be invoked with the routes for 'foo.bar', 'foo', and 'application' individually. If the callback returns anything other than `true`, then iteration will stop. @private @param {Route} originRoute @param {Array} routeInfos @param {Function} callback @return {Void} */ function forEachRouteAbove(routeInfos, callback) { for (let i = routeInfos.length - 1; i >= 0; --i) { let routeInfo = routeInfos[i]; let route = routeInfo.route; // routeInfo.handler being `undefined` generally means either: // // 1. an error occurred during creation of the route in question // 2. the route is across an async boundary (e.g. within an engine) // // In both of these cases, we cannot invoke the callback on that specific // route, because it just doesn't exist... if (route === undefined) { continue; } if (callback(route, routeInfo) !== true) { return; } } } // These get invoked when an action bubbles above ApplicationRoute // and are not meant to be overridable. let defaultActionHandlers = { willResolveModel(_routeInfos, transition, originRoute) { this._scheduleLoadingEvent(transition, originRoute); }, // Attempt to find an appropriate error route or substate to enter. error(routeInfos, error, transition) { let router = this; let routeInfoWithError = routeInfos[routeInfos.length - 1]; forEachRouteAbove(routeInfos, (route, routeInfo) => { // We don't check the leaf most routeInfo since that would // technically be below where we're at in the route hierarchy. if (routeInfo !== routeInfoWithError) { // Check for the existence of an 'error' route. let errorRouteName = findRouteStateName(route, 'error'); if (errorRouteName) { router._markErrorAsHandled(error); router.intermediateTransitionTo(errorRouteName, error); return false; } } // Check for an 'error' substate route let errorSubstateName = findRouteSubstateName(route, 'error'); if (errorSubstateName) { router._markErrorAsHandled(error); router.intermediateTransitionTo(errorSubstateName, error); return false; } return true; }); logError(error, `Error while processing route: ${transition.targetName}`); }, // Attempt to find an appropriate loading route or substate to enter. loading(routeInfos, transition) { let router = this; let routeInfoWithSlowLoading = routeInfos[routeInfos.length - 1]; forEachRouteAbove(routeInfos, (route, routeInfo) => { // We don't check the leaf most routeInfos since that would // technically be below where we're at in the route hierarchy. if (routeInfo !== routeInfoWithSlowLoading) { // Check for the existence of a 'loading' route. let loadingRouteName = findRouteStateName(route, 'loading'); if (loadingRouteName) { router.intermediateTransitionTo(loadingRouteName); return false; } } // Check for loading substate let loadingSubstateName = findRouteSubstateName(route, 'loading'); if (loadingSubstateName) { router.intermediateTransitionTo(loadingSubstateName); return false; } // Don't bubble above pivot route. return transition.pivotHandler !== route; }); } }; function logError(_error, initialMessage) { let errorArgs = []; let error; 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); } } console.error(...errorArgs); //eslint-disable-line no-console } /** Finds the name of the substate route if it exists for the given route. A substate route is of the form `route_state`, such as `foo_loading`. @private @param {Route} route @param {String} state @return {String} */ function findRouteSubstateName(route, state) { let owner = (0, _owner.getOwner)(route); let { routeName, fullRouteName, _router: router } = route; let substateName = `${routeName}_${state}`; let substateNameFull = `${fullRouteName}_${state}`; return routeHasBeenDefined(owner, router, substateName, substateNameFull) ? substateNameFull : ''; } /** Finds the name of the state route if it exists for the given route. A state route is of the form `route.state`, such as `foo.loading`. Properly Handles `application` named routes. @private @param {Route} route @param {String} state @return {String} */ function findRouteStateName(route, state) { let owner = (0, _owner.getOwner)(route); let { routeName, fullRouteName, _router: router } = route; let stateName = routeName === 'application' ? state : `${routeName}.${state}`; let stateNameFull = fullRouteName === 'application' ? state : `${fullRouteName}.${state}`; return routeHasBeenDefined(owner, router, stateName, stateNameFull) ? stateNameFull : ''; } /** Determines whether or not a route has been defined by checking that the route is in the Router's map and the owner has a registration for that route. @private @param {Owner} owner @param {Router} router @param {String} localName @param {String} fullName @return {Boolean} */ function routeHasBeenDefined(owner, router, localName, fullName) { let routerHasRoute = router.hasRoute(fullName); let ownerHasRoute = owner.hasRegistration(`template:${localName}`) || owner.hasRegistration(`route:${localName}`); return routerHasRoute && ownerHasRoute; } function triggerEvent(routeInfos, ignoreFailure, name, args) { if (!routeInfos) { if (ignoreFailure) { return; } throw new _error2.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.`); } let eventWasHandled = false; let routeInfo, handler, actionHandler; for (let i = routeInfos.length - 1; i >= 0; i--) { routeInfo = routeInfos[i]; handler = routeInfo.route; actionHandler = handler && handler.actions && handler.actions[name]; if (actionHandler) { if (actionHandler.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') { handler._router._markErrorAsHandled(args[0]); } return; } } } let defaultHandler = defaultActionHandlers[name]; if (defaultHandler) { defaultHandler.apply(this, [routeInfos, ...args]); return; } if (!eventWasHandled && !ignoreFailure) { throw new _error2.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) { let state = emberRouter._routerMicrolib.applyIntent(leafRouteName, contexts); let { routeInfos, params } = state; for (let i = 0; i < routeInfos.length; ++i) { let routeInfo = routeInfos[i]; // If the routeInfo is not resolved, we serialize the context into params if (!routeInfo.isResolved) { params[routeInfo.name] = routeInfo.serialize(routeInfo.context); } else { params[routeInfo.name] = routeInfo.params; } } return state; } function updatePaths(router) { let infos = router._routerMicrolib.currentRouteInfos; if (infos.length === 0) { return; } let path = EmberRouter._routePath(infos); let currentRouteName = infos[infos.length - 1].name; let currentURL = router.get('location').getURL(); (0, _metal.set)(router, 'currentPath', path); (0, _metal.set)(router, 'currentRouteName', currentRouteName); (0, _metal.set)(router, 'currentURL', currentURL); let appController = (0, _owner.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)) { (0, _metal.defineProperty)(appController, 'currentPath'); } (0, _metal.set)(appController, 'currentPath', path); if (!('currentRouteName' in appController)) { (0, _metal.defineProperty)(appController, 'currentRouteName'); } (0, _metal.set)(appController, 'currentRouteName', currentRouteName); } EmberRouter.reopenClass({ /** 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. ```app/router.js 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](https://guides.emberjs.com/release/routing/defining-your-routes/). @method map @param callback @public */ map(callback) { if (!this.dslCallbacks) { this.dslCallbacks = []; this.reopenClass({ dslCallbacks: this.dslCallbacks }); } this.dslCallbacks.push(callback); return this; }, _routePath(routeInfos) { let 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 (let i = 0; i < a1.length; ++i) { if (a1[i] !== a2[i]) { return false; } } return true; } let name, nameParts, oldNameParts; for (let i = 1; i < routeInfos.length; i++) { name = routeInfos[i].name; nameParts = name.split('.'); oldNameParts = slice.call(path); while (oldNameParts.length) { if (intersectionMatches(oldNameParts, nameParts)) { break; } oldNameParts.shift(); } path.push(...nameParts.slice(oldNameParts.length)); } return path.join('.'); } }); function didBeginTransition(transition, router) { let routerState = new _router_state.default(router, router._routerMicrolib, transition[_router_js.STATE_SYMBOL]); if (!router.currentState) { router.set('currentState', routerState); } router.set('targetState', routerState); transition.promise = transition.catch(error => { if (router._isErrorHandled(error)) { router._clearHandledError(error); } else { throw error; } }, 'Transition Error'); } function forEachQueryParam(router, routeInfos, queryParams, callback) { let qpCache = router._queryParamsFor(routeInfos); for (let key in queryParams) { if (!queryParams.hasOwnProperty(key)) { continue; } let value = queryParams[key]; let qp = qpCache.map[key]; callback(key, value, qp); } } function findLiveRoute(liveRoutes, name) { if (!liveRoutes) { return; } let stack = [liveRoutes]; while (stack.length > 0) { let test = stack.shift(); if (test.render.name === name) { return test; } let outlets = test.outlets; for (let outletName in outlets) { stack.push(outlets[outletName]); } } return; } function appendLiveRoute(liveRoutes, defaultParentState, renderOptions) { let target; let myState = { render: renderOptions, outlets: Object.create(null), wasUsed: false }; if (renderOptions.into) { target = findLiveRoute(liveRoutes, renderOptions.into); } else { target = defaultParentState; } if (target) { (0, _metal.set)(target.outlets, renderOptions.outlet, myState); } else { liveRoutes = myState; } return { liveRoutes, ownState: myState }; } function representEmptyRoute(liveRoutes, defaultParentState, route) { // the route didn't render anything let 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; } } EmberRouter.reopen(_runtime.Evented, { /** 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 import config from './config/environment'; import EmberRouter from '@ember/routing/router'; let Router = EmberRouter.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: defaultDidTransition, /** Handles notifying any listeners of an impending URL change. Triggers the router level `willTransition` hook. @method willTransition @public @since 1.11.0 */ willTransition: defaultWillTransition, /** 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: '/', /** 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 capabilities: `history` if possible, then `hash` if possible, otherwise `none` This value is defaulted to `auto` by the `locationType` setting of `/config/environment.js` @property location @default 'hash' @see {Location} @public */ location: 'hash', /** Represents the current URL. @method url @return {String} The current URL. @private */ url: (0, _metal.computed)(function () { return (0, _metal.get)(this, 'location').getURL(); }) }); if (true /* EMBER_ROUTING_ROUTER_SERVICE */ && _deprecatedFeatures.ROUTER_EVENTS) { EmberRouter.reopen(_route.ROUTER_EVENT_DEPRECATIONS); } exports.default = EmberRouter; }); enifed('@ember/-internals/routing/lib/system/router_state', ['exports', '@ember/polyfills', '@ember/-internals/routing/lib/utils'], function (exports, _polyfills, _utils) { 'use strict'; class RouterState { constructor(emberRouter, router, routerJsState) { this.emberRouter = emberRouter; this.router = router; this.routerJsState = routerJsState; } isActiveIntent(routeName, models, queryParams, queryParamsMustMatch) { let state = this.routerJsState; if (!this.router.isActiveIntent(routeName, models, undefined, state)) { return false; } if (queryParamsMustMatch && Object.keys(queryParams).length > 0) { let visibleQueryParams = (0, _polyfills.assign)({}, queryParams); this.emberRouter._prepareQueryParams(routeName, models, visibleQueryParams); return (0, _utils.shallowEqual)(visibleQueryParams, state.queryParams); } return true; } } exports.default = RouterState; }); enifed("@ember/-internals/routing/lib/system/transition", [], function () { "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 @public */ /** 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 */ /** 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 */ /** 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 */ /** 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 */ /** 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 */ /** 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 */ /** 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 */ /** 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 */ /** 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 */ /** * This property is a `RouteInfo` object that represents * where the router is transitioning to. It's important * to note that a `RouteInfo` is a linked list and this * property is simply represents leafmost route. * @property {RouteInfo|RouteInfoWithAttributes} to * @public * @category ember-routing-router-service */ /** * This property is a `RouteInfo` object that represents * where transition originated from. It's important * to note that a `RouteInfo` is a linked list and this * property is simply represents head node of the list. * In the case of an initial render, from will be set to * `null`. * @property {RouteInfoWithAttributes} from * @public * @category ember-routing-router-service */ /** 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 */ }); enifed('@ember/-internals/routing/lib/utils', ['exports', '@ember/-internals/metal', '@ember/-internals/owner', '@ember/error', '@ember/polyfills', 'router_js'], function (exports, _metal, _owner, _error, _polyfills, _router_js) { 'use strict'; exports.extractRouteArgs = extractRouteArgs; exports.getActiveTargetName = getActiveTargetName; exports.stashParamNames = stashParamNames; exports.calculateCacheKey = calculateCacheKey; exports.normalizeControllerQueryParams = normalizeControllerQueryParams; exports.resemblesURL = resemblesURL; exports.prefixRouteNameArg = prefixRouteNameArg; exports.shallowEqual = shallowEqual; const ALL_PERIODS_REGEX = /\./g; function extractRouteArgs(args) { args = args.slice(); let possibleQueryParams = args[args.length - 1]; let queryParams; if (possibleQueryParams && possibleQueryParams.hasOwnProperty('queryParams')) { queryParams = args.pop().queryParams; } else { queryParams = {}; } let routeName = args.shift(); return { routeName, models: args, queryParams }; } function getActiveTargetName(router) { let routeInfos = router.activeTransition ? router.activeTransition[_router_js.STATE_SYMBOL].routeInfos : router.state.routeInfos; return routeInfos[routeInfos.length - 1].name; } function stashParamNames(router, routeInfos) { if (routeInfos['_namesStashed']) { return; } // This helper exists because router.js/route-recognizer.js awkwardly // keeps separate a routeInfo's list of parameter names depending // on whether a URL transition or named transition is happening. // Hopefully we can remove this in the future. let targetRouteName = routeInfos[routeInfos.length - 1].name; let recogHandlers = router._routerMicrolib.recognizer.handlersFor(targetRouteName); let dynamicParent; for (let i = 0; i < routeInfos.length; ++i) { let routeInfo = routeInfos[i]; let names = recogHandlers[i].names; if (names.length) { dynamicParent = routeInfo; } routeInfo['_names'] = names; let route = routeInfo.route; route._stashNames(routeInfo, dynamicParent); } routeInfos['_namesStashed'] = true; } function _calculateCacheValuePrefix(prefix, part) { // calculates the dot separated 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) let prefixParts = prefix.split('.'); let currPrefix = ''; for (let i = 0; i < prefixParts.length; i++) { let 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) { let suffixes = ''; for (let i = 0; i < parts.length; ++i) { let part = parts[i]; let cacheValuePrefix = _calculateCacheValuePrefix(prefix, part); let value; if (values) { if (cacheValuePrefix && cacheValuePrefix in values) { let partRemovedPrefix = part.indexOf(cacheValuePrefix) === 0 ? part.substr(cacheValuePrefix.length + 1) : part; value = (0, _metal.get)(values[cacheValuePrefix], partRemovedPrefix); } else { value = (0, _metal.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) { let qpMap = {}; for (let i = 0; i < queryParams.length; ++i) { accumulateQueryParamDescriptors(queryParams[i], qpMap); } return qpMap; } function accumulateQueryParamDescriptors(_desc, accum) { let desc = _desc; let tmp; if (typeof desc === 'string') { tmp = {}; tmp[desc] = { as: null }; desc = tmp; } for (let key in desc) { if (!desc.hasOwnProperty(key)) { return; } let singleDesc = desc[key]; if (typeof singleDesc === 'string') { singleDesc = { as: singleDesc }; } tmp = accum[key] || { as: null, scope: 'model' }; (0, _polyfills.assign)(tmp, singleDesc); accum[key] = tmp; } } /* Check if a routeName resembles a url instead @private */ function resemblesURL(str) { return typeof str === 'string' && (str === '' || str[0] === '/'); } /* Returns an arguments array where the route name arg is prefixed based on the mount point @private */ function prefixRouteNameArg(route, args) { let routeName = args[0]; let owner = (0, _owner.getOwner)(route); let 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 _error.default('Programmatic transitions by URL cannot be used within an Engine. Please use the route name instead.'); } else { routeName = `${prefix}.${routeName}`; args[0] = routeName; } } return args; } function shallowEqual(a, b) { let k; let aCount = 0; let bCount = 0; for (k in a) { if (a.hasOwnProperty(k)) { if (a[k] !== b[k]) { return false; } aCount++; } } for (k in b) { if (b.hasOwnProperty(k)) { bCount++; } } return aCount === bCount; } }); enifed('@ember/-internals/runtime/index', ['exports', '@ember/-internals/runtime/lib/system/object', '@ember/-internals/runtime/lib/mixins/registry_proxy', '@ember/-internals/runtime/lib/mixins/container_proxy', '@ember/-internals/runtime/lib/copy', '@ember/-internals/runtime/lib/compare', '@ember/-internals/runtime/lib/is-equal', '@ember/-internals/runtime/lib/mixins/array', '@ember/-internals/runtime/lib/mixins/comparable', '@ember/-internals/runtime/lib/system/namespace', '@ember/-internals/runtime/lib/system/array_proxy', '@ember/-internals/runtime/lib/system/object_proxy', '@ember/-internals/runtime/lib/system/core_object', '@ember/-internals/runtime/lib/mixins/action_handler', '@ember/-internals/runtime/lib/mixins/copyable', '@ember/-internals/runtime/lib/mixins/enumerable', '@ember/-internals/runtime/lib/mixins/-proxy', '@ember/-internals/runtime/lib/mixins/observable', '@ember/-internals/runtime/lib/mixins/mutable_enumerable', '@ember/-internals/runtime/lib/mixins/target_action_support', '@ember/-internals/runtime/lib/mixins/evented', '@ember/-internals/runtime/lib/mixins/promise_proxy', '@ember/-internals/runtime/lib/ext/rsvp', '@ember/-internals/runtime/lib/type-of', '@ember/-internals/runtime/lib/ext/function'], function (exports, _object, _registry_proxy, _container_proxy, _copy, _compare, _isEqual, _array, _comparable, _namespace, _array_proxy, _object_proxy, _core_object, _action_handler, _copyable, _enumerable, _proxy, _observable, _mutable_enumerable, _target_action_support, _evented, _promise_proxy, _rsvp, _typeOf) { 'use strict'; exports.typeOf = exports.onerrorDefault = exports.RSVP = exports.PromiseProxyMixin = exports.Evented = exports.TargetActionSupport = exports.MutableEnumerable = exports.Observable = exports._contentFor = exports._ProxyMixin = exports.Enumerable = exports.Copyable = exports.ActionHandler = exports.CoreObject = exports.ObjectProxy = exports.ArrayProxy = exports.Namespace = exports.Comparable = exports.isArray = exports.uniqBy = exports.removeAt = exports.MutableArray = exports.A = exports.NativeArray = exports.isEmberArray = exports.Array = exports.isEqual = exports.compare = exports.copy = exports.ContainerProxyMixin = exports.RegistryProxyMixin = exports.FrameworkObject = exports.Object = undefined; Object.defineProperty(exports, 'Object', { enumerable: true, get: function () { return _object.default; } }); Object.defineProperty(exports, 'FrameworkObject', { enumerable: true, get: function () { return _object.FrameworkObject; } }); Object.defineProperty(exports, 'RegistryProxyMixin', { enumerable: true, get: function () { return _registry_proxy.default; } }); Object.defineProperty(exports, 'ContainerProxyMixin', { enumerable: true, get: function () { return _container_proxy.default; } }); Object.defineProperty(exports, 'copy', { enumerable: true, get: function () { return _copy.default; } }); Object.defineProperty(exports, 'compare', { enumerable: true, get: function () { return _compare.default; } }); Object.defineProperty(exports, 'isEqual', { enumerable: true, get: function () { return _isEqual.default; } }); Object.defineProperty(exports, 'Array', { enumerable: true, get: function () { return _array.default; } }); Object.defineProperty(exports, 'isEmberArray', { enumerable: true, get: function () { return _array.isEmberArray; } }); Object.defineProperty(exports, 'NativeArray', { enumerable: true, get: function () { return _array.NativeArray; } }); Object.defineProperty(exports, 'A', { enumerable: true, get: function () { return _array.A; } }); Object.defineProperty(exports, 'MutableArray', { enumerable: true, get: function () { return _array.MutableArray; } }); Object.defineProperty(exports, 'removeAt', { enumerable: true, get: function () { return _array.removeAt; } }); Object.defineProperty(exports, 'uniqBy', { enumerable: true, get: function () { return _array.uniqBy; } }); Object.defineProperty(exports, 'isArray', { enumerable: true, get: function () { return _array.isArray; } }); Object.defineProperty(exports, 'Comparable', { enumerable: true, get: function () { return _comparable.default; } }); Object.defineProperty(exports, 'Namespace', { enumerable: true, get: function () { return _namespace.default; } }); Object.defineProperty(exports, 'ArrayProxy', { enumerable: true, get: function () { return _array_proxy.default; } }); Object.defineProperty(exports, 'ObjectProxy', { enumerable: true, get: function () { return _object_proxy.default; } }); Object.defineProperty(exports, 'CoreObject', { enumerable: true, get: function () { return _core_object.default; } }); Object.defineProperty(exports, 'ActionHandler', { enumerable: true, get: function () { return _action_handler.default; } }); Object.defineProperty(exports, 'Copyable', { enumerable: true, get: function () { return _copyable.default; } }); Object.defineProperty(exports, 'Enumerable', { enumerable: true, get: function () { return _enumerable.default; } }); Object.defineProperty(exports, '_ProxyMixin', { enumerable: true, get: function () { return _proxy.default; } }); Object.defineProperty(exports, '_contentFor', { enumerable: true, get: function () { return _proxy.contentFor; } }); Object.defineProperty(exports, 'Observable', { enumerable: true, get: function () { return _observable.default; } }); Object.defineProperty(exports, 'MutableEnumerable', { enumerable: true, get: function () { return _mutable_enumerable.default; } }); Object.defineProperty(exports, 'TargetActionSupport', { enumerable: true, get: function () { return _target_action_support.default; } }); Object.defineProperty(exports, 'Evented', { enumerable: true, get: function () { return _evented.default; } }); Object.defineProperty(exports, 'PromiseProxyMixin', { enumerable: true, get: function () { return _promise_proxy.default; } }); Object.defineProperty(exports, 'RSVP', { enumerable: true, get: function () { return _rsvp.default; } }); Object.defineProperty(exports, 'onerrorDefault', { enumerable: true, get: function () { return _rsvp.onerrorDefault; } }); Object.defineProperty(exports, 'typeOf', { enumerable: true, get: function () { return _typeOf.typeOf; } }); }); enifed('@ember/-internals/runtime/lib/compare', ['exports', '@ember/-internals/runtime/lib/type-of', '@ember/-internals/runtime/lib/mixins/comparable'], function (exports, _typeOf, _comparable) { 'use strict'; exports.default = compare; const 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) { let diff = a - b; return (diff > 0) - (diff < 0); } /** @module @ember/utils */ /** 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 import { compare } from '@ember/utils'; compare('hello', 'hello'); // 0 compare('abc', 'dfg'); // -1 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 import { compare } from '@ember/utils'; compare('hello', 50); // 1 compare(50, 'hello'); // -1 ``` @method compare @for @ember/utils @static @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; } let type1 = (0, _typeOf.typeOf)(v); let type2 = (0, _typeOf.typeOf)(w); if (type1 === 'instance' && _comparable.default.detect(v) && v.constructor.compare) { return v.constructor.compare(v, w); } if (type2 === 'instance' && _comparable.default.detect(w) && w.constructor.compare) { return w.constructor.compare(w, v) * -1; } let 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': { let vLen = v.length; let wLen = w.length; let len = Math.min(vLen, wLen); for (let i = 0; i < len; i++) { let 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 (_comparable.default.detect(v)) { return v.compare(v, w); } return 0; case 'date': return spaceship(v.getTime(), w.getTime()); default: return 0; } } }); enifed('@ember/-internals/runtime/lib/copy', ['exports', '@ember/debug', '@ember/-internals/runtime/lib/system/object', '@ember/-internals/runtime/lib/mixins/copyable'], function (exports, _debug, _object, _copyable) { 'use strict'; exports.default = copy; /** @module @ember/object */ function _copy(obj, deep, seen, copies) { // primitive data types are immutable, just return them. if (typeof obj !== 'object' || obj === null) { return obj; } let ret, loc; // avoid cyclical loops if (deep && (loc = seen.indexOf(obj)) >= 0) { return copies[loc]; } if (deep) { seen.push(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) { copies.push(ret); loc = ret.length; while (--loc >= 0) { ret[loc] = _copy(ret[loc], deep, seen, copies); } } } else if (_copyable.default.detect(obj)) { ret = obj.copy(deep, seen, copies); if (deep) { copies.push(ret); } } else if (obj instanceof Date) { ret = new Date(obj.getTime()); if (deep) { copies.push(ret); } } else { true && !(!(obj instanceof _object.default) || _copyable.default.detect(obj)) && (0, _debug.assert)('Cannot clone an EmberObject that does not implement Copyable', !(obj instanceof _object.default) || _copyable.default.detect(obj)); ret = {}; if (deep) { copies.push(ret); } let key; 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]; } } 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 `Copyable` interface, then this function will delegate to the object's `copy()` method and return the result. See `Copyable` for further details. For primitive values (which are immutable in JavaScript), the passed object is simply returned. @method copy @deprecated Use 'ember-copy' addon instead @static @for @ember/object/internals @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) { true && !false && (0, _debug.deprecate)('Use ember-copy addon instead of copy method and Copyable mixin.', false, { id: 'ember-runtime.deprecate-copy-copyable', until: '4.0.0', url: 'https://emberjs.com/deprecations/v3.x/#toc_ember-runtime-deprecate-copy-copyable' }); // fast paths if ('object' !== typeof obj || obj === null) { return obj; // can't copy primitives } if (!Array.isArray(obj) && _copyable.default.detect(obj)) { return obj.copy(deep); } return _copy(obj, deep, deep ? [] : null, deep ? [] : null); } }); enifed('@ember/-internals/runtime/lib/ext/function', ['@ember/-internals/environment', '@ember/-internals/metal'], function (_environment, _metal) { 'use strict'; /** @module ember */ if (_environment.ENV.EXTEND_PROTOTYPES.Function) { Object.defineProperties(Function.prototype, { /** 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: ```app/utils/president.js import EmberObject from '@ember/object'; export default EmberObject.extend({ firstName: '', lastName: '', fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); }.property() // Call this flag to mark the function as a property }); ``` ```javascript let president = 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: ```app/utils/president.js import EmberObject from '@ember/object'; export default EmberObject.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 [ComputedProperty](/api/ember/release/classes/ComputedProperty), [@ember/object/computed](/api/ember/release/classes/@ember%2Fobject%2Fcomputed). @method property @for Function @public */ property: { configurable: true, enumerable: false, writable: true, value: function () { return (0, _metal.computed)(...arguments, this); } }, /** 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 import EmberObject from '@ember/object'; EmberObject.extend({ valueObserver: function() { // Executes whenever the "value" property changes }.observes('value') }); ``` In the future this method may become asynchronous. See `observer`. @method observes @for Function @public */ observes: { configurable: true, enumerable: false, writable: true, value: function () { return (0, _metal.observer)(...arguments, this); } }, /** 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 import Mixin from '@ember/mixin'; Mixin.create({ doSomethingWithElement: function() { // Executes whenever the "didInsertElement" event fires }.on('didInsertElement') }); ``` See `@ember/object/evented/on`. @method on @for Function @public */ on: { configurable: true, enumerable: false, writable: true, value: function () { return (0, _metal.on)(...arguments, this); } } }); } }); enifed('@ember/-internals/runtime/lib/ext/rsvp', ['exports', 'rsvp', '@ember/runloop', '@ember/-internals/error-handling', '@ember/debug'], function (exports, _rsvp, _runloop, _errorHandling, _debug) { 'use strict'; exports.onerrorDefault = onerrorDefault; _rsvp.configure('async', (callback, promise) => { _runloop.backburner.schedule('actions', null, callback, promise); }); _rsvp.configure('after', cb => { _runloop.backburner.schedule(_runloop._rsvpErrorQueue, null, cb); }); _rsvp.on('error', onerrorDefault); function onerrorDefault(reason) { let error = errorFor(reason); if (error) { let overrideDispatch = (0, _errorHandling.getDispatchOverride)(); if (overrideDispatch) { overrideDispatch(error); } else { throw error; } } } function errorFor(reason) { if (!reason) return; if (reason.errorThrown) { return unwrapErrorThrown(reason); } if (reason.name === 'UnrecognizedURLError') { true && !false && (0, _debug.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) { let 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/-internals/runtime/lib/is-equal', ['exports'], function (exports) { 'use strict'; exports.default = isEqual; /** @module @ember/utils */ /** Compares two objects, returning true if they are equal. ```javascript import { isEqual } from '@ember/utils'; isEqual('hello', 'hello'); // true 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 import { isEqual } from '@ember/utils'; import EmberObject from '@ember/object'; let Person = EmberObject.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'}); 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 import { isEqual } from '@ember/utils'; isEqual([4, 2], [4, 2]); // false ``` @method isEqual @for @ember/utils @static @param {Object} a first object to compare @param {Object} b second object to compare @return {Boolean} @public */ 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/-internals/runtime/lib/mixins/-proxy', ['exports', '@glimmer/reference', '@ember/-internals/meta', '@ember/-internals/metal', '@ember/-internals/utils', '@ember/debug'], function (exports, _reference, _meta, _metal, _utils, _debug) { 'use strict'; exports.contentFor = contentFor; function contentPropertyDidChange(content, contentKey) { let key = contentKey.slice(8); // remove "content." if (key in this) { return; } // if shadowed in proxy (0, _metal.notifyPropertyChange)(this, key); } /** @module ember */ function contentFor(proxy, m) { let content = (0, _metal.get)(proxy, 'content'); let tag = (m === undefined ? (0, _meta.meta)(proxy) : m).readableTag(); if (tag !== undefined) { tag.inner.second.inner.update((0, _metal.tagFor)(content)); } return content; } /** `Ember.ProxyMixin` forwards all properties not defined by the proxy itself to a proxied `content` object. See ObjectProxy for more details. @class ProxyMixin @namespace Ember @private */ exports.default = _metal.Mixin.create({ /** The object whose properties will be forwarded. @property content @type EmberObject @default null @private */ content: null, init() { this._super(...arguments); (0, _utils.setProxy)(this); let m = (0, _meta.meta)(this); m.writableTag(() => (0, _reference.combine)([_reference.DirtyableTag.create(), _reference.UpdatableTag.create(_reference.CONSTANT_TAG)])); }, willDestroy() { this.set('content', null); this._super(...arguments); }, isTruthy: (0, _metal.computed)('content', function () { return !!(0, _metal.get)(this, 'content'); }), willWatchProperty(key) { let contentKey = `content.${key}`; (0, _metal.addObserver)(this, contentKey, null, contentPropertyDidChange); }, didUnwatchProperty(key) { let contentKey = `content.${key}`; (0, _metal.removeObserver)(this, contentKey, null, contentPropertyDidChange); }, unknownProperty(key) { let content = contentFor(this); if (content) { return (0, _metal.get)(content, key); } }, setUnknownProperty(key, value) { let m = (0, _meta.meta)(this); if (m.isInitializing() || m.isPrototypeMeta(this)) { // if marked as prototype or object is initializing then just // defineProperty rather than delegate (0, _metal.defineProperty)(this, key, null, value); return value; } let content = contentFor(this, m); true && !content && (0, _debug.assert)(`Cannot delegate set('${key}', ${value}) to the \'content\' property of object proxy ${this}: its 'content' is undefined.`, content); return (0, _metal.set)(content, key, value); } }); }); enifed('@ember/-internals/runtime/lib/mixins/action_handler', ['exports', '@ember/-internals/metal', '@ember/debug'], function (exports, _metal, _debug) { 'use strict'; /** `Ember.ActionHandler` is available on some familiar classes including `Route`, `Component`, and `Controller`. (Internally the mixin is used by `Ember.CoreView`, `Ember.ControllerMixin`, and `Route` and available to the above classes through inheritance.) @class ActionHandler @namespace Ember @private */ /** @module ember */ const ActionHandler = _metal.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.: ```app/mixins/can-display-banner.js import Mixin from '@ember/mixin'; export default Mixin.create({ actions: { displayBanner(msg) { // ... } } }); ``` ```app/routes/welcome.js import Route from '@ember/routing/route'; import CanDisplayBanner from '../mixins/can-display-banner'; export default Route.extend(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 or Component's action handler, the value of the `this` context is the Controller, Route or Component object: ```app/routes/song.js import Route from '@ember/routing/route'; export default 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: ```app/mixins/debug-route.js import Mixin from '@ember/mixin'; export default Mixin.create({ actions: { debugRouteInformation() { console.debug("It's a-me, console.debug!"); } } }); ``` ```app/routes/annoying-debug.js import Route from '@ember/routing/route'; import DebugRoute from '../mixins/debug-route'; export default Route.extend(DebugRoute, { actions: { debugRouteInformation() { // also call the debugRouteInformation of mixed in 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: ```app/router.js Router.map(function() { this.route("album", function() { this.route("song"); }); }); ``` ```app/routes/album.js import Route from '@ember/routing/route'; export default Route.extend({ actions: { startPlaying: function() { } } }); ``` ```app/routes/album-song.js import Route from '@ember/routing/route'; export default 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 ```app/routes/welcome.js import Route from '@ember/routing/route'; export default 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(actionName, ...args) { true && !(!this.isDestroying && !this.isDestroyed) && (0, _debug.assert)(`Attempted to call .send() with the action '${actionName}' on the destroyed object '${this}'.`, !this.isDestroying && !this.isDestroyed); if (this.actions && this.actions[actionName]) { let shouldBubble = this.actions[actionName].apply(this, args) === true; if (!shouldBubble) { return; } } let target = (0, _metal.get)(this, 'target'); if (target) { true && !(typeof target.send === 'function') && (0, _debug.assert)(`The \`target\` for ${this} (${target}) does not have a \`send\` method`, typeof target.send === 'function'); target.send(...arguments); } } }); exports.default = ActionHandler; }); enifed('@ember/-internals/runtime/lib/mixins/array', ['exports', '@ember/deprecated-features', '@ember/-internals/metal', '@ember/-internals/utils', '@ember/debug', '@ember/-internals/runtime/lib/mixins/enumerable', '@ember/-internals/runtime/lib/compare', '@ember/-internals/environment', '@ember/-internals/runtime/lib/mixins/observable', '@ember/-internals/runtime/lib/copy', '@ember/-internals/runtime/lib/mixins/mutable_enumerable', '@ember/-internals/runtime/lib/type-of'], function (exports, _deprecatedFeatures, _metal, _utils, _debug, _enumerable, _compare, _environment, _observable, _copy, _mutable_enumerable, _typeOf) { 'use strict'; exports.MutableArray = exports.NativeArray = exports.A = undefined; exports.isEmberArray = isEmberArray; exports.uniqBy = uniqBy; exports.removeAt = removeAt; exports.isArray = isArray; /** @module @ember/array */ const EMPTY_ARRAY = Object.freeze([]); const EMBER_ARRAY = (0, _utils.symbol)('EMBER_ARRAY'); function isEmberArray(obj) { return obj && obj[EMBER_ARRAY]; } const identityFunction = item => item; function uniqBy(array, key = identityFunction) { true && !isArray(array) && (0, _debug.assert)(`first argument passed to \`uniqBy\` should be array`, isArray(array)); let ret = A(); let seen = new Set(); let getter = typeof key === 'function' ? key : item => (0, _metal.get)(item, key); array.forEach(item => { let val = getter(item); if (!seen.has(val)) { seen.add(val); ret.push(item); } }); return ret; } function iter(key, value) { let valueProvided = arguments.length === 2; return valueProvided ? item => value === (0, _metal.get)(item, key) : item => !!(0, _metal.get)(item, key); } function findIndex(array, predicate, startAt) { let len = array.length; for (let index = startAt; index < len; index++) { let item = (0, _metal.objectAt)(array, index); if (predicate(item, index, array)) { return index; } } return -1; } function find(array, callback, target) { let predicate = callback.bind(target); let index = findIndex(array, predicate, 0); return index === -1 ? undefined : (0, _metal.objectAt)(array, index); } function any(array, callback, target) { let predicate = callback.bind(target); return findIndex(array, predicate, 0) !== -1; } function every(array, callback, target) { let cb = callback.bind(target); let predicate = (item, index, array) => !cb(item, index, array); return findIndex(array, predicate, 0) === -1; } function indexOf(array, val, startAt = 0, withNaNCheck) { let len = array.length; if (startAt < 0) { startAt += len; } // SameValueZero comparison (NaN !== NaN) let predicate = withNaNCheck && val !== val ? item => item !== item : item => item === val; return findIndex(array, predicate, startAt); } function removeAt(array, index, len = 1) { true && !(index > -1 && index < array.length) && (0, _debug.assert)(`\`removeAt\` index provided is out of range`, index > -1 && index < array.length); (0, _metal.replace)(array, index, len, EMPTY_ARRAY); return array; } function insertAt(array, index, item) { true && !(index > -1 && index <= array.length) && (0, _debug.assert)(`\`insertAt\` index provided is out of range`, index > -1 && index <= array.length); (0, _metal.replace)(array, index, 0, [item]); return item; } /** 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 `typeOf` this method returns true even if the passed object is not formally an array but appears to be array-like (i.e. implements `Array`) ```javascript import { isArray } from '@ember/array'; import ArrayProxy from '@ember/array/proxy'; isArray(); // false isArray([]); // true isArray(ArrayProxy.create({ content: [] })); // true ``` @method isArray @static @for @ember/array @param {Object} obj The object to test @return {Boolean} true if the passed object is an array or Array-like @public */ function isArray(_obj) { let obj = _obj; if (true /* DEBUG */ && _utils.HAS_NATIVE_PROXY && typeof _obj === 'object' && _obj !== null) { let possibleProxyContent = _obj[_metal.PROXY_CONTENT]; if (possibleProxyContent !== undefined) { obj = possibleProxyContent; } } if (!obj || obj.setInterval) { return false; } if (Array.isArray(obj) || ArrayMixin.detect(obj)) { return true; } let type = (0, _typeOf.typeOf)(obj); if ('array' === type) { return true; } let length = obj.length; if (typeof length === 'number' && length === length && 'object' === type) { return true; } return false; } // .......................................................... // 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. 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 `EmberArray` in your own class, you must override two primitives to use it: `length()` and `objectAt()`. @class EmberArray @uses Enumerable @since Ember 0.9.0 @public */ const ArrayMixin = _metal.Mixin.create(_enumerable.default, { [EMBER_ARRAY]: true, /** __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 `EmberArray`. 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 */ objectsAt(indexes) { return indexes.map(idx => (0, _metal.objectAt)(this, idx)); }, /** 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. @property [] @return this @public */ '[]': (0, _metal.computed)({ get() { return this; }, set(key, value) { this.replace(0, this.length, value); return this; } }), /** The first object in the array, or `undefined` if the array is empty. @property firstObject @return {Object | undefined} The first object in the array @public */ firstObject: (0, _metal.computed)(function () { return (0, _metal.objectAt)(this, 0); }).readOnly(), /** The last object in the array, or `undefined` if the array is empty. @property lastObject @return {Object | undefined} The last object in the array @public */ lastObject: (0, _metal.computed)(function () { return (0, _metal.objectAt)(this, this.length - 1); }).readOnly(), // Add any extra methods to EmberArray 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 */ slice(beginIndex = 0, endIndex) { let ret = A(); let length = this.length; if (beginIndex < 0) { beginIndex = length + beginIndex; } if (endIndex === undefined || endIndex > length) { endIndex = length; } else if (endIndex < 0) { endIndex = length + endIndex; } while (beginIndex < endIndex) { ret[ret.length] = (0, _metal.objectAt)(this, beginIndex++); } return ret; }, /** 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 */ indexOf(object, startAt) { return indexOf(this, object, startAt, false); }, /** 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 */ lastIndexOf(object, startAt) { let len = this.length; if (startAt === undefined || startAt >= len) { startAt = len - 1; } if (startAt < 0) { startAt += len; } for (let idx = startAt; idx >= 0; idx--) { if ((0, _metal.objectAt)(this, idx) === object) { return idx; } } return -1; }, // .......................................................... // ARRAY OBSERVERS // /** Adds an array observer to the receiving array. The array observer object normally must implement two methods: * `willChange(observedObj, start, removeCount, addCount)` - This method will be called just before the array is modified. * `didChange(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 {EmberArray} receiver @public */ addArrayObserver(target, opts) { return (0, _metal.addArrayObserver)(this, target, opts); }, /** 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 {EmberArray} receiver @public */ removeArrayObserver(target, opts) { return (0, _metal.removeArrayObserver)(this, target, opts); }, /** Becomes true whenever the array currently has observers watching changes on the array. @property {Boolean} hasArrayObservers @public */ hasArrayObservers: (0, _metal.computed)(function () { return (0, _metal.hasListeners)(this, '@array:change') || (0, _metal.hasListeners)(this, '@array:before'); }), /** If you are implementing an object that supports `EmberArray`, 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 {EmberArray} receiver @public */ arrayContentWillChange(startIdx, removeAmt, addAmt) { return (0, _metal.arrayContentWillChange)(this, startIdx, removeAmt, addAmt); }, /** If you are implementing an object that supports `EmberArray`, 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 {EmberArray} receiver @public */ arrayContentDidChange(startIdx, removeAmt, addAmt) { return (0, _metal.arrayContentDidChange)(this, startIdx, removeAmt, addAmt); }, /** Iterates through the array, 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, array); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `array` is the array 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(callback, target = null) { true && !(typeof callback === 'function') && (0, _debug.assert)('`forEach` expects a function as first argument.', typeof callback === 'function'); let length = this.length; for (let index = 0; index < length; index++) { let item = this.objectAt(index); callback.call(target, item, index, this); } return this; }, /** Alias for `mapBy` @method getEach @param {String} key name of the property @return {Array} The mapped array. @public */ getEach: (0, _metal.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 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(key, value) { return this.forEach(item => (0, _metal.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, array); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `array` is the array 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(callback, target = null) { true && !(typeof callback === 'function') && (0, _debug.assert)('`map` expects a function as first argument.', typeof callback === 'function'); let ret = A(); this.forEach((x, idx, i) => 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(key) { return this.map(next => (0, _metal.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, array); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `array` is the array 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(callback, target = null) { true && !(typeof callback === 'function') && (0, _debug.assert)('`filter` expects a function as first argument.', typeof callback === 'function'); let ret = A(); this.forEach((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, array); ``` - *item* is the current item in the iteration. - *index* is the current index in the iteration - *array* is the array 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(callback, target = null) { true && !(typeof callback === 'function') && (0, _debug.assert)('`reject` expects a function as first argument.', typeof callback === 'function'); 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() { return this.filter(iter(...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 {*} [value] optional value to test against. @return {Array} rejected array @public */ rejectBy() { return this.reject(iter(...arguments)); }, /** Returns the first item in the array for which the callback returns true. This method is similar to the `find()` method defined in ECMAScript 2015. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, array); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `array` is the array 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(callback, target = null) { true && !(typeof callback === 'function') && (0, _debug.assert)('`find` expects a function as first argument.', typeof callback === 'function'); return find(this, callback, target); }, /** 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() { return find(this, iter(...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, array); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `array` is the array 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(callback, target = null) { true && !(typeof callback === 'function') && (0, _debug.assert)('`every` expects a function as first argument.', typeof callback === 'function'); return every(this, callback, target); }, /** Returns `true` if the passed property resolves to the value of the second argument for all items in the array. This method is often simpler/faster than using a callback. Note that like the native `Array.every`, `isEvery` will return true when called on any empty array. @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() { return every(this, iter(...arguments)); }, /** Returns `true` if the passed function returns true for any item in the enumeration. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(item, index, array); ``` - `item` is the current item in the iteration. - `index` is the current index in the iteration. - `array` is the array object itself. It must return a truthy value (i.e. `true`) to include an item in the results. Any non-truthy return value will discard the item from 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. 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(callback, target = null) { true && !(typeof callback === 'function') && (0, _debug.assert)('`any` expects a function as first argument.', typeof callback === 'function'); return any(this, callback, target); }, /** Returns `true` if the passed property resolves to the value of the second argument for any item in the array. 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() { return any(this, iter(...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, array); ``` - `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. - `array` is the array 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 @return {Object} The reduced value. @public */ reduce(callback, initialValue) { true && !(typeof callback === 'function') && (0, _debug.assert)('`reduce` expects a function as first argument.', typeof callback === 'function'); let ret = initialValue; this.forEach(function (item, i) { ret = callback(ret, item, i, this); }, 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(methodName, ...args) { let ret = A(); this.forEach(item => ret.push((0, _utils.tryInvoke)(item, methodName, args))); return ret; }, /** Simply converts the object into a genuine array. The order is not guaranteed. Corresponds to the method implemented by Prototype. @method toArray @return {Array} the object as an array. @public */ toArray() { return this.map(item => item); }, /** 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() { return this.filter(value => value != null); }, /** 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} object 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(object, startAt) { return indexOf(this, object, startAt, true) !== -1; }, /** Sorts the array by the keys specified in the argument. You may provide multiple arguments to sort by multiple properties. ```javascript let colors = [{name: 'red'}, {name: 'green'}, {name: 'blue'}]; colors.sortBy('name'); // [{name: 'blue'}, {name: 'green'}, {name: 'red'}] ``` @method sortBy @param {String} property name(s) to sort on @return {Array} The sorted array. @since 1.2.0 @public */ sortBy() { let sortKeys = arguments; return this.toArray().sort((a, b) => { for (let i = 0; i < sortKeys.length; i++) { let key = sortKeys[i]; let propA = (0, _metal.get)(a, key); let propB = (0, _metal.get)(b, key); // return 1 or -1 else continue to the next sortKey let compareValue = (0, _compare.default)(propA, propB); if (compareValue) { return compareValue; } } return 0; }); }, /** Returns a new array 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 {EmberArray} @public */ uniq() { return uniqBy(this); }, /** Returns a new array 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' }] let arr = [2.2, 2.1, 3.2, 3.3]; arr.uniqBy(Math.floor); // [2.2, 3.2]; ``` @method uniqBy @param {String,Function} key @return {EmberArray} @public */ uniqBy(key) { return uniqBy(this, key); }, /** Returns a new array 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 array. ```javascript let arr = ['a', 'b', 'a', 'c']; arr.without('a'); // ['b', 'c'] ``` @method without @param {Object} value @return {EmberArray} @public */ without(value) { if (!this.includes(value)) { return this; // nothing to do } // SameValueZero comparison (NaN !== NaN) let predicate = value === value ? item => item !== value : item => item === item; return this.filter(predicate); }, /** 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 array 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 @deprecated @public */ '@each': _deprecatedFeatures.ARRAY_AT_EACH ? (0, _metal.computed)(function () { true && !false && (0, _debug.deprecate)(`Getting the '@each' property on object ${(0, _utils.toString)(this)} is deprecated`, false, { id: 'ember-metal.getting-each', until: '3.5.0', url: 'https://emberjs.com/deprecations/v3.x#toc_getting-the-each-property' }); return (0, _metal.eachProxyFor)(this); }).readOnly() : undefined }); /** 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 @uses EmberArray @uses MutableEnumerable @public */ const MutableArray = _metal.Mixin.create(ArrayMixin, _mutable_enumerable.default, { /** __Required.__ You must implement this method to apply this mixin. This is one of the primitives you must implement to support `Array`. You should replace amt objects started at idx with the objects in the passed array. You should also call `this.arrayContentDidChange()` Note that this method is expected to validate the type(s) of objects that it expects. @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 {EmberArray} objects An array of zero or more objects that should be inserted into the array at *idx* @public */ /** 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']; colors.length; // 3 colors.clear(); // [] colors.length; // 0 ``` @method clear @return {Array} An empty Array. @public */ clear() { let len = this.length; if (len === 0) { return this; } this.replace(0, len, EMPTY_ARRAY); 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 {EmberArray} receiver @public */ insertAt(idx, object) { insertAt(this, idx, 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 assertion. ```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 {EmberArray} receiver @public */ removeAt(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(obj) { return insertAt(this, this.length, obj); }, /** Add the objects in the passed array 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 {EmberArray} objects the objects to add @return {EmberArray} receiver @public */ pushObjects(objects) { this.replace(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() { let len = this.length; if (len === 0) { return null; } let ret = (0, _metal.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() { if (this.length === 0) { return null; } let ret = (0, _metal.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(obj) { return insertAt(this, 0, 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 {Enumberable} objects the objects to add @return {EmberArray} receiver @public */ unshiftObjects(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 {EmberArray} receiver @public */ reverseObjects() { let len = this.length; if (len === 0) { return this; } let 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 {EmberArray} objects array whose content will be used for replacing the content of the receiver @return {EmberArray} receiver with the new content @public */ setObjects(objects) { if (objects.length === 0) { return this.clear(); } let len = this.length; this.replace(0, len, objects); return this; }, /** 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 {EmberArray} receiver @public */ removeObject(obj) { let loc = this.length || 0; while (--loc >= 0) { let curObject = (0, _metal.objectAt)(this, loc); if (curObject === obj) { this.removeAt(loc); } } return this; }, /** Removes each object in the passed array from the receiver. @method removeObjects @param {EmberArray} objects the objects to remove @return {EmberArray} receiver @public */ removeObjects(objects) { (0, _metal.beginPropertyChanges)(); for (let i = objects.length - 1; i >= 0; i--) { this.removeObject(objects[i]); } (0, _metal.endPropertyChanges)(); 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 {EmberArray} receiver @public */ addObject(obj) { let included = this.includes(obj); if (!included) { this.pushObject(obj); } return this; }, /** Adds each object in the passed array to the receiver. @method addObjects @param {EmberArray} objects the objects to add. @return {EmberArray} receiver @public */ addObjects(objects) { (0, _metal.beginPropertyChanges)(); objects.forEach(obj => this.addObject(obj)); (0, _metal.endPropertyChanges)(); return this; } }); /** Creates an `Ember.NativeArray` from an Array-like object. Does not modify the original object's contents. `A()` is not needed if `EmberENV.EXTEND_PROTOTYPES` is `true` (the default value). However, it is recommended that you use `A()` when creating addons for ember or when you can not guarantee that `EmberENV.EXTEND_PROTOTYPES` will be `true`. Example ```app/components/my-component.js import Component from '@ember/component'; import { A } from '@ember/array'; export default Component.extend({ tagName: 'ul', classNames: ['pagination'], init() { this._super(...arguments); if (!this.get('content')) { this.set('content', A()); this.set('otherContent', A([1,2,3])); } } }); ``` @method A @static @for @ember/array @return {Ember.NativeArray} @public */ // 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. /** @module ember */ /** The NativeArray mixin contains the properties needed to make the native Array support 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 Ember.NativeArray @uses MutableArray @uses Observable @public */ let NativeArray = _metal.Mixin.create(MutableArray, _observable.default, { objectAt(idx) { return this[idx]; }, // primitive for array support. replace(start, deleteCount, items = EMPTY_ARRAY) { true && !Array.isArray(items) && (0, _debug.assert)('The third argument to replace needs to be an array.', Array.isArray(items)); (0, _metal.replaceInNativeArray)(this, start, deleteCount, items); return this; }, copy(deep) { true && !false && (0, _debug.deprecate)(`Using \`NativeArray#copy\` is deprecated`, false, { id: 'ember-runtime.using-array-copy', until: '3.5.0' }); if (deep) { return this.map(item => (0, _copy.default)(item, true)); } return this.slice(); } }); // Remove any methods implemented natively so we don't override them const ignore = ['length']; NativeArray.keys().forEach(methodName => { if (Array.prototype[methodName]) { ignore.push(methodName); } }); exports.NativeArray = NativeArray = NativeArray.without(...ignore); let A; if (_environment.ENV.EXTEND_PROTOTYPES.Array) { NativeArray.apply(Array.prototype); exports.A = A = function (arr) { true && !!(this instanceof A) && (0, _debug.deprecate)('`new A()` has been deprecated, please update to calling A as a function: `A()`', !(this instanceof A), { id: 'array.new-array-wrapper', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_array-new-array-wrapper' }); return arr || []; }; } else { exports.A = A = function (arr) { true && !!(this instanceof A) && (0, _debug.deprecate)('`new A()` has been deprecated, please update to calling A as a function: `A()`', !(this instanceof A), { id: 'array.new-array-wrapper', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_array-new-array-wrapper' }); if (!arr) { arr = []; } return ArrayMixin.detect(arr) ? arr : NativeArray.apply(arr); }; } exports.A = A; exports.NativeArray = NativeArray; exports.MutableArray = MutableArray; exports.default = ArrayMixin; }); enifed('@ember/-internals/runtime/lib/mixins/comparable', ['exports', '@ember/-internals/metal'], function (exports, _metal) { 'use strict'; exports.default = _metal.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/-internals/runtime/lib/mixins/container_proxy', ['exports', '@ember/runloop', '@ember/-internals/metal'], function (exports, _runloop, _metal) { 'use strict'; /** ContainerProxyMixin is used to provide public access to specific container functionality. @class ContainerProxyMixin @private */ let containerProxyMixin = { /** 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: ``` import { getOwner } from '@ember/application'; let owner = getOwner(this); User.create( owner.ownerInjection(), { username: 'rwjblue' } ) ``` @public @method ownerInjection @since 2.3.0 @return {Object} */ ownerInjection() { return this.__container__.ownerInjection(); }, /** Given a fullName return a corresponding instance. The default behavior 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(fullName, options) { return this.__container__.lookup(fullName, options); }, destroy() { let container = this.__container__; if (container) { (0, _runloop.join)(() => { container.destroy(); (0, _runloop.schedule)('destroy', container, 'finalizeDestroy'); }); } this._super(); }, /** Given a fullName return a factory manager. This method returns a manager which can be used for introspection of the factory's class or for the creation of factory instances with initial properties. The manager is an object with the following properties: * `class` - The registered or resolved class. * `create` - A function that will create an instance of the class with any dependencies injected. For example: ```javascript import { getOwner } from '@ember/application'; let owner = getOwner(otherInstance); // the owner is commonly the `applicationInstance`, and can be accessed via // an instance initializer. let factory = owner.factoryFor('service:bespoke'); factory.class; // The registered or resolved class. For example when used with an Ember-CLI // app, this would be the default export from `app/services/bespoke.js`. let instance = factory.create({ someProperty: 'an initial property value' }); // Create an instance with any injections and the passed options as // initial properties. ``` @public @method factoryFor @param {String} fullName @param {Object} options @return {FactoryManager} */ factoryFor(fullName, options = {}) { return this.__container__.factoryFor(fullName, options); } }; /** @module ember */ exports.default = _metal.Mixin.create(containerProxyMixin); }); enifed('@ember/-internals/runtime/lib/mixins/copyable', ['exports', '@ember/-internals/metal'], function (exports, _metal) { 'use strict'; exports.default = _metal.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 }); }); enifed('@ember/-internals/runtime/lib/mixins/enumerable', ['exports', '@ember/-internals/metal'], function (exports, _metal) { 'use strict'; exports.default = _metal.Mixin.create(); }); enifed('@ember/-internals/runtime/lib/mixins/evented', ['exports', '@ember/-internals/metal'], function (exports, _metal) { 'use strict'; exports.default = _metal.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(name, target, method) { (0, _metal.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(name, target, method) { if (!method) { method = target; target = null; } (0, _metal.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(name, ...args) { (0, _metal.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(name, target, method) { (0, _metal.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(name) { return (0, _metal.hasListeners)(this, name); } }); }); enifed('@ember/-internals/runtime/lib/mixins/mutable_enumerable', ['exports', '@ember/-internals/runtime/lib/mixins/enumerable', '@ember/-internals/metal'], function (exports, _enumerable, _metal) { 'use strict'; exports.default = _metal.Mixin.create(_enumerable.default); }); enifed('@ember/-internals/runtime/lib/mixins/observable', ['exports', '@ember/-internals/metal', '@ember/debug'], function (exports, _metal, _debug) { 'use strict'; exports.default = _metal.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 import { computed } from '@ember/object'; fullName: computed('firstName', 'lastName', function() { return this.get('firstName') + ' ' + this.get('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(keyName) { return (0, _metal.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(...args) { return (0, _metal.getProperties)(...[this].concat(args)); }, /** Sets the provided key or path to the value. ```javascript record.set("key", 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(keyName, value) { return (0, _metal.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(hash) { return (0, _metal.setProperties)(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 {Observable} @private */ beginPropertyChanges() { (0, _metal.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 {Observable} @private */ endPropertyChanges() { (0, _metal.endPropertyChanges)(); return this; }, /** @method propertyWillChange @private */ propertyWillChange(keyName) { (0, _metal.propertyWillChange)(this, keyName); return this; }, /** @method propertyDidChange @private */ propertyDidChange(keyName) { (0, _metal.propertyDidChange)(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 instead. Calling this method will notify all observers that the property has potentially changed value. @method notifyPropertyChange @param {String} keyName The property key to be notified about. @return {Observable} @public */ notifyPropertyChange(keyName) { (0, _metal.notifyPropertyChange)(this, 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. ### Observer Methods Observer methods have the following signature: ```app/components/my-component.js import Component from '@ember/component'; export default Component.extend({ init() { this._super(...arguments); this.addObserver('foo', this, 'fooDidChange'); }, fooDidChange(sender, key, value, rev) { // your code } }); ``` 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. Usually you will not need the value 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 observe @param {Object} target The target object to invoke @param {String|Function} method The method to invoke @return {Observable} @public */ addObserver(key, target, method) { (0, _metal.addObserver)(this, key, target, method); return this; }, /** 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 observe @param {Object} target The target object to invoke @param {String|Function} method The method to invoke @return {Observable} @public */ removeObserver(key, target, method) { (0, _metal.removeObserver)(this, key, target, method); return this; }, /** 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(key) { return (0, _metal.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(keyName, defaultValue) { return (0, _metal.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(keyName, increment = 1) { true && !(!isNaN(parseFloat(increment)) && isFinite(increment)) && (0, _debug.assert)('Must pass a numeric value to incrementProperty', !isNaN(parseFloat(increment)) && isFinite(increment)); return (0, _metal.set)(this, keyName, (parseFloat((0, _metal.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(keyName, decrement = 1) { true && !(!isNaN(parseFloat(decrement)) && isFinite(decrement)) && (0, _debug.assert)('Must pass a numeric value to decrementProperty', !isNaN(parseFloat(decrement)) && isFinite(decrement)); return (0, _metal.set)(this, keyName, ((0, _metal.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(keyName) { return (0, _metal.set)(this, keyName, !(0, _metal.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(keyName) { return (0, _metal.getCachedValueFor)(this, keyName); } }); }); enifed('@ember/-internals/runtime/lib/mixins/promise_proxy', ['exports', '@ember/-internals/metal', '@ember/error'], function (exports, _metal, _error) { 'use strict'; /** @module @ember/object */ function tap(proxy, promise) { (0, _metal.setProperties)(proxy, { isFulfilled: false, isRejected: false }); return promise.then(value => { if (!proxy.isDestroyed && !proxy.isDestroying) { (0, _metal.setProperties)(proxy, { content: value, isFulfilled: true }); } return value; }, reason => { if (!proxy.isDestroyed && !proxy.isDestroying) { (0, _metal.setProperties)(proxy, { reason, isRejected: true }); } throw reason; }, 'Ember: PromiseProxy'); } /** A low level mixin making ObjectProxy promise-aware. ```javascript import { resolve } from 'rsvp'; import $ from 'jquery'; import ObjectProxy from '@ember/object/proxy'; import PromiseProxyMixin from '@ember/object/promise-proxy-mixin'; let ObjectPromiseProxy = ObjectProxy.extend(PromiseProxyMixin); let proxy = ObjectPromiseProxy.create({ promise: resolve($.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.resolve` 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 PromiseProxyMixin @public */ exports.default = _metal.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: (0, _metal.computed)('isSettled', function () { return !(0, _metal.get)(this, 'isSettled'); }).readOnly(), /** Once the proxied promise has settled this will become `true`. @property isSettled @default false @public */ isSettled: (0, _metal.computed)('isRejected', 'isFulfilled', function () { return (0, _metal.get)(this, 'isRejected') || (0, _metal.get)(this, '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 import ObjectProxy from '@ember/object/proxy'; import PromiseProxyMixin from '@ember/object/promise-proxy-mixin'; ObjectProxy.extend(PromiseProxyMixin).create({ promise: }); ``` @property promise @public */ promise: (0, _metal.computed)({ get() { throw new _error.default("PromiseProxy's promise must be set"); }, set(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 () { let promise = (0, _metal.get)(this, 'promise'); return promise[name](...arguments); }; } }); enifed('@ember/-internals/runtime/lib/mixins/registry_proxy', ['exports', '@ember/debug', '@ember/-internals/metal'], function (exports, _debug, _metal) { 'use strict'; exports.default = _metal.Mixin.create({ __registry__: null, /** Given a fullName return the corresponding factory. @public @method resolveRegistration @param {String} fullName @return {Function} fullName's factory */ resolveRegistration(fullName, options) { true && !this.__registry__.isValidFullName(fullName) && (0, _debug.assert)('fullName must be a proper full name', this.__registry__.isValidFullName(fullName)); return this.__registry__.resolve(fullName, options); }, /** 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 import Application from '@ember/application'; import EmberObject from '@ember/object'; let App = Application.create(); App.Orange = EmberObject.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 import Application from '@ember/application'; import Controller from '@ember/controller'; let App = Application.create(); let Session = 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 = 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 import Application from '@ember/application'; import EmberObject from '@ember/object'; let App = Application.create(); App.Person = EmberObject.extend(); App.Orange = EmberObject.extend(); App.Email = EmberObject.extend(); App.session = EmberObject.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 import Application from '@ember/application'; import EmberObject from '@ember/object'; let App = Application.create(); let User = EmberObject.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'), /** 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 import Application from '@ember/application'; let App = Application.create(); let appInstance = App.buildInstance(); // if all of type `connection` must not be singletons appInstance.registerOptionsForType('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 import { alias } from '@ember/object/computed'; import Application from '@ember/application'; import Controller from '@ember/controller'; import EmberObject from '@ember/object'; let App = Application.create(); let Session = EmberObject.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 = Controller.extend({ isLoggedIn: alias('session.isAuthenticated') }); ``` Injections can also be performed on specific factories. ```javascript App.inject(, , ) 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. @public @method inject @param factoryNameOrType {String} @param property {String} @param injectionName {String} **/ inject: registryAlias('injection') }); function registryAlias(name) { return function () { return this.__registry__[name](...arguments); }; } }); enifed('@ember/-internals/runtime/lib/mixins/target_action_support', ['exports', '@ember/-internals/environment', '@ember/-internals/metal', '@ember/debug', '@ember/deprecated-features'], function (exports, _environment, _metal, _debug, _deprecatedFeatures) { 'use strict'; exports.default = _metal.Mixin.create({ target: null, targetObject: _deprecatedFeatures.TARGET_OBJECT ? (0, _metal.descriptor)({ configurable: true, enumerable: false, get() { let message = `${this} Usage of \`targetObject\` is deprecated. Please use \`target\` instead.`; let options = { id: 'ember-runtime.using-targetObject', until: '3.5.0' }; true && !false && (0, _debug.deprecate)(message, false, options); return this._targetObject; }, set(value) { let message = `${this} Usage of \`targetObject\` is deprecated. Please use \`target\` instead.`; let options = { id: 'ember-runtime.using-targetObject', until: '3.5.0' }; true && !false && (0, _debug.deprecate)(message, false, options); this._targetObject = value; } }) : undefined, action: null, actionContext: null, actionContextObject: (0, _metal.computed)('actionContext', function () { let actionContext = (0, _metal.get)(this, 'actionContext'); if (typeof actionContext === 'string') { let value = (0, _metal.get)(this, actionContext); if (value === undefined) { value = (0, _metal.get)(_environment.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 import { alias } from '@ember/object/computed'; App.SaveButtonView = Ember.View.extend(Ember.TargetActionSupport, { target: alias('controller'), action: 'save', actionContext: 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 import { alias } from '@ember/object/computed'; App.SaveButtonView = Ember.View.extend(Ember.TargetActionSupport, { target: 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(opts = {}) { let { action, target, actionContext } = opts; action = action || (0, _metal.get)(this, 'action'); target = target || getTarget(this); if (actionContext === undefined) { actionContext = (0, _metal.get)(this, 'actionContextObject') || this; } if (target && action) { let ret; if (target.send) { ret = target.send(...[action].concat(actionContext)); } else { true && !(typeof target[action] === 'function') && (0, _debug.assert)(`The action '${action}' did not exist on ${target}`, typeof target[action] === 'function'); ret = target[action](...[].concat(actionContext)); } if (ret !== false) { return true; } } return false; } }); function getTarget(instance) { let target = (0, _metal.get)(instance, 'target'); if (target) { if (typeof target === 'string') { let value = (0, _metal.get)(instance, target); if (value === undefined) { value = (0, _metal.get)(_environment.context.lookup, target); } return value; } else { return target; } } // if a `targetObject` CP was provided, use it if (target) { return target; } // if _targetObject use it if (_deprecatedFeatures.TARGET_OBJECT && instance._targetObject) { return instance._targetObject; } return null; } }); enifed('@ember/-internals/runtime/lib/system/array_proxy', ['exports', '@ember/-internals/metal', '@ember/-internals/runtime/lib/system/object', '@ember/-internals/runtime/lib/mixins/array', '@ember/debug'], function (exports, _metal, _object, _array, _debug) { 'use strict'; /** @module @ember/array */ const ARRAY_OBSERVER_MAPPING = { willChange: '_arrangedContentArrayWillChange', didChange: '_arrangedContentArrayDidChange' }; /** An ArrayProxy wraps any other object that implements `Array` and/or `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 import { A } from '@ember/array'; import ArrayProxy from '@ember/array/proxy'; let pets = ['dog', 'cat', 'fish']; let ap = ArrayProxy.create({ content: 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 import { A } from '@ember/array'; import ArrayProxy from '@ember/array/proxy'; let pets = ['dog', 'cat', 'fish']; let ap = ArrayProxy.create({ content: A(pets), objectAtContent: function(idx) { return this.get('content').objectAt(idx).toUpperCase(); } }); ap.get('firstObject'); // . 'DOG' ``` When overriding this class, it is important to place the call to `_super` *after* setting `content` so the internal observers have a chance to fire properly: ```javascript import { A } from '@ember/array'; import ArrayProxy from '@ember/array/proxy'; export default ArrayProxy.extend({ init() { this.set('content', A(['dog', 'cat', 'fish'])); this._super(...arguments); } }); ``` @class ArrayProxy @extends EmberObject @uses MutableArray @public */ class ArrayProxy extends _object.default { init() { super.init(...arguments); /* `this._objectsDirtyIndex` determines which indexes in the `this._objects` cache are dirty. If `this._objectsDirtyIndex === -1` then no indexes are dirty. Otherwise, an index `i` is dirty if `i >= this._objectsDirtyIndex`. Calling `objectAt` with a dirty index will cause the `this._objects` cache to be recomputed. */ this._objectsDirtyIndex = 0; this._objects = null; this._lengthDirty = true; this._length = 0; this._arrangedContent = null; this._addArrangedContentArrayObsever(); } willDestroy() { this._removeArrangedContentArrayObsever(); } /** The content array. Must be an object that implements `Array` and/or `MutableArray.` @property content @type EmberArray @public */ /** 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 @public */ objectAtContent(idx) { return (0, _metal.objectAt)((0, _metal.get)(this, 'arrangedContent'), idx); } // See additional docs for `replace` from `MutableArray`: // https://www.emberjs.com/api/ember/3.3/classes/MutableArray/methods/replace?anchor=replace replace(idx, amt, objects) { true && !((0, _metal.get)(this, 'arrangedContent') === (0, _metal.get)(this, 'content')) && (0, _debug.assert)('Mutating an arranged ArrayProxy is not allowed', (0, _metal.get)(this, 'arrangedContent') === (0, _metal.get)(this, 'content')); this.replaceContent(idx, amt, objects); } /** 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 {EmberArray} objects Optional array of objects to insert or null if no objects. @return {void} @public */ replaceContent(idx, amt, objects) { (0, _metal.get)(this, 'content').replace(idx, amt, objects); } // Overriding objectAt is not supported. objectAt(idx) { if (this._objects === null) { this._objects = []; } if (this._objectsDirtyIndex !== -1 && idx >= this._objectsDirtyIndex) { let arrangedContent = (0, _metal.get)(this, 'arrangedContent'); if (arrangedContent) { let length = this._objects.length = (0, _metal.get)(arrangedContent, 'length'); for (let i = this._objectsDirtyIndex; i < length; i++) { this._objects[i] = this.objectAtContent(i); } } else { this._objects.length = 0; } this._objectsDirtyIndex = -1; } return this._objects[idx]; } // Overriding length is not supported. get length() { if (this._lengthDirty) { let arrangedContent = (0, _metal.get)(this, 'arrangedContent'); this._length = arrangedContent ? (0, _metal.get)(arrangedContent, 'length') : 0; this._lengthDirty = false; } return this._length; } set length(value) { let length = this.length; let removedCount = length - value; let added; if (removedCount === 0) { return; } else if (removedCount < 0) { added = new Array(-removedCount); removedCount = 0; } let content = (0, _metal.get)(this, 'content'); if (content) { (0, _metal.replace)(content, value, removedCount, added); this._invalidate(); } } [_metal.PROPERTY_DID_CHANGE](key) { if (key === 'arrangedContent') { let oldLength = this._objects === null ? 0 : this._objects.length; let arrangedContent = (0, _metal.get)(this, 'arrangedContent'); let newLength = arrangedContent ? (0, _metal.get)(arrangedContent, 'length') : 0; this._removeArrangedContentArrayObsever(); this.arrayContentWillChange(0, oldLength, newLength); this._invalidate(); this.arrayContentDidChange(0, oldLength, newLength); this._addArrangedContentArrayObsever(); } else if (key === 'content') { this._invalidate(); } } _addArrangedContentArrayObsever() { let arrangedContent = (0, _metal.get)(this, 'arrangedContent'); if (arrangedContent) { true && !(arrangedContent !== this) && (0, _debug.assert)("Can't set ArrayProxy's content to itself", arrangedContent !== this); true && !((0, _array.isArray)(arrangedContent) || arrangedContent.isDestroyed) && (0, _debug.assert)(`ArrayProxy expects an Array or ArrayProxy, but you passed ${typeof arrangedContent}`, (0, _array.isArray)(arrangedContent) || arrangedContent.isDestroyed); (0, _metal.addArrayObserver)(arrangedContent, this, ARRAY_OBSERVER_MAPPING); this._arrangedContent = arrangedContent; } } _removeArrangedContentArrayObsever() { if (this._arrangedContent) { (0, _metal.removeArrayObserver)(this._arrangedContent, this, ARRAY_OBSERVER_MAPPING); } } _arrangedContentArrayWillChange() {} _arrangedContentArrayDidChange(proxy, idx, removedCnt, addedCnt) { this.arrayContentWillChange(idx, removedCnt, addedCnt); let dirtyIndex = idx; if (dirtyIndex < 0) { let length = (0, _metal.get)(this._arrangedContent, 'length'); dirtyIndex += length + removedCnt - addedCnt; } if (this._objectsDirtyIndex === -1) { this._objectsDirtyIndex = dirtyIndex; } else { if (this._objectsDirtyIndex > dirtyIndex) { this._objectsDirtyIndex = dirtyIndex; } } this._lengthDirty = true; this.arrayContentDidChange(idx, removedCnt, addedCnt); } _invalidate() { this._objectsDirtyIndex = 0; this._lengthDirty = true; } } exports.default = ArrayProxy; ArrayProxy.reopen(_array.MutableArray, { /** 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 @public */ arrangedContent: (0, _metal.alias)('content') }); }); enifed('@ember/-internals/runtime/lib/system/core_object', ['exports', '@ember/-internals/container', '@ember/polyfills', '@ember/-internals/utils', '@ember/runloop', '@ember/-internals/meta', '@ember/-internals/metal', '@ember/-internals/runtime/lib/mixins/action_handler', '@ember/debug'], function (exports, _container, _polyfills, _utils, _runloop, _meta, _metal, _action_handler, _debug) { 'use strict'; /** @module @ember/object */ const reopen = _metal.Mixin.prototype.reopen; const wasApplied = new _polyfills._WeakSet(); const factoryMap = new WeakMap(); const prototypeMixinMap = new WeakMap(); const DELAY_INIT = Object.freeze({}); let initCalled; // only used in debug builds to enable the proxy trap // using DEBUG here to avoid the extraneous variable when not needed if (true /* DEBUG */) { initCalled = new _polyfills._WeakSet(); } function initialize(obj, properties) { let m = (0, _meta.meta)(obj); if (properties !== undefined) { true && !(typeof properties === 'object' && properties !== null) && (0, _debug.assert)('EmberObject.create only accepts objects.', typeof properties === 'object' && properties !== null); true && !!(properties instanceof _metal.Mixin) && (0, _debug.assert)('EmberObject.create no longer supports mixing in other ' + 'definitions, use .extend & .create separately instead.', !(properties instanceof _metal.Mixin)); let concatenatedProperties = obj.concatenatedProperties; let mergedProperties = obj.mergedProperties; let hasConcatenatedProps = concatenatedProperties !== undefined && concatenatedProperties.length > 0; let hasMergedProps = mergedProperties !== undefined && mergedProperties.length > 0; let keyNames = Object.keys(properties); for (let i = 0; i < keyNames.length; i++) { let keyName = keyNames[i]; let value = properties[keyName]; true && !!(value instanceof _metal.ComputedProperty) && (0, _debug.assert)('EmberObject.create no longer supports defining computed ' + 'properties. Define computed properties using extend() or reopen() ' + 'before calling create().', !(value instanceof _metal.ComputedProperty)); true && !!(typeof value === 'function' && value.toString().indexOf('._super') !== -1) && (0, _debug.assert)('EmberObject.create no longer supports defining methods that call _super.', !(typeof value === 'function' && value.toString().indexOf('._super') !== -1)); true && !!(keyName === 'actions' && _action_handler.default.detect(obj)) && (0, _debug.assert)('`actions` must be provided at extend time, not at create time, ' + 'when Ember.ActionHandler is used (i.e. views, controllers & routes).', !(keyName === 'actions' && _action_handler.default.detect(obj))); let possibleDesc = (0, _meta.descriptorFor)(obj, keyName, m); let isDescriptor = possibleDesc !== undefined; if (!isDescriptor) { let baseValue = obj[keyName]; if (hasConcatenatedProps && concatenatedProperties.indexOf(keyName) > -1) { if (baseValue) { value = (0, _utils.makeArray)(baseValue).concat(value); } else { value = (0, _utils.makeArray)(value); } } if (hasMergedProps && mergedProperties.indexOf(keyName) > -1) { value = (0, _polyfills.assign)({}, baseValue, value); } } if (isDescriptor) { possibleDesc.set(obj, keyName, value); } else if (typeof obj.setUnknownProperty === 'function' && !(keyName in obj)) { obj.setUnknownProperty(keyName, value); } else { if (true /* DEBUG */) { (0, _metal.defineProperty)(obj, keyName, null, value, m); // setup mandatory setter } else { obj[keyName] = value; } } } } // using DEBUG here to avoid the extraneous variable when not needed if (true /* DEBUG */) { initCalled.add(obj); } obj.init(properties); // re-enable chains m.unsetInitializing(); (0, _metal.finishChains)(m); (0, _metal.sendEvent)(obj, 'init', undefined, undefined, undefined, m); } /** @class CoreObject @public */ class CoreObject { static _initFactory(factory) { factoryMap.set(this, factory); } constructor(properties) { // pluck off factory let initFactory = factoryMap.get(this.constructor); if (initFactory !== undefined) { factoryMap.delete(this.constructor); _container.FACTORY_FOR.set(this, initFactory); } // prepare prototype... this.constructor.proto(); let self = this; if (true /* DEBUG */ && _utils.HAS_NATIVE_PROXY && typeof self.unknownProperty === 'function') { let messageFor = (obj, property) => { return `You attempted to access the \`${String(property)}\` property (of ${obj}).\n` + `Since Ember 3.1, this is usually fine as you no longer need to use \`.get()\`\n` + `to access computed properties. However, in this case, the object in question\n` + `is a special kind of Ember object (a proxy). Therefore, it is still necessary\n` + `to use \`.get('${String(property)}')\` in this case.\n\n` + `If you encountered this error because of third-party code that you don't control,\n` + `there is more information at https://github.com/emberjs/ember.js/issues/16148, and\n` + `you can help us improve this error message by telling us more about what happened in\n` + `this situation.`; }; /* globals Proxy Reflect */ self = new Proxy(this, { get(target, property, receiver) { if (property === _metal.PROXY_CONTENT) { return target; } else if ( // init called will be set on the proxy, not the target, so get with the receiver !initCalled.has(receiver) || typeof property === 'symbol' || (0, _utils.isInternalSymbol)(property) || property === 'toJSON' || property === 'toString' || property === 'toStringExtension' || property === 'didDefineProperty' || property === 'willWatchProperty' || property === 'didUnwatchProperty' || property === 'didAddListener' || property === 'didRemoveListener' || property === 'isDescriptor' || property === '_onLookup' || property in target) { return Reflect.get(target, property, receiver); } let value = target.unknownProperty.call(receiver, property); if (typeof value !== 'function') { true && !(value === undefined || value === null) && (0, _debug.assert)(messageFor(receiver, property), value === undefined || value === null); } } }); _container.FACTORY_FOR.set(self, initFactory); } // disable chains let m = (0, _meta.meta)(self); m.setInitializing(); if (properties !== DELAY_INIT) { true && !false && (0, _debug.deprecate)('using `new` with EmberObject has been deprecated. Please use `create` instead, or consider using native classes without extending from EmberObject.', false, { id: 'object.new-constructor', until: '3.9.0', url: 'https://emberjs.com/deprecations/v3.x#toc_object-new-constructor' }); initialize(self, properties); } // only return when in debug builds and `self` is the proxy created above if (true /* DEBUG */ && self !== this) { return self; } } reopen(...args) { (0, _metal.applyMixin)(this, args); return this; } /** An overridable method called when objects are instantiated. By default, does nothing unless it is overridden during class definition. Example: ```javascript import EmberObject from '@ember/object'; const Person = EmberObject.extend({ init() { alert(`Name is ${this.get('name')}`); } }); let steve = 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() {} /** 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 import EmberObject from '@ember/object'; const Bar = EmberObject.extend({ // Configure which properties to concatenate concatenatedProperties: ['concatenatedProperty'], someNonConcatenatedProperty: ['bar'], concatenatedProperty: ['bar'] }); const FooBar = Bar.extend({ someNonConcatenatedProperty: ['foo'], concatenatedProperty: ['foo'] }); let fooBar = FooBar.create(); fooBar.get('someNonConcatenatedProperty'); // ['foo'] fooBar.get('concatenatedProperty'); // ['bar', 'foo'] ``` This behavior extends to object creation as well. Continuing the above example: ```javascript let fooBar = FooBar.create({ someNonConcatenatedProperty: ['baz'], concatenatedProperty: ['baz'] }) fooBar.get('someNonConcatenatedProperty'); // ['baz'] fooBar.get('concatenatedProperty'); // ['bar', 'foo', 'baz'] ``` Adding a single property that is not an array will just add it in the array: ```javascript let fooBar = FooBar.create({ concatenatedProperty: 'baz' }) view.get('concatenatedProperty'); // ['bar', 'foo', 'baz'] ``` Using the `concatenatedProperties` property, we can tell Ember to mix the content of the properties. In `Component` the `classNames`, `classNameBindings` and `attributeBindings` properties are concatenated. 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 import EmberObject from '@ember/object'; const Bar = EmberObject.extend({ // Configure which properties are to be merged mergedProperties: ['mergedProperty'], someNonMergedProperty: { nonMerged: 'superclass value of nonMerged' }, mergedProperty: { page: { replace: false }, limit: { replace: true } } }); const FooBar = Bar.extend({ someNonMergedProperty: { completelyNonMerged: 'subclass value of nonMerged' }, mergedProperty: { limit: { replace: false } } }); let fooBar = FooBar.create(); fooBar.get('someNonMergedProperty'); // => { completelyNonMerged: 'subclass value of nonMerged' } // // Note the entire object, including the nonMerged property of // the superclass object, has been replaced fooBar.get('mergedProperty'); // => { // 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. In `Route` the `queryParams` property is merged. 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 */ get isDestroyed() { return (0, _meta.peekMeta)(this).isSourceDestroyed(); } set isDestroyed(value) { true && !false && (0, _debug.assert)(`You cannot set \`${this}.isDestroyed\` directly, please use \`.destroy()\`.`, false); } /** 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 */ get isDestroying() { return (0, _meta.peekMeta)(this).isSourceDestroying(); } set isDestroying(value) { true && !false && (0, _debug.assert)(`You cannot set \`${this}.isDestroying\` directly, please use \`.destroy()\`.`, false); } /** 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 {EmberObject} receiver @public */ destroy() { let m = (0, _meta.peekMeta)(this); if (m.isSourceDestroying()) { return; } m.setSourceDestroying(); (0, _runloop.schedule)('actions', this, this.willDestroy); (0, _runloop.schedule)('destroy', this, this._scheduledDestroy, m); return this; } /** Override to implement teardown. @method willDestroy @public */ willDestroy() {} /** Invoked by the run loop to actually destroy the object. This is scheduled for execution by the `destroy` method. @private @method _scheduledDestroy */ _scheduledDestroy(m) { if (m.isSourceDestroyed()) { return; } (0, _meta.deleteMeta)(this); m.setSourceDestroyed(); } /** 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 import EmberObject from '@ember/object'; const Person = EmberObject.extend(); person = Person.create(); person.toString(); //=> "" ``` If the object's class is not defined on an Ember namespace, it will indicate it is a subclass of the registered superclass: ```javascript const Student = Person.extend(); let student = Student.create(); student.toString(); //=> "<(subclass of Person):ember1025>" ``` If the method `toStringExtension` is defined, its return value will be included in the output. ```javascript const Teacher = Person.extend({ toStringExtension() { return this.get('fullName'); } }); teacher = Teacher.create(); teacher.toString(); //=> "" ``` @method toString @return {String} string representation @public */ toString() { let hasToStringExtension = typeof this.toStringExtension === 'function'; let extension = hasToStringExtension ? `:${this.toStringExtension()}` : ''; let ret = `<${(0, _utils.getName)(this) || _container.FACTORY_FOR.get(this) || this.constructor.toString()}:${(0, _utils.guidFor)(this)}${extension}>`; return ret; } /** Creates a new subclass. ```javascript import EmberObject from '@ember/object'; const Person = EmberObject.extend({ say(thing) { alert(thing); } }); ``` This defines a new subclass of EmberObject: `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 `Component` class: ```javascript import Component from '@ember/component'; const PersonComponent = Component.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 import EmberObject from '@ember/object'; const Person = EmberObject.extend({ say(thing) { let name = this.get('name'); alert(`${name} says: ${thing}`); } }); const Soldier = Person.extend({ say(thing) { this._super(`${thing}, sir!`); }, march(numberOfHours) { alert(`${this.get('name')} marches for ${numberOfHours} hours.`); } }); let yehuda = Soldier.create({ name: 'Yehuda Katz' }); yehuda.say('Yes'); // alerts "Yehuda Katz says: Yes, sir!" ``` The `create()` on line #17 creates an *instance* of the `Soldier` class. The `extend()` on line #8 creates a *subclass* of `Person`. Any instance of the `Person` class will *not* have the `march()` method. You can also pass `Mixin` classes to add additional properties to the subclass. ```javascript import EmberObject from '@ember/object'; import Mixin from '@ember/object/mixin'; const Person = EmberObject.extend({ say(thing) { alert(`${this.get('name')} says: ${thing}`); } }); const SingingMixin = Mixin.create({ sing(thing) { alert(`${this.get('name')} sings: la la la ${thing}`); } }); const BroadwayStar = Person.extend(SingingMixin, { dance() { alert(`${this.get('name')} dances: tap tap tap tap `); } }); ``` The `BroadwayStar` class contains three methods: `say()`, `sing()`, and `dance()`. @method extend @static @for @ember/object @param {Mixin} [mixins]* One or more Mixin classes @param {Object} [arguments]* Object containing values to use within the new class @public */ static extend() { let Class = class extends this {}; reopen.apply(Class.PrototypeMixin, arguments); 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 import EmberObject from '@ember/object'; const Person = EmberObject.extend({ helloWorld() { alert(`Hi, my name is ${this.get('name')}`); } }); let tom = Person.create({ name: 'Tom Dale' }); tom.helloWorld(); // alerts "Hi, my name is Tom Dale". ``` `create` will call the `init` function if defined during `AnyObject.extend` If no arguments are passed to `create`, it will not set values to the new instance during initialization: ```javascript let noName = 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 @for @ember/object @static @param [arguments]* @public */ static create(props, extra) { let C = this; let instance = new C(DELAY_INIT); if (extra === undefined) { initialize(instance, props); } else { initialize(instance, flattenProps.apply(this, arguments)); } return instance; } /** Augments a constructor's prototype with additional properties and functions: ```javascript import EmberObject from '@ember/object'; const MyObject = EmberObject.extend({ name: 'an object' }); o = MyObject.create(); o.get('name'); // 'an object' MyObject.reopen({ say(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 @for @ember/object @static @public */ static reopen() { this.willReopen(); reopen.apply(this.PrototypeMixin, arguments); return this; } static willReopen() { let p = this.prototype; if (wasApplied.has(p)) { wasApplied.delete(p); // If the base mixin already exists and was applied, create a new mixin to // make sure that it gets properly applied. Reusing the same mixin after // the first `proto` call will cause it to get skipped. if (prototypeMixinMap.has(this)) { prototypeMixinMap.set(this, _metal.Mixin.create(this.PrototypeMixin)); } } } /** Augments a constructor's own properties and functions: ```javascript import EmberObject from '@ember/object'; const MyObject = EmberObject.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 import EmberObject from '@ember/object'; const Person = EmberObject.extend({ name: '', sayHello() { alert(`Hello. My name is ${this.get('name')}`); } }); Person.reopenClass({ species: 'Homo sapiens', createPerson(name) { return Person.create({ name }); } }); let tom = Person.create({ name: 'Tom Dale' }); let yehuda = Person.createPerson('Yehuda Katz'); tom.sayHello(); // "Hello. My name is Tom Dale" yehuda.sayHello(); // "Hello. My name is Yehuda Katz" alert(Person.species); // "Homo sapiens" ``` Note that `species` and `createPerson` are *not* valid on the `tom` and `yehuda` variables. They are only valid on `Person`. To add functions and properties to instances of a constructor by extending the constructor's prototype see `reopen` @method reopenClass @for @ember/object @static @public */ static reopenClass() { (0, _metal.applyMixin)(this, arguments); return this; } static detect(obj) { if ('function' !== typeof obj) { return false; } while (obj) { if (obj === this) { return true; } obj = obj.superclass; } return false; } static detectInstance(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 import { computed } from '@ember/object'; person: computed(function() { let personId = this.get('personId'); return Person.create({ id: personId }); }).meta({ type: 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 */ static metaForProperty(key) { let proto = this.proto(); // ensure prototype is initialized let possibleDesc = (0, _meta.descriptorFor)(proto, key); true && !(possibleDesc !== undefined) && (0, _debug.assert)(`metaForProperty() could not find a computed property with key '${key}'.`, possibleDesc !== undefined); return possibleDesc._meta || {}; } /** 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 */ static eachComputedProperty(callback, binding = this) { this.proto(); // ensure prototype is initialized let empty = {}; (0, _meta.meta)(this.prototype).forEachDescriptors((name, descriptor) => { if (descriptor.enumerable) { let meta = descriptor._meta || empty; callback.call(binding, name, meta); } }); } static get PrototypeMixin() { let prototypeMixin = prototypeMixinMap.get(this); if (prototypeMixin === undefined) { prototypeMixin = _metal.Mixin.create(); prototypeMixin.ownerConstructor = this; prototypeMixinMap.set(this, prototypeMixin); } return prototypeMixin; } static get superclass() { let c = Object.getPrototypeOf(this); if (c !== Function.prototype) return c; } static proto() { let p = this.prototype; if (!wasApplied.has(p)) { wasApplied.add(p); let parent = this.superclass; if (parent) { parent.proto(); } // If the prototype mixin exists, apply it. In the case of native classes, // it will not exist (unless the class has been reopened). if (prototypeMixinMap.has(this)) { this.PrototypeMixin.apply(p); } } return p; } } CoreObject.toString = _metal.classToString; (0, _utils.setName)(CoreObject, 'Ember.CoreObject'); CoreObject.isClass = true; CoreObject.isMethod = false; function flattenProps(...props) { let { concatenatedProperties, mergedProperties } = this; let hasConcatenatedProps = concatenatedProperties !== undefined && concatenatedProperties.length > 0; let hasMergedProps = mergedProperties !== undefined && mergedProperties.length > 0; let initProperties = {}; for (let i = 0; i < props.length; i++) { let properties = props[i]; true && !!(properties instanceof _metal.Mixin) && (0, _debug.assert)('EmberObject.create no longer supports mixing in other ' + 'definitions, use .extend & .create separately instead.', !(properties instanceof _metal.Mixin)); let keyNames = Object.keys(properties); for (let j = 0, k = keyNames.length; j < k; j++) { let keyName = keyNames[j]; let value = properties[keyName]; if (hasConcatenatedProps && concatenatedProperties.indexOf(keyName) > -1) { let baseValue = initProperties[keyName]; if (baseValue) { value = (0, _utils.makeArray)(baseValue).concat(value); } else { value = (0, _utils.makeArray)(value); } } if (hasMergedProps && mergedProperties.indexOf(keyName) > -1) { let baseValue = initProperties[keyName]; value = (0, _polyfills.assign)({}, baseValue, value); } initProperties[keyName] = value; } } return initProperties; } if (true /* DEBUG */) { /** Provides lookup-time type validation for injected properties. @private @method _onLookup */ CoreObject._onLookup = function injectedPropertyAssertion(debugContainerKey) { let [type] = debugContainerKey.split(':'); let proto = this.proto(); for (let key in proto) { let desc = (0, _meta.descriptorFor)(proto, key); if (desc instanceof _metal.InjectedProperty) { true && !(type === 'controller' || desc.type !== 'controller') && (0, _debug.assert)(`Defining \`${key}\` as an injected controller property on a non-controller (\`${debugContainerKey}\`) is not allowed.`, type === 'controller' || desc.type !== 'controller'); } } }; /** 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 */ CoreObject._lazyInjections = function () { let injections = {}; let proto = this.proto(); let key; let desc; for (key in proto) { desc = (0, _meta.descriptorFor)(proto, key); if (desc instanceof _metal.InjectedProperty) { injections[key] = { namespace: desc.namespace, source: desc.source, specifier: `${desc.type}:${desc.name || key}` }; } } return injections; }; } exports.default = CoreObject; }); enifed('@ember/-internals/runtime/lib/system/namespace', ['exports', '@ember/-internals/metal', '@ember/-internals/utils', '@ember/-internals/runtime/lib/system/object'], function (exports, _metal, _utils, _object) { 'use strict'; /** 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 EmberObject @public */ // Preloaded into namespaces class Namespace extends _object.default { init() { (0, _metal.addNamespace)(this); } toString() { let name = (0, _metal.get)(this, 'name') || (0, _metal.get)(this, 'modulePrefix'); if (name) { return name; } (0, _metal.findNamespaces)(); name = (0, _utils.getName)(this); if (name === undefined) { name = (0, _utils.guidFor)(this); (0, _utils.setName)(this, name); } return name; } nameClasses() { (0, _metal.processNamespace)(this); } destroy() { (0, _metal.removeNamespace)(this); super.destroy(); } } exports.default = Namespace; Namespace.prototype.isNamespace = true; Namespace.NAMESPACES = _metal.NAMESPACES; Namespace.NAMESPACES_BY_ID = _metal.NAMESPACES_BY_ID; Namespace.processAll = _metal.processAllNamespaces; Namespace.byName = _metal.findNamespace; }); enifed('@ember/-internals/runtime/lib/system/object', ['exports', '@ember/-internals/container', '@ember/-internals/owner', '@ember/-internals/utils', '@ember/-internals/metal', '@ember/-internals/runtime/lib/system/core_object', '@ember/-internals/runtime/lib/mixins/observable', '@ember/debug'], function (exports, _container, _owner, _utils, _metal, _core_object, _observable, _debug) { 'use strict'; exports.FrameworkObject = undefined; let OVERRIDE_OWNER = (0, _utils.symbol)('OVERRIDE_OWNER'); /** `EmberObject` is the main base class for all Ember objects. It is a subclass of `CoreObject` with the `Observable` mixin applied. For details, see the documentation for each of these. @class EmberObject @extends CoreObject @uses Observable @public */ /** @module @ember/object */ class EmberObject extends _core_object.default { get _debugContainerKey() { let factory = _container.FACTORY_FOR.get(this); return factory !== undefined && factory.fullName; } get [_owner.OWNER]() { if (this[OVERRIDE_OWNER]) { return this[OVERRIDE_OWNER]; } let factory = _container.FACTORY_FOR.get(this); return factory !== undefined && factory.owner; } // we need a setter here largely to support // folks calling `owner.ownerInjection()` API set [_owner.OWNER](value) { this[OVERRIDE_OWNER] = value; } } exports.default = EmberObject; (0, _utils.setName)(EmberObject, 'Ember.Object'); _observable.default.apply(EmberObject.prototype); let FrameworkObject = exports.FrameworkObject = EmberObject; if (true /* DEBUG */) { let INIT_WAS_CALLED = (0, _utils.symbol)('INIT_WAS_CALLED'); let ASSERT_INIT_WAS_CALLED = (0, _utils.symbol)('ASSERT_INIT_WAS_CALLED'); exports.FrameworkObject = FrameworkObject = class FrameworkObject extends EmberObject { init() { super.init(...arguments); this[INIT_WAS_CALLED] = true; } [ASSERT_INIT_WAS_CALLED]() { true && !this[INIT_WAS_CALLED] && (0, _debug.assert)(`You must call \`this._super(...arguments);\` when overriding \`init\` on a framework object. Please update ${this} to call \`this._super(...arguments);\` from \`init\`.`, this[INIT_WAS_CALLED]); } }; (0, _metal.addListener)(FrameworkObject.prototype, 'init', null, ASSERT_INIT_WAS_CALLED); } }); enifed('@ember/-internals/runtime/lib/system/object_proxy', ['exports', '@ember/-internals/runtime/lib/system/object', '@ember/-internals/runtime/lib/mixins/-proxy'], function (exports, _object, _proxy) { 'use strict'; /** `ObjectProxy` forwards all properties not defined by the proxy itself to a proxied `content` object. ```javascript import EmberObject from '@ember/object'; import ObjectProxy from '@ember/object/proxy'; object = EmberObject.create({ name: 'Foo' }); proxy = 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 import ObjectProxy from '@ember/object/proxy'; proxy = 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 import { computed } from '@ember/object'; import ObjectProxy from '@ember/object/proxy'; ProxyWithComputedProperty = ObjectProxy.extend({ fullName: computed('firstName', 'lastName', function() { var firstName = this.get('firstName'), lastName = this.get('lastName'); if (firstName && lastName) { return firstName + ' ' + lastName; } return 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 @extends EmberObject @uses Ember.ProxyMixin @public */ class ObjectProxy extends _object.default {} exports.default = ObjectProxy; ObjectProxy.PrototypeMixin.reopen(_proxy.default); }); enifed('@ember/-internals/runtime/lib/type-of', ['exports', '@ember/-internals/runtime/lib/system/object'], function (exports, _object) { 'use strict'; exports.typeOf = typeOf; // ........................................ // TYPING & ARRAY MESSAGING // const 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', '[object FileList]': 'filelist' }; const { toString } = Object.prototype; /** @module @ember/utils */ /** 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 | | 'filelist' | An instance of FileList | | 'class' | An Ember class (created using EmberObject.extend()) | | 'instance' | An Ember object instance | | 'error' | An instance of the Error object | | 'object' | A JavaScript object not inheriting from EmberObject | Examples: ```javascript import { A } from '@ember/array'; import { typeOf } from '@ember/utils'; import EmberObject from '@ember/object'; typeOf(); // 'undefined' typeOf(null); // 'null' typeOf(undefined); // 'undefined' typeOf('michael'); // 'string' typeOf(new String('michael')); // 'string' typeOf(101); // 'number' typeOf(new Number(101)); // 'number' typeOf(true); // 'boolean' typeOf(new Boolean(true)); // 'boolean' typeOf(A); // 'function' typeOf([1, 2, 90]); // 'array' typeOf(/abc/); // 'regexp' typeOf(new Date()); // 'date' typeOf(event.target.files); // 'filelist' typeOf(EmberObject.extend()); // 'class' typeOf(EmberObject.create()); // 'instance' typeOf(new Error('teamocil')); // 'error' // 'normal' JavaScript object typeOf({ a: 'b' }); // 'object' ``` @method typeOf @for @ember/utils @param {Object} item the item to check @return {String} the type @public @static */ function typeOf(item) { if (item === null) { return 'null'; } if (item === undefined) { return 'undefined'; } let ret = TYPE_MAP[toString.call(item)] || 'object'; if (ret === 'function') { if (_object.default.detect(item)) { ret = 'class'; } } else if (ret === 'object') { if (item instanceof Error) { ret = 'error'; } else if (item instanceof _object.default) { ret = 'instance'; } else if (item instanceof Date) { ret = 'date'; } } return ret; } }); enifed('@ember/-internals/utils', ['exports', '@ember/polyfills'], function (exports, _polyfills) { 'use strict'; exports.Cache = exports.setProxy = exports.isProxy = exports.HAS_NATIVE_PROXY = exports.HAS_NATIVE_SYMBOL = exports.toString = exports.setName = exports.getName = exports.makeArray = exports.tryInvoke = exports.canInvoke = exports.lookupDescriptor = exports.inspect = exports.setListeners = exports.setObservers = exports.getListeners = exports.getObservers = exports.wrap = exports.ROOT = exports.checkHasSuper = exports.intern = exports.guidFor = exports.generateGuid = exports.GUID_KEY = exports.uuid = exports.dictionary = exports.isInternalSymbol = exports.symbol = exports.NAME_KEY = undefined; /** 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) { let obj = {}; obj[str] = 1; for (let key in obj) { if (key === str) { return key; } } return str; } /** Returns whether Type(value) is Object. Useful for checking whether a value is a valid WeakMap key. Refs: https://tc39.github.io/ecma262/#sec-typeof-operator-runtime-semantics-evaluation https://tc39.github.io/ecma262/#sec-weakmap.prototype.set @private @function isObject */ function isObject(value) { return value !== null && (typeof value === 'object' || typeof value === 'function'); } /** @module @ember/object */ /** 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 */ let _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 */ const GUID_PREFIX = 'ember'; // Used for guid generation... const OBJECT_GUIDS = new WeakMap(); const NON_OBJECT_GUIDS = new Map(); /** 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 */ const GUID_KEY = intern(`__ember${+new Date()}`); /** 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 `guidFor(obj)`, which return an existing guid if available. @private @method generateGuid @static @for @ember/object/internals @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 = GUID_PREFIX) { let guid = prefix + uuid(); if (isObject(obj)) { OBJECT_GUIDS.set(obj, guid); } return guid; } /** 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, `EmberObject`-based or not. You can also use this method on DOM Element objects. @public @static @method guidFor @for @ember/object/internals @param {Object} obj any object, string, number, Element, or primitive @return {String} the unique guid for this instance. */ function guidFor(value) { let guid; if (isObject(value)) { guid = OBJECT_GUIDS.get(value); if (guid === undefined) { guid = GUID_PREFIX + uuid(); OBJECT_GUIDS.set(value, guid); } } else { guid = NON_OBJECT_GUIDS.get(value); if (guid === undefined) { let type = typeof value; if (type === 'string') { guid = 'st' + uuid(); } else if (type === 'number') { guid = 'nu' + uuid(); } else if (type === 'symbol') { guid = 'sy' + uuid(); } else { guid = '(' + value + ')'; } NON_OBJECT_GUIDS.set(value, guid); } } return guid; } const GENERATED_SYMBOLS = []; function isInternalSymbol(possibleSymbol) { return GENERATED_SYMBOLS.indexOf(possibleSymbol) !== -1; } 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. let id = GUID_KEY + Math.floor(Math.random() * +new Date()); let symbol = intern(`__${debugName}${id}__`); GENERATED_SYMBOLS.push(symbol); return symbol; } // 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) { let dict = Object.create(parent); dict['_dict'] = null; delete dict['_dict']; return dict; } const HAS_SUPER_PATTERN = /\.(_super|call\(this|apply\(this)/; const fnToString = Function.prototype.toString; const checkHasSuper = (() => { let 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; }; })(); const HAS_SUPER_MAP = new WeakMap(); const ROOT = Object.freeze(function () {}); HAS_SUPER_MAP.set(ROOT, false); function hasSuper(func) { let hasSuper = HAS_SUPER_MAP.get(func); if (hasSuper === undefined) { hasSuper = checkHasSuper(func); HAS_SUPER_MAP.set(func, hasSuper); } return hasSuper; } const OBSERVERS_MAP = new WeakMap(); function setObservers(func, observers) { if (observers) { OBSERVERS_MAP.set(func, observers); } } function getObservers(func) { return OBSERVERS_MAP.get(func); } const LISTENERS_MAP = new WeakMap(); function setListeners(func, listeners) { if (listeners) { LISTENERS_MAP.set(func, listeners); } } function getListeners(func) { return LISTENERS_MAP.get(func); } const IS_WRAPPED_FUNCTION_SET = new _polyfills._WeakSet(); /** 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 (!IS_WRAPPED_FUNCTION_SET.has(superFunc) && hasSuper(superFunc)) { return _wrap(func, _wrap(superFunc, ROOT)); } return _wrap(func, superFunc); } function _wrap(func, superFunc) { function superWrapper() { let orig = this._super; this._super = superFunc; let ret = func.apply(this, arguments); this._super = orig; return ret; } IS_WRAPPED_FUNCTION_SET.add(superWrapper); setObservers(superWrapper, getObservers(func)); setListeners(superWrapper, getListeners(func)); return superWrapper; } const { toString: objectToString } = Object.prototype; const { toString: functionToString } = Function.prototype; const { isArray } = Array; const { keys: objectKeys } = Object; const { stringify } = JSON; const LIST_LIMIT = 100; const DEPTH_LIMIT = 4; const SAFE_KEY = /^[\w$]+$/; /** @module @ember/debug */ /** 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 @static @param {Object} obj The object you want to inspect. @return {String} A description of the object @since 1.4.0 @private */ function inspect(obj) { // detect Node util.inspect call inspect(depth: number, opts: object) if (typeof obj === 'number' && arguments.length === 2) { return this; } return inspectValue(obj, 0); } function inspectValue(value, depth, seen) { let valueIsArray = false; switch (typeof value) { case 'undefined': return 'undefined'; case 'object': if (value === null) return 'null'; if (isArray(value)) { valueIsArray = true; break; } // is toString Object.prototype.toString or undefined then traverse if (value.toString === objectToString || value.toString === undefined) { break; } // custom toString return value.toString(); case 'function': return value.toString === functionToString ? value.name ? `[Function:${value.name}]` : `[Function]` : value.toString(); case 'string': return stringify(value); case 'symbol': case 'boolean': case 'number': default: return value.toString(); } if (seen === undefined) { seen = new _polyfills._WeakSet(); } else { if (seen.has(value)) return `[Circular]`; } seen.add(value); return valueIsArray ? inspectArray(value, depth + 1, seen) : inspectObject(value, depth + 1, seen); } function inspectKey(key) { return SAFE_KEY.test(key) ? key : stringify(key); } function inspectObject(obj, depth, seen) { if (depth > DEPTH_LIMIT) { return '[Object]'; } let s = '{'; let keys = objectKeys(obj); for (let i = 0; i < keys.length; i++) { s += i === 0 ? ' ' : ', '; if (i >= LIST_LIMIT) { s += `... ${keys.length - LIST_LIMIT} more keys`; break; } let key = keys[i]; s += inspectKey(key) + ': ' + inspectValue(obj[key], depth, seen); } s += ' }'; return s; } function inspectArray(arr, depth, seen) { if (depth > DEPTH_LIMIT) { return '[Array]'; } let s = '['; for (let i = 0; i < arr.length; i++) { s += i === 0 ? ' ' : ', '; if (i >= LIST_LIMIT) { s += `... ${arr.length - LIST_LIMIT} more items`; break; } s += inspectValue(arr[i], depth, seen); } s += ' ]'; return s; } function lookupDescriptor(obj, keyName) { let current = obj; do { let descriptor = Object.getOwnPropertyDescriptor(current, keyName); if (descriptor !== undefined) { return descriptor; } current = Object.getPrototypeOf(current); } while (current !== null); return null; } /** 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 !== null && obj !== undefined && typeof obj[methodName] === 'function'; } /** @module @ember/utils */ /** Checks to see if the `methodName` exists on the `obj`, and if it does, invokes it with the arguments passed. ```javascript import { tryInvoke } from '@ember/utils'; let d = new Date('03/15/2013'); tryInvoke(d, 'getTime'); // 1363320000000 tryInvoke(d, 'setFullYear', [2014]); // 1394856000000 tryInvoke(d, 'noSuchMethod', [2014]); // undefined ``` @method tryInvoke @for @ember/utils @static @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)) { let method = obj[methodName]; return method.apply(obj, args); } } const { isArray: isArray$1 } = Array; function makeArray(obj) { if (obj === null || obj === undefined) { return []; } return isArray$1(obj) ? obj : [obj]; } const NAMES = new WeakMap(); function setName(obj, name) { if (isObject(obj)) NAMES.set(obj, name); } function getName(obj) { return NAMES.get(obj); } const objectToString$1 = Object.prototype.toString; function isNone(obj) { return obj === null || obj === undefined; } /* A `toString` util function that supports objects without a `toString` method, e.g. an object created with `Object.create(null)`. */ function toString(obj) { if (typeof obj === 'string') { return obj; } if (null === obj) return 'null'; if (undefined === obj) return 'undefined'; if (Array.isArray(obj)) { // Reimplement Array.prototype.join according to spec (22.1.3.13) // Changing ToString(element) with this safe version of ToString. let r = ''; for (let k = 0; k < obj.length; k++) { if (k > 0) { r += ','; } if (!isNone(obj[k])) { r += toString(obj[k]); } } return r; } if (typeof obj.toString === 'function') { return obj.toString(); } return objectToString$1.call(obj); } const HAS_NATIVE_SYMBOL = function () { if (typeof Symbol !== 'function') { return false; } // use `Object`'s `.toString` directly to prevent us from detecting // polyfills as native return Object.prototype.toString.call(Symbol()) === '[object Symbol]'; }(); const HAS_NATIVE_PROXY = typeof Proxy === 'function'; const PROXIES = new _polyfills._WeakSet(); function isProxy(object) { if (isObject(object)) { return PROXIES.has(object); } return false; } function setProxy(object) { if (isObject(object)) { PROXIES.add(object); } } class Cache { constructor(limit, func, store) { this.limit = limit; this.func = func; this.store = store; this.size = 0; this.misses = 0; this.hits = 0; this.store = store || new Map(); } get(key) { let value = this.store.get(key); if (this.store.has(key)) { this.hits++; return this.store.get(key); } else { this.misses++; value = this.set(key, this.func(key)); } return value; } set(key, value) { if (this.limit > this.size) { this.size++; this.store.set(key, value); } return value; } purge() { this.store.clear(); this.size = 0; this.hits = 0; this.misses = 0; } } /* This package will be eagerly parsed and should have no dependencies on external packages. It is intended to be used to share utility methods that will be needed by every Ember application (and is **not** a dumping ground of useful utilities). Utility methods that are needed in < 80% of cases should be placed elsewhere (so they can be lazily evaluated / parsed). */ const NAME_KEY = symbol('NAME_KEY'); exports.NAME_KEY = NAME_KEY; exports.symbol = symbol; exports.isInternalSymbol = isInternalSymbol; exports.dictionary = makeDictionary; exports.uuid = uuid; exports.GUID_KEY = GUID_KEY; exports.generateGuid = generateGuid; exports.guidFor = guidFor; exports.intern = intern; exports.checkHasSuper = checkHasSuper; exports.ROOT = ROOT; exports.wrap = wrap; exports.getObservers = getObservers; exports.getListeners = getListeners; exports.setObservers = setObservers; exports.setListeners = setListeners; exports.inspect = inspect; exports.lookupDescriptor = lookupDescriptor; exports.canInvoke = canInvoke; exports.tryInvoke = tryInvoke; exports.makeArray = makeArray; exports.getName = getName; exports.setName = setName; exports.toString = toString; exports.HAS_NATIVE_SYMBOL = HAS_NATIVE_SYMBOL; exports.HAS_NATIVE_PROXY = HAS_NATIVE_PROXY; exports.isProxy = isProxy; exports.setProxy = setProxy; exports.Cache = Cache; }); enifed('@ember/-internals/views/index', ['exports', '@ember/-internals/views/lib/system/jquery', '@ember/-internals/views/lib/system/utils', '@ember/-internals/views/lib/system/event_dispatcher', '@ember/-internals/views/lib/component_lookup', '@ember/-internals/views/lib/mixins/text_support', '@ember/-internals/views/lib/views/core_view', '@ember/-internals/views/lib/mixins/class_names_support', '@ember/-internals/views/lib/mixins/child_views_support', '@ember/-internals/views/lib/mixins/view_state_support', '@ember/-internals/views/lib/mixins/view_support', '@ember/-internals/views/lib/mixins/action_support', '@ember/-internals/views/lib/compat/attrs', '@ember/-internals/views/lib/system/lookup_partial', '@ember/-internals/views/lib/utils/lookup-component', '@ember/-internals/views/lib/system/action_manager', '@ember/-internals/views/lib/compat/fallback-view-registry'], function (exports, _jquery, _utils, _event_dispatcher, _component_lookup, _text_support, _core_view, _class_names_support, _child_views_support, _view_state_support, _view_support, _action_support, _attrs, _lookup_partial, _lookupComponent, _action_manager, _fallbackViewRegistry) { 'use strict'; Object.defineProperty(exports, 'jQuery', { enumerable: true, get: function () { return _jquery.default; } }); Object.defineProperty(exports, 'jQueryDisabled', { enumerable: true, get: function () { return _jquery.jQueryDisabled; } }); Object.defineProperty(exports, 'addChildView', { enumerable: true, get: function () { return _utils.addChildView; } }); Object.defineProperty(exports, 'isSimpleClick', { enumerable: true, get: function () { return _utils.isSimpleClick; } }); Object.defineProperty(exports, 'getViewBounds', { enumerable: true, get: function () { return _utils.getViewBounds; } }); Object.defineProperty(exports, 'getViewClientRects', { enumerable: true, get: function () { return _utils.getViewClientRects; } }); Object.defineProperty(exports, 'getViewBoundingClientRect', { enumerable: true, get: function () { return _utils.getViewBoundingClientRect; } }); Object.defineProperty(exports, 'getRootViews', { enumerable: true, get: function () { return _utils.getRootViews; } }); Object.defineProperty(exports, 'getChildViews', { enumerable: true, get: function () { return _utils.getChildViews; } }); Object.defineProperty(exports, 'getViewId', { enumerable: true, get: function () { return _utils.getViewId; } }); Object.defineProperty(exports, 'getViewElement', { enumerable: true, get: function () { return _utils.getViewElement; } }); Object.defineProperty(exports, 'setViewElement', { enumerable: true, get: function () { return _utils.setViewElement; } }); Object.defineProperty(exports, 'constructStyleDeprecationMessage', { enumerable: true, get: function () { return _utils.constructStyleDeprecationMessage; } }); Object.defineProperty(exports, 'EventDispatcher', { enumerable: true, get: function () { return _event_dispatcher.default; } }); Object.defineProperty(exports, 'ComponentLookup', { enumerable: true, get: function () { return _component_lookup.default; } }); Object.defineProperty(exports, 'TextSupport', { enumerable: true, get: function () { return _text_support.default; } }); Object.defineProperty(exports, 'CoreView', { enumerable: true, get: function () { return _core_view.default; } }); Object.defineProperty(exports, 'ClassNamesSupport', { enumerable: true, get: function () { return _class_names_support.default; } }); Object.defineProperty(exports, 'ChildViewsSupport', { enumerable: true, get: function () { return _child_views_support.default; } }); Object.defineProperty(exports, 'ViewStateSupport', { enumerable: true, get: function () { return _view_state_support.default; } }); Object.defineProperty(exports, 'ViewMixin', { enumerable: true, get: function () { return _view_support.default; } }); Object.defineProperty(exports, 'ActionSupport', { enumerable: true, get: function () { return _action_support.default; } }); Object.defineProperty(exports, 'MUTABLE_CELL', { enumerable: true, get: function () { return _attrs.MUTABLE_CELL; } }); Object.defineProperty(exports, 'lookupPartial', { enumerable: true, get: function () { return _lookup_partial.default; } }); Object.defineProperty(exports, 'hasPartial', { enumerable: true, get: function () { return _lookup_partial.hasPartial; } }); Object.defineProperty(exports, 'lookupComponent', { enumerable: true, get: function () { return _lookupComponent.default; } }); Object.defineProperty(exports, 'ActionManager', { enumerable: true, get: function () { return _action_manager.default; } }); Object.defineProperty(exports, 'fallbackViewRegistry', { enumerable: true, get: function () { return _fallbackViewRegistry.default; } }); }); enifed('@ember/-internals/views/lib/compat/attrs', ['exports', '@ember/-internals/utils'], function (exports, _utils) { 'use strict'; exports.MUTABLE_CELL = undefined; let MUTABLE_CELL = exports.MUTABLE_CELL = (0, _utils.symbol)('MUTABLE_CELL'); }); enifed('@ember/-internals/views/lib/compat/fallback-view-registry', ['exports', '@ember/-internals/utils'], function (exports, _utils) { 'use strict'; exports.default = (0, _utils.dictionary)(null); }); enifed('@ember/-internals/views/lib/component_lookup', ['exports', '@ember/debug', '@ember/-internals/runtime'], function (exports, _debug, _runtime) { 'use strict'; exports.default = _runtime.Object.extend({ componentFor(name, owner, options) { true && !(name.indexOf('-') > -1 || true /* EMBER_GLIMMER_ANGLE_BRACKET_INVOCATION */) && (0, _debug.assert)(`You cannot use '${name}' as a component name. Component names must contain a hyphen${true /* EMBER_GLIMMER_ANGLE_BRACKET_INVOCATION */ ? ' or start with a capital letter' : ''}.`, name.indexOf('-') > -1 || true); let fullName = `component:${name}`; return owner.factoryFor(fullName, options); }, layoutFor(name, owner, options) { true && !(name.indexOf('-') > -1 || true /* EMBER_GLIMMER_ANGLE_BRACKET_INVOCATION */) && (0, _debug.assert)(`You cannot use '${name}' as a component name. Component names must contain a hyphen.`, name.indexOf('-') > -1 || true); let templateFullName = `template:components/${name}`; return owner.lookup(templateFullName, options); } }); }); enifed('@ember/-internals/views/lib/mixins/action_support', ['exports', '@ember/-internals/utils', '@ember/-internals/metal', '@ember/debug', '@ember/-internals/views/lib/compat/attrs', '@ember/deprecated-features'], function (exports, _utils, _metal, _debug, _attrs, _deprecatedFeatures) { 'use strict'; const mixinObj = { send(actionName, ...args) { true && !(!this.isDestroying && !this.isDestroyed) && (0, _debug.assert)(`Attempted to call .send() with the action '${actionName}' on the destroyed object '${this}'.`, !this.isDestroying && !this.isDestroyed); let action = this.actions && this.actions[actionName]; if (action) { let shouldBubble = action.apply(this, args) === true; if (!shouldBubble) { return; } } let target = (0, _metal.get)(this, 'target'); if (target) { true && !(typeof target.send === 'function') && (0, _debug.assert)(`The \`target\` for ${this} (${target}) does not have a \`send\` method`, typeof target.send === 'function'); target.send(...arguments); } else { true && !action && (0, _debug.assert)(`${(0, _utils.inspect)(this)} had no action handler for: ${actionName}`, action); } } }; /** @module ember */ if (_deprecatedFeatures.SEND_ACTION) { /** 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: ```app/components/play-button.js import Component from '@ember/component'; export default 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. ```app/controller/application.js import Controller from '@ember/controller'; export default 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. ```app/components/next-button.js import Component from '@ember/component'; export default Component.extend({ click() { this.sendAction(); } }); ``` ```handlebars {{! app/templates/application.hbs }} {{next-button action=(action "playNextSongInAlbum")}} ``` ```app/controllers/application.js import Controller from '@ember/controller'; export default Controller.extend({ actions: { playNextSongInAlbum() { ... } } }); ``` @method sendAction @param [action] {String} the action to call @param [params] {*} arguments for the action @public @deprecated */ let sendAction = function sendAction(action, ...contexts) { true && !(!this.isDestroying && !this.isDestroyed) && (0, _debug.assert)(`Attempted to call .sendAction() with the action '${action}' on the destroyed object '${this}'.`, !this.isDestroying && !this.isDestroyed); true && !false && (0, _debug.deprecate)(`You called ${(0, _utils.inspect)(this)}.sendAction(${typeof action === 'string' ? `"${action}"` : ''}) but Component#sendAction is deprecated. Please use closure actions instead.`, false, { id: 'ember-component.send-action', until: '4.0.0', url: 'https://emberjs.com/deprecations/v3.x#toc_ember-component-send-action' }); let actionName; // Send the default action if (action === undefined) { action = 'action'; } actionName = (0, _metal.get)(this, `attrs.${action}`) || (0, _metal.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(...contexts); } else { this.triggerAction({ action: actionName, actionContext: contexts }); } }; let validateAction = function validateAction(component, actionName) { if (actionName && actionName[_attrs.MUTABLE_CELL]) { actionName = actionName.value; } true && !(actionName === null || actionName === undefined || typeof actionName === 'string' || typeof actionName === 'function') && (0, _debug.assert)(`The default action was triggered on the component ${component.toString()}, but the action name (${actionName}) was not a string.`, actionName === null || actionName === undefined || typeof actionName === 'string' || typeof actionName === 'function'); return actionName; }; mixinObj.sendAction = sendAction; } /** @class ActionSupport @namespace Ember @private */ exports.default = _metal.Mixin.create(mixinObj); }); enifed('@ember/-internals/views/lib/mixins/child_views_support', ['exports', '@ember/-internals/metal', '@ember/-internals/views/lib/system/utils'], function (exports, _metal, _utils) { 'use strict'; exports.default = _metal.Mixin.create({ /** Array of child views. You should never edit this array directly. @property childViews @type Array @default [] @private */ childViews: (0, _metal.descriptor)({ configurable: false, enumerable: false, get() { return (0, _utils.getChildViews)(this); } }), appendChild(view) { (0, _utils.addChildView)(this, view); } }); }); enifed('@ember/-internals/views/lib/mixins/class_names_support', ['exports', '@ember/-internals/meta', '@ember/-internals/metal', '@ember/debug'], function (exports, _meta, _metal, _debug) { 'use strict'; const EMPTY_ARRAY = Object.freeze([]); /** @class ClassNamesSupport @namespace Ember @private */ /** @module ember */ exports.default = _metal.Mixin.create({ concatenatedProperties: ['classNames', 'classNameBindings'], init() { this._super(...arguments); true && !((0, _meta.descriptorFor)(this, 'classNameBindings') === undefined && Array.isArray(this.classNameBindings)) && (0, _debug.assert)(`Only arrays are allowed for 'classNameBindings'`, (0, _meta.descriptorFor)(this, 'classNameBindings') === undefined && Array.isArray(this.classNameBindings)); true && !((0, _meta.descriptorFor)(this, 'classNames') === undefined && Array.isArray(this.classNames)) && (0, _debug.assert)(`Only arrays of static class strings are allowed for 'classNames'. For dynamic classes, use 'classNameBindings'.`, (0, _meta.descriptorFor)(this, 'classNames') === undefined && Array.isArray(this.classNames)); }, /** 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: EMPTY_ARRAY, /** 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 import Component from '@ember/component'; Component.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 import Component from '@ember/component'; Component.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 import Component from '@ember/component'; Component.extend({ classNameBindings: ['isUrgent:urgent'], isUrgent: true }); ``` If you would like to specify a class that should only be added when the property is false, you can declare a binding like this: ```javascript // Applies the 'disabled' class to the view element import Component from '@ember/component'; Component.extend({ classNameBindings: ['isEnabled::disabled'], isEnabled: false }); ``` This list of properties is inherited from the component's superclasses as well. @property classNameBindings @type Array @default [] @public */ classNameBindings: EMPTY_ARRAY }); }); enifed('@ember/-internals/views/lib/mixins/text_support', ['exports', '@ember/-internals/metal', '@ember/-internals/runtime', '@ember/debug', '@ember/deprecated-features'], function (exports, _metal, _runtime, _debug, _deprecatedFeatures) { 'use strict'; /** @module ember */ const KEY_EVENTS = { 13: 'insertNewline', 27: 'cancel' }; /** `TextSupport` is a shared mixin used by both `TextField` and `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 specified 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 import Application from '@ember/application'; import Controller from '@ember/controller'; App = Application.create(); App.ApplicationController = 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 | enter | | | | | 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 Mixin @private */ exports.default = _metal.Mixin.create(_runtime.TargetActionSupport, { value: '', attributeBindings: ['autocapitalize', 'autocorrect', 'autofocus', 'disabled', 'form', 'maxlength', 'minlength', 'placeholder', 'readonly', 'required', 'selectionDirection', 'spellcheck', 'tabindex', 'title'], placeholder: null, disabled: false, maxlength: null, init() { this._super(...arguments); this.on('paste', this, this._elementValueDidChange); this.on('cut', this, this._elementValueDidChange); this.on('input', this, this._elementValueDidChange); }, /** 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(event) { let map = KEY_EVENTS; let method = map[event.keyCode]; this._elementValueDidChange(); if (method) { return this[method](event); } }, _elementValueDidChange() { (0, _metal.set)(this, 'value', this.element.value); }, change(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(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(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(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(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(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(event) { this.interpretKeyEvents(event); sendAction('key-up', this, 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(event) { sendAction('key-down', this, 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) { let actionName = (0, _metal.get)(view, `attrs.${eventName}`) || (0, _metal.get)(view, eventName); let value = (0, _metal.get)(view, 'value'); if (_deprecatedFeatures.SEND_ACTION && typeof actionName === 'string') { true && !false && (0, _debug.deprecate)(`Passing actions to components as strings (like {{input ${eventName}="${actionName}"}}) is deprecated. Please use closure actions instead ({{input ${eventName}=(action "${actionName}")}})`, false, { id: 'ember-component.send-action', until: '4.0.0', url: 'https://emberjs.com/deprecations/v3.x#toc_ember-component-send-action' }); view.triggerAction({ action: actionName, actionContext: [value, event] }); } else if (typeof actionName === 'function') { actionName(value, event); } if (actionName && !(0, _metal.get)(view, 'bubbles')) { event.stopPropagation(); } } }); enifed('@ember/-internals/views/lib/mixins/view_state_support', ['exports', '@ember/-internals/metal'], function (exports, _metal) { 'use strict'; exports.default = _metal.Mixin.create({ _transitionTo(state) { let priorState = this._currentState; let currentState = this._currentState = this._states[state]; this._state = state; if (priorState && priorState.exit) { priorState.exit(this); } if (currentState.enter) { currentState.enter(this); } } }); }); enifed('@ember/-internals/views/lib/mixins/view_support', ['exports', '@ember/-internals/utils', '@ember/-internals/meta', '@ember/-internals/metal', '@ember/debug', '@ember/-internals/browser-environment', '@ember/-internals/views/lib/system/utils', '@ember/-internals/views/lib/system/jquery'], function (exports, _utils, _meta, _metal, _debug, _browserEnvironment, _utils2, _jquery) { 'use strict'; function K() { return this; } /** @class ViewMixin @namespace Ember @private */ exports.default = _metal.Mixin.create({ /** A list of properties of the view to apply as attributes. If the property is a string value, the value of that string will be applied as the value for an attribute of the property's name. The following example creates a tag like `
`. ```app/components/my-component.js import Component from '@ember/component'; export default Component.extend({ attributeBindings: ['priority'], priority: 'high' }); ``` If the value of the property is a Boolean, the attribute is treated as an HTML Boolean attribute. It will be present if the property is `true` and omitted if the property is `false`. The following example creates markup like `
`. ```app/components/my-component.js import Component from '@ember/component'; export default Component.extend({ attributeBindings: ['visible'], visible: true }); ``` If you would prefer to use a custom value instead of the property name, you can create the same markup as the last example with a binding like this: ```app/components/my-component.js import Component from '@ember/component'; export default Component.extend({ attributeBindings: ['isVisible:visible'], isVisible: true }); ``` This list of attributes is inherited from the component's superclasses, as well. @property attributeBindings @type Array @default [] @public */ 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 Mixin. @return Ember.View @deprecated use `yield` and contextual components for composition instead. @private */ nearestOfType(klass) { let view = this.parentView; let isOfType = klass instanceof _metal.Mixin ? view => klass.detect(view) : view => 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(property) { let 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() { return this._currentState.rerender(this); }, // .......................................................... // ELEMENT SUPPORT // /** Returns the current DOM element for the view. @property element @type DOMElement @public */ element: (0, _metal.descriptor)({ configurable: false, enumerable: false, get() { return this.renderer.getElement(this); } }), /** 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 */ $(sel) { true && !(this.tagName !== '') && (0, _debug.assert)("You cannot access this.$() on a component with `tagName: ''` specified.", this.tagName !== ''); true && !!_jquery.jQueryDisabled && (0, _debug.assert)('You cannot access this.$() with `jQuery` disabled.', !_jquery.jQueryDisabled); if (this.element) { return sel ? (0, _jquery.default)(sel, this.element) : (0, _jquery.default)(this.element); } }, /** 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 `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(selector) { let target; if (_browserEnvironment.hasDOM) { target = typeof selector === 'string' ? document.querySelector(selector) : selector; true && !target && (0, _debug.assert)(`You tried to append to (${selector}) but that isn't in the DOM`, target); true && !!(0, _utils2.matches)(target, '.ember-view') && (0, _debug.assert)('You cannot append to an existing Ember.View.', !(0, _utils2.matches)(target, '.ember-view')); true && !(() => { let node = target.parentNode; while (node) { if (node.nodeType !== 9 && (0, _utils2.matches)(node, '.ember-view')) { return false; } node = node.parentNode; } return true; })() && (0, _debug.assert)('You cannot append to an existing Ember.View.', (() => { let node = target.parentNode;while (node) { if (node.nodeType !== 9 && (0, _utils2.matches)(node, '.ember-view')) { return false; }node = node.parentNode; }return true; })()); } else { target = selector; true && !(typeof target !== 'string') && (0, _debug.assert)(`You tried to append to a selector string (${selector}) in an environment without jQuery`, typeof target !== 'string'); true && !(typeof selector.appendChild === 'function') && (0, _debug.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; }, /** 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() { 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: ```app/components/my-component.js import Component from '@ember/component'; export default Component.extend({ init() { this._super(...arguments); 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(parentElem) { let id = `#${this.elementId}`; return (0, _jquery.default)(id)[0] || (0, _jquery.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. 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 and on itself afterwards. @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() { this._super(...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 after the element of the view is destroyed. @event willDestroyElement @public */ didDestroyElement: 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 `
` 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() { this._super(...arguments); // tslint:disable-next-line:max-line-length true && !((0, _meta.descriptorFor)(this, 'elementId') === undefined) && (0, _debug.assert)(`You cannot use a computed property for the component's \`elementId\` (${this}).`, (0, _meta.descriptorFor)(this, 'elementId') === undefined); // tslint:disable-next-line:max-line-length true && !((0, _meta.descriptorFor)(this, 'tagName') === undefined) && (0, _debug.assert)(`You cannot use a computed property for the component's \`tagName\` (${this}).`, (0, _meta.descriptorFor)(this, 'tagName') === undefined); if (!this.elementId && this.tagName !== '') { this.elementId = (0, _utils.guidFor)(this); } true && !!this.render && (0, _debug.assert)('Using a custom `.render` function is no longer supported.', !this.render); }, // ....................................................... // EVENT HANDLING // /** Handle events from `EventDispatcher` @method handleEvent @param eventName {String} @param evt {Event} @private */ handleEvent(eventName, evt) { return this._currentState.handleEvent(this, eventName, evt); } }); }); enifed("@ember/-internals/views/lib/system/action_manager", ["exports"], function (exports) { "use strict"; exports.default = ActionManager; /** @module ember */ function ActionManager() {} /** Global action id hash. @private @property registeredActions @type Object */ ActionManager.registeredActions = {}; }); enifed('@ember/-internals/views/lib/system/event_dispatcher', ['exports', '@ember/-internals/owner', '@ember/polyfills', '@ember/debug', '@ember/-internals/metal', '@ember/-internals/runtime', '@ember/-internals/views/lib/system/jquery', '@ember/-internals/views/lib/system/action_manager', '@ember/-internals/views/lib/compat/fallback-view-registry', '@ember/-internals/views/lib/system/jquery_event_deprecation', '@ember/-internals/views/lib/system/utils'], function (exports, _owner, _polyfills, _debug, _metal, _runtime, _jquery, _action_manager, _fallbackViewRegistry, _jquery_event_deprecation, _utils) { 'use strict'; /** @module ember */ const ROOT_ELEMENT_CLASS = 'ember-application'; const ROOT_ELEMENT_SELECTOR = `.${ROOT_ELEMENT_CLASS}`; const EVENT_MAP = { mouseenter: 'mouseover', mouseleave: 'mouseout' }; /** `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 = _runtime.Object.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 `Application.customEvents` hash. To add new events to be listened to: ```javascript import Application from '@ember/application'; let App = Application.create({ customEvents: { paste: 'paste' } }); ``` To prevent default events from being listened to: ```javascript import Application from '@ember/application'; let App = 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', init() { this._super(); true && !(() => { let owner = (0, _owner.getOwner)(this); let environment = owner.lookup('-environment:main'); return environment.isInteractive; })() && (0, _debug.assert)('EventDispatcher should never be instantiated in fastboot mode. Please report this as an Ember bug.', (() => { let owner = (0, _owner.getOwner)(this);let environment = owner.lookup('-environment:main');return environment.isInteractive; })()); this._eventHandlers = Object.create(null); }, /** 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(addedEvents, _rootElement) { let events = this._finalEvents = (0, _polyfills.assign)({}, (0, _metal.get)(this, 'events'), addedEvents); if (_rootElement !== undefined && _rootElement !== null) { (0, _metal.set)(this, 'rootElement', _rootElement); } let rootElementSelector = (0, _metal.get)(this, 'rootElement'); let rootElement; if (_jquery.jQueryDisabled) { if (typeof rootElementSelector !== 'string') { rootElement = rootElementSelector; } else { rootElement = document.querySelector(rootElementSelector); } true && !!rootElement.classList.contains(ROOT_ELEMENT_CLASS) && (0, _debug.assert)(`You cannot use the same root element (${(0, _metal.get)(this, 'rootElement') || rootElement.tagName}) multiple times in an Ember.Application`, !rootElement.classList.contains(ROOT_ELEMENT_CLASS)); true && !(() => { let target = rootElement.parentNode; do { if (target.classList.contains(ROOT_ELEMENT_CLASS)) { return false; } target = target.parentNode; } while (target && target.nodeType === 1); return true; })() && (0, _debug.assert)('You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application', (() => { let target = rootElement.parentNode;do { if (target.classList.contains(ROOT_ELEMENT_CLASS)) { return false; }target = target.parentNode; } while (target && target.nodeType === 1);return true; })()); true && !!rootElement.querySelector(ROOT_ELEMENT_SELECTOR) && (0, _debug.assert)('You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application', !rootElement.querySelector(ROOT_ELEMENT_SELECTOR)); rootElement.classList.add(ROOT_ELEMENT_CLASS); true && !rootElement.classList.contains(ROOT_ELEMENT_CLASS) && (0, _debug.assert)(`Unable to add '${ROOT_ELEMENT_CLASS}' class to root element (${(0, _metal.get)(this, 'rootElement') || rootElement.tagName}). Make sure you set rootElement to the body or an element in the body.`, rootElement.classList.contains(ROOT_ELEMENT_CLASS)); } else { rootElement = (0, _jquery.default)(rootElementSelector); true && !!rootElement.is(ROOT_ELEMENT_SELECTOR) && (0, _debug.assert)(`You cannot use the same root element (${rootElement.selector || rootElement[0].tagName}) multiple times in an Ember.Application`, !rootElement.is(ROOT_ELEMENT_SELECTOR)); true && !!rootElement.closest(ROOT_ELEMENT_SELECTOR).length && (0, _debug.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); true && !!rootElement.find(ROOT_ELEMENT_SELECTOR).length && (0, _debug.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.`); } } let viewRegistry = this._getViewRegistry(); for (let event in events) { if (events.hasOwnProperty(event)) { this.setupHandler(rootElement, event, events[event], viewRegistry); } } }, /** 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 @param {Object} viewRegistry */ setupHandler(rootElement, event, eventName, viewRegistry) { if (eventName === null) { return; } if (_jquery.jQueryDisabled) { let viewHandler = (target, event) => { let view = viewRegistry[target.id]; let result = true; if (view) { result = view.handleEvent(eventName, event); } return result; }; let actionHandler = (target, event) => { let actionId = target.getAttribute('data-ember-action'); let actions = _action_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 === '') { let attributes = target.attributes; let attributeCount = attributes.length; actions = []; for (let i = 0; i < attributeCount; i++) { let attr = attributes.item(i); let attrName = attr.name; if (attrName.indexOf('data-ember-action-') === 0) { actions = actions.concat(_action_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 (let index = 0; index < actions.length; index++) { let action = actions[index]; if (action && action.eventName === eventName) { return action.handler(event); } } }; // Special handling of events that don't bubble (event delegation does not work). // Mimics the way this is handled in jQuery, // see https://github.com/jquery/jquery/blob/899c56f6ada26821e8af12d9f35fa039100e838e/src/event.js#L666-L700 if (EVENT_MAP[event] !== undefined) { let mappedEventType = EVENT_MAP[event]; let origEventType = event; let createFakeEvent = (eventType, event) => { let fakeEvent = document.createEvent('MouseEvent'); fakeEvent.initMouseEvent(eventType, false, false, event.view, event.detail, event.screenX, event.screenY, event.clientX, event.clientY, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey, event.button, event.relatedTarget); // fake event.target as we don't dispatch the event Object.defineProperty(fakeEvent, 'target', { value: event.target, enumerable: true }); return fakeEvent; }; let handleMappedEvent = this._eventHandlers[mappedEventType] = event => { let target = event.target; let related = event.relatedTarget; while (target && target.nodeType === 1 && (related === null || related !== target && !(0, _utils.contains)(target, related))) { // mouseEnter/Leave don't bubble, so there is no logic to prevent it as with other events if (viewRegistry[target.id]) { viewHandler(target, createFakeEvent(origEventType, event)); } else if (target.hasAttribute('data-ember-action')) { actionHandler(target, createFakeEvent(origEventType, event)); } // separate mouseEnter/Leave events are dispatched for each listening element // until the element (related) has been reached that the pointing device exited from/to target = target.parentNode; } }; rootElement.addEventListener(mappedEventType, handleMappedEvent); } else { let handleEvent = this._eventHandlers[event] = event => { let target = event.target; do { if (viewRegistry[target.id]) { if (viewHandler(target, event) === false) { event.preventDefault(); event.stopPropagation(); break; } } else if (target.hasAttribute('data-ember-action')) { if (actionHandler(target, event) === false) { break; } } target = target.parentNode; } while (target && target.nodeType === 1); }; rootElement.addEventListener(event, handleEvent); } } else { rootElement.on(`${event}.ember`, '.ember-view', function (evt) { let view = viewRegistry[this.id]; let result = true; if (view) { result = view.handleEvent(eventName, (0, _jquery_event_deprecation.default)(evt)); } return result; }); rootElement.on(`${event}.ember`, '[data-ember-action]', evt => { let attributes = evt.currentTarget.attributes; let handledActions = []; evt = (0, _jquery_event_deprecation.default)(evt); for (let i = 0; i < attributes.length; i++) { let attr = attributes.item(i); let attrName = attr.name; if (attrName.lastIndexOf('data-ember-action-', 0) !== -1) { let action = _action_manager.default.registeredActions[attr.value]; // We have to check for action 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 (action && action.eventName === eventName && handledActions.indexOf(action) === -1) { action.handler(evt); // Action handlers can mutate state which in turn creates new attributes on the element. // This effect could cause the `data-ember-action` attribute to shift down and be invoked twice. // To avoid this, we keep track of which actions have been handled. handledActions.push(action); } } } }); } }, _getViewRegistry() { let owner = (0, _owner.getOwner)(this); let viewRegistry = owner && owner.lookup('-view-registry:main') || _fallbackViewRegistry.default; return viewRegistry; }, destroy() { let rootElementSelector = (0, _metal.get)(this, 'rootElement'); let rootElement; if (rootElementSelector.nodeType) { rootElement = rootElementSelector; } else { rootElement = document.querySelector(rootElementSelector); } if (!rootElement) { return; } if (_jquery.jQueryDisabled) { for (let event in this._eventHandlers) { rootElement.removeEventListener(event, this._eventHandlers[event]); } } else { (0, _jquery.default)(rootElementSelector).off('.ember', '**'); } rootElement.classList.remove(ROOT_ELEMENT_CLASS); return this._super(...arguments); }, toString() { return '(EventDispatcher)'; } }); }); enifed('@ember/-internals/views/lib/system/jquery', ['exports', '@ember/-internals/environment', '@ember/-internals/browser-environment'], function (exports, _environment, _browserEnvironment) { 'use strict'; exports.jQueryDisabled = undefined; let jQuery; let jQueryDisabled = exports.jQueryDisabled = _environment.ENV._JQUERY_INTEGRATION === false; if (_browserEnvironment.hasDOM) { jQuery = _environment.context.imports.jQuery; if (!jQueryDisabled && 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(eventName => { jQuery.event.fixHooks[eventName] = { props: ['dataTransfer'] }; }); } } else { exports.jQueryDisabled = jQueryDisabled = true; } } exports.default = jQueryDisabled ? undefined : jQuery; }); enifed('@ember/-internals/views/lib/system/jquery_event_deprecation', ['exports', '@ember/debug', '@ember/-internals/environment', '@ember/-internals/utils'], function (exports, _debug, _environment, _utils) { 'use strict'; exports.default = addJQueryEventDeprecation; function addJQueryEventDeprecation(jqEvent) { if (!true /* DEBUG */ || !_utils.HAS_NATIVE_PROXY) { return jqEvent; } let boundFunctions = new Map(); // wrap the jQuery event in a Proxy to add the deprecation message for originalEvent, according to RFC#294 // we need a native Proxy here, so we can make sure that the internal use of originalEvent in jQuery itself does // not trigger a deprecation return new Proxy(jqEvent, { get(target, name) { switch (name) { case 'originalEvent': true && !(EmberENV => { // this deprecation is intentionally checking `global.EmberENV` / // `global.ENV` so that we can ensure we _only_ deprecate in the // case where jQuery integration is enabled implicitly (e.g. // "defaulted" to enabled) as opposed to when the user explicitly // opts in to using jQuery if (typeof EmberENV !== 'object' || EmberENV === null) return false; return EmberENV._JQUERY_INTEGRATION === true; })(_environment.global.EmberENV || _environment.global.ENV) && (0, _debug.deprecate)('Accessing jQuery.Event specific properties is deprecated. Either use the ember-jquery-legacy addon to normalize events to native events, or explicitly opt into jQuery integration using @ember/optional-features.', (EmberENV => { if (typeof EmberENV !== 'object' || EmberENV === null) return false;return EmberENV._JQUERY_INTEGRATION === true; })(_environment.global.EmberENV || _environment.global.ENV), { id: 'ember-views.event-dispatcher.jquery-event', until: '4.0.0', url: 'https://emberjs.com/deprecations/v3.x#toc_jquery-event' }); return target[name]; // provide an escape hatch for ember-jquery-legacy to access originalEvent without a deprecation case '__originalEvent': return target.originalEvent; default: if (typeof target[name] === 'function') { // cache functions for reuse if (!boundFunctions.has(name)) { // for jQuery.Event methods call them with `target` as the `this` context, so they will access // `originalEvent` from the original jQuery event, not our proxy, thus not trigger the deprecation boundFunctions.set(name, target[name].bind(target)); } return boundFunctions.get(name); } // same for jQuery's getter functions for simple properties return target[name]; } } }); } /* global Proxy */ }); enifed('@ember/-internals/views/lib/system/lookup_partial', ['exports', '@ember/debug', '@ember/error'], function (exports, _debug, _error) { 'use strict'; exports.default = lookupPartial; exports.hasPartial = hasPartial; function parseUnderscoredName(templateName) { let nameParts = templateName.split('/'); let lastPart = nameParts[nameParts.length - 1]; nameParts[nameParts.length - 1] = `_${lastPart}`; return nameParts.join('/'); } function lookupPartial(templateName, owner) { if (templateName == null) { return; } let template = templateFor(owner, parseUnderscoredName(templateName), templateName); true && !!!template && (0, _debug.assert)(`Unable to find partial with name "${templateName}"`, !!template); return template; } function hasPartial(name, owner) { if (!owner) { throw new _error.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.hasRegistration(`template:${parseUnderscoredName(name)}`) || owner.hasRegistration(`template:${name}`); } function templateFor(owner, underscored, name) { if (!name) { return; } true && !(name.indexOf('.') === -1) && (0, _debug.assert)(`templateNames are not allowed to contain periods: ${name}`, name.indexOf('.') === -1); if (!owner) { throw new _error.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:${underscored}`) || owner.lookup(`template:${name}`); } }); enifed('@ember/-internals/views/lib/system/utils', ['exports', '@ember/-internals/owner', '@ember/-internals/utils'], function (exports, _owner, _utils) { 'use strict'; exports.elMatches = undefined; exports.isSimpleClick = isSimpleClick; exports.constructStyleDeprecationMessage = constructStyleDeprecationMessage; exports.getRootViews = getRootViews; exports.getViewId = getViewId; exports.getViewElement = getViewElement; exports.initViewElement = initViewElement; exports.setViewElement = setViewElement; exports.getChildViews = getChildViews; exports.initChildViews = initChildViews; exports.addChildView = addChildView; exports.collectChildViews = collectChildViews; exports.getViewBounds = getViewBounds; exports.getViewRange = getViewRange; exports.getViewClientRects = getViewClientRects; exports.getViewBoundingClientRect = getViewBoundingClientRect; exports.matches = matches; exports.contains = contains; /** @module ember */ function isSimpleClick(event) { let modifier = event.shiftKey || event.metaKey || event.altKey || event.ctrlKey; let secondaryClick = event.which > 1; // IE9 may return undefined return !modifier && !secondaryClick; } /* globals Element */ function constructStyleDeprecationMessage(affectedStyle) { return '' + '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 ' + 'https://emberjs.com/deprecations/v1.x/#toc_binding-style-attributes. ' + 'Style affected: "' + affectedStyle + '"'; } /** @private @method getRootViews @param {Object} owner */ function getRootViews(owner) { let registry = owner.lookup('-view-registry:main'); let rootViews = []; Object.keys(registry).forEach(id => { let view = registry[id]; if (view.parentView === null) { rootViews.push(view); } }); return rootViews; } /** @private @method getViewId @param {Ember.View} view */ function getViewId(view) { if (view.tagName !== '' && view.elementId) { return view.elementId; } else { return (0, _utils.guidFor)(view); } } const VIEW_ELEMENT = (0, _utils.symbol)('VIEW_ELEMENT'); /** @private @method getViewElement @param {Ember.View} view */ function getViewElement(view) { return view[VIEW_ELEMENT]; } function initViewElement(view) { view[VIEW_ELEMENT] = null; } function setViewElement(view, element) { return view[VIEW_ELEMENT] = element; } const CHILD_VIEW_IDS = new WeakMap(); /** @private @method getChildViews @param {Ember.View} view */ function getChildViews(view) { let owner = (0, _owner.getOwner)(view); let registry = owner.lookup('-view-registry:main'); return collectChildViews(view, registry); } function initChildViews(view) { let childViews = new Set(); CHILD_VIEW_IDS.set(view, childViews); return childViews; } function addChildView(parent, child) { let childViews = CHILD_VIEW_IDS.get(parent); if (childViews === undefined) { childViews = initChildViews(parent); } childViews.add(getViewId(child)); } function collectChildViews(view, registry) { let views = []; let childViews = CHILD_VIEW_IDS.get(view); if (childViews !== undefined) { childViews.forEach(id => { let view = registry[id]; if (view && !view.isDestroying && !view.isDestroyed) { views.push(view); } }); } return views; } /** @private @method getViewBounds @param {Ember.View} view */ function getViewBounds(view) { return view.renderer.getBounds(view); } /** @private @method getViewRange @param {Ember.View} view */ function getViewRange(view) { let bounds = getViewBounds(view); let range = document.createRange(); range.setStartBefore(bounds.firstNode); range.setEndAfter(bounds.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) { let 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 Inspector and may not work on older browsers. @private @method getViewBoundingClientRect @param {Ember.View} view */ function getViewBoundingClientRect(view) { let range = getViewRange(view); return range.getBoundingClientRect(); } /** Determines if the element matches the specified selector. @private @method matches @param {DOMElement} el @param {String} selector */ const elMatches = exports.elMatches = typeof Element !== 'undefined' && (Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector); function matches(el, selector) { return elMatches.call(el, selector); } function contains(a, b) { if (a.contains !== undefined) { return a.contains(b); } while (b = b.parentNode) { if (b === a) { return true; } } return false; } }); enifed('@ember/-internals/views/lib/utils/lookup-component', ['exports'], function (exports) { 'use strict'; exports.default = lookupComponent; function lookupModuleUnificationComponentPair(componentLookup, owner, name, options) { let localComponent = componentLookup.componentFor(name, owner, options); let localLayout = componentLookup.layoutFor(name, owner, options); let globalComponent = componentLookup.componentFor(name, owner); let globalLayout = componentLookup.layoutFor(name, owner); // TODO: we shouldn't have to recheck fallback, we should have a lookup that doesn't fallback if (localComponent !== undefined && globalComponent !== undefined && globalComponent.class === localComponent.class) { localComponent = undefined; } if (localLayout !== undefined && globalLayout !== undefined && localLayout.referrer.moduleName === globalLayout.referrer.moduleName) { localLayout = undefined; } if (localLayout !== undefined || localComponent !== undefined) { return { layout: localLayout, component: localComponent }; } return { layout: globalLayout, component: globalComponent }; } function lookupComponentPair(componentLookup, owner, name, options) { if (false /* EMBER_MODULE_UNIFICATION */) { return lookupModuleUnificationComponentPair(componentLookup, owner, name, options); } let component = componentLookup.componentFor(name, owner, options); let layout = componentLookup.layoutFor(name, owner, options); let result = { layout, component }; return result; } function lookupComponent(owner, name, options) { let componentLookup = owner.lookup('component-lookup:main'); if (options && (options.source || options.namespace)) { let localResult = lookupComponentPair(componentLookup, owner, name, options); if (localResult.component || localResult.layout) { return localResult; } } return lookupComponentPair(componentLookup, owner, name); } }); enifed('@ember/-internals/views/lib/views/core_view', ['exports', '@ember/-internals/runtime', '@ember/-internals/views/lib/system/utils', '@ember/-internals/views/lib/views/states'], function (exports, _runtime, _utils, _states) { 'use strict'; /** `Ember.CoreView` is an abstract class that exists to give view-like behavior to both Ember's main view class `Component` and other classes that don't need the full functionality of `Component`. Unless you have specific needs for `CoreView`, you will use `Component` in your applications. @class CoreView @namespace Ember @extends EmberObject @deprecated Use `Component` instead. @uses Evented @uses Ember.ActionHandler @private */ const CoreView = _runtime.FrameworkObject.extend(_runtime.Evented, _runtime.ActionHandler, { isView: true, _states: (0, _states.cloneStates)(_states.states), init() { this._super(...arguments); this._state = 'preRender'; this._currentState = this._states.preRender; (0, _utils.initViewElement)(this); if (!this.renderer) { throw new Error(`Cannot instantiate a component without a renderer. Please ensure that you are creating ${this} with a proper container/registry.`); } }, /** 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, instrumentDetails(hash) { hash.object = this.toString(); hash.containerKey = this._debugContainerKey; hash.view = this; return hash; }, /** Override the default event firing from `Evented` to also call methods with the given name. @method trigger @param name {String} @private */ trigger(name, ...args) { this._super(...arguments); let method = this[name]; if (typeof method === 'function') { return method.apply(this, args); } }, has(name) { return typeof this[name] === 'function' || this._super(name); } }); CoreView.reopenClass({ isViewFactory: true }); exports.default = CoreView; }); enifed('@ember/-internals/views/lib/views/states', ['exports', '@ember/polyfills', '@ember/-internals/views/lib/views/states/default', '@ember/-internals/views/lib/views/states/pre_render', '@ember/-internals/views/lib/views/states/has_element', '@ember/-internals/views/lib/views/states/in_dom', '@ember/-internals/views/lib/views/states/destroying'], function (exports, _polyfills, _default2, _pre_render, _has_element, _in_dom, _destroying) { 'use strict'; exports.states = undefined; exports.cloneStates = cloneStates; function cloneStates(from) { let 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 (let stateName in from) { if (!from.hasOwnProperty(stateName)) { continue; } (0, _polyfills.assign)(into[stateName], from[stateName]); } return into; } /* 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 * 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. */ let states = exports.states = { _default: _default2.default, preRender: _pre_render.default, inDOM: _in_dom.default, hasElement: _has_element.default, destroying: _destroying.default }; }); enifed("@ember/-internals/views/lib/views/states/default", ["exports", "@ember/error"], function (exports, _error) { "use strict"; exports.default = { // appendChild is only legal while rendering the buffer. appendChild() { throw new _error.default("You can't use appendChild outside of the rendering process"); }, // Handle events from `Ember.EventDispatcher` handleEvent() { return true; // continue event propagation }, rerender() {}, destroy() {} }; }); enifed('@ember/-internals/views/lib/views/states/destroying', ['exports', '@ember/polyfills', '@ember/error', '@ember/-internals/views/lib/views/states/default'], function (exports, _polyfills, _error, _default2) { 'use strict'; const destroying = Object.create(_default2.default); (0, _polyfills.assign)(destroying, { appendChild() { throw new _error.default("You can't call appendChild on a view being destroyed"); }, rerender() { throw new _error.default("You can't call rerender on a view being destroyed"); } }); exports.default = destroying; }); enifed('@ember/-internals/views/lib/views/states/has_element', ['exports', '@ember/polyfills', '@ember/-internals/views/lib/views/states/default', '@ember/runloop', '@ember/instrumentation'], function (exports, _polyfills, _default2, _runloop, _instrumentation) { 'use strict'; const hasElement = Object.create(_default2.default); (0, _polyfills.assign)(hasElement, { rerender(view) { view.renderer.rerender(view); }, destroy(view) { view.renderer.remove(view); }, // Handle events from `Ember.EventDispatcher` handleEvent(view, eventName, event) { if (view.has(eventName)) { // Handler should be able to re-dispatch events, so we don't // preventDefault or stopPropagation. return (0, _instrumentation.flaggedInstrument)(`interaction.${eventName}`, { event, view }, () => { return (0, _runloop.join)(view, view.trigger, eventName, event); }); } else { return true; // continue event propagation } } }); exports.default = hasElement; }); enifed('@ember/-internals/views/lib/views/states/in_dom', ['exports', '@ember/polyfills', '@ember/-internals/metal', '@ember/error', '@ember/-internals/views/lib/views/states/has_element'], function (exports, _polyfills, _metal, _error, _has_element) { 'use strict'; const inDOM = Object.create(_has_element.default); (0, _polyfills.assign)(inDOM, { enter(view) { // Register the view for event handling. This hash is used by // Ember.EventDispatcher to dispatch incoming events. view.renderer.register(view); if (true /* DEBUG */) { (0, _metal.addObserver)(view, 'elementId', () => { throw new _error.default("Changing a view's elementId after creation is not allowed"); }); } }, exit(view) { view.renderer.unregister(view); } }); exports.default = inDOM; }); enifed('@ember/-internals/views/lib/views/states/pre_render', ['exports', '@ember/-internals/views/lib/views/states/default'], function (exports, _default2) { 'use strict'; exports.default = Object.create(_default2.default); }); enifed('@ember/application/globals-resolver', ['exports', '@ember/-internals/utils', '@ember/-internals/metal', '@ember/debug', '@ember/string', '@ember/-internals/runtime', '@ember/application/lib/validate-type', '@ember/-internals/glimmer'], function (exports, _utils, _metal, _debug, _string, _runtime, _validateType, _glimmer) { 'use strict'; /** 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: ```app/app.js import Application from '@ember/application'; import GlobalsResolver from '@ember/application/globals-resolver'; App = Application.create({ Resolver: GlobalsResolver.extend({ resolveTemplate(parsedName) { let resolvedTemplate = this._super(parsedName); if (resolvedTemplate) { return resolvedTemplate; } return Ember.TEMPLATES['not_found']; } }) }); ``` Some examples of how names are resolved: ```text 'template:post' //=> Ember.TEMPLATES['post'] 'template:posts/byline' //=> Ember.TEMPLATES['posts/byline'] 'template:posts.byline' //=> Ember.TEMPLATES['posts/byline'] 'template:blogPost' //=> Ember.TEMPLATES['blog-post'] 'controller:post' //=> App.PostController 'controller:posts.index' //=> App.PostsIndexController 'controller:blog/post' //=> Blog.PostController 'controller:basic' //=> Controller 'route:post' //=> App.PostRoute 'route:posts.index' //=> App.PostsIndexRoute 'route:blog/post' //=> Blog.PostRoute 'route:basic' //=> Route 'foo:post' //=> App.PostFoo 'model:post' //=> App.Post ``` @class GlobalsResolver @extends EmberObject @public */ class DefaultResolver extends _runtime.Object { static create(props) { // DO NOT REMOVE even though this doesn't do anything // This is required for a FireFox 60+ JIT bug with our tests. // without it, create(props) in our tests would lose props on a deopt. return super.create(props); } /** This will be set to the Application instance when it is created. @property namespace @public */ init() { this._parseNameCache = (0, _utils.dictionary)(null); } normalize(fullName) { let [type, name] = fullName.split(':'); true && !(fullName.split(':').length === 2) && (0, _debug.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') { let result = name.replace(/(\.|_|-)./g, m => 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(fullName) { let parsedName = this.parseName(fullName); let resolveMethodName = parsedName.resolveMethodName; let resolved; if (this[resolveMethodName]) { resolved = this[resolveMethodName](parsedName); } resolved = resolved || this.resolveOther(parsedName); if (true /* DEBUG */) { if (parsedName.root && parsedName.root.LOG_RESOLVER) { this._logLookup(resolved, parsedName); } } if (resolved) { (0, _validateType.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(fullName) { return this._parseNameCache[fullName] || (this._parseNameCache[fullName] = this._parseName(fullName)); } _parseName(fullName) { let [type, fullNameWithoutType] = fullName.split(':'); let name = fullNameWithoutType; let namespace = (0, _metal.get)(this, 'namespace'); let root = namespace; let lastSlashIndex = name.lastIndexOf('/'); let dirname = lastSlashIndex !== -1 ? name.slice(0, lastSlashIndex) : null; if (type !== 'template' && lastSlashIndex !== -1) { let parts = name.split('/'); name = parts[parts.length - 1]; let namespaceName = (0, _string.capitalize)(parts.slice(0, -1).join('.')); root = (0, _metal.findNamespace)(namespaceName); true && !root && (0, _debug.assert)(`You are looking for a ${name} ${type} in the ${namespaceName} namespace, but the namespace could not be found`, root); } let resolveMethodName = fullNameWithoutType === 'main' ? 'Main' : (0, _string.classify)(type); if (!(name && type)) { throw new TypeError(`Invalid fullName: \`${fullName}\`, must be of the form \`type:name\` `); } return { fullName, type, fullNameWithoutType, dirname, name, 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(fullName) { let parsedName = this.parseName(fullName); let description; if (parsedName.type === 'template') { return `template at ${parsedName.fullNameWithoutType.replace(/\./g, '/')}`; } description = `${parsedName.root}.${(0, _string.classify)(parsedName.name).replace(/\./g, '')}`; if (parsedName.type !== 'model') { description += (0, _string.classify)(parsedName.type); } return description; } makeToString(factory) { return factory.toString(); } /** Given a parseName object (output from `parseName`), apply the conventions expected by `Router` @param {Object} parsedName a parseName object with the parsed fullName lookup string @method useRouterNaming @protected */ useRouterNaming(parsedName) { if (parsedName.name === 'basic') { parsedName.name = ''; } else { parsedName.name = parsedName.name.replace(/\./g, '_'); } } /** Look up the template in Ember.TEMPLATES @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveTemplate @protected */ resolveTemplate(parsedName) { let templateName = parsedName.fullNameWithoutType.replace(/\./g, '/'); return (0, _glimmer.getTemplate)(templateName) || (0, _glimmer.getTemplate)((0, _string.decamelize)(templateName)); } /** Lookup the view using `resolveOther` @param {Object} parsedName a parseName object with the parsed fullName lookup string @method resolveView @protected */ resolveView(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(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(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(parsedName) { let className = (0, _string.classify)(parsedName.name); let factory = (0, _metal.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(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(parsedName) { let className = (0, _string.classify)(parsedName.name) + (0, _string.classify)(parsedName.type); let factory = (0, _metal.get)(parsedName.root, className); return factory; } resolveMain(parsedName) { let className = (0, _string.classify)(parsedName.type); return (0, _metal.get)(parsedName.root, className); } /** Used to iterate all items of a given type. @method knownForType @param {String} type the type to search for @private */ knownForType(type) { let namespace = (0, _metal.get)(this, 'namespace'); let suffix = (0, _string.classify)(type); let typeRegexp = new RegExp(`${suffix}$`); let known = (0, _utils.dictionary)(null); let knownKeys = Object.keys(namespace); for (let index = 0; index < knownKeys.length; index++) { let name = knownKeys[index]; if (typeRegexp.test(name)) { let 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(type, name) { let suffix = (0, _string.classify)(type); let namePrefix = name.slice(0, suffix.length * -1); let dasherizedName = (0, _string.dasherize)(namePrefix); return `${type}:${dasherizedName}`; } } /** @module @ember/application */ exports.default = DefaultResolver; if (true /* DEBUG */) { /** @method _logLookup @param {Boolean} found @param {Object} parsedName @private */ DefaultResolver.prototype._logLookup = function (found, parsedName) { let symbol = found ? '[✓]' : '[ ]'; let padding; if (parsedName.fullName.length > 60) { padding = '.'; } else { padding = new Array(60 - parsedName.fullName.length).join('.'); } (0, _debug.info)(symbol, parsedName.fullName, padding, this.lookupDescription(parsedName.fullName)); }; } }); enifed('@ember/application/index', ['exports', '@ember/-internals/owner', '@ember/application/lib/lazy_load', '@ember/application/lib/application'], function (exports, _owner, _lazy_load, _application) { 'use strict'; Object.defineProperty(exports, 'getOwner', { enumerable: true, get: function () { return _owner.getOwner; } }); Object.defineProperty(exports, 'setOwner', { enumerable: true, get: function () { return _owner.setOwner; } }); Object.defineProperty(exports, 'onLoad', { enumerable: true, get: function () { return _lazy_load.onLoad; } }); Object.defineProperty(exports, 'runLoadHooks', { enumerable: true, get: function () { return _lazy_load.runLoadHooks; } }); Object.defineProperty(exports, '_loaded', { enumerable: true, get: function () { return _lazy_load._loaded; } }); Object.defineProperty(exports, 'default', { enumerable: true, get: function () { return _application.default; } }); }); enifed('@ember/application/instance', ['exports', '@ember/polyfills', '@ember/-internals/metal', '@ember/-internals/browser-environment', '@ember/-internals/views', '@ember/engine/instance', '@ember/-internals/glimmer'], function (exports, _polyfills, _metal, _browserEnvironment, _views, _instance, _glimmer) { 'use strict'; /** 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 ApplicationInstance @extends EngineInstance */ /** @module @ember/application */ const ApplicationInstance = _instance.default.extend({ /** The `Application` for which this is an instance. @property {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() { this._super(...arguments); this.application._watchInstance(this); // 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(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) { let router = (0, _metal.get)(this, 'router'); (0, _metal.set)(router, 'location', options.location); } this.application.runInstanceInitializers(this); if (options.isInteractive) { this.setupEventDispatcher(); } this._booted = true; return this; }, setupRegistry(options) { this.constructor.setupRegistry(this.__registry__, options); }, router: (0, _metal.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(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() { let router = (0, _metal.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() { if (this._didSetupRouter) { return; } this._didSetupRouter = true; let router = (0, _metal.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(url) { let router = (0, _metal.get)(this, 'router'); this.setupRouter(); return router.handleURL(url); }, /** @private */ setupEventDispatcher() { let dispatcher = this.lookup('event_dispatcher:main'); let applicationCustomEvents = (0, _metal.get)(this.application, 'customEvents'); let instanceCustomEvents = (0, _metal.get)(this, 'customEvents'); let customEvents = (0, _polyfills.assign)({}, 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() { return (0, _metal.get)(this, '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(url) { this.setupRouter(); let bootOptions = this.__container__.lookup('-environment:main'); let router = (0, _metal.get)(this, 'router'); let handleTransitionResolve = () => { if (!bootOptions.options.shouldRender) { // No rendering is needed, and routing has completed, simply return. return this; } else { // Ensure that the visit promise resolves when all rendering has completed return (0, _glimmer.renderSettled)().then(() => this); } }; let handleTransitionReject = error => { if (error.error) { throw error.error; } else if (error.name === 'TransitionAborted' && router._routerMicrolib.activeTransition) { return router._routerMicrolib.activeTransition.then(handleTransitionResolve, handleTransitionReject); } else if (error.name === 'TransitionAborted') { throw new Error(error.message); } else { throw error; } }; let location = (0, _metal.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(handleTransitionResolve, handleTransitionReject); }, willDestroy() { this._super(...arguments); this.application._unwatchInstance(this); } }); ApplicationInstance.reopenClass({ /** @private @method setupRegistry @param {Registry} registry @param {BootOptions} options */ setupRegistry(registry, options = {}) { if (!options.toEnvironment) { options = new BootOptions(options); } 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 `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 `Application#visit` for the supported configurations. Internal, experimental or otherwise unstable flags are marked as private. @class BootOptions @namespace ApplicationInstance @public */ class BootOptions { constructor(options = {}) { /** 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 = _views.jQuery; // 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 = _browserEnvironment.hasDOM; // This default is overridable below /** @property _renderMode @type string @default false @private */ this._renderMode = options._renderMode; /** Run in a full browser environment. When this flag is set to `true`, 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 = _browserEnvironment.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 `Application`'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; } } toEnvironment() { // Do we really want to assign all of this!? let env = (0, _polyfills.assign)({}, _browserEnvironment); // For compatibility with existing code env.hasDOM = this.isBrowser; env.isInteractive = this.isInteractive; env._renderMode = this._renderMode; env.options = this; return env; } } exports.default = ApplicationInstance; }); enifed('@ember/application/lib/application', ['exports', '@ember/-internals/utils', '@ember/-internals/environment', '@ember/-internals/browser-environment', '@ember/debug', '@ember/runloop', '@ember/-internals/metal', '@ember/application/lib/lazy_load', '@ember/-internals/runtime', '@ember/-internals/views', '@ember/-internals/routing', '@ember/application/instance', '@ember/engine', '@ember/-internals/container', '@ember/-internals/glimmer'], function (exports, _utils, _environment, _browserEnvironment, _debug, _runloop, _metal, _lazy_load, _runtime, _views, _routing, _instance, _engine, _container, _glimmer) { 'use strict'; let librariesRegistered = false; /** An instance of `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 `Application` object. In fact, the very first thing you should do in your application is create the instance: ```javascript import Application from '@ember/application'; window.App = Application.create(); ``` Typically, the application object is the only global variable. All other classes in your app should be properties on the `Application` instance, which highlights its first role: a global namespace. For example, if you define a view class, it might look like this: ```javascript import Application from '@ember/application'; App.MyView = Ember.View.extend(); ``` By default, calling `Application.create()` will automatically initialize your application by calling the `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 `Application` instance, which will be run by Ember when the application is initialized. Because `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 `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. `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 import Application from '@ember/application'; let App = 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 import Application from '@ember/application'; let App = 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 import Application from '@ember/application'; let App = 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/release/components/handling-events/#toc_event-names). ### Initializers Libraries on top of Ember can add initializers, like so: ```javascript import Application from '@ember/application'; 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, `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 import Application from '@ember/application'; let App = 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 @extends Engine @uses RegistryProxyMixin @public */ /** @module @ember/application */ const Application = _engine.default.extend({ /** 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 `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 import Application from '@ember/application'; let App = Application.create({ customEvents: { // add support for the paste event paste: 'paste' } }); ``` To prevent default events from being listened to: ```javascript import Application from '@ember/application'; let App = 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 import Application from '@ember/application'; import Component from '@ember/component'; let App = Application.create({ ... }); App.Router.reopen({ location: 'none' }); App.Router.map({ ... }); App.MyComponent = 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, /** An array of application instances created by `buildInstance()`. Used internally to ensure that all instances get destroyed. @property _applicationInstances @type Array @default null @private */ _applicationInstances: null, init() { // eslint-disable-line no-unused-vars this._super(...arguments); if (!this.$) { this.$ = _views.jQuery; } registerLibraries(); if (true /* DEBUG */) { if (_environment.ENV.LOG_VERSION) { // we only need to see this once per Application#init _environment.ENV.LOG_VERSION = false; _metal.libraries.logVersions(); } } // 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._applicationInstances = new Set(); this.autoboot = this._globalsMode = !!this.autoboot; if (this._globalsMode) { this._prepareForGlobalsMode(); } if (this.autoboot) { this.waitForDOMReady(); } }, /** Create an ApplicationInstance for this application. @public @method buildInstance @return {ApplicationInstance} the application instance */ buildInstance(options = {}) { options.base = this; options.application = this; return _instance.default.create(options); }, /** Start tracking an ApplicationInstance for this application. Used when the ApplicationInstance is created. @private @method _watchInstance */ _watchInstance(instance) { this._applicationInstances.add(instance); }, /** Stop tracking an ApplicationInstance for this application. Used when the ApplicationInstance is about to be destroyed. @private @method _unwatchInstance */ _unwatchInstance(instance) { return this._applicationInstances.delete(instance); }, /** 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() { // Create subclass of Router for this Application instance. // This is to ensure that someone reopening `App.Router` does not // tamper with the default `Router`. this.Router = (this.Router || _routing.Router).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() { // Build a default instance let 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() { if (!this.$ || this.$.isReady) { (0, _runloop.schedule)('actions', this, 'domReady'); } else { this.$().ready((0, _runloop.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() { if (this.isDestroyed) { return; } this._bootSync(); // Continues to `didBecomeReady` }, /** Use this to defer readiness until some condition is true. Example: ```javascript import Application from '@ember/application'; let App = Application.create(); App.deferReadiness(); // $ is a reference to the jQuery object/function import $ from 'jquery; $.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() { true && !(this instanceof Application) && (0, _debug.assert)('You must call deferReadiness on an instance of Application', this instanceof Application); true && !(this._readinessDeferrals > 0) && (0, _debug.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 {Application#deferReadiness} @public */ advanceReadiness() { true && !(this instanceof Application) && (0, _debug.assert)('You must call advanceReadiness on an instance of Application', this instanceof Application); this._readinessDeferrals--; if (this._readinessDeferrals === 0) { (0, _runloop.once)(this, this.didBecomeReady); } }, /** Initialize the application and return a promise that resolves with the `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`. @public @method boot @return {Promise} */ boot() { if (this._bootPromise) { return this._bootPromise; } try { this._bootSync(); } catch (_) { // Ignore the 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() { 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. let defer = this._bootResolver = _runtime.RSVP.defer(); this._bootPromise = defer.promise; try { this.runInitializers(); (0, _lazy_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 import Application from '@ember/application'; let App; run(function() { App = 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 import Application from '@ember/application'; let App; run(function() { App = 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() { true && !(this._globalsMode && this.autoboot) && (0, _debug.assert)(`Calling reset() on instances of \`Application\` is not supported when globals mode is disabled; call \`visit()\` to create new \`ApplicationInstance\`s and dispose them via their \`destroy()\` method instead.`, this._globalsMode && this.autoboot); let instance = this.__deprecatedInstance__; this._readinessDeferrals = 1; this._bootPromise = null; this._bootResolver = null; this._booted = false; function handleReset() { (0, _runloop.run)(instance, 'destroy'); this._buildDeprecatedInstance(); (0, _runloop.schedule)('actions', this, '_bootSync'); } (0, _runloop.join)(this, handleReset); }, /** @private @method didBecomeReady */ didBecomeReady() { try { // TODO: Is this still needed for _globalsMode = false? if (!(0, _debug.isTesting)()) { // Eagerly name all classes that are already loaded (0, _metal.processAllNamespaces)(); (0, _metal.setNamespaceSearchDisabled)(true); } // See documentation on `_autoboot()` for details if (this.autoboot) { let instance; 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() { return this; }, // This method must be moved to the application instance object willDestroy() { this._super(...arguments); (0, _metal.setNamespaceSearchDisabled)(false); this._booted = false; this._bootPromise = null; this._bootResolver = null; if (_lazy_load._loaded.application === this) { _lazy_load._loaded.application = undefined; } if (this._applicationInstances.size) { this._applicationInstances.forEach(i => i.destroy()); this._applicationInstances.clear(); } }, /** Boot a new instance of `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 occurred 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 `ApplicationInstance.BootOptions` for details. `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 foreign `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 needs 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 `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 fulfill 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 appropriate implementation 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 Route from '@ember/routing/route'; // An example of how the (hypothetical) service is used in routes. export default 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 {ApplicationInstance.BootOptions} @return {Promise} */ visit(url, options) { return this.boot().then(() => { let instance = this.buildInstance(); return instance.boot(options).then(() => instance.visit(url)).catch(error => { (0, _runloop.run)(instance, 'destroy'); throw error; }); }); } }); 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 {Application} namespace the application for which to build the registry @return {Ember.Registry} the built registry @private */ buildRegistry() { // eslint-disable-line no-unused-vars let registry = this._super(...arguments); commonSetupRegistry(registry); (0, _glimmer.setupApplicationRegistry)(registry); return registry; } }); function commonSetupRegistry(registry) { registry.register('router:main', _routing.Router.extend()); registry.register('-view-registry:main', { create() { return (0, _utils.dictionary)(null); } }); registry.register('route:basic', _routing.Route); registry.register('event_dispatcher:main', _views.EventDispatcher); registry.injection('router:main', 'namespace', 'application:main'); registry.register('location:auto', _routing.AutoLocation); registry.register('location:hash', _routing.HashLocation); registry.register('location:history', _routing.HistoryLocation); registry.register('location:none', _routing.NoneLocation); registry.register(_container.privatize`-bucket-cache:main`, { create() { return new _routing.BucketCache(); } }); registry.register('service:router', _routing.RouterService); registry.injection('service:router', '_router', 'router:main'); } function registerLibraries() { if (!librariesRegistered) { librariesRegistered = true; if (_browserEnvironment.hasDOM && !_views.jQueryDisabled) { _metal.libraries.registerCoreLibrary('jQuery', (0, _views.jQuery)().jquery); } } } exports.default = Application; }); enifed('@ember/application/lib/lazy_load', ['exports', '@ember/-internals/environment', '@ember/-internals/browser-environment'], function (exports, _environment, _browserEnvironment) { 'use strict'; exports._loaded = undefined; exports.onLoad = onLoad; exports.runLoadHooks = runLoadHooks; /** @module @ember/application */ /*globals CustomEvent */ const loadHooks = _environment.ENV.EMBER_LOAD_HOOKS || {}; const loaded = {}; let _loaded = exports._loaded = loaded; /** Detects when a specific package of Ember (e.g. '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 import { onLoad } from '@ember/application'; onLoad('Ember.Application' function(hbars) { hbars.registerHelper(...); }); ``` @method onLoad @static @for @ember/application @param name {String} name of hook @param callback {Function} callback to be called @private */ function onLoad(name, callback) { let object = loaded[name]; loadHooks[name] = loadHooks[name] || []; loadHooks[name].push(callback); if (object) { callback(object); } } /** Called when an Ember.js package (e.g Application) has finished loading. Triggers any callbacks registered for this event. @method runLoadHooks @static @for @ember/application @param name {String} name of hook @param object {Object} object to pass to callbacks @private */ function runLoadHooks(name, object) { loaded[name] = object; if (_browserEnvironment.window && typeof CustomEvent === 'function') { let event = new CustomEvent(name, { detail: object, name }); _browserEnvironment.window.dispatchEvent(event); } if (loadHooks[name]) { loadHooks[name].forEach(callback => callback(object)); } } }); enifed('@ember/application/lib/validate-type', ['exports', '@ember/debug'], function (exports, _debug) { 'use strict'; exports.default = validateType; const 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) { let validationAttributes = VALIDATED_TYPES[parsedName.type]; if (!validationAttributes) { return; } let [, factoryFlag, expectedType] = validationAttributes; true && !!!resolvedType[factoryFlag] && (0, _debug.assert)(`Expected ${parsedName.fullName} to resolve to an ${expectedType} but ` + `instead it was ${resolvedType}.`, !!resolvedType[factoryFlag]); } }); enifed('@ember/canary-features/index', ['exports', '@ember/-internals/environment', '@ember/polyfills'], function (exports, _environment, _polyfills) { 'use strict'; exports.EMBER_GLIMMER_ANGLE_BRACKET_INVOCATION = exports.EMBER_TEMPLATE_BLOCK_LET_HELPER = exports.GLIMMER_CUSTOM_COMPONENT_MANAGER = exports.EMBER_METAL_TRACKED_PROPERTIES = exports.EMBER_MODULE_UNIFICATION = exports.EMBER_ENGINES_MOUNT_PARAMS = exports.EMBER_ROUTING_ROUTER_SERVICE = exports.EMBER_GLIMMER_NAMED_ARGUMENTS = exports.EMBER_IMPROVED_INSTRUMENTATION = exports.EMBER_LIBRARIES_ISREGISTERED = exports.FEATURES = exports.DEFAULT_FEATURES = undefined; exports.isEnabled = isEnabled; /** Set `EmberENV.FEATURES` in your application's `config/environment.js` file to enable canary features in your application. See the [feature flag guide](https://guides.emberjs.com/release/configuring-ember/feature-flags/) for more details. @module @ember/canary-features @public */ const DEFAULT_FEATURES = exports.DEFAULT_FEATURES = { EMBER_LIBRARIES_ISREGISTERED: false, EMBER_IMPROVED_INSTRUMENTATION: false, EMBER_GLIMMER_NAMED_ARGUMENTS: true, EMBER_ROUTING_ROUTER_SERVICE: true, EMBER_ENGINES_MOUNT_PARAMS: true, EMBER_MODULE_UNIFICATION: false, GLIMMER_CUSTOM_COMPONENT_MANAGER: true, EMBER_TEMPLATE_BLOCK_LET_HELPER: true, EMBER_METAL_TRACKED_PROPERTIES: false, EMBER_GLIMMER_ANGLE_BRACKET_INVOCATION: true }; /** The hash of enabled Canary features. Add to this, any canary features before creating your application. @class FEATURES @static @since 1.1.0 @public */ const FEATURES = exports.FEATURES = (0, _polyfills.assign)(DEFAULT_FEATURES, _environment.ENV.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} @since 1.1.0 @public */ function isEnabled(feature) { let featureValue = FEATURES[feature]; if (featureValue === true || featureValue === false) { return featureValue; } else if (_environment.ENV.ENABLE_OPTIONAL_FEATURES) { return true; } else { return false; } } function featureValue(value) { if (_environment.ENV.ENABLE_OPTIONAL_FEATURES && value === null) { return true; } return value; } const EMBER_LIBRARIES_ISREGISTERED = exports.EMBER_LIBRARIES_ISREGISTERED = featureValue(FEATURES.EMBER_LIBRARIES_ISREGISTERED); const EMBER_IMPROVED_INSTRUMENTATION = exports.EMBER_IMPROVED_INSTRUMENTATION = featureValue(FEATURES.EMBER_IMPROVED_INSTRUMENTATION); const EMBER_GLIMMER_NAMED_ARGUMENTS = exports.EMBER_GLIMMER_NAMED_ARGUMENTS = featureValue(FEATURES.EMBER_GLIMMER_NAMED_ARGUMENTS); const EMBER_ROUTING_ROUTER_SERVICE = exports.EMBER_ROUTING_ROUTER_SERVICE = featureValue(FEATURES.EMBER_ROUTING_ROUTER_SERVICE); const EMBER_ENGINES_MOUNT_PARAMS = exports.EMBER_ENGINES_MOUNT_PARAMS = featureValue(FEATURES.EMBER_ENGINES_MOUNT_PARAMS); const EMBER_MODULE_UNIFICATION = exports.EMBER_MODULE_UNIFICATION = featureValue(FEATURES.EMBER_MODULE_UNIFICATION); const EMBER_METAL_TRACKED_PROPERTIES = exports.EMBER_METAL_TRACKED_PROPERTIES = featureValue(FEATURES.EMBER_METAL_TRACKED_PROPERTIES); const GLIMMER_CUSTOM_COMPONENT_MANAGER = exports.GLIMMER_CUSTOM_COMPONENT_MANAGER = featureValue(FEATURES.GLIMMER_CUSTOM_COMPONENT_MANAGER); const EMBER_TEMPLATE_BLOCK_LET_HELPER = exports.EMBER_TEMPLATE_BLOCK_LET_HELPER = featureValue(FEATURES.EMBER_TEMPLATE_BLOCK_LET_HELPER); const EMBER_GLIMMER_ANGLE_BRACKET_INVOCATION = exports.EMBER_GLIMMER_ANGLE_BRACKET_INVOCATION = featureValue(FEATURES.EMBER_GLIMMER_ANGLE_BRACKET_INVOCATION); }); enifed('@ember/controller/index', ['exports', '@ember/-internals/runtime', '@ember/controller/lib/controller_mixin', '@ember/-internals/metal'], function (exports, _runtime, _controller_mixin, _metal) { 'use strict'; exports.inject = inject; /** @module @ember/controller */ /** @class Controller @extends EmberObject @uses Ember.ControllerMixin @public */ const Controller = _runtime.Object.extend(_controller_mixin.default); /** Creates a property that lazily looks up another controller in the container. Can only be used when defining another controller. Example: ```app/controllers/post.js import Controller, { inject as controller } from '@ember/controller'; export default Controller.extend({ posts: 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. @method inject @static @for @ember/controller @since 1.10.0 @param {String} name (optional) name of the controller to inject, defaults to the property's name @return {Ember.InjectedProperty} injection descriptor instance @public */ function inject(name, options) { return new _metal.InjectedProperty('controller', name, options); } exports.default = Controller; }); enifed('@ember/controller/lib/controller_mixin', ['exports', '@ember/-internals/metal', '@ember/-internals/runtime'], function (exports, _metal, _runtime) { 'use strict'; exports.default = _metal.Mixin.create(_runtime.ActionHandler, { /* 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 }); }); enifed('@ember/debug/index', ['exports', '@ember/debug/lib/warn', '@ember/debug/lib/deprecate', '@ember/debug/lib/testing', '@ember/-internals/browser-environment', '@ember/error'], function (exports, _warn2, _deprecate2, _testing, _browserEnvironment, _error) { 'use strict'; exports._warnIfUsingStrippedFeatureFlags = exports.getDebugFunction = exports.setDebugFunction = exports.deprecateFunc = exports.runInDebug = exports.debugFreeze = exports.debugSeal = exports.deprecate = exports.debug = exports.warn = exports.info = exports.assert = exports.setTesting = exports.isTesting = exports.registerDeprecationHandler = exports.registerWarnHandler = undefined; Object.defineProperty(exports, 'registerWarnHandler', { enumerable: true, get: function () { return _warn2.registerHandler; } }); Object.defineProperty(exports, 'registerDeprecationHandler', { enumerable: true, get: function () { return _deprecate2.registerHandler; } }); Object.defineProperty(exports, 'isTesting', { enumerable: true, get: function () { return _testing.isTesting; } }); Object.defineProperty(exports, 'setTesting', { enumerable: true, get: function () { return _testing.setTesting; } }); // These are the default production build versions: const noop = () => {}; let assert = noop; let info = noop; let warn = noop; let debug = noop; let deprecate = noop; let debugSeal = noop; let debugFreeze = noop; let runInDebug = noop; let setDebugFunction = noop; let getDebugFunction = noop; let deprecateFunc = function () { return arguments[arguments.length - 1]; }; if (true /* DEBUG */) { exports.setDebugFunction = setDebugFunction = function (type, callback) { switch (type) { case 'assert': return exports.assert = assert = callback; case 'info': return exports.info = info = callback; case 'warn': return exports.warn = warn = callback; case 'debug': return exports.debug = debug = callback; case 'deprecate': return exports.deprecate = deprecate = callback; case 'debugSeal': return exports.debugSeal = debugSeal = callback; case 'debugFreeze': return exports.debugFreeze = debugFreeze = callback; case 'runInDebug': return exports.runInDebug = runInDebug = callback; case 'deprecateFunc': return exports.deprecateFunc = deprecateFunc = callback; } }; exports.getDebugFunction = getDebugFunction = function (type) { switch (type) { case 'assert': return assert; case 'info': return info; case 'warn': return warn; case 'debug': return debug; case 'deprecate': return deprecate; case 'debugSeal': return debugSeal; case 'debugFreeze': return debugFreeze; case 'runInDebug': return runInDebug; case 'deprecateFunc': return deprecateFunc; } }; } /** @module @ember/debug */ if (true /* DEBUG */) { /** Verify that a certain expectation is met, or throw a exception otherwise. This is useful for communicating assumptions in the code to other human readers as well as catching bugs that accidentally violates these expectations. Assertions are removed from production builds, so they can be freely added for documentation and debugging purposes without worries of incuring any performance penalty. However, because of that, they should not be used for checks that could reasonably fail during normal usage. Furthermore, care should be taken to avoid accidentally relying on side-effects produced from evaluating the condition itself, since the code will not run in production. ```javascript import { assert } from '@ember/debug'; // Test for truthiness assert('Must pass a string', typeof str === 'string'); // Fail unconditionally assert('This code path should never be run'); ``` @method assert @static @for @ember/debug @param {String} description Describes the expectation. This will become the text of the Error thrown if the assertion fails. @param {Boolean} condition Must be truthy for the assertion to pass. If falsy, an exception will be thrown. @public @since 1.0.0 */ setDebugFunction('assert', function assert(desc, test) { if (!test) { throw new _error.default(`Assertion Failed: ${desc}`); } }); /** Display a debug notice. Calls to this function are removed from production builds, so they can be freely added for documentation and debugging purposes without worries of incuring any performance penalty. ```javascript import { debug } from '@ember/debug'; debug('I\'m a debug notice!'); ``` @method debug @for @ember/debug @static @param {String} message A debug message to display. @public */ setDebugFunction('debug', function debug(message) { /* eslint-disable no-console */ if (console.debug) { console.debug(`DEBUG: ${message}`); } else { console.log(`DEBUG: ${message}`); } /* eslint-ensable no-console */ }); /** Display an info notice. Calls to this function are removed from production builds, so they can be freely added for documentation and debugging purposes without worries of incuring any performance penalty. @method info @private */ setDebugFunction('info', function info() { console.info(...arguments); /* eslint-disable-line no-console */ }); /** @module @ember/application @public */ /** 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. Calls to this function are removed from production builds, so they can be freely added for documentation and debugging purposes without worries of incuring any performance penalty. ```javascript import { deprecateFunc } from '@ember/application/deprecations'; Ember.oldMethod = deprecateFunc('Please use the new, updated method', options, Ember.newMethod); ``` @method deprecateFunc @static @for @ember/application/deprecations @param {String} message A description of the deprecation. @param {Object} [options] The options object for `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 */ setDebugFunction('deprecateFunc', function deprecateFunc(...args) { if (args.length === 3) { let [message, options, func] = args; return function () { deprecate(message, false, options); return func.apply(this, arguments); }; } else { let [message, func] = args; return function () { deprecate(message); return func.apply(this, arguments); }; } }); /** @module @ember/debug @public */ /** Run a function meant for debugging. Calls to this function are removed from production builds, so they can be freely added for documentation and debugging purposes without worries of incuring any performance penalty. ```javascript import Component from '@ember/component'; import { runInDebug } from '@ember/debug'; runInDebug(() => { Component.reopen({ didInsertElement() { console.log("I'm happy"); } }); }); ``` @method runInDebug @for @ember/debug @static @param {Function} func The function to be executed. @since 1.5.0 @public */ setDebugFunction('runInDebug', function runInDebug(func) { func(); }); setDebugFunction('debugSeal', function debugSeal(obj) { Object.seal(obj); }); setDebugFunction('debugFreeze', function debugFreeze(obj) { Object.freeze(obj); }); setDebugFunction('deprecate', _deprecate2.default); setDebugFunction('warn', _warn2.default); } let _warnIfUsingStrippedFeatureFlags; if (true /* DEBUG */ && !(0, _testing.isTesting)()) { if (typeof window !== 'undefined' && (_browserEnvironment.isFirefox || _browserEnvironment.isChrome) && window.addEventListener) { window.addEventListener('load', () => { if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset.emberExtension) { let downloadURL; if (_browserEnvironment.isChrome) { downloadURL = 'https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi'; } else if (_browserEnvironment.isFirefox) { downloadURL = 'https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/'; } debug(`For more advanced debugging, install the Ember Inspector from ${downloadURL}`); } }, false); } } exports.assert = assert; exports.info = info; exports.warn = warn; exports.debug = debug; exports.deprecate = deprecate; exports.debugSeal = debugSeal; exports.debugFreeze = debugFreeze; exports.runInDebug = runInDebug; exports.deprecateFunc = deprecateFunc; exports.setDebugFunction = setDebugFunction; exports.getDebugFunction = getDebugFunction; exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags; }); enifed('@ember/debug/lib/deprecate', ['exports', '@ember/-internals/environment', '@ember/debug/index', '@ember/debug/lib/handlers'], function (exports, _environment, _index, _handlers) { 'use strict'; exports.missingOptionsUntilDeprecation = exports.missingOptionsIdDeprecation = exports.missingOptionsDeprecation = exports.registerHandler = undefined; /** @module @ember/debug @public */ /** Allows for runtime registration of handler functions that override the default deprecation behavior. Deprecations are invoked by calls to [@ember/application/deprecations/deprecate](https://emberjs.com/api/ember/release/classes/@ember%2Fapplication%2Fdeprecations/methods/deprecate?anchor=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 import { registerDeprecationHandler } from '@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:
  • message - The message received from the deprecation call.
  • options - An object passed in with the deprecation call containing additional information including:
    • id - An id of the deprecation in the form of package-name.specific-deprecation.
    • until - The Ember version number the feature and deprecation will be removed in.
  • next - A function that calls into the previously registered handler.
@public @static @method registerDeprecationHandler @for @ember/debug @param handler {Function} A function to handle deprecation calls. @since 2.1.0 */ let registerHandler = () => {}; let missingOptionsDeprecation; let missingOptionsIdDeprecation; let missingOptionsUntilDeprecation; let deprecate = () => {}; if (true /* DEBUG */) { exports.registerHandler = registerHandler = function registerHandler(handler) { (0, _handlers.registerHandler)('deprecate', handler); }; let formatMessage = function formatMessage(_message, options) { let 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) { let updatedMessage = formatMessage(message, options); console.warn(`DEPRECATION: ${updatedMessage}`); // eslint-disable-line no-console }); let captureErrorForStack; if (new Error().stack) { captureErrorForStack = () => new Error(); } else { captureErrorForStack = () => { try { __fail__.fail(); } catch (e) { return e; } }; } registerHandler(function logDeprecationStackTrace(message, options, next) { if (_environment.ENV.LOG_STACKTRACE_ON_DEPRECATION) { let stackStr = ''; let error = captureErrorForStack(); let stack; if (error.stack) { if (error['arguments']) { // Chrome stack = error.stack.replace(/^\s+at\s+/gm, '').replace(/^([^\(]+?)([\n$])/gm, '{anonymous}($1)$2').replace(/^Object.\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 ')}`; } let updatedMessage = formatMessage(message, options); console.warn(`DEPRECATION: ${updatedMessage}${stackStr}`); // eslint-disable-line no-console } else { next(message, options); } }); registerHandler(function raiseOnDeprecation(message, options, next) { if (_environment.ENV.RAISE_ON_DEPRECATION) { let updatedMessage = formatMessage(message); throw new Error(updatedMessage); } else { next(message, options); } }); exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `deprecate` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include `id` and `until` properties.'; exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `deprecate` you must provide `id` in options.'; exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation = 'When calling `deprecate` you must provide `until` in options.'; /** @module @ember/application @public */ /** 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 @for @ember/application/deprecations @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. @static @public @since 1.0.0 */ deprecate = function deprecate(message, test, options) { (0, _index.assert)(missingOptionsDeprecation, !!(options && (options.id || options.until))); (0, _index.assert)(missingOptionsIdDeprecation, !!options.id); (0, _index.assert)(missingOptionsUntilDeprecation, !!options.until); (0, _handlers.invoke)('deprecate', message, test, options); }; } exports.default = deprecate; exports.registerHandler = registerHandler; exports.missingOptionsDeprecation = missingOptionsDeprecation; exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation; exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation; }); enifed("@ember/debug/lib/handlers", ["exports"], function (exports) { "use strict"; let HANDLERS = exports.HANDLERS = {}; let registerHandler = () => {}; let invoke = () => {}; if (true /* DEBUG */) { exports.registerHandler = registerHandler = function registerHandler(type, callback) { let nextHandler = HANDLERS[type] || (() => {}); HANDLERS[type] = (message, options) => { callback(message, options, nextHandler); }; }; exports.invoke = invoke = function invoke(type, message, test, options) { if (test) { return; } let handlerForType = HANDLERS[type]; if (handlerForType) { handlerForType(message, options); } }; } exports.registerHandler = registerHandler; exports.invoke = invoke; }); enifed("@ember/debug/lib/testing", ["exports"], function (exports) { "use strict"; exports.isTesting = isTesting; exports.setTesting = setTesting; let testing = false; function isTesting() { return testing; } function setTesting(value) { testing = !!value; } }); enifed('@ember/debug/lib/warn', ['exports', '@ember/debug/index', '@ember/debug/lib/handlers'], function (exports, _index, _handlers) { 'use strict'; exports.missingOptionsDeprecation = exports.missingOptionsIdDeprecation = exports.registerHandler = undefined; let registerHandler = () => {}; let warn = () => {}; let missingOptionsDeprecation; let missingOptionsIdDeprecation; /** @module @ember/debug */ if (true /* DEBUG */) { /** Allows for runtime registration of handler functions that override the default warning behavior. Warnings are invoked by calls made to [@ember/debug/warn](https://emberjs.com/api/ember/release/classes/@ember%2Fdebug/methods/warn?anchor=warn). The following example demonstrates its usage by registering a handler that does nothing overriding Ember's default warning behavior. ```javascript import { registerWarnHandler } from '@ember/debug'; // next is not called, so no warnings get the default behavior registerWarnHandler(() => {}); ``` The handler function takes the following arguments:
  • message - The message received from the warn call.
  • options - An object passed in with the warn call containing additional information including:
    • id - An id of the warning in the form of package-name.specific-warning.
  • next - A function that calls into the previously registered handler.
@public @static @method registerWarnHandler @for @ember/debug @param handler {Function} A function to handle warnings. @since 2.1.0 */ exports.registerHandler = registerHandler = function registerHandler(handler) { (0, _handlers.registerHandler)('warn', handler); }; registerHandler(function logWarning(message) { /* eslint-disable no-console */ console.warn(`WARNING: ${message}`); if (console.trace) { console.trace(); } /* eslint-enable no-console */ }); exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `warn` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include an `id` property.'; exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `warn` you must provide `id` in options.'; /** 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. ```javascript import { warn } from '@ember/debug'; import tomsterCount from './tomster-counter'; // a module in my project // Log a warning if we have more than 3 tomsters warn('Too many tomsters!', tomsterCount <= 3, { id: 'ember-debug.too-many-tomsters' }); ``` @method warn @for @ember/debug @static @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" @public @since 1.0.0 */ warn = function warn(message, test, options) { if (arguments.length === 2 && typeof test === 'object') { options = test; test = false; } (0, _index.assert)(missingOptionsDeprecation, !!options); (0, _index.assert)(missingOptionsIdDeprecation, !!(options && options.id)); (0, _handlers.invoke)('warn', message, test, options); }; } exports.default = warn; exports.registerHandler = registerHandler; exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation; exports.missingOptionsDeprecation = missingOptionsDeprecation; }); enifed('@ember/deprecated-features/index', ['exports'], function (exports) { 'use strict'; const SEND_ACTION = exports.SEND_ACTION = !!'3.4.0'; const EMBER_EXTEND_PROTOTYPES = exports.EMBER_EXTEND_PROTOTYPES = !!'3.2.0-beta.5'; const RUN_SYNC = exports.RUN_SYNC = !!'3.0.0-beta.4'; const LOGGER = exports.LOGGER = !!'3.2.0-beta.1'; const POSITIONAL_PARAM_CONFLICT = exports.POSITIONAL_PARAM_CONFLICT = !!'3.1.0-beta.1'; const PROPERTY_WILL_CHANGE = exports.PROPERTY_WILL_CHANGE = !!'3.1.0-beta.1'; const PROPERTY_DID_CHANGE = exports.PROPERTY_DID_CHANGE = !!'3.1.0-beta.1'; const ROUTER_ROUTER = exports.ROUTER_ROUTER = !!'3.2.0-beta.1'; const ARRAY_AT_EACH = exports.ARRAY_AT_EACH = !!'3.1.0-beta.1'; const TARGET_OBJECT = exports.TARGET_OBJECT = !!'2.18.0-beta.1'; const MAP = exports.MAP = !!'3.3.0-beta.1'; const ORDERED_SET = exports.ORDERED_SET = !!'3.3.0-beta.1'; const MERGE = exports.MERGE = !!'3.6.0-beta.1'; const HANDLER_INFOS = exports.HANDLER_INFOS = !!'3.9.0'; const ROUTER_EVENTS = exports.ROUTER_EVENTS = !!'3.9.0'; const TRANSITION_STATE = exports.TRANSITION_STATE = !!'3.9.0'; }); enifed('@ember/engine/index', ['exports', '@ember/engine/lib/engine-parent', '@ember/-internals/utils', '@ember/controller', '@ember/-internals/runtime', '@ember/-internals/container', 'dag-map', '@ember/debug', '@ember/-internals/metal', '@ember/application/globals-resolver', '@ember/engine/instance', '@ember/-internals/routing', '@ember/-internals/extension-support', '@ember/-internals/views', '@ember/-internals/glimmer'], function (exports, _engineParent, _utils, _controller, _runtime, _container, _dagMap, _debug, _metal, _globalsResolver, _instance, _routing, _extensionSupport, _views, _glimmer) { 'use strict'; exports.setEngineParent = exports.getEngineParent = undefined; Object.defineProperty(exports, 'getEngineParent', { enumerable: true, get: function () { return _engineParent.getEngineParent; } }); Object.defineProperty(exports, 'setEngineParent', { enumerable: true, get: function () { return _engineParent.setEngineParent; } }); function props(obj) { let properties = []; for (let 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 @extends Ember.Namespace @uses RegistryProxy @public */ const Engine = _runtime.Namespace.extend(_runtime.RegistryProxyMixin, { init() { this._super(...arguments); 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() { if (!this._initializersRan) { this.runInitializers(); this._initializersRan = true; } }, /** Create an EngineInstance for this engine. @public @method buildInstance @return {EngineInstance} the engine instance */ buildInstance(options = {}) { this.ensureInitializers(); options.base = this; return _instance.default.create(options); }, /** Build and configure the registry for the current engine. @private @method buildRegistry @return {Ember.Registry} the configured registry */ buildRegistry() { let registry = this.__registry__ = this.constructor.buildRegistry(this); return registry; }, /** @private @method initializer */ initializer(options) { this.constructor.initializer(options); }, /** @private @method instanceInitializer */ instanceInitializer(options) { this.constructor.instanceInitializer(options); }, /** @private @method runInitializers */ runInitializers() { this._runInitializer('initializers', (name, initializer) => { true && !!!initializer && (0, _debug.assert)(`No application initializer named '${name}'`, !!initializer); initializer.initialize(this); }); }, /** @private @since 1.12.0 @method runInstanceInitializers */ runInstanceInitializers(instance) { this._runInitializer('instanceInitializers', (name, initializer) => { true && !!!initializer && (0, _debug.assert)(`No instance initializer named '${name}'`, !!initializer); initializer.initialize(instance); }); }, _runInitializer(bucketName, cb) { let initializersByName = (0, _metal.get)(this.constructor, bucketName); let initializers = props(initializersByName); let graph = new _dagMap.default(); let initializer; for (let i = 0; i < initializers.length; i++) { initializer = initializersByName[initializers[i]]; graph.add(initializer.name, initializer, initializer.before, initializer.after); } graph.topsort(cb); } }); Engine.reopenClass({ initializers: Object.create(null), instanceInitializers: Object.create(null), /** 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. ```app/initializer/named-initializer.js import { debug } from '@ember/debug'; export function initialize() { debug('Running namedInitializer!'); } export default { name: 'named-initializer', initialize }; ``` * `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`: ```app/initializer/first.js import { debug } from '@ember/debug'; export function initialize() { debug('First initializer!'); } export default { name: 'first', initialize }; ``` ```bash // DEBUG: First initializer! ``` We add another initializer named `second`, specifying that it should run after the initializer named `first`: ```app/initializer/second.js import { debug } from '@ember/debug'; export function initialize() { debug('Second initializer!'); } export default { name: 'second', after: 'first', initialize }; ``` ``` // 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`: ```app/initializer/pre.js import { debug } from '@ember/debug'; export function initialize() { debug('Pre initializer!'); } export default { name: 'pre', before: 'first', initialize }; ``` ```bash // 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: ```app/initializer/post.js import { debug } from '@ember/debug'; export function initialize() { debug('Post initializer!'); } export default { name: 'post', after: ['first', 'second'], initialize }; ``` ```bash // 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: ```app/initializer/api-adapter.js import ApiAdapter from '../utils/api-adapter'; export function initialize(application) { application.register('api-adapter:main', ApiAdapter); } export default { name: 'post', after: ['first', 'second'], initialize }; ``` @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. ```app/initializer/named-instance-initializer.js import { debug } from '@ember/debug'; export function initialize() { debug('Running named-instance-initializer!'); } export default { name: 'named-instance-initializer', initialize }; ``` * `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 Application.initializer for discussion on the usage of before and after. Example instanceInitializer to preload data into the store. ```app/initializer/preload-data.js import $ from 'jquery'; export function initialize(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 = $('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); } export default { name: 'named-instance-initializer', initialize }; ``` @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 {Application} namespace the application for which to build the registry @return {Ember.Registry} the built registry @private */ buildRegistry(namespace) { let registry = new _container.Registry({ resolver: resolverFor(namespace) }); registry.set = _metal.set; registry.register('application:main', namespace, { instantiate: false }); commonSetupRegistry(registry); (0, _glimmer.setupEngineRegistry)(registry); return registry; }, /** Set this to provide an alternate class to `DefaultResolver` @deprecated Use 'Resolver' instead @property resolver @public */ resolver: null, /** Set this to provide an alternate class to `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) { let ResolverClass = (0, _metal.get)(namespace, 'Resolver') || _globalsResolver.default; let props = { namespace }; return ResolverClass.create(props); } 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]) { let attrs = {}; attrs[bucketName] = Object.create(this[bucketName]); this.reopenClass(attrs); } true && !!this[bucketName][initializer.name] && (0, _debug.assert)(`The ${humanName} '${initializer.name}' has already been registered`, !this[bucketName][initializer.name]); true && !(0, _utils.canInvoke)(initializer, 'initialize') && (0, _debug.assert)(`An ${humanName} cannot be registered without an initialize function`, (0, _utils.canInvoke)(initializer, 'initialize')); true && !(initializer.name !== undefined) && (0, _debug.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.register('controller:basic', _controller.default, { instantiate: false }); 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', _container.privatize`-bucket-cache:main`); registry.injection('route', '_bucketCache', _container.privatize`-bucket-cache:main`); registry.injection('route', '_router', 'router:main'); // Register the routing service... registry.register('service:-routing', _routing.RoutingService); // 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', _extensionSupport.ContainerDebugAdapter); registry.register('component-lookup:main', _views.ComponentLookup); } exports.default = Engine; }); enifed('@ember/engine/instance', ['exports', '@ember/-internals/utils', '@ember/-internals/runtime', '@ember/debug', '@ember/error', '@ember/-internals/container', '@ember/engine/lib/engine-parent'], function (exports, _utils, _runtime, _debug, _error, _container, _engineParent) { 'use strict'; /** The `EngineInstance` encapsulates all of the stateful aspects of a running `Engine`. @public @class EngineInstance @extends EmberObject @uses RegistryProxyMixin @uses ContainerProxyMixin */ /** @module @ember/engine */ const EngineInstance = _runtime.Object.extend(_runtime.RegistryProxyMixin, _runtime.ContainerProxyMixin, { /** The base `Engine` for which this is an instance. @property {Engine} engine @private */ base: null, init() { this._super(...arguments); (0, _utils.guidFor)(this); let 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. let registry = this.__registry__ = new _container.Registry({ fallback: base.__registry__ }); // Create a per-instance container from the instance's registry this.__container__ = registry.container({ owner: this }); this._booted = false; }, /** Initialize the `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. @public @method boot @param options {Object} @return {Promise} */ boot(options) { if (this._bootPromise) { return this._bootPromise; } this._bootPromise = new _runtime.RSVP.Promise(resolve => 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(options) { if (this._booted) { return this; } true && !(0, _engineParent.getEngineParent)(this) && (0, _debug.assert)("An engine instance's parent must be set via `setEngineParent(engine, parent)` prior to calling `engine.boot()`.", (0, _engineParent.getEngineParent)(this)); this.cloneParentDependencies(); this.setupRegistry(options); this.base.runInstanceInitializers(this); this._booted = true; return this; }, setupRegistry(options = this.__container__.lookup('-environment:main')) { 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(fullName) { this.__container__.reset(fullName); this._super(...arguments); }, /** Build a new `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 {EngineInstance,Error} */ buildChildEngineInstance(name, options = {}) { let Engine = this.lookup(`engine:${name}`); if (!Engine) { throw new _error.default(`You attempted to mount the engine '${name}', but it is not registered with its parent.`); } let engineInstance = Engine.buildInstance(options); (0, _engineParent.setEngineParent)(engineInstance, this); return engineInstance; }, /** Clone dependencies shared between an engine instance and its parent. @private @method cloneParentDependencies */ cloneParentDependencies() { let parent = (0, _engineParent.getEngineParent)(this); let registrations = ['route:basic', 'service:-routing', 'service:-glimmer-environment']; registrations.forEach(key => this.register(key, parent.resolveRegistration(key))); let env = parent.lookup('-environment:main'); this.register('-environment:main', env, { instantiate: false }); let singletons = ['router:main', _container.privatize`-bucket-cache:main`, '-view-registry:main', `renderer:-${env.isInteractive ? 'dom' : 'inert'}`, 'service:-document', _container.privatize`template-compiler:main`]; if (env.isInteractive) { singletons.push('event_dispatcher:main'); } singletons.forEach(key => this.register(key, parent.lookup(key), { instantiate: false })); this.inject('view', '_environment', '-environment:main'); this.inject('route', '_environment', '-environment:main'); } }); EngineInstance.reopenClass({ /** @private @method setupRegistry @param {Registry} registry @param {BootOptions} options */ setupRegistry(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'); } } }); exports.default = EngineInstance; }); enifed('@ember/engine/lib/engine-parent', ['exports', '@ember/-internals/utils'], function (exports, _utils) { 'use strict'; exports.getEngineParent = getEngineParent; exports.setEngineParent = setEngineParent; const ENGINE_PARENT = (0, _utils.symbol)('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/engine @static @private */ /** @module @ember/engine */ 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/error/index", ["exports"], function (exports) { "use strict"; exports.default = EmberError; /** A subclass of the JavaScript Error object for use in Ember. @class Error @namespace Ember @extends Error @constructor @public */ function EmberError(message) { if (!(this instanceof EmberError)) { return new EmberError(message); } let error = Error.call(this, message); this.stack = error.stack; this.description = error.description; this.fileName = error.fileName; this.lineNumber = error.lineNumber; this.message = error.message; this.name = error.name; this.number = error.number; this.code = error.code; } EmberError.prototype = Object.create(Error.prototype); EmberError.prototype.constructor = EmberError; }); enifed('@ember/instrumentation/index', ['exports', '@ember/-internals/environment'], function (exports, _environment) { 'use strict'; exports.flaggedInstrument = exports.subscribers = undefined; exports.instrument = instrument; exports._instrumentStart = _instrumentStart; exports.subscribe = subscribe; exports.unsubscribe = unsubscribe; exports.reset = reset; /** @module @ember/instrumentation @private */ /** The purpose of the Ember Instrumentation module is to provide efficient, general-purpose instrumentation for Ember. Subscribe to a listener by using `subscribe`: ```javascript import { subscribe } from '@ember/instrumentation'; 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 `instrument`: ```javascript import { instrument } from '@ember/instrumentation'; instrument("render.handlebars", payload, function() { // rendering logic }, binding); ``` Event names passed to `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 @static @private */ let subscribers = exports.subscribers = []; /* eslint no-console:off */ /* global console */ let cache = {}; function populateListeners(name) { let listeners = []; let subscriber; for (let i = 0; i < subscribers.length; i++) { subscriber = subscribers[i]; if (subscriber.regex.test(name)) { listeners.push(subscriber.object); } } cache[name] = listeners; return listeners; } const time = (() => { let perf = 'undefined' !== typeof window ? window.performance || {} : {}; let 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) : () => { return +new Date(); }; })(); function instrument(name, p1, p2, p3) { let payload; let callback; let binding; if (arguments.length <= 3 && typeof p1 === 'function') { payload = {}; callback = p1; binding = p2; } else { payload = p1 || {}; callback = p2; binding = p3; } if (subscribers.length === 0) { return callback.call(binding); } let finalizer = _instrumentStart(name, () => payload); if (finalizer) { return withFinalizer(callback, finalizer, payload, binding); } else { return callback.call(binding); } } let flaggedInstrument; if (false /* EMBER_IMPROVED_INSTRUMENTATION */) { exports.flaggedInstrument = flaggedInstrument = instrument; } else { exports.flaggedInstrument = flaggedInstrument = (_name, _payload, callback) => callback(); } exports.flaggedInstrument = flaggedInstrument; function withFinalizer(callback, finalizer, payload, binding) { let result; try { result = callback.call(binding); } catch (e) { payload.exception = e; result = payload; } finally { finalizer(); } return result; } function NOOP() {} function _instrumentStart(name, _payload, _payloadParam) { if (subscribers.length === 0) { return NOOP; } let listeners = cache[name]; if (!listeners) { listeners = populateListeners(name); } if (listeners.length === 0) { return NOOP; } let payload = _payload(_payloadParam); let STRUCTURED_PROFILE = _environment.ENV.STRUCTURED_PROFILE; let timeName; if (STRUCTURED_PROFILE) { timeName = `${name}: ${payload.object}`; console.time(timeName); } let beforeValues = new Array(listeners.length); let i; let listener; let timestamp = time(); for (i = 0; i < listeners.length; i++) { listener = listeners[i]; beforeValues[i] = listener.before(name, timestamp, payload); } return function _instrumentEnd() { let i; let listener; let 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 @for @ember/instrumentation @static @param {String} [pattern] Namespaced event name. @param {Object} [object] Before and After hooks. @return {Subscriber} @private */ function subscribe(pattern, object) { let paths = pattern.split('.'); let path; let regexes = []; for (let i = 0; i < paths.length; i++) { path = paths[i]; if (path === '*') { regexes.push('[^\\.]*'); } else { regexes.push(path); } } let regex = regexes.join('\\.'); regex = `${regex}(\\..*)?`; let subscriber = { pattern, regex: new RegExp(`^${regex}$`), object }; subscribers.push(subscriber); cache = {}; return subscriber; } /** Unsubscribes from a particular event or instrumented block of code. @method unsubscribe @for @ember/instrumentation @static @param {Object} [subscriber] @private */ function unsubscribe(subscriber) { let index = 0; for (let i = 0; i < subscribers.length; i++) { if (subscribers[i] === subscriber) { index = i; } } subscribers.splice(index, 1); cache = {}; } /** Resets `Instrumentation` by flushing list of subscribers. @method reset @for @ember/instrumentation @static @private */ function reset() { subscribers.length = 0; cache = {}; } }); enifed('@ember/map/index', ['exports', '@ember/debug', '@ember/-internals/utils', '@ember/map/lib/ordered-set', '@ember/map/lib/utils', '@ember/deprecated-features'], function (exports, _debug, _utils, _orderedSet, _utils2, _deprecatedFeatures) { 'use strict'; /** @module @ember/map @private */ let Map; if (_deprecatedFeatures.MAP) { /* 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 `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 `EmberMap.create()` for symmetry with other Ember classes. */ /** 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 `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 @private @constructor @deprecated use native `Map` instead. */ Map = class Map { constructor() { true && !false && (0, _debug.deprecate)('Use of @ember/Map is deprecated. Please use native `Map` instead', false, { id: 'ember-map-deprecation', until: '3.5.0' }); this._keys = new _orderedSet.default(); this._values = Object.create(null); this.size = 0; } /** @method create @static @private */ static create() { let Constructor = this; return new Constructor(); } /** Retrieve the value associated with a given key. @method get @param {*} key @return {*} the value associated with the key, or `undefined` @private */ get(key) { if (this.size === 0) { return; } let values = this._values; let guid = (0, _utils.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 {Map} @private */ set(key, value) { let keys = this._keys; let values = this._values; let guid = (0, _utils.guidFor)(key); // ensure we don't store -0 let k = key === -0 ? 0 : key; // eslint-disable-line no-compare-neg-zero 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(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; let keys = this._keys; let values = this._values; let guid = (0, _utils.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(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(callback /*, ...thisArg*/) { true && !(typeof callback === 'function') && (0, _debug.assert)(`${Object.prototype.toString.call(callback)} is not a function`, typeof callback === 'function'); if (this.size === 0) { return; } let map = this; let cb, thisArg; if (arguments.length === 2) { thisArg = arguments[1]; cb = key => callback.call(thisArg, map.get(key), key, map); } else { cb = key => callback(map.get(key), key, map); } this._keys.forEach(cb); } /** @method clear @private */ clear() { this._keys.clear(); this._values = Object.create(null); this.size = 0; } /** @method copy @return {Map} @private */ copy() { return (0, _utils2.copyMap)(this, new Map()); } }; } exports.default = Map; }); enifed('@ember/map/lib/ordered-set', ['exports', '@ember/debug', '@ember/-internals/utils', '@ember/map/lib/utils', '@ember/deprecated-features'], function (exports, _debug, _utils, _utils2, _deprecatedFeatures) { 'use strict'; exports.__OrderedSet__ = undefined; /** 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 @deprecated */ let __OrderedSet__, OrderedSet; /** * This is exported so it can be used by the OrderedSet library. * This is private do not use it. @private */ if (_deprecatedFeatures.ORDERED_SET) { exports.__OrderedSet__ = __OrderedSet__ = class __OrderedSet__ { constructor() { this.clear(); } /** @method create @static @return {Ember.OrderedSet} @private */ static create() { let Constructor = this; return new Constructor(); } /** @method clear @private */ clear() { this.presenceSet = Object.create(null); this.list = []; this.size = 0; } /** @method add @param obj @param guid (optional, and for internal use) @return {Ember.OrderedSet} @private */ add(obj, _guid) { let guid = _guid || (0, _utils.guidFor)(obj); let presenceSet = this.presenceSet; let 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(obj, _guid) { let guid = _guid || (0, _utils.guidFor)(obj); let presenceSet = this.presenceSet; let list = this.list; if (presenceSet[guid] === true) { delete presenceSet[guid]; let 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() { return this.size === 0; } /** @method has @param obj @return {Boolean} @private */ has(obj) { if (this.size === 0) { return false; } let guid = (0, _utils.guidFor)(obj); let presenceSet = this.presenceSet; return presenceSet[guid] === true; } /** @method forEach @param {Function} fn @param self @private */ forEach(fn /*, ...thisArg*/) { true && !(typeof fn === 'function') && (0, _debug.assert)(`${Object.prototype.toString.call(fn)} is not a function`, typeof fn === 'function'); if (this.size === 0) { return; } let list = this.list; if (arguments.length === 2) { for (let i = 0; i < list.length; i++) { fn.call(arguments[1], list[i]); } } else { for (let i = 0; i < list.length; i++) { fn(list[i]); } } } /** @method toArray @return {Array} @private */ toArray() { return this.list.slice(); } /** @method copy @return {Ember.OrderedSet} @private */ copy() { let Constructor = this.constructor; let set = new Constructor(); set.presenceSet = (0, _utils2.copyNull)(this.presenceSet); set.list = this.toArray(); set.size = this.size; return set; } }; OrderedSet = class OrderedSet extends __OrderedSet__ { constructor() { super(); true && !false && (0, _debug.deprecate)('Use of @ember/OrderedSet is deprecated. Please use native `Map` instead', false, { id: 'ember-map-deprecation', until: '3.5.0' }); } }; } exports.__OrderedSet__ = __OrderedSet__; exports.default = OrderedSet; }); enifed('@ember/map/lib/utils', ['exports', '@ember/deprecated-features'], function (exports, _deprecatedFeatures) { 'use strict'; exports.copyNull = exports.copyMap = undefined; let copyNull, copyMap; if (_deprecatedFeatures.MAP || _deprecatedFeatures.ORDERED_SET) { exports.copyNull = copyNull = function copyNull(obj) { let output = Object.create(null); for (let prop in obj) { // hasOwnPropery is not needed because obj is Object.create(null); output[prop] = obj[prop]; } return output; }; exports.copyMap = copyMap = function copyMap(original, newObject) { let keys = original._keys.copy(); let values = copyNull(original._values); newObject._keys = keys; newObject._values = values; newObject.size = original.size; return newObject; }; } exports.copyMap = copyMap; exports.copyNull = copyNull; }); enifed('@ember/map/with-default', ['exports', '@ember/debug', '@ember/map/index', '@ember/map/lib/utils', '@ember/deprecated-features'], function (exports, _debug, _index, _utils, _deprecatedFeatures) { 'use strict'; let MapWithDefault; if (_deprecatedFeatures.MAP) { /** @class MapWithDefault @extends Map @private @constructor @param [options] @param {*} [options.defaultValue] */ MapWithDefault = class MapWithDefault extends _index.default { constructor(options) { true && !false && (0, _debug.deprecate)('Use of @ember/MapWithDefault is deprecated. Please use native `Map` instead', false, { id: 'ember-map-deprecation', until: '3.5.0' }); super(); this.defaultValue = options.defaultValue; } /** @method create @static @param [options] @param {*} [options.defaultValue] @return {MapWithDefault|Map} If options are passed, returns `MapWithDefault` otherwise returns `EmberMap` @private @deprecated use native `Map` instead */ static create(options) { if (options) { return new MapWithDefault(options); } else { return new _index.default(); } } /** Retrieve the value associated with a given key. @method get @param {*} key @return {*} the value associated with the key, or the default value @private */ get(key) { let hasValue = this.has(key); if (hasValue) { return super.get(key); } else { let defaultValue = this.defaultValue(key); this.set(key, defaultValue); return defaultValue; } } /** @method copy @return {MapWithDefault} @private */ copy() { let Constructor = this.constructor; return (0, _utils.copyMap)(this, new Constructor({ defaultValue: this.defaultValue })); } }; } exports.default = MapWithDefault; }); enifed('@ember/object/computed', ['exports', '@ember/object/lib/computed/computed_macros', '@ember/object/lib/computed/reduce_computed_macros'], function (exports, _computed_macros, _reduce_computed_macros) { 'use strict'; Object.defineProperty(exports, 'empty', { enumerable: true, get: function () { return _computed_macros.empty; } }); Object.defineProperty(exports, 'notEmpty', { enumerable: true, get: function () { return _computed_macros.notEmpty; } }); Object.defineProperty(exports, 'none', { enumerable: true, get: function () { return _computed_macros.none; } }); Object.defineProperty(exports, 'not', { enumerable: true, get: function () { return _computed_macros.not; } }); Object.defineProperty(exports, 'bool', { enumerable: true, get: function () { return _computed_macros.bool; } }); Object.defineProperty(exports, 'match', { enumerable: true, get: function () { return _computed_macros.match; } }); Object.defineProperty(exports, 'equal', { enumerable: true, get: function () { return _computed_macros.equal; } }); Object.defineProperty(exports, 'gt', { enumerable: true, get: function () { return _computed_macros.gt; } }); Object.defineProperty(exports, 'gte', { enumerable: true, get: function () { return _computed_macros.gte; } }); Object.defineProperty(exports, 'lt', { enumerable: true, get: function () { return _computed_macros.lt; } }); Object.defineProperty(exports, 'lte', { enumerable: true, get: function () { return _computed_macros.lte; } }); Object.defineProperty(exports, 'oneWay', { enumerable: true, get: function () { return _computed_macros.oneWay; } }); Object.defineProperty(exports, 'readOnly', { enumerable: true, get: function () { return _computed_macros.readOnly; } }); Object.defineProperty(exports, 'deprecatingAlias', { enumerable: true, get: function () { return _computed_macros.deprecatingAlias; } }); Object.defineProperty(exports, 'and', { enumerable: true, get: function () { return _computed_macros.and; } }); Object.defineProperty(exports, 'or', { enumerable: true, get: function () { return _computed_macros.or; } }); Object.defineProperty(exports, 'sum', { enumerable: true, get: function () { return _reduce_computed_macros.sum; } }); Object.defineProperty(exports, 'min', { enumerable: true, get: function () { return _reduce_computed_macros.min; } }); Object.defineProperty(exports, 'max', { enumerable: true, get: function () { return _reduce_computed_macros.max; } }); Object.defineProperty(exports, 'map', { enumerable: true, get: function () { return _reduce_computed_macros.map; } }); Object.defineProperty(exports, 'sort', { enumerable: true, get: function () { return _reduce_computed_macros.sort; } }); Object.defineProperty(exports, 'setDiff', { enumerable: true, get: function () { return _reduce_computed_macros.setDiff; } }); Object.defineProperty(exports, 'mapBy', { enumerable: true, get: function () { return _reduce_computed_macros.mapBy; } }); Object.defineProperty(exports, 'filter', { enumerable: true, get: function () { return _reduce_computed_macros.filter; } }); Object.defineProperty(exports, 'filterBy', { enumerable: true, get: function () { return _reduce_computed_macros.filterBy; } }); Object.defineProperty(exports, 'uniq', { enumerable: true, get: function () { return _reduce_computed_macros.uniq; } }); Object.defineProperty(exports, 'uniqBy', { enumerable: true, get: function () { return _reduce_computed_macros.uniqBy; } }); Object.defineProperty(exports, 'union', { enumerable: true, get: function () { return _reduce_computed_macros.union; } }); Object.defineProperty(exports, 'intersect', { enumerable: true, get: function () { return _reduce_computed_macros.intersect; } }); Object.defineProperty(exports, 'collect', { enumerable: true, get: function () { return _reduce_computed_macros.collect; } }); }); enifed('@ember/object/lib/computed/computed_macros', ['exports', '@ember/-internals/metal', '@ember/debug'], function (exports, _metal, _debug) { 'use strict'; exports.or = exports.and = undefined; 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/object */ function expandPropertiesToArray(predicateName, properties) { let expandedProperties = []; function extractProperty(entry) { expandedProperties.push(entry); } for (let i = 0; i < properties.length; i++) { let property = properties[i]; true && !(property.indexOf(' ') < 0) && (0, _debug.assert)(`Dependent keys passed to computed.${predicateName}() can\'t have spaces.`, property.indexOf(' ') < 0); (0, _metal.expandProperties)(property, extractProperty); } return expandedProperties; } function generateComputedWithPredicate(name, predicate) { return (...properties) => { let dependentKeys = expandPropertiesToArray(name, properties); let computedFunc = new _metal.ComputedProperty(function () { let lastIdx = dependentKeys.length - 1; for (let i = 0; i < lastIdx; i++) { let value = (0, _metal.get)(this, dependentKeys[i]); if (!predicate(value)) { return value; } } return (0, _metal.get)(this, dependentKeys[lastIdx]); }, { dependentKeys }); return computedFunc; }; } /** 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 import { empty } from '@ember/object/computed'; import EmberObject from '@ember/object'; let ToDoList = EmberObject.extend({ isDone: 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 @static @for @ember/object/computed @param {String} dependentKey @return {ComputedProperty} computed property which returns true if the value of the dependent property is null, an empty string, empty array, or empty function and false if the underlying value is not empty. @public */ function empty(dependentKey) { return (0, _metal.computed)(`${dependentKey}.length`, function () { return (0, _metal.isEmpty)((0, _metal.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 import { notEmpty } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ hasStuff: 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 @static @for @ember/object/computed @param {String} dependentKey @return {ComputedProperty} computed property which returns true if original value for property is not empty. @public */ function notEmpty(dependentKey) { return (0, _metal.computed)(`${dependentKey}.length`, function () { return !(0, _metal.isEmpty)((0, _metal.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 import { none } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ isHungry: 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 @static @for @ember/object/computed @param {String} dependentKey @return {ComputedProperty} computed property which returns true if original value for property is null or undefined. @public */ function none(dependentKey) { return (0, _metal.computed)(dependentKey, function () { return (0, _metal.isNone)((0, _metal.get)(this, dependentKey)); }); } /** A computed property that returns the inverse boolean value of the original value for the dependent property. Example ```javascript import { not } from '@ember/object/computed'; import EmberObject from '@ember/object'; let User = EmberObject.extend({ isAnonymous: not('loggedIn') }); let user = User.create({loggedIn: false}); user.get('isAnonymous'); // true user.set('loggedIn', true); user.get('isAnonymous'); // false ``` @method not @static @for @ember/object/computed @param {String} dependentKey @return {ComputedProperty} computed property which returns inverse of the original value for property @public */ function not(dependentKey) { return (0, _metal.computed)(dependentKey, function () { return !(0, _metal.get)(this, dependentKey); }); } /** A computed property that converts the provided dependent property into a boolean value. ```javascript import { bool } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ hasBananas: 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 @static @for @ember/object/computed @param {String} dependentKey @return {ComputedProperty} computed property which converts to boolean the original value for property @public */ function bool(dependentKey) { return (0, _metal.computed)(dependentKey, function () { return !!(0, _metal.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 import { match } from '@ember/object/computed'; import EmberObject from '@ember/object'; let User = EmberObject.extend({ hasValidEmail: 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 @static @for @ember/object/computed @param {String} dependentKey @param {RegExp} regexp @return {ComputedProperty} computed property which match the original value for property against a given RegExp @public */ function match(dependentKey, regexp) { return (0, _metal.computed)(dependentKey, function () { let value = (0, _metal.get)(this, dependentKey); return regexp.test(value); }); } /** A computed property that returns true if the provided dependent property is equal to the given value. Example ```javascript import { equal } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ satisfied: equal('percentCarrotsEaten', 100) }); let hamster = Hamster.create(); hamster.get('satisfied'); // false hamster.set('percentCarrotsEaten', 100); hamster.get('satisfied'); // true hamster.set('percentCarrotsEaten', 50); hamster.get('satisfied'); // false ``` @method equal @static @for @ember/object/computed @param {String} dependentKey @param {String|Number|Object} value @return {ComputedProperty} computed property which returns true if the original value for property is equal to the given value. @public */ function equal(dependentKey, value) { return (0, _metal.computed)(dependentKey, function () { return (0, _metal.get)(this, dependentKey) === value; }); } /** A computed property that returns true if the provided dependent property is greater than the provided value. Example ```javascript import { gt } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ hasTooManyBananas: 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 @static @for @ember/object/computed @param {String} dependentKey @param {Number} value @return {ComputedProperty} computed property which returns true if the original value for property is greater than given value. @public */ function gt(dependentKey, value) { return (0, _metal.computed)(dependentKey, function () { return (0, _metal.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 import { gte } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ hasTooManyBananas: 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 @static @for @ember/object/computed @param {String} dependentKey @param {Number} value @return {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 (0, _metal.computed)(dependentKey, function () { return (0, _metal.get)(this, dependentKey) >= value; }); } /** A computed property that returns true if the provided dependent property is less than the provided value. Example ```javascript import { lt } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ needsMoreBananas: 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 @static @for @ember/object/computed @param {String} dependentKey @param {Number} value @return {ComputedProperty} computed property which returns true if the original value for property is less then given value. @public */ function lt(dependentKey, value) { return (0, _metal.computed)(dependentKey, function () { return (0, _metal.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 import { lte } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ needsMoreBananas: 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 @static @for @ember/object/computed @param {String} dependentKey @param {Number} value @return {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 (0, _metal.computed)(dependentKey, function () { return (0, _metal.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 import { and } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ readyForCamp: and('hasTent', 'hasBackpack'), readyForHike: 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 @static @for @ember/object/computed @param {String} dependentKey* @return {ComputedProperty} computed property which performs a logical `and` on the values of all the original values for properties. @public */ const and = exports.and = generateComputedWithPredicate('and', value => value); /** 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 import { or } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ readyForRain: or('hasJacket', 'hasUmbrella'), readyForBeach: 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 @static @for @ember/object/computed @param {String} dependentKey* @return {ComputedProperty} computed property which performs a logical `or` on the values of all the original values for properties. @public */ const or = exports.or = generateComputedWithPredicate('or', value => !value); /** 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 import { alias } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Person = EmberObject.extend({ name: 'Alex Matchneer', nomen: 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 @static @for @ember/object/computed @param {String} dependentKey @return {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 import { oneWay } from '@ember/object/computed'; import EmberObject from '@ember/object'; let User = EmberObject.extend({ firstName: null, lastName: null, nickName: 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 @static @for @ember/object/computed @param {String} dependentKey @return {ComputedProperty} computed property which creates a one way computed property to the original value for property. @public */ function oneWay(dependentKey) { return (0, _metal.alias)(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 @static @for @ember/object/computed @param {String} dependentKey @return {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 import { readOnly } from '@ember/object/computed'; import EmberObject from '@ember/object'; let User = EmberObject.extend({ firstName: null, lastName: null, nickName: readOnly('firstName') }); let teddy = User.create({ firstName: 'Teddy', lastName: 'Zeenny' }); teddy.get('nickName'); // 'Teddy' teddy.set('nickName', 'TeddyBear'); // throws Exception // throw new EmberError('Cannot Set: nickName on: ' );` teddy.get('firstName'); // 'Teddy' ``` @method readOnly @static @for @ember/object/computed @param {String} dependentKey @return {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 (0, _metal.alias)(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 import { deprecatingAlias } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ bananaCount: 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 @static @for @ember/object/computed @param {String} dependentKey @param {Object} options Options for `deprecate`. @return {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 (0, _metal.computed)(dependentKey, { get(key) { true && !false && (0, _debug.deprecate)(`Usage of \`${key}\` is deprecated, use \`${dependentKey}\` instead.`, false, options); return (0, _metal.get)(this, dependentKey); }, set(key, value) { true && !false && (0, _debug.deprecate)(`Usage of \`${key}\` is deprecated, use \`${dependentKey}\` instead.`, false, options); (0, _metal.set)(this, dependentKey, value); return value; } }); } }); enifed('@ember/object/lib/computed/reduce_computed_macros', ['exports', '@ember/debug', '@ember/-internals/metal', '@ember/-internals/runtime'], function (exports, _debug, _metal, _runtime) { 'use strict'; exports.union = undefined; 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, name) { true && !!/[\[\]\{\}]/g.test(dependentKey) && (0, _debug.assert)(`Dependent key passed to \`computed.${name}\` shouldn't contain brace expanding pattern.`, !/[\[\]\{\}]/g.test(dependentKey)); let cp = new _metal.ComputedProperty(function () { let arr = (0, _metal.get)(this, dependentKey); if (arr === null || typeof arr !== 'object') { return initialValue; } return arr.reduce(callback, initialValue, this); }, { dependentKeys: [`${dependentKey}.[]`], readOnly: true }); return cp; } /** @module @ember/object */ function arrayMacro(dependentKey, callback) { // This is a bit ugly let propertyName; if (/@each/.test(dependentKey)) { propertyName = dependentKey.replace(/\.@each.*$/, ''); } else { propertyName = dependentKey; dependentKey += '.[]'; } let cp = new _metal.ComputedProperty(function () { let value = (0, _metal.get)(this, propertyName); if ((0, _runtime.isArray)(value)) { return (0, _runtime.A)(callback.call(this, value)); } else { return (0, _runtime.A)(); } }, { readOnly: true }); cp.property(dependentKey); // this forces to expand properties GH #15855 return cp; } function multiArrayMacro(_dependentKeys, callback, name) { true && !_dependentKeys.every(dependentKey => !/[\[\]\{\}]/g.test(dependentKey)) && (0, _debug.assert)(`Dependent keys passed to \`computed.${name}\` shouldn't contain brace expanding pattern.`, _dependentKeys.every(dependentKey => !/[\[\]\{\}]/g.test(dependentKey))); let dependentKeys = _dependentKeys.map(key => `${key}.[]`); let cp = new _metal.ComputedProperty(function () { return (0, _runtime.A)(callback.call(this, _dependentKeys)); }, { dependentKeys, readOnly: true }); return cp; } /** A computed property that returns the sum of the values in the dependent array. @method sum @for @ember/object/computed @static @param {String} dependentKey @return {ComputedProperty} computes the sum of all values in the dependentKey's array @since 1.4.0 @public */ function sum(dependentKey) { return reduceMacro(dependentKey, (sum, item) => sum + item, 0, 'sum'); } /** A computed property that calculates the maximum value in the dependent array. This will return `-Infinity` when the dependent array is empty. ```javascript import { mapBy, max } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Person = EmberObject.extend({ childAges: mapBy('children', 'age'), maxChildAge: 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/object/computed @static @param {String} dependentKey @return {ComputedProperty} computes the largest value in the dependentKey's array @public */ function max(dependentKey) { return reduceMacro(dependentKey, (max, item) => Math.max(max, item), -Infinity, 'max'); } /** A computed property that calculates the minimum value in the dependent array. This will return `Infinity` when the dependent array is empty. ```javascript import { mapBy, min } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Person = EmberObject.extend({ childAges: mapBy('children', 'age'), minChildAge: 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/object/computed @static @param {String} dependentKey @return {ComputedProperty} computes the smallest value in the dependentKey's array @public */ function min(dependentKey) { return reduceMacro(dependentKey, (min, item) => Math.min(min, item), Infinity, 'min'); } /** 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 import { map } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ excitingChores: 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/object/computed @static @param {String} dependentKey @param {Function} callback @return {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 import { mapBy } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Person = EmberObject.extend({ childAges: 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/object/computed @static @param {String} dependentKey @param {String} propertyKey @return {ComputedProperty} an array mapped to the specified key @public */ function mapBy(dependentKey, propertyKey) { true && !(typeof propertyKey === 'string') && (0, _debug.assert)('`computed.mapBy` expects a property string for its second argument, ' + 'perhaps you meant to use "map"', typeof propertyKey === 'string'); true && !!/[\[\]\{\}]/g.test(dependentKey) && (0, _debug.assert)(`Dependent key passed to \`computed.mapBy\` shouldn't contain brace expanding pattern.`, !/[\[\]\{\}]/g.test(dependentKey)); return map(`${dependentKey}.@each.${propertyKey}`, item => (0, _metal.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 import { filter } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ remainingChores: 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}] ``` You can also use `@each.property` in your dependent key, the callback will still use the underlying array: ```javascript import { A } from '@ember/array'; import { filter } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ remainingChores: filter('chores.@each.done', function(chore, index, array) { return !chore.get('done'); }) }); let hamster = Hamster.create({ chores: A([ EmberObject.create({ name: 'cook', done: true }), EmberObject.create({ name: 'clean', done: true }), EmberObject.create({ name: 'write more unit tests', done: false }) ]) }); hamster.get('remainingChores'); // [{name: 'write more unit tests', done: false}] hamster.get('chores').objectAt(2).set('done', true); hamster.get('remainingChores'); // [] ``` @method filter @for @ember/object/computed @static @param {String} dependentKey @param {Function} callback @return {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 import { filterBy } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ remainingChores: 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/object/computed @static @param {String} dependentKey @param {String} propertyKey @param {*} value @return {ComputedProperty} the filtered array @public */ function filterBy(dependentKey, propertyKey, value) { true && !!/[\[\]\{\}]/g.test(dependentKey) && (0, _debug.assert)(`Dependent key passed to \`computed.filterBy\` shouldn't contain brace expanding pattern.`, !/[\[\]\{\}]/g.test(dependentKey)); let callback; if (arguments.length === 2) { callback = item => (0, _metal.get)(item, propertyKey); } else { callback = item => (0, _metal.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 import { uniq } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ uniqueFruits: uniq('fruits') }); let hamster = Hamster.create({ fruits: [ 'banana', 'grape', 'kale', 'banana' ] }); hamster.get('uniqueFruits'); // ['banana', 'grape', 'kale'] ``` @method uniq @for @ember/object/computed @static @param {String} propertyKey* @return {ComputedProperty} computes a new array with all the unique elements from the dependent array @public */ function uniq(...args) { return multiArrayMacro(args, function (dependentKeys) { let uniq = (0, _runtime.A)(); let seen = new Set(); dependentKeys.forEach(dependentKey => { let value = (0, _metal.get)(this, dependentKey); if ((0, _runtime.isArray)(value)) { value.forEach(item => { if (!seen.has(item)) { seen.add(item); uniq.push(item); } }); } }); return uniq; }, '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 import { uniqBy } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ uniqueFruits: 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/object/computed @static @param {String} dependentKey @param {String} propertyKey @return {ComputedProperty} computes a new array with all the unique elements from the dependent array @public */ function uniqBy(dependentKey, propertyKey) { true && !!/[\[\]\{\}]/g.test(dependentKey) && (0, _debug.assert)(`Dependent key passed to \`computed.uniqBy\` shouldn't contain brace expanding pattern.`, !/[\[\]\{\}]/g.test(dependentKey)); let cp = new _metal.ComputedProperty(function () { let list = (0, _metal.get)(this, dependentKey); return (0, _runtime.isArray)(list) ? (0, _runtime.uniqBy)(list, propertyKey) : (0, _runtime.A)(); }, { dependentKeys: [`${dependentKey}.[]`], readOnly: true }); return cp; } /** A computed property which returns a new array with all the unique elements from one or more dependent arrays. Example ```javascript import { union } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ uniqueFruits: union('fruits', 'vegetables') }); let hamster = Hamster.create({ fruits: [ 'banana', 'grape', 'kale', 'banana', 'tomato' ], vegetables: [ 'tomato', 'carrot', 'lettuce' ] }); hamster.get('uniqueFruits'); // ['banana', 'grape', 'kale', 'tomato', 'carrot', 'lettuce'] ``` @method union @for @ember/object/computed @static @param {String} propertyKey* @return {ComputedProperty} computes a new array with all the unique elements from the dependent array @public */ let union = exports.union = uniq; /** A computed property which returns a new array with all the elements two or more dependent arrays have in common. Example ```javascript import { intersect } from '@ember/object/computed'; import EmberObject from '@ember/object'; let obj = EmberObject.extend({ friendsInCommon: 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/object/computed @static @param {String} propertyKey* @return {ComputedProperty} computes a new array with all the duplicated elements from the dependent arrays @public */ function intersect(...args) { return multiArrayMacro(args, function (dependentKeys) { let arrays = dependentKeys.map(dependentKey => { let array = (0, _metal.get)(this, dependentKey); return (0, _runtime.isArray)(array) ? array : []; }); let results = arrays.pop().filter(candidate => { for (let i = 0; i < arrays.length; i++) { let found = false; let array = arrays[i]; for (let j = 0; j < array.length; j++) { if (array[j] === candidate) { found = true; break; } } if (found === false) { return false; } } return true; }, 'intersect'); return (0, _runtime.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 import { setDiff } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ likes: ['banana', 'grape', 'kale'], wants: setDiff('likes', 'fruits') }); let hamster = Hamster.create({ fruits: [ 'grape', 'kale', ] }); hamster.get('wants'); // ['banana'] ``` @method setDiff @for @ember/object/computed @static @param {String} setAProperty @param {String} setBProperty @return {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) { true && !(arguments.length === 2) && (0, _debug.assert)('`computed.setDiff` requires exactly two dependent arrays.', arguments.length === 2); true && !(!/[\[\]\{\}]/g.test(setAProperty) && !/[\[\]\{\}]/g.test(setBProperty)) && (0, _debug.assert)(`Dependent keys passed to \`computed.setDiff\` shouldn't contain brace expanding pattern.`, !/[\[\]\{\}]/g.test(setAProperty) && !/[\[\]\{\}]/g.test(setBProperty)); let cp = new _metal.ComputedProperty(function () { let setA = this.get(setAProperty); let setB = this.get(setBProperty); if (!(0, _runtime.isArray)(setA)) { return (0, _runtime.A)(); } if (!(0, _runtime.isArray)(setB)) { return (0, _runtime.A)(setA); } return setA.filter(x => setB.indexOf(x) === -1); }, { dependentKeys: [`${setAProperty}.[]`, `${setBProperty}.[]`], readOnly: true }); return cp; } /** A computed property that returns the array of values for the provided dependent properties. Example ```javascript import { collect } from '@ember/object/computed'; import EmberObject from '@ember/object'; let Hamster = EmberObject.extend({ clothes: 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/object/computed @static @param {String} dependentKey* @return {ComputedProperty} computed property which maps values of all passed in properties to an array. @public */ function collect(...dependentKeys) { return multiArrayMacro(dependentKeys, function () { let properties = (0, _metal.getProperties)(this, dependentKeys); let res = (0, _runtime.A)(); for (let key in properties) { if (properties.hasOwnProperty(key)) { if (properties[key] === undefined) { res.push(null); } else { res.push(properties[key]); } } } return res; }, 'collect'); } /** 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 import { sort } from '@ember/object/computed'; import EmberObject from '@ember/object'; let ToDoList = EmberObject.extend({ // using standard ascending sort todosSorting: Object.freeze(['name']), sortedTodos: sort('todos', 'todosSorting'), // using descending sort todosSortingDesc: Object.freeze(['name:desc']), sortedTodosDesc: sort('todos', 'todosSortingDesc'), // using a custom sort function priorityTodos: 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/object/computed @static @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 {ComputedProperty} computes a new sorted array based on the sort property array or callback function @public */ function sort(itemsKey, sortDefinition) { true && !(arguments.length === 2) && (0, _debug.assert)('`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) { return value.slice().sort((x, y) => comparator.call(this, x, y)); }); } // This one needs to dynamically set up and tear down observers on the itemsKey // depending on the sortProperties function propertySort(itemsKey, sortPropertiesKey) { let cp = new _metal.ComputedProperty(function (key) { let sortProperties = (0, _metal.get)(this, sortPropertiesKey); true && !((0, _runtime.isArray)(sortProperties) && sortProperties.every(s => typeof s === 'string')) && (0, _debug.assert)(`The sort definition for '${key}' on ${this} must be a function or an array of strings`, (0, _runtime.isArray)(sortProperties) && sortProperties.every(s => typeof s === 'string')); // Add/remove property observers as required. let activeObserversMap = cp._activeObserverMap || (cp._activeObserverMap = new WeakMap()); let activeObservers = activeObserversMap.get(this); let sortPropertyDidChangeMap = cp._sortPropertyDidChangeMap || (cp._sortPropertyDidChangeMap = new WeakMap()); if (!sortPropertyDidChangeMap.has(this)) { sortPropertyDidChangeMap.set(this, function () { this.notifyPropertyChange(key); }); } let sortPropertyDidChange = sortPropertyDidChangeMap.get(this); if (activeObservers !== undefined) { activeObservers.forEach(path => (0, _metal.removeObserver)(this, path, sortPropertyDidChange)); } let itemsKeyIsAtThis = itemsKey === '@this'; let normalizedSortProperties = normalizeSortProperties(sortProperties); if (normalizedSortProperties.length === 0) { let path = itemsKeyIsAtThis ? `[]` : `${itemsKey}.[]`; (0, _metal.addObserver)(this, path, sortPropertyDidChange); activeObservers = [path]; } else { activeObservers = normalizedSortProperties.map(([prop]) => { let path = itemsKeyIsAtThis ? `@each.${prop}` : `${itemsKey}.@each.${prop}`; (0, _metal.addObserver)(this, path, sortPropertyDidChange); return path; }); } activeObserversMap.set(this, activeObservers); let items = itemsKeyIsAtThis ? this : (0, _metal.get)(this, itemsKey); if (!(0, _runtime.isArray)(items)) { return (0, _runtime.A)(); } if (normalizedSortProperties.length === 0) { return (0, _runtime.A)(items.slice()); } else { return sortByNormalizedSortProperties(items, normalizedSortProperties); } }, { dependentKeys: [`${sortPropertiesKey}.[]`], readOnly: true }); cp._activeObserverMap = undefined; cp._sortPropertyDidChangeMap = undefined; return cp; } function normalizeSortProperties(sortProperties) { return sortProperties.map(p => { let [prop, direction] = p.split(':'); direction = direction || 'asc'; return [prop, direction]; }); } function sortByNormalizedSortProperties(items, normalizedSortProperties) { return (0, _runtime.A)(items.slice().sort((itemA, itemB) => { for (let i = 0; i < normalizedSortProperties.length; i++) { let [prop, direction] = normalizedSortProperties[i]; let result = (0, _runtime.compare)((0, _metal.get)(itemA, prop), (0, _metal.get)(itemB, prop)); if (result !== 0) { return direction === 'desc' ? -1 * result : result; } } return 0; })); } }); enifed('@ember/polyfills/index', ['exports', '@ember/polyfills/lib/assign', '@ember/polyfills/lib/weak_set', '@ember/deprecated-features', '@ember/polyfills/lib/merge'], function (exports, _assign, _weak_set, _deprecatedFeatures, _merge) { 'use strict'; exports.merge = exports._WeakSet = exports.assignPolyfill = exports.assign = undefined; Object.defineProperty(exports, 'assign', { enumerable: true, get: function () { return _assign.default; } }); Object.defineProperty(exports, 'assignPolyfill', { enumerable: true, get: function () { return _assign.assign; } }); Object.defineProperty(exports, '_WeakSet', { enumerable: true, get: function () { return _weak_set.default; } }); let merge = _deprecatedFeatures.MERGE ? _merge.default : undefined; // Export `assignPolyfill` for testing exports.merge = merge; }); enifed("@ember/polyfills/lib/assign", ["exports"], function (exports) { "use strict"; exports.assign = assign; /** @module @ember/polyfills */ /** Copy properties from a source object to a target object. ```javascript import { assign } from '@ember/polyfills'; var a = { first: 'Yehuda' }; var b = { last: 'Katz' }; var c = { company: 'Tilde Inc.' }; assign(a, b, c); // a === { first: 'Yehuda', last: 'Katz', company: 'Tilde Inc.' }, b === { last: 'Katz' }, c === { company: 'Tilde Inc.' } ``` @method assign @for @ember/polyfills @param {Object} target The object to assign into @param {Object} ...args The objects to copy properties from @return {Object} @public @static */ function assign(target) { for (let i = 1; i < arguments.length; i++) { let arg = arguments[i]; if (!arg) { continue; } let updates = Object.keys(arg); for (let i = 0; i < updates.length; i++) { let prop = updates[i]; target[prop] = arg[prop]; } } return target; } // Note: We use the bracket notation so // that the babel plugin does not // transform it. // https://www.npmjs.com/package/babel-plugin-transform-object-assign const { assign: _assign } = Object; exports.default = _assign || assign; }); enifed('@ember/polyfills/lib/merge', ['exports', '@ember/debug'], function (exports, _debug) { 'use strict'; exports.default = merge; /** Merge the contents of two objects together into the first object. ```javascript import { merge } from '@ember/polyfills'; merge({ first: 'Tom' }, { last: 'Dale' }); // { first: 'Tom', last: 'Dale' } var a = { first: 'Yehuda' }; var b = { last: 'Katz' }; merge(a, b); // a == { first: 'Yehuda', last: 'Katz' }, b == { last: 'Katz' } ``` @method merge @static @for @ember/polyfills @param {Object} original The object to merge into @param {Object} updates The object to copy properties from @return {Object} @public */ function merge(original, updates) { true && !false && (0, _debug.deprecate)('Use of `merge` has been deprecated. Please use `assign` instead.', false, { id: 'ember-polyfills.deprecate-merge', until: '4.0.0', url: 'https://emberjs.com/deprecations/v3.x/#toc_ember-polyfills-deprecate-merge' }); if (updates === null || typeof updates !== 'object') { return original; } let props = Object.keys(updates); let prop; for (let i = 0; i < props.length; i++) { prop = props[i]; original[prop] = updates[prop]; } return original; } }); enifed('@ember/polyfills/lib/weak_set', ['exports'], function (exports) { 'use strict'; exports.default = typeof WeakSet === 'function' ? WeakSet : class WeakSetPolyFill { constructor() { this._map = new WeakMap(); } add(val) { this._map.set(val, true); return this; } delete(val) { return this._map.delete(val); } has(val) { return this._map.has(val); } }; }); enifed('@ember/runloop/index', ['exports', '@ember/debug', '@ember/-internals/error-handling', '@ember/-internals/metal', 'backburner', '@ember/deprecated-features'], function (exports, _debug, _errorHandling, _metal, _backburner, _deprecatedFeatures) { 'use strict'; exports.bind = exports._globalsRun = exports.backburner = exports.queues = exports._rsvpErrorQueue = undefined; exports.getCurrentRunLoop = getCurrentRunLoop; exports.run = run; exports.join = join; exports.begin = begin; exports.end = end; exports.schedule = schedule; exports.hasScheduledTimers = hasScheduledTimers; exports.cancelTimers = cancelTimers; exports.later = later; exports.once = once; exports.scheduleOnce = scheduleOnce; exports.next = next; exports.cancel = cancel; exports.debounce = debounce; exports.throttle = throttle; let currentRunLoop = null; function getCurrentRunLoop() { return currentRunLoop; } function onBegin(current) { currentRunLoop = current; } function onEnd(current, next) { currentRunLoop = next; } const _rsvpErrorQueue = exports._rsvpErrorQueue = `${Math.random()}${Date.now()}`.replace('.', ''); /** 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 ['actions', 'destroy'] @private */ const queues = exports.queues = ['actions', // used in router transitions to prevent unnecessary loading state entry // if all context promises resolve on the 'actions' queue first 'routerTransitions', 'render', 'afterRender', 'destroy', // used to re-throw unhandled RSVP rejection errors specifically in this // position to avoid breaking anything rendered in the other sections _rsvpErrorQueue]; let backburnerOptions = { defaultQueue: 'actions', onBegin, onEnd, onErrorTarget: _errorHandling.onErrorTarget, onErrorMethod: 'onerror' }; if (_deprecatedFeatures.RUN_SYNC) { queues.unshift('sync'); backburnerOptions.sync = { before: _metal.beginPropertyChanges, after: _metal.endPropertyChanges }; } const backburner = exports.backburner = new _backburner.default(queues, backburnerOptions); /** @module @ember/runloop */ // .......................................................... // 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 import { run } from '@ember/runloop'; run(function() { // code to be executed within a RunLoop }); ``` @method run @for @ember/runloop @static @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(...arguments); } // used for the Ember.run global only const _globalsRun = exports._globalsRun = run.bind(null); /** 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 import { join } from '@ember/runloop'; join(function() { // creates a new run-loop }); ``` Alternatively, if called within an existing run loop: ```javascript import { run, join } from '@ember/runloop'; run(function() { // creates a new run-loop join(function() { // joins with the existing run-loop, and queues for invocation on // the existing run-loops action queue. }); }); ``` @method join @static @for @ember/runloop @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 */ function join() { return backburner.join(...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. `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: ```app/components/rich-text-editor.js import Component from '@ember/component'; import { on } from '@ember/object/evented'; import { bind } from '@ember/runloop'; export default Component.extend({ initializeTinyMCE: on('didInsertElement', function() { tinymce.init({ selector: '#' + this.$().prop('id'), setup: bind(this, this.setupEditor) }); }), didInsertElement() { tinymce.init({ selector: '#' + this.$().prop('id'), setup: bind(this, this.setupEditor) }); } setupEditor(editor) { this.set('editor', editor); editor.on('change', function() { console.log('content changed!'); }); } }); ``` In this example, we use `bind` to bind the setupEditor method to the context of the RichTextEditor component and to have the invocation of that method be safely handled and executed by the Ember run loop. @method bind @static @for @ember/runloop @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 */ const bind = exports.bind = (...curried) => { true && !function (methodOrTarget, methodOrArg) { // Applies the same logic as backburner parseArgs for detecting if a method // is actually being passed. let length = arguments.length; if (length === 0) { return false; } else if (length === 1) { return typeof methodOrTarget === 'function'; } else { let type = typeof methodOrArg; return type === 'function' || // second argument is a function methodOrTarget !== null && type === 'string' && methodOrArg in methodOrTarget || // second argument is the name of a method in first argument typeof methodOrTarget === 'function' //first argument is a function ; } }(...curried) && (0, _debug.assert)('could not find a suitable method to bind', function (methodOrTarget, methodOrArg) { let length = arguments.length;if (length === 0) { return false; } else if (length === 1) { return typeof methodOrTarget === 'function'; } else { let type = typeof methodOrArg;return type === 'function' || methodOrTarget !== null && type === 'string' && methodOrArg in methodOrTarget || typeof methodOrTarget === 'function'; } }(...curried)); return (...args) => join(...curried.concat(args)); }; /** Begins a new RunLoop. Any deferred actions invoked after the begin will be buffered until you invoke a matching call to `end()`. This is a lower-level way to use a RunLoop instead of using `run()`. ```javascript import { begin, end } from '@ember/runloop'; begin(); // code to be executed within a RunLoop end(); ``` @method begin @static @for @ember/runloop @return {void} @public */ function begin() { backburner.begin(); } /** Ends a RunLoop. This must be called sometime after you call `begin()` to flush any deferred actions. This is a lower-level way to use a RunLoop instead of using `run()`. ```javascript import { begin, end } from '@ember/runloop'; begin(); // code to be executed within a RunLoop end(); ``` @method end @static @for @ember/runloop @return {void} @public */ function end() { backburner.end(); } /** 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 `queues` property. ```javascript import { schedule } from '@ember/runloop'; 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 @static @for @ember/runloop @param {String} queue The name of the queue to schedule against. Default queues is '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 {*} Timer information for use in canceling, see `cancel`. @public */ function schedule(queue /*, target, method */) { true && !(queue !== 'sync') && (0, _debug.deprecate)(`Scheduling into the '${queue}' run loop queue is deprecated.`, queue !== 'sync', { id: 'ember-metal.run.sync', until: '3.5.0' }); return backburner.schedule(...arguments); } // Used by global test teardown function hasScheduledTimers() { return backburner.hasTimers(); } // Used by global test teardown function cancelTimers() { backburner.cancelTimers(); } /** 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 import { later } from '@ember/runloop'; later(myContext, function() { // code here will execute within a RunLoop in about 500ms with this == myContext }, 500); ``` @method later @static @for @ember/runloop @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 canceling, see `cancel`. @public */ function later() /*target, method*/{ return backburner.later(...arguments); } /** Schedule a function to run one time during the current RunLoop. This is equivalent to calling `scheduleOnce` with the "actions" queue. @method once @static @for @ember/runloop @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 canceling, see `cancel`. @public */ function once(...args) { args.unshift('actions'); return backburner.scheduleOnce(...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 import { run, scheduleOnce } from '@ember/runloop'; function sayHi() { console.log('hi'); } run(function() { scheduleOnce('afterRender', myContext, sayHi); scheduleOnce('afterRender', myContext, sayHi); // sayHi will only be executed once, in the afterRender queue of the RunLoop }); ``` Also note that for `scheduleOnce` to prevent additional calls, you need to pass the same function instance. The following case works as expected: ```javascript function log() { console.log('Logging only once'); } function scheduleIt() { scheduleOnce('actions', myContext, log); } scheduleIt(); scheduleIt(); ``` But this other case will schedule the function multiple times: ```javascript import { scheduleOnce } from '@ember/runloop'; function scheduleIt() { scheduleOnce('actions', myContext, function() { console.log('Closure'); }); } scheduleIt(); scheduleIt(); // "Closure" will print twice, even though we're using `scheduleOnce`, // because the function we pass to it won't match the // previously scheduled operation. ``` Available queues, and their order, can be found at `queues` @method scheduleOnce @static @for @ember/runloop @param {String} [queue] The name of the queue to schedule against. Default queues is '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 canceling, see `cancel`. @public */ function scheduleOnce(queue /*, target, method*/) { true && !(queue !== 'sync') && (0, _debug.deprecate)(`Scheduling into the '${queue}' run loop queue is deprecated.`, queue !== 'sync', { id: 'ember-metal.run.sync', until: '3.5.0' }); return backburner.scheduleOnce(...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 `later` with a wait time of 1ms. ```javascript import { next } from '@ember/runloop'; next(myContext, function() { // code to be executed in the next run loop, // which will be scheduled after the current one }); ``` Multiple operations scheduled with `next` will coalesce into the same later run loop, along with any other operations scheduled by `later` that expire right around the same time that `next` operations will fire. Note that there are often alternatives to using `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: ```app/components/my-component.js import Component from '@ember/component'; import { scheduleOnce } from '@ember/runloop'; export Component.extend({ didInsertElement() { this._super(...arguments); 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 `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 `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 `next`. @method next @static @for @ember/runloop @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 canceling, see `cancel`. @public */ function next(...args) { args.push(1); return backburner.later(...args); } /** Cancels a scheduled item. Must be a value returned by `later()`, `once()`, `scheduleOnce()`, `next()`, `debounce()`, or `throttle()`. ```javascript import { next, cancel, later, scheduleOnce, once, throttle, debounce } from '@ember/runloop'; let runNext = next(myContext, function() { // will not be executed }); cancel(runNext); let runLater = later(myContext, function() { // will not be executed }, 500); cancel(runLater); let runScheduleOnce = scheduleOnce('afterRender', myContext, function() { // will not be executed }); cancel(runScheduleOnce); let runOnce = once(myContext, function() { // will not be executed }); cancel(runOnce); let throttle = throttle(myContext, function() { // will not be executed }, 1, false); cancel(throttle); let debounce = debounce(myContext, function() { // will not be executed }, 1); cancel(debounce); let debounceImmediate = 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 canceled cancel(debounceImmediate); ``` @method cancel @static @for @ember/runloop @param {Object} timer Timer object to cancel @return {Boolean} true if canceled or false/undefined if it wasn't found @public */ function cancel(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 import { debounce } from '@ember/runloop'; function whoRan() { console.log(this.name + ' ran.'); } let myContext = { name: 'debounce' }; debounce(myContext, whoRan, 150); // less than 150ms passes 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 import { debounce } from '@ember/runloop'; function whoRan() { console.log(this.name + ' ran.'); } let myContext = { name: 'debounce' }; debounce(myContext, whoRan, 150, true); // console logs 'debounce ran.' one time immediately. // 100ms passes debounce(myContext, whoRan, 150, true); // 150ms passes and nothing else is logged to the console and // the debouncee is no longer being watched 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 @static @for @ember/runloop @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 canceling, see `cancel`. @public */ function debounce() { return backburner.debounce(...arguments); } /** Ensure that the target method is never called more frequently than the specified spacing period. The target method is called immediately. ```javascript import { throttle } from '@ember/runloop'; function whoRan() { console.log(this.name + ' ran.'); } let myContext = { name: 'throttle' }; throttle(myContext, whoRan, 150); // whoRan is invoked with context myContext // console logs 'throttle ran.' // 50ms passes throttle(myContext, whoRan, 150); // 50ms passes throttle(myContext, whoRan, 150); // 150ms passes throttle(myContext, whoRan, 150); // whoRan is invoked with context myContext // console logs 'throttle ran.' ``` @method throttle @static @for @ember/runloop @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 canceling, see `cancel`. @public */ function throttle() { return backburner.throttle(...arguments); } }); enifed('@ember/service/index', ['exports', '@ember/-internals/runtime', '@ember/-internals/metal'], function (exports, _runtime, _metal) { 'use strict'; exports.inject = inject; /** @module @ember/service @public */ /** 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: ```app/routes/application.js import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; export default Route.extend({ authManager: service('auth'), model() { 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 inject @static @since 1.10.0 @for @ember/service @param {String} name (optional) name of the service to inject, defaults to the property's name @return {Ember.InjectedProperty} injection descriptor instance @public */ function inject(name, options) { return new _metal.InjectedProperty('service', name, options); } /** @class Service @extends EmberObject @since 1.10.0 @public */ const Service = _runtime.Object.extend(); Service.reopenClass({ isServiceFactory: true }); exports.default = Service; }); enifed('@ember/string/index', ['exports', '@ember/string/lib/string_registry', '@ember/-internals/environment', '@ember/-internals/utils'], function (exports, _string_registry, _environment, _utils) { 'use strict'; exports._setStrings = exports._getStrings = undefined; Object.defineProperty(exports, '_getStrings', { enumerable: true, get: function () { return _string_registry.getStrings; } }); Object.defineProperty(exports, '_setStrings', { enumerable: true, get: function () { return _string_registry.setStrings; } }); exports.loc = loc; exports.w = w; exports.decamelize = decamelize; exports.dasherize = dasherize; exports.camelize = camelize; exports.classify = classify; exports.underscore = underscore; exports.capitalize = capitalize; const STRING_DASHERIZE_REGEXP = /[ _]/g; const STRING_DASHERIZE_CACHE = new _utils.Cache(1000, key => decamelize(key).replace(STRING_DASHERIZE_REGEXP, '-')); const STRING_CAMELIZE_REGEXP_1 = /(\-|\_|\.|\s)+(.)?/g; const STRING_CAMELIZE_REGEXP_2 = /(^|\/)([A-Z])/g; const CAMELIZE_CACHE = new _utils.Cache(1000, key => key.replace(STRING_CAMELIZE_REGEXP_1, (_match, _separator, chr) => chr ? chr.toUpperCase() : '').replace(STRING_CAMELIZE_REGEXP_2, (match /*, separator, chr */) => match.toLowerCase())); const STRING_CLASSIFY_REGEXP_1 = /^(\-|_)+(.)?/; const STRING_CLASSIFY_REGEXP_2 = /(.)(\-|\_|\.|\s)+(.)?/g; const STRING_CLASSIFY_REGEXP_3 = /(^|\/|\.)([a-z])/g; const CLASSIFY_CACHE = new _utils.Cache(1000, str => { let replace1 = (_match, _separator, chr) => chr ? `_${chr.toUpperCase()}` : ''; let replace2 = (_match, initialChar, _separator, chr) => initialChar + (chr ? chr.toUpperCase() : ''); let parts = str.split('/'); for (let 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, (match /*, separator, chr */) => match.toUpperCase()); }); const STRING_UNDERSCORE_REGEXP_1 = /([a-z\d])([A-Z]+)/g; const STRING_UNDERSCORE_REGEXP_2 = /\-|\s+/g; const UNDERSCORE_CACHE = new _utils.Cache(1000, str => str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2').replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase()); const STRING_CAPITALIZE_REGEXP = /(^|\/)([a-z\u00C0-\u024F])/g; const CAPITALIZE_CACHE = new _utils.Cache(1000, str => str.replace(STRING_CAPITALIZE_REGEXP, (match /*, separator, chr */) => match.toUpperCase())); const STRING_DECAMELIZE_REGEXP = /([a-z\d])([A-Z])/g; const DECAMELIZE_CACHE = new _utils.Cache(1000, str => str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase()); /** 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 @public */ function _fmt(str, formats) { // first, replace any ORDERED replacements. let idx = 0; // the current index for non-numerical replacements return str.replace(/%@([0-9]+)?/g, (_s, argIndex) => { let i = argIndex ? parseInt(argIndex, 10) - 1 : idx++; let r = i < formats.length ? formats[i] : undefined; return typeof r === 'string' ? r : r === null ? '(null)' : r === undefined ? '' : '' + r; }); } /** Formats the passed string, but first looks up the string in the localized strings hash. This is a convenient way to localize text. 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 import { loc } from '@ember/string'; Ember.STRINGS = { '_Hello World': 'Bonjour le monde', '_Hello %@ %@': 'Bonjour %@ %@' }; loc("_Hello World"); // 'Bonjour le monde'; 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 */ function loc(str, formats) { if (!Array.isArray(formats) || arguments.length > 2) { formats = Array.prototype.slice.call(arguments, 1); } str = (0, _string_registry.getString)(str) || str; return _fmt(str, formats); } /** 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 import { w } from '@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 */ function w(str) { return str.split(/\s+/); } /** 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 */ function decamelize(str) { return DECAMELIZE_CACHE.get(str); } /** 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 */ function dasherize(str) { return STRING_DASHERIZE_CACHE.get(str); } /** 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 */ function camelize(str) { return CAMELIZE_CACHE.get(str); } /** 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 */ function classify(str) { return CLASSIFY_CACHE.get(str); } /** 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 */ function underscore(str) { return UNDERSCORE_CACHE.get(str); } /** 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 */ function capitalize(str) { return CAPITALIZE_CACHE.get(str); } if (_environment.ENV.EXTEND_PROTOTYPES.String) { Object.defineProperties(String.prototype, { /** See [String.w](/api/ember/release/classes/String/methods/w?anchor=w). @method w @for @ember/string @static @private */ w: { configurable: true, enumerable: false, writeable: true, value: function () { return w(this); } }, /** See [String.loc](/api/ember/release/classes/String/methods/loc?anchor=loc). @method loc @for @ember/string @static @private */ loc: { configurable: true, enumerable: false, writeable: true, value: function (...args) { return loc(this, args); } }, /** See [String.camelize](/api/ember/release/classes/String/methods/camelize?anchor=camelize). @method camelize @for @ember/string @static @private */ camelize: { configurable: true, enumerable: false, writeable: true, value: function () { return camelize(this); } }, /** See [String.decamelize](/api/ember/release/classes/String/methods/decamelize?anchor=decamelize). @method decamelize @for @ember/string @static @private */ decamelize: { configurable: true, enumerable: false, writeable: true, value: function () { return decamelize(this); } }, /** See [String.dasherize](/api/ember/release/classes/String/methods/dasherize?anchor=dasherize). @method dasherize @for @ember/string @static @private */ dasherize: { configurable: true, enumerable: false, writeable: true, value: function () { return dasherize(this); } }, /** See [String.underscore](/api/ember/release/classes/String/methods/underscore?anchor=underscore). @method underscore @for @ember/string @static @private */ underscore: { configurable: true, enumerable: false, writeable: true, value: function () { return underscore(this); } }, /** See [String.classify](/api/ember/release/classes/String/methods/classify?anchor=classify). @method classify @for @ember/string @static @private */ classify: { configurable: true, enumerable: false, writeable: true, value: function () { return classify(this); } }, /** See [String.capitalize](/api/ember/release/classes/String/methods/capitalize?anchor=capitalize). @method capitalize @for @ember/string @static @private */ capitalize: { configurable: true, enumerable: false, writeable: true, value: function () { return capitalize(this); } } }); } }); enifed("@ember/string/lib/string_registry", ["exports"], function (exports) { "use strict"; exports.setStrings = setStrings; exports.getStrings = getStrings; exports.getString = getString; // STATE within a module is frowned upon, this exists // to support Ember.STRINGS but shield ember internals from this legacy global // API. let STRINGS = {}; function setStrings(strings) { STRINGS = strings; } function getStrings() { return STRINGS; } function getString(name) { return STRINGS[name]; } }); enifed('@glimmer/encoder', ['exports'], function (exports) { 'use strict'; class InstructionEncoder { constructor(buffer) { this.buffer = buffer; this.typePos = 0; this.size = 0; } encode(type, machine) { if (type > 255 /* TYPE_SIZE */) { throw new Error(`Opcode type over 8-bits. Got ${type}.`); } this.buffer.push(type | machine | arguments.length - 2 << 8 /* ARG_SHIFT */); this.typePos = this.buffer.length - 1; for (let i = 2; i < arguments.length; i++) { let op = arguments[i]; if (typeof op === 'number' && op > 65535 /* MAX_SIZE */) { throw new Error(`Operand over 16-bits. Got ${op}.`); } this.buffer.push(op); } this.size = this.buffer.length; } patch(position, target) { if (this.buffer[position + 1] === -1) { this.buffer[position + 1] = target; } else { throw new Error('Trying to patch operand in populated slot instead of a reserved slot.'); } } patchWith(position, target, operand) { if (this.buffer[position + 1] === -1) { this.buffer[position + 1] = target; this.buffer[position + 2] = operand; } else { throw new Error('Trying to patch operand in populated slot instead of a reserved slot.'); } } } exports.InstructionEncoder = InstructionEncoder; }); enifed('@glimmer/low-level', ['exports'], function (exports) { 'use strict'; class Storage { constructor() { this.array = []; this.next = 0; } add(element) { let { next: slot, array } = this; if (slot === array.length) { this.next++; } else { let prev = array[slot]; this.next = prev; } this.array[slot] = element; return slot; } deref(pointer) { return this.array[pointer]; } drop(pointer) { this.array[pointer] = this.next; this.next = pointer; } } class Stack { constructor(vec = []) { this.vec = vec; } clone() { return new Stack(this.vec.slice()); } sliceFrom(start) { return new Stack(this.vec.slice(start)); } slice(start, end) { return new Stack(this.vec.slice(start, end)); } copy(from, to) { this.vec[to] = this.vec[from]; } // TODO: how to model u64 argument? writeRaw(pos, value) { // TODO: Grow? this.vec[pos] = value; } writeSmi(pos, value) { this.vec[pos] = encodeSmi(value); } // TODO: partially decoded enum? getRaw(pos) { return this.vec[pos]; } getSmi(pos) { return decodeSmi(this.vec[pos]); } reset() { this.vec.length = 0; } len() { return this.vec.length; } } function decodeSmi(smi) { switch (smi & 0b111) { case 0 /* NUMBER */: return smi >> 3; case 4 /* NEGATIVE */: return -(smi >> 3); default: throw new Error('unreachable'); } } function encodeSmi(primitive) { if (primitive < 0) { return Math.abs(primitive) << 3 | 4 /* NEGATIVE */; } else { return primitive << 3 | 0 /* NUMBER */; } } exports.Storage = Storage; exports.Stack = Stack; }); enifed('@glimmer/node', ['exports', '@glimmer/runtime'], function (exports, _runtime) { 'use strict'; exports.serializeBuilder = exports.NodeDOMTreeConstruction = undefined; class NodeDOMTreeConstruction extends _runtime.DOMTreeConstruction { constructor(doc) { super(doc); } // override to prevent usage of `this.document` until after the constructor setupUselessElement() {} insertHTMLBefore(parent, reference, html) { let prev = reference ? reference.previousSibling : parent.lastChild; let raw = this.document.createRawHTMLSection(html); parent.insertBefore(raw, reference); let first = prev ? prev.nextSibling : parent.firstChild; let last = reference ? reference.previousSibling : parent.lastChild; return new _runtime.ConcreteBounds(parent, first, last); } // override to avoid SVG detection/work when in node (this is not needed in SSR) createElement(tag) { return this.document.createElement(tag); } // override to avoid namespace shenanigans when in node (this is not needed in SSR) setAttribute(element, name, value) { element.setAttribute(name, value); } } const TEXT_NODE = 3; function currentNode(cursor) { let { element, nextSibling } = cursor; if (nextSibling === null) { return element.lastChild; } else { return nextSibling.previousSibling; } } class SerializeBuilder extends _runtime.NewElementBuilder { constructor() { super(...arguments); this.serializeBlockDepth = 0; } __openBlock() { let depth = this.serializeBlockDepth++; this.__appendComment(`%+b:${depth}%`); super.__openBlock(); } __closeBlock() { super.__closeBlock(); this.__appendComment(`%-b:${--this.serializeBlockDepth}%`); } __appendHTML(html) { // Do we need to run the html tokenizer here? let first = this.__appendComment('%glmr%'); if (this.element.tagName === 'TABLE') { let openIndex = html.indexOf('<'); if (openIndex > -1) { let tr = html.slice(openIndex + 1, openIndex + 3); if (tr === 'tr') { html = `${html}`; } } } if (html === '') { this.__appendComment('% %'); } else { super.__appendHTML(html); } let last = this.__appendComment('%glmr%'); return new _runtime.ConcreteBounds(this.element, first, last); } __appendText(string) { let current = currentNode(this); if (string === '') { return this.__appendComment('% %'); } else if (current && current.nodeType === TEXT_NODE) { this.__appendComment('%|%'); } return super.__appendText(string); } closeElement() { if (this.element['needsExtraClose'] === true) { this.element['needsExtraClose'] = false; super.closeElement(); } super.closeElement(); } openElement(tag) { if (tag === 'tr') { if (this.element.tagName !== 'TBODY') { this.openElement('tbody'); // This prevents the closeBlock comment from being re-parented // under the auto inserted tbody. Rehydration builder needs to // account for the insertion since it is injected here and not // really in the template. this.constructing['needsExtraClose'] = true; this.flushElement(); } } return super.openElement(tag); } pushRemoteElement(element, cursorId, nextSibling = null) { let { dom } = this; let script = dom.createElement('script'); script.setAttribute('glmr', cursorId); dom.insertBefore(element, script, nextSibling); super.pushRemoteElement(element, cursorId, nextSibling); } } function serializeBuilder(env, cursor) { return SerializeBuilder.forInitialRender(env, cursor); } exports.NodeDOMTreeConstruction = NodeDOMTreeConstruction; exports.serializeBuilder = serializeBuilder; }); enifed('@glimmer/opcode-compiler', ['exports', '@glimmer/util', '@glimmer/vm', '@glimmer/wire-format', '@glimmer/encoder', '@glimmer/program'], function (exports, _util, _vm, _wireFormat, _encoder, _program) { 'use strict'; exports.PLACEHOLDER_HANDLE = exports.WrappedBuilder = exports.logOpcode = exports.debugSlice = exports.debug = exports.templateFactory = exports.PartialDefinition = exports.StdOpcodeBuilder = exports.OpcodeBuilder = exports.EagerOpcodeBuilder = exports.LazyOpcodeBuilder = exports.CompilableProgram = exports.CompilableBlock = exports.debugCompiler = exports.AbstractCompiler = exports.compile = exports.LazyCompiler = exports.Macros = exports.ATTRS_BLOCK = undefined; const PLACEHOLDER_HANDLE = -1; var Ops$1; (function (Ops$$1) { Ops$$1[Ops$$1["OpenComponentElement"] = 0] = "OpenComponentElement"; Ops$$1[Ops$$1["DidCreateElement"] = 1] = "DidCreateElement"; Ops$$1[Ops$$1["SetComponentAttrs"] = 2] = "SetComponentAttrs"; Ops$$1[Ops$$1["DidRenderLayout"] = 3] = "DidRenderLayout"; Ops$$1[Ops$$1["Debugger"] = 4] = "Debugger"; })(Ops$1 || (Ops$1 = {})); var Ops$2 = _wireFormat.Ops; const ATTRS_BLOCK = '&attrs'; class Compilers { constructor(offset = 0) { this.offset = offset; this.names = (0, _util.dict)(); this.funcs = []; } add(name, func) { this.funcs.push(func); this.names[name] = this.funcs.length - 1; } compile(sexp, builder) { let name = sexp[this.offset]; let index = this.names[name]; let func = this.funcs[index]; func(sexp, builder); } } let _statementCompiler; function statementCompiler() { if (_statementCompiler) { return _statementCompiler; } const STATEMENTS = _statementCompiler = new Compilers(); STATEMENTS.add(Ops$2.Text, (sexp, builder) => { builder.text(sexp[1]); }); STATEMENTS.add(Ops$2.Comment, (sexp, builder) => { builder.comment(sexp[1]); }); STATEMENTS.add(Ops$2.CloseElement, (_sexp, builder) => { builder.closeElement(); }); STATEMENTS.add(Ops$2.FlushElement, (_sexp, builder) => { builder.flushElement(); }); STATEMENTS.add(Ops$2.Modifier, (sexp, builder) => { let { referrer } = builder; let [, name, params, hash] = sexp; let handle = builder.compiler.resolveModifier(name, referrer); if (handle !== null) { builder.modifier(handle, params, hash); } else { throw new Error(`Compile Error ${name} is not a modifier: Helpers may not be used in the element form.`); } }); STATEMENTS.add(Ops$2.StaticAttr, (sexp, builder) => { let [, name, value, namespace] = sexp; builder.staticAttr(name, namespace, value); }); STATEMENTS.add(Ops$2.DynamicAttr, (sexp, builder) => { dynamicAttr(sexp, false, builder); }); STATEMENTS.add(Ops$2.TrustingAttr, (sexp, builder) => { dynamicAttr(sexp, true, builder); }); STATEMENTS.add(Ops$2.OpenElement, (sexp, builder) => { builder.openPrimitiveElement(sexp[1]); }); STATEMENTS.add(Ops$2.OpenSplattedElement, (sexp, builder) => { builder.setComponentAttrs(true); builder.putComponentOperations(); builder.openPrimitiveElement(sexp[1]); }); STATEMENTS.add(Ops$2.DynamicComponent, (sexp, builder) => { let [, definition, attrs, args, template] = sexp; let block = builder.template(template); let attrsBlock = null; if (attrs.length > 0) { let wrappedAttrs = [[Ops$2.ClientSideStatement, Ops$1.SetComponentAttrs, true], ...attrs, [Ops$2.ClientSideStatement, Ops$1.SetComponentAttrs, false]]; attrsBlock = builder.inlineBlock({ statements: wrappedAttrs, parameters: _util.EMPTY_ARRAY }); } builder.dynamicComponent(definition, attrsBlock, null, args, false, block, null); }); STATEMENTS.add(Ops$2.Component, (sexp, builder) => { let [, tag, _attrs, args, block] = sexp; let { referrer } = builder; let { handle, capabilities, compilable } = builder.compiler.resolveLayoutForTag(tag, referrer); if (handle !== null && capabilities !== null) { let attrs = [[Ops$2.ClientSideStatement, Ops$1.SetComponentAttrs, true], ..._attrs, [Ops$2.ClientSideStatement, Ops$1.SetComponentAttrs, false]]; let attrsBlock = builder.inlineBlock({ statements: attrs, parameters: _util.EMPTY_ARRAY }); let child = builder.template(block); if (compilable) { builder.pushComponentDefinition(handle); builder.invokeStaticComponent(capabilities, compilable, attrsBlock, null, args, false, child && child); } else { builder.pushComponentDefinition(handle); builder.invokeComponent(capabilities, attrsBlock, null, args, false, child && child); } } else { throw new Error(`Compile Error: Cannot find component ${tag}`); } }); STATEMENTS.add(Ops$2.Partial, (sexp, builder) => { let [, name, evalInfo] = sexp; let { referrer } = builder; builder.replayableIf({ args() { builder.expr(name); builder.dup(); return 2; }, ifTrue() { builder.invokePartial(referrer, builder.evalSymbols(), evalInfo); builder.popScope(); builder.popFrame(); // FIXME: WAT } }); }); STATEMENTS.add(Ops$2.Yield, (sexp, builder) => { let [, to, params] = sexp; builder.yield(to, params); }); STATEMENTS.add(Ops$2.AttrSplat, (sexp, builder) => { let [, to] = sexp; builder.yield(to, []); builder.setComponentAttrs(false); }); STATEMENTS.add(Ops$2.Debugger, (sexp, builder) => { let [, evalInfo] = sexp; builder.debugger(builder.evalSymbols(), evalInfo); }); STATEMENTS.add(Ops$2.ClientSideStatement, (sexp, builder) => { CLIENT_SIDE.compile(sexp, builder); }); STATEMENTS.add(Ops$2.Append, (sexp, builder) => { let [, value, trusting] = sexp; let returned = builder.compileInline(sexp) || value; if (returned === true) return; builder.guardedAppend(value, trusting); }); STATEMENTS.add(Ops$2.Block, (sexp, builder) => { let [, name, params, hash, _template, _inverse] = sexp; let template = builder.template(_template); let inverse = builder.template(_inverse); let templateBlock = template && template; let inverseBlock = inverse && inverse; builder.compileBlock(name, params, hash, templateBlock, inverseBlock); }); const CLIENT_SIDE = new Compilers(1); CLIENT_SIDE.add(Ops$1.OpenComponentElement, (sexp, builder) => { builder.putComponentOperations(); builder.openPrimitiveElement(sexp[2]); }); CLIENT_SIDE.add(Ops$1.DidCreateElement, (_sexp, builder) => { builder.didCreateElement(_vm.Register.s0); }); CLIENT_SIDE.add(Ops$1.SetComponentAttrs, (sexp, builder) => { builder.setComponentAttrs(sexp[2]); }); CLIENT_SIDE.add(Ops$1.Debugger, () => { // tslint:disable-next-line:no-debugger debugger; }); CLIENT_SIDE.add(Ops$1.DidRenderLayout, (_sexp, builder) => { builder.didRenderLayout(_vm.Register.s0); }); return STATEMENTS; } function dynamicAttr(sexp, trusting, builder) { let [, name, value, namespace] = sexp; builder.expr(value); if (namespace) { builder.dynamicAttr(name, namespace, trusting); } else { builder.dynamicAttr(name, null, trusting); } } let _expressionCompiler; function expressionCompiler() { if (_expressionCompiler) { return _expressionCompiler; } const EXPRESSIONS = _expressionCompiler = new Compilers(); EXPRESSIONS.add(Ops$2.Unknown, (sexp, builder) => { let { compiler, referrer, containingLayout: { asPartial } } = builder; let name = sexp[1]; let handle = compiler.resolveHelper(name, referrer); if (handle !== null) { builder.helper(handle, null, null); } else if (asPartial) { builder.resolveMaybeLocal(name); } else { builder.getVariable(0); builder.getProperty(name); } }); EXPRESSIONS.add(Ops$2.Concat, (sexp, builder) => { let parts = sexp[1]; for (let i = 0; i < parts.length; i++) { builder.expr(parts[i]); } builder.concat(parts.length); }); EXPRESSIONS.add(Ops$2.Helper, (sexp, builder) => { let { compiler, referrer } = builder; let [, name, params, hash] = sexp; // TODO: triage this in the WF compiler if (name === 'component') { let [definition, ...restArgs] = params; builder.curryComponent(definition, restArgs, hash, true); return; } let handle = compiler.resolveHelper(name, referrer); if (handle !== null) { builder.helper(handle, params, hash); } else { throw new Error(`Compile Error: ${name} is not a helper`); } }); EXPRESSIONS.add(Ops$2.Get, (sexp, builder) => { let [, head, path] = sexp; builder.getVariable(head); for (let i = 0; i < path.length; i++) { builder.getProperty(path[i]); } }); EXPRESSIONS.add(Ops$2.MaybeLocal, (sexp, builder) => { let [, path] = sexp; if (builder.containingLayout.asPartial) { let head = path[0]; path = path.slice(1); builder.resolveMaybeLocal(head); } else { builder.getVariable(0); } for (let i = 0; i < path.length; i++) { builder.getProperty(path[i]); } }); EXPRESSIONS.add(Ops$2.Undefined, (_sexp, builder) => { return builder.pushPrimitiveReference(undefined); }); EXPRESSIONS.add(Ops$2.HasBlock, (sexp, builder) => { builder.hasBlock(sexp[1]); }); EXPRESSIONS.add(Ops$2.HasBlockParams, (sexp, builder) => { builder.hasBlockParams(sexp[1]); }); return EXPRESSIONS; } class Macros { constructor() { let { blocks, inlines } = populateBuiltins(); this.blocks = blocks; this.inlines = inlines; } } class Blocks { constructor() { this.names = (0, _util.dict)(); this.funcs = []; } add(name, func) { this.funcs.push(func); this.names[name] = this.funcs.length - 1; } addMissing(func) { this.missing = func; } compile(name, params, hash, template, inverse, builder) { let index = this.names[name]; if (index === undefined) { let func = this.missing; let handled = func(name, params, hash, template, inverse, builder); } else { let func = this.funcs[index]; func(params, hash, template, inverse, builder); } } } class Inlines { constructor() { this.names = (0, _util.dict)(); this.funcs = []; } add(name, func) { this.funcs.push(func); this.names[name] = this.funcs.length - 1; } addMissing(func) { this.missing = func; } compile(sexp, builder) { let value = sexp[1]; // TODO: Fix this so that expression macros can return // things like components, so that {{component foo}} // is the same as {{(component foo)}} if (!Array.isArray(value)) return ['expr', value]; let name; let params; let hash; if (value[0] === Ops$2.Helper) { name = value[1]; params = value[2]; hash = value[3]; } else if (value[0] === Ops$2.Unknown) { name = value[1]; params = hash = null; } else { return ['expr', value]; } let index = this.names[name]; if (index === undefined && this.missing) { let func = this.missing; let returned = func(name, params, hash, builder); return returned === false ? ['expr', value] : returned; } else if (index !== undefined) { let func = this.funcs[index]; let returned = func(name, params, hash, builder); return returned === false ? ['expr', value] : returned; } else { return ['expr', value]; } } } function populateBuiltins(blocks = new Blocks(), inlines = new Inlines()) { blocks.add('if', (params, _hash, template, inverse, builder) => { // PutArgs // Test(Environment) // Enter(BEGIN, END) // BEGIN: Noop // JumpUnless(ELSE) // Evaluate(default) // Jump(END) // ELSE: Noop // Evalulate(inverse) // END: Noop // Exit if (!params || params.length !== 1) { throw new Error(`SYNTAX ERROR: #if requires a single argument`); } builder.replayableIf({ args() { builder.expr(params[0]); builder.toBoolean(); return 1; }, ifTrue() { builder.invokeStaticBlock(template); }, ifFalse() { if (inverse) { builder.invokeStaticBlock(inverse); } } }); }); blocks.add('unless', (params, _hash, template, inverse, builder) => { // PutArgs // Test(Environment) // Enter(BEGIN, END) // BEGIN: Noop // JumpUnless(ELSE) // Evaluate(default) // Jump(END) // ELSE: Noop // Evalulate(inverse) // END: Noop // Exit if (!params || params.length !== 1) { throw new Error(`SYNTAX ERROR: #unless requires a single argument`); } builder.replayableIf({ args() { builder.expr(params[0]); builder.toBoolean(); return 1; }, ifTrue() { if (inverse) { builder.invokeStaticBlock(inverse); } }, ifFalse() { builder.invokeStaticBlock(template); } }); }); blocks.add('with', (params, _hash, template, inverse, builder) => { // PutArgs // Test(Environment) // Enter(BEGIN, END) // BEGIN: Noop // JumpUnless(ELSE) // Evaluate(default) // Jump(END) // ELSE: Noop // Evalulate(inverse) // END: Noop // Exit if (!params || params.length !== 1) { throw new Error(`SYNTAX ERROR: #with requires a single argument`); } builder.replayableIf({ args() { builder.expr(params[0]); builder.dup(); builder.toBoolean(); return 2; }, ifTrue() { builder.invokeStaticBlock(template, 1); }, ifFalse() { if (inverse) { builder.invokeStaticBlock(inverse); } } }); }); blocks.add('each', (params, hash, template, inverse, builder) => { // Enter(BEGIN, END) // BEGIN: Noop // PutArgs // PutIterable // JumpUnless(ELSE) // EnterList(BEGIN2, END2) // ITER: Noop // NextIter(BREAK) // BEGIN2: Noop // PushChildScope // Evaluate(default) // PopScope // END2: Noop // Exit // Jump(ITER) // BREAK: Noop // ExitList // Jump(END) // ELSE: Noop // Evalulate(inverse) // END: Noop // Exit builder.replayable({ args() { if (hash && hash[0][0] === 'key') { builder.expr(hash[1][0]); } else { builder.pushPrimitiveReference(null); } builder.expr(params[0]); return 2; }, body() { builder.putIterator(); builder.jumpUnless('ELSE'); builder.pushFrame(); builder.dup(_vm.Register.fp, 1); builder.returnTo('ITER'); builder.enterList('BODY'); builder.label('ITER'); builder.iterate('BREAK'); builder.label('BODY'); builder.invokeStaticBlock(template, 2); builder.pop(2); builder.jump('FINALLY'); builder.label('BREAK'); builder.exitList(); builder.popFrame(); builder.jump('FINALLY'); builder.label('ELSE'); if (inverse) { builder.invokeStaticBlock(inverse); } } }); }); blocks.add('in-element', (params, hash, template, _inverse, builder) => { if (!params || params.length !== 1) { throw new Error(`SYNTAX ERROR: #in-element requires a single argument`); } builder.replayableIf({ args() { let [keys, values] = hash; for (let i = 0; i < keys.length; i++) { let key = keys[i]; if (key === 'nextSibling' || key === 'guid') { builder.expr(values[i]); } else { throw new Error(`SYNTAX ERROR: #in-element does not take a \`${keys[0]}\` option`); } } builder.expr(params[0]); builder.dup(); return 4; }, ifTrue() { builder.pushRemoteElement(); builder.invokeStaticBlock(template); builder.popRemoteElement(); } }); }); blocks.add('-with-dynamic-vars', (_params, hash, template, _inverse, builder) => { if (hash) { let [names, expressions] = hash; builder.compileParams(expressions); builder.pushDynamicScope(); builder.bindDynamicScope(names); builder.invokeStaticBlock(template); builder.popDynamicScope(); } else { builder.invokeStaticBlock(template); } }); blocks.add('component', (_params, hash, template, inverse, builder) => { let tag = _params[0]; if (typeof tag === 'string') { let returned = builder.staticComponentHelper(_params[0], hash, template); if (returned) return; } let [definition, ...params] = _params; builder.dynamicComponent(definition, null, params, hash, true, template, inverse); }); inlines.add('component', (_name, _params, hash, builder) => { let tag = _params && _params[0]; if (typeof tag === 'string') { let returned = builder.staticComponentHelper(tag, hash, null); if (returned) return true; } let [definition, ...params] = _params; builder.dynamicComponent(definition, null, params, hash, true, null, null); return true; }); return { blocks, inlines }; } const PLACEHOLDER_HANDLE$1 = -1; class CompilableProgram { constructor(compiler, layout) { this.compiler = compiler; this.layout = layout; this.compiled = null; } get symbolTable() { return this.layout.block; } compile() { if (this.compiled !== null) return this.compiled; this.compiled = PLACEHOLDER_HANDLE$1; let { block: { statements } } = this.layout; return this.compiled = this.compiler.add(statements, this.layout); } } class CompilableBlock { constructor(compiler, parsed) { this.compiler = compiler; this.parsed = parsed; this.compiled = null; } get symbolTable() { return this.parsed.block; } compile() { if (this.compiled !== null) return this.compiled; // Track that compilation has started but not yet finished by temporarily // using a placeholder handle. In eager compilation mode, where compile() // may be called recursively, we use this as a signal that the handle cannot // be known synchronously and must be linked lazily. this.compiled = PLACEHOLDER_HANDLE$1; let { block: { statements }, containingLayout } = this.parsed; return this.compiled = this.compiler.add(statements, containingLayout); } } function compile(statements, builder, compiler) { let sCompiler = statementCompiler(); for (let i = 0; i < statements.length; i++) { sCompiler.compile(statements[i], builder); } let handle = builder.commit(); return handle; } function debugSlice(program, start, end) {} function logOpcode(type, params) { let out = type; if (params) { let args = Object.keys(params).map(p => ` ${p}=${json(params[p])}`).join(''); out += args; } return `(${out})`; } function json(param) {} function debug(pos, c, op, ...operands) { let metadata = null; if (!metadata) { throw (0, _util.unreachable)(`Missing Opcode Metadata for ${op}`); } let out = (0, _util.dict)(); metadata.ops.forEach((operand, index) => { let op = operands[index]; switch (operand.type) { case 'to': out[operand.name] = pos + op; break; case 'i32': case 'symbol': case 'block': out[operand.name] = op; break; case 'handle': out[operand.name] = c.resolveHandle(op); break; case 'str': out[operand.name] = c.getString(op); break; case 'option-str': out[operand.name] = op ? c.getString(op) : null; break; case 'str-array': out[operand.name] = c.getStringArray(op); break; case 'array': out[operand.name] = c.getArray(op); break; case 'bool': out[operand.name] = !!op; break; case 'primitive': out[operand.name] = decodePrimitive(op, c); break; case 'register': out[operand.name] = _vm.Register[op]; break; case 'serializable': out[operand.name] = c.getSerializable(op); break; case 'lazy-constant': out[operand.name] = c.getOther(op); break; } }); return [metadata.name, out]; } function decodePrimitive(primitive, constants) { let flag = primitive & 7; // 111 let value = primitive >> 3; switch (flag) { case 0 /* NUMBER */: return value; case 1 /* FLOAT */: return constants.getNumber(value); case 2 /* STRING */: return constants.getString(value); case 3 /* BOOLEAN_OR_VOID */: switch (value) { case 0: return false; case 1: return true; case 2: return null; case 3: return undefined; } case 4 /* NEGATIVE */: return constants.getNumber(value); default: throw (0, _util.unreachable)(); } } class StdLib { constructor(main, trustingGuardedAppend, cautiousGuardedAppend) { this.main = main; this.trustingGuardedAppend = trustingGuardedAppend; this.cautiousGuardedAppend = cautiousGuardedAppend; } static compile(compiler) { let main = this.std(compiler, b => b.main()); let trustingGuardedAppend = this.std(compiler, b => b.stdAppend(true)); let cautiousGuardedAppend = this.std(compiler, b => b.stdAppend(false)); return new StdLib(main, trustingGuardedAppend, cautiousGuardedAppend); } static std(compiler, callback) { return StdOpcodeBuilder.build(compiler, callback); } getAppend(trusting) { return trusting ? this.trustingGuardedAppend : this.cautiousGuardedAppend; } } class AbstractCompiler { constructor(macros, program, resolver) { this.macros = macros; this.program = program; this.resolver = resolver; this.initialize(); } initialize() { this.stdLib = StdLib.compile(this); } get constants() { return this.program.constants; } compileInline(sexp, builder) { let { inlines } = this.macros; return inlines.compile(sexp, builder); } compileBlock(name, params, hash, template, inverse, builder) { let { blocks } = this.macros; blocks.compile(name, params, hash, template, inverse, builder); } add(statements, containingLayout) { return compile(statements, this.builderFor(containingLayout), this); } commit(scopeSize, buffer) { let heap = this.program.heap; // TODO: change the whole malloc API and do something more efficient let handle = heap.malloc(); for (let i = 0; i < buffer.length; i++) { let value = buffer[i]; if (typeof value === 'function') { heap.pushPlaceholder(value); } else { heap.push(value); } } heap.finishMalloc(handle, scopeSize); return handle; } resolveLayoutForTag(tag, referrer) { let { resolver } = this; let handle = resolver.lookupComponentDefinition(tag, referrer); if (handle === null) return { handle: null, capabilities: null, compilable: null }; return this.resolveLayoutForHandle(handle); } resolveLayoutForHandle(handle) { let { resolver } = this; let capabilities = resolver.getCapabilities(handle); let compilable = null; if (!capabilities.dynamicLayout) { compilable = resolver.getLayout(handle); } return { handle, capabilities, compilable }; } resolveModifier(name, referrer) { return this.resolver.lookupModifier(name, referrer); } resolveHelper(name, referrer) { return this.resolver.lookupHelper(name, referrer); } } let debugCompiler; class WrappedBuilder { constructor(compiler, layout) { this.compiler = compiler; this.layout = layout; this.compiled = null; let { block } = layout; let symbols = block.symbols.slice(); // ensure ATTRS_BLOCK is always included (only once) in the list of symbols let attrsBlockIndex = symbols.indexOf(ATTRS_BLOCK); if (attrsBlockIndex === -1) { this.attrsBlockNumber = symbols.push(ATTRS_BLOCK); } else { this.attrsBlockNumber = attrsBlockIndex + 1; } this.symbolTable = { hasEval: block.hasEval, symbols }; } compile() { if (this.compiled !== null) return this.compiled; //========DYNAMIC // PutValue(TagExpr) // Test // JumpUnless(BODY) // PutComponentOperations // OpenDynamicPrimitiveElement // DidCreateElement // ...attr statements... // FlushElement // BODY: Noop // ...body statements... // PutValue(TagExpr) // Test // JumpUnless(END) // CloseElement // END: Noop // DidRenderLayout // Exit // //========STATIC // OpenPrimitiveElementOpcode // DidCreateElement // ...attr statements... // FlushElement // ...body statements... // CloseElement // DidRenderLayout // Exit let { compiler, layout } = this; let b = compiler.builderFor(layout); b.startLabels(); b.fetch(_vm.Register.s1); b.getComponentTagName(_vm.Register.s0); b.primitiveReference(); b.dup(); b.load(_vm.Register.s1); b.jumpUnless('BODY'); b.fetch(_vm.Register.s1); b.setComponentAttrs(true); b.putComponentOperations(); b.openDynamicElement(); b.didCreateElement(_vm.Register.s0); b.yield(this.attrsBlockNumber, []); b.setComponentAttrs(false); b.flushElement(); b.label('BODY'); b.invokeStaticBlock(blockFor(layout, compiler)); b.fetch(_vm.Register.s1); b.jumpUnless('END'); b.closeElement(); b.label('END'); b.load(_vm.Register.s1); b.stopLabels(); let handle = b.commit(); return this.compiled = handle; } } function blockFor(layout, compiler) { return new CompilableBlock(compiler, { block: { statements: layout.block.statements, parameters: _util.EMPTY_ARRAY }, containingLayout: layout }); } class ComponentBuilder { constructor(builder) { this.builder = builder; } static(handle, args) { let [params, hash, _default, inverse] = args; let { builder } = this; if (handle !== null) { let { capabilities, compilable } = builder.compiler.resolveLayoutForHandle(handle); if (compilable) { builder.pushComponentDefinition(handle); builder.invokeStaticComponent(capabilities, compilable, null, params, hash, false, _default, inverse); } else { builder.pushComponentDefinition(handle); builder.invokeComponent(capabilities, null, params, hash, false, _default, inverse); } } } } class Labels { constructor() { this.labels = (0, _util.dict)(); this.targets = []; } label(name, index) { this.labels[name] = index; } target(at, target) { this.targets.push({ at, target }); } patch(encoder) { let { targets, labels } = this; for (let i = 0; i < targets.length; i++) { let { at, target } = targets[i]; let address = labels[target] - at; encoder.patch(at, address); } } } class StdOpcodeBuilder { constructor(compiler, size = 0) { this.size = size; this.encoder = new _encoder.InstructionEncoder([]); this.labelsStack = new _util.Stack(); this.compiler = compiler; } static build(compiler, callback) { let builder = new StdOpcodeBuilder(compiler); callback(builder); return builder.commit(); } push(name) { switch (arguments.length) { case 1: return this.encoder.encode(name, 0); case 2: return this.encoder.encode(name, 0, arguments[1]); case 3: return this.encoder.encode(name, 0, arguments[1], arguments[2]); default: return this.encoder.encode(name, 0, arguments[1], arguments[2], arguments[3]); } } pushMachine(name) { switch (arguments.length) { case 1: return this.encoder.encode(name, 1024 /* MACHINE_MASK */); case 2: return this.encoder.encode(name, 1024 /* MACHINE_MASK */, arguments[1]); case 3: return this.encoder.encode(name, 1024 /* MACHINE_MASK */, arguments[1], arguments[2]); default: return this.encoder.encode(name, 1024 /* MACHINE_MASK */, arguments[1], arguments[2], arguments[3]); } } commit() { this.pushMachine(24 /* Return */); return this.compiler.commit(this.size, this.encoder.buffer); } reserve(name) { this.encoder.encode(name, 0, -1); } reserveWithOperand(name, operand) { this.encoder.encode(name, 0, -1, operand); } reserveMachine(name) { this.encoder.encode(name, 1024 /* MACHINE_MASK */, -1); } /// main() { this.push(68 /* Main */, _vm.Register.s0); this.invokePreparedComponent(false, false, true); } appendHTML() { this.push(28 /* AppendHTML */); } appendSafeHTML() { this.push(29 /* AppendSafeHTML */); } appendDocumentFragment() { this.push(30 /* AppendDocumentFragment */); } appendNode() { this.push(31 /* AppendNode */); } appendText() { this.push(32 /* AppendText */); } beginComponentTransaction() { this.push(91 /* BeginComponentTransaction */); } commitComponentTransaction() { this.push(92 /* CommitComponentTransaction */); } pushDynamicScope() { this.push(44 /* PushDynamicScope */); } popDynamicScope() { this.push(45 /* PopDynamicScope */); } pushRemoteElement() { this.push(41 /* PushRemoteElement */); } popRemoteElement() { this.push(42 /* PopRemoteElement */); } pushRootScope(symbols, bindCallerScope) { this.push(20 /* RootScope */, symbols, bindCallerScope ? 1 : 0); } pushVirtualRootScope(register) { this.push(21 /* VirtualRootScope */, register); } pushChildScope() { this.push(22 /* ChildScope */); } popScope() { this.push(23 /* PopScope */); } prepareArgs(state) { this.push(79 /* PrepareArgs */, state); } createComponent(state, hasDefault) { let flag = hasDefault | 0; this.push(81 /* CreateComponent */, flag, state); } registerComponentDestructor(state) { this.push(82 /* RegisterComponentDestructor */, state); } putComponentOperations() { this.push(83 /* PutComponentOperations */); } getComponentSelf(state) { this.push(84 /* GetComponentSelf */, state); } getComponentTagName(state) { this.push(85 /* GetComponentTagName */, state); } getComponentLayout(state) { this.push(86 /* GetComponentLayout */, state); } setupForEval(state) { this.push(87 /* SetupForEval */, state); } invokeComponentLayout(state) { this.push(90 /* InvokeComponentLayout */, state); } didCreateElement(state) { this.push(93 /* DidCreateElement */, state); } didRenderLayout(state) { this.push(94 /* DidRenderLayout */, state); } pushFrame() { this.pushMachine(57 /* PushFrame */); } popFrame() { this.pushMachine(58 /* PopFrame */); } pushSmallFrame() { this.pushMachine(59 /* PushSmallFrame */); } popSmallFrame() { this.pushMachine(60 /* PopSmallFrame */); } invokeVirtual() { this.pushMachine(49 /* InvokeVirtual */); } invokeYield() { this.push(51 /* InvokeYield */); } toBoolean() { this.push(63 /* ToBoolean */); } invokePreparedComponent(hasBlock, bindableBlocks, bindableAtNames, populateLayout = null) { this.beginComponentTransaction(); this.pushDynamicScope(); this.createComponent(_vm.Register.s0, hasBlock); // this has to run after createComponent to allow // for late-bound layouts, but a caller is free // to populate the layout earlier if it wants to // and do nothing here. if (populateLayout) populateLayout(); this.registerComponentDestructor(_vm.Register.s0); this.getComponentSelf(_vm.Register.s0); this.pushVirtualRootScope(_vm.Register.s0); this.setVariable(0); this.setupForEval(_vm.Register.s0); if (bindableAtNames) this.setNamedVariables(_vm.Register.s0); if (bindableBlocks) this.setBlocks(_vm.Register.s0); this.pop(); this.invokeComponentLayout(_vm.Register.s0); this.didRenderLayout(_vm.Register.s0); this.popFrame(); this.popScope(); this.popDynamicScope(); this.commitComponentTransaction(); } get pos() { return this.encoder.typePos; } get nextPos() { return this.encoder.size; } /// compileInline(sexp) { return this.compiler.compileInline(sexp, this); } compileBlock(name, params, hash, template, inverse) { this.compiler.compileBlock(name, params, hash, template, inverse, this); } label(name) { this.labels.label(name, this.nextPos); } // helpers get labels() { return this.labelsStack.current; } startLabels() { this.labelsStack.push(new Labels()); } stopLabels() { let label = this.labelsStack.pop(); label.patch(this.encoder); } // components pushCurriedComponent() { this.push(74 /* PushCurriedComponent */); } pushDynamicComponentInstance() { this.push(73 /* PushDynamicComponentInstance */); } // dom openDynamicElement() { this.push(34 /* OpenDynamicElement */); } flushElement() { this.push(38 /* FlushElement */); } closeElement() { this.push(39 /* CloseElement */); } // lists putIterator() { this.push(66 /* PutIterator */); } enterList(start) { this.reserve(64 /* EnterList */); this.labels.target(this.pos, start); } exitList() { this.push(65 /* ExitList */); } iterate(breaks) { this.reserve(67 /* Iterate */); this.labels.target(this.pos, breaks); } // expressions setNamedVariables(state) { this.push(2 /* SetNamedVariables */, state); } setBlocks(state) { this.push(3 /* SetBlocks */, state); } setVariable(symbol) { this.push(4 /* SetVariable */, symbol); } setBlock(symbol) { this.push(5 /* SetBlock */, symbol); } getVariable(symbol) { this.push(6 /* GetVariable */, symbol); } getBlock(symbol) { this.push(8 /* GetBlock */, symbol); } hasBlock(symbol) { this.push(9 /* HasBlock */, symbol); } concat(size) { this.push(11 /* Concat */, size); } load(register) { this.push(18 /* Load */, register); } fetch(register) { this.push(19 /* Fetch */, register); } dup(register = _vm.Register.sp, offset = 0) { return this.push(16 /* Dup */, register, offset); } pop(count = 1) { return this.push(17 /* Pop */, count); } // vm returnTo(label) { this.reserveMachine(25 /* ReturnTo */); this.labels.target(this.pos, label); } primitiveReference() { this.push(14 /* PrimitiveReference */); } reifyU32() { this.push(15 /* ReifyU32 */); } enter(args) { this.push(61 /* Enter */, args); } exit() { this.push(62 /* Exit */); } return() { this.pushMachine(24 /* Return */); } jump(target) { this.reserveMachine(52 /* Jump */); this.labels.target(this.pos, target); } jumpIf(target) { this.reserve(53 /* JumpIf */); this.labels.target(this.pos, target); } jumpUnless(target) { this.reserve(54 /* JumpUnless */); this.labels.target(this.pos, target); } jumpEq(value, target) { this.reserveWithOperand(55 /* JumpEq */, value); this.labels.target(this.pos, target); } assertSame() { this.push(56 /* AssertSame */); } pushEmptyArgs() { this.push(77 /* PushEmptyArgs */); } switch(_opcode, callback) { // Setup the switch DSL let clauses = []; let count = 0; function when(match, callback) { clauses.push({ match, callback, label: `CLAUSE${count++}` }); } // Call the callback callback(when); // Emit the opcodes for the switch this.enter(2); this.assertSame(); this.reifyU32(); this.startLabels(); // First, emit the jump opcodes. We don't need a jump for the last // opcode, since it bleeds directly into its clause. clauses.slice(0, -1).forEach(clause => this.jumpEq(clause.match, clause.label)); // Enumerate the clauses in reverse order. Earlier matches will // require fewer checks. for (let i = clauses.length - 1; i >= 0; i--) { let clause = clauses[i]; this.label(clause.label); this.pop(2); clause.callback(); // The first match is special: it is placed directly before the END // label, so no additional jump is needed at the end of it. if (i !== 0) { this.jump('END'); } } this.label('END'); this.stopLabels(); this.exit(); } stdAppend(trusting) { this.switch(this.contentType(), when => { when(1 /* String */, () => { if (trusting) { this.assertSame(); this.appendHTML(); } else { this.appendText(); } }); when(0 /* Component */, () => { this.pushCurriedComponent(); this.pushDynamicComponentInstance(); this.invokeBareComponent(); }); when(3 /* SafeString */, () => { this.assertSame(); this.appendSafeHTML(); }); when(4 /* Fragment */, () => { this.assertSame(); this.appendDocumentFragment(); }); when(5 /* Node */, () => { this.assertSame(); this.appendNode(); }); }); } populateLayout(state) { this.push(89 /* PopulateLayout */, state); } invokeBareComponent() { this.fetch(_vm.Register.s0); this.dup(_vm.Register.sp, 1); this.load(_vm.Register.s0); this.pushFrame(); this.pushEmptyArgs(); this.prepareArgs(_vm.Register.s0); this.invokePreparedComponent(false, false, true, () => { this.getComponentLayout(_vm.Register.s0); this.populateLayout(_vm.Register.s0); }); this.load(_vm.Register.s0); } isComponent() { this.push(69 /* IsComponent */); } contentType() { this.push(70 /* ContentType */); } pushBlockScope() { this.push(47 /* PushBlockScope */); } } class OpcodeBuilder extends StdOpcodeBuilder { constructor(compiler, containingLayout) { super(compiler, containingLayout ? containingLayout.block.symbols.length : 0); this.containingLayout = containingLayout; this.component = new ComponentBuilder(this); this.expressionCompiler = expressionCompiler(); this.isComponentAttrs = false; this.constants = compiler.constants; this.stdLib = compiler.stdLib; } /// MECHANICS get referrer() { return this.containingLayout && this.containingLayout.referrer; } setComponentAttrs(enabled) { this.isComponentAttrs = enabled; } expr(expression) { if (Array.isArray(expression)) { this.expressionCompiler.compile(expression, this); } else { this.pushPrimitiveReference(expression); } } /// // args pushArgs(names, flags) { let serialized = this.constants.stringArray(names); this.push(76 /* PushArgs */, serialized, flags); } pushYieldableBlock(block) { this.pushSymbolTable(block && block.symbolTable); this.pushBlockScope(); this.pushBlock(block); } curryComponent(definition, /* TODO: attrs: Option, */params, hash, synthetic) { let referrer = this.containingLayout.referrer; this.pushFrame(); this.compileArgs(params, hash, null, synthetic); this.push(80 /* CaptureArgs */); this.expr(definition); this.push(71 /* CurryComponent */, this.constants.serializable(referrer)); this.popFrame(); this.fetch(_vm.Register.v0); } pushSymbolTable(table) { if (table) { let constant = this.constants.serializable(table); this.push(48 /* PushSymbolTable */, constant); } else { this.primitive(null); } } invokeComponent(capabilities, attrs, params, hash, synthetic, block, inverse = null, layout) { this.fetch(_vm.Register.s0); this.dup(_vm.Register.sp, 1); this.load(_vm.Register.s0); this.pushFrame(); let bindableBlocks = !!(block || inverse || attrs); let bindableAtNames = capabilities === true || capabilities.prepareArgs || !!(hash && hash[0].length !== 0); let blocks = { main: block, else: inverse, attrs }; this.compileArgs(params, hash, blocks, synthetic); this.prepareArgs(_vm.Register.s0); this.invokePreparedComponent(block !== null, bindableBlocks, bindableAtNames, () => { if (layout) { this.pushSymbolTable(layout.symbolTable); this.pushLayout(layout); this.resolveLayout(); } else { this.getComponentLayout(_vm.Register.s0); } this.populateLayout(_vm.Register.s0); }); this.load(_vm.Register.s0); } invokeStaticComponent(capabilities, layout, attrs, params, hash, synthetic, block, inverse = null) { let { symbolTable } = layout; let bailOut = symbolTable.hasEval || capabilities.prepareArgs; if (bailOut) { this.invokeComponent(capabilities, attrs, params, hash, synthetic, block, inverse, layout); return; } this.fetch(_vm.Register.s0); this.dup(_vm.Register.sp, 1); this.load(_vm.Register.s0); let { symbols } = symbolTable; if (capabilities.createArgs) { this.pushFrame(); this.compileArgs(null, hash, null, synthetic); } this.beginComponentTransaction(); if (capabilities.dynamicScope) { this.pushDynamicScope(); } if (capabilities.createInstance) { this.createComponent(_vm.Register.s0, block !== null); } if (capabilities.createArgs) { this.popFrame(); } this.pushFrame(); this.registerComponentDestructor(_vm.Register.s0); let bindings = []; this.getComponentSelf(_vm.Register.s0); bindings.push({ symbol: 0, isBlock: false }); for (let i = 0; i < symbols.length; i++) { let symbol = symbols[i]; switch (symbol.charAt(0)) { case '&': let callerBlock = null; if (symbol === '&default') { callerBlock = block; } else if (symbol === '&inverse') { callerBlock = inverse; } else if (symbol === ATTRS_BLOCK) { callerBlock = attrs; } else { throw (0, _util.unreachable)(); } if (callerBlock) { this.pushYieldableBlock(callerBlock); bindings.push({ symbol: i + 1, isBlock: true }); } else { this.pushYieldableBlock(null); bindings.push({ symbol: i + 1, isBlock: true }); } break; case '@': if (!hash) { break; } let [keys, values] = hash; let lookupName = symbol; if (synthetic) { lookupName = symbol.slice(1); } let index = keys.indexOf(lookupName); if (index !== -1) { this.expr(values[index]); bindings.push({ symbol: i + 1, isBlock: false }); } break; } } this.pushRootScope(symbols.length + 1, !!(block || inverse || attrs)); for (let i = bindings.length - 1; i >= 0; i--) { let { symbol, isBlock } = bindings[i]; if (isBlock) { this.setBlock(symbol); } else { this.setVariable(symbol); } } this.invokeStatic(layout); if (capabilities.createInstance) { this.didRenderLayout(_vm.Register.s0); } this.popFrame(); this.popScope(); if (capabilities.dynamicScope) { this.popDynamicScope(); } this.commitComponentTransaction(); this.load(_vm.Register.s0); } dynamicComponent(definition, attrs, params, hash, synthetic, block, inverse = null) { this.replayable({ args: () => { this.expr(definition); this.dup(); return 2; }, body: () => { this.jumpUnless('ELSE'); this.resolveDynamicComponent(this.containingLayout.referrer); this.pushDynamicComponentInstance(); this.invokeComponent(true, attrs, params, hash, synthetic, block, inverse); this.label('ELSE'); } }); } yield(to, params) { this.compileArgs(params, null, null, false); this.getBlock(to); this.resolveBlock(); this.invokeYield(); this.popScope(); this.popFrame(); } guardedAppend(expression, trusting) { this.pushFrame(); this.expr(expression); this.pushMachine(50 /* InvokeStatic */, this.stdLib.getAppend(trusting)); this.popFrame(); } invokeStaticBlock(block, callerCount = 0) { let { parameters } = block.symbolTable; let calleeCount = parameters.length; let count = Math.min(callerCount, calleeCount); this.pushFrame(); if (count) { this.pushChildScope(); for (let i = 0; i < count; i++) { this.dup(_vm.Register.fp, callerCount - i); this.setVariable(parameters[i]); } } this.pushBlock(block); this.resolveBlock(); this.invokeVirtual(); if (count) { this.popScope(); } this.popFrame(); } /// CONVENIENCE // internal helpers string(_string) { return this.constants.string(_string); } names(_names) { let names = []; for (let i = 0; i < _names.length; i++) { let n = _names[i]; names[i] = this.constants.string(n); } return this.constants.array(names); } symbols(symbols) { return this.constants.array(symbols); } // vm primitive(_primitive) { let type = 0 /* NUMBER */; let primitive; switch (typeof _primitive) { case 'number': if (_primitive % 1 === 0) { if (_primitive > -1) { primitive = _primitive; } else { primitive = this.constants.number(_primitive); type = 4 /* NEGATIVE */; } } else { primitive = this.constants.number(_primitive); type = 1 /* FLOAT */; } break; case 'string': primitive = this.string(_primitive); type = 2 /* STRING */; break; case 'boolean': primitive = _primitive | 0; type = 3 /* BOOLEAN_OR_VOID */; break; case 'object': // assume null primitive = 2; type = 3 /* BOOLEAN_OR_VOID */; break; case 'undefined': primitive = 3; type = 3 /* BOOLEAN_OR_VOID */; break; default: throw new Error('Invalid primitive passed to pushPrimitive'); } let immediate = this.sizeImmediate(primitive << 3 | type, primitive); this.push(13 /* Primitive */, immediate); } sizeImmediate(shifted, primitive) { if (shifted >= 65535 /* MAX_SIZE */ || shifted < 0) { return this.constants.number(primitive) << 3 | 5 /* BIG_NUM */; } return shifted; } pushPrimitiveReference(primitive) { this.primitive(primitive); this.primitiveReference(); } // components pushComponentDefinition(handle) { this.push(72 /* PushComponentDefinition */, this.constants.handle(handle)); } resolveDynamicComponent(referrer) { this.push(75 /* ResolveDynamicComponent */, this.constants.serializable(referrer)); } staticComponentHelper(tag, hash, template) { let { handle, capabilities, compilable } = this.compiler.resolveLayoutForTag(tag, this.referrer); if (handle !== null && capabilities !== null) { if (compilable) { if (hash) { for (let i = 0; i < hash.length; i = i + 2) { hash[i][0] = `@${hash[i][0]}`; } } this.pushComponentDefinition(handle); this.invokeStaticComponent(capabilities, compilable, null, null, hash, false, template && template); return true; } } return false; } // partial invokePartial(referrer, symbols, evalInfo) { let _meta = this.constants.serializable(referrer); let _symbols = this.constants.stringArray(symbols); let _evalInfo = this.constants.array(evalInfo); this.push(95 /* InvokePartial */, _meta, _symbols, _evalInfo); } resolveMaybeLocal(name) { this.push(96 /* ResolveMaybeLocal */, this.string(name)); } // debugger debugger(symbols, evalInfo) { this.push(97 /* Debugger */, this.constants.stringArray(symbols), this.constants.array(evalInfo)); } // dom text(text) { this.push(26 /* Text */, this.constants.string(text)); } openPrimitiveElement(tag) { this.push(33 /* OpenElement */, this.constants.string(tag)); } modifier(locator, params, hash) { this.pushFrame(); this.compileArgs(params, hash, null, true); this.push(40 /* Modifier */, this.constants.handle(locator)); this.popFrame(); } comment(_comment) { let comment = this.constants.string(_comment); this.push(27 /* Comment */, comment); } dynamicAttr(_name, _namespace, trusting) { let name = this.constants.string(_name); let namespace = _namespace ? this.constants.string(_namespace) : 0; if (this.isComponentAttrs) { this.push(37 /* ComponentAttr */, name, trusting === true ? 1 : 0, namespace); } else { this.push(36 /* DynamicAttr */, name, trusting === true ? 1 : 0, namespace); } } staticAttr(_name, _namespace, _value) { let name = this.constants.string(_name); let namespace = _namespace ? this.constants.string(_namespace) : 0; if (this.isComponentAttrs) { this.pushPrimitiveReference(_value); this.push(37 /* ComponentAttr */, name, 1, namespace); } else { let value = this.constants.string(_value); this.push(35 /* StaticAttr */, name, value, namespace); } } // expressions hasBlockParams(to) { this.getBlock(to); this.resolveBlock(); this.push(10 /* HasBlockParams */); } getProperty(key) { this.push(7 /* GetProperty */, this.string(key)); } helper(helper, params, hash) { this.pushFrame(); this.compileArgs(params, hash, null, true); this.push(1 /* Helper */, this.constants.handle(helper)); this.popFrame(); this.fetch(_vm.Register.v0); } bindDynamicScope(_names) { this.push(43 /* BindDynamicScope */, this.names(_names)); } // convenience methods /** * A convenience for pushing some arguments on the stack and * running some code if the code needs to be re-executed during * updating execution if some of the arguments have changed. * * # Initial Execution * * The `args` function should push zero or more arguments onto * the stack and return the number of arguments pushed. * * The `body` function provides the instructions to execute both * during initial execution and during updating execution. * * Internally, this function starts by pushing a new frame, so * that the body can return and sets the return point ($ra) to * the ENDINITIAL label. * * It then executes the `args` function, which adds instructions * responsible for pushing the arguments for the block to the * stack. These arguments will be restored to the stack before * updating execution. * * Next, it adds the Enter opcode, which marks the current position * in the DOM, and remembers the current $pc (the next instruction) * as the first instruction to execute during updating execution. * * Next, it runs `body`, which adds the opcodes that should * execute both during initial execution and during updating execution. * If the `body` wishes to finish early, it should Jump to the * `FINALLY` label. * * Next, it adds the FINALLY label, followed by: * * - the Exit opcode, which finalizes the marked DOM started by the * Enter opcode. * - the Return opcode, which returns to the current return point * ($ra). * * Finally, it adds the ENDINITIAL label followed by the PopFrame * instruction, which restores $fp, $sp and $ra. * * # Updating Execution * * Updating execution for this `replayable` occurs if the `body` added an * assertion, via one of the `JumpIf`, `JumpUnless` or `AssertSame` opcodes. * * If, during updating executon, the assertion fails, the initial VM is * restored, and the stored arguments are pushed onto the stack. The DOM * between the starting and ending markers is cleared, and the VM's cursor * is set to the area just cleared. * * The return point ($ra) is set to -1, the exit instruction. * * Finally, the $pc is set to to the instruction saved off by the * Enter opcode during initial execution, and execution proceeds as * usual. * * The only difference is that when a `Return` instruction is * encountered, the program jumps to -1 rather than the END label, * and the PopFrame opcode is not needed. */ replayable({ args, body }) { // Start a new label frame, to give END and RETURN // a unique meaning. this.startLabels(); this.pushFrame(); // If the body invokes a block, its return will return to // END. Otherwise, the return in RETURN will return to END. this.returnTo('ENDINITIAL'); // Push the arguments onto the stack. The args() function // tells us how many stack elements to retain for re-execution // when updating. let count = args(); // Start a new updating closure, remembering `count` elements // from the stack. Everything after this point, and before END, // will execute both initially and to update the block. // // The enter and exit opcodes also track the area of the DOM // associated with this block. If an assertion inside the block // fails (for example, the test value changes from true to false // in an #if), the DOM is cleared and the program is re-executed, // restoring `count` elements to the stack and executing the // instructions between the enter and exit. this.enter(count); // Evaluate the body of the block. The body of the block may // return, which will jump execution to END during initial // execution, and exit the updating routine. body(); // All execution paths in the body should run the FINALLY once // they are done. It is executed both during initial execution // and during updating execution. this.label('FINALLY'); // Finalize the DOM. this.exit(); // In initial execution, this is a noop: it returns to the // immediately following opcode. In updating execution, this // exits the updating routine. this.return(); // Cleanup code for the block. Runs on initial execution // but not on updating. this.label('ENDINITIAL'); this.popFrame(); this.stopLabels(); } /** * A specialized version of the `replayable` convenience that allows the * caller to provide different code based upon whether the item at * the top of the stack is true or false. * * As in `replayable`, the `ifTrue` and `ifFalse` code can invoke `return`. * * During the initial execution, a `return` will continue execution * in the cleanup code, which finalizes the current DOM block and pops * the current frame. * * During the updating execution, a `return` will exit the updating * routine, as it can reuse the DOM block and is always only a single * frame deep. */ replayableIf({ args, ifTrue, ifFalse }) { this.replayable({ args, body: () => { // If the conditional is false, jump to the ELSE label. this.jumpUnless('ELSE'); // Otherwise, execute the code associated with the true branch. ifTrue(); // We're done, so return. In the initial execution, this runs // the cleanup code. In the updating VM, it exits the updating // routine. this.jump('FINALLY'); this.label('ELSE'); // If the conditional is false, and code associatied ith the // false branch was provided, execute it. If there was no code // associated with the false branch, jumping to the else statement // has no other behavior. if (ifFalse) { ifFalse(); } } }); } inlineBlock(block) { return new CompilableBlock(this.compiler, { block, containingLayout: this.containingLayout }); } evalSymbols() { let { containingLayout: { block } } = this; return block.hasEval ? block.symbols : null; } compileParams(params) { if (!params) return 0; for (let i = 0; i < params.length; i++) { this.expr(params[i]); } return params.length; } compileArgs(params, hash, blocks, synthetic) { if (blocks) { this.pushYieldableBlock(blocks.main); this.pushYieldableBlock(blocks.else); this.pushYieldableBlock(blocks.attrs); } let count = this.compileParams(params); let flags = count << 4; if (synthetic) flags |= 0b1000; if (blocks) { flags |= 0b111; } let names = _util.EMPTY_ARRAY; if (hash) { names = hash[0]; let val = hash[1]; for (let i = 0; i < val.length; i++) { this.expr(val[i]); } } this.pushArgs(names, flags); } template(block) { if (!block) return null; return this.inlineBlock(block); } } class LazyOpcodeBuilder extends OpcodeBuilder { pushBlock(block) { if (block) { this.pushOther(block); } else { this.primitive(null); } } resolveBlock() { this.push(46 /* CompileBlock */); } pushLayout(layout) { if (layout) { this.pushOther(layout); } else { this.primitive(null); } } resolveLayout() { this.push(46 /* CompileBlock */); } invokeStatic(compilable) { this.pushOther(compilable); this.push(46 /* CompileBlock */); this.pushMachine(49 /* InvokeVirtual */); } pushOther(value) { this.push(12 /* Constant */, this.other(value)); } other(value) { return this.constants.other(value); } } class EagerOpcodeBuilder extends OpcodeBuilder { pushBlock(block) { let handle = block ? block.compile() : null; this.primitive(handle); } resolveBlock() { return; } pushLayout(layout) { if (layout) { this.primitive(layout.compile()); } else { this.primitive(null); } } resolveLayout() {} invokeStatic(compilable) { let handle = compilable.compile(); // If the handle for the invoked component is not yet known (for example, // because this is a recursive invocation and we're still compiling), push a // function that will produce the correct handle when the heap is // serialized. if (handle === PLACEHOLDER_HANDLE$1) { this.pushMachine(50 /* InvokeStatic */, () => compilable.compile()); } else { this.pushMachine(50 /* InvokeStatic */, handle); } } } class LazyCompiler extends AbstractCompiler { // FIXME: turn to static method constructor(lookup, resolver, macros) { let constants = new _program.LazyConstants(resolver); let program = new _program.Program(constants); super(macros, program, lookup); } builderFor(containingLayout) { return new LazyOpcodeBuilder(this, containingLayout); } } class PartialDefinition { constructor(name, // for debugging template) { this.name = name; this.template = template; } getPartial() { let partial = this.template.asPartial(); let handle = partial.compile(); return { symbolTable: partial.symbolTable, handle }; } } let clientId = 0; function templateFactory({ id: templateId, meta, block }) { let parsedBlock; let id = templateId || `client-${clientId++}`; let create = (compiler, envMeta) => { let newMeta = envMeta ? (0, _util.assign)({}, envMeta, meta) : meta; if (!parsedBlock) { parsedBlock = JSON.parse(block); } return new TemplateImpl(compiler, { id, block: parsedBlock, referrer: newMeta }); }; return { id, meta, create }; } class TemplateImpl { constructor(compiler, parsedLayout) { this.compiler = compiler; this.parsedLayout = parsedLayout; this.layout = null; this.partial = null; this.wrappedLayout = null; let { block } = parsedLayout; this.symbols = block.symbols; this.hasEval = block.hasEval; this.referrer = parsedLayout.referrer; this.id = parsedLayout.id || `client-${clientId++}`; } asLayout() { if (this.layout) return this.layout; return this.layout = new CompilableProgram(this.compiler, Object.assign({}, this.parsedLayout, { asPartial: false })); } asPartial() { if (this.partial) return this.partial; return this.layout = new CompilableProgram(this.compiler, Object.assign({}, this.parsedLayout, { asPartial: true })); } asWrappedLayout() { if (this.wrappedLayout) return this.wrappedLayout; return this.wrappedLayout = new WrappedBuilder(this.compiler, Object.assign({}, this.parsedLayout, { asPartial: false })); } } exports.ATTRS_BLOCK = ATTRS_BLOCK; exports.Macros = Macros; exports.LazyCompiler = LazyCompiler; exports.compile = compile; exports.AbstractCompiler = AbstractCompiler; exports.debugCompiler = debugCompiler; exports.CompilableBlock = CompilableBlock; exports.CompilableProgram = CompilableProgram; exports.LazyOpcodeBuilder = LazyOpcodeBuilder; exports.EagerOpcodeBuilder = EagerOpcodeBuilder; exports.OpcodeBuilder = OpcodeBuilder; exports.StdOpcodeBuilder = StdOpcodeBuilder; exports.PartialDefinition = PartialDefinition; exports.templateFactory = templateFactory; exports.debug = debug; exports.debugSlice = debugSlice; exports.logOpcode = logOpcode; exports.WrappedBuilder = WrappedBuilder; exports.PLACEHOLDER_HANDLE = PLACEHOLDER_HANDLE; }); enifed('@glimmer/program', ['exports', '@glimmer/util'], function (exports) { 'use strict'; exports.Opcode = exports.Program = exports.RuntimeProgram = exports.WriteOnlyProgram = exports.Heap = exports.LazyConstants = exports.Constants = exports.RuntimeConstants = exports.WriteOnlyConstants = exports.WELL_KNOWN_EMPTY_ARRAY_POSITION = undefined; const UNRESOLVED = {}; const WELL_KNOWN_EMPTY_ARRAY_POSITION = 0; const WELL_KNOW_EMPTY_ARRAY = Object.freeze([]); class WriteOnlyConstants { constructor() { // `0` means NULL this.strings = []; this.arrays = [WELL_KNOW_EMPTY_ARRAY]; this.tables = []; this.handles = []; this.resolved = []; this.numbers = []; } string(value) { let index = this.strings.indexOf(value); if (index > -1) { return index; } return this.strings.push(value) - 1; } stringArray(strings) { let _strings = new Array(strings.length); for (let i = 0; i < strings.length; i++) { _strings[i] = this.string(strings[i]); } return this.array(_strings); } array(values) { if (values.length === 0) { return WELL_KNOWN_EMPTY_ARRAY_POSITION; } let index = this.arrays.indexOf(values); if (index > -1) { return index; } return this.arrays.push(values) - 1; } handle(handle) { let index = this.handles.indexOf(handle); if (index > -1) { return index; } this.resolved.push(UNRESOLVED); return this.handles.push(handle) - 1; } serializable(value) { let str = JSON.stringify(value); let index = this.strings.indexOf(str); if (index > -1) { return index; } return this.strings.push(str) - 1; } number(number) { let index = this.numbers.indexOf(number); if (index > -1) { return index; } return this.numbers.push(number) - 1; } toPool() { return { strings: this.strings, arrays: this.arrays, handles: this.handles, numbers: this.numbers }; } } class RuntimeConstants { constructor(resolver, pool) { this.resolver = resolver; this.strings = pool.strings; this.arrays = pool.arrays; this.handles = pool.handles; this.resolved = this.handles.map(() => UNRESOLVED); this.numbers = pool.numbers; } getString(value) { return this.strings[value]; } getNumber(value) { return this.numbers[value]; } getStringArray(value) { let names = this.getArray(value); let _names = new Array(names.length); for (let i = 0; i < names.length; i++) { let n = names[i]; _names[i] = this.getString(n); } return _names; } getArray(value) { return this.arrays[value]; } resolveHandle(index) { let resolved = this.resolved[index]; if (resolved === UNRESOLVED) { let handle = this.handles[index]; resolved = this.resolved[index] = this.resolver.resolve(handle); } return resolved; } getSerializable(s) { return JSON.parse(this.strings[s]); } } class Constants extends WriteOnlyConstants { constructor(resolver, pool) { super(); this.resolver = resolver; if (pool) { this.strings = pool.strings; this.arrays = pool.arrays; this.handles = pool.handles; this.resolved = this.handles.map(() => UNRESOLVED); this.numbers = pool.numbers; } } getNumber(value) { return this.numbers[value]; } getString(value) { return this.strings[value]; } getStringArray(value) { let names = this.getArray(value); let _names = new Array(names.length); for (let i = 0; i < names.length; i++) { let n = names[i]; _names[i] = this.getString(n); } return _names; } getArray(value) { return this.arrays[value]; } resolveHandle(index) { let resolved = this.resolved[index]; if (resolved === UNRESOLVED) { let handle = this.handles[index]; resolved = this.resolved[index] = this.resolver.resolve(handle); } return resolved; } getSerializable(s) { return JSON.parse(this.strings[s]); } } class LazyConstants extends Constants { constructor() { super(...arguments); this.others = []; this.serializables = []; } serializable(value) { let index = this.serializables.indexOf(value); if (index > -1) { return index; } return this.serializables.push(value) - 1; } getSerializable(s) { return this.serializables[s]; } getOther(value) { return this.others[value - 1]; } other(other) { return this.others.push(other); } } class Opcode { constructor(heap) { this.heap = heap; this.offset = 0; } get size() { let rawType = this.heap.getbyaddr(this.offset); return ((rawType & 768 /* OPERAND_LEN_MASK */) >> 8 /* ARG_SHIFT */) + 1; } get isMachine() { let rawType = this.heap.getbyaddr(this.offset); return rawType & 1024 /* MACHINE_MASK */; } get type() { return this.heap.getbyaddr(this.offset) & 255 /* TYPE_MASK */; } get op1() { return this.heap.getbyaddr(this.offset + 1); } get op2() { return this.heap.getbyaddr(this.offset + 2); } get op3() { return this.heap.getbyaddr(this.offset + 3); } } function encodeTableInfo(size, scopeSize, state) { return size | scopeSize << 16 | state << 30; } function changeState(info, newState) { return info | newState << 30; } const PAGE_SIZE = 0x100000; /** * The Heap is responsible for dynamically allocating * memory in which we read/write the VM's instructions * from/to. When we malloc we pass out a VMHandle, which * is used as an indirect way of accessing the memory during * execution of the VM. Internally we track the different * regions of the memory in an int array known as the table. * * The table 32-bit aligned and has the following layout: * * | ... | hp (u32) | info (u32) | * | ... | Handle | Size | Scope Size | State | * | ... | 32-bits | 16b | 14b | 2b | * * With this information we effectively have the ability to * control when we want to free memory. That being said you * can not free during execution as raw address are only * valid during the execution. This means you cannot close * over them as you will have a bad memory access exception. */ class Heap { constructor(serializedHeap) { this.placeholders = []; this.offset = 0; this.handle = 0; this.capacity = PAGE_SIZE; if (serializedHeap) { let { buffer, table, handle } = serializedHeap; this.heap = new Uint16Array(buffer); this.table = table; this.offset = this.heap.length; this.handle = handle; this.capacity = 0; } else { this.heap = new Uint16Array(PAGE_SIZE); this.table = []; } } push(item) { this.sizeCheck(); this.heap[this.offset++] = item; } sizeCheck() { if (this.capacity === 0) { let heap = slice(this.heap, 0, this.offset); this.heap = new Uint16Array(heap.length + PAGE_SIZE); this.heap.set(heap, 0); this.capacity = PAGE_SIZE; } this.capacity--; } getbyaddr(address) { return this.heap[address]; } setbyaddr(address, value) { this.heap[address] = value; } malloc() { this.table.push(this.offset, 0); let handle = this.handle; this.handle += 2 /* ENTRY_SIZE */; return handle; } finishMalloc(handle, scopeSize) { let start = this.table[handle]; let finish = this.offset; let instructionSize = finish - start; let info = encodeTableInfo(instructionSize, scopeSize, 0 /* Allocated */); this.table[handle + 1 /* INFO_OFFSET */] = info; } size() { return this.offset; } // It is illegal to close over this address, as compaction // may move it. However, it is legal to use this address // multiple times between compactions. getaddr(handle) { return this.table[handle]; } gethandle(address) { this.table.push(address, encodeTableInfo(0, 0, 3 /* Pointer */)); let handle = this.handle; this.handle += 2 /* ENTRY_SIZE */; return handle; } sizeof(handle) { return -1; } scopesizeof(handle) { let info = this.table[handle + 1 /* INFO_OFFSET */]; return (info & 1073676288 /* SCOPE_MASK */) >> 16; } free(handle) { let info = this.table[handle + 1 /* INFO_OFFSET */]; this.table[handle + 1 /* INFO_OFFSET */] = changeState(info, 1 /* Freed */); } /** * The heap uses the [Mark-Compact Algorithm](https://en.wikipedia.org/wiki/Mark-compact_algorithm) to shift * reachable memory to the bottom of the heap and freeable * memory to the top of the heap. When we have shifted all * the reachable memory to the top of the heap, we move the * offset to the next free position. */ compact() { let compactedSize = 0; let { table, table: { length }, heap } = this; for (let i = 0; i < length; i += 2 /* ENTRY_SIZE */) { let offset = table[i]; let info = table[i + 1 /* INFO_OFFSET */]; let size = info & 65535 /* SIZE_MASK */; let state = info & 3221225472 /* STATE_MASK */ >> 30; if (state === 2 /* Purged */) { continue; } else if (state === 1 /* Freed */) { // transition to "already freed" aka "purged" // a good improvement would be to reuse // these slots table[i + 1 /* INFO_OFFSET */] = changeState(info, 2 /* Purged */); compactedSize += size; } else if (state === 0 /* Allocated */) { for (let j = offset; j <= i + size; j++) { heap[j - compactedSize] = heap[j]; } table[i] = offset - compactedSize; } else if (state === 3 /* Pointer */) { table[i] = offset - compactedSize; } } this.offset = this.offset - compactedSize; } pushPlaceholder(valueFunc) { this.sizeCheck(); let address = this.offset++; this.heap[address] = 65535 /* MAX_SIZE */; this.placeholders.push([address, valueFunc]); } patchPlaceholders() { let { placeholders } = this; for (let i = 0; i < placeholders.length; i++) { let [address, getValue] = placeholders[i]; this.setbyaddr(address, getValue()); } } capture(offset = this.offset) { this.patchPlaceholders(); // Only called in eager mode let buffer = slice(this.heap, 0, offset).buffer; return { handle: this.handle, table: this.table, buffer: buffer }; } } class WriteOnlyProgram { constructor(constants = new WriteOnlyConstants(), heap = new Heap()) { this.constants = constants; this.heap = heap; this._opcode = new Opcode(this.heap); } opcode(offset) { this._opcode.offset = offset; return this._opcode; } } class RuntimeProgram { constructor(constants, heap) { this.constants = constants; this.heap = heap; this._opcode = new Opcode(this.heap); } static hydrate(rawHeap, pool, resolver) { let heap = new Heap(rawHeap); let constants = new RuntimeConstants(resolver, pool); return new RuntimeProgram(constants, heap); } opcode(offset) { this._opcode.offset = offset; return this._opcode; } } class Program extends WriteOnlyProgram {} function slice(arr, start, end) { if (arr.slice !== undefined) { return arr.slice(start, end); } let ret = new Uint16Array(end); for (; start < end; start++) { ret[start] = arr[start]; } return ret; } exports.WELL_KNOWN_EMPTY_ARRAY_POSITION = WELL_KNOWN_EMPTY_ARRAY_POSITION; exports.WriteOnlyConstants = WriteOnlyConstants; exports.RuntimeConstants = RuntimeConstants; exports.Constants = Constants; exports.LazyConstants = LazyConstants; exports.Heap = Heap; exports.WriteOnlyProgram = WriteOnlyProgram; exports.RuntimeProgram = RuntimeProgram; exports.Program = Program; exports.Opcode = Opcode; }); enifed('@glimmer/reference', ['exports', '@glimmer/util'], function (exports, _util) { 'use strict'; exports.isModified = exports.ReferenceCache = exports.map = exports.CachedReference = exports.UpdatableTag = exports.CachedTag = exports.combine = exports.combineSlice = exports.combineTagged = exports.DirtyableTag = exports.bump = exports.isConstTag = exports.isConst = exports.CURRENT_TAG = exports.VOLATILE_TAG = exports.CONSTANT_TAG = exports.TagWrapper = exports.RevisionTag = exports.VOLATILE = exports.INITIAL = exports.CONSTANT = exports.IteratorSynchronizer = exports.ReferenceIterator = exports.IterationArtifacts = exports.ListItem = exports.ConstReference = undefined; const CONSTANT = 0; const INITIAL = 1; const VOLATILE = NaN; class RevisionTag { validate(snapshot) { return this.value() === snapshot; } } RevisionTag.id = 0; const VALUE = []; const VALIDATE = []; class TagWrapper { constructor(type, inner) { this.type = type; this.inner = inner; } value() { let func = VALUE[this.type]; return func(this.inner); } validate(snapshot) { let func = VALIDATE[this.type]; return func(this.inner, snapshot); } } function register(Type) { let type = VALUE.length; VALUE.push(tag => tag.value()); VALIDATE.push((tag, snapshot) => tag.validate(snapshot)); Type.id = type; } /// // CONSTANT: 0 VALUE.push(() => CONSTANT); VALIDATE.push((_tag, snapshot) => snapshot === CONSTANT); const CONSTANT_TAG = new TagWrapper(0, null); // VOLATILE: 1 VALUE.push(() => VOLATILE); VALIDATE.push((_tag, snapshot) => snapshot === VOLATILE); const VOLATILE_TAG = new TagWrapper(1, null); // CURRENT: 2 VALUE.push(() => $REVISION); VALIDATE.push((_tag, snapshot) => snapshot === $REVISION); const CURRENT_TAG = new TagWrapper(2, null); function isConst({ tag }) { return tag === CONSTANT_TAG; } function isConstTag(tag) { return tag === CONSTANT_TAG; } /// let $REVISION = INITIAL; function bump() { $REVISION++; } class DirtyableTag extends RevisionTag { static create(revision = $REVISION) { return new TagWrapper(this.id, new DirtyableTag(revision)); } constructor(revision = $REVISION) { super(); this.revision = revision; } value() { return this.revision; } dirty() { this.revision = ++$REVISION; } } register(DirtyableTag); function combineTagged(tagged) { let optimized = []; for (let i = 0, l = tagged.length; i < l; i++) { let tag = tagged[i].tag; if (tag === VOLATILE_TAG) return VOLATILE_TAG; if (tag === CONSTANT_TAG) continue; optimized.push(tag); } return _combine(optimized); } function combineSlice(slice) { let optimized = []; let node = slice.head(); while (node !== null) { let tag = node.tag; if (tag === VOLATILE_TAG) return VOLATILE_TAG; if (tag !== CONSTANT_TAG) optimized.push(tag); node = slice.nextNode(node); } return _combine(optimized); } function combine(tags) { let optimized = []; for (let i = 0, l = tags.length; i < l; i++) { let tag = tags[i]; if (tag === VOLATILE_TAG) return VOLATILE_TAG; if (tag === CONSTANT_TAG) continue; optimized.push(tag); } return _combine(optimized); } function _combine(tags) { switch (tags.length) { case 0: return CONSTANT_TAG; case 1: return tags[0]; case 2: return TagsPair.create(tags[0], tags[1]); default: return TagsCombinator.create(tags); } } class CachedTag extends RevisionTag { constructor() { super(...arguments); this.lastChecked = null; this.lastValue = null; } value() { let { lastChecked, lastValue } = this; if (lastChecked !== $REVISION) { this.lastChecked = $REVISION; this.lastValue = lastValue = this.compute(); } return this.lastValue; } invalidate() { this.lastChecked = null; } } class TagsPair extends CachedTag { static create(first, second) { return new TagWrapper(this.id, new TagsPair(first, second)); } constructor(first, second) { super(); this.first = first; this.second = second; } compute() { return Math.max(this.first.value(), this.second.value()); } } register(TagsPair); class TagsCombinator extends CachedTag { static create(tags) { return new TagWrapper(this.id, new TagsCombinator(tags)); } constructor(tags) { super(); this.tags = tags; } compute() { let { tags } = this; let max = -1; for (let i = 0; i < tags.length; i++) { let value = tags[i].value(); max = Math.max(value, max); } return max; } } register(TagsCombinator); class UpdatableTag extends CachedTag { static create(tag) { return new TagWrapper(this.id, new UpdatableTag(tag)); } constructor(tag) { super(); this.tag = tag; this.lastUpdated = INITIAL; } compute() { return Math.max(this.lastUpdated, this.tag.value()); } update(tag) { if (tag !== this.tag) { this.tag = tag; this.lastUpdated = $REVISION; this.invalidate(); } } } register(UpdatableTag); class CachedReference { constructor() { this.lastRevision = null; this.lastValue = null; } value() { let { tag, lastRevision, lastValue } = this; if (lastRevision === null || !tag.validate(lastRevision)) { lastValue = this.lastValue = this.compute(); this.lastRevision = tag.value(); } return lastValue; } invalidate() { this.lastRevision = null; } } class MapperReference extends CachedReference { constructor(reference, mapper) { super(); this.tag = reference.tag; this.reference = reference; this.mapper = mapper; } compute() { let { reference, mapper } = this; return mapper(reference.value()); } } function map(reference, mapper) { return new MapperReference(reference, mapper); } ////////// class ReferenceCache { constructor(reference) { this.lastValue = null; this.lastRevision = null; this.initialized = false; this.tag = reference.tag; this.reference = reference; } peek() { if (!this.initialized) { return this.initialize(); } return this.lastValue; } revalidate() { if (!this.initialized) { return this.initialize(); } let { reference, lastRevision } = this; let tag = reference.tag; if (tag.validate(lastRevision)) return NOT_MODIFIED; this.lastRevision = tag.value(); let { lastValue } = this; let value = reference.value(); if (value === lastValue) return NOT_MODIFIED; this.lastValue = value; return value; } initialize() { let { reference } = this; let value = this.lastValue = reference.value(); this.lastRevision = reference.tag.value(); this.initialized = true; return value; } } const NOT_MODIFIED = 'adb3b78e-3d22-4e4b-877a-6317c2c5c145'; function isModified(value) { return value !== NOT_MODIFIED; } class ConstReference { constructor(inner) { this.inner = inner; this.tag = CONSTANT_TAG; } value() { return this.inner; } } class ListItem extends _util.ListNode { constructor(iterable, result) { super(iterable.valueReferenceFor(result)); this.retained = false; this.seen = false; this.key = result.key; this.iterable = iterable; this.memo = iterable.memoReferenceFor(result); } update(item) { this.retained = true; this.iterable.updateValueReference(this.value, item); this.iterable.updateMemoReference(this.memo, item); } shouldRemove() { return !this.retained; } reset() { this.retained = false; this.seen = false; } } class IterationArtifacts { constructor(iterable) { this.iterator = null; this.map = (0, _util.dict)(); this.list = new _util.LinkedList(); this.tag = iterable.tag; this.iterable = iterable; } isEmpty() { let iterator = this.iterator = this.iterable.iterate(); return iterator.isEmpty(); } iterate() { let iterator; if (this.iterator === null) { iterator = this.iterable.iterate(); } else { iterator = this.iterator; } this.iterator = null; return iterator; } has(key) { return !!this.map[key]; } get(key) { return this.map[key]; } wasSeen(key) { let node = this.map[key]; return node !== undefined && node.seen; } append(item) { let { map, list, iterable } = this; let node = map[item.key] = new ListItem(iterable, item); list.append(node); return node; } insertBefore(item, reference) { let { map, list, iterable } = this; let node = map[item.key] = new ListItem(iterable, item); node.retained = true; list.insertBefore(node, reference); return node; } move(item, reference) { let { list } = this; item.retained = true; list.remove(item); list.insertBefore(item, reference); } remove(item) { let { list } = this; list.remove(item); delete this.map[item.key]; } nextNode(item) { return this.list.nextNode(item); } head() { return this.list.head(); } } class ReferenceIterator { // if anyone needs to construct this object with something other than // an iterable, let @wycats know. constructor(iterable) { this.iterator = null; let artifacts = new IterationArtifacts(iterable); this.artifacts = artifacts; } next() { let { artifacts } = this; let iterator = this.iterator = this.iterator || artifacts.iterate(); let item = iterator.next(); if (item === null) return null; return artifacts.append(item); } } var Phase; (function (Phase) { Phase[Phase["Append"] = 0] = "Append"; Phase[Phase["Prune"] = 1] = "Prune"; Phase[Phase["Done"] = 2] = "Done"; })(Phase || (Phase = {})); class IteratorSynchronizer { constructor({ target, artifacts }) { this.target = target; this.artifacts = artifacts; this.iterator = artifacts.iterate(); this.current = artifacts.head(); } sync() { let phase = Phase.Append; while (true) { switch (phase) { case Phase.Append: phase = this.nextAppend(); break; case Phase.Prune: phase = this.nextPrune(); break; case Phase.Done: this.nextDone(); return; } } } advanceToKey(key) { let { current, artifacts } = this; let seek = current; while (seek !== null && seek.key !== key) { seek.seen = true; seek = artifacts.nextNode(seek); } if (seek !== null) { this.current = artifacts.nextNode(seek); } } nextAppend() { let { iterator, current, artifacts } = this; let item = iterator.next(); if (item === null) { return this.startPrune(); } let { key } = item; if (current !== null && current.key === key) { this.nextRetain(item); } else if (artifacts.has(key)) { this.nextMove(item); } else { this.nextInsert(item); } return Phase.Append; } nextRetain(item) { let { artifacts, current } = this; current = current; current.update(item); this.current = artifacts.nextNode(current); this.target.retain(item.key, current.value, current.memo); } nextMove(item) { let { current, artifacts, target } = this; let { key } = item; let found = artifacts.get(item.key); found.update(item); if (artifacts.wasSeen(item.key)) { artifacts.move(found, current); target.move(found.key, found.value, found.memo, current ? current.key : null); } else { this.advanceToKey(key); } } nextInsert(item) { let { artifacts, target, current } = this; let node = artifacts.insertBefore(item, current); target.insert(node.key, node.value, node.memo, current ? current.key : null); } startPrune() { this.current = this.artifacts.head(); return Phase.Prune; } nextPrune() { let { artifacts, target, current } = this; if (current === null) { return Phase.Done; } let node = current; this.current = artifacts.nextNode(node); if (node.shouldRemove()) { artifacts.remove(node); target.delete(node.key); } else { node.reset(); } return Phase.Prune; } nextDone() { this.target.done(); } } exports.ConstReference = ConstReference; exports.ListItem = ListItem; exports.IterationArtifacts = IterationArtifacts; exports.ReferenceIterator = ReferenceIterator; exports.IteratorSynchronizer = IteratorSynchronizer; exports.CONSTANT = CONSTANT; exports.INITIAL = INITIAL; exports.VOLATILE = VOLATILE; exports.RevisionTag = RevisionTag; exports.TagWrapper = TagWrapper; exports.CONSTANT_TAG = CONSTANT_TAG; exports.VOLATILE_TAG = VOLATILE_TAG; exports.CURRENT_TAG = CURRENT_TAG; exports.isConst = isConst; exports.isConstTag = isConstTag; exports.bump = bump; exports.DirtyableTag = DirtyableTag; exports.combineTagged = combineTagged; exports.combineSlice = combineSlice; exports.combine = combine; exports.CachedTag = CachedTag; exports.UpdatableTag = UpdatableTag; exports.CachedReference = CachedReference; exports.map = map; exports.ReferenceCache = ReferenceCache; exports.isModified = isModified; }); enifed('@glimmer/runtime', ['exports', '@glimmer/util', '@glimmer/reference', '@glimmer/vm', '@glimmer/low-level'], function (exports, _util, _reference, _vm2, _lowLevel) { 'use strict'; exports.hasCapability = exports.capabilityFlagsFrom = exports.Cursor = exports.ConcreteBounds = exports.RehydrateBuilder = exports.rehydrationBuilder = exports.clientBuilder = exports.NewElementBuilder = exports.normalizeProperty = exports.insertHTMLBefore = exports.isWhitespace = exports.DOMTreeConstruction = exports.IDOMChanges = exports.SVG_NAMESPACE = exports.DOMChanges = exports.curry = exports.isCurriedComponentDefinition = exports.CurriedComponentDefinition = exports.MINIMAL_CAPABILITIES = exports.DEFAULT_CAPABILITIES = exports.DefaultEnvironment = exports.Environment = exports.Scope = exports.EMPTY_ARGS = exports.DynamicAttribute = exports.SimpleDynamicAttribute = exports.RenderResult = exports.UpdatingVM = exports.LowLevelVM = exports.getDynamicVar = exports.resetDebuggerCallback = exports.setDebuggerCallback = exports.ConditionalReference = exports.PrimitiveReference = exports.UNDEFINED_REFERENCE = exports.NULL_REFERENCE = exports.renderMain = undefined; // these import bindings will be stripped from build class AppendOpcodes { constructor() { this.evaluateOpcode = (0, _util.fillNulls)(98 /* Size */).slice(); } add(name, evaluate, kind = 'syscall') { this.evaluateOpcode[name] = { syscall: kind === 'syscall', evaluate }; } debugBefore(vm, opcode, type) { let sp; let state; return { sp: sp, state }; } debugAfter(vm, opcode, type, pre) { let expectedChange; let { sp, state } = pre; let metadata = null; if (metadata !== null) { if (typeof metadata.stackChange === 'number') { expectedChange = metadata.stackChange; } else { expectedChange = metadata.stackChange({ opcode, constants: vm.constants, state }); if (isNaN(expectedChange)) throw (0, _util.unreachable)(); } } } evaluate(vm, opcode, type) { let operation = this.evaluateOpcode[type]; if (operation.syscall) { operation.evaluate(vm, opcode); } else { operation.evaluate(vm.inner, opcode); } } } const APPEND_OPCODES = new AppendOpcodes(); class AbstractOpcode { constructor() { (0, _util.initializeGuid)(this); } } class UpdatingOpcode extends AbstractOpcode { constructor() { super(...arguments); this.next = null; this.prev = null; } } class PrimitiveReference extends _reference.ConstReference { constructor(value) { super(value); } static create(value) { if (value === undefined) { return UNDEFINED_REFERENCE; } else if (value === null) { return NULL_REFERENCE; } else if (value === true) { return TRUE_REFERENCE; } else if (value === false) { return FALSE_REFERENCE; } else if (typeof value === 'number') { return new ValueReference(value); } else { return new StringReference(value); } } get(_key) { return UNDEFINED_REFERENCE; } } class StringReference extends PrimitiveReference { constructor() { super(...arguments); this.lengthReference = null; } get(key) { if (key === 'length') { let { lengthReference } = this; if (lengthReference === null) { lengthReference = this.lengthReference = new ValueReference(this.inner.length); } return lengthReference; } else { return super.get(key); } } } class ValueReference extends PrimitiveReference { constructor(value) { super(value); } } const UNDEFINED_REFERENCE = new ValueReference(undefined); const NULL_REFERENCE = new ValueReference(null); const TRUE_REFERENCE = new ValueReference(true); const FALSE_REFERENCE = new ValueReference(false); class ConditionalReference { constructor(inner) { this.inner = inner; this.tag = inner.tag; } value() { return this.toBool(this.inner.value()); } toBool(value) { return !!value; } } class ConcatReference extends _reference.CachedReference { constructor(parts) { super(); this.parts = parts; this.tag = (0, _reference.combineTagged)(parts); } compute() { let parts = new Array(); for (let i = 0; i < this.parts.length; i++) { let value = this.parts[i].value(); if (value !== null && value !== undefined) { parts[i] = castToString(value); } } if (parts.length > 0) { return parts.join(''); } return null; } } function castToString(value) { if (typeof value.toString !== 'function') { return ''; } return String(value); } APPEND_OPCODES.add(1 /* Helper */, (vm, { op1: handle }) => { let stack = vm.stack; let helper = vm.constants.resolveHandle(handle); let args = stack.pop(); let value = helper(vm, args); vm.loadValue(_vm2.Register.v0, value); }); APPEND_OPCODES.add(6 /* GetVariable */, (vm, { op1: symbol }) => { let expr = vm.referenceForSymbol(symbol); vm.stack.push(expr); }); APPEND_OPCODES.add(4 /* SetVariable */, (vm, { op1: symbol }) => { let expr = vm.stack.pop(); vm.scope().bindSymbol(symbol, expr); }); APPEND_OPCODES.add(5 /* SetBlock */, (vm, { op1: symbol }) => { let handle = vm.stack.pop(); let scope = vm.stack.pop(); // FIXME(mmun): shouldn't need to cast this let table = vm.stack.pop(); let block = table ? [handle, scope, table] : null; vm.scope().bindBlock(symbol, block); }); APPEND_OPCODES.add(96 /* ResolveMaybeLocal */, (vm, { op1: _name }) => { let name = vm.constants.getString(_name); let locals = vm.scope().getPartialMap(); let ref = locals[name]; if (ref === undefined) { ref = vm.getSelf().get(name); } vm.stack.push(ref); }); APPEND_OPCODES.add(20 /* RootScope */, (vm, { op1: symbols, op2: bindCallerScope }) => { vm.pushRootScope(symbols, !!bindCallerScope); }); APPEND_OPCODES.add(7 /* GetProperty */, (vm, { op1: _key }) => { let key = vm.constants.getString(_key); let expr = vm.stack.pop(); vm.stack.push(expr.get(key)); }); APPEND_OPCODES.add(8 /* GetBlock */, (vm, { op1: _block }) => { let { stack } = vm; let block = vm.scope().getBlock(_block); if (block) { stack.push(block[2]); stack.push(block[1]); stack.push(block[0]); } else { stack.push(null); stack.push(null); stack.push(null); } }); APPEND_OPCODES.add(9 /* HasBlock */, (vm, { op1: _block }) => { let hasBlock = !!vm.scope().getBlock(_block); vm.stack.push(hasBlock ? TRUE_REFERENCE : FALSE_REFERENCE); }); APPEND_OPCODES.add(10 /* HasBlockParams */, vm => { // FIXME(mmun): should only need to push the symbol table let block = vm.stack.pop(); let scope = vm.stack.pop(); let table = vm.stack.pop(); let hasBlockParams = table && table.parameters.length; vm.stack.push(hasBlockParams ? TRUE_REFERENCE : FALSE_REFERENCE); }); APPEND_OPCODES.add(11 /* Concat */, (vm, { op1: count }) => { let out = new Array(count); for (let i = count; i > 0; i--) { let offset = i - 1; out[offset] = vm.stack.pop(); } vm.stack.push(new ConcatReference(out)); }); const CURRIED_COMPONENT_DEFINITION_BRAND = 'CURRIED COMPONENT DEFINITION [id=6f00feb9-a0ef-4547-99ea-ac328f80acea]'; function isCurriedComponentDefinition(definition) { return !!(definition && definition[CURRIED_COMPONENT_DEFINITION_BRAND]); } function isComponentDefinition(definition) { return definition && definition[CURRIED_COMPONENT_DEFINITION_BRAND]; } class CurriedComponentDefinition { /** @internal */ constructor(inner, args) { this.inner = inner; this.args = args; this[CURRIED_COMPONENT_DEFINITION_BRAND] = true; } unwrap(args) { args.realloc(this.offset); let definition = this; while (true) { let { args: curriedArgs, inner } = definition; if (curriedArgs) { args.positional.prepend(curriedArgs.positional); args.named.merge(curriedArgs.named); } if (!isCurriedComponentDefinition(inner)) { return inner; } definition = inner; } } /** @internal */ get offset() { let { inner, args } = this; let length = args ? args.positional.length : 0; return isCurriedComponentDefinition(inner) ? length + inner.offset : length; } } function curry(spec, args = null) { return new CurriedComponentDefinition(spec, args); } function normalizeStringValue(value) { if (isEmpty(value)) { return ''; } return String(value); } function shouldCoerce(value) { return isString(value) || isEmpty(value) || typeof value === 'boolean' || typeof value === 'number'; } function isEmpty(value) { return value === null || value === undefined || typeof value.toString !== 'function'; } function isSafeString(value) { return typeof value === 'object' && value !== null && typeof value.toHTML === 'function'; } function isNode(value) { return typeof value === 'object' && value !== null && typeof value.nodeType === 'number'; } function isFragment(value) { return isNode(value) && value.nodeType === 11; } function isString(value) { return typeof value === 'string'; } class DynamicTextContent extends UpdatingOpcode { constructor(node, reference, lastValue) { super(); this.node = node; this.reference = reference; this.lastValue = lastValue; this.type = 'dynamic-text'; this.tag = reference.tag; this.lastRevision = this.tag.value(); } evaluate() { let { reference, tag } = this; if (!tag.validate(this.lastRevision)) { this.lastRevision = tag.value(); this.update(reference.value()); } } update(value) { let { lastValue } = this; if (value === lastValue) return; let normalized; if (isEmpty(value)) { normalized = ''; } else if (isString(value)) { normalized = value; } else { normalized = String(value); } if (normalized !== lastValue) { let textNode = this.node; textNode.nodeValue = this.lastValue = normalized; } } } class IsCurriedComponentDefinitionReference extends ConditionalReference { static create(inner) { return new IsCurriedComponentDefinitionReference(inner); } toBool(value) { return isCurriedComponentDefinition(value); } } class ContentTypeReference { constructor(inner) { this.inner = inner; this.tag = inner.tag; } value() { let value = this.inner.value(); if (shouldCoerce(value)) { return 1 /* String */; } else if (isComponentDefinition(value)) { return 0 /* Component */; } else if (isSafeString(value)) { return 3 /* SafeString */; } else if (isFragment(value)) { return 4 /* Fragment */; } else if (isNode(value)) { return 5 /* Node */; } else { return 1 /* String */; } } } APPEND_OPCODES.add(28 /* AppendHTML */, vm => { let reference = vm.stack.pop(); let rawValue = reference.value(); let value = isEmpty(rawValue) ? '' : String(rawValue); vm.elements().appendDynamicHTML(value); }); APPEND_OPCODES.add(29 /* AppendSafeHTML */, vm => { let reference = vm.stack.pop(); let rawValue = reference.value().toHTML(); let value = isEmpty(rawValue) ? '' : rawValue; vm.elements().appendDynamicHTML(value); }); APPEND_OPCODES.add(32 /* AppendText */, vm => { let reference = vm.stack.pop(); let rawValue = reference.value(); let value = isEmpty(rawValue) ? '' : String(rawValue); let node = vm.elements().appendDynamicText(value); if (!(0, _reference.isConst)(reference)) { vm.updateWith(new DynamicTextContent(node, reference, value)); } }); APPEND_OPCODES.add(30 /* AppendDocumentFragment */, vm => { let reference = vm.stack.pop(); let value = reference.value(); vm.elements().appendDynamicFragment(value); }); APPEND_OPCODES.add(31 /* AppendNode */, vm => { let reference = vm.stack.pop(); let value = reference.value(); vm.elements().appendDynamicNode(value); }); APPEND_OPCODES.add(22 /* ChildScope */, vm => vm.pushChildScope()); APPEND_OPCODES.add(23 /* PopScope */, vm => vm.popScope()); APPEND_OPCODES.add(44 /* PushDynamicScope */, vm => vm.pushDynamicScope()); APPEND_OPCODES.add(45 /* PopDynamicScope */, vm => vm.popDynamicScope()); APPEND_OPCODES.add(12 /* Constant */, (vm, { op1: other }) => { vm.stack.push(vm.constants.getOther(other)); }); APPEND_OPCODES.add(13 /* Primitive */, (vm, { op1: primitive }) => { let stack = vm.stack; let flag = primitive & 7; // 111 let value = primitive >> 3; switch (flag) { case 0 /* NUMBER */: stack.push(value); break; case 1 /* FLOAT */: stack.push(vm.constants.getNumber(value)); break; case 2 /* STRING */: stack.push(vm.constants.getString(value)); break; case 3 /* BOOLEAN_OR_VOID */: stack.pushEncodedImmediate(primitive); break; case 4 /* NEGATIVE */: stack.push(vm.constants.getNumber(value)); break; case 5 /* BIG_NUM */: stack.push(vm.constants.getNumber(value)); break; } }); APPEND_OPCODES.add(14 /* PrimitiveReference */, vm => { let stack = vm.stack; stack.push(PrimitiveReference.create(stack.pop())); }); APPEND_OPCODES.add(15 /* ReifyU32 */, vm => { let stack = vm.stack; stack.push(stack.peek().value()); }); APPEND_OPCODES.add(16 /* Dup */, (vm, { op1: register, op2: offset }) => { let position = vm.fetchValue(register) - offset; vm.stack.dup(position); }); APPEND_OPCODES.add(17 /* Pop */, (vm, { op1: count }) => { vm.stack.pop(count); }); APPEND_OPCODES.add(18 /* Load */, (vm, { op1: register }) => { vm.load(register); }); APPEND_OPCODES.add(19 /* Fetch */, (vm, { op1: register }) => { vm.fetch(register); }); APPEND_OPCODES.add(43 /* BindDynamicScope */, (vm, { op1: _names }) => { let names = vm.constants.getArray(_names); vm.bindDynamicScope(names); }); APPEND_OPCODES.add(61 /* Enter */, (vm, { op1: args }) => { vm.enter(args); }); APPEND_OPCODES.add(62 /* Exit */, vm => { vm.exit(); }); APPEND_OPCODES.add(48 /* PushSymbolTable */, (vm, { op1: _table }) => { let stack = vm.stack; stack.push(vm.constants.getSerializable(_table)); }); APPEND_OPCODES.add(47 /* PushBlockScope */, vm => { let stack = vm.stack; stack.push(vm.scope()); }); APPEND_OPCODES.add(46 /* CompileBlock */, vm => { let stack = vm.stack; let block = stack.pop(); if (block) { stack.pushSmi(block.compile()); } else { stack.pushNull(); } }); APPEND_OPCODES.add(51 /* InvokeYield */, vm => { let { stack } = vm; let handle = stack.pop(); let scope = stack.pop(); // FIXME(mmun): shouldn't need to cast this let table = stack.pop(); let args = stack.pop(); if (table === null) { // To balance the pop{Frame,Scope} vm.pushFrame(); vm.pushScope(scope); // Could be null but it doesnt matter as it is immediatelly popped. return; } let invokingScope = scope; // If necessary, create a child scope { let locals = table.parameters; let localsCount = locals.length; if (localsCount > 0) { invokingScope = invokingScope.child(); for (let i = 0; i < localsCount; i++) { invokingScope.bindSymbol(locals[i], args.at(i)); } } } vm.pushFrame(); vm.pushScope(invokingScope); vm.call(handle); }); APPEND_OPCODES.add(53 /* JumpIf */, (vm, { op1: target }) => { let reference = vm.stack.pop(); if ((0, _reference.isConst)(reference)) { if (reference.value()) { vm.goto(target); } } else { let cache = new _reference.ReferenceCache(reference); if (cache.peek()) { vm.goto(target); } vm.updateWith(new Assert(cache)); } }); APPEND_OPCODES.add(54 /* JumpUnless */, (vm, { op1: target }) => { let reference = vm.stack.pop(); if ((0, _reference.isConst)(reference)) { if (!reference.value()) { vm.goto(target); } } else { let cache = new _reference.ReferenceCache(reference); if (!cache.peek()) { vm.goto(target); } vm.updateWith(new Assert(cache)); } }); APPEND_OPCODES.add(55 /* JumpEq */, (vm, { op1: target, op2: comparison }) => { let other = vm.stack.peek(); if (other === comparison) { vm.goto(target); } }); APPEND_OPCODES.add(56 /* AssertSame */, vm => { let reference = vm.stack.peek(); if (!(0, _reference.isConst)(reference)) { vm.updateWith(Assert.initialize(new _reference.ReferenceCache(reference))); } }); APPEND_OPCODES.add(63 /* ToBoolean */, vm => { let { env, stack } = vm; stack.push(env.toConditionalReference(stack.pop())); }); class Assert extends UpdatingOpcode { constructor(cache) { super(); this.type = 'assert'; this.tag = cache.tag; this.cache = cache; } static initialize(cache) { let assert = new Assert(cache); cache.peek(); return assert; } evaluate(vm) { let { cache } = this; if ((0, _reference.isModified)(cache.revalidate())) { vm.throw(); } } } class JumpIfNotModifiedOpcode extends UpdatingOpcode { constructor(tag, target) { super(); this.target = target; this.type = 'jump-if-not-modified'; this.tag = tag; this.lastRevision = tag.value(); } evaluate(vm) { let { tag, target, lastRevision } = this; if (!vm.alwaysRevalidate && tag.validate(lastRevision)) { vm.goto(target); } } didModify() { this.lastRevision = this.tag.value(); } } class DidModifyOpcode extends UpdatingOpcode { constructor(target) { super(); this.target = target; this.type = 'did-modify'; this.tag = _reference.CONSTANT_TAG; } evaluate() { this.target.didModify(); } } class LabelOpcode { constructor(label) { this.tag = _reference.CONSTANT_TAG; this.type = 'label'; this.label = null; this.prev = null; this.next = null; (0, _util.initializeGuid)(this); this.label = label; } evaluate() {} inspect() { return `${this.label} [${this._guid}]`; } } APPEND_OPCODES.add(26 /* Text */, (vm, { op1: text }) => { vm.elements().appendText(vm.constants.getString(text)); }); APPEND_OPCODES.add(27 /* Comment */, (vm, { op1: text }) => { vm.elements().appendComment(vm.constants.getString(text)); }); APPEND_OPCODES.add(33 /* OpenElement */, (vm, { op1: tag }) => { vm.elements().openElement(vm.constants.getString(tag)); }); APPEND_OPCODES.add(34 /* OpenDynamicElement */, vm => { let tagName = vm.stack.pop().value(); vm.elements().openElement(tagName); }); APPEND_OPCODES.add(41 /* PushRemoteElement */, vm => { let elementRef = vm.stack.pop(); let nextSiblingRef = vm.stack.pop(); let guidRef = vm.stack.pop(); let element; let nextSibling; let guid = guidRef.value(); if ((0, _reference.isConst)(elementRef)) { element = elementRef.value(); } else { let cache = new _reference.ReferenceCache(elementRef); element = cache.peek(); vm.updateWith(new Assert(cache)); } if ((0, _reference.isConst)(nextSiblingRef)) { nextSibling = nextSiblingRef.value(); } else { let cache = new _reference.ReferenceCache(nextSiblingRef); nextSibling = cache.peek(); vm.updateWith(new Assert(cache)); } vm.elements().pushRemoteElement(element, guid, nextSibling); }); APPEND_OPCODES.add(42 /* PopRemoteElement */, vm => { vm.elements().popRemoteElement(); }); APPEND_OPCODES.add(38 /* FlushElement */, vm => { let operations = vm.fetchValue(_vm2.Register.t0); if (operations) { operations.flush(vm); vm.loadValue(_vm2.Register.t0, null); } vm.elements().flushElement(); }); APPEND_OPCODES.add(39 /* CloseElement */, vm => { vm.elements().closeElement(); }); APPEND_OPCODES.add(40 /* Modifier */, (vm, { op1: handle }) => { let { manager, state } = vm.constants.resolveHandle(handle); let stack = vm.stack; let args = stack.pop(); let { element, updateOperations } = vm.elements(); let dynamicScope = vm.dynamicScope(); let modifier = manager.create(element, state, args, dynamicScope, updateOperations); vm.env.scheduleInstallModifier(modifier, manager); let destructor = manager.getDestructor(modifier); if (destructor) { vm.newDestroyable(destructor); } let tag = manager.getTag(modifier); if (!(0, _reference.isConstTag)(tag)) { vm.updateWith(new UpdateModifierOpcode(tag, manager, modifier)); } }); class UpdateModifierOpcode extends UpdatingOpcode { constructor(tag, manager, modifier) { super(); this.tag = tag; this.manager = manager; this.modifier = modifier; this.type = 'update-modifier'; this.lastUpdated = tag.value(); } evaluate(vm) { let { manager, modifier, tag, lastUpdated } = this; if (!tag.validate(lastUpdated)) { vm.env.scheduleUpdateModifier(modifier, manager); this.lastUpdated = tag.value(); } } } APPEND_OPCODES.add(35 /* StaticAttr */, (vm, { op1: _name, op2: _value, op3: _namespace }) => { let name = vm.constants.getString(_name); let value = vm.constants.getString(_value); let namespace = _namespace ? vm.constants.getString(_namespace) : null; vm.elements().setStaticAttribute(name, value, namespace); }); APPEND_OPCODES.add(36 /* DynamicAttr */, (vm, { op1: _name, op2: trusting, op3: _namespace }) => { let name = vm.constants.getString(_name); let reference = vm.stack.pop(); let value = reference.value(); let namespace = _namespace ? vm.constants.getString(_namespace) : null; let attribute = vm.elements().setDynamicAttribute(name, value, !!trusting, namespace); if (!(0, _reference.isConst)(reference)) { vm.updateWith(new UpdateDynamicAttributeOpcode(reference, attribute)); } }); class UpdateDynamicAttributeOpcode extends UpdatingOpcode { constructor(reference, attribute) { super(); this.reference = reference; this.attribute = attribute; this.type = 'patch-element'; this.tag = reference.tag; this.lastRevision = this.tag.value(); } evaluate(vm) { let { attribute, reference, tag } = this; if (!tag.validate(this.lastRevision)) { this.lastRevision = tag.value(); attribute.update(reference.value(), vm.env); } } } function resolveComponent(resolver, name, meta) { let definition = resolver.lookupComponentDefinition(name, meta); return definition; } class CurryComponentReference { constructor(inner, resolver, meta, args) { this.inner = inner; this.resolver = resolver; this.meta = meta; this.args = args; this.tag = inner.tag; this.lastValue = null; this.lastDefinition = null; } value() { let { inner, lastValue } = this; let value = inner.value(); if (value === lastValue) { return this.lastDefinition; } let definition = null; if (isCurriedComponentDefinition(value)) { definition = value; } else if (typeof value === 'string' && value) { let { resolver, meta } = this; definition = resolveComponent(resolver, value, meta); } definition = this.curry(definition); this.lastValue = value; this.lastDefinition = definition; return definition; } get() { return UNDEFINED_REFERENCE; } curry(definition) { let { args } = this; if (!args && isCurriedComponentDefinition(definition)) { return definition; } else if (!definition) { return null; } else { return new CurriedComponentDefinition(definition, args); } } } class ClassListReference { constructor(list) { this.list = list; this.tag = (0, _reference.combineTagged)(list); this.list = list; } value() { let ret = []; let { list } = this; for (let i = 0; i < list.length; i++) { let value = normalizeStringValue(list[i].value()); if (value) ret.push(value); } return ret.length === 0 ? null : ret.join(' '); } } /** * Converts a ComponentCapabilities object into a 32-bit integer representation. */ function capabilityFlagsFrom(capabilities) { return 0 | (capabilities.dynamicLayout ? 1 /* DynamicLayout */ : 0) | (capabilities.dynamicTag ? 2 /* DynamicTag */ : 0) | (capabilities.prepareArgs ? 4 /* PrepareArgs */ : 0) | (capabilities.createArgs ? 8 /* CreateArgs */ : 0) | (capabilities.attributeHook ? 16 /* AttributeHook */ : 0) | (capabilities.elementHook ? 32 /* ElementHook */ : 0) | (capabilities.dynamicScope ? 64 /* DynamicScope */ : 0) | (capabilities.createCaller ? 128 /* CreateCaller */ : 0) | (capabilities.updateHook ? 256 /* UpdateHook */ : 0) | (capabilities.createInstance ? 512 /* CreateInstance */ : 0); } function hasCapability(capabilities, capability) { return !!(capabilities & capability); } APPEND_OPCODES.add(69 /* IsComponent */, vm => { let stack = vm.stack; let ref = stack.pop(); stack.push(IsCurriedComponentDefinitionReference.create(ref)); }); APPEND_OPCODES.add(70 /* ContentType */, vm => { let stack = vm.stack; let ref = stack.peek(); stack.push(new ContentTypeReference(ref)); }); APPEND_OPCODES.add(71 /* CurryComponent */, (vm, { op1: _meta }) => { let stack = vm.stack; let definition = stack.pop(); let capturedArgs = stack.pop(); let meta = vm.constants.getSerializable(_meta); let resolver = vm.constants.resolver; vm.loadValue(_vm2.Register.v0, new CurryComponentReference(definition, resolver, meta, capturedArgs)); // expectStackChange(vm.stack, -args.length - 1, 'CurryComponent'); }); APPEND_OPCODES.add(72 /* PushComponentDefinition */, (vm, { op1: handle }) => { let definition = vm.constants.resolveHandle(handle); let { manager } = definition; let capabilities = capabilityFlagsFrom(manager.getCapabilities(definition.state)); let instance = { definition, manager, capabilities, state: null, handle: null, table: null, lookup: null }; vm.stack.push(instance); }); APPEND_OPCODES.add(75 /* ResolveDynamicComponent */, (vm, { op1: _meta }) => { let stack = vm.stack; let component = stack.pop().value(); let meta = vm.constants.getSerializable(_meta); vm.loadValue(_vm2.Register.t1, null); // Clear the temp register let definition; if (typeof component === 'string') { let { constants: { resolver } } = vm; let resolvedDefinition = resolveComponent(resolver, component, meta); definition = resolvedDefinition; } else if (isCurriedComponentDefinition(component)) { definition = component; } else { throw (0, _util.unreachable)(); } stack.push(definition); }); APPEND_OPCODES.add(73 /* PushDynamicComponentInstance */, vm => { let { stack } = vm; let definition = stack.pop(); let capabilities, manager; if (isCurriedComponentDefinition(definition)) { manager = capabilities = null; } else { manager = definition.manager; capabilities = capabilityFlagsFrom(manager.getCapabilities(definition.state)); } stack.push({ definition, capabilities, manager, state: null, handle: null, table: null }); }); APPEND_OPCODES.add(74 /* PushCurriedComponent */, (vm, { op1: _meta }) => { let stack = vm.stack; let component = stack.pop().value(); let definition; if (isCurriedComponentDefinition(component)) { definition = component; } else { throw (0, _util.unreachable)(); } stack.push(definition); }); APPEND_OPCODES.add(76 /* PushArgs */, (vm, { op1: _names, op2: flags }) => { let stack = vm.stack; let names = vm.constants.getStringArray(_names); let positionalCount = flags >> 4; let synthetic = flags & 0b1000; let blockNames = []; if (flags & 0b0100) blockNames.push('main'); if (flags & 0b0010) blockNames.push('else'); if (flags & 0b0001) blockNames.push('attrs'); vm.args.setup(stack, names, blockNames, positionalCount, !!synthetic); stack.push(vm.args); }); APPEND_OPCODES.add(77 /* PushEmptyArgs */, vm => { let { stack } = vm; stack.push(vm.args.empty(stack)); }); APPEND_OPCODES.add(80 /* CaptureArgs */, vm => { let stack = vm.stack; let args = stack.pop(); let capturedArgs = args.capture(); stack.push(capturedArgs); }); APPEND_OPCODES.add(79 /* PrepareArgs */, (vm, { op1: _state }) => { let stack = vm.stack; let instance = vm.fetchValue(_state); let args = stack.pop(); let { definition } = instance; if (isCurriedComponentDefinition(definition)) { definition = resolveCurriedComponentDefinition(instance, definition, args); } let { manager, state } = definition; let capabilities = instance.capabilities; if (hasCapability(capabilities, 4 /* PrepareArgs */) !== true) { stack.push(args); return; } let blocks = args.blocks.values; let blockNames = args.blocks.names; let preparedArgs = manager.prepareArgs(state, args); if (preparedArgs) { args.clear(); for (let i = 0; i < blocks.length; i++) { stack.push(blocks[i]); } let { positional, named } = preparedArgs; let positionalCount = positional.length; for (let i = 0; i < positionalCount; i++) { stack.push(positional[i]); } let names = Object.keys(named); for (let i = 0; i < names.length; i++) { stack.push(named[names[i]]); } args.setup(stack, names, blockNames, positionalCount, true); } stack.push(args); }); function resolveCurriedComponentDefinition(instance, definition, args) { let unwrappedDefinition = instance.definition = definition.unwrap(args); let { manager, state } = unwrappedDefinition; instance.manager = manager; instance.capabilities = capabilityFlagsFrom(manager.getCapabilities(state)); return unwrappedDefinition; } APPEND_OPCODES.add(81 /* CreateComponent */, (vm, { op1: flags, op2: _state }) => { let instance = vm.fetchValue(_state); let { definition, manager } = instance; let capabilities = instance.capabilities = capabilityFlagsFrom(manager.getCapabilities(definition.state)); let dynamicScope = null; if (hasCapability(capabilities, 64 /* DynamicScope */)) { dynamicScope = vm.dynamicScope(); } let hasDefaultBlock = flags & 1; let args = null; if (hasCapability(capabilities, 8 /* CreateArgs */)) { args = vm.stack.peek(); } let self = null; if (hasCapability(capabilities, 128 /* CreateCaller */)) { self = vm.getSelf(); } let state = manager.create(vm.env, definition.state, args, dynamicScope, self, !!hasDefaultBlock); // We want to reuse the `state` POJO here, because we know that the opcodes // only transition at exactly one place. instance.state = state; let tag = manager.getTag(state); if (hasCapability(capabilities, 256 /* UpdateHook */) && !(0, _reference.isConstTag)(tag)) { vm.updateWith(new UpdateComponentOpcode(tag, state, manager, dynamicScope)); } }); APPEND_OPCODES.add(82 /* RegisterComponentDestructor */, (vm, { op1: _state }) => { let { manager, state } = vm.fetchValue(_state); let destructor = manager.getDestructor(state); if (destructor) vm.newDestroyable(destructor); }); APPEND_OPCODES.add(91 /* BeginComponentTransaction */, vm => { vm.beginCacheGroup(); vm.elements().pushSimpleBlock(); }); APPEND_OPCODES.add(83 /* PutComponentOperations */, vm => { vm.loadValue(_vm2.Register.t0, new ComponentElementOperations()); }); APPEND_OPCODES.add(37 /* ComponentAttr */, (vm, { op1: _name, op2: trusting, op3: _namespace }) => { let name = vm.constants.getString(_name); let reference = vm.stack.pop(); let namespace = _namespace ? vm.constants.getString(_namespace) : null; vm.fetchValue(_vm2.Register.t0).setAttribute(name, reference, !!trusting, namespace); }); class ComponentElementOperations { constructor() { this.attributes = (0, _util.dict)(); this.classes = []; } setAttribute(name, value, trusting, namespace) { let deferred = { value, namespace, trusting }; if (name === 'class') { this.classes.push(value); } this.attributes[name] = deferred; } flush(vm) { for (let name in this.attributes) { let attr = this.attributes[name]; let { value: reference, namespace, trusting } = attr; if (name === 'class') { reference = new ClassListReference(this.classes); } if (name === 'type') { continue; } let attribute = vm.elements().setDynamicAttribute(name, reference.value(), trusting, namespace); if (!(0, _reference.isConst)(reference)) { vm.updateWith(new UpdateDynamicAttributeOpcode(reference, attribute)); } } if ('type' in this.attributes) { let type = this.attributes.type; let { value: reference, namespace, trusting } = type; let attribute = vm.elements().setDynamicAttribute('type', reference.value(), trusting, namespace); if (!(0, _reference.isConst)(reference)) { vm.updateWith(new UpdateDynamicAttributeOpcode(reference, attribute)); } } } } APPEND_OPCODES.add(93 /* DidCreateElement */, (vm, { op1: _state }) => { let { definition, state } = vm.fetchValue(_state); let { manager } = definition; let operations = vm.fetchValue(_vm2.Register.t0); let action = 'DidCreateElementOpcode#evaluate'; manager.didCreateElement(state, vm.elements().expectConstructing(action), operations); }); APPEND_OPCODES.add(84 /* GetComponentSelf */, (vm, { op1: _state }) => { let { definition, state } = vm.fetchValue(_state); let { manager } = definition; vm.stack.push(manager.getSelf(state)); }); APPEND_OPCODES.add(85 /* GetComponentTagName */, (vm, { op1: _state }) => { let { definition, state } = vm.fetchValue(_state); let { manager } = definition; vm.stack.push(manager.getTagName(state)); }); // Dynamic Invocation Only APPEND_OPCODES.add(86 /* GetComponentLayout */, (vm, { op1: _state }) => { let instance = vm.fetchValue(_state); let { manager, definition } = instance; let { constants: { resolver }, stack } = vm; let { state: instanceState, capabilities } = instance; let { state: definitionState } = definition; let invoke; if (hasStaticLayout(capabilities, manager)) { invoke = manager.getLayout(definitionState, resolver); } else if (hasDynamicLayout(capabilities, manager)) { invoke = manager.getDynamicLayout(instanceState, resolver); } else { throw (0, _util.unreachable)(); } stack.push(invoke.symbolTable); stack.push(invoke.handle); }); function hasStaticLayout(capabilities, _manager) { return hasCapability(capabilities, 1 /* DynamicLayout */) === false; } function hasDynamicLayout(capabilities, _manager) { return hasCapability(capabilities, 1 /* DynamicLayout */) === true; } APPEND_OPCODES.add(68 /* Main */, (vm, { op1: register }) => { let definition = vm.stack.pop(); let invocation = vm.stack.pop(); let { manager } = definition; let capabilities = capabilityFlagsFrom(manager.getCapabilities(definition.state)); let state = { definition, manager, capabilities, state: null, handle: invocation.handle, table: invocation.symbolTable, lookup: null }; vm.loadValue(register, state); }); APPEND_OPCODES.add(89 /* PopulateLayout */, (vm, { op1: _state }) => { let { stack } = vm; let handle = stack.pop(); let table = stack.pop(); let state = vm.fetchValue(_state); state.handle = handle; state.table = table; }); APPEND_OPCODES.add(21 /* VirtualRootScope */, (vm, { op1: _state }) => { let { symbols } = vm.fetchValue(_state).table; vm.pushRootScope(symbols.length + 1, true); }); APPEND_OPCODES.add(87 /* SetupForEval */, (vm, { op1: _state }) => { let state = vm.fetchValue(_state); if (state.table.hasEval) { let lookup = state.lookup = (0, _util.dict)(); vm.scope().bindEvalScope(lookup); } }); APPEND_OPCODES.add(2 /* SetNamedVariables */, (vm, { op1: _state }) => { let state = vm.fetchValue(_state); let scope = vm.scope(); let args = vm.stack.peek(); let callerNames = args.named.atNames; for (let i = callerNames.length - 1; i >= 0; i--) { let atName = callerNames[i]; let symbol = state.table.symbols.indexOf(callerNames[i]); let value = args.named.get(atName, false); if (symbol !== -1) scope.bindSymbol(symbol + 1, value); if (state.lookup) state.lookup[atName] = value; } }); function bindBlock(symbolName, blockName, state, blocks, vm) { let symbol = state.table.symbols.indexOf(symbolName); let block = blocks.get(blockName); if (symbol !== -1) { vm.scope().bindBlock(symbol + 1, block); } if (state.lookup) state.lookup[symbolName] = block; } APPEND_OPCODES.add(3 /* SetBlocks */, (vm, { op1: _state }) => { let state = vm.fetchValue(_state); let { blocks } = vm.stack.peek(); bindBlock('&attrs', 'attrs', state, blocks, vm); bindBlock('&inverse', 'else', state, blocks, vm); bindBlock('&default', 'main', state, blocks, vm); }); // Dynamic Invocation Only APPEND_OPCODES.add(90 /* InvokeComponentLayout */, (vm, { op1: _state }) => { let state = vm.fetchValue(_state); vm.call(state.handle); }); APPEND_OPCODES.add(94 /* DidRenderLayout */, (vm, { op1: _state }) => { let { manager, state } = vm.fetchValue(_state); let bounds = vm.elements().popBlock(); let mgr = manager; mgr.didRenderLayout(state, bounds); vm.env.didCreate(state, manager); vm.updateWith(new DidUpdateLayoutOpcode(manager, state, bounds)); }); APPEND_OPCODES.add(92 /* CommitComponentTransaction */, vm => { vm.commitCacheGroup(); }); class UpdateComponentOpcode extends UpdatingOpcode { constructor(tag, component, manager, dynamicScope) { super(); this.tag = tag; this.component = component; this.manager = manager; this.dynamicScope = dynamicScope; this.type = 'update-component'; } evaluate(_vm) { let { component, manager, dynamicScope } = this; manager.update(component, dynamicScope); } } class DidUpdateLayoutOpcode extends UpdatingOpcode { constructor(manager, component, bounds) { super(); this.manager = manager; this.component = component; this.bounds = bounds; this.type = 'did-update-layout'; this.tag = _reference.CONSTANT_TAG; } evaluate(vm) { let { manager, component, bounds } = this; manager.didUpdateLayout(component, bounds); vm.env.didUpdate(component, manager); } } /* tslint:disable */ function debugCallback(context, get) { console.info('Use `context`, and `get()` to debug this template.'); // for example... context === get('this'); debugger; } /* tslint:enable */ let callback = debugCallback; // For testing purposes function setDebuggerCallback(cb) { callback = cb; } function resetDebuggerCallback() { callback = debugCallback; } class ScopeInspector { constructor(scope, symbols, evalInfo) { this.scope = scope; this.locals = (0, _util.dict)(); for (let i = 0; i < evalInfo.length; i++) { let slot = evalInfo[i]; let name = symbols[slot - 1]; let ref = scope.getSymbol(slot); this.locals[name] = ref; } } get(path) { let { scope, locals } = this; let parts = path.split('.'); let [head, ...tail] = path.split('.'); let evalScope = scope.getEvalScope(); let ref; if (head === 'this') { ref = scope.getSelf(); } else if (locals[head]) { ref = locals[head]; } else if (head.indexOf('@') === 0 && evalScope[head]) { ref = evalScope[head]; } else { ref = this.scope.getSelf(); tail = parts; } return tail.reduce((r, part) => r.get(part), ref); } } APPEND_OPCODES.add(97 /* Debugger */, (vm, { op1: _symbols, op2: _evalInfo }) => { let symbols = vm.constants.getStringArray(_symbols); let evalInfo = vm.constants.getArray(_evalInfo); let inspector = new ScopeInspector(vm.scope(), symbols, evalInfo); callback(vm.getSelf().value(), path => inspector.get(path).value()); }); APPEND_OPCODES.add(95 /* InvokePartial */, (vm, { op1: _meta, op2: _symbols, op3: _evalInfo }) => { let { constants, constants: { resolver }, stack } = vm; let name = stack.pop().value(); let meta = constants.getSerializable(_meta); let outerSymbols = constants.getStringArray(_symbols); let evalInfo = constants.getArray(_evalInfo); let handle = resolver.lookupPartial(name, meta); let definition = resolver.resolve(handle); let { symbolTable, handle: vmHandle } = definition.getPartial(); { let partialSymbols = symbolTable.symbols; let outerScope = vm.scope(); let partialScope = vm.pushRootScope(partialSymbols.length, false); let evalScope = outerScope.getEvalScope(); partialScope.bindCallerScope(outerScope.getCallerScope()); partialScope.bindEvalScope(evalScope); partialScope.bindSelf(outerScope.getSelf()); let locals = Object.create(outerScope.getPartialMap()); for (let i = 0; i < evalInfo.length; i++) { let slot = evalInfo[i]; let name = outerSymbols[slot - 1]; let ref = outerScope.getSymbol(slot); locals[name] = ref; } if (evalScope) { for (let i = 0; i < partialSymbols.length; i++) { let name = partialSymbols[i]; let symbol = i + 1; let value = evalScope[name]; if (value !== undefined) partialScope.bind(symbol, value); } } partialScope.bindPartialMap(locals); vm.pushFrame(); // sp += 2 vm.call(vmHandle); } }); class IterablePresenceReference { constructor(artifacts) { this.tag = artifacts.tag; this.artifacts = artifacts; } value() { return !this.artifacts.isEmpty(); } } APPEND_OPCODES.add(66 /* PutIterator */, vm => { let stack = vm.stack; let listRef = stack.pop(); let key = stack.pop(); let iterable = vm.env.iterableFor(listRef, key.value()); let iterator = new _reference.ReferenceIterator(iterable); stack.push(iterator); stack.push(new IterablePresenceReference(iterator.artifacts)); }); APPEND_OPCODES.add(64 /* EnterList */, (vm, { op1: relativeStart }) => { vm.enterList(relativeStart); }); APPEND_OPCODES.add(65 /* ExitList */, vm => { vm.exitList(); }); APPEND_OPCODES.add(67 /* Iterate */, (vm, { op1: breaks }) => { let stack = vm.stack; let item = stack.peek().next(); if (item) { let tryOpcode = vm.iterate(item.memo, item.value); vm.enterItem(item.key, tryOpcode); } else { vm.goto(breaks); } }); class Cursor { constructor(element, nextSibling) { this.element = element; this.nextSibling = nextSibling; } } class ConcreteBounds { constructor(parentNode, first, last) { this.parentNode = parentNode; this.first = first; this.last = last; } parentElement() { return this.parentNode; } firstNode() { return this.first; } lastNode() { return this.last; } } class SingleNodeBounds { constructor(parentNode, node) { this.parentNode = parentNode; this.node = node; } parentElement() { return this.parentNode; } firstNode() { return this.node; } lastNode() { return this.node; } } function bounds(parent, first, last) { return new ConcreteBounds(parent, first, last); } function single(parent, node) { return new SingleNodeBounds(parent, node); } function move(bounds, reference) { let parent = bounds.parentElement(); let first = bounds.firstNode(); let last = bounds.lastNode(); let node = first; while (node) { let next = node.nextSibling; parent.insertBefore(node, reference); if (node === last) return next; node = next; } return null; } function clear(bounds) { let parent = bounds.parentElement(); let first = bounds.firstNode(); let last = bounds.lastNode(); let node = first; while (node) { let next = node.nextSibling; parent.removeChild(node); if (node === last) return next; node = next; } return null; } const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; // Patch: insertAdjacentHTML on SVG Fix // Browsers: Safari, IE, Edge, Firefox ~33-34 // Reason: insertAdjacentHTML does not exist on SVG elements in Safari. It is // present but throws an exception on IE and Edge. Old versions of // Firefox create nodes in the incorrect namespace. // Fix: Since IE and Edge silently fail to create SVG nodes using // innerHTML, and because Firefox may create nodes in the incorrect // namespace using innerHTML on SVG elements, an HTML-string wrapping // approach is used. A pre/post SVG tag is added to the string, then // that whole string is added to a div. The created nodes are plucked // out and applied to the target location on DOM. function applySVGInnerHTMLFix(document, DOMClass, svgNamespace) { if (!document) return DOMClass; if (!shouldApplyFix(document, svgNamespace)) { return DOMClass; } let div = document.createElement('div'); return class DOMChangesWithSVGInnerHTMLFix extends DOMClass { insertHTMLBefore(parent, nextSibling, html) { if (parent.namespaceURI !== svgNamespace) { return super.insertHTMLBefore(parent, nextSibling, html); } return fixSVG(parent, div, html, nextSibling); } }; } function fixSVG(parent, div, html, reference) { let source; // This is important, because decendants of the integration // point are parsed in the HTML namespace if (parent.tagName.toUpperCase() === 'FOREIGNOBJECT') { // IE, Edge: also do not correctly support using `innerHTML` on SVG // namespaced elements. So here a wrapper is used. let wrappedHtml = '' + (html || '') + ''; div.innerHTML = wrappedHtml; source = div.firstChild.firstChild; } else { // IE, Edge: also do not correctly support using `innerHTML` on SVG // namespaced elements. So here a wrapper is used. let wrappedHtml = '' + (html || '') + ''; div.innerHTML = wrappedHtml; source = div.firstChild; } let [first, last] = moveNodesBefore(source, parent, reference); return new ConcreteBounds(parent, first, last); } function shouldApplyFix(document, svgNamespace) { let svg = document.createElementNS(svgNamespace, 'svg'); try { svg['insertAdjacentHTML']('beforeend', ''); } catch (e) { // IE, Edge: Will throw, insertAdjacentHTML is unsupported on SVG // Safari: Will throw, insertAdjacentHTML is not present on SVG } finally { // FF: Old versions will create a node in the wrong namespace if (svg.childNodes.length === 1 && svg.firstChild.namespaceURI === SVG_NAMESPACE) { // The test worked as expected, no fix required return false; } return true; } } // Patch: Adjacent text node merging fix // Browsers: IE, Edge, Firefox w/o inspector open // Reason: These browsers will merge adjacent text nodes. For exmaple given //
Hello
with div.insertAdjacentHTML(' world') browsers // with proper behavior will populate div.childNodes with two items. // These browsers will populate it with one merged node instead. // Fix: Add these nodes to a wrapper element, then iterate the childNodes // of that wrapper and move the nodes to their target location. Note // that potential SVG bugs will have been handled before this fix. // Note that this fix must only apply to the previous text node, as // the base implementation of `insertHTMLBefore` already handles // following text nodes correctly. function applyTextNodeMergingFix(document, DOMClass) { if (!document) return DOMClass; if (!shouldApplyFix$1(document)) { return DOMClass; } return class DOMChangesWithTextNodeMergingFix extends DOMClass { constructor(document) { super(document); this.uselessComment = document.createComment(''); } insertHTMLBefore(parent, nextSibling, html) { let didSetUselessComment = false; let nextPrevious = nextSibling ? nextSibling.previousSibling : parent.lastChild; if (nextPrevious && nextPrevious instanceof Text) { didSetUselessComment = true; parent.insertBefore(this.uselessComment, nextSibling); } let bounds = super.insertHTMLBefore(parent, nextSibling, html); if (didSetUselessComment) { parent.removeChild(this.uselessComment); } return bounds; } }; } function shouldApplyFix$1(document) { let mergingTextDiv = document.createElement('div'); mergingTextDiv.innerHTML = 'first'; mergingTextDiv.insertAdjacentHTML('beforeend', 'second'); if (mergingTextDiv.childNodes.length === 2) { // It worked as expected, no fix required return false; } return true; } const SVG_NAMESPACE$1 = 'http://www.w3.org/2000/svg'; // http://www.w3.org/TR/html/syntax.html#html-integration-point const SVG_INTEGRATION_POINTS = { foreignObject: 1, desc: 1, title: 1 }; // http://www.w3.org/TR/html/syntax.html#adjust-svg-attributes // TODO: Adjust SVG attributes // http://www.w3.org/TR/html/syntax.html#parsing-main-inforeign // TODO: Adjust SVG elements // http://www.w3.org/TR/html/syntax.html#parsing-main-inforeign const BLACKLIST_TABLE = Object.create(null); ['b', 'big', 'blockquote', 'body', 'br', 'center', 'code', 'dd', 'div', 'dl', 'dt', 'em', 'embed', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'i', 'img', 'li', 'listing', 'main', 'meta', 'nobr', 'ol', 'p', 'pre', 'ruby', 's', 'small', 'span', 'strong', 'strike', 'sub', 'sup', 'table', 'tt', 'u', 'ul', 'var'].forEach(tag => BLACKLIST_TABLE[tag] = 1); const WHITESPACE = /[\t-\r \xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]/; let doc = typeof document === 'undefined' ? null : document; function isWhitespace(string) { return WHITESPACE.test(string); } function moveNodesBefore(source, target, nextSibling) { let first = source.firstChild; let last = null; let current = first; while (current) { last = current; current = current.nextSibling; target.insertBefore(last, nextSibling); } return [first, last]; } class DOMOperations { constructor(document) { this.document = document; this.setupUselessElement(); } // split into seperate method so that NodeDOMTreeConstruction // can override it. setupUselessElement() { this.uselessElement = this.document.createElement('div'); } createElement(tag, context) { let isElementInSVGNamespace, isHTMLIntegrationPoint; if (context) { isElementInSVGNamespace = context.namespaceURI === SVG_NAMESPACE$1 || tag === 'svg'; isHTMLIntegrationPoint = SVG_INTEGRATION_POINTS[context.tagName]; } else { isElementInSVGNamespace = tag === 'svg'; isHTMLIntegrationPoint = false; } if (isElementInSVGNamespace && !isHTMLIntegrationPoint) { // FIXME: This does not properly handle with color, face, or // size attributes, which is also disallowed by the spec. We should fix // this. if (BLACKLIST_TABLE[tag]) { throw new Error(`Cannot create a ${tag} inside an SVG context`); } return this.document.createElementNS(SVG_NAMESPACE$1, tag); } else { return this.document.createElement(tag); } } insertBefore(parent, node, reference) { parent.insertBefore(node, reference); } insertHTMLBefore(_parent, nextSibling, html) { return insertHTMLBefore(this.uselessElement, _parent, nextSibling, html); } createTextNode(text) { return this.document.createTextNode(text); } createComment(data) { return this.document.createComment(data); } } var DOM; (function (DOM) { class TreeConstruction extends DOMOperations { createElementNS(namespace, tag) { return this.document.createElementNS(namespace, tag); } setAttribute(element, name, value, namespace = null) { if (namespace) { element.setAttributeNS(namespace, name, value); } else { element.setAttribute(name, value); } } } DOM.TreeConstruction = TreeConstruction; let appliedTreeContruction = TreeConstruction; appliedTreeContruction = applyTextNodeMergingFix(doc, appliedTreeContruction); appliedTreeContruction = applySVGInnerHTMLFix(doc, appliedTreeContruction, SVG_NAMESPACE$1); DOM.DOMTreeConstruction = appliedTreeContruction; })(DOM || (DOM = {})); class DOMChanges extends DOMOperations { constructor(document) { super(document); this.document = document; this.namespace = null; } setAttribute(element, name, value) { element.setAttribute(name, value); } removeAttribute(element, name) { element.removeAttribute(name); } insertAfter(element, node, reference) { this.insertBefore(element, node, reference.nextSibling); } } function insertHTMLBefore(useless, _parent, _nextSibling, _html) { let parent = _parent; let nextSibling = _nextSibling; let prev = nextSibling ? nextSibling.previousSibling : parent.lastChild; let last; let html = _html || ''; if (nextSibling === null) { parent.insertAdjacentHTML('beforeend', html); last = parent.lastChild; } else if (nextSibling instanceof HTMLElement) { nextSibling.insertAdjacentHTML('beforebegin', html); last = nextSibling.previousSibling; } else { // Non-element nodes do not support insertAdjacentHTML, so add an // element and call it on that element. Then remove the element. // // This also protects Edge, IE and Firefox w/o the inspector open // from merging adjacent text nodes. See ./compat/text-node-merging-fix.ts parent.insertBefore(useless, nextSibling); useless.insertAdjacentHTML('beforebegin', html); last = useless.previousSibling; parent.removeChild(useless); } let first = prev ? prev.nextSibling : parent.firstChild; return new ConcreteBounds(parent, first, last); } let helper = DOMChanges; helper = applyTextNodeMergingFix(doc, helper); helper = applySVGInnerHTMLFix(doc, helper, SVG_NAMESPACE$1); var helper$1 = helper; const DOMTreeConstruction = DOM.DOMTreeConstruction; const badProtocols = ['javascript:', 'vbscript:']; const badTags = ['A', 'BODY', 'LINK', 'IMG', 'IFRAME', 'BASE', 'FORM']; const badTagsForDataURI = ['EMBED']; const badAttributes = ['href', 'src', 'background', 'action']; const badAttributesForDataURI = ['src']; function has(array, item) { return array.indexOf(item) !== -1; } function checkURI(tagName, attribute) { return (tagName === null || has(badTags, tagName)) && has(badAttributes, attribute); } function checkDataURI(tagName, attribute) { if (tagName === null) return false; return has(badTagsForDataURI, tagName) && has(badAttributesForDataURI, attribute); } function requiresSanitization(tagName, attribute) { return checkURI(tagName, attribute) || checkDataURI(tagName, attribute); } function sanitizeAttributeValue(env, element, attribute, value) { let tagName = null; if (value === null || value === undefined) { return value; } if (isSafeString(value)) { return value.toHTML(); } if (!element) { tagName = null; } else { tagName = element.tagName.toUpperCase(); } let str = normalizeStringValue(value); if (checkURI(tagName, attribute)) { let protocol = env.protocolForURL(str); if (has(badProtocols, protocol)) { return `unsafe:${str}`; } } if (checkDataURI(tagName, attribute)) { return `unsafe:${str}`; } return str; } /* * @method normalizeProperty * @param element {HTMLElement} * @param slotName {String} * @returns {Object} { name, type } */ function normalizeProperty(element, slotName) { let type, normalized; if (slotName in element) { normalized = slotName; type = 'prop'; } else { let 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, type }; } // properties that MUST be set as attributes, due to: // * browser bug // * strange spec outlier const ATTR_OVERRIDES = { INPUT: { 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, // Chrome 54.0.2840.98: 'list' in document.createElement('input') === true // Safari 9.1.3: 'list' in document.createElement('input') === false list: 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 }, BUTTON: { form: true } }; function preferAttr(tagName, propName) { let tag = ATTR_OVERRIDES[tagName.toUpperCase()]; return tag && tag[propName.toLowerCase()] || false; } function dynamicAttribute(element, attr, namespace) { let { tagName, namespaceURI } = element; let attribute = { element, name: attr, namespace }; if (namespaceURI === SVG_NAMESPACE$1) { return buildDynamicAttribute(tagName, attr, attribute); } let { type, normalized } = normalizeProperty(element, attr); if (type === 'attr') { return buildDynamicAttribute(tagName, normalized, attribute); } else { return buildDynamicProperty(tagName, normalized, attribute); } } function buildDynamicAttribute(tagName, name, attribute) { if (requiresSanitization(tagName, name)) { return new SafeDynamicAttribute(attribute); } else { return new SimpleDynamicAttribute(attribute); } } function buildDynamicProperty(tagName, name, attribute) { if (requiresSanitization(tagName, name)) { return new SafeDynamicProperty(name, attribute); } if (isUserInputValue(tagName, name)) { return new InputValueDynamicAttribute(name, attribute); } if (isOptionSelected(tagName, name)) { return new OptionSelectedDynamicAttribute(name, attribute); } return new DefaultDynamicProperty(name, attribute); } class DynamicAttribute { constructor(attribute) { this.attribute = attribute; } } class SimpleDynamicAttribute extends DynamicAttribute { set(dom, value, _env) { let normalizedValue = normalizeValue(value); if (normalizedValue !== null) { let { name, namespace } = this.attribute; dom.__setAttribute(name, normalizedValue, namespace); } } update(value, _env) { let normalizedValue = normalizeValue(value); let { element, name } = this.attribute; if (normalizedValue === null) { element.removeAttribute(name); } else { element.setAttribute(name, normalizedValue); } } } class DefaultDynamicProperty extends DynamicAttribute { constructor(normalizedName, attribute) { super(attribute); this.normalizedName = normalizedName; } set(dom, value, _env) { if (value !== null && value !== undefined) { this.value = value; dom.__setProperty(this.normalizedName, value); } } update(value, _env) { let { element } = this.attribute; if (this.value !== value) { element[this.normalizedName] = this.value = value; if (value === null || value === undefined) { this.removeAttribute(); } } } removeAttribute() { // TODO this sucks but to preserve properties first and to meet current // semantics we must do this. let { element, namespace } = this.attribute; if (namespace) { element.removeAttributeNS(namespace, this.normalizedName); } else { element.removeAttribute(this.normalizedName); } } } class SafeDynamicProperty extends DefaultDynamicProperty { set(dom, value, env) { let { element, name } = this.attribute; let sanitized = sanitizeAttributeValue(env, element, name, value); super.set(dom, sanitized, env); } update(value, env) { let { element, name } = this.attribute; let sanitized = sanitizeAttributeValue(env, element, name, value); super.update(sanitized, env); } } class SafeDynamicAttribute extends SimpleDynamicAttribute { set(dom, value, env) { let { element, name } = this.attribute; let sanitized = sanitizeAttributeValue(env, element, name, value); super.set(dom, sanitized, env); } update(value, env) { let { element, name } = this.attribute; let sanitized = sanitizeAttributeValue(env, element, name, value); super.update(sanitized, env); } } class InputValueDynamicAttribute extends DefaultDynamicProperty { set(dom, value) { dom.__setProperty('value', normalizeStringValue(value)); } update(value) { let input = this.attribute.element; let currentValue = input.value; let normalizedValue = normalizeStringValue(value); if (currentValue !== normalizedValue) { input.value = normalizedValue; } } } class OptionSelectedDynamicAttribute extends DefaultDynamicProperty { set(dom, value) { if (value !== null && value !== undefined && value !== false) { dom.__setProperty('selected', true); } } update(value) { let option = this.attribute.element; if (value) { option.selected = true; } else { option.selected = false; } } } function isOptionSelected(tagName, attribute) { return tagName === 'OPTION' && attribute === 'selected'; } function isUserInputValue(tagName, attribute) { return (tagName === 'INPUT' || tagName === 'TEXTAREA') && attribute === 'value'; } function normalizeValue(value) { if (value === false || value === undefined || value === null || typeof value.toString === 'undefined') { return null; } if (value === true) { return ''; } // onclick function etc in SSR if (typeof value === 'function') { return null; } return String(value); } class Scope { constructor( // the 0th slot is `self` slots, callerScope, // named arguments and blocks passed to a layout that uses eval evalScope, // locals in scope when the partial was invoked partialMap) { this.slots = slots; this.callerScope = callerScope; this.evalScope = evalScope; this.partialMap = partialMap; } static root(self, size = 0) { let refs = new Array(size + 1); for (let i = 0; i <= size; i++) { refs[i] = UNDEFINED_REFERENCE; } return new Scope(refs, null, null, null).init({ self }); } static sized(size = 0) { let refs = new Array(size + 1); for (let i = 0; i <= size; i++) { refs[i] = UNDEFINED_REFERENCE; } return new Scope(refs, null, null, null); } init({ self }) { this.slots[0] = self; return this; } getSelf() { return this.get(0); } getSymbol(symbol) { return this.get(symbol); } getBlock(symbol) { let block = this.get(symbol); return block === UNDEFINED_REFERENCE ? null : block; } getEvalScope() { return this.evalScope; } getPartialMap() { return this.partialMap; } bind(symbol, value) { this.set(symbol, value); } bindSelf(self) { this.set(0, self); } bindSymbol(symbol, value) { this.set(symbol, value); } bindBlock(symbol, value) { this.set(symbol, value); } bindEvalScope(map) { this.evalScope = map; } bindPartialMap(map) { this.partialMap = map; } bindCallerScope(scope) { this.callerScope = scope; } getCallerScope() { return this.callerScope; } child() { return new Scope(this.slots.slice(), this.callerScope, this.evalScope, this.partialMap); } get(index) { if (index >= this.slots.length) { throw new RangeError(`BUG: cannot get $${index} from scope; length=${this.slots.length}`); } return this.slots[index]; } set(index, value) { if (index >= this.slots.length) { throw new RangeError(`BUG: cannot get $${index} from scope; length=${this.slots.length}`); } this.slots[index] = value; } } class Transaction { constructor() { this.scheduledInstallManagers = []; this.scheduledInstallModifiers = []; this.scheduledUpdateModifierManagers = []; this.scheduledUpdateModifiers = []; this.createdComponents = []; this.createdManagers = []; this.updatedComponents = []; this.updatedManagers = []; this.destructors = []; } didCreate(component, manager) { this.createdComponents.push(component); this.createdManagers.push(manager); } didUpdate(component, manager) { this.updatedComponents.push(component); this.updatedManagers.push(manager); } scheduleInstallModifier(modifier, manager) { this.scheduledInstallManagers.push(manager); this.scheduledInstallModifiers.push(modifier); } scheduleUpdateModifier(modifier, manager) { this.scheduledUpdateModifierManagers.push(manager); this.scheduledUpdateModifiers.push(modifier); } didDestroy(d) { this.destructors.push(d); } commit() { let { createdComponents, createdManagers } = this; for (let i = 0; i < createdComponents.length; i++) { let component = createdComponents[i]; let manager = createdManagers[i]; manager.didCreate(component); } let { updatedComponents, updatedManagers } = this; for (let i = 0; i < updatedComponents.length; i++) { let component = updatedComponents[i]; let manager = updatedManagers[i]; manager.didUpdate(component); } let { destructors } = this; for (let i = 0; i < destructors.length; i++) { destructors[i].destroy(); } let { scheduledInstallManagers, scheduledInstallModifiers } = this; for (let i = 0; i < scheduledInstallManagers.length; i++) { let manager = scheduledInstallManagers[i]; let modifier = scheduledInstallModifiers[i]; manager.install(modifier); } let { scheduledUpdateModifierManagers, scheduledUpdateModifiers } = this; for (let i = 0; i < scheduledUpdateModifierManagers.length; i++) { let manager = scheduledUpdateModifierManagers[i]; let modifier = scheduledUpdateModifiers[i]; manager.update(modifier); } } } class Environment { constructor({ appendOperations, updateOperations }) { this._transaction = null; this.appendOperations = appendOperations; this.updateOperations = updateOperations; } toConditionalReference(reference) { return new ConditionalReference(reference); } getAppendOperations() { return this.appendOperations; } getDOM() { return this.updateOperations; } begin() { this._transaction = new Transaction(); } get transaction() { return this._transaction; } didCreate(component, manager) { this.transaction.didCreate(component, manager); } didUpdate(component, manager) { this.transaction.didUpdate(component, manager); } scheduleInstallModifier(modifier, manager) { this.transaction.scheduleInstallModifier(modifier, manager); } scheduleUpdateModifier(modifier, manager) { this.transaction.scheduleUpdateModifier(modifier, manager); } didDestroy(d) { this.transaction.didDestroy(d); } commit() { let transaction = this.transaction; this._transaction = null; transaction.commit(); } attributeFor(element, attr, _isTrusting, namespace = null) { return dynamicAttribute(element, attr, namespace); } } class DefaultEnvironment extends Environment { constructor(options) { if (!options) { let document = window.document; let appendOperations = new DOMTreeConstruction(document); let updateOperations = new DOMChanges(document); options = { appendOperations, updateOperations }; } super(options); } } class LowLevelVM { constructor(stack, heap, program, externs, pc = -1, ra = -1) { this.stack = stack; this.heap = heap; this.program = program; this.externs = externs; this.pc = pc; this.ra = ra; this.currentOpSize = 0; } // Start a new frame and save $ra and $fp on the stack pushFrame() { this.stack.pushSmi(this.ra); this.stack.pushSmi(this.stack.fp); this.stack.fp = this.stack.sp - 1; } // Restore $ra, $sp and $fp popFrame() { this.stack.sp = this.stack.fp - 1; this.ra = this.stack.getSmi(0); this.stack.fp = this.stack.getSmi(1); } pushSmallFrame() { this.stack.pushSmi(this.ra); } popSmallFrame() { this.ra = this.stack.popSmi(); } // Jump to an address in `program` goto(offset) { let addr = this.pc + offset - this.currentOpSize; this.pc = addr; } // Save $pc into $ra, then jump to a new address in `program` (jal in MIPS) call(handle) { this.ra = this.pc; this.pc = this.heap.getaddr(handle); } // Put a specific `program` address in $ra returnTo(offset) { let addr = this.pc + offset - this.currentOpSize; this.ra = addr; } // Return to the `program` address stored in $ra return() { this.pc = this.ra; } nextStatement() { let { pc, program } = this; if (pc === -1) { return null; } // We have to save off the current operations size so that // when we do a jump we can calculate the correct offset // to where we are going. We can't simply ask for the size // in a jump because we have have already incremented the // program counter to the next instruction prior to executing. let { size } = this.program.opcode(pc); let operationSize = this.currentOpSize = size; this.pc += operationSize; return program.opcode(pc); } evaluateOuter(opcode, vm) { { this.evaluateInner(opcode, vm); } } evaluateInner(opcode, vm) { if (opcode.isMachine) { this.evaluateMachine(opcode); } else { this.evaluateSyscall(opcode, vm); } } evaluateMachine(opcode) { switch (opcode.type) { case 57 /* PushFrame */: return this.pushFrame(); case 58 /* PopFrame */: return this.popFrame(); case 59 /* PushSmallFrame */: return this.pushSmallFrame(); case 60 /* PopSmallFrame */: return this.popSmallFrame(); case 50 /* InvokeStatic */: return this.call(opcode.op1); case 49 /* InvokeVirtual */: return this.call(this.stack.popSmi()); case 52 /* Jump */: return this.goto(opcode.op1); case 24 /* Return */: return this.return(); case 25 /* ReturnTo */: return this.returnTo(opcode.op1); } } evaluateSyscall(opcode, vm) { APPEND_OPCODES.evaluate(vm, opcode, opcode.type); } } class First { constructor(node) { this.node = node; } firstNode() { return this.node; } } class Last { constructor(node) { this.node = node; } lastNode() { return this.node; } } class NewElementBuilder { constructor(env, parentNode, nextSibling) { this.constructing = null; this.operations = null; this.cursorStack = new _util.Stack(); this.blockStack = new _util.Stack(); this.pushElement(parentNode, nextSibling); this.env = env; this.dom = env.getAppendOperations(); this.updateOperations = env.getDOM(); } static forInitialRender(env, cursor) { let builder = new this(env, cursor.element, cursor.nextSibling); builder.pushSimpleBlock(); return builder; } static resume(env, tracker, nextSibling) { let parentNode = tracker.parentElement(); let stack = new this(env, parentNode, nextSibling); stack.pushSimpleBlock(); stack.pushBlockTracker(tracker); return stack; } get element() { return this.cursorStack.current.element; } get nextSibling() { return this.cursorStack.current.nextSibling; } expectConstructing(method) { return this.constructing; } block() { return this.blockStack.current; } popElement() { this.cursorStack.pop(); this.cursorStack.current; } pushSimpleBlock() { return this.pushBlockTracker(new SimpleBlockTracker(this.element)); } pushUpdatableBlock() { return this.pushBlockTracker(new UpdatableBlockTracker(this.element)); } pushBlockList(list) { return this.pushBlockTracker(new BlockListTracker(this.element, list)); } pushBlockTracker(tracker, isRemote = false) { let current = this.blockStack.current; if (current !== null) { current.newDestroyable(tracker); if (!isRemote) { current.didAppendBounds(tracker); } } this.__openBlock(); this.blockStack.push(tracker); return tracker; } popBlock() { this.block().finalize(this); this.__closeBlock(); return this.blockStack.pop(); } __openBlock() {} __closeBlock() {} // todo return seems unused openElement(tag) { let element = this.__openElement(tag); this.constructing = element; return element; } __openElement(tag) { return this.dom.createElement(tag, this.element); } flushElement() { let parent = this.element; let element = this.constructing; this.__flushElement(parent, element); this.constructing = null; this.operations = null; this.pushElement(element, null); this.didOpenElement(element); } __flushElement(parent, constructing) { this.dom.insertBefore(parent, constructing, this.nextSibling); } closeElement() { this.willCloseElement(); this.popElement(); } pushRemoteElement(element, guid, nextSibling = null) { this.__pushRemoteElement(element, guid, nextSibling); } __pushRemoteElement(element, _guid, nextSibling) { this.pushElement(element, nextSibling); let tracker = new RemoteBlockTracker(element); this.pushBlockTracker(tracker, true); } popRemoteElement() { this.popBlock(); this.popElement(); } pushElement(element, nextSibling) { this.cursorStack.push(new Cursor(element, nextSibling)); } didAddDestroyable(d) { this.block().newDestroyable(d); } didAppendBounds(bounds$$1) { this.block().didAppendBounds(bounds$$1); return bounds$$1; } didAppendNode(node) { this.block().didAppendNode(node); return node; } didOpenElement(element) { this.block().openElement(element); return element; } willCloseElement() { this.block().closeElement(); } appendText(string) { return this.didAppendNode(this.__appendText(string)); } __appendText(text) { let { dom, element, nextSibling } = this; let node = dom.createTextNode(text); dom.insertBefore(element, node, nextSibling); return node; } __appendNode(node) { this.dom.insertBefore(this.element, node, this.nextSibling); return node; } __appendFragment(fragment) { let first = fragment.firstChild; if (first) { let ret = bounds(this.element, first, fragment.lastChild); this.dom.insertBefore(this.element, fragment, this.nextSibling); return ret; } else { return single(this.element, this.__appendComment('')); } } __appendHTML(html) { return this.dom.insertHTMLBefore(this.element, this.nextSibling, html); } appendDynamicHTML(value) { let bounds$$1 = this.trustedContent(value); this.didAppendBounds(bounds$$1); } appendDynamicText(value) { let node = this.untrustedContent(value); this.didAppendNode(node); return node; } appendDynamicFragment(value) { let bounds$$1 = this.__appendFragment(value); this.didAppendBounds(bounds$$1); } appendDynamicNode(value) { let node = this.__appendNode(value); let bounds$$1 = single(this.element, node); this.didAppendBounds(bounds$$1); } trustedContent(value) { return this.__appendHTML(value); } untrustedContent(value) { return this.__appendText(value); } appendComment(string) { return this.didAppendNode(this.__appendComment(string)); } __appendComment(string) { let { dom, element, nextSibling } = this; let node = dom.createComment(string); dom.insertBefore(element, node, nextSibling); return node; } __setAttribute(name, value, namespace) { this.dom.setAttribute(this.constructing, name, value, namespace); } __setProperty(name, value) { this.constructing[name] = value; } setStaticAttribute(name, value, namespace) { this.__setAttribute(name, value, namespace); } setDynamicAttribute(name, value, trusting, namespace) { let element = this.constructing; let attribute = this.env.attributeFor(element, name, trusting, namespace); attribute.set(this, value, this.env); return attribute; } } class SimpleBlockTracker { constructor(parent) { this.parent = parent; this.first = null; this.last = null; this.destroyables = null; this.nesting = 0; } destroy() { let { destroyables } = this; if (destroyables && destroyables.length) { for (let i = 0; i < destroyables.length; i++) { destroyables[i].destroy(); } } } parentElement() { return this.parent; } firstNode() { return this.first && this.first.firstNode(); } lastNode() { return this.last && this.last.lastNode(); } openElement(element) { this.didAppendNode(element); this.nesting++; } closeElement() { this.nesting--; } didAppendNode(node) { if (this.nesting !== 0) return; if (!this.first) { this.first = new First(node); } this.last = new Last(node); } didAppendBounds(bounds$$1) { if (this.nesting !== 0) return; if (!this.first) { this.first = bounds$$1; } this.last = bounds$$1; } newDestroyable(d) { this.destroyables = this.destroyables || []; this.destroyables.push(d); } finalize(stack) { if (this.first === null) { stack.appendComment(''); } } } class RemoteBlockTracker extends SimpleBlockTracker { destroy() { super.destroy(); clear(this); } } class UpdatableBlockTracker extends SimpleBlockTracker { reset(env) { let { destroyables } = this; if (destroyables && destroyables.length) { for (let i = 0; i < destroyables.length; i++) { env.didDestroy(destroyables[i]); } } let nextSibling = clear(this); this.first = null; this.last = null; this.destroyables = null; this.nesting = 0; return nextSibling; } } class BlockListTracker { constructor(parent, boundList) { this.parent = parent; this.boundList = boundList; this.parent = parent; this.boundList = boundList; } destroy() { this.boundList.forEachNode(node => node.destroy()); } parentElement() { return this.parent; } firstNode() { let head = this.boundList.head(); return head && head.firstNode(); } lastNode() { let tail = this.boundList.tail(); return tail && tail.lastNode(); } openElement(_element) {} closeElement() {} didAppendNode(_node) {} didAppendBounds(_bounds) {} newDestroyable(_d) {} finalize(_stack) {} } function clientBuilder(env, cursor) { return NewElementBuilder.forInitialRender(env, cursor); } const HI = 0x80000000; const MASK = 0x7fffffff; class InnerStack { constructor(inner = new _lowLevel.Stack(), js = []) { this.inner = inner; this.js = js; } slice(start, end) { let inner; if (typeof start === 'number' && typeof end === 'number') { inner = this.inner.slice(start, end); } else if (typeof start === 'number' && end === undefined) { inner = this.inner.sliceFrom(start); } else { inner = this.inner.clone(); } return new InnerStack(inner, this.js.slice(start, end)); } sliceInner(start, end) { let out = []; for (let i = start; i < end; i++) { out.push(this.get(i)); } return out; } copy(from, to) { this.inner.copy(from, to); } write(pos, value) { if (isImmediate(value)) { this.inner.writeRaw(pos, encodeImmediate(value)); } else { let idx = this.js.length; this.js.push(value); this.inner.writeRaw(pos, idx | HI); } } writeSmi(pos, value) { this.inner.writeSmi(pos, value); } writeImmediate(pos, value) { this.inner.writeRaw(pos, value); } get(pos) { let value = this.inner.getRaw(pos); if (value & HI) { return this.js[value & MASK]; } else { return decodeImmediate(value); } } getSmi(pos) { return this.inner.getSmi(pos); } reset() { this.inner.reset(); this.js.length = 0; } get length() { return this.inner.len(); } } class EvaluationStack { constructor(stack, fp, sp) { this.stack = stack; this.fp = fp; this.sp = sp; } static empty() { return new this(new InnerStack(), 0, -1); } static restore(snapshot) { let stack = new InnerStack(); for (let i = 0; i < snapshot.length; i++) { stack.write(i, snapshot[i]); } return new this(stack, 0, snapshot.length - 1); } push(value) { this.stack.write(++this.sp, value); } pushSmi(value) { this.stack.writeSmi(++this.sp, value); } pushImmediate(value) { this.stack.writeImmediate(++this.sp, encodeImmediate(value)); } pushEncodedImmediate(value) { this.stack.writeImmediate(++this.sp, value); } pushNull() { this.stack.writeImmediate(++this.sp, 19 /* Null */); } dup(position = this.sp) { this.stack.copy(position, ++this.sp); } copy(from, to) { this.stack.copy(from, to); } pop(n = 1) { let top = this.stack.get(this.sp); this.sp -= n; return top; } popSmi() { return this.stack.getSmi(this.sp--); } peek(offset = 0) { return this.stack.get(this.sp - offset); } peekSmi(offset = 0) { return this.stack.getSmi(this.sp - offset); } get(offset, base = this.fp) { return this.stack.get(base + offset); } getSmi(offset, base = this.fp) { return this.stack.getSmi(base + offset); } set(value, offset, base = this.fp) { this.stack.write(base + offset, value); } slice(start, end) { return this.stack.slice(start, end); } sliceArray(start, end) { return this.stack.sliceInner(start, end); } capture(items) { let end = this.sp + 1; let start = end - items; return this.stack.sliceInner(start, end); } reset() { this.stack.reset(); } toArray() { return this.stack.sliceInner(this.fp, this.sp + 1); } } function isImmediate(value) { let type = typeof value; if (value === null || value === undefined) return true; switch (type) { case 'boolean': case 'undefined': return true; case 'number': // not an integer if (value % 1 !== 0) return false; let abs = Math.abs(value); // too big if (abs > HI) return false; return true; default: return false; } } function encodeSmi(primitive) { if (primitive < 0) { return Math.abs(primitive) << 3 | 4 /* NEGATIVE */; } else { return primitive << 3 | 0 /* NUMBER */; } } function encodeImmediate(primitive) { switch (typeof primitive) { case 'number': return encodeSmi(primitive); case 'boolean': return primitive ? 11 /* True */ : 3 /* False */; case 'object': // assume null return 19 /* Null */; case 'undefined': return 27 /* Undef */; default: throw (0, _util.unreachable)(); } } function decodeSmi(smi) { switch (smi & 0b111) { case 0 /* NUMBER */: return smi >> 3; case 4 /* NEGATIVE */: return -(smi >> 3); default: throw (0, _util.unreachable)(); } } function decodeImmediate(immediate) { switch (immediate) { case 3 /* False */: return false; case 11 /* True */: return true; case 19 /* Null */: return null; case 27 /* Undef */: return undefined; default: return decodeSmi(immediate); } } class UpdatingVM { constructor(env, program, { alwaysRevalidate = false }) { this.frameStack = new _util.Stack(); this.env = env; this.constants = program.constants; this.dom = env.getDOM(); this.alwaysRevalidate = alwaysRevalidate; } execute(opcodes, handler) { let { frameStack } = this; this.try(opcodes, handler); while (true) { if (frameStack.isEmpty()) break; let opcode = this.frame.nextStatement(); if (opcode === null) { this.frameStack.pop(); continue; } opcode.evaluate(this); } } get frame() { return this.frameStack.current; } goto(op) { this.frame.goto(op); } try(ops, handler) { this.frameStack.push(new UpdatingVMFrame(ops, handler)); } throw() { this.frame.handleException(); this.frameStack.pop(); } } class BlockOpcode extends UpdatingOpcode { constructor(start, state, runtime, bounds$$1, children) { super(); this.start = start; this.state = state; this.runtime = runtime; this.type = 'block'; this.next = null; this.prev = null; this.children = children; this.bounds = bounds$$1; } parentElement() { return this.bounds.parentElement(); } firstNode() { return this.bounds.firstNode(); } lastNode() { return this.bounds.lastNode(); } evaluate(vm) { vm.try(this.children, null); } destroy() { this.bounds.destroy(); } didDestroy() { this.runtime.env.didDestroy(this.bounds); } } class TryOpcode extends BlockOpcode { constructor(start, state, runtime, bounds$$1, children) { super(start, state, runtime, bounds$$1, children); this.type = 'try'; this.tag = this._tag = _reference.UpdatableTag.create(_reference.CONSTANT_TAG); } didInitializeChildren() { this._tag.inner.update((0, _reference.combineSlice)(this.children)); } evaluate(vm) { vm.try(this.children, this); } handleException() { let { state, bounds: bounds$$1, children, start, prev, next, runtime } = this; children.clear(); let elementStack = NewElementBuilder.resume(runtime.env, bounds$$1, bounds$$1.reset(runtime.env)); let vm = VM.resume(state, runtime, elementStack); let updating = new _util.LinkedList(); vm.execute(start, vm => { vm.stack = EvaluationStack.restore(state.stack); vm.updatingOpcodeStack.push(updating); vm.updateWith(this); vm.updatingOpcodeStack.push(children); }); this.prev = prev; this.next = next; } } class ListRevalidationDelegate { constructor(opcode, marker) { this.opcode = opcode; this.marker = marker; this.didInsert = false; this.didDelete = false; this.map = opcode.map; this.updating = opcode['children']; } insert(key, item, memo, before) { let { map, opcode, updating } = this; let nextSibling = null; let reference = null; if (typeof before === 'string') { reference = map[before]; nextSibling = reference['bounds'].firstNode(); } else { nextSibling = this.marker; } let vm = opcode.vmForInsertion(nextSibling); let tryOpcode = null; let { start } = opcode; vm.execute(start, vm => { map[key] = tryOpcode = vm.iterate(memo, item); vm.updatingOpcodeStack.push(new _util.LinkedList()); vm.updateWith(tryOpcode); vm.updatingOpcodeStack.push(tryOpcode.children); }); updating.insertBefore(tryOpcode, reference); this.didInsert = true; } retain(_key, _item, _memo) {} move(key, _item, _memo, before) { let { map, updating } = this; let entry = map[key]; let reference = map[before] || null; if (typeof before === 'string') { move(entry, reference.firstNode()); } else { move(entry, this.marker); } updating.remove(entry); updating.insertBefore(entry, reference); } delete(key) { let { map } = this; let opcode = map[key]; opcode.didDestroy(); clear(opcode); this.updating.remove(opcode); delete map[key]; this.didDelete = true; } done() { this.opcode.didInitializeChildren(this.didInsert || this.didDelete); } } class ListBlockOpcode extends BlockOpcode { constructor(start, state, runtime, bounds$$1, children, artifacts) { super(start, state, runtime, bounds$$1, children); this.type = 'list-block'; this.map = (0, _util.dict)(); this.lastIterated = _reference.INITIAL; this.artifacts = artifacts; let _tag = this._tag = _reference.UpdatableTag.create(_reference.CONSTANT_TAG); this.tag = (0, _reference.combine)([artifacts.tag, _tag]); } didInitializeChildren(listDidChange = true) { this.lastIterated = this.artifacts.tag.value(); if (listDidChange) { this._tag.inner.update((0, _reference.combineSlice)(this.children)); } } evaluate(vm) { let { artifacts, lastIterated } = this; if (!artifacts.tag.validate(lastIterated)) { let { bounds: bounds$$1 } = this; let { dom } = vm; let marker = dom.createComment(''); dom.insertAfter(bounds$$1.parentElement(), marker, bounds$$1.lastNode()); let target = new ListRevalidationDelegate(this, marker); let synchronizer = new _reference.IteratorSynchronizer({ target, artifacts }); synchronizer.sync(); this.parentElement().removeChild(marker); } // Run now-updated updating opcodes super.evaluate(vm); } vmForInsertion(nextSibling) { let { bounds: bounds$$1, state, runtime } = this; let elementStack = NewElementBuilder.forInitialRender(runtime.env, { element: bounds$$1.parentElement(), nextSibling }); return VM.resume(state, runtime, elementStack); } } class UpdatingVMFrame { constructor(ops, exceptionHandler) { this.ops = ops; this.exceptionHandler = exceptionHandler; this.current = ops.head(); } goto(op) { this.current = op; } nextStatement() { let { current, ops } = this; if (current) this.current = ops.nextNode(current); return current; } handleException() { if (this.exceptionHandler) { this.exceptionHandler.handleException(); } } } class RenderResult { constructor(env, program, updating, bounds$$1) { this.env = env; this.program = program; this.updating = updating; this.bounds = bounds$$1; } rerender({ alwaysRevalidate = false } = { alwaysRevalidate: false }) { let { env, program, updating } = this; let vm = new UpdatingVM(env, program, { alwaysRevalidate }); vm.execute(updating, this); } parentElement() { return this.bounds.parentElement(); } firstNode() { return this.bounds.firstNode(); } lastNode() { return this.bounds.lastNode(); } handleException() { throw 'this should never happen'; } destroy() { this.bounds.destroy(); clear(this.bounds); } } class Arguments { constructor() { this.stack = null; this.positional = new PositionalArguments(); this.named = new NamedArguments(); this.blocks = new BlockArguments(); } empty(stack) { let base = stack.sp + 1; this.named.empty(stack, base); this.positional.empty(stack, base); this.blocks.empty(stack, base); return this; } setup(stack, names, blockNames, positionalCount, synthetic) { this.stack = stack; /* | ... | blocks | positional | named | | ... | b0 b1 | p0 p1 p2 p3 | n0 n1 | index | ... | 4/5/6 7/8/9 | 10 11 12 13 | 14 15 | ^ ^ ^ ^ bbase pbase nbase sp */ let named = this.named; let namedCount = names.length; let namedBase = stack.sp - namedCount + 1; named.setup(stack, namedBase, namedCount, names, synthetic); let positional = this.positional; let positionalBase = namedBase - positionalCount; positional.setup(stack, positionalBase, positionalCount); let blocks = this.blocks; let blocksCount = blockNames.length; let blocksBase = positionalBase - blocksCount * 3; blocks.setup(stack, blocksBase, blocksCount, blockNames); } get tag() { return (0, _reference.combineTagged)([this.positional, this.named]); } get base() { return this.blocks.base; } get length() { return this.positional.length + this.named.length + this.blocks.length * 3; } at(pos) { return this.positional.at(pos); } realloc(offset) { let { stack } = this; if (offset > 0 && stack !== null) { let { positional, named } = this; let newBase = positional.base + offset; let length = positional.length + named.length; for (let i = length - 1; i >= 0; i--) { stack.copy(i + positional.base, i + newBase); } positional.base += offset; named.base += offset; stack.sp += offset; } } capture() { let positional = this.positional.length === 0 ? EMPTY_POSITIONAL : this.positional.capture(); let named = this.named.length === 0 ? EMPTY_NAMED : this.named.capture(); return { tag: this.tag, length: this.length, positional, named }; } clear() { let { stack, length } = this; if (length > 0 && stack !== null) stack.pop(length); } } class PositionalArguments { constructor() { this.base = 0; this.length = 0; this.stack = null; this._tag = null; this._references = null; } empty(stack, base) { this.stack = stack; this.base = base; this.length = 0; this._tag = _reference.CONSTANT_TAG; this._references = _util.EMPTY_ARRAY; } setup(stack, base, length) { this.stack = stack; this.base = base; this.length = length; if (length === 0) { this._tag = _reference.CONSTANT_TAG; this._references = _util.EMPTY_ARRAY; } else { this._tag = null; this._references = null; } } get tag() { let tag = this._tag; if (!tag) { tag = this._tag = (0, _reference.combineTagged)(this.references); } return tag; } at(position) { let { base, length, stack } = this; if (position < 0 || position >= length) { return UNDEFINED_REFERENCE; } return stack.get(position, base); } capture() { return new CapturedPositionalArguments(this.tag, this.references); } prepend(other) { let additions = other.length; if (additions > 0) { let { base, length, stack } = this; this.base = base = base - additions; this.length = length + additions; for (let i = 0; i < additions; i++) { stack.set(other.at(i), i, base); } this._tag = null; this._references = null; } } get references() { let references = this._references; if (!references) { let { stack, base, length } = this; references = this._references = stack.sliceArray(base, base + length); } return references; } } class CapturedPositionalArguments { constructor(tag, references, length = references.length) { this.tag = tag; this.references = references; this.length = length; } static empty() { return new CapturedPositionalArguments(_reference.CONSTANT_TAG, _util.EMPTY_ARRAY, 0); } at(position) { return this.references[position]; } value() { return this.references.map(this.valueOf); } get(name) { let { references, length } = this; if (name === 'length') { return PrimitiveReference.create(length); } else { let idx = parseInt(name, 10); if (idx < 0 || idx >= length) { return UNDEFINED_REFERENCE; } else { return references[idx]; } } } valueOf(reference) { return reference.value(); } } class NamedArguments { constructor() { this.base = 0; this.length = 0; this._references = null; this._names = _util.EMPTY_ARRAY; this._atNames = _util.EMPTY_ARRAY; } empty(stack, base) { this.stack = stack; this.base = base; this.length = 0; this._references = _util.EMPTY_ARRAY; this._names = _util.EMPTY_ARRAY; this._atNames = _util.EMPTY_ARRAY; } setup(stack, base, length, names, synthetic) { this.stack = stack; this.base = base; this.length = length; if (length === 0) { this._references = _util.EMPTY_ARRAY; this._names = _util.EMPTY_ARRAY; this._atNames = _util.EMPTY_ARRAY; } else { this._references = null; if (synthetic) { this._names = names; this._atNames = null; } else { this._names = null; this._atNames = names; } } } get tag() { return (0, _reference.combineTagged)(this.references); } get names() { let names = this._names; if (!names) { names = this._names = this._atNames.map(this.toSyntheticName); } return names; } get atNames() { let atNames = this._atNames; if (!atNames) { atNames = this._atNames = this._names.map(this.toAtName); } return atNames; } has(name) { return this.names.indexOf(name) !== -1; } get(name, synthetic = true) { let { base, stack } = this; let names = synthetic ? this.names : this.atNames; let idx = names.indexOf(name); if (idx === -1) { return UNDEFINED_REFERENCE; } return stack.get(idx, base); } capture() { return new CapturedNamedArguments(this.tag, this.names, this.references); } merge(other) { let { length: extras } = other; if (extras > 0) { let { names, length, stack } = this; let { names: extraNames } = other; if (Object.isFrozen(names) && names.length === 0) { names = []; } for (let i = 0; i < extras; i++) { let name = extraNames[i]; let idx = names.indexOf(name); if (idx === -1) { length = names.push(name); stack.push(other.references[i]); } } this.length = length; this._references = null; this._names = names; this._atNames = null; } } get references() { let references = this._references; if (!references) { let { base, length, stack } = this; references = this._references = stack.sliceArray(base, base + length); } return references; } toSyntheticName(name) { return name.slice(1); } toAtName(name) { return `@${name}`; } } class CapturedNamedArguments { constructor(tag, names, references) { this.tag = tag; this.names = names; this.references = references; this.length = names.length; this._map = null; } get map() { let map = this._map; if (!map) { let { names, references } = this; map = this._map = (0, _util.dict)(); for (let i = 0; i < names.length; i++) { let name = names[i]; map[name] = references[i]; } } return map; } has(name) { return this.names.indexOf(name) !== -1; } get(name) { let { names, references } = this; let idx = names.indexOf(name); if (idx === -1) { return UNDEFINED_REFERENCE; } else { return references[idx]; } } value() { let { names, references } = this; let out = (0, _util.dict)(); for (let i = 0; i < names.length; i++) { let name = names[i]; out[name] = references[i].value(); } return out; } } class BlockArguments { constructor() { this.internalValues = null; this.internalTag = null; this.names = _util.EMPTY_ARRAY; this.length = 0; this.base = 0; } empty(stack, base) { this.stack = stack; this.names = _util.EMPTY_ARRAY; this.base = base; this.length = 0; this.internalTag = _reference.CONSTANT_TAG; this.internalValues = _util.EMPTY_ARRAY; } setup(stack, base, length, names) { this.stack = stack; this.names = names; this.base = base; this.length = length; if (length === 0) { this.internalTag = _reference.CONSTANT_TAG; this.internalValues = _util.EMPTY_ARRAY; } else { this.internalTag = null; this.internalValues = null; } } get values() { let values = this.internalValues; if (!values) { let { base, length, stack } = this; values = this.internalValues = stack.sliceArray(base, base + length * 3); } return values; } has(name) { return this.names.indexOf(name) !== -1; } get(name) { let { base, stack, names } = this; let idx = names.indexOf(name); if (names.indexOf(name) === -1) { return null; } let table = stack.get(idx * 3, base); let scope = stack.get(idx * 3 + 1, base); // FIXME(mmun): shouldn't need to cast this let handle = stack.get(idx * 3 + 2, base); return handle === null ? null : [handle, scope, table]; } capture() { return new CapturedBlockArguments(this.names, this.values); } } class CapturedBlockArguments { constructor(names, values) { this.names = names; this.values = values; this.length = names.length; } has(name) { return this.names.indexOf(name) !== -1; } get(name) { let idx = this.names.indexOf(name); if (idx === -1) return null; return [this.values[idx * 3 + 2], this.values[idx * 3 + 1], this.values[idx * 3]]; } } const EMPTY_NAMED = new CapturedNamedArguments(_reference.CONSTANT_TAG, _util.EMPTY_ARRAY, _util.EMPTY_ARRAY); const EMPTY_POSITIONAL = new CapturedPositionalArguments(_reference.CONSTANT_TAG, _util.EMPTY_ARRAY); const EMPTY_ARGS = { tag: _reference.CONSTANT_TAG, length: 0, positional: EMPTY_POSITIONAL, named: EMPTY_NAMED }; class VM { constructor(runtime, scope, dynamicScope, elementStack) { this.runtime = runtime; this.elementStack = elementStack; this.dynamicScopeStack = new _util.Stack(); this.scopeStack = new _util.Stack(); this.updatingOpcodeStack = new _util.Stack(); this.cacheGroups = new _util.Stack(); this.listBlockStack = new _util.Stack(); this.s0 = null; this.s1 = null; this.t0 = null; this.t1 = null; this.v0 = null; this.heap = this.program.heap; this.constants = this.program.constants; this.elementStack = elementStack; this.scopeStack.push(scope); this.dynamicScopeStack.push(dynamicScope); this.args = new Arguments(); this.inner = new LowLevelVM(EvaluationStack.empty(), this.heap, runtime.program, { debugBefore: opcode => { return APPEND_OPCODES.debugBefore(this, opcode, opcode.type); }, debugAfter: (opcode, state) => { APPEND_OPCODES.debugAfter(this, opcode, opcode.type, state); } }); } get stack() { return this.inner.stack; } set stack(value) { this.inner.stack = value; } /* Registers */ set currentOpSize(value) { this.inner.currentOpSize = value; } get currentOpSize() { return this.inner.currentOpSize; } get pc() { return this.inner.pc; } set pc(value) { this.inner.pc = value; } get ra() { return this.inner.ra; } set ra(value) { this.inner.ra = value; } get fp() { return this.stack.fp; } set fp(fp) { this.stack.fp = fp; } get sp() { return this.stack.sp; } set sp(sp) { this.stack.sp = sp; } // Fetch a value from a register onto the stack fetch(register) { this.stack.push(this[_vm2.Register[register]]); } // Load a value from the stack into a register load(register) { this[_vm2.Register[register]] = this.stack.pop(); } // Fetch a value from a register fetchValue(register) { return this[_vm2.Register[register]]; } // Load a value into a register loadValue(register, value) { this[_vm2.Register[register]] = value; } /** * Migrated to Inner */ // Start a new frame and save $ra and $fp on the stack pushFrame() { this.inner.pushFrame(); } // Restore $ra, $sp and $fp popFrame() { this.inner.popFrame(); } // Jump to an address in `program` goto(offset) { this.inner.goto(offset); } // Save $pc into $ra, then jump to a new address in `program` (jal in MIPS) call(handle) { this.inner.call(handle); } // Put a specific `program` address in $ra returnTo(offset) { this.inner.returnTo(offset); } // Return to the `program` address stored in $ra return() { this.inner.return(); } /** * End of migrated. */ static initial(program, env, self, dynamicScope, elementStack, handle) { let scopeSize = program.heap.scopesizeof(handle); let scope = Scope.root(self, scopeSize); let vm = new VM({ program, env }, scope, dynamicScope, elementStack); vm.pc = vm.heap.getaddr(handle); vm.updatingOpcodeStack.push(new _util.LinkedList()); return vm; } static empty(program, env, elementStack) { let dynamicScope = { get() { return UNDEFINED_REFERENCE; }, set() { return UNDEFINED_REFERENCE; }, child() { return dynamicScope; } }; let vm = new VM({ program, env }, Scope.root(UNDEFINED_REFERENCE, 0), dynamicScope, elementStack); vm.updatingOpcodeStack.push(new _util.LinkedList()); return vm; } static resume({ scope, dynamicScope }, runtime, stack) { return new VM(runtime, scope, dynamicScope, stack); } get program() { return this.runtime.program; } get env() { return this.runtime.env; } capture(args) { return { dynamicScope: this.dynamicScope(), scope: this.scope(), stack: this.stack.capture(args) }; } beginCacheGroup() { this.cacheGroups.push(this.updating().tail()); } commitCacheGroup() { // JumpIfNotModified(END) // (head) // (....) // (tail) // DidModify // END: Noop let END = new LabelOpcode('END'); let opcodes = this.updating(); let marker = this.cacheGroups.pop(); let head = marker ? opcodes.nextNode(marker) : opcodes.head(); let tail = opcodes.tail(); let tag = (0, _reference.combineSlice)(new _util.ListSlice(head, tail)); let guard = new JumpIfNotModifiedOpcode(tag, END); opcodes.insertBefore(guard, head); opcodes.append(new DidModifyOpcode(guard)); opcodes.append(END); } enter(args) { let updating = new _util.LinkedList(); let state = this.capture(args); let tracker = this.elements().pushUpdatableBlock(); let tryOpcode = new TryOpcode(this.heap.gethandle(this.pc), state, this.runtime, tracker, updating); this.didEnter(tryOpcode); } iterate(memo, value) { let stack = this.stack; stack.push(value); stack.push(memo); let state = this.capture(2); let tracker = this.elements().pushUpdatableBlock(); // let ip = this.ip; // this.ip = end + 4; // this.frames.push(ip); return new TryOpcode(this.heap.gethandle(this.pc), state, this.runtime, tracker, new _util.LinkedList()); } enterItem(key, opcode) { this.listBlock().map[key] = opcode; this.didEnter(opcode); } enterList(relativeStart) { let updating = new _util.LinkedList(); let state = this.capture(0); let tracker = this.elements().pushBlockList(updating); let artifacts = this.stack.peek().artifacts; let addr = this.pc + relativeStart - this.currentOpSize; let start = this.heap.gethandle(addr); let opcode = new ListBlockOpcode(start, state, this.runtime, tracker, updating, artifacts); this.listBlockStack.push(opcode); this.didEnter(opcode); } didEnter(opcode) { this.updateWith(opcode); this.updatingOpcodeStack.push(opcode.children); } exit() { this.elements().popBlock(); this.updatingOpcodeStack.pop(); let parent = this.updating().tail(); parent.didInitializeChildren(); } exitList() { this.exit(); this.listBlockStack.pop(); } updateWith(opcode) { this.updating().append(opcode); } listBlock() { return this.listBlockStack.current; } updating() { return this.updatingOpcodeStack.current; } elements() { return this.elementStack; } scope() { return this.scopeStack.current; } dynamicScope() { return this.dynamicScopeStack.current; } pushChildScope() { this.scopeStack.push(this.scope().child()); } pushDynamicScope() { let child = this.dynamicScope().child(); this.dynamicScopeStack.push(child); return child; } pushRootScope(size, bindCaller) { let scope = Scope.sized(size); if (bindCaller) scope.bindCallerScope(this.scope()); this.scopeStack.push(scope); return scope; } pushScope(scope) { this.scopeStack.push(scope); } popScope() { this.scopeStack.pop(); } popDynamicScope() { this.dynamicScopeStack.pop(); } newDestroyable(d) { this.elements().didAddDestroyable(d); } /// SCOPE HELPERS getSelf() { return this.scope().getSelf(); } referenceForSymbol(symbol) { return this.scope().getSymbol(symbol); } /// EXECUTION execute(start, initialize) { this.pc = this.heap.getaddr(start); if (initialize) initialize(this); let result; while (true) { result = this.next(); if (result.done) break; } return result.value; } next() { let { env, program, updatingOpcodeStack, elementStack } = this; let opcode = this.inner.nextStatement(); let result; if (opcode !== null) { this.inner.evaluateOuter(opcode, this); result = { done: false, value: null }; } else { // Unload the stack this.stack.reset(); result = { done: true, value: new RenderResult(env, program, updatingOpcodeStack.pop(), elementStack.popBlock()) }; } return result; } bindDynamicScope(names) { let scope = this.dynamicScope(); for (let i = names.length - 1; i >= 0; i--) { let name = this.constants.getString(names[i]); scope.set(name, this.stack.pop()); } } } class TemplateIteratorImpl { constructor(vm) { this.vm = vm; } next() { return this.vm.next(); } } function render(program, env, self, dynamicScope, builder, handle) { let vm = VM.initial(program, env, self, dynamicScope, builder, handle); return new TemplateIteratorImpl(vm); } class DynamicVarReference { constructor(scope, nameRef) { this.scope = scope; this.nameRef = nameRef; let varTag = this.varTag = _reference.UpdatableTag.create(_reference.CONSTANT_TAG); this.tag = (0, _reference.combine)([nameRef.tag, varTag]); } value() { return this.getVar().value(); } get(key) { return this.getVar().get(key); } getVar() { let name = String(this.nameRef.value()); let ref = this.scope.get(name); this.varTag.inner.update(ref.tag); return ref; } } function getDynamicVar(vm, args) { let scope = vm.dynamicScope(); let nameRef = args.positional.at(0); return new DynamicVarReference(scope, nameRef); } /** @internal */ const DEFAULT_CAPABILITIES = { dynamicLayout: true, dynamicTag: true, prepareArgs: true, createArgs: true, attributeHook: false, elementHook: false, dynamicScope: true, createCaller: false, updateHook: true, createInstance: true }; const MINIMAL_CAPABILITIES = { dynamicLayout: false, dynamicTag: false, prepareArgs: false, createArgs: false, attributeHook: false, elementHook: false, dynamicScope: false, createCaller: false, updateHook: false, createInstance: false }; class RehydratingCursor extends Cursor { constructor(element, nextSibling, startingBlockDepth) { super(element, nextSibling); this.startingBlockDepth = startingBlockDepth; this.candidate = null; this.injectedOmittedNode = false; this.openBlockDepth = startingBlockDepth - 1; } } class RehydrateBuilder extends NewElementBuilder { // private candidate: Option = null; constructor(env, parentNode, nextSibling) { super(env, parentNode, nextSibling); this.unmatchedAttributes = null; this.blockDepth = 0; if (nextSibling) throw new Error('Rehydration with nextSibling not supported'); let node = this.currentCursor.element.firstChild; while (node !== null) { if (isComment(node) && (0, _util.isSerializationFirstNode)(node)) { break; } node = node.nextSibling; } this.candidate = node; } get currentCursor() { return this.cursorStack.current; } get candidate() { if (this.currentCursor) { return this.currentCursor.candidate; } return null; } set candidate(node) { this.currentCursor.candidate = node; } pushElement(element, nextSibling) { let { blockDepth = 0 } = this; let cursor = new RehydratingCursor(element, nextSibling, blockDepth); let currentCursor = this.currentCursor; if (currentCursor) { if (currentCursor.candidate) { /** *
<--------------- currentCursor.element * *
<--------------- currentCursor.candidate -> cursor.element * <- currentCursor.candidate.firstChild -> cursor.candidate * Foo * *
* <-- becomes currentCursor.candidate */ // where to rehydrate from if we are in rehydration mode cursor.candidate = element.firstChild; // where to continue when we pop currentCursor.candidate = element.nextSibling; } } this.cursorStack.push(cursor); } clearMismatch(candidate) { let current = candidate; let currentCursor = this.currentCursor; if (currentCursor !== null) { let openBlockDepth = currentCursor.openBlockDepth; if (openBlockDepth >= currentCursor.startingBlockDepth) { while (current && !(isComment(current) && getCloseBlockDepth(current) === openBlockDepth)) { current = this.remove(current); } } else { while (current !== null) { current = this.remove(current); } } // current cursor parentNode should be openCandidate if element // or openCandidate.parentNode if comment currentCursor.nextSibling = current; // disable rehydration until we popElement or closeBlock for openBlockDepth currentCursor.candidate = null; } } __openBlock() { let { currentCursor } = this; if (currentCursor === null) return; let blockDepth = this.blockDepth; this.blockDepth++; let { candidate } = currentCursor; if (candidate === null) return; if (isComment(candidate) && getOpenBlockDepth(candidate) === blockDepth) { currentCursor.candidate = this.remove(candidate); currentCursor.openBlockDepth = blockDepth; } else { this.clearMismatch(candidate); } } __closeBlock() { let { currentCursor } = this; if (currentCursor === null) return; // openBlock is the last rehydrated open block let openBlockDepth = currentCursor.openBlockDepth; // this currently is the expected next open block depth this.blockDepth--; let { candidate } = currentCursor; // rehydrating if (candidate !== null) { if (isComment(candidate) && getCloseBlockDepth(candidate) === openBlockDepth) { currentCursor.candidate = this.remove(candidate); currentCursor.openBlockDepth--; } else { this.clearMismatch(candidate); } // if the openBlockDepth matches the blockDepth we just closed to // then restore rehydration } if (currentCursor.openBlockDepth === this.blockDepth) { currentCursor.candidate = this.remove(currentCursor.nextSibling); currentCursor.openBlockDepth--; } } __appendNode(node) { let { candidate } = this; // This code path is only used when inserting precisely one node. It needs more // comparison logic, but we can probably lean on the cases where this code path // is actually used. if (candidate) { return candidate; } else { return super.__appendNode(node); } } __appendHTML(html) { let candidateBounds = this.markerBounds(); if (candidateBounds) { let first = candidateBounds.firstNode(); let last = candidateBounds.lastNode(); let newBounds = bounds(this.element, first.nextSibling, last.previousSibling); let possibleEmptyMarker = this.remove(first); this.remove(last); if (possibleEmptyMarker !== null && isEmpty$1(possibleEmptyMarker)) { this.candidate = this.remove(possibleEmptyMarker); if (this.candidate !== null) { this.clearMismatch(this.candidate); } } return newBounds; } else { return super.__appendHTML(html); } } remove(node) { let element = node.parentNode; let next = node.nextSibling; element.removeChild(node); return next; } markerBounds() { let _candidate = this.candidate; if (_candidate && isMarker(_candidate)) { let first = _candidate; let last = first.nextSibling; while (last && !isMarker(last)) { last = last.nextSibling; } return bounds(this.element, first, last); } else { return null; } } __appendText(string) { let { candidate } = this; if (candidate) { if (isTextNode(candidate)) { if (candidate.nodeValue !== string) { candidate.nodeValue = string; } this.candidate = candidate.nextSibling; return candidate; } else if (candidate && (isSeparator(candidate) || isEmpty$1(candidate))) { this.candidate = candidate.nextSibling; this.remove(candidate); return this.__appendText(string); } else if (isEmpty$1(candidate)) { let next = this.remove(candidate); this.candidate = next; let text = this.dom.createTextNode(string); this.dom.insertBefore(this.element, text, next); return text; } else { this.clearMismatch(candidate); return super.__appendText(string); } } else { return super.__appendText(string); } } __appendComment(string) { let _candidate = this.candidate; if (_candidate && isComment(_candidate)) { if (_candidate.nodeValue !== string) { _candidate.nodeValue = string; } this.candidate = _candidate.nextSibling; return _candidate; } else if (_candidate) { this.clearMismatch(_candidate); } return super.__appendComment(string); } __openElement(tag) { let _candidate = this.candidate; if (_candidate && isElement(_candidate) && isSameNodeType(_candidate, tag)) { this.unmatchedAttributes = [].slice.call(_candidate.attributes); return _candidate; } else if (_candidate) { if (isElement(_candidate) && _candidate.tagName === 'TBODY') { this.pushElement(_candidate, null); this.currentCursor.injectedOmittedNode = true; return this.__openElement(tag); } this.clearMismatch(_candidate); } return super.__openElement(tag); } __setAttribute(name, value, namespace) { let unmatched = this.unmatchedAttributes; if (unmatched) { let attr = findByName(unmatched, name); if (attr) { if (attr.value !== value) { attr.value = value; } unmatched.splice(unmatched.indexOf(attr), 1); return; } } return super.__setAttribute(name, value, namespace); } __setProperty(name, value) { let unmatched = this.unmatchedAttributes; if (unmatched) { let attr = findByName(unmatched, name); if (attr) { if (attr.value !== value) { attr.value = value; } unmatched.splice(unmatched.indexOf(attr), 1); return; } } return super.__setProperty(name, value); } __flushElement(parent, constructing) { let { unmatchedAttributes: unmatched } = this; if (unmatched) { for (let i = 0; i < unmatched.length; i++) { this.constructing.removeAttribute(unmatched[i].name); } this.unmatchedAttributes = null; } else { super.__flushElement(parent, constructing); } } willCloseElement() { let { candidate, currentCursor } = this; if (candidate !== null) { this.clearMismatch(candidate); } if (currentCursor && currentCursor.injectedOmittedNode) { this.popElement(); } super.willCloseElement(); } getMarker(element, guid) { let marker = element.querySelector(`script[glmr="${guid}"]`); if (marker) { return marker; } throw new Error('Cannot find serialized cursor for `in-element`'); } __pushRemoteElement(element, cursorId, nextSibling = null) { let marker = this.getMarker(element, cursorId); if (marker.parentNode === element) { let currentCursor = this.currentCursor; let candidate = currentCursor.candidate; this.pushElement(element, nextSibling); currentCursor.candidate = candidate; this.candidate = this.remove(marker); let tracker = new RemoteBlockTracker(element); this.pushBlockTracker(tracker, true); } } didAppendBounds(bounds$$1) { super.didAppendBounds(bounds$$1); if (this.candidate) { let last = bounds$$1.lastNode(); this.candidate = last && last.nextSibling; } return bounds$$1; } } function isTextNode(node) { return node.nodeType === 3; } function isComment(node) { return node.nodeType === 8; } function getOpenBlockDepth(node) { let boundsDepth = node.nodeValue.match(/^%\+b:(\d+)%$/); if (boundsDepth && boundsDepth[1]) { return Number(boundsDepth[1]); } else { return null; } } function getCloseBlockDepth(node) { let boundsDepth = node.nodeValue.match(/^%\-b:(\d+)%$/); if (boundsDepth && boundsDepth[1]) { return Number(boundsDepth[1]); } else { return null; } } function isElement(node) { return node.nodeType === 1; } function isMarker(node) { return node.nodeType === 8 && node.nodeValue === '%glmr%'; } function isSeparator(node) { return node.nodeType === 8 && node.nodeValue === '%|%'; } function isEmpty$1(node) { return node.nodeType === 8 && node.nodeValue === '% %'; } function isSameNodeType(candidate, tag) { if (candidate.namespaceURI === SVG_NAMESPACE$1) { return candidate.tagName === tag; } return candidate.tagName === tag.toUpperCase(); } function findByName(array, name) { for (let i = 0; i < array.length; i++) { let attr = array[i]; if (attr.name === name) return attr; } return undefined; } function rehydrationBuilder(env, cursor) { return RehydrateBuilder.forInitialRender(env, cursor); } exports.renderMain = render; exports.NULL_REFERENCE = NULL_REFERENCE; exports.UNDEFINED_REFERENCE = UNDEFINED_REFERENCE; exports.PrimitiveReference = PrimitiveReference; exports.ConditionalReference = ConditionalReference; exports.setDebuggerCallback = setDebuggerCallback; exports.resetDebuggerCallback = resetDebuggerCallback; exports.getDynamicVar = getDynamicVar; exports.LowLevelVM = VM; exports.UpdatingVM = UpdatingVM; exports.RenderResult = RenderResult; exports.SimpleDynamicAttribute = SimpleDynamicAttribute; exports.DynamicAttribute = DynamicAttribute; exports.EMPTY_ARGS = EMPTY_ARGS; exports.Scope = Scope; exports.Environment = Environment; exports.DefaultEnvironment = DefaultEnvironment; exports.DEFAULT_CAPABILITIES = DEFAULT_CAPABILITIES; exports.MINIMAL_CAPABILITIES = MINIMAL_CAPABILITIES; exports.CurriedComponentDefinition = CurriedComponentDefinition; exports.isCurriedComponentDefinition = isCurriedComponentDefinition; exports.curry = curry; exports.DOMChanges = helper$1; exports.SVG_NAMESPACE = SVG_NAMESPACE$1; exports.IDOMChanges = DOMChanges; exports.DOMTreeConstruction = DOMTreeConstruction; exports.isWhitespace = isWhitespace; exports.insertHTMLBefore = insertHTMLBefore; exports.normalizeProperty = normalizeProperty; exports.NewElementBuilder = NewElementBuilder; exports.clientBuilder = clientBuilder; exports.rehydrationBuilder = rehydrationBuilder; exports.RehydrateBuilder = RehydrateBuilder; exports.ConcreteBounds = ConcreteBounds; exports.Cursor = Cursor; exports.capabilityFlagsFrom = capabilityFlagsFrom; exports.hasCapability = hasCapability; }); enifed('@glimmer/util', ['exports'], function (exports) { 'use strict'; function unwrap(val) { if (val === null || val === undefined) throw new Error(`Expected value to be present`); return val; } function expect(val, message) { if (val === null || val === undefined) throw new Error(message); return val; } function unreachable(message = 'unreachable') { return new Error(message); } // import Logger from './logger'; // let alreadyWarned = false; function debugAssert(test, msg) { // if (!alreadyWarned) { // alreadyWarned = true; // Logger.warn("Don't leave debug assertions on in public builds"); // } if (!test) { throw new Error(msg || 'assertion failure'); } } const { keys: objKeys } = Object; function assign(obj) { for (let i = 1; i < arguments.length; i++) { let assignment = arguments[i]; if (assignment === null || typeof assignment !== 'object') continue; let keys = objKeys(assignment); for (let j = 0; j < keys.length; j++) { let key = keys[j]; obj[key] = assignment[key]; } } return obj; } function fillNulls(count) { let arr = new Array(count); for (let i = 0; i < count; i++) { arr[i] = null; } return arr; } let GUID = 0; function initializeGuid(object) { return object._guid = ++GUID; } function ensureGuid(object) { return object._guid || initializeGuid(object); } const SERIALIZATION_FIRST_NODE_STRING = '%+b:0%'; function isSerializationFirstNode(node) { return node.nodeValue === SERIALIZATION_FIRST_NODE_STRING; } function dict() { return Object.create(null); } class DictSet { constructor() { this.dict = dict(); } add(obj) { if (typeof obj === 'string') this.dict[obj] = obj;else this.dict[ensureGuid(obj)] = obj; return this; } delete(obj) { if (typeof obj === 'string') delete this.dict[obj];else if (obj._guid) delete this.dict[obj._guid]; } } class Stack { constructor() { this.stack = []; this.current = null; } get size() { return this.stack.length; } push(item) { this.current = item; this.stack.push(item); } pop() { let item = this.stack.pop(); let len = this.stack.length; this.current = len === 0 ? null : this.stack[len - 1]; return item === undefined ? null : item; } isEmpty() { return this.stack.length === 0; } } class ListNode { constructor(value) { this.next = null; this.prev = null; this.value = value; } } class LinkedList { constructor() { this.clear(); } head() { return this._head; } tail() { return this._tail; } clear() { this._head = this._tail = null; } toArray() { let out = []; this.forEachNode(n => out.push(n)); return out; } nextNode(node) { return node.next; } forEachNode(callback) { let node = this._head; while (node !== null) { callback(node); node = node.next; } } insertBefore(node, reference = null) { if (reference === null) return this.append(node); if (reference.prev) reference.prev.next = node;else this._head = node; node.prev = reference.prev; node.next = reference; reference.prev = node; return node; } append(node) { let tail = this._tail; if (tail) { tail.next = node; node.prev = tail; node.next = null; } else { this._head = node; } return this._tail = node; } remove(node) { if (node.prev) node.prev.next = node.next;else this._head = node.next; if (node.next) node.next.prev = node.prev;else this._tail = node.prev; return node; } } class ListSlice { constructor(head, tail) { this._head = head; this._tail = tail; } forEachNode(callback) { let node = this._head; while (node !== null) { callback(node); node = this.nextNode(node); } } head() { return this._head; } tail() { return this._tail; } toArray() { let out = []; this.forEachNode(n => out.push(n)); return out; } nextNode(node) { if (node === this._tail) return null; return node.next; } } const EMPTY_SLICE = new ListSlice(null, null); const EMPTY_ARRAY = Object.freeze([]); exports.assert = debugAssert; exports.assign = assign; exports.fillNulls = fillNulls; exports.ensureGuid = ensureGuid; exports.initializeGuid = initializeGuid; exports.isSerializationFirstNode = isSerializationFirstNode; exports.SERIALIZATION_FIRST_NODE_STRING = SERIALIZATION_FIRST_NODE_STRING; exports.Stack = Stack; exports.DictSet = DictSet; exports.dict = dict; exports.EMPTY_SLICE = EMPTY_SLICE; exports.LinkedList = LinkedList; exports.ListNode = ListNode; exports.ListSlice = ListSlice; exports.EMPTY_ARRAY = EMPTY_ARRAY; exports.unwrap = unwrap; exports.expect = expect; exports.unreachable = unreachable; }); enifed("@glimmer/vm", ["exports"], function (exports) { "use strict"; /** * Registers * * For the most part, these follows MIPS naming conventions, however the * register numbers are different. */ var Register; (function (Register) { // $0 or $pc (program counter): pointer into `program` for the next insturction; -1 means exit Register[Register["pc"] = 0] = "pc"; // $1 or $ra (return address): pointer into `program` for the return Register[Register["ra"] = 1] = "ra"; // $2 or $fp (frame pointer): pointer into the `evalStack` for the base of the stack Register[Register["fp"] = 2] = "fp"; // $3 or $sp (stack pointer): pointer into the `evalStack` for the top of the stack Register[Register["sp"] = 3] = "sp"; // $4-$5 or $s0-$s1 (saved): callee saved general-purpose registers Register[Register["s0"] = 4] = "s0"; Register[Register["s1"] = 5] = "s1"; // $6-$7 or $t0-$t1 (temporaries): caller saved general-purpose registers Register[Register["t0"] = 6] = "t0"; Register[Register["t1"] = 7] = "t1"; // $8 or $v0 (return value) Register[Register["v0"] = 8] = "v0"; })(Register || (exports.Register = Register = {})); exports.Register = Register; }); enifed("@glimmer/wire-format", ["exports"], function (exports) { "use strict"; var Opcodes; (function (Opcodes) { // Statements Opcodes[Opcodes["Text"] = 0] = "Text"; Opcodes[Opcodes["Append"] = 1] = "Append"; Opcodes[Opcodes["Comment"] = 2] = "Comment"; Opcodes[Opcodes["Modifier"] = 3] = "Modifier"; Opcodes[Opcodes["Block"] = 4] = "Block"; Opcodes[Opcodes["Component"] = 5] = "Component"; Opcodes[Opcodes["DynamicComponent"] = 6] = "DynamicComponent"; Opcodes[Opcodes["OpenElement"] = 7] = "OpenElement"; Opcodes[Opcodes["OpenSplattedElement"] = 8] = "OpenSplattedElement"; Opcodes[Opcodes["FlushElement"] = 9] = "FlushElement"; Opcodes[Opcodes["CloseElement"] = 10] = "CloseElement"; Opcodes[Opcodes["StaticAttr"] = 11] = "StaticAttr"; Opcodes[Opcodes["DynamicAttr"] = 12] = "DynamicAttr"; Opcodes[Opcodes["AttrSplat"] = 13] = "AttrSplat"; Opcodes[Opcodes["Yield"] = 14] = "Yield"; Opcodes[Opcodes["Partial"] = 15] = "Partial"; Opcodes[Opcodes["DynamicArg"] = 16] = "DynamicArg"; Opcodes[Opcodes["StaticArg"] = 17] = "StaticArg"; Opcodes[Opcodes["TrustingAttr"] = 18] = "TrustingAttr"; Opcodes[Opcodes["Debugger"] = 19] = "Debugger"; Opcodes[Opcodes["ClientSideStatement"] = 20] = "ClientSideStatement"; // Expressions Opcodes[Opcodes["Unknown"] = 21] = "Unknown"; Opcodes[Opcodes["Get"] = 22] = "Get"; Opcodes[Opcodes["MaybeLocal"] = 23] = "MaybeLocal"; Opcodes[Opcodes["HasBlock"] = 24] = "HasBlock"; Opcodes[Opcodes["HasBlockParams"] = 25] = "HasBlockParams"; Opcodes[Opcodes["Undefined"] = 26] = "Undefined"; Opcodes[Opcodes["Helper"] = 27] = "Helper"; Opcodes[Opcodes["Concat"] = 28] = "Concat"; Opcodes[Opcodes["ClientSideExpression"] = 29] = "ClientSideExpression"; })(Opcodes || (exports.Ops = Opcodes = {})); function is(variant) { return function (value) { return Array.isArray(value) && value[0] === variant; }; } // Statements const isFlushElement = is(Opcodes.FlushElement); const isAttrSplat = is(Opcodes.AttrSplat); function isAttribute(val) { return val[0] === Opcodes.StaticAttr || val[0] === Opcodes.DynamicAttr || val[0] === Opcodes.TrustingAttr; } function isArgument(val) { return val[0] === Opcodes.StaticArg || val[0] === Opcodes.DynamicArg; } // Expressions const isGet = is(Opcodes.Get); const isMaybeLocal = is(Opcodes.MaybeLocal); exports.is = is; exports.isFlushElement = isFlushElement; exports.isAttrSplat = isAttrSplat; exports.isAttribute = isAttribute; exports.isArgument = isArgument; exports.isGet = isGet; exports.isMaybeLocal = isMaybeLocal; exports.Ops = Opcodes; }); enifed('backburner', ['exports'], function (exports) { 'use strict'; const SET_TIMEOUT = setTimeout; const NOOP = () => {}; function buildPlatform(flush) { let next; let clearNext = NOOP; if (typeof MutationObserver === 'function') { let iterations = 0; let observer = new MutationObserver(flush); let node = document.createTextNode(''); observer.observe(node, { characterData: true }); next = () => { iterations = ++iterations % 2; node.data = '' + iterations; return iterations; }; } else if (typeof Promise === 'function') { const autorunPromise = Promise.resolve(); next = () => autorunPromise.then(flush); } else { next = () => SET_TIMEOUT(flush, 0); } return { setTimeout(fn, ms) { return setTimeout(fn, ms); }, clearTimeout(timerId) { return clearTimeout(timerId); }, now() { return Date.now(); }, next, clearNext }; } const NUMBER = /\d+/; const TIMERS_OFFSET = 6; function isCoercableNumber(suspect) { let type = typeof suspect; return type === 'number' && suspect === suspect || type === 'string' && NUMBER.test(suspect); } function getOnError(options) { return options.onError || options.onErrorTarget && options.onErrorTarget[options.onErrorMethod]; } function findItem(target, method, collection) { let index = -1; for (let i = 0, l = collection.length; i < l; i += 4) { if (collection[i] === target && collection[i + 1] === method) { index = i; break; } } return index; } function findTimerItem(target, method, collection) { let index = -1; for (let i = 2, l = collection.length; i < l; i += 6) { if (collection[i] === target && collection[i + 1] === method) { index = i - 2; break; } } return index; } function getQueueItems(items, queueItemLength, queueItemPositionOffset = 0) { let queueItems = []; for (let i = 0; i < items.length; i += queueItemLength) { let maybeError = items[i + 3 /* stack */ + queueItemPositionOffset]; let queueItem = { target: items[i + 0 /* target */ + queueItemPositionOffset], method: items[i + 1 /* method */ + queueItemPositionOffset], args: items[i + 2 /* args */ + queueItemPositionOffset], stack: maybeError !== undefined && 'stack' in maybeError ? maybeError.stack : '' }; queueItems.push(queueItem); } return queueItems; } function binarySearch(time, timers) { let start = 0; let end = timers.length - TIMERS_OFFSET; let middle; let l; while (start < end) { // since timers is an array of pairs 'l' will always // be an integer l = (end - start) / TIMERS_OFFSET; // compensate for the index in case even number // of pairs inside timers middle = start + l - l % TIMERS_OFFSET; if (time >= timers[middle]) { start = middle + TIMERS_OFFSET; } else { end = middle; } } return time >= timers[start] ? start + TIMERS_OFFSET : start; } const QUEUE_ITEM_LENGTH = 4; class Queue { constructor(name, options = {}, globalOptions = {}) { this._queueBeingFlushed = []; this.targetQueues = new Map(); this.index = 0; this._queue = []; this.name = name; this.options = options; this.globalOptions = globalOptions; } stackFor(index) { if (index < this._queue.length) { let entry = this._queue[index * 3 + QUEUE_ITEM_LENGTH]; if (entry) { return entry.stack; } else { return null; } } } flush(sync) { let { before, after } = this.options; let target; let method; let args; let errorRecordedForStack; this.targetQueues.clear(); if (this._queueBeingFlushed.length === 0) { this._queueBeingFlushed = this._queue; this._queue = []; } if (before !== undefined) { before(); } let invoke; let queueItems = this._queueBeingFlushed; if (queueItems.length > 0) { let onError = getOnError(this.globalOptions); invoke = onError ? this.invokeWithOnError : this.invoke; for (let i = this.index; i < queueItems.length; i += QUEUE_ITEM_LENGTH) { this.index += QUEUE_ITEM_LENGTH; method = queueItems[i + 1]; // method could have been nullified / canceled during flush if (method !== null) { // // ** 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. // // One possible long-term solution is the following Chrome issue: // https://bugs.chromium.org/p/chromium/issues/detail?id=332624 // target = queueItems[i]; args = queueItems[i + 2]; errorRecordedForStack = queueItems[i + 3]; // Debugging assistance invoke(target, method, args, onError, errorRecordedForStack); } if (this.index !== this._queueBeingFlushed.length && this.globalOptions.mustYield && this.globalOptions.mustYield()) { return 1 /* Pause */; } } } if (after !== undefined) { after(); } this._queueBeingFlushed.length = 0; this.index = 0; if (sync !== false && this._queue.length > 0) { // check if new items have been added this.flush(true); } } hasWork() { return this._queueBeingFlushed.length > 0 || this._queue.length > 0; } cancel({ target, method }) { let queue = this._queue; let targetQueueMap = this.targetQueues.get(target); if (targetQueueMap !== undefined) { targetQueueMap.delete(method); } let index = findItem(target, method, queue); if (index > -1) { queue.splice(index, QUEUE_ITEM_LENGTH); return true; } // if not found in current queue // could be in the queue that is being flushed queue = this._queueBeingFlushed; index = findItem(target, method, queue); if (index > -1) { queue[index + 1] = null; return true; } return false; } push(target, method, args, stack) { this._queue.push(target, method, args, stack); return { queue: this, target, method }; } pushUnique(target, method, args, stack) { let localQueueMap = this.targetQueues.get(target); if (localQueueMap === undefined) { localQueueMap = new Map(); this.targetQueues.set(target, localQueueMap); } let index = localQueueMap.get(method); if (index === undefined) { let queueIndex = this._queue.push(target, method, args, stack) - QUEUE_ITEM_LENGTH; localQueueMap.set(method, queueIndex); } else { let queue = this._queue; queue[index + 2] = args; // replace args queue[index + 3] = stack; // replace stack } return { queue: this, target, method }; } _getDebugInfo(debugEnabled) { if (debugEnabled) { let debugInfo = getQueueItems(this._queue, QUEUE_ITEM_LENGTH); return debugInfo; } return undefined; } invoke(target, method, args /*, onError, errorRecordedForStack */) { if (args === undefined) { method.call(target); } else { method.apply(target, args); } } invokeWithOnError(target, method, args, onError, errorRecordedForStack) { try { if (args === undefined) { method.call(target); } else { method.apply(target, args); } } catch (error) { onError(error, errorRecordedForStack); } } } class DeferredActionQueues { constructor(queueNames = [], options) { this.queues = {}; this.queueNameIndex = 0; this.queueNames = queueNames; queueNames.reduce(function (queues, queueName) { queues[queueName] = new Queue(queueName, options[queueName], options); return queues; }, this.queues); } /** * @method schedule * @param {String} queueName * @param {Any} target * @param {Any} method * @param {Any} args * @param {Boolean} onceFlag * @param {Any} stack * @return queue */ schedule(queueName, target, method, args, onceFlag, stack) { let queues = this.queues; let queue = queues[queueName]; if (queue === undefined) { throw new Error(`You attempted to schedule an action in a queue (${queueName}) that doesn\'t exist`); } if (method === undefined || method === null) { throw new Error(`You attempted to schedule an action in a queue (${queueName}) for a method that doesn\'t exist`); } this.queueNameIndex = 0; if (onceFlag) { return queue.pushUnique(target, method, args, stack); } else { return queue.push(target, method, args, stack); } } /** * DeferredActionQueues.flush() calls Queue.flush() * * @method flush * @param {Boolean} fromAutorun */ flush(fromAutorun = false) { let queue; let queueName; let numberOfQueues = this.queueNames.length; while (this.queueNameIndex < numberOfQueues) { queueName = this.queueNames[this.queueNameIndex]; queue = this.queues[queueName]; if (queue.hasWork() === false) { this.queueNameIndex++; if (fromAutorun && this.queueNameIndex < numberOfQueues) { return 1 /* Pause */; } } else { if (queue.flush(false /* async */) === 1 /* Pause */) { return 1 /* Pause */; } } } } /** * Returns debug information for the current queues. * * @method _getDebugInfo * @param {Boolean} debugEnabled * @returns {IDebugInfo | undefined} */ _getDebugInfo(debugEnabled) { if (debugEnabled) { let debugInfo = {}; let queue; let queueName; let numberOfQueues = this.queueNames.length; let i = 0; while (i < numberOfQueues) { queueName = this.queueNames[i]; queue = this.queues[queueName]; debugInfo[queueName] = queue._getDebugInfo(debugEnabled); i++; } return debugInfo; } return; } } function iteratorDrain(fn) { let iterator = fn(); let result = iterator.next(); while (result.done === false) { result.value(); result = iterator.next(); } } const noop = function () {}; const DISABLE_SCHEDULE = Object.freeze([]); function parseArgs() { let length = arguments.length; let args; let method; let target; if (length === 0) {} else if (length === 1) { target = null; method = arguments[0]; } else { let argsIndex = 2; let methodOrTarget = arguments[0]; let methodOrArgs = arguments[1]; let type = typeof methodOrArgs; if (type === 'function') { target = methodOrTarget; method = methodOrArgs; } else if (methodOrTarget !== null && type === 'string' && methodOrArgs in methodOrTarget) { target = methodOrTarget; method = target[methodOrArgs]; } else if (typeof methodOrTarget === 'function') { argsIndex = 1; target = null; method = methodOrTarget; } if (length > argsIndex) { let len = length - argsIndex; args = new Array(len); for (let i = 0; i < len; i++) { args[i] = arguments[i + argsIndex]; } } } return [target, method, args]; } function parseTimerArgs() { let [target, method, args] = parseArgs(...arguments); let wait = 0; let length = args !== undefined ? args.length : 0; if (length > 0) { let last = args[length - 1]; if (isCoercableNumber(last)) { wait = parseInt(args.pop(), 10); } } return [target, method, args, wait]; } function parseDebounceArgs() { let target; let method; let isImmediate; let args; let wait; if (arguments.length === 2) { method = arguments[0]; wait = arguments[1]; target = null; } else { [target, method, args] = parseArgs(...arguments); if (args === undefined) { wait = 0; } else { wait = args.pop(); if (!isCoercableNumber(wait)) { isImmediate = wait === true; wait = args.pop(); } } } wait = parseInt(wait, 10); return [target, method, args, wait, isImmediate]; } let UUID = 0; let beginCount = 0; let endCount = 0; let beginEventCount = 0; let endEventCount = 0; let runCount = 0; let joinCount = 0; let deferCount = 0; let scheduleCount = 0; let scheduleIterableCount = 0; let deferOnceCount = 0; let scheduleOnceCount = 0; let setTimeoutCount = 0; let laterCount = 0; let throttleCount = 0; let debounceCount = 0; let cancelTimersCount = 0; let cancelCount = 0; let autorunsCreatedCount = 0; let autorunsCompletedCount = 0; let deferredActionQueuesCreatedCount = 0; let nestedDeferredActionQueuesCreated = 0; class Backburner { constructor(queueNames, options) { this.DEBUG = false; this.currentInstance = null; this.instanceStack = []; this._eventCallbacks = { end: [], begin: [] }; this._timerTimeoutId = null; this._timers = []; this._autorun = null; this._autorunStack = null; this.queueNames = queueNames; this.options = options || {}; if (typeof this.options.defaultQueue === 'string') { this._defaultQueue = this.options.defaultQueue; } else { this._defaultQueue = this.queueNames[0]; } this._onBegin = this.options.onBegin || noop; this._onEnd = this.options.onEnd || noop; this._boundRunExpiredTimers = this._runExpiredTimers.bind(this); this._boundAutorunEnd = () => { autorunsCompletedCount++; // if the autorun was already flushed, do nothing if (this._autorun === null) { return; } this._autorun = null; this._autorunStack = null; this._end(true /* fromAutorun */); }; let builder = this.options._buildPlatform || buildPlatform; this._platform = builder(this._boundAutorunEnd); } get counters() { return { begin: beginCount, end: endCount, events: { begin: beginEventCount, end: endEventCount }, autoruns: { created: autorunsCreatedCount, completed: autorunsCompletedCount }, run: runCount, join: joinCount, defer: deferCount, schedule: scheduleCount, scheduleIterable: scheduleIterableCount, deferOnce: deferOnceCount, scheduleOnce: scheduleOnceCount, setTimeout: setTimeoutCount, later: laterCount, throttle: throttleCount, debounce: debounceCount, cancelTimers: cancelTimersCount, cancel: cancelCount, loops: { total: deferredActionQueuesCreatedCount, nested: nestedDeferredActionQueuesCreated } }; } get defaultQueue() { return this._defaultQueue; } /* @method begin @return instantiated class DeferredActionQueues */ begin() { beginCount++; let options = this.options; let previousInstance = this.currentInstance; let current; if (this._autorun !== null) { current = previousInstance; this._cancelAutorun(); } else { if (previousInstance !== null) { nestedDeferredActionQueuesCreated++; this.instanceStack.push(previousInstance); } deferredActionQueuesCreatedCount++; current = this.currentInstance = new DeferredActionQueues(this.queueNames, options); beginEventCount++; this._trigger('begin', current, previousInstance); } this._onBegin(current, previousInstance); return current; } end() { endCount++; this._end(false); } on(eventName, callback) { if (typeof callback !== 'function') { throw new TypeError(`Callback must be a function`); } let callbacks = this._eventCallbacks[eventName]; if (callbacks !== undefined) { callbacks.push(callback); } else { throw new TypeError(`Cannot on() event ${eventName} because it does not exist`); } } off(eventName, callback) { let callbacks = this._eventCallbacks[eventName]; if (!eventName || callbacks === undefined) { throw new TypeError(`Cannot off() event ${eventName} because it does not exist`); } let callbackFound = false; if (callback) { for (let 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`); } } run() { runCount++; let [target, method, args] = parseArgs(...arguments); return this._run(target, method, args); } join() { joinCount++; let [target, method, args] = parseArgs(...arguments); return this._join(target, method, args); } /** * @deprecated please use schedule instead. */ defer(queueName, target, method, ...args) { deferCount++; return this.schedule(queueName, target, method, ...args); } schedule(queueName, ..._args) { scheduleCount++; let [target, method, args] = parseArgs(..._args); let stack = this.DEBUG ? new Error() : undefined; return this._ensureInstance().schedule(queueName, target, method, args, false, stack); } /* Defer the passed iterable of functions to run inside the specified queue. @method scheduleIterable @param {String} queueName @param {Iterable} an iterable of functions to execute @return method result */ scheduleIterable(queueName, iterable) { scheduleIterableCount++; let stack = this.DEBUG ? new Error() : undefined; return this._ensureInstance().schedule(queueName, null, iteratorDrain, [iterable], false, stack); } /** * @deprecated please use scheduleOnce instead. */ deferOnce(queueName, target, method, ...args) { deferOnceCount++; return this.scheduleOnce(queueName, target, method, ...args); } scheduleOnce(queueName, ..._args) { scheduleOnceCount++; let [target, method, args] = parseArgs(..._args); let stack = this.DEBUG ? new Error() : undefined; return this._ensureInstance().schedule(queueName, target, method, args, true, stack); } setTimeout() { setTimeoutCount++; return this.later(...arguments); } later() { laterCount++; let [target, method, args, wait] = parseTimerArgs(...arguments); return this._later(target, method, args, wait); } throttle() { throttleCount++; let [target, method, args, wait, isImmediate = true] = parseDebounceArgs(...arguments); let index = findTimerItem(target, method, this._timers); let timerId; if (index === -1) { timerId = this._later(target, method, isImmediate ? DISABLE_SCHEDULE : args, wait); if (isImmediate) { this._join(target, method, args); } } else { timerId = this._timers[index + 1]; let argIndex = index + 4; if (this._timers[argIndex] !== DISABLE_SCHEDULE) { this._timers[argIndex] = args; } } return timerId; } debounce() { debounceCount++; let [target, method, args, wait, isImmediate = false] = parseDebounceArgs(...arguments); let _timers = this._timers; let index = findTimerItem(target, method, _timers); let timerId; if (index === -1) { timerId = this._later(target, method, isImmediate ? DISABLE_SCHEDULE : args, wait); if (isImmediate) { this._join(target, method, args); } } else { let executeAt = this._platform.now() + wait; let argIndex = index + 4; if (_timers[argIndex] === DISABLE_SCHEDULE) { args = DISABLE_SCHEDULE; } timerId = _timers[index + 1]; let i = binarySearch(executeAt, _timers); if (index + TIMERS_OFFSET === i) { _timers[index] = executeAt; _timers[argIndex] = args; } else { let stack = this._timers[index + 5]; this._timers.splice(i, 0, executeAt, timerId, target, method, args, stack); this._timers.splice(index, TIMERS_OFFSET); } if (index === 0) { this._reinstallTimerTimeout(); } } return timerId; } cancelTimers() { cancelTimersCount++; this._clearTimerTimeout(); this._timers = []; this._cancelAutorun(); } hasTimers() { return this._timers.length > 0 || this._autorun !== null; } cancel(timer) { cancelCount++; if (timer === null || timer === undefined) { return false; } let timerType = typeof timer; if (timerType === 'number') { // we're cancelling a setTimeout or throttle or debounce return this._cancelLaterTimer(timer); } else if (timerType === 'object' && timer.queue && timer.method) { // we're cancelling a deferOnce return timer.queue.cancel(timer); } return false; } ensureInstance() { this._ensureInstance(); } /** * Returns debug information related to the current instance of Backburner * * @method getDebugInfo * @returns {Object | undefined} Will return and Object containing debug information if * the DEBUG flag is set to true on the current instance of Backburner, else undefined. */ getDebugInfo() { if (this.DEBUG) { return { autorun: this._autorunStack, counters: this.counters, timers: getQueueItems(this._timers, TIMERS_OFFSET, 2), instanceStack: [this.currentInstance, ...this.instanceStack].map(deferredActionQueue => deferredActionQueue && deferredActionQueue._getDebugInfo(this.DEBUG)) }; } return undefined; } _end(fromAutorun) { let currentInstance = this.currentInstance; let nextInstance = null; if (currentInstance === null) { throw new Error(`end called without begin`); } // 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 let finallyAlreadyCalled = false; let result; try { result = currentInstance.flush(fromAutorun); } finally { if (!finallyAlreadyCalled) { finallyAlreadyCalled = true; if (result === 1 /* Pause */) { this._scheduleAutorun(); } else { this.currentInstance = null; if (this.instanceStack.length > 0) { nextInstance = this.instanceStack.pop(); this.currentInstance = nextInstance; } this._trigger('end', currentInstance, nextInstance); this._onEnd(currentInstance, nextInstance); } } } } _join(target, method, args) { if (this.currentInstance === null) { return this._run(target, method, args); } if (target === undefined && args === undefined) { return method(); } else { return method.apply(target, args); } } _run(target, method, args) { let onError = getOnError(this.options); this.begin(); if (onError) { try { return method.apply(target, args); } catch (error) { onError(error); } finally { this.end(); } } else { try { return method.apply(target, args); } finally { this.end(); } } } _cancelAutorun() { if (this._autorun !== null) { this._platform.clearNext(this._autorun); this._autorun = null; this._autorunStack = null; } } _later(target, method, args, wait) { let stack = this.DEBUG ? new Error() : undefined; let executeAt = this._platform.now() + wait; let id = UUID++; if (this._timers.length === 0) { this._timers.push(executeAt, id, target, method, args, stack); this._installTimerTimeout(); } else { // find position to insert let i = binarySearch(executeAt, this._timers); this._timers.splice(i, 0, executeAt, id, target, method, args, stack); // always reinstall since it could be out of sync this._reinstallTimerTimeout(); } return id; } _cancelLaterTimer(timer) { for (let i = 1; i < this._timers.length; i += TIMERS_OFFSET) { if (this._timers[i] === timer) { this._timers.splice(i - 1, TIMERS_OFFSET); if (i === 1) { this._reinstallTimerTimeout(); } return true; } } return false; } /** 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 instance and then an argument for the next instance. @private @method _trigger @param {String} eventName @param {any} arg1 @param {any} arg2 */ _trigger(eventName, arg1, arg2) { let callbacks = this._eventCallbacks[eventName]; if (callbacks !== undefined) { for (let i = 0; i < callbacks.length; i++) { callbacks[i](arg1, arg2); } } } _runExpiredTimers() { this._timerTimeoutId = null; if (this._timers.length > 0) { this.begin(); this._scheduleExpiredTimers(); this.end(); } } _scheduleExpiredTimers() { let timers = this._timers; let i = 0; let l = timers.length; let defaultQueue = this._defaultQueue; let n = this._platform.now(); for (; i < l; i += TIMERS_OFFSET) { let executeAt = timers[i]; if (executeAt > n) { break; } let args = timers[i + 4]; if (args !== DISABLE_SCHEDULE) { let target = timers[i + 2]; let method = timers[i + 3]; let stack = timers[i + 5]; this.currentInstance.schedule(defaultQueue, target, method, args, false, stack); } } timers.splice(0, i); this._installTimerTimeout(); } _reinstallTimerTimeout() { this._clearTimerTimeout(); this._installTimerTimeout(); } _clearTimerTimeout() { if (this._timerTimeoutId === null) { return; } this._platform.clearTimeout(this._timerTimeoutId); this._timerTimeoutId = null; } _installTimerTimeout() { if (this._timers.length === 0) { return; } let minExpiresAt = this._timers[0]; let n = this._platform.now(); let wait = Math.max(0, minExpiresAt - n); this._timerTimeoutId = this._platform.setTimeout(this._boundRunExpiredTimers, wait); } _ensureInstance() { let currentInstance = this.currentInstance; if (currentInstance === null) { this._autorunStack = this.DEBUG ? new Error() : undefined; currentInstance = this.begin(); this._scheduleAutorun(); } return currentInstance; } _scheduleAutorun() { autorunsCreatedCount++; const next = this._platform.next; this._autorun = next(); } } Backburner.Queue = Queue; exports.default = Backburner; exports.buildPlatform = buildPlatform; }); enifed("dag-map", ["exports"], function (exports) { "use strict"; /** * A topologically ordered map of key/value pairs with a simple API for adding constraints. * * Edges can forward reference keys that have not been added yet (the forward reference will * map the key to undefined). */ var DAG = function () { function DAG() { this._vertices = new Vertices(); } /** * Adds a key/value pair with dependencies on other key/value pairs. * * @public * @param key The key of the vertex to be added. * @param value The value of that vertex. * @param before A key or array of keys of the vertices that must * be visited before this vertex. * @param after An string or array of strings with the keys of the * vertices that must be after this vertex is visited. */ DAG.prototype.add = function (key, value, before, after) { if (!key) throw new Error('argument `key` is required'); var vertices = this._vertices; var v = vertices.add(key); v.val = value; if (before) { if (typeof before === "string") { vertices.addEdge(v, vertices.add(before)); } else { for (var i = 0; i < before.length; i++) { vertices.addEdge(v, vertices.add(before[i])); } } } if (after) { if (typeof after === "string") { vertices.addEdge(vertices.add(after), v); } else { for (var i = 0; i < after.length; i++) { vertices.addEdge(vertices.add(after[i]), v); } } } }; /** * @deprecated please use add. */ DAG.prototype.addEdges = function (key, value, before, after) { this.add(key, value, before, after); }; /** * Visits key/value pairs in topological order. * * @public * @param callback The function to be invoked with each key/value. */ DAG.prototype.each = function (callback) { this._vertices.walk(callback); }; /** * @deprecated please use each. */ DAG.prototype.topsort = function (callback) { this.each(callback); }; return DAG; }(); exports.default = DAG; /** @private */ var Vertices = function () { function Vertices() { this.length = 0; this.stack = new IntStack(); this.path = new IntStack(); this.result = new IntStack(); } Vertices.prototype.add = function (key) { if (!key) throw new Error("missing key"); var l = this.length | 0; var vertex; for (var i = 0; i < l; i++) { vertex = this[i]; if (vertex.key === key) return vertex; } this.length = l + 1; return this[l] = { idx: l, key: key, val: undefined, out: false, flag: false, length: 0 }; }; Vertices.prototype.addEdge = function (v, w) { this.check(v, w.key); var l = w.length | 0; for (var i = 0; i < l; i++) { if (w[i] === v.idx) return; } w.length = l + 1; w[l] = v.idx; v.out = true; }; Vertices.prototype.walk = function (cb) { this.reset(); for (var i = 0; i < this.length; i++) { var vertex = this[i]; if (vertex.out) continue; this.visit(vertex, ""); } this.each(this.result, cb); }; Vertices.prototype.check = function (v, w) { if (v.key === w) { throw new Error("cycle detected: " + w + " <- " + w); } // quick check if (v.length === 0) return; // shallow check for (var i = 0; i < v.length; i++) { var key = this[v[i]].key; if (key === w) { throw new Error("cycle detected: " + w + " <- " + v.key + " <- " + w); } } // deep check this.reset(); this.visit(v, w); if (this.path.length > 0) { var msg_1 = "cycle detected: " + w; this.each(this.path, function (key) { msg_1 += " <- " + key; }); throw new Error(msg_1); } }; Vertices.prototype.reset = function () { this.stack.length = 0; this.path.length = 0; this.result.length = 0; for (var i = 0, l = this.length; i < l; i++) { this[i].flag = false; } }; Vertices.prototype.visit = function (start, search) { var _a = this, stack = _a.stack, path = _a.path, result = _a.result; stack.push(start.idx); while (stack.length) { var index = stack.pop() | 0; if (index >= 0) { // enter var vertex = this[index]; if (vertex.flag) continue; vertex.flag = true; path.push(index); if (search === vertex.key) break; // push exit stack.push(~index); this.pushIncoming(vertex); } else { // exit path.pop(); result.push(~index); } } }; Vertices.prototype.pushIncoming = function (incomming) { var stack = this.stack; for (var i = incomming.length - 1; i >= 0; i--) { var index = incomming[i]; if (!this[index].flag) { stack.push(index); } } }; Vertices.prototype.each = function (indices, cb) { for (var i = 0, l = indices.length; i < l; i++) { var vertex = this[indices[i]]; cb(vertex.key, vertex.val); } }; return Vertices; }(); /** @private */ var IntStack = function () { function IntStack() { this.length = 0; } IntStack.prototype.push = function (n) { this[this.length++] = n | 0; }; IntStack.prototype.pop = function () { return this[--this.length] | 0; }; return IntStack; }(); }); enifed('ember-babel', ['exports'], function (exports) { 'use strict'; exports.classCallCheck = classCallCheck; exports.inherits = inherits; exports.taggedTemplateLiteralLoose = taggedTemplateLiteralLoose; exports.createClass = createClass; const create = Object.create; const setPrototypeOf = Object.setPrototypeOf; const defineProperty = Object.defineProperty; function classCallCheck(instance, Constructor) { if (true /* DEBUG */) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } } function inherits(subClass, superClass) { if (true /* DEBUG */) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } } subClass.prototype = create(superClass === null ? null : superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass !== null) setPrototypeOf(subClass, superClass); } function taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; defineProperty(target, descriptor.key, descriptor); } } function createClass(Constructor, protoProps, staticProps) { if (protoProps !== undefined) defineProperties(Constructor.prototype, protoProps); if (staticProps !== undefined) defineProperties(Constructor, staticProps); return Constructor; } const possibleConstructorReturn = exports.possibleConstructorReturn = function (self, call) { if (true /* DEBUG */) { if (!self) { throw new ReferenceError(`this hasn't been initialized - super() hasn't been called`); } } return call !== null && typeof call === 'object' || typeof call === 'function' ? call : self; }; }); enifed('ember-testing/index', ['exports', 'ember-testing/lib/test', 'ember-testing/lib/adapters/adapter', 'ember-testing/lib/setup_for_testing', 'ember-testing/lib/adapters/qunit', 'ember-testing/lib/support', 'ember-testing/lib/ext/application', 'ember-testing/lib/ext/rsvp', 'ember-testing/lib/helpers', 'ember-testing/lib/initializers'], function (exports, _test, _adapter, _setup_for_testing, _qunit) { 'use strict'; exports.QUnitAdapter = exports.setupForTesting = exports.Adapter = exports.Test = undefined; Object.defineProperty(exports, 'Test', { enumerable: true, get: function () { return _test.default; } }); Object.defineProperty(exports, 'Adapter', { enumerable: true, get: function () { return _adapter.default; } }); Object.defineProperty(exports, 'setupForTesting', { enumerable: true, get: function () { return _setup_for_testing.default; } }); Object.defineProperty(exports, 'QUnitAdapter', { enumerable: true, get: function () { return _qunit.default; } }); }); enifed('ember-testing/lib/adapters/adapter', ['exports', '@ember/-internals/runtime'], function (exports, _runtime) { 'use strict'; function K() { return this; } /** @module @ember/test */ /** The primary purpose of this class is to create hooks that can be implemented by an adapter for various test frameworks. @class TestAdapter @public */ exports.default = _runtime.Object.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(error) { throw error; } }); }); enifed('ember-testing/lib/adapters/qunit', ['exports', '@ember/-internals/utils', 'ember-testing/lib/adapters/adapter'], function (exports, _utils, _adapter) { 'use strict'; exports.default = _adapter.default.extend({ init() { this.doneCallbacks = []; }, asyncStart() { if (typeof QUnit.stop === 'function') { // very old QUnit version QUnit.stop(); } else { this.doneCallbacks.push(QUnit.config.current ? QUnit.config.current.assert.async() : null); } }, asyncEnd() { // checking for QUnit.stop here (even though we _need_ QUnit.start) because // QUnit.start() still exists in QUnit 2.x (it just throws an error when calling // inside a test context) if (typeof QUnit.stop === 'function') { QUnit.start(); } else { let done = this.doneCallbacks.pop(); // This can be null if asyncStart() was called outside of a test if (done) { done(); } } }, exception(error) { QUnit.config.current.assert.ok(false, (0, _utils.inspect)(error)); } }); }); enifed('ember-testing/lib/events', ['exports', '@ember/runloop', '@ember/polyfills', 'ember-testing/lib/helpers/-is-form-control'], function (exports, _runloop, _polyfills, _isFormControl) { 'use strict'; exports.focus = focus; exports.fireEvent = fireEvent; const DEFAULT_EVENT_OPTIONS = { canBubble: true, cancelable: true }; const KEYBOARD_EVENT_TYPES = ['keydown', 'keypress', 'keyup']; const MOUSE_EVENT_TYPES = ['click', 'mousedown', 'mouseup', 'dblclick', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover']; function focus(el) { if (!el) { return; } if (el.isContentEditable || (0, _isFormControl.default)(el)) { let type = el.getAttribute('type'); if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') { (0, _runloop.run)(null, function () { let browserIsNotFocused = document.hasFocus && !document.hasFocus(); // makes `document.activeElement` be `element`. If the browser is focused, it also fires a focus event el.focus(); // Firefox does not trigger the `focusin` event if the window // does not have focus. If the document does not have focus then // fire `focusin` event as well. if (browserIsNotFocused) { // if the browser is not focused the previous `el.focus()` didn't fire an event, so we simulate it fireEvent(el, 'focus', { bubbles: false }); fireEvent(el, 'focusin'); } }); } } } function fireEvent(element, type, options = {}) { if (!element) { return; } let event; if (KEYBOARD_EVENT_TYPES.indexOf(type) > -1) { event = buildKeyboardEvent(type, options); } else if (MOUSE_EVENT_TYPES.indexOf(type) > -1) { let rect = element.getBoundingClientRect(); let x = rect.left + 1; let y = rect.top + 1; let simulatedCoordinates = { screenX: x + 5, screenY: y + 95, clientX: x, clientY: y }; event = buildMouseEvent(type, (0, _polyfills.assign)(simulatedCoordinates, options)); } else { event = buildBasicEvent(type, options); } element.dispatchEvent(event); } function buildBasicEvent(type, options = {}) { let event = document.createEvent('Events'); // Event.bubbles is read only let bubbles = options.bubbles !== undefined ? options.bubbles : true; let cancelable = options.cancelable !== undefined ? options.cancelable : true; delete options.bubbles; delete options.cancelable; event.initEvent(type, bubbles, cancelable); (0, _polyfills.assign)(event, options); return event; } function buildMouseEvent(type, options = {}) { let event; try { event = document.createEvent('MouseEvents'); let eventOpts = (0, _polyfills.assign)({}, 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, options = {}) { let event; try { event = document.createEvent('KeyEvents'); let eventOpts = (0, _polyfills.assign)({}, 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/lib/ext/application', ['@ember/application', 'ember-testing/lib/setup_for_testing', 'ember-testing/lib/test/helpers', 'ember-testing/lib/test/promise', 'ember-testing/lib/test/run', 'ember-testing/lib/test/on_inject_helpers', 'ember-testing/lib/test/adapter'], function (_application, _setup_for_testing, _helpers, _promise, _run, _on_inject_helpers, _adapter) { 'use strict'; _application.default.reopen({ /** This property contains the testing helpers for the current application. These are created once you call `injectTestHelpers` on your `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). `setupForTesting` should only be called after setting a custom `router` class (for example `App.Router = Router.extend(`). Example: ``` App.setupForTesting(); ``` @method setupForTesting @public */ setupForTesting() { (0, _setup_for_testing.default)(); this.testing = true; this.resolveRegistration('router:main').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(helperContainer) { if (helperContainer) { this.helperContainer = helperContainer; } else { this.helperContainer = window; } this.reopen({ willDestroy() { this._super(...arguments); this.removeTestHelpers(); } }); this.testHelpers = {}; for (let name in _helpers.helpers) { this.originalMethods[name] = this.helperContainer[name]; this.testHelpers[name] = this.helperContainer[name] = helper(this, name); protoWrap(_promise.default.prototype, name, helper(this, name), _helpers.helpers[name].meta.wait); } (0, _on_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() { if (!this.helperContainer) { return; } for (let name in _helpers.helpers) { this.helperContainer[name] = this.originalMethods[name]; delete _promise.default.prototype[name]; delete this.testHelpers[name]; delete this.originalMethods[name]; } } }); // This method is no longer needed // But still here for backwards compatibility // of helper chaining function protoWrap(proto, name, callback, isAsync) { proto[name] = function (...args) { if (isAsync) { return callback.apply(this, args); } else { return this.then(function () { return callback.apply(this, args); }); } }; } function helper(app, name) { let fn = _helpers.helpers[name].method; let meta = _helpers.helpers[name].meta; if (!meta.wait) { return (...args) => fn.apply(app, [app, ...args]); } return (...args) => { let lastPromise = (0, _run.default)(() => (0, _promise.resolve)((0, _promise.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. (0, _adapter.asyncStart)(); return lastPromise.then(() => fn.apply(app, [app, ...args])).finally(_adapter.asyncEnd); }; } }); enifed('ember-testing/lib/ext/rsvp', ['exports', '@ember/-internals/runtime', '@ember/runloop', '@ember/debug', 'ember-testing/lib/test/adapter'], function (exports, _runtime, _runloop, _debug, _adapter) { 'use strict'; _runtime.RSVP.configure('async', function (callback, promise) { // if schedule will cause autorun, we need to inform adapter if ((0, _debug.isTesting)() && !_runloop.backburner.currentInstance) { (0, _adapter.asyncStart)(); _runloop.backburner.schedule('actions', () => { (0, _adapter.asyncEnd)(); callback(promise); }); } else { _runloop.backburner.schedule('actions', () => callback(promise)); } }); exports.default = _runtime.RSVP; }); enifed('ember-testing/lib/helpers', ['ember-testing/lib/test/helpers', 'ember-testing/lib/helpers/and_then', 'ember-testing/lib/helpers/click', 'ember-testing/lib/helpers/current_path', 'ember-testing/lib/helpers/current_route_name', 'ember-testing/lib/helpers/current_url', 'ember-testing/lib/helpers/fill_in', 'ember-testing/lib/helpers/find', 'ember-testing/lib/helpers/find_with_assert', 'ember-testing/lib/helpers/key_event', 'ember-testing/lib/helpers/pause_test', 'ember-testing/lib/helpers/trigger_event', 'ember-testing/lib/helpers/visit', 'ember-testing/lib/helpers/wait'], function (_helpers, _and_then, _click, _current_path, _current_route_name, _current_url, _fill_in, _find, _find_with_assert, _key_event, _pause_test, _trigger_event, _visit, _wait) { 'use strict'; (0, _helpers.registerAsyncHelper)('visit', _visit.default); (0, _helpers.registerAsyncHelper)('click', _click.default); (0, _helpers.registerAsyncHelper)('keyEvent', _key_event.default); (0, _helpers.registerAsyncHelper)('fillIn', _fill_in.default); (0, _helpers.registerAsyncHelper)('wait', _wait.default); (0, _helpers.registerAsyncHelper)('andThen', _and_then.default); (0, _helpers.registerAsyncHelper)('pauseTest', _pause_test.pauseTest); (0, _helpers.registerAsyncHelper)('triggerEvent', _trigger_event.default); (0, _helpers.registerHelper)('find', _find.default); (0, _helpers.registerHelper)('findWithAssert', _find_with_assert.default); (0, _helpers.registerHelper)('currentRouteName', _current_route_name.default); (0, _helpers.registerHelper)('currentPath', _current_path.default); (0, _helpers.registerHelper)('currentURL', _current_url.default); (0, _helpers.registerHelper)('resumeTest', _pause_test.resumeTest); }); enifed('ember-testing/lib/helpers/-is-form-control', ['exports'], function (exports) { 'use strict'; exports.default = isFormControl; const FORM_CONTROL_TAGS = ['INPUT', 'BUTTON', 'SELECT', 'TEXTAREA']; /** @private @param {Element} element the element to check @returns {boolean} `true` when the element is a form control, `false` otherwise */ function isFormControl(element) { let { tagName, type } = element; if (type === 'hidden') { return false; } return FORM_CONTROL_TAGS.indexOf(tagName) > -1; } }); enifed("ember-testing/lib/helpers/and_then", ["exports"], function (exports) { "use strict"; exports.default = andThen; function andThen(app, callback) { return app.testHelpers.wait(callback(app)); } }); enifed('ember-testing/lib/helpers/click', ['exports', 'ember-testing/lib/events'], function (exports, _events) { 'use strict'; exports.default = click; /** 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 */ function click(app, selector, context) { let $el = app.testHelpers.findWithAssert(selector, context); let el = $el[0]; (0, _events.fireEvent)(el, 'mousedown'); (0, _events.focus)(el); (0, _events.fireEvent)(el, 'mouseup'); (0, _events.fireEvent)(el, 'click'); return app.testHelpers.wait(); } /** @module ember */ }); enifed('ember-testing/lib/helpers/current_path', ['exports', '@ember/-internals/metal'], function (exports, _metal) { 'use strict'; exports.default = currentPath; /** 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 */ function currentPath(app) { let routingService = app.__container__.lookup('service:-routing'); return (0, _metal.get)(routingService, 'currentPath'); } /** @module ember */ }); enifed('ember-testing/lib/helpers/current_route_name', ['exports', '@ember/-internals/metal'], function (exports, _metal) { '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) { let routingService = app.__container__.lookup('service:-routing'); return (0, _metal.get)(routingService, 'currentRouteName'); } /** @module ember */ }); enifed('ember-testing/lib/helpers/current_url', ['exports', '@ember/-internals/metal'], function (exports, _metal) { 'use strict'; exports.default = currentURL; /** 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 */ function currentURL(app) { let router = app.__container__.lookup('router:main'); return (0, _metal.get)(router, 'location').getURL(); } /** @module ember */ }); enifed('ember-testing/lib/helpers/fill_in', ['exports', 'ember-testing/lib/events', 'ember-testing/lib/helpers/-is-form-control'], function (exports, _events, _isFormControl) { 'use strict'; exports.default = fillIn; /** 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 */ /** @module ember */ function fillIn(app, selector, contextOrText, text) { let $el, el, context; if (text === undefined) { text = contextOrText; } else { context = contextOrText; } $el = app.testHelpers.findWithAssert(selector, context); el = $el[0]; (0, _events.focus)(el); if ((0, _isFormControl.default)(el)) { el.value = text; } else { el.innerHTML = text; } (0, _events.fireEvent)(el, 'input'); (0, _events.fireEvent)(el, 'change'); return app.testHelpers.wait(); } }); enifed('ember-testing/lib/helpers/find', ['exports', '@ember/-internals/metal', '@ember/debug', '@ember/-internals/views'], function (exports, _metal, _debug, _views) { 'use strict'; exports.default = find; /** 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'); ``` With the `context` param: ```javascript var $el = find('.my-selector', '.parent-element-class'); ``` @method find @param {String} selector jQuery selector for element lookup @param {String} [context] (optional) jQuery selector that will limit the selector argument to find only within the context's children @return {Object} DOM element representing the results of the query @public */ function find(app, selector, context) { if (_views.jQueryDisabled) { true && !false && (0, _debug.assert)('If jQuery is disabled, please import and use helpers from @ember/test-helpers [https://github.com/emberjs/ember-test-helpers]. Note: `find` is not an available helper.'); } let $el; context = context || (0, _metal.get)(app, 'rootElement'); $el = app.$(selector, context); return $el; } /** @module ember */ }); enifed('ember-testing/lib/helpers/find_with_assert', ['exports'], function (exports) { 'use strict'; exports.default = findWithAssert; /** @module ember */ /** Like `find`, but throws an error if the element selector returns no results. Example: ```javascript var $el = findWithAssert('.doesnt-exist'); // throws error ``` With the `context` param: ```javascript var $el = findWithAssert('.selector-id', '.parent-element-class'); // assert will pass ``` @method findWithAssert @param {String} selector jQuery selector string for finding an element within the DOM @param {String} [context] (optional) jQuery selector that will limit the selector argument to find only within the context's children @return {Object} jQuery object representing the results of the query @throws {Error} throws error if object returned has a length of 0 @public */ function findWithAssert(app, selector, context) { let $el = app.testHelpers.find(selector, context); if ($el.length === 0) { throw new Error('Element ' + selector + ' not found.'); } return $el; } }); enifed("ember-testing/lib/helpers/key_event", ["exports"], function (exports) { "use strict"; exports.default = keyEvent; /** @module ember */ /** 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 */ function keyEvent(app, selector, contextOrType, typeOrKeyCode, keyCode) { let context, type; if (keyCode === undefined) { context = null; keyCode = typeOrKeyCode; type = contextOrType; } else { context = contextOrType; type = typeOrKeyCode; } return app.testHelpers.triggerEvent(selector, context, type, { keyCode, which: keyCode }); } }); enifed('ember-testing/lib/helpers/pause_test', ['exports', '@ember/-internals/runtime', '@ember/debug'], function (exports, _runtime, _debug) { 'use strict'; exports.resumeTest = resumeTest; exports.pauseTest = pauseTest; /** @module ember */ let resume; /** Resumes a test paused by `pauseTest`. @method resumeTest @return {void} @public */ function resumeTest() { true && !resume && (0, _debug.assert)('Testing has not been paused. There is nothing to resume.', resume); resume(); resume = undefined; } /** 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'); ``` You may want to turn off the timeout before pausing. qunit (as of 2.4.0): ``` visit('/'); assert.timeout(0); return pauseTest(); click('.btn'); ``` mocha: ``` visit('/'); this.timeout(0); return pauseTest(); click('.btn'); ``` @since 1.9.0 @method pauseTest @return {Object} A promise that will never resolve @public */ function pauseTest() { (0, _debug.info)('Testing paused. Use `resumeTest()` to continue.'); return new _runtime.RSVP.Promise(resolve => { resume = resolve; }, 'TestAdapter paused promise'); } }); enifed('ember-testing/lib/helpers/trigger_event', ['exports', 'ember-testing/lib/events'], function (exports, _events) { '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) { let arity = arguments.length; let context, type, options; 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; } let $el = app.testHelpers.findWithAssert(selector, context); let el = $el[0]; (0, _events.fireEvent)(el, type, options); return app.testHelpers.wait(); } /** @module ember */ }); enifed('ember-testing/lib/helpers/visit', ['exports', '@ember/runloop'], function (exports, _runloop) { 'use strict'; exports.default = visit; /** 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 */ function visit(app, url) { let router = app.__container__.lookup('router:main'); let shouldHandleURL = false; app.boot().then(() => { router.location.setURL(url); if (shouldHandleURL) { (0, _runloop.run)(app.__deprecatedInstance__, 'handleURL', url); } }); if (app._readinessDeferrals > 0) { router.initialURL = url; (0, _runloop.run)(app, 'advanceReadiness'); delete router.initialURL; } else { shouldHandleURL = true; } return app.testHelpers.wait(); } }); enifed('ember-testing/lib/helpers/wait', ['exports', 'ember-testing/lib/test/waiters', '@ember/-internals/runtime', '@ember/runloop', 'ember-testing/lib/test/pending_requests'], function (exports, _waiters, _runtime, _runloop, _pending_requests) { 'use strict'; exports.default = wait; /** 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). However, there is a method to register a test helper which utilizes this method without the need to actually call `wait()` in your helpers. The `wait` helper is built into `registerAsyncHelper` by default. You will not need to `return app.testHelpers.wait();` - the wait behavior is provided for you. Example: ```javascript import { registerAsyncHelper } from '@ember/test'; registerAsyncHelper('loginUser', function(app, username, password) { visit('secured/path/here') .fillIn('#username', username) .fillIn('#password', password) .click('.submit'); }); ``` @method wait @param {Object} value The value to be returned. @return {RSVP.Promise} Promise that resolves to the passed value. @public @since 1.0.0 */ /** @module ember */ function wait(app, value) { return new _runtime.RSVP.Promise(function (resolve) { let router = app.__container__.lookup('router:main'); // Every 10ms, poll for the async thing to have finished let watcher = setInterval(() => { // 1. If the router is loading, keep polling let routerIsLoading = router._routerMicrolib && !!router._routerMicrolib.activeTransition; if (routerIsLoading) { return; } // 2. If there are pending Ajax requests, keep polling if ((0, _pending_requests.pendingRequests)()) { return; } // 3. If there are scheduled timers or we are inside of a run loop, keep polling if ((0, _runloop.hasScheduledTimers)() || (0, _runloop.getCurrentRunLoop)()) { return; } if ((0, _waiters.checkWaiters)()) { return; } // Stop polling clearInterval(watcher); // Synchronously resolve the promise (0, _runloop.run)(null, resolve, value); }, 10); }); } }); enifed('ember-testing/lib/initializers', ['@ember/application'], function (_application) { 'use strict'; let name = 'deferReadiness in `testing` mode'; (0, _application.onLoad)('Ember.Application', function (Application) { if (!Application.initializers[name]) { Application.initializer({ name: name, initialize(application) { if (application.testing) { application.deferReadiness(); } } }); } }); }); enifed('ember-testing/lib/setup_for_testing', ['exports', '@ember/debug', '@ember/-internals/views', 'ember-testing/lib/test/adapter', 'ember-testing/lib/test/pending_requests', 'ember-testing/lib/adapters/adapter', 'ember-testing/lib/adapters/qunit'], function (exports, _debug, _views, _adapter, _pending_requests, _adapter2, _qunit) { '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 */ /* global self */ function setupForTesting() { (0, _debug.setTesting)(true); let adapter = (0, _adapter.getAdapter)(); // if adapter is not manually set default to QUnit if (!adapter) { (0, _adapter.setAdapter)(typeof self.QUnit === 'undefined' ? _adapter2.default.create() : _qunit.default.create()); } if (!_views.jQueryDisabled) { (0, _views.jQuery)(document).off('ajaxSend', _pending_requests.incrementPendingRequests); (0, _views.jQuery)(document).off('ajaxComplete', _pending_requests.decrementPendingRequests); (0, _pending_requests.clearPendingRequests)(); (0, _views.jQuery)(document).on('ajaxSend', _pending_requests.incrementPendingRequests); (0, _views.jQuery)(document).on('ajaxComplete', _pending_requests.decrementPendingRequests); } } }); enifed('ember-testing/lib/support', ['@ember/debug', '@ember/-internals/views', '@ember/-internals/browser-environment'], function (_debug, _views, _browserEnvironment) { 'use strict'; /** @module ember */ const $ = _views.jQuery; /** 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) { let input = document.createElement('input'); $(input).attr('type', 'checkbox').css({ position: 'absolute', left: '-1000px', top: '-1000px' }).appendTo('body').on('click', handler).trigger('click').remove(); } if (_browserEnvironment.hasDOM && !_views.jQueryDisabled) { $(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() { if (this.nodeName === 'INPUT' && this.type === 'checkbox' && this.click) { this.click(); return false; } } }; } }); // Try again to verify that the patch took effect or blow up. testCheckboxClick(function () { true && (0, _debug.warn)("clicked checkboxes should be checked! the jQuery patch didn't work", this.checked, { id: 'ember-testing.test-checkbox-click' }); }); }); } }); enifed('ember-testing/lib/test', ['exports', 'ember-testing/lib/test/helpers', 'ember-testing/lib/test/on_inject_helpers', 'ember-testing/lib/test/promise', 'ember-testing/lib/test/waiters', 'ember-testing/lib/test/adapter'], function (exports, _helpers, _on_inject_helpers, _promise, _waiters, _adapter) { '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 */ const Test = { /** Hash containing all known test helpers. @property _helpers @private @since 1.7.0 */ _helpers: _helpers.helpers, registerHelper: _helpers.registerHelper, registerAsyncHelper: _helpers.registerAsyncHelper, unregisterHelper: _helpers.unregisterHelper, onInjectHelpers: _on_inject_helpers.onInjectHelpers, Promise: _promise.default, promise: _promise.promise, resolve: _promise.resolve, registerWaiter: _waiters.registerWaiter, unregisterWaiter: _waiters.unregisterWaiter, checkWaiters: _waiters.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 */ /** @module ember */ Object.defineProperty(Test, 'adapter', { get: _adapter.getAdapter, set: _adapter.setAdapter }); exports.default = Test; }); enifed('ember-testing/lib/test/adapter', ['exports', '@ember/-internals/error-handling'], function (exports, _errorHandling) { 'use strict'; exports.getAdapter = getAdapter; exports.setAdapter = setAdapter; exports.asyncStart = asyncStart; exports.asyncEnd = asyncEnd; let adapter; function getAdapter() { return adapter; } function setAdapter(value) { adapter = value; if (value && typeof value.exception === 'function') { (0, _errorHandling.setDispatchOverride)(adapterDispatch); } else { (0, _errorHandling.setDispatchOverride)(null); } } function asyncStart() { if (adapter) { adapter.asyncStart(); } } function asyncEnd() { if (adapter) { adapter.asyncEnd(); } } function adapterDispatch(error) { adapter.exception(error); console.error(error.stack); // eslint-disable-line no-console } }); enifed('ember-testing/lib/test/helpers', ['exports', 'ember-testing/lib/test/promise'], function (exports, _promise) { 'use strict'; exports.helpers = undefined; exports.registerHelper = registerHelper; exports.registerAsyncHelper = registerAsyncHelper; exports.unregisterHelper = unregisterHelper; const helpers = exports.helpers = {}; /** @module @ember/test */ /** `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 import { registerHelper } from '@ember/test'; import { run } from '@ember/runloop'; registerHelper('boot', function(app) { run(app, app.advanceReadiness); }); ``` This helper can later be called without arguments because it will be called with `app` as the first parameter. ```javascript import Application from '@ember/application'; App = Application.create(); App.injectTestHelpers(); boot(); ``` @public @for @ember/test @static @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 import { registerAsyncHelper } from '@ember/test'; import { run } from '@ember/runloop'; registerAsyncHelper('boot', function(app) { 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 import { registerAsyncHelper } from '@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 import { unregisterHelper } from '@ember/test'; unregisterHelper('wait'); ``` @public @method unregisterHelper @static @for @ember/test @param {String} name The helper to remove. */ function unregisterHelper(name) { delete helpers[name]; delete _promise.default.prototype[name]; } }); enifed("ember-testing/lib/test/on_inject_helpers", ["exports"], function (exports) { "use strict"; exports.onInjectHelpers = onInjectHelpers; exports.invokeInjectHelpersCallbacks = invokeInjectHelpersCallbacks; const callbacks = exports.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 import $ from 'jquery'; Ember.Test.onInjectHelpers(function() { $(document).ajaxSend(function() { Test.pendingRequests++; }); $(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 (let i = 0; i < callbacks.length; i++) { callbacks[i](app); } } }); enifed("ember-testing/lib/test/pending_requests", ["exports"], function (exports) { "use strict"; exports.pendingRequests = pendingRequests; exports.clearPendingRequests = clearPendingRequests; exports.incrementPendingRequests = incrementPendingRequests; exports.decrementPendingRequests = decrementPendingRequests; let requests = []; function pendingRequests() { return requests.length; } function clearPendingRequests() { requests.length = 0; } function incrementPendingRequests(_, xhr) { requests.push(xhr); } function decrementPendingRequests(_, xhr) { setTimeout(function () { for (let i = 0; i < requests.length; i++) { if (xhr === requests[i]) { requests.splice(i, 1); break; } } }, 0); } }); enifed('ember-testing/lib/test/promise', ['exports', '@ember/-internals/runtime', 'ember-testing/lib/test/run'], function (exports, _runtime, _run) { 'use strict'; exports.promise = promise; exports.resolve = resolve; exports.getLastPromise = getLastPromise; let lastPromise; class TestPromise extends _runtime.RSVP.Promise { constructor() { super(...arguments); lastPromise = this; } then(_onFulfillment, ...args) { let onFulfillment = typeof _onFulfillment === 'function' ? result => isolate(_onFulfillment, result) : undefined; return super.then(onFulfillment, ...args); } } exports.default = TestPromise; /** 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. */ function promise(resolver, label) { let fullLabel = `Ember.Test.promise: ${label || ''}`; 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, label) { return TestPromise.resolve(result, label); } 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; let value = onFulfillment(result); let 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 (0, _run.default)(() => resolve(promise).then(() => value)); } } }); enifed('ember-testing/lib/test/run', ['exports', '@ember/runloop'], function (exports, _runloop) { 'use strict'; exports.default = run; function run(fn) { if (!(0, _runloop.getCurrentRunLoop)()) { return (0, _runloop.run)(fn); } else { return fn(); } } }); enifed("ember-testing/lib/test/waiters", ["exports"], function (exports) { "use strict"; exports.registerWaiter = registerWaiter; exports.unregisterWaiter = unregisterWaiter; exports.checkWaiters = checkWaiters; /** @module @ember/test */ const contexts = []; const 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. The waiter runs periodically after each async helper (i.e. `click`, `andThen`, `visit`, etc) has executed, until the returning result is truthy. After the waiters finish, the next async helper is executed and the process repeats. For example: ```javascript import { registerWaiter } from '@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 import { registerWaiter } from '@ember/test'; registerWaiter(MyDB, MyDB.hasPendingTransactions); ``` @public @for @ember/test @static @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 @static @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; } let 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 (let i = 0; i < callbacks.length; i++) { let context = contexts[i]; let callback = callbacks[i]; if (!callback.call(context)) { return true; } } return false; } function indexOf(context, callback) { for (let i = 0; i < callbacks.length; i++) { if (callbacks[i] === callback && contexts[i] === context) { return i; } } return -1; } }); enifed('ember/index', ['exports', 'require', '@ember/-internals/environment', 'node-module', '@ember/-internals/utils', '@ember/-internals/container', '@ember/instrumentation', '@ember/-internals/meta', '@ember/-internals/metal', '@ember/canary-features', '@ember/debug', 'backburner', '@ember/-internals/console', '@ember/controller', '@ember/controller/lib/controller_mixin', '@ember/string', '@ember/service', '@ember/object/computed', '@ember/-internals/runtime', '@ember/-internals/glimmer', 'ember/version', '@ember/-internals/views', '@ember/-internals/routing', '@ember/-internals/extension-support', '@ember/error', '@ember/runloop', '@ember/-internals/error-handling', '@ember/-internals/owner', '@ember/application', '@ember/application/globals-resolver', '@ember/application/instance', '@ember/engine', '@ember/engine/instance', '@ember/map', '@ember/map/with-default', '@ember/map/lib/ordered-set', '@ember/polyfills', '@ember/deprecated-features'], function (exports, _require2, _environment, _nodeModule, _utils, _container, _instrumentation, _meta, _metal, _canaryFeatures, _debug, _backburner, _console, _controller, _controller_mixin, _string, _service, _computed, _runtime, _glimmer, _version, _views, _routing, _extensionSupport, _error, _runloop, _errorHandling, _owner, _application, _globalsResolver, _instance, _engine, _instance2, _map, _withDefault, _orderedSet, _polyfills, _deprecatedFeatures) { 'use strict'; // ****@ember/-internals/environment**** // eslint-disable-next-line import/no-unresolved const Ember = typeof _environment.context.imports.Ember === 'object' && _environment.context.imports.Ember || {}; Ember.isNamespace = true; Ember.toString = function () { return 'Ember'; }; Object.defineProperty(Ember, 'ENV', { get: _environment.getENV, enumerable: false }); Object.defineProperty(Ember, 'lookup', { get: _environment.getLookup, set: _environment.setLookup, enumerable: false }); if (_deprecatedFeatures.EMBER_EXTEND_PROTOTYPES) { Object.defineProperty(Ember, 'EXTEND_PROTOTYPES', { enumerable: false, get() { true && !false && (0, _debug.deprecate)('Accessing Ember.EXTEND_PROTOTYPES is deprecated, please migrate to Ember.ENV.EXTEND_PROTOTYPES', false, { id: 'ember-env.old-extend-prototypes', until: '4.0.0' }); return _environment.ENV.EXTEND_PROTOTYPES; } }); } // ****@ember/application**** Ember.getOwner = _owner.getOwner; Ember.setOwner = _owner.setOwner; Ember.Application = _application.default; Ember.DefaultResolver = Ember.Resolver = _globalsResolver.default; Ember.ApplicationInstance = _instance.default; // ****@ember/engine**** Ember.Engine = _engine.default; Ember.EngineInstance = _instance2.default; // ****@ember/map**** Ember.OrderedSet = _orderedSet.default; Ember.__OrderedSet__ = _orderedSet.__OrderedSet__; Ember.Map = _map.default; Ember.MapWithDefault = _withDefault.default; // ****@ember/polyfills**** Ember.assign = _polyfills.assign; Ember.merge = _polyfills.merge; // ****@ember/-internals/utils**** Ember.generateGuid = _utils.generateGuid; Ember.GUID_KEY = _utils.GUID_KEY; Ember.guidFor = _utils.guidFor; Ember.inspect = _utils.inspect; Ember.makeArray = _utils.makeArray; Ember.canInvoke = _utils.canInvoke; Ember.tryInvoke = _utils.tryInvoke; Ember.wrap = _utils.wrap; Ember.uuid = _utils.uuid; Ember.NAME_KEY = _utils.NAME_KEY; Ember._Cache = _utils.Cache; // ****@ember/-internals/container**** Ember.Container = _container.Container; Ember.Registry = _container.Registry; // ****@ember/debug**** Ember.assert = _debug.assert; Ember.warn = _debug.warn; Ember.debug = _debug.debug; Ember.deprecate = _debug.deprecate; Ember.deprecateFunc = _debug.deprecateFunc; Ember.runInDebug = _debug.runInDebug; // ****@ember/error**** Ember.Error = _error.default; /** @public @class Ember.Debug */ Ember.Debug = { registerDeprecationHandler: _debug.registerDeprecationHandler, registerWarnHandler: _debug.registerWarnHandler }; // ****@ember/instrumentation**** Ember.instrument = _instrumentation.instrument; Ember.subscribe = _instrumentation.subscribe; Ember.Instrumentation = { instrument: _instrumentation.instrument, subscribe: _instrumentation.subscribe, unsubscribe: _instrumentation.unsubscribe, reset: _instrumentation.reset }; // ****@ember/runloop**** // Using _globalsRun here so that mutating the function (adding // `next`, `later`, etc to it) is only available in globals builds Ember.run = _runloop._globalsRun; Ember.run.backburner = _runloop.backburner; Ember.run.begin = _runloop.begin; Ember.run.bind = _runloop.bind; Ember.run.cancel = _runloop.cancel; Ember.run.debounce = _runloop.debounce; Ember.run.end = _runloop.end; Ember.run.hasScheduledTimers = _runloop.hasScheduledTimers; Ember.run.join = _runloop.join; Ember.run.later = _runloop.later; Ember.run.next = _runloop.next; Ember.run.once = _runloop.once; Ember.run.schedule = _runloop.schedule; Ember.run.scheduleOnce = _runloop.scheduleOnce; Ember.run.throttle = _runloop.throttle; Ember.run.cancelTimers = _runloop.cancelTimers; Object.defineProperty(Ember.run, 'currentRunLoop', { get: _runloop.getCurrentRunLoop, enumerable: false }); // ****@ember/-internals/metal**** // Using _globalsComputed here so that mutating the function is only available // in globals builds const computed = _metal._globalsComputed; Ember.computed = computed; computed.alias = _metal.alias; Ember.ComputedProperty = _metal.ComputedProperty; Ember.cacheFor = _metal.getCachedValueFor; Ember.meta = _meta.meta; Ember.get = _metal.get; Ember.getWithDefault = _metal.getWithDefault; Ember._getPath = _metal._getPath; Ember.set = _metal.set; Ember.trySet = _metal.trySet; Ember.FEATURES = (0, _polyfills.assign)({ isEnabled: _canaryFeatures.isEnabled }, _canaryFeatures.FEATURES); Ember._Cache = _utils.Cache; Ember.on = _metal.on; Ember.addListener = _metal.addListener; Ember.removeListener = _metal.removeListener; Ember.sendEvent = _metal.sendEvent; Ember.hasListeners = _metal.hasListeners; Ember.isNone = _metal.isNone; Ember.isEmpty = _metal.isEmpty; Ember.isBlank = _metal.isBlank; Ember.isPresent = _metal.isPresent; if (_deprecatedFeatures.PROPERTY_WILL_CHANGE) { Ember.propertyWillChange = _metal.propertyWillChange; } if (_deprecatedFeatures.PROPERTY_DID_CHANGE) { Ember.propertyDidChange = _metal.propertyDidChange; } Ember.notifyPropertyChange = _metal.notifyPropertyChange; Ember.overrideChains = _metal.overrideChains; Ember.beginPropertyChanges = _metal.beginPropertyChanges; Ember.endPropertyChanges = _metal.endPropertyChanges; Ember.changeProperties = _metal.changeProperties; Ember.platform = { defineProperty: true, hasPropertyAccessors: true }; Ember.defineProperty = _metal.defineProperty; Ember.watchKey = _metal.watchKey; Ember.unwatchKey = _metal.unwatchKey; Ember.removeChainWatcher = _metal.removeChainWatcher; Ember._ChainNode = _metal.ChainNode; Ember.finishChains = _metal.finishChains; Ember.watchPath = _metal.watchPath; Ember.unwatchPath = _metal.unwatchPath; Ember.watch = _metal.watch; Ember.isWatching = _metal.isWatching; Ember.unwatch = _metal.unwatch; Ember.destroy = _meta.deleteMeta; Ember.libraries = _metal.libraries; Ember.getProperties = _metal.getProperties; Ember.setProperties = _metal.setProperties; Ember.expandProperties = _metal.expandProperties; Ember.addObserver = _metal.addObserver; Ember.removeObserver = _metal.removeObserver; Ember.aliasMethod = _metal.aliasMethod; Ember.observer = _metal.observer; Ember.mixin = _metal.mixin; Ember.Mixin = _metal.Mixin; /** 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 import $ from 'jquery'; Ember.onerror = function(error) { $.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(Ember, 'onerror', { get: _errorHandling.getOnerror, set: _errorHandling.setOnerror, enumerable: false }); Object.defineProperty(Ember, 'testing', { get: _debug.isTesting, set: _debug.setTesting, enumerable: false }); Ember._Backburner = _backburner.default; // ****@ember/-internals/console**** if (_deprecatedFeatures.LOGGER) { Ember.Logger = _console.default; } // ****@ember/-internals/runtime**** Ember.A = _runtime.A; Ember.String = { loc: _string.loc, w: _string.w, dasherize: _string.dasherize, decamelize: _string.decamelize, camelize: _string.camelize, classify: _string.classify, underscore: _string.underscore, capitalize: _string.capitalize }; Ember.Object = _runtime.Object; Ember._RegistryProxyMixin = _runtime.RegistryProxyMixin; Ember._ContainerProxyMixin = _runtime.ContainerProxyMixin; Ember.compare = _runtime.compare; Ember.copy = _runtime.copy; Ember.isEqual = _runtime.isEqual; /** @module ember */ /** Namespace for injection helper methods. @class inject @namespace Ember @static @public */ Ember.inject = function inject() { true && !false && (0, _debug.assert)(`Injected properties must be created through helpers, see '${Object.keys(inject).map(k => `'inject.${k}'`).join(' or ')}'`); }; Ember.inject.service = _service.inject; Ember.inject.controller = _controller.inject; Ember.Array = _runtime.Array; Ember.Comparable = _runtime.Comparable; Ember.Enumerable = _runtime.Enumerable; Ember.ArrayProxy = _runtime.ArrayProxy; Ember.ObjectProxy = _runtime.ObjectProxy; Ember.ActionHandler = _runtime.ActionHandler; Ember.CoreObject = _runtime.CoreObject; Ember.NativeArray = _runtime.NativeArray; Ember.Copyable = _runtime.Copyable; Ember.MutableEnumerable = _runtime.MutableEnumerable; Ember.MutableArray = _runtime.MutableArray; Ember.TargetActionSupport = _runtime.TargetActionSupport; Ember.Evented = _runtime.Evented; Ember.PromiseProxyMixin = _runtime.PromiseProxyMixin; Ember.Observable = _runtime.Observable; Ember.typeOf = _runtime.typeOf; Ember.isArray = _runtime.isArray; Ember.Object = _runtime.Object; Ember.onLoad = _application.onLoad; Ember.runLoadHooks = _application.runLoadHooks; Ember.Controller = _controller.default; Ember.ControllerMixin = _controller_mixin.default; Ember.Service = _service.default; Ember._ProxyMixin = _runtime._ProxyMixin; Ember.RSVP = _runtime.RSVP; Ember.Namespace = _runtime.Namespace; computed.empty = _computed.empty; computed.notEmpty = _computed.notEmpty; computed.none = _computed.none; computed.not = _computed.not; computed.bool = _computed.bool; computed.match = _computed.match; computed.equal = _computed.equal; computed.gt = _computed.gt; computed.gte = _computed.gte; computed.lt = _computed.lt; computed.lte = _computed.lte; computed.oneWay = _computed.oneWay; computed.reads = _computed.oneWay; computed.readOnly = _computed.readOnly; computed.deprecatingAlias = _computed.deprecatingAlias; computed.and = _computed.and; computed.or = _computed.or; computed.sum = _computed.sum; computed.min = _computed.min; computed.max = _computed.max; computed.map = _computed.map; computed.sort = _computed.sort; computed.setDiff = _computed.setDiff; computed.mapBy = _computed.mapBy; computed.filter = _computed.filter; computed.filterBy = _computed.filterBy; computed.uniq = _computed.uniq; computed.uniqBy = _computed.uniqBy; computed.union = _computed.union; computed.intersect = _computed.intersect; computed.collect = _computed.collect; /** Defines the hash of localized strings for the current language. Used by the `String.loc` helper. To localize, add string values to this hash. @property STRINGS @for Ember @type Object @private */ Object.defineProperty(Ember, 'STRINGS', { configurable: false, get: _string._getStrings, set: _string._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(Ember, 'BOOTED', { configurable: false, enumerable: false, get: _metal.isNamespaceSearchDisabled, set: _metal.setNamespaceSearchDisabled }); // ****@ember/-internals/glimmer**** Ember.Component = _glimmer.Component; _glimmer.Helper.helper = _glimmer.helper; Ember.Helper = _glimmer.Helper; Ember.Checkbox = _glimmer.Checkbox; Ember.TextField = _glimmer.TextField; Ember.TextArea = _glimmer.TextArea; Ember.LinkComponent = _glimmer.LinkComponent; Ember._setComponentManager = _glimmer.setComponentManager; Ember._componentManagerCapabilities = _glimmer.capabilities; Ember.Handlebars = { template: _glimmer.template, Utils: { escapeExpression: _glimmer.escapeExpression } }; Ember.HTMLBars = { template: _glimmer.template }; if (_environment.ENV.EXTEND_PROTOTYPES.String) { String.prototype.htmlSafe = function () { return (0, _glimmer.htmlSafe)(this); }; } Ember.String.htmlSafe = _glimmer.htmlSafe; Ember.String.isHTMLSafe = _glimmer.isHTMLSafe; /** 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(Ember, 'TEMPLATES', { get: _glimmer.getTemplates, set: _glimmer.setTemplates, configurable: false, enumerable: false }); /** The semantic version @property VERSION @type String @public */ Ember.VERSION = _version.default; // ****@ember/-internals/views**** if (!_views.jQueryDisabled) { Ember.$ = _views.jQuery; } Ember.ViewUtils = { isSimpleClick: _views.isSimpleClick, getViewElement: _views.getViewElement, getViewBounds: _views.getViewBounds, getViewClientRects: _views.getViewClientRects, getViewBoundingClientRect: _views.getViewBoundingClientRect, getRootViews: _views.getRootViews, getChildViews: _views.getChildViews, isSerializationFirstNode: _glimmer.isSerializationFirstNode }; Ember.TextSupport = _views.TextSupport; Ember.ComponentLookup = _views.ComponentLookup; Ember.EventDispatcher = _views.EventDispatcher; // ****@ember/-internals/routing**** Ember.Location = _routing.Location; Ember.AutoLocation = _routing.AutoLocation; Ember.HashLocation = _routing.HashLocation; Ember.HistoryLocation = _routing.HistoryLocation; Ember.NoneLocation = _routing.NoneLocation; Ember.controllerFor = _routing.controllerFor; Ember.generateControllerFactory = _routing.generateControllerFactory; Ember.generateController = _routing.generateController; Ember.RouterDSL = _routing.RouterDSL; Ember.Router = _routing.Router; Ember.Route = _routing.Route; (0, _application.runLoadHooks)('Ember.Application', _application.default); Ember.DataAdapter = _extensionSupport.DataAdapter; Ember.ContainerDebugAdapter = _extensionSupport.ContainerDebugAdapter; if ((0, _require2.has)('ember-template-compiler')) { (0, _require2.default)('ember-template-compiler'); } // do this to ensure that Ember.Test is defined properly on the global // if it is present. if ((0, _require2.has)('ember-testing')) { let testing = (0, _require2.default)('ember-testing'); Ember.Test = testing.Test; Ember.Test.Adapter = testing.Adapter; Ember.Test.QUnitAdapter = testing.QUnitAdapter; Ember.setupForTesting = testing.setupForTesting; } (0, _application.runLoadHooks)('Ember'); exports.default = Ember; if (_nodeModule.IS_NODE) { _nodeModule.module.exports = Ember; } else { _environment.context.exports.Ember = _environment.context.exports.Em = Ember; } /** @module jquery @public */ /** @class jquery @public @static */ /** Alias for jQuery @for jquery @method $ @static @public */ }); enifed("ember/version", ["exports"], function (exports) { "use strict"; exports.default = "3.6.0"; }); /*global enifed, module */ enifed('node-module', ['exports'], function(_exports) { var IS_NODE = typeof module === 'object' && typeof module.require === 'function'; if (IS_NODE) { _exports.require = module.require; _exports.module = module; _exports.IS_NODE = IS_NODE; } else { _exports.require = null; _exports.module = null; _exports.IS_NODE = IS_NODE; } }); enifed("route-recognizer", ["exports"], function (exports) { "use strict"; var createObject = Object.create; function createMap() { var map = createObject(null); map["__"] = undefined; delete map["__"]; return map; } var Target = function Target(path, matcher, delegate) { this.path = path; this.matcher = matcher; this.delegate = delegate; }; Target.prototype.to = function to(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); } }; var Matcher = function Matcher(target) { this.routes = createMap(); this.children = createMap(); this.target = target; }; Matcher.prototype.add = function add(path, target) { this.routes[path] = target; }; Matcher.prototype.addChild = function addChild(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) { function match(path, callback) { var fullPath = startingPath + path; if (callback) { callback(generateMatch(fullPath, matcher, delegate)); } else { return new Target(fullPath, matcher, delegate); } } return match; } 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; var paths = Object.keys(routes); for (var i = 0; i < paths.length; i++) { var path = paths[i]; var routeArray = baseRoute.slice(); addRoute(routeArray, path, routes[path]); var nested = matcher.children[path]; if (nested) { eachRoute(routeArray, nested, callback, binding); } else { callback.call(binding, routeArray); } } } var map = function (callback, addRouteCallback) { var matcher = new Matcher(); callback(generateMatch("", matcher, this.delegate)); eachRoute([], matcher, function (routes) { if (addRouteCallback) { addRouteCallback(this, routes); } else { this.add(routes); } }, 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. // Normalizes percent-encoded values in `path` to upper-case and decodes percent-encoded 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) { if (segment.length < 3 || segment.indexOf("%") === -1) { return 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 = /%(?:2(?:4|6|B|C)|3(?:B|D|A)|40)/g; function encodePathSegment(str) { return encodeURIComponent(str).replace(PATH_SEGMENT_ENCODINGS, decodeURIComponent); } var escapeRegex = /(\/|\.|\*|\+|\?|\||\(|\)|\[|\]|\{|\}|\\)/g; var isArray = Array.isArray; var hasOwnProperty = Object.prototype.hasOwnProperty; function getParam(params, key) { if (typeof params !== "object" || params === null) { throw new Error("You must pass an object as the second argument to `generate`."); } if (!hasOwnProperty.call(params, key)) { throw new Error("You must provide param `" + key + "` to `generate`."); } var value = params[key]; var str = typeof value === "string" ? value : "" + value; if (str.length === 0) { throw new Error("You must provide a param `" + key + "`."); } return str; } var eachChar = []; eachChar[0 /* Static */] = function (segment, currentState) { var state = currentState; var value = segment.value; for (var i = 0; i < value.length; i++) { var ch = value.charCodeAt(i); state = state.put(ch, false, false); } return state; }; eachChar[1 /* Dynamic */] = function (_, currentState) { return currentState.put(47 /* SLASH */, true, true); }; eachChar[2 /* Star */] = function (_, currentState) { return currentState.put(-1 /* ANY */, false, true); }; eachChar[4 /* Epsilon */] = function (_, currentState) { return currentState; }; var regex = []; regex[0 /* Static */] = function (segment) { return segment.value.replace(escapeRegex, "\\$1"); }; regex[1 /* Dynamic */] = function () { return "([^/]+)"; }; regex[2 /* Star */] = function () { return "(.+)"; }; regex[4 /* Epsilon */] = function () { return ""; }; var generate = []; generate[0 /* Static */] = function (segment) { return segment.value; }; generate[1 /* Dynamic */] = function (segment, params) { var value = getParam(params, segment.value); if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) { return encodePathSegment(value); } else { return value; } }; generate[2 /* Star */] = function (segment, params) { return getParam(params, segment.value); }; generate[4 /* Epsilon */] = function () { return ""; }; var EmptyObject = Object.freeze({}); var EmptyArray = Object.freeze([]); // 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(segments, route, types) { // normalize route as not starting with a "/". Recognition will // also normalize. if (route.length > 0 && route.charCodeAt(0) === 47 /* SLASH */) { route = route.substr(1); } var parts = route.split("/"); var names = undefined; var shouldDecodes = undefined; for (var i = 0; i < parts.length; i++) { var part = parts[i]; var flags = 0; var type = 0; if (part === "") { type = 4 /* Epsilon */; } else if (part.charCodeAt(0) === 58 /* COLON */) { type = 1 /* Dynamic */; } else if (part.charCodeAt(0) === 42 /* STAR */) { type = 2 /* Star */; } else { type = 0 /* Static */; } flags = 2 << type; if (flags & 12 /* Named */) { part = part.slice(1); names = names || []; names.push(part); shouldDecodes = shouldDecodes || []; shouldDecodes.push((flags & 4 /* Decoded */) !== 0); } if (flags & 14 /* Counted */) { types[type]++; } segments.push({ type: type, value: normalizeSegment(part) }); } return { names: names || EmptyArray, shouldDecodes: shouldDecodes || EmptyArray }; } function isEqualCharSpec(spec, char, negate) { return spec.char === char && spec.negate === negate; } // 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. var State = function State(states, id, char, negate, repeat) { this.states = states; this.id = id; this.char = char; this.negate = negate; this.nextStates = repeat ? id : null; this.pattern = ""; this._regex = undefined; this.handlers = undefined; this.types = undefined; }; State.prototype.regex = function regex$1() { if (!this._regex) { this._regex = new RegExp(this.pattern); } return this._regex; }; State.prototype.get = function get(char, negate) { var this$1 = this; var nextStates = this.nextStates; if (nextStates === null) { return; } if (isArray(nextStates)) { for (var i = 0; i < nextStates.length; i++) { var child = this$1.states[nextStates[i]]; if (isEqualCharSpec(child, char, negate)) { return child; } } } else { var child$1 = this.states[nextStates]; if (isEqualCharSpec(child$1, char, negate)) { return child$1; } } }; State.prototype.put = function put(char, negate, repeat) { var state; // If the character specification already exists in a child of the current // state, just return that state. if (state = this.get(char, negate)) { return state; } // Make a new state for the character spec var states = this.states; state = new State(states, states.length, char, negate, repeat); states[states.length] = state; // Insert the new state as a child of the current state if (this.nextStates == null) { this.nextStates = state.id; } else if (isArray(this.nextStates)) { this.nextStates.push(state.id); } else { this.nextStates = [this.nextStates, state.id]; } // Return the new state return state; }; // Find a list of child states matching the next character State.prototype.match = function match(ch) { var this$1 = this; var nextStates = this.nextStates; if (!nextStates) { return []; } var returned = []; if (isArray(nextStates)) { for (var i = 0; i < nextStates.length; i++) { var child = this$1.states[nextStates[i]]; if (isMatch(child, ch)) { returned.push(child); } } } else { var child$1 = this.states[nextStates]; if (isMatch(child$1, ch)) { returned.push(child$1); } } return returned; }; function isMatch(spec, char) { return spec.negate ? spec.char !== char && spec.char !== -1 /* ANY */ : spec.char === char || spec.char === -1 /* ANY */; } // 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) { var ref = a.types || [0, 0, 0]; var astatics = ref[0]; var adynamics = ref[1]; var astars = ref[2]; var ref$1 = b.types || [0, 0, 0]; var bstatics = ref$1[0]; var bdynamics = ref$1[1]; var bstars = ref$1[2]; if (astars !== bstars) { return astars - bstars; } if (astars) { if (astatics !== bstatics) { return bstatics - astatics; } if (adynamics !== bdynamics) { return bdynamics - adynamics; } } if (adynamics !== bdynamics) { return adynamics - bdynamics; } if (astatics !== bstatics) { return bstatics - astatics; } 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 RecognizeResults = function RecognizeResults(queryParams) { this.length = 0; this.queryParams = queryParams || {}; }; RecognizeResults.prototype.splice = Array.prototype.splice; RecognizeResults.prototype.slice = Array.prototype.slice; RecognizeResults.prototype.push = Array.prototype.push; function findHandler(state, originalPath, queryParams) { var handlers = state.handlers; var regex = state.regex(); if (!regex || !handlers) { throw new Error("state not initialized"); } var captures = originalPath.match(regex); var currentCapture = 1; var result = new RecognizeResults(queryParams); result.length = handlers.length; for (var i = 0; i < handlers.length; i++) { var handler = handlers[i]; var names = handler.names; var shouldDecodes = handler.shouldDecodes; var params = EmptyObject; var isDynamic = false; if (names !== EmptyArray && shouldDecodes !== EmptyArray) { for (var j = 0; j < names.length; j++) { isDynamic = true; var name = names[j]; var capture = captures && captures[currentCapture++]; if (params === EmptyObject) { params = {}; } if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS && shouldDecodes[j]) { params[name] = capture && decodeURIComponent(capture); } else { params[name] = capture; } } } result[i] = { handler: handler.handler, params: params, isDynamic: isDynamic }; } 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; } var RouteRecognizer = function RouteRecognizer() { this.names = createMap(); var states = []; var state = new State(states, 0, -1 /* ANY */, true, false); states[0] = state; this.states = states; this.rootState = state; }; RouteRecognizer.prototype.add = function add(routes, options) { var currentState = this.rootState; var pattern = "^"; var types = [0, 0, 0]; var handlers = new Array(routes.length); var allSegments = []; var isEmpty = true; var j = 0; for (var i = 0; i < routes.length; i++) { var route = routes[i]; var ref = parse(allSegments, route.path, types); var names = ref.names; var shouldDecodes = ref.shouldDecodes; // preserve j so it points to the start of newly added segments for (; j < allSegments.length; j++) { var segment = allSegments[j]; if (segment.type === 4 /* Epsilon */) { continue; } isEmpty = false; // Add a "/" for the new segment currentState = currentState.put(47 /* SLASH */, false, false); pattern += "/"; // Add a representation of the segment to the NFA and regex currentState = eachChar[segment.type](segment, currentState); pattern += regex[segment.type](segment); } handlers[i] = { handler: route.handler, names: names, shouldDecodes: shouldDecodes }; } if (isEmpty) { currentState = currentState.put(47 /* SLASH */, false, false); pattern += "/"; } currentState.handlers = handlers; currentState.pattern = pattern + "$"; currentState.types = types; var name; if (typeof options === "object" && options !== null && options.as) { name = options.as; } if (name) { // if (this.names[name]) { // throw new Error("You may not add a duplicate route named `" + name + "`."); // } this.names[name] = { segments: allSegments, handlers: handlers }; } }; RouteRecognizer.prototype.handlersFor = function handlersFor(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++) { var handler = route.handlers[i]; result[i] = handler; } return result; }; RouteRecognizer.prototype.hasRoute = function hasRoute(name) { return !!this.names[name]; }; RouteRecognizer.prototype.generate = function generate$1(name, params) { var route = this.names[name]; var 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.type === 4 /* Epsilon */) { continue; } output += "/"; output += generate[segment.type](segment, params); } if (output.charAt(0) !== "/") { output = "/" + output; } if (params && params.queryParams) { output += this.generateQueryString(params.queryParams); } return output; }; RouteRecognizer.prototype.generateQueryString = function generateQueryString(params) { var pairs = []; var keys = Object.keys(params); keys.sort(); for (var i = 0; i < keys.length; i++) { var 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("&"); }; RouteRecognizer.prototype.parseQueryString = function parseQueryString(queryString) { var pairs = queryString.split("&"); var queryParams = {}; for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split("="), key = decodeQueryParamPart(pair[0]), keyLength = key.length, isArray = false, value = void 0; 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; }; RouteRecognizer.prototype.recognize = function recognize(path) { var results; var states = [this.rootState]; var queryParams = {}; var isSlashDropped = false; var hashStart = path.indexOf("#"); if (hashStart !== -1) { path = path.substr(0, hashStart); } var 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); } var pathLen = path.length; if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { path = path.substr(0, pathLen - 1); originalPath = originalPath.substr(0, originalPath.length - 1); isSlashDropped = true; } for (var i = 0; i < path.length; i++) { states = recognizeChar(states, path.charCodeAt(i)); if (!states.length) { break; } } var solutions = []; for (var i$1 = 0; i$1 < states.length; i$1++) { if (states[i$1].handlers) { solutions.push(states[i$1]); } } 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.pattern && state.pattern.slice(-5) === "(.+)$") { originalPath = originalPath + "/"; } results = findHandler(state, originalPath, queryParams); } return results; }; RouteRecognizer.VERSION = "0.3.4"; // 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 }; RouteRecognizer.prototype.map = map; exports.default = RouteRecognizer; }); enifed('router_js', ['exports', 'rsvp', 'route-recognizer'], function (exports, _rsvp, _routeRecognizer) { 'use strict'; exports.InternalRouteInfo = exports.TransitionError = exports.TransitionState = exports.QUERY_PARAMS_SYMBOL = exports.PARAMS_SYMBOL = exports.STATE_SYMBOL = exports.logAbort = exports.InternalTransition = undefined; const TransitionAbortedError = function () { TransitionAbortedError.prototype = Object.create(Error.prototype); TransitionAbortedError.prototype.constructor = TransitionAbortedError; function TransitionAbortedError(message) { let error = Error.call(this, message); this.name = 'TransitionAborted'; this.message = message || 'TransitionAborted'; if (Error.captureStackTrace) { Error.captureStackTrace(this, TransitionAbortedError); } else { this.stack = error.stack; } } return TransitionAbortedError; }(); const slice = Array.prototype.slice; const hasOwnProperty = Object.prototype.hasOwnProperty; /** Determines if an object is Promise by checking if it is "thenable". **/ function isPromise(p) { return p !== null && typeof p === 'object' && typeof p.then === 'function'; } function merge(hash, other) { for (let prop in other) { if (hasOwnProperty.call(other, prop)) { hash[prop] = other[prop]; } } } /** @private Extracts query params from the end of an array **/ function extractQueryParams(array) { let len = array && array.length, head, queryParams; if (len && len > 0) { let obj = array[len - 1]; if (isQueryParams(obj)) { queryParams = obj.queryParams; head = slice.call(array, 0, len - 1); return [head, queryParams]; } } return [array, null]; } function isQueryParams(obj) { return obj && hasOwnProperty.call(obj, 'queryParams'); } /** @private Coerces query param properties and array elements into strings. **/ function coerceQueryParamsToString(queryParams) { for (let key in queryParams) { let val = queryParams[key]; if (typeof val === 'number') { queryParams[key] = '' + val; } else if (Array.isArray(val)) { for (let i = 0, l = val.length; i < l; i++) { val[i] = '' + val[i]; } } } } /** @private */ function log(router, ...args) { if (!router.log) { return; } if (arguments.length === 2) { let [sequence, msg] = args; router.log('Transition #' + sequence + ': ' + msg); } else { let [msg] = args; router.log(msg); } } function isParam(object) { return typeof object === 'string' || object instanceof String || typeof object === 'number' || object instanceof Number; } function forEach(array, callback) { for (let i = 0, l = array.length; i < l && callback(array[i]) !== false; i++) { // empty intentionally } } function getChangelist(oldObject, newObject) { let key; let results = { all: {}, changed: {}, removed: {} }; merge(results.all, newObject); let didChange = false; coerceQueryParamsToString(oldObject); coerceQueryParamsToString(newObject); // Calculate removals for (key in oldObject) { if (hasOwnProperty.call(oldObject, key)) { if (!hasOwnProperty.call(newObject, key)) { didChange = true; results.removed[key] = oldObject[key]; } } } // Calculate changes for (key in newObject) { if (hasOwnProperty.call(newObject, key)) { let oldElement = oldObject[key]; let newElement = newObject[key]; if (isArray(oldElement) && isArray(newElement)) { if (oldElement.length !== newElement.length) { results.changed[key] = newObject[key]; didChange = true; } else { for (let i = 0, l = oldElement.length; i < l; i++) { if (oldElement[i] !== newElement[i]) { results.changed[key] = newObject[key]; didChange = true; } } } } else if (oldObject[key] !== newObject[key]) { results.changed[key] = newObject[key]; didChange = true; } } } return didChange ? results : undefined; } function isArray(obj) { return Array.isArray(obj); } function promiseLabel(label) { return 'Router: ' + label; } const STATE_SYMBOL = `__STATE__-2619860001345920-3322w3`; const PARAMS_SYMBOL = `__PARAMS__-261986232992830203-23323`; const QUERY_PARAMS_SYMBOL = `__QPS__-2619863929824844-32323`; /** 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 */ class Transition { constructor(router, intent, state, error = undefined, previousTransition = undefined) { this.from = null; this.to = undefined; this.isAborted = false; this.isActive = true; this.urlMethod = 'update'; this.resolveIndex = 0; this.queryParamsOnly = false; this.isTransition = true; this.isCausedByAbortingTransition = false; this.isCausedByInitialTransition = false; this.isCausedByAbortingReplaceTransition = false; this._visibleQueryParams = {}; this[STATE_SYMBOL] = state || router.state; this.intent = intent; this.router = router; this.data = intent && intent.data || {}; this.resolvedModels = {}; this[QUERY_PARAMS_SYMBOL] = {}; this.promise = undefined; this.error = undefined; this[PARAMS_SYMBOL] = {}; this.routeInfos = []; this.targetName = undefined; this.pivotHandler = undefined; this.sequence = -1; if (error) { this.promise = _rsvp.Promise.reject(error); this.error = error; return; } // if you're doing multiple redirects, need the new transition to know if it // is actually part of the first transition or not. Any further redirects // in the initial transition also need to know if they are part of the // initial transition this.isCausedByAbortingTransition = !!previousTransition; this.isCausedByInitialTransition = !!previousTransition && (previousTransition.isCausedByInitialTransition || previousTransition.sequence === 0); // Every transition in the chain is a replace this.isCausedByAbortingReplaceTransition = !!previousTransition && previousTransition.urlMethod === 'replace' && (!previousTransition.isCausedByAbortingTransition || previousTransition.isCausedByAbortingReplaceTransition); if (state) { this[PARAMS_SYMBOL] = state.params; this[QUERY_PARAMS_SYMBOL] = state.queryParams; this.routeInfos = state.routeInfos; let len = state.routeInfos.length; if (len) { this.targetName = state.routeInfos[len - 1].name; } for (let i = 0; i < len; ++i) { let handlerInfo = state.routeInfos[i]; // TODO: this all seems hacky if (!handlerInfo.isResolved) { break; } this.pivotHandler = handlerInfo.route; } this.sequence = router.currentSequence++; this.promise = state.resolve(() => { if (this.isAborted) { return _rsvp.Promise.reject(false, promiseLabel('Transition aborted - reject')); } return _rsvp.Promise.resolve(true); }, this).catch(result => { return _rsvp.Promise.reject(this.router.transitionDidError(result, this)); }, promiseLabel('Handle Abort')); } else { this.promise = _rsvp.Promise.resolve(this[STATE_SYMBOL]); this[PARAMS_SYMBOL] = {}; } } /** 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 */ /** 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 */ /** 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(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(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(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() { this.rollback(); let transition = new Transition(this.router, undefined, undefined, undefined); transition.to = this.from; transition.from = this.from; transition.isAborted = true; this.router.routeWillChange(transition); this.router.routeDidChange(transition); return this; } rollback() { if (!this.isAborted) { log(this.router, this.sequence, this.targetName + ': transition was aborted'); if (this.intent !== undefined && this.intent !== null) { this.intent.preTransitionState = this.router.state; } this.isAborted = true; this.isActive = false; this.router.activeTransition = undefined; } } redirect(newTransition) { this.rollback(); this.router.routeWillChange(newTransition); } /** 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() { // TODO: add tests for merged state retry()s this.abort(); let newTransition = this.router.transitionByIntent(this.intent, false); // inheriting a `null` urlMethod is not valid // the urlMethod is only set to `null` when // the transition is initiated *after* the url // has been updated (i.e. `router.handleURL`) // // in that scenario, the url method cannot be // inherited for a new transition because then // the url would not update even though it should if (this.urlMethod !== null) { newTransition.method(this.urlMethod); } return newTransition; } /** 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(method) { this.urlMethod = method; return this; } // Alias 'trigger' as 'send' send(ignoreFailure, _name, err, transition, handler) { this.trigger(ignoreFailure, _name, err, transition, handler); } /** 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(ignoreFailure, name, ...args) { this.router.triggerEvent(this[STATE_SYMBOL].routeInfos.slice(0, this.resolveIndex + 1), ignoreFailure, name, 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() { let router = this.router; return this.promise.catch(function (reason) { if (router.activeTransition) { return router.activeTransition.followRedirects(); } return _rsvp.Promise.reject(reason); }); } toString() { return 'Transition (sequence ' + this.sequence + ')'; } /** @private */ log(message) { log(this.router, this.sequence, message); } } /** @private Logs and returns an instance of TransitionAborted. */ function logAbort(transition) { log(transition.router, transition.sequence, 'detected abort.'); return new TransitionAbortedError(); } function isTransition(obj) { return typeof obj === 'object' && obj instanceof Transition && obj.isTransition; } function prepareResult(obj) { if (isTransition(obj)) { return null; } return obj; } let ROUTE_INFOS = new WeakMap(); function toReadOnlyRouteInfo(routeInfos, queryParams = {}, includeAttributes = false) { return routeInfos.map((info, i) => { let { name, params, paramNames, context } = info; if (ROUTE_INFOS.has(info) && includeAttributes) { let routeInfo = ROUTE_INFOS.get(info); let routeInfoWithAttribute = createRouteInfoWithAttributes(routeInfo, context); ROUTE_INFOS.set(info, routeInfoWithAttribute); return routeInfoWithAttribute; } let routeInfo = { find(predicate, thisArg) { let publicInfo; let arr = []; if (predicate.length === 3) { arr = routeInfos.map(info => ROUTE_INFOS.get(info)); } for (let i = 0; routeInfos.length > i; i++) { publicInfo = ROUTE_INFOS.get(routeInfos[i]); if (predicate.call(thisArg, publicInfo, i, arr)) { return publicInfo; } } return undefined; }, get name() { return name; }, get paramNames() { return paramNames; }, get parent() { let parent = routeInfos[i - 1]; if (parent === undefined) { return null; } return ROUTE_INFOS.get(parent); }, get child() { let child = routeInfos[i + 1]; if (child === undefined) { return null; } return ROUTE_INFOS.get(child); }, get localName() { let parts = this.name.split('.'); return parts[parts.length - 1]; }, get params() { return params; }, get queryParams() { return queryParams; } }; if (includeAttributes) { routeInfo = createRouteInfoWithAttributes(routeInfo, context); } ROUTE_INFOS.set(info, routeInfo); return routeInfo; }); } function createRouteInfoWithAttributes(routeInfo, context) { let attributes = { get attributes() { return context; } }; if (Object.isFrozen(routeInfo) || routeInfo.hasOwnProperty('attributes')) { return Object.assign({}, routeInfo, attributes); } return Object.assign(routeInfo, attributes); } class InternalRouteInfo { constructor(router, name, paramNames, route) { this._routePromise = undefined; this._route = null; this.params = {}; this.isResolved = false; this.name = name; this.paramNames = paramNames; this.router = router; if (route) { this._processRoute(route); } } getModel(_transition) { return _rsvp.Promise.resolve(this.context); } serialize(_context) { return this.params || {}; } resolve(shouldContinue, transition) { return _rsvp.Promise.resolve(this.routePromise).then(route => this.checkForAbort(shouldContinue, route)).then(() => this.runBeforeModelHook(transition)).then(() => this.checkForAbort(shouldContinue, null)).then(() => this.getModel(transition)).then(resolvedModel => this.checkForAbort(shouldContinue, resolvedModel)).then(resolvedModel => this.runAfterModelHook(transition, resolvedModel)).then(resolvedModel => this.becomeResolved(transition, resolvedModel)); } becomeResolved(transition, resolvedContext) { let params = this.serialize(resolvedContext); if (transition) { this.stashResolvedModel(transition, resolvedContext); transition[PARAMS_SYMBOL] = transition[PARAMS_SYMBOL] || {}; transition[PARAMS_SYMBOL][this.name] = params; } let context; let contextsMatch = resolvedContext === this.context; if ('context' in this || !contextsMatch) { context = resolvedContext; } let cached = ROUTE_INFOS.get(this); let resolved = new ResolvedRouteInfo(this.router, this.name, this.paramNames, params, this.route, context); if (cached !== undefined) { ROUTE_INFOS.set(resolved, cached); } return resolved; } shouldSupercede(routeInfo) { // Prefer this newer routeInfo over `other` if: // 1) The other one doesn't exist // 2) The names don't match // 3) This route has a context that doesn't match // the other one (or the other one doesn't have one). // 4) This route has parameters that don't match the other. if (!routeInfo) { return true; } let contextsMatch = routeInfo.context === this.context; return routeInfo.name !== this.name || 'context' in this && !contextsMatch || this.hasOwnProperty('params') && !paramsMatch(this.params, routeInfo.params); } get route() { // _route could be set to either a route object or undefined, so we // compare against null to know when it's been set if (this._route !== null) { return this._route; } return this.fetchRoute(); } set route(route) { this._route = route; } get routePromise() { if (this._routePromise) { return this._routePromise; } this.fetchRoute(); return this._routePromise; } set routePromise(routePromise) { this._routePromise = routePromise; } log(transition, message) { if (transition.log) { transition.log(this.name + ': ' + message); } } updateRoute(route) { return this.route = route; } runBeforeModelHook(transition) { if (transition.trigger) { transition.trigger(true, 'willResolveModel', transition, this.route); } let result; if (this.route) { if (this.route.beforeModel !== undefined) { result = this.route.beforeModel(transition); } } if (isTransition(result)) { result = null; } return _rsvp.Promise.resolve(result); } runAfterModelHook(transition, resolvedModel) { // Stash the resolved model on the payload. // This makes it possible for users to swap out // the resolved model in afterModel. let name = this.name; this.stashResolvedModel(transition, resolvedModel); let result; if (this.route !== undefined) { if (this.route.afterModel !== undefined) { result = this.route.afterModel(resolvedModel, transition); } } result = prepareResult(result); return _rsvp.Promise.resolve(result).then(() => { // Ignore the fulfilled value returned from afterModel. // Return the value stashed in resolvedModels, which // might have been swapped out in afterModel. return transition.resolvedModels[name]; }); } checkForAbort(shouldContinue, value) { return _rsvp.Promise.resolve(shouldContinue()).then(function () { // We don't care about shouldContinue's resolve value; // pass along the original value passed to this fn. return value; }, null); } stashResolvedModel(transition, resolvedModel) { transition.resolvedModels = transition.resolvedModels || {}; transition.resolvedModels[this.name] = resolvedModel; } fetchRoute() { let route = this.router.getRoute(this.name); return this._processRoute(route); } _processRoute(route) { // Setup a routePromise so that we can wait for asynchronously loaded routes this.routePromise = _rsvp.Promise.resolve(route); // Wait until the 'route' property has been updated when chaining to a route // that is a promise if (isPromise(route)) { this.routePromise = this.routePromise.then(r => { return this.updateRoute(r); }); // set to undefined to avoid recursive loop in the route getter return this.route = undefined; } else if (route) { return this.updateRoute(route); } return undefined; } } class ResolvedRouteInfo extends InternalRouteInfo { constructor(router, name, paramNames, params, route, context) { super(router, name, paramNames, route); this.params = params; this.isResolved = true; this.context = context; } resolve(_shouldContinue, transition) { // A ResolvedRouteInfo just resolved with itself. if (transition && transition.resolvedModels) { transition.resolvedModels[this.name] = this.context; } return _rsvp.Promise.resolve(this); } } class UnresolvedRouteInfoByParam extends InternalRouteInfo { constructor(router, name, paramNames, params, route) { super(router, name, paramNames, route); this.params = {}; this.params = params; } getModel(transition) { let fullParams = this.params; if (transition && transition[QUERY_PARAMS_SYMBOL]) { fullParams = {}; merge(fullParams, this.params); fullParams.queryParams = transition[QUERY_PARAMS_SYMBOL]; } let route = this.route; let result = undefined; if (route.deserialize) { result = route.deserialize(fullParams, transition); } else if (route.model) { result = route.model(fullParams, transition); } if (result && isTransition(result)) { result = undefined; } return _rsvp.Promise.resolve(result); } } class UnresolvedRouteInfoByObject extends InternalRouteInfo { constructor(router, name, paramNames, context) { super(router, name, paramNames); this.context = context; this.serializer = this.router.getSerializer(name); } getModel(transition) { if (this.router.log !== undefined) { this.router.log(this.name + ': resolving provided model'); } return super.getModel(transition); } /** @private Serializes a route 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 route */ serialize(model) { let { paramNames, context } = this; if (!model) { model = context; } let object = {}; if (isParam(model)) { object[paramNames[0]] = model; return object; } // Use custom serialize if it exists. if (this.serializer) { // invoke this.serializer unbound (getSerializer returns a stateless function) return this.serializer.call(null, model, paramNames); } else if (this.route !== undefined) { if (this.route.serialize) { return this.route.serialize(model, paramNames); } } if (paramNames.length !== 1) { return; } let name = paramNames[0]; if (/_id$/.test(name)) { object[name] = model.id; } else { object[name] = model; } return object; } } 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 routes, they should. for (let k in a) { if (a.hasOwnProperty(k) && a[k] !== b[k]) { return false; } } return true; } class TransitionIntent { constructor(router, data = {}) { this.router = router; this.data = data; } } class TransitionState { constructor() { this.routeInfos = []; this.queryParams = {}; this.params = {}; } promiseLabel(label) { let targetName = ''; forEach(this.routeInfos, function (routeInfo) { if (targetName !== '') { targetName += '.'; } targetName += routeInfo.name; return true; }); return promiseLabel("'" + targetName + "': " + label); } resolve(shouldContinue, transition) { // First, calculate params for this state. This is useful // information to provide to the various route hooks. let params = this.params; forEach(this.routeInfos, routeInfo => { params[routeInfo.name] = routeInfo.params || {}; return true; }); transition.resolveIndex = 0; let currentState = this; let wasAborted = false; // The prelude RSVP.resolve() asyncs us into the promise land. return _rsvp.Promise.resolve(null, this.promiseLabel('Start transition')).then(resolveOneRouteInfo, null, this.promiseLabel('Resolve route')).catch(handleError, this.promiseLabel('Handle error')); function innerShouldContinue() { return _rsvp.Promise.resolve(shouldContinue(), currentState.promiseLabel('Check if should continue')).catch(function (reason) { // We distinguish between errors that occurred // during resolution (e.g. before"Model/model/afterModel), // and aborts due to a rejecting promise from shouldContinue(). wasAborted = true; return _rsvp.Promise.reject(reason); }, currentState.promiseLabel('Handle abort')); } function handleError(error) { // This is the only possible // reject value of TransitionState#resolve let routeInfos = currentState.routeInfos; let errorHandlerIndex = transition.resolveIndex >= routeInfos.length ? routeInfos.length - 1 : transition.resolveIndex; return _rsvp.Promise.reject(new TransitionError(error, currentState.routeInfos[errorHandlerIndex].route, wasAborted, currentState)); } function proceed(resolvedRouteInfo) { let wasAlreadyResolved = currentState.routeInfos[transition.resolveIndex].isResolved; // Swap the previously unresolved routeInfo with // the resolved routeInfo currentState.routeInfos[transition.resolveIndex++] = resolvedRouteInfo; 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. let { route } = resolvedRouteInfo; if (route !== undefined) { if (route.redirect) { route.redirect(resolvedRouteInfo.context, transition); } } } // Proceed after ensuring that the redirect hook // didn't abort this transition by transitioning elsewhere. return innerShouldContinue().then(resolveOneRouteInfo, null, currentState.promiseLabel('Resolve route')); } function resolveOneRouteInfo() { if (transition.resolveIndex === currentState.routeInfos.length) { // This is is the only possible // fulfill value of TransitionState#resolve return currentState; } let routeInfo = currentState.routeInfos[transition.resolveIndex]; return routeInfo.resolve(innerShouldContinue, transition).then(proceed, null, currentState.promiseLabel('Proceed')); } } } class TransitionError { constructor(error, route, wasAborted, state) { this.error = error; this.route = route; this.wasAborted = wasAborted; this.state = state; } } class NamedTransitionIntent extends TransitionIntent { constructor(router, name, pivotHandler, contexts = [], queryParams = {}, data) { super(router, data); this.preTransitionState = undefined; this.name = name; this.pivotHandler = pivotHandler; this.contexts = contexts; this.queryParams = queryParams; } applyToState(oldState, isIntermediate) { // TODO: WTF fix me let partitionedArgs = extractQueryParams([this.name].concat(this.contexts)), pureArgs = partitionedArgs[0], handlers = this.router.recognizer.handlersFor(pureArgs[0]); let targetRouteName = handlers[handlers.length - 1].handler; return this.applyToHandlers(oldState, handlers, targetRouteName, isIntermediate, false); } applyToHandlers(oldState, parsedHandlers, targetRouteName, isIntermediate, checkingIfActive) { let i, len; let newState = new TransitionState(); let objects = this.contexts.slice(0); let invalidateIndex = parsedHandlers.length; // Pivot handlers are provided for refresh transitions if (this.pivotHandler) { for (i = 0, len = parsedHandlers.length; i < len; ++i) { if (parsedHandlers[i].handler === this.pivotHandler.routeName) { invalidateIndex = i; break; } } } for (i = parsedHandlers.length - 1; i >= 0; --i) { let result = parsedHandlers[i]; let name = result.handler; let oldHandlerInfo = oldState.routeInfos[i]; let newHandlerInfo = null; if (result.names.length > 0) { if (i >= invalidateIndex) { newHandlerInfo = this.createParamHandlerInfo(name, result.names, objects, oldHandlerInfo); } else { newHandlerInfo = this.getHandlerInfoForDynamicSegment(name, result.names, objects, oldHandlerInfo, targetRouteName, i); } } 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, 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); let oldContext = oldHandlerInfo && oldHandlerInfo.context; if (result.names.length > 0 && oldHandlerInfo.context !== undefined && 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; } let 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.routeInfos.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.routeInfos, invalidateIndex); } merge(newState.queryParams, this.queryParams || {}); return newState; } invalidateChildren(handlerInfos, invalidateIndex) { for (let i = invalidateIndex, l = handlerInfos.length; i < l; ++i) { let handlerInfo = handlerInfos[i]; if (handlerInfo.isResolved) { let { name, params, route, paramNames } = handlerInfos[i]; handlerInfos[i] = new UnresolvedRouteInfoByParam(this.router, name, paramNames, params, route); } } } getHandlerInfoForDynamicSegment(name, names, objects, oldHandlerInfo, _targetRouteName, i) { let objectToUse; if (objects.length > 0) { // Use the objects provided for this transition. objectToUse = objects[objects.length - 1]; if (isParam(objectToUse)) { return this.createParamHandlerInfo(name, names, objects, oldHandlerInfo); } else { objects.pop(); } } else if (oldHandlerInfo && oldHandlerInfo.name === name) { // Reuse the matching oldHandlerInfo return oldHandlerInfo; } else { if (this.preTransitionState) { let preTransitionHandlerInfo = this.preTransitionState.routeInfos[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 new UnresolvedRouteInfoByObject(this.router, name, names, objectToUse); } createParamHandlerInfo(name, names, objects, oldHandlerInfo) { let params = {}; // Soak up all the provided string/numbers let numNames = names.length; while (numNames--) { // Only use old params if the names match with the new handler let oldParams = oldHandlerInfo && name === oldHandlerInfo.name && oldHandlerInfo.params || {}; let peek = objects[objects.length - 1]; let paramName = names[numNames]; if (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 new UnresolvedRouteInfoByParam(this.router, name, names, params); } } const UnrecognizedURLError = function () { UnrecognizedURLError.prototype = Object.create(Error.prototype); UnrecognizedURLError.prototype.constructor = UnrecognizedURLError; function UnrecognizedURLError(message) { let error = Error.call(this, message); this.name = 'UnrecognizedURLError'; this.message = message || 'UnrecognizedURL'; if (Error.captureStackTrace) { Error.captureStackTrace(this, UnrecognizedURLError); } else { this.stack = error.stack; } } return UnrecognizedURLError; }(); class URLTransitionIntent extends TransitionIntent { constructor(router, url, data) { super(router, data); this.url = url; this.preTransitionState = undefined; } applyToState(oldState) { let newState = new TransitionState(); let results = this.router.recognizer.recognize(this.url), i, len; if (!results) { throw new UnrecognizedURLError(this.url); } let statesDiffer = false; let _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 UnrecognizedURLError(_url); } return handler; } for (i = 0, len = results.length; i < len; ++i) { let result = results[i]; let name = result.handler; let paramNames = []; if (this.router.recognizer.hasRoute(name)) { paramNames = this.router.recognizer.handlersFor(name)[i].names; } let newRouteInfo = new UnresolvedRouteInfoByParam(this.router, name, paramNames, result.params); let route = newRouteInfo.route; if (route) { checkHandlerAccessibility(route); } else { // If the hanlder is being loaded asynchronously, check if we can // access it after it has resolved newRouteInfo.routePromise = newRouteInfo.routePromise.then(checkHandlerAccessibility); } let oldRouteInfo = oldState.routeInfos[i]; if (statesDiffer || newRouteInfo.shouldSupercede(oldRouteInfo)) { statesDiffer = true; newState.routeInfos[i] = newRouteInfo; } else { newState.routeInfos[i] = oldRouteInfo; } } merge(newState.queryParams, results.queryParams); return newState; } } class Router { constructor(logger) { this._lastQueryParams = {}; this.state = undefined; this.oldState = undefined; this.activeTransition = undefined; this.currentRouteInfos = undefined; this._changedQueryParams = undefined; this.currentSequence = 0; this.log = logger; this.recognizer = new _routeRecognizer.default(); this.reset(); } /** 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(callback) { this.recognizer.map(callback, function (recognizer, routes) { for (let i = routes.length - 1, proceed = true; i >= 0 && proceed; --i) { let route = routes[i]; let handler = route.handler; recognizer.add(routes, { as: handler }); proceed = route.path === '/' || route.path === '' || handler.slice(-6) === '.index'; } }); } hasRoute(route) { return this.recognizer.hasRoute(route); } queryParamsTransition(changelist, wasTransitioning, oldState, newState) { this.fireQueryParamDidChange(newState, changelist); if (!wasTransitioning && this.activeTransition) { // One of the routes 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). let newTransition = new Transition(this, undefined, undefined); newTransition.queryParamsOnly = true; oldState.queryParams = this.finalizeQueryParamChange(newState.routeInfos, newState.queryParams, newTransition); newTransition[QUERY_PARAMS_SYMBOL] = newState.queryParams; this.toReadOnlyInfos(newTransition, newState); this.routeWillChange(newTransition); newTransition.promise = newTransition.promise.then(result => { this._updateURL(newTransition, oldState); this.didTransition(this.currentRouteInfos); this.toInfos(newTransition, newState.routeInfos, true); this.routeDidChange(newTransition); return result; }, null, promiseLabel('Transition complete')); return newTransition; } } transitionByIntent(intent, isIntermediate) { try { return this.getTransitionByIntent(intent, isIntermediate); } catch (e) { return new Transition(this, intent, undefined, e, undefined); } } recognize(url) { let intent = new URLTransitionIntent(this, url); let newState = this.generateNewState(intent); if (newState === null) { return newState; } let readonlyInfos = toReadOnlyRouteInfo(newState.routeInfos, newState.queryParams); return readonlyInfos[readonlyInfos.length - 1]; } recognizeAndLoad(url) { let intent = new URLTransitionIntent(this, url); let newState = this.generateNewState(intent); if (newState === null) { return _rsvp.Promise.reject(`URL ${url} was not recognized`); } let newTransition = new Transition(this, intent, newState, undefined); return newTransition.then(() => { let routeInfosWithAttributes = toReadOnlyRouteInfo(newState.routeInfos, newTransition[QUERY_PARAMS_SYMBOL], true); return routeInfosWithAttributes[routeInfosWithAttributes.length - 1]; }); } generateNewState(intent) { try { return intent.applyToState(this.state, false); } catch (e) { return null; } } getTransitionByIntent(intent, isIntermediate) { let wasTransitioning = !!this.activeTransition; let oldState = wasTransitioning ? this.activeTransition[STATE_SYMBOL] : this.state; let newTransition; let newState = intent.applyToState(oldState, isIntermediate); let queryParamChangelist = getChangelist(oldState.queryParams, newState.queryParams); if (routeInfosEqual(newState.routeInfos, oldState.routeInfos)) { // This is a no-op transition. See if query params changed. if (queryParamChangelist) { let newTransition = this.queryParamsTransition(queryParamChangelist, wasTransitioning, oldState, newState); newTransition.queryParamsOnly = true; return newTransition; } // No-op. No need to create a new transition. return this.activeTransition || new Transition(this, undefined, undefined); } if (isIntermediate) { this.setupContexts(newState); let transition = this.activeTransition; if (!transition.isCausedByAbortingTransition) { transition = new Transition(this, undefined, undefined); transition.from = transition.from; } this.toInfos(transition, newState.routeInfos); this.routeWillChange(transition); return this.activeTransition; } // Create a new transition to the destination route. newTransition = new Transition(this, intent, newState, undefined, this.activeTransition); // transition is to same route with same params, only query params differ. // not caught above probably because refresh() has been used if (routeInfosSameExceptQueryParams(newState.routeInfos, oldState.routeInfos)) { newTransition.queryParamsOnly = true; } this.toReadOnlyInfos(newTransition, newState); // Abort and usurp any previously active transition. if (this.activeTransition) { this.activeTransition.redirect(newTransition); } 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(result => { return this.finalizeTransition(newTransition, result); }, null, promiseLabel('Settle transition promise when transition is finalized')); if (!wasTransitioning) { this.notifyExistingHandlers(newState, newTransition); } this.fireQueryParamDidChange(newState, queryParamChangelist); return newTransition; } /** @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 */ doTransition(name, modelsArray = [], isIntermediate = false) { let lastArg = modelsArray[modelsArray.length - 1]; let queryParams = {}; if (lastArg !== undefined && lastArg.hasOwnProperty('queryParams')) { queryParams = modelsArray.pop().queryParams; } let intent; if (name === undefined) { log(this, 'Updating query params'); // A query param update is really just a transition // into the route you're already on. let { routeInfos } = this.state; intent = new NamedTransitionIntent(this, routeInfos[routeInfos.length - 1].name, undefined, [], queryParams); } else if (name.charAt(0) === '/') { log(this, 'Attempting URL transition to ' + name); intent = new URLTransitionIntent(this, name); } else { log(this, 'Attempting transition to ' + name); intent = new NamedTransitionIntent(this, name, undefined, modelsArray, queryParams); } return this.transitionByIntent(intent, isIntermediate); } /** @private Updates the URL (if necessary) and calls `setupContexts` to update the router's array of `currentRouteInfos`. */ finalizeTransition(transition, newState) { try { log(transition.router, transition.sequence, 'Resolved all models on destination route; finalizing transition.'); let routeInfos = newState.routeInfos; // Run all the necessary enter/setup/exit hooks this.setupContexts(newState, transition); // Check if a redirect occurred in enter/setup if (transition.isAborted) { // TODO: cleaner way? distinguish b/w targetRouteInfos? this.state.routeInfos = this.currentRouteInfos; return _rsvp.Promise.reject(logAbort(transition)); } this._updateURL(transition, newState); transition.isActive = false; this.activeTransition = undefined; this.triggerEvent(this.currentRouteInfos, true, 'didTransition', []); this.didTransition(this.currentRouteInfos); this.toInfos(transition, newState.routeInfos, true); this.routeDidChange(transition); log(this, transition.sequence, 'TRANSITION COMPLETE.'); // Resolve with the final route. return routeInfos[routeInfos.length - 1].route; } catch (e) { if (!(e instanceof TransitionAbortedError)) { let infos = transition[STATE_SYMBOL].routeInfos; transition.trigger(true, 'error', e, transition, infos[infos.length - 1].route); transition.abort(); } throw e; } } /** @private Takes an Array of `RouteInfo`s, figures out which ones are exiting, entering, or changing contexts, and calls the proper route hooks. For example, consider the following tree of routes. Each route 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` routes 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 */ setupContexts(newState, transition) { let partition = this.partitionRoutes(this.state, newState); let i, l, route; for (i = 0, l = partition.exited.length; i < l; i++) { route = partition.exited[i].route; delete route.context; if (route !== undefined) { if (route._internalReset !== undefined) { route._internalReset(true, transition); } if (route.exit !== undefined) { route.exit(transition); } } } let oldState = this.oldState = this.state; this.state = newState; let currentRouteInfos = this.currentRouteInfos = partition.unchanged.slice(); try { for (i = 0, l = partition.reset.length; i < l; i++) { route = partition.reset[i].route; if (route !== undefined) { if (route._internalReset !== undefined) { route._internalReset(false, transition); } } } for (i = 0, l = partition.updatedContext.length; i < l; i++) { this.routeEnteredOrUpdated(currentRouteInfos, partition.updatedContext[i], false, transition); } for (i = 0, l = partition.entered.length; i < l; i++) { this.routeEnteredOrUpdated(currentRouteInfos, partition.entered[i], true, transition); } } catch (e) { this.state = oldState; this.currentRouteInfos = oldState.routeInfos; throw e; } this.state.queryParams = this.finalizeQueryParamChange(currentRouteInfos, newState.queryParams, transition); } /** @private Fires queryParamsDidChange event */ fireQueryParamDidChange(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. this._changedQueryParams = queryParamChangelist.all; this.triggerEvent(newState.routeInfos, true, 'queryParamsDidChange', [queryParamChangelist.changed, queryParamChangelist.all, queryParamChangelist.removed]); this._changedQueryParams = undefined; } } /** @private Helper method used by setupContexts. Handles errors or redirects that may happen in enter/setup. */ routeEnteredOrUpdated(currentRouteInfos, routeInfo, enter, transition) { let route = routeInfo.route, context = routeInfo.context; function _routeEnteredOrUpdated(route) { if (enter) { if (route.enter !== undefined) { route.enter(transition); } } if (transition && transition.isAborted) { throw new TransitionAbortedError(); } route.context = context; if (route.contextDidChange !== undefined) { route.contextDidChange(); } if (route.setup !== undefined) { route.setup(context, transition); } if (transition && transition.isAborted) { throw new TransitionAbortedError(); } currentRouteInfos.push(routeInfo); return route; } // If the route doesn't exist, it means we haven't resolved the route promise yet if (route === undefined) { routeInfo.routePromise = routeInfo.routePromise.then(_routeEnteredOrUpdated); } else { _routeEnteredOrUpdated(route); } return true; } /** @private This function is called when transitioning from one URL to another to determine which routes are no longer active, which routes are newly active, and which routes remain active but have their context changed. Take a list of old routes and new routes and partition them into four buckets: * unchanged: the route was active in both the old and new URL, and its context remains the same * updated context: the route was active in both the old and new URL, but its context changed. The route's `setup` method, if any, will be called with the new context. * exited: the route was active in the old URL, but is no longer active. * entered: the route was not active in the old URL, but is now active. The PartitionedRoutes structure has four fields: * `updatedContext`: a list of `RouteInfo` objects that represent routes that remain active but have a changed context * `entered`: a list of `RouteInfo` objects that represent routes that are newly active * `exited`: a list of `RouteInfo` objects that are no longer active. * `unchanged`: a list of `RouteInfo` objects that remain active. @param {Array[InternalRouteInfo]} oldRoutes a list of the route information for the previous URL (or `[]` if this is the first handled transition) @param {Array[InternalRouteInfo]} newRoutes a list of the route information for the new URL @return {Partition} */ partitionRoutes(oldState, newState) { let oldRouteInfos = oldState.routeInfos; let newRouteInfos = newState.routeInfos; let routes = { updatedContext: [], exited: [], entered: [], unchanged: [], reset: [] }; let routeChanged, contextChanged = false, i, l; for (i = 0, l = newRouteInfos.length; i < l; i++) { let oldRouteInfo = oldRouteInfos[i], newRouteInfo = newRouteInfos[i]; if (!oldRouteInfo || oldRouteInfo.route !== newRouteInfo.route) { routeChanged = true; } if (routeChanged) { routes.entered.push(newRouteInfo); if (oldRouteInfo) { routes.exited.unshift(oldRouteInfo); } } else if (contextChanged || oldRouteInfo.context !== newRouteInfo.context) { contextChanged = true; routes.updatedContext.push(newRouteInfo); } else { routes.unchanged.push(oldRouteInfo); } } for (i = newRouteInfos.length, l = oldRouteInfos.length; i < l; i++) { routes.exited.unshift(oldRouteInfos[i]); } routes.reset = routes.updatedContext.slice(); routes.reset.reverse(); return routes; } _updateURL(transition, state) { let urlMethod = transition.urlMethod; if (!urlMethod) { return; } let { routeInfos } = state; let { name: routeName } = routeInfos[routeInfos.length - 1]; let params = {}; for (let i = routeInfos.length - 1; i >= 0; --i) { let routeInfo = routeInfos[i]; merge(params, routeInfo.params); if (routeInfo.route.inaccessibleByURL) { urlMethod = null; } } if (urlMethod) { params.queryParams = transition._visibleQueryParams || state.queryParams; let url = this.recognizer.generate(routeName, params); // transitions during the initial transition must always use replaceURL. // When the app boots, you are at a url, e.g. /foo. If some route // redirects to bar as part of the initial transition, you don't want to // add a history entry for /foo. If you do, pressing back will immediately // hit the redirect again and take you back to /bar, thus killing the back // button let initial = transition.isCausedByInitialTransition; // say you are at / and you click a link to route /foo. In /foo's // route, the transition is aborted using replacewith('/bar'). // Because the current url is still /, the history entry for / is // removed from the history. Clicking back will take you to the page // you were on before /, which is often not even the app, thus killing // the back button. That's why updateURL is always correct for an // aborting transition that's not the initial transition let replaceAndNotAborting = urlMethod === 'replace' && !transition.isCausedByAbortingTransition; // because calling refresh causes an aborted transition, this needs to be // special cased - if the initial transition is a replace transition, the // urlMethod should be honored here. let isQueryParamsRefreshTransition = transition.queryParamsOnly && urlMethod === 'replace'; // say you are at / and you a `replaceWith(/foo)` is called. Then, that // transition is aborted with `replaceWith(/bar)`. At the end, we should // end up with /bar replacing /. We are replacing the replace. We only // will replace the initial route if all subsequent aborts are also // replaces. However, there is some ambiguity around the correct behavior // here. let replacingReplace = urlMethod === 'replace' && transition.isCausedByAbortingReplaceTransition; if (initial || replaceAndNotAborting || isQueryParamsRefreshTransition || replacingReplace) { this.replaceURL(url); } else { this.updateURL(url); } } } finalizeQueryParamChange(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 (let k in newQueryParams) { if (newQueryParams.hasOwnProperty(k) && newQueryParams[k] === null) { delete newQueryParams[k]; } } let finalQueryParamsArray = []; this.triggerEvent(resolvedHandlers, true, 'finalizeQueryParamChange', [newQueryParams, finalQueryParamsArray, transition]); if (transition) { transition._visibleQueryParams = {}; } let finalQueryParams = {}; for (let i = 0, len = finalQueryParamsArray.length; i < len; ++i) { let qp = finalQueryParamsArray[i]; finalQueryParams[qp.key] = qp.value; if (transition && qp.visible !== false) { transition._visibleQueryParams[qp.key] = qp.value; } } return finalQueryParams; } toReadOnlyInfos(newTransition, newState) { let oldRouteInfos = this.state.routeInfos; this.fromInfos(newTransition, oldRouteInfos); this.toInfos(newTransition, newState.routeInfos); this._lastQueryParams = newState.queryParams; } fromInfos(newTransition, oldRouteInfos) { if (newTransition !== undefined && oldRouteInfos.length > 0) { let fromInfos = toReadOnlyRouteInfo(oldRouteInfos, Object.assign({}, this._lastQueryParams), true); newTransition.from = fromInfos[fromInfos.length - 1] || null; } } toInfos(newTransition, newRouteInfos, includeAttributes = false) { if (newTransition !== undefined && newRouteInfos.length > 0) { let toInfos = toReadOnlyRouteInfo(newRouteInfos, Object.assign({}, newTransition[QUERY_PARAMS_SYMBOL]), includeAttributes); newTransition.to = toInfos[toInfos.length - 1] || null; } } notifyExistingHandlers(newState, newTransition) { let oldRouteInfos = this.state.routeInfos, i, oldRouteInfoLen, oldHandler, newRouteInfo; oldRouteInfoLen = oldRouteInfos.length; for (i = 0; i < oldRouteInfoLen; i++) { oldHandler = oldRouteInfos[i]; newRouteInfo = newState.routeInfos[i]; if (!newRouteInfo || oldHandler.name !== newRouteInfo.name) { break; } if (!newRouteInfo.isResolved) {} } this.triggerEvent(oldRouteInfos, true, 'willTransition', [newTransition]); this.routeWillChange(newTransition); this.willTransition(oldRouteInfos, newState.routeInfos, newTransition); } /** Clears the current and target route routes and triggers exit on each of them starting at the leaf and traversing up through its ancestors. */ reset() { if (this.state) { forEach(this.state.routeInfos.slice().reverse(), function (routeInfo) { let route = routeInfo.route; if (route !== undefined) { if (route.exit !== undefined) { route.exit(); } } return true; }); } this.oldState = undefined; this.state = new TransitionState(); this.currentRouteInfos = undefined; } /** let handler = routeInfo.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(url) { // Perform a URL-based transition, but don't change // the URL afterward, since it already happened. if (url.charAt(0) !== '/') { url = '/' + url; } return this.doTransition(url).method(null); } /** Transition into the specified named route. If necessary, trigger the exit callback on any routes that are no longer represented by the target route. @param {String} name the name of the route */ transitionTo(name, ...contexts) { if (typeof name === 'object') { contexts.push(name); return this.doTransition(undefined, contexts, false); } return this.doTransition(name, contexts); } intermediateTransitionTo(name, ...args) { return this.doTransition(name, args, true); } refresh(pivotRoute) { let previousTransition = this.activeTransition; let state = previousTransition ? previousTransition[STATE_SYMBOL] : this.state; let routeInfos = state.routeInfos; if (pivotRoute === undefined) { pivotRoute = routeInfos[0].route; } log(this, 'Starting a refresh transition'); let name = routeInfos[routeInfos.length - 1].name; let intent = new NamedTransitionIntent(this, name, pivotRoute, [], this._changedQueryParams || state.queryParams); let newTransition = this.transitionByIntent(intent, false); // if the previous transition is a replace transition, that needs to be preserved if (previousTransition && previousTransition.urlMethod === 'replace') { newTransition.method(previousTransition.urlMethod); } return newTransition; } /** 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(name) { return this.doTransition(name).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(routeName, ...args) { let partitionedArgs = extractQueryParams(args), suppliedParams = partitionedArgs[0], queryParams = partitionedArgs[1]; // Construct a TransitionIntent with the provided params // and apply it to the present state of the router. let intent = new NamedTransitionIntent(this, routeName, undefined, suppliedParams); let state = intent.applyToState(this.state, false); let params = {}; for (let i = 0, len = state.routeInfos.length; i < len; ++i) { let routeInfo = state.routeInfos[i]; let routeParams = routeInfo.serialize(); merge(params, routeParams); } params.queryParams = queryParams; return this.recognizer.generate(routeName, params); } applyIntent(routeName, contexts) { let intent = new NamedTransitionIntent(this, routeName, undefined, contexts); let state = this.activeTransition && this.activeTransition[STATE_SYMBOL] || this.state; return intent.applyToState(state, false); } isActiveIntent(routeName, contexts, queryParams, _state) { let state = _state || this.state, targetRouteInfos = state.routeInfos, routeInfo, len; if (!targetRouteInfos.length) { return false; } let targetHandler = targetRouteInfos[targetRouteInfos.length - 1].name; let recogHandlers = this.recognizer.handlersFor(targetHandler); let index = 0; for (len = recogHandlers.length; index < len; ++index) { routeInfo = targetRouteInfos[index]; if (routeInfo.name === routeName) { break; } } if (index === recogHandlers.length) { // The provided route name isn't even in the route hierarchy. return false; } let testState = new TransitionState(); testState.routeInfos = targetRouteInfos.slice(0, index + 1); recogHandlers = recogHandlers.slice(0, index + 1); let intent = new NamedTransitionIntent(this, targetHandler, undefined, contexts); let newState = intent.applyToHandlers(testState, recogHandlers, targetHandler, true, true); let routesEqual = routeInfosEqual(newState.routeInfos, testState.routeInfos); if (!queryParams || !routesEqual) { return routesEqual; } // Get a hash of QPs that will still be active on new route let activeQPsOnNewHandler = {}; merge(activeQPsOnNewHandler, queryParams); let activeQueryParams = state.queryParams; for (let key in activeQueryParams) { if (activeQueryParams.hasOwnProperty(key) && activeQPsOnNewHandler.hasOwnProperty(key)) { activeQPsOnNewHandler[key] = activeQueryParams[key]; } } return routesEqual && !getChangelist(activeQPsOnNewHandler, queryParams); } isActive(routeName, ...args) { let partitionedArgs = extractQueryParams(args); return this.isActiveIntent(routeName, partitionedArgs[0], partitionedArgs[1]); } trigger(name, ...args) { this.triggerEvent(this.currentRouteInfos, false, name, args); } } function routeInfosEqual(routeInfos, otherRouteInfos) { if (routeInfos.length !== otherRouteInfos.length) { return false; } for (let i = 0, len = routeInfos.length; i < len; ++i) { if (routeInfos[i] !== otherRouteInfos[i]) { return false; } } return true; } function routeInfosSameExceptQueryParams(routeInfos, otherRouteInfos) { if (routeInfos.length !== otherRouteInfos.length) { return false; } for (let i = 0, len = routeInfos.length; i < len; ++i) { if (routeInfos[i].name !== otherRouteInfos[i].name) { return false; } if (!paramsEqual(routeInfos[i].params, otherRouteInfos[i].params)) { return false; } } return true; } function paramsEqual(params, otherParams) { if (!params && !otherParams) { return true; } else if (!params && !!otherParams || !!params && !otherParams) { // one is falsy but other is not; return false; } let keys = Object.keys(params); let otherKeys = Object.keys(otherParams); if (keys.length !== otherKeys.length) { return false; } for (let i = 0, len = keys.length; i < len; ++i) { let key = keys[i]; if (params[key] !== otherParams[key]) { return false; } } return true; } exports.default = Router; exports.InternalTransition = Transition; exports.logAbort = logAbort; exports.STATE_SYMBOL = STATE_SYMBOL; exports.PARAMS_SYMBOL = PARAMS_SYMBOL; exports.QUERY_PARAMS_SYMBOL = QUERY_PARAMS_SYMBOL; exports.TransitionState = TransitionState; exports.TransitionError = TransitionError; exports.InternalRouteInfo = InternalRouteInfo; }); enifed('rsvp', ['exports', 'node-module'], function (exports, _nodeModule) { 'use strict'; exports.filter = exports.async = exports.map = exports.reject = exports.resolve = exports.off = exports.on = exports.configure = exports.denodeify = exports.defer = exports.rethrow = exports.hashSettled = exports.hash = exports.race = exports.allSettled = exports.all = exports.EventTarget = exports.Promise = exports.cast = exports.asap = undefined; function callbacksFor(object) { let callbacks = object._promiseCallbacks; if (!callbacks) { callbacks = object._promiseCallbacks = {}; } return callbacks; } /** @class RSVP.EventTarget */ var EventTarget = { /** `RSVP.EventTarget.mixin` extends an object with EventTarget methods. For Example: ```javascript let object = {}; RSVP.EventTarget.mixin(object); object.on('finished', function(event) { // handle event }); object.trigger('finished', { detail: value }); ``` `EventTarget.mixin` also works with prototypes: ```javascript let Person = function() {}; RSVP.EventTarget.mixin(Person.prototype); let yehuda = new Person(); let 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(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(eventName, callback) { if (typeof callback !== 'function') { throw new TypeError('Callback must be a function'); } let allCallbacks = callbacksFor(this); let callbacks = allCallbacks[eventName]; if (!callbacks) { callbacks = allCallbacks[eventName] = []; } if (callbacks.indexOf(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 let callback1 = function(){}; let 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(eventName, callback) { let allCallbacks = callbacksFor(this); if (!callback) { allCallbacks[eventName] = []; return; } let callbacks = allCallbacks[eventName]; let index = callbacks.indexOf(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(eventName, options, label) { let allCallbacks = callbacksFor(this); let callbacks = allCallbacks[eventName]; if (callbacks) { // Don't cache the callbacks.length since it may grow let callback; for (let i = 0; i < callbacks.length; i++) { callback = callbacks[i]; callback(options, label); } } } }; const config = { instrument: false }; EventTarget['mixin'](config); function configure(name, value) { if (arguments.length === 2) { config[name] = value; } else { return config[name]; } } const queue = []; function scheduleFlush() { setTimeout(() => { for (let i = 0; i < queue.length; i++) { let entry = queue[i]; let payload = entry.payload; payload.guid = payload.key + payload.id; payload.childGuid = payload.key + payload.childId; if (payload.error) { payload.stack = payload.error.stack; } 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: Date.now(), error: config["instrument-with-stack"] ? new Error(promise._label) : null } })) { scheduleFlush(); } } /** `RSVP.Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let 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 let 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$$1(object, label) { /*jshint validthis:true */ let Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } let promise = new Constructor(noop, label); resolve$1(promise, object); return promise; } function withOwnPromise() { return new TypeError('A promises callback cannot return that same promise.'); } function objectOrFunction(x) { let type = typeof x; return x !== null && (type === 'object' || type === 'function'); } function noop() {} const PENDING = void 0; const FULFILLED = 1; const REJECTED = 2; const TRY_CATCH_ERROR = { error: null }; function getThen(promise) { try { return promise.then; } catch (error) { TRY_CATCH_ERROR.error = error; return TRY_CATCH_ERROR; } } let tryCatchCallback; function tryCatcher() { try { let target = tryCatchCallback; tryCatchCallback = null; return target.apply(this, arguments); } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR; } } function tryCatch(fn) { tryCatchCallback = fn; return tryCatcher; } function handleForeignThenable(promise, thenable, then$$1) { config.async(promise => { let sealed = false; let result = tryCatch(then$$1).call(thenable, value => { if (sealed) { return; } sealed = true; if (thenable === value) { fulfill(promise, value); } else { resolve$1(promise, value); } }, reason => { if (sealed) { return; } sealed = true; reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && result === TRY_CATCH_ERROR) { sealed = true; let error = TRY_CATCH_ERROR.error; TRY_CATCH_ERROR.error = null; 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, value => { if (thenable === value) { fulfill(promise, value); } else { resolve$1(promise, value); } }, reason => reject(promise, reason)); } } function handleMaybeThenable(promise, maybeThenable, then$$1) { let isOwnThenable = maybeThenable.constructor === promise.constructor && then$$1 === then && promise.constructor.resolve === resolve$$1; if (isOwnThenable) { handleOwnThenable(promise, maybeThenable); } else if (then$$1 === TRY_CATCH_ERROR) { let error = TRY_CATCH_ERROR.error; TRY_CATCH_ERROR.error = null; reject(promise, error); } else if (typeof then$$1 === 'function') { handleForeignThenable(promise, maybeThenable, then$$1); } else { fulfill(promise, maybeThenable); } } function resolve$1(promise, value) { if (promise === value) { fulfill(promise, value); } else if (objectOrFunction(value)) { handleMaybeThenable(promise, value, getThen(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 (config.instrument) { instrument('fulfilled', promise); } } else { config.async(publish, promise); } } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; config.async(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { let subscribers = parent._subscribers; let length = subscribers.length; parent._onError = null; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { config.async(publish, parent); } } function publish(promise) { let subscribers = promise._subscribers; let settled = promise._state; if (config.instrument) { instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise); } if (subscribers.length === 0) { return; } let child, callback, result = promise._result; for (let i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, result); } else { callback(result); } } promise._subscribers.length = 0; } function invokeCallback(state, promise, callback, result) { let hasCallback = typeof callback === 'function'; let value; if (hasCallback) { value = tryCatch(callback)(result); } else { value = result; } if (promise._state !== PENDING) { // noop } else if (value === promise) { reject(promise, withOwnPromise()); } else if (value === TRY_CATCH_ERROR) { let error = TRY_CATCH_ERROR.error; TRY_CATCH_ERROR.error = null; // release reject(promise, error); } else if (hasCallback) { resolve$1(promise, value); } else if (state === FULFILLED) { fulfill(promise, value); } else if (state === REJECTED) { reject(promise, value); } } function initializePromise(promise, resolver) { let resolved = false; try { resolver(value => { if (resolved) { return; } resolved = true; resolve$1(promise, value); }, reason => { if (resolved) { return; } resolved = true; reject(promise, reason); }); } catch (e) { reject(promise, e); } } function then(onFulfillment, onRejection, label) { let parent = this; let state = parent._state; if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) { config.instrument && instrument('chained', parent, parent); return parent; } parent._onError = null; let child = new parent.constructor(noop, label); let result = parent._result; config.instrument && instrument('chained', parent, child); if (state === PENDING) { subscribe(parent, child, onFulfillment, onRejection); } else { let callback = state === FULFILLED ? onFulfillment : onRejection; config.async(() => invokeCallback(state, child, callback, result)); } return child; } class Enumerator { constructor(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop, label); this._abortOnReject = abortOnReject; this._isUsingOwnPromise = Constructor === Promise; this._isUsingOwnResolve = Constructor.resolve === resolve$$1; this._init(...arguments); } _init(Constructor, input) { let len = input.length || 0; this.length = len; this._remaining = len; this._result = new Array(len); this._enumerate(input); } _enumerate(input) { let length = this.length; let promise = this.promise; for (let i = 0; promise._state === PENDING && i < length; i++) { this._eachEntry(input[i], i, true); } this._checkFullfillment(); } _checkFullfillment() { if (this._remaining === 0) { let result = this._result; fulfill(this.promise, result); this._result = null; } } _settleMaybeThenable(entry, i, firstPass) { let c = this._instanceConstructor; if (this._isUsingOwnResolve) { let then$$1 = getThen(entry); if (then$$1 === then && entry._state !== PENDING) { entry._onError = null; this._settledAt(entry._state, i, entry._result, firstPass); } else if (typeof then$$1 !== 'function') { this._settledAt(FULFILLED, i, entry, firstPass); } else if (this._isUsingOwnPromise) { let promise = new c(noop); handleMaybeThenable(promise, entry, then$$1); this._willSettleAt(promise, i, firstPass); } else { this._willSettleAt(new c(resolve => resolve(entry)), i, firstPass); } } else { this._willSettleAt(c.resolve(entry), i, firstPass); } } _eachEntry(entry, i, firstPass) { if (entry !== null && typeof entry === 'object') { this._settleMaybeThenable(entry, i, firstPass); } else { this._setResultAt(FULFILLED, i, entry, firstPass); } } _settledAt(state, i, value, firstPass) { let promise = this.promise; if (promise._state === PENDING) { if (this._abortOnReject && state === REJECTED) { reject(promise, value); } else { this._setResultAt(state, i, value, firstPass); this._checkFullfillment(); } } } _setResultAt(state, i, value, firstPass) { this._remaining--; this._result[i] = value; } _willSettleAt(promise, i, firstPass) { subscribe(promise, undefined, value => this._settledAt(FULFILLED, i, value, firstPass), reason => this._settledAt(REJECTED, i, reason, firstPass)); } } function setSettledResult(state, i, value) { this._remaining--; if (state === FULFILLED) { this._result[i] = { state: 'fulfilled', value: value }; } else { this._result[i] = { state: 'rejected', reason: value }; } } /** `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 let promise1 = RSVP.resolve(1); let promise2 = RSVP.resolve(2); let promise3 = RSVP.resolve(3); let 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 let promise1 = RSVP.resolve(1); let promise2 = RSVP.reject(new Error("2")); let promise3 = RSVP.reject(new Error("3")); let 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) { if (!Array.isArray(entries)) { return this.reject(new TypeError("Promise.all must be called with an array"), label); } return new Enumerator(this, entries, true /* abort on reject */, label).promise; } /** `RSVP.Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let 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 let promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let 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 */ let Constructor = this; let promise = new Constructor(noop, label); if (!Array.isArray(entries)) { reject(promise, new TypeError('Promise.race must be called with an array')); return promise; } for (let i = 0; promise._state === PENDING && i < entries.length; i++) { subscribe(Constructor.resolve(entries[i]), undefined, value => resolve$1(promise, value), reason => reject(promise, reason)); } return promise; } /** `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let 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 let 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$1(reason, label) { /*jshint validthis:true */ let Constructor = this; let promise = new Constructor(noop, label); reject(promise, reason); return promise; } const guidKey = 'rsvp_' + Date.now() + '-'; let 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 let 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){ let 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 */ class Promise { constructor(resolver, label) { this._id = counter++; this._label = label; this._state = undefined; this._result = undefined; this._subscribers = []; config.instrument && instrument('created', this); if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } } _onError(reason) { config.after(() => { if (this._onError) { config.trigger('error', reason, this._label); } }); } /** `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(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 findOtherAuthor(); } finally { // always runs // doesn't affect the return value } ``` Asynchronous example: ```js findAuthor().catch(function(reason){ return findOtherAuthor(); }).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(callback, label) { let promise = this; let constructor = promise.constructor; return promise.then(value => constructor.resolve(callback()).then(() => value), reason => constructor.resolve(callback()).then(() => { throw reason; }), label); } } Promise.cast = resolve$$1; // deprecated Promise.all = all; Promise.race = race; Promise.resolve = resolve$$1; Promise.reject = reject$1; Promise.prototype._guidKey = guidKey; /** 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 let 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 let 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} */ Promise.prototype.then = then; function makeObject(_, argumentNames) { let obj = {}; let length = _.length; let args = new Array(length); for (let x = 0; x < length; x++) { args[x] = _[x]; } for (let i = 0; i < argumentNames.length; i++) { let name = argumentNames[i]; obj[name] = args[i + 1]; } return obj; } function arrayResult(_) { let length = _.length; let args = new Array(length - 1); for (let i = 1; i < length; i++) { args[i - 1] = _[i]; } return args; } function wrapThenable(then, promise) { return { then(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 let fs = require('fs'); fs.readFile('myfile.txt', function(err, data){ if (err) return handleError(err); handleData(data); }); ``` into: ```javascript let fs = require('fs'); let 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 let 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 let 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 let 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 let app = require('express')(); let 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 let 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 let 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 let fs = require('fs'); let readFile = RSVP.denodeify(fs.readFile); let 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) { let fn = function () { let l = arguments.length; let args = new Array(l + 1); let promiseInput = false; for (let i = 0; i < l; ++i) { let arg = arguments[i]; if (!promiseInput) { // TODO: clean this up promiseInput = needsPromiseInput(arg); if (promiseInput === TRY_CATCH_ERROR) { let error = TRY_CATCH_ERROR.error; TRY_CATCH_ERROR.error = null; let p = new Promise(noop); reject(p, error); return p; } else if (promiseInput && promiseInput !== true) { arg = wrapThenable(promiseInput, arg); } } args[i] = arg; } let promise = new Promise(noop); args[l] = function (err, val) { if (err) { reject(promise, err); } else if (options === undefined) { resolve$1(promise, val); } else if (options === true) { resolve$1(promise, arrayResult(arguments)); } else if (Array.isArray(options)) { resolve$1(promise, makeObject(arguments, options)); } else { resolve$1(promise, val); } }; if (promiseInput) { return handlePromiseInput(promise, args, nodeFunc, this); } else { return handleValueInput(promise, args, nodeFunc, this); } }; fn.__proto__ = nodeFunc; return fn; } function handleValueInput(promise, args, nodeFunc, self) { let result = tryCatch(nodeFunc).apply(self, args); if (result === TRY_CATCH_ERROR) { let error = TRY_CATCH_ERROR.error; TRY_CATCH_ERROR.error = null; reject(promise, error); } return promise; } function handlePromiseInput(promise, args, nodeFunc, self) { return Promise.all(args).then(args => handleValueInput(promise, args, nodeFunc, self)); } function needsPromiseInput(arg) { if (arg !== null && typeof arg === 'object') { if (arg.constructor === Promise) { return true; } else { return getThen(arg); } } else { return false; } } /** 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$1(array, label) { return Promise.all(array, label); } class AllSettled extends Enumerator { constructor(Constructor, entries, label) { super(Constructor, entries, false /* don't abort on reject */, label); } } AllSettled.prototype._setResultAt = setSettledResult; /** `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 let promise1 = RSVP.Promise.resolve(1); let promise2 = RSVP.Promise.reject(new Error('2')); let promise3 = RSVP.Promise.reject(new Error('3')); let 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) { if (!Array.isArray(entries)) { return Promise.reject(new TypeError("Promise.allSettled must be called with an array"), label); } return new AllSettled(Promise, entries, label).promise; } /** 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$1(array, label) { return Promise.race(array, label); } class PromiseHash extends Enumerator { constructor(Constructor, object, abortOnReject = true, label) { super(Constructor, object, abortOnReject, label); } _init(Constructor, object) { this._result = {}; this._enumerate(object); } _enumerate(input) { let keys = Object.keys(input); let length = keys.length; let promise = this.promise; this._remaining = length; let key, val; for (let i = 0; promise._state === PENDING && i < length; i++) { key = keys[i]; val = input[key]; this._eachEntry(val, key, true); } this._checkFullfillment(); } } /** `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 let 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 let 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') }; let 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) { if (object === null || typeof object !== 'object') { return Promise.reject(new TypeError("Promise.hash must be called with an object"), label); } return new PromiseHash(Promise, object, label).promise; } class HashSettled extends PromiseHash { constructor(Constructor, object, label) { super(Constructor, object, false, label); } } HashSettled.prototype._setResultAt = setSettledResult; /** `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 let 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 let 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') }; let 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) { if (object === null || typeof object !== 'object') { return Promise.reject(new TypeError("RSVP.hashSettled must be called with an object"), label); } return new HashSettled(Promise, object, false, label).promise; } /** `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!'); } let 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 */ function rethrow(reason) { setTimeout(() => { throw reason; }); throw reason; } /** `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 let 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) { let deferred = { resolve: undefined, reject: undefined }; deferred.promise = new Promise((resolve, reject) => { deferred.resolve = resolve; deferred.reject = reject; }, label); return deferred; } class MapEnumerator extends Enumerator { constructor(Constructor, entries, mapFn, label) { super(Constructor, entries, true, label, mapFn); } _init(Constructor, input, bool, label, mapFn) { let len = input.length || 0; this.length = len; this._remaining = len; this._result = new Array(len); this._mapFn = mapFn; this._enumerate(input); } _setResultAt(state, i, value, firstPass) { if (firstPass) { let val = tryCatch(this._mapFn)(value, i); if (val === TRY_CATCH_ERROR) { this._settledAt(REJECTED, i, val.error, false); } else { this._eachEntry(val, i, false); } } else { this._remaining--; this._result[i] = value; } } } /** `RSVP.map` is similar to JavaScript's native `map` method. `mapFn` is eagerly called meaning that as soon as any promise resolves its value will be passed to `mapFn`. `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 let promise1 = RSVP.resolve(1); let promise2 = RSVP.resolve(2); let promise3 = RSVP.resolve(3); let promises = [ promise1, promise2, promise3 ]; let 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 let promise1 = RSVP.resolve(1); let promise2 = RSVP.reject(new Error('2')); let promise3 = RSVP.reject(new Error('3')); let promises = [ promise1, promise2, promise3 ]; let 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 let 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) { if (!Array.isArray(promises)) { return Promise.reject(new TypeError("RSVP.map must be called with an array"), label); } if (typeof mapFn !== 'function') { return Promise.reject(new TypeError("RSVP.map expects a function as a second argument"), label); } return new MapEnumerator(Promise, promises, mapFn, label).promise; } /** 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$2(value, label) { return Promise.resolve(value, label); } /** 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$2(reason, label) { return Promise.reject(reason, label); } const EMPTY_OBJECT = {}; class FilterEnumerator extends MapEnumerator { _checkFullfillment() { if (this._remaining === 0 && this._result !== null) { let result = this._result.filter(val => val !== EMPTY_OBJECT); fulfill(this.promise, result); this._result = null; } } _setResultAt(state, i, value, firstPass) { if (firstPass) { this._result[i] = value; let val = tryCatch(this._mapFn)(value, i); if (val === TRY_CATCH_ERROR) { this._settledAt(REJECTED, i, val.error, false); } else { this._eachEntry(val, i, false); } } else { this._remaining--; if (!value) { this._result[i] = EMPTY_OBJECT; } } } } /** `RSVP.filter` is similar to JavaScript's native `filter` method. `filterFn` is eagerly called meaning that as soon as any promise resolves its value will be passed to `filterFn`. `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 let promise1 = RSVP.resolve(1); let promise2 = RSVP.resolve(2); let promise3 = RSVP.resolve(3); let promises = [promise1, promise2, promise3]; let 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 let promise1 = RSVP.resolve(1); let promise2 = RSVP.reject(new Error('2')); let promise3 = RSVP.reject(new Error('3')); let promises = [ promise1, promise2, promise3 ]; let 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 let alice = { name: 'alice' }; let bob = { name: 'bob' }; let users = [ alice, bob ]; let promises = users.map(function(user){ return RSVP.resolve(user); }); let 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) { if (typeof filterFn !== 'function') { return Promise.reject(new TypeError("RSVP.filter expects function as a second argument"), label); } return Promise.resolve(promises, label).then(function (promises) { if (!Array.isArray(promises)) { throw new TypeError("RSVP.filter must be called with an array"); } return new FilterEnumerator(Promise, promises, filterFn, label).promise; }); } let len = 0; let vertxNext; function asap(callback, arg) { queue$1[len] = callback; queue$1[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$1(); } } const browserWindow = typeof window !== 'undefined' ? window : undefined; const browserGlobal = browserWindow || {}; const BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; const isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; // test for web worker but not in IE10 const isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { let nextTick = process.nextTick; // node version 0.10.x displays a deprecation warning when nextTick is used recursively // setImmediate should be used instead instead let version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { nextTick = setImmediate; } return () => nextTick(flush); } // vertx function useVertxTimer() { if (typeof vertxNext !== 'undefined') { return function () { vertxNext(flush); }; } return useSetTimeout(); } function useMutationObserver() { let iterations = 0; let observer = new BrowserMutationObserver(flush); let node = document.createTextNode(''); observer.observe(node, { characterData: true }); return () => node.data = iterations = ++iterations % 2; } // web worker function useMessageChannel() { let channel = new MessageChannel(); channel.port1.onmessage = flush; return () => channel.port2.postMessage(0); } function useSetTimeout() { return () => setTimeout(flush, 1); } const queue$1 = new Array(1000); function flush() { for (let i = 0; i < len; i += 2) { let callback = queue$1[i]; let arg = queue$1[i + 1]; callback(arg); queue$1[i] = undefined; queue$1[i + 1] = undefined; } len = 0; } function attemptVertex() { try { const vertx = Function('return this')().require('vertx'); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } let scheduleFlush$1; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush$1 = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush$1 = useMutationObserver(); } else if (isWorker) { scheduleFlush$1 = useMessageChannel(); } else if (browserWindow === undefined && typeof _nodeModule.require === 'function') { scheduleFlush$1 = attemptVertex(); } else { scheduleFlush$1 = useSetTimeout(); } // defaults config.async = asap; config.after = cb => setTimeout(cb, 0); const cast = resolve$2; const async = (callback, arg) => config.async(callback, arg); function on() { config.on(...arguments); } function off() { config.off(...arguments); } // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') { let callbacks = window['__PROMISE_INSTRUMENTATION__']; configure('instrument', true); for (let eventName in callbacks) { if (callbacks.hasOwnProperty(eventName)) { on(eventName, callbacks[eventName]); } } } // the default export here is for backwards compat: // https://github.com/tildeio/rsvp.js/issues/434 var rsvp = { asap, cast, Promise, EventTarget, all: all$1, allSettled, race: race$1, hash, hashSettled, rethrow, defer, denodeify, configure, on, off, resolve: resolve$2, reject: reject$2, map, async, filter }; exports.default = rsvp; exports.asap = asap; exports.cast = cast; exports.Promise = Promise; exports.EventTarget = EventTarget; exports.all = all$1; exports.allSettled = allSettled; exports.race = race$1; exports.hash = hash; exports.hashSettled = hashSettled; exports.rethrow = rethrow; exports.defer = defer; exports.denodeify = denodeify; exports.configure = configure; exports.on = on; exports.off = off; exports.resolve = resolve$2; exports.reject = reject$2; exports.map = map; exports.async = async; exports.filter = filter; }); requireModule('ember') }()); //# sourceMappingURL=ember.debug.map