UNPKG

1.94 MBJavaScriptView Raw
1(function() {
2/*!
3 * @overview Ember - JavaScript Application Framework
4 * @copyright Copyright 2011-2020 Tilde Inc. and contributors
5 * Portions Copyright 2006-2011 Strobe Inc.
6 * Portions Copyright 2008-2011 Apple Inc. All rights reserved.
7 * @license Licensed under MIT license
8 * See https://raw.github.com/emberjs/ember.js/master/LICENSE
9 * @version 3.21.3
10 */
11/*globals process */
12var define, require, Ember; // Used in @ember/-internals/environment/lib/global.js
13
14
15mainContext = this; // eslint-disable-line no-undef
16
17(function () {
18 var registry;
19 var seen;
20
21 function missingModule(name, referrerName) {
22 if (referrerName) {
23 throw new Error('Could not find module ' + name + ' required by: ' + referrerName);
24 } else {
25 throw new Error('Could not find module ' + name);
26 }
27 }
28
29 function internalRequire(_name, referrerName) {
30 var name = _name;
31 var mod = registry[name];
32
33 if (!mod) {
34 name = name + '/index';
35 mod = registry[name];
36 }
37
38 var exports = seen[name];
39
40 if (exports !== undefined) {
41 return exports;
42 }
43
44 exports = seen[name] = {};
45
46 if (!mod) {
47 missingModule(_name, referrerName);
48 }
49
50 var deps = mod.deps;
51 var callback = mod.callback;
52 var reified = new Array(deps.length);
53
54 for (var i = 0; i < deps.length; i++) {
55 if (deps[i] === 'exports') {
56 reified[i] = exports;
57 } else if (deps[i] === 'require') {
58 reified[i] = require;
59 } else {
60 reified[i] = internalRequire(deps[i], name);
61 }
62 }
63
64 callback.apply(this, reified);
65 return exports;
66 }
67
68 var isNode = typeof window === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
69
70 if (!isNode) {
71 Ember = this.Ember = this.Ember || {};
72 }
73
74 if (typeof Ember === 'undefined') {
75 Ember = {};
76 }
77
78 if (typeof Ember.__loader === 'undefined') {
79 registry = Object.create(null);
80 seen = Object.create(null);
81
82 define = function (name, deps, callback) {
83 var value = {};
84
85 if (!callback) {
86 value.deps = [];
87 value.callback = deps;
88 } else {
89 value.deps = deps;
90 value.callback = callback;
91 }
92
93 registry[name] = value;
94 };
95
96 require = function (name) {
97 return internalRequire(name, null);
98 }; // setup `require` module
99
100
101 require['default'] = require;
102
103 require.has = function registryHas(moduleName) {
104 return Boolean(registry[moduleName]) || Boolean(registry[moduleName + '/index']);
105 };
106
107 require._eak_seen = registry;
108 Ember.__loader = {
109 define: define,
110 require: require,
111 registry: registry
112 };
113 } else {
114 define = Ember.__loader.define;
115 require = Ember.__loader.require;
116 }
117})();
118define("@ember/-internals/browser-environment/index", ["exports"], function (_exports) {
119 "use strict";
120
121 Object.defineProperty(_exports, "__esModule", {
122 value: true
123 });
124 _exports.hasDOM = _exports.isFirefox = _exports.isChrome = _exports.userAgent = _exports.history = _exports.location = _exports.window = void 0;
125 // check if window exists and actually is the global
126 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';
127 _exports.hasDOM = hasDom;
128 var window = hasDom ? self : null;
129 _exports.window = window;
130 var location$1 = hasDom ? self.location : null;
131 _exports.location = location$1;
132 var history$1 = hasDom ? self.history : null;
133 _exports.history = history$1;
134 var userAgent = hasDom ? self.navigator.userAgent : 'Lynx (textmode)';
135 _exports.userAgent = userAgent;
136 var isChrome = hasDom ? Boolean(window.chrome) && !window.opera : false;
137 _exports.isChrome = isChrome;
138 var isFirefox = hasDom ? typeof InstallTrigger !== 'undefined' : false;
139 _exports.isFirefox = isFirefox;
140});
141define("@ember/-internals/console/index", ["exports", "@ember/debug", "@ember/deprecated-features"], function (_exports, _debug, _deprecatedFeatures) {
142 "use strict";
143
144 Object.defineProperty(_exports, "__esModule", {
145 value: true
146 });
147 _exports.default = void 0;
148 // Deliver message that the function is deprecated
149 var DEPRECATION_MESSAGE = 'Use of Ember.Logger is deprecated. Please use `console` for logging.';
150 var DEPRECATION_ID = 'ember-console.deprecate-logger';
151 var DEPRECATION_URL = 'https://emberjs.com/deprecations/v3.x#toc_use-console-rather-than-ember-logger';
152 /**
153 @module ember
154 */
155
156 /**
157 Inside Ember-Metal, simply uses the methods from `imports.console`.
158 Override this to provide more robust logging functionality.
159
160 @class Logger
161 @deprecated Use 'console' instead
162
163 @namespace Ember
164 @public
165 */
166
167 var DEPRECATED_LOGGER;
168
169 if (_deprecatedFeatures.LOGGER) {
170 DEPRECATED_LOGGER = {
171 /**
172 Logs the arguments to the console.
173 You can pass as many arguments as you want and they will be joined together with a space.
174 ```javascript
175 var foo = 1;
176 Ember.Logger.log('log value of foo:', foo);
177 // "log value of foo: 1" will be printed to the console
178 ```
179 @method log
180 @for Ember.Logger
181 @param {*} arguments
182 @public
183 */
184 log() {
185 (true && !(false) && (0, _debug.deprecate)(DEPRECATION_MESSAGE, false, {
186 id: DEPRECATION_ID,
187 until: '4.0.0',
188 url: DEPRECATION_URL
189 }));
190 return console.log(...arguments); // eslint-disable-line no-console
191 },
192
193 /**
194 Prints the arguments to the console with a warning icon.
195 You can pass as many arguments as you want and they will be joined together with a space.
196 ```javascript
197 Ember.Logger.warn('Something happened!');
198 // "Something happened!" will be printed to the console with a warning icon.
199 ```
200 @method warn
201 @for Ember.Logger
202 @param {*} arguments
203 @public
204 */
205 warn() {
206 (true && !(false) && (0, _debug.deprecate)(DEPRECATION_MESSAGE, false, {
207 id: DEPRECATION_ID,
208 until: '4.0.0',
209 url: DEPRECATION_URL
210 }));
211 return console.warn(...arguments); // eslint-disable-line no-console
212 },
213
214 /**
215 Prints the arguments to the console with an error icon, red text and a stack trace.
216 You can pass as many arguments as you want and they will be joined together with a space.
217 ```javascript
218 Ember.Logger.error('Danger! Danger!');
219 // "Danger! Danger!" will be printed to the console in red text.
220 ```
221 @method error
222 @for Ember.Logger
223 @param {*} arguments
224 @public
225 */
226 error() {
227 (true && !(false) && (0, _debug.deprecate)(DEPRECATION_MESSAGE, false, {
228 id: DEPRECATION_ID,
229 until: '4.0.0',
230 url: DEPRECATION_URL
231 }));
232 return console.error(...arguments); // eslint-disable-line no-console
233 },
234
235 /**
236 Logs the arguments to the console.
237 You can pass as many arguments as you want and they will be joined together with a space.
238 ```javascript
239 var foo = 1;
240 Ember.Logger.info('log value of foo:', foo);
241 // "log value of foo: 1" will be printed to the console
242 ```
243 @method info
244 @for Ember.Logger
245 @param {*} arguments
246 @public
247 */
248 info() {
249 (true && !(false) && (0, _debug.deprecate)(DEPRECATION_MESSAGE, false, {
250 id: DEPRECATION_ID,
251 until: '4.0.0',
252 url: DEPRECATION_URL
253 }));
254 return console.info(...arguments); // eslint-disable-line no-console
255 },
256
257 /**
258 Logs the arguments to the console in blue text.
259 You can pass as many arguments as you want and they will be joined together with a space.
260 ```javascript
261 var foo = 1;
262 Ember.Logger.debug('log value of foo:', foo);
263 // "log value of foo: 1" will be printed to the console
264 ```
265 @method debug
266 @for Ember.Logger
267 @param {*} arguments
268 @public
269 */
270 debug() {
271 (true && !(false) && (0, _debug.deprecate)(DEPRECATION_MESSAGE, false, {
272 id: DEPRECATION_ID,
273 until: '4.0.0',
274 url: DEPRECATION_URL
275 }));
276 /* eslint-disable no-console */
277
278 if (console.debug) {
279 return console.debug(...arguments);
280 }
281
282 return console.info(...arguments);
283 /* eslint-enable no-console */
284 },
285
286 /**
287 If the value passed into `Ember.Logger.assert` is not truthy it will throw an error with a stack trace.
288 ```javascript
289 Ember.Logger.assert(true); // undefined
290 Ember.Logger.assert(true === false); // Throws an Assertion failed error.
291 Ember.Logger.assert(true === false, 'Something invalid'); // Throws an Assertion failed error with message.
292 ```
293 @method assert
294 @for Ember.Logger
295 @param {Boolean} bool Value to test
296 @param {String} message Assertion message on failed
297 @public
298 */
299 assert() {
300 (true && !(false) && (0, _debug.deprecate)(DEPRECATION_MESSAGE, false, {
301 id: DEPRECATION_ID,
302 until: '4.0.0',
303 url: DEPRECATION_URL
304 }));
305 return console.assert(...arguments); // eslint-disable-line no-console
306 }
307
308 };
309 }
310
311 var _default = DEPRECATED_LOGGER;
312 _exports.default = _default;
313});
314define("@ember/-internals/container/index", ["exports", "@ember/-internals/owner", "@ember/-internals/utils", "@ember/debug", "@ember/polyfills"], function (_exports, _owner, _utils, _debug, _polyfills) {
315 "use strict";
316
317 Object.defineProperty(_exports, "__esModule", {
318 value: true
319 });
320 _exports.privatize = privatize;
321 _exports.getFactoryFor = getFactoryFor;
322 _exports.setFactoryFor = setFactoryFor;
323 _exports.INIT_FACTORY = _exports.Container = _exports.Registry = void 0;
324 var leakTracking;
325 var containers;
326
327 if (true
328 /* DEBUG */
329 ) {
330 // requires v8
331 // chrome --js-flags="--allow-natives-syntax --expose-gc"
332 // node --allow-natives-syntax --expose-gc
333 try {
334 if (typeof gc === 'function') {
335 leakTracking = (() => {
336 // avoid syntax errors when --allow-natives-syntax not present
337 var GetWeakSetValues = new Function('weakSet', 'return %GetWeakSetValues(weakSet, 0)');
338 containers = new WeakSet();
339 return {
340 hasContainers() {
341 gc();
342 return GetWeakSetValues(containers).length > 0;
343 },
344
345 reset() {
346 var values = GetWeakSetValues(containers);
347
348 for (var i = 0; i < values.length; i++) {
349 containers.delete(values[i]);
350 }
351 }
352
353 };
354 })();
355 }
356 } catch (e) {// ignore
357 }
358 }
359 /**
360 A container used to instantiate and cache objects.
361
362 Every `Container` must be associated with a `Registry`, which is referenced
363 to determine the factory and options that should be used to instantiate
364 objects.
365
366 The public API for `Container` is still in flux and should not be considered
367 stable.
368
369 @private
370 @class Container
371 */
372
373
374 class Container {
375 constructor(registry, options = {}) {
376 this.registry = registry;
377 this.owner = options.owner || null;
378 this.cache = (0, _utils.dictionary)(options.cache || null);
379 this.factoryManagerCache = (0, _utils.dictionary)(options.factoryManagerCache || null);
380 this.isDestroyed = false;
381 this.isDestroying = false;
382
383 if (true
384 /* DEBUG */
385 ) {
386 this.validationCache = (0, _utils.dictionary)(options.validationCache || null);
387
388 if (containers !== undefined) {
389 containers.add(this);
390 }
391 }
392 }
393 /**
394 @private
395 @property registry
396 @type Registry
397 @since 1.11.0
398 */
399
400 /**
401 @private
402 @property cache
403 @type InheritingDict
404 */
405
406 /**
407 @private
408 @property validationCache
409 @type InheritingDict
410 */
411
412 /**
413 Given a fullName return a corresponding instance.
414 The default behavior is for lookup to return a singleton instance.
415 The singleton is scoped to the container, allowing multiple containers
416 to all have their own locally scoped singletons.
417 ```javascript
418 let registry = new Registry();
419 let container = registry.container();
420 registry.register('api:twitter', Twitter);
421 let twitter = container.lookup('api:twitter');
422 twitter instanceof Twitter; // => true
423 // by default the container will return singletons
424 let twitter2 = container.lookup('api:twitter');
425 twitter2 instanceof Twitter; // => true
426 twitter === twitter2; //=> true
427 ```
428 If singletons are not wanted, an optional flag can be provided at lookup.
429 ```javascript
430 let registry = new Registry();
431 let container = registry.container();
432 registry.register('api:twitter', Twitter);
433 let twitter = container.lookup('api:twitter', { singleton: false });
434 let twitter2 = container.lookup('api:twitter', { singleton: false });
435 twitter === twitter2; //=> false
436 ```
437 @private
438 @method lookup
439 @param {String} fullName
440 @param {Object} [options]
441 @param {String} [options.source] The fullname of the request source (used for local lookup)
442 @return {any}
443 */
444
445
446 lookup(fullName, options) {
447 if (this.isDestroyed) {
448 throw new Error(`Can not call \`.lookup\` after the owner has been destroyed`);
449 }
450
451 (true && !(this.registry.isValidFullName(fullName)) && (0, _debug.assert)('fullName must be a proper full name', this.registry.isValidFullName(fullName)));
452 return lookup(this, this.registry.normalize(fullName), options);
453 }
454 /**
455 A depth first traversal, destroying the container, its descendant containers and all
456 their managed objects.
457 @private
458 @method destroy
459 */
460
461
462 destroy() {
463 this.isDestroying = true;
464 destroyDestroyables(this);
465 }
466
467 finalizeDestroy() {
468 resetCache(this);
469 this.isDestroyed = true;
470 }
471 /**
472 Clear either the entire cache or just the cache for a particular key.
473 @private
474 @method reset
475 @param {String} fullName optional key to reset; if missing, resets everything
476 */
477
478
479 reset(fullName) {
480 if (this.isDestroyed) return;
481
482 if (fullName === undefined) {
483 destroyDestroyables(this);
484 resetCache(this);
485 } else {
486 resetMember(this, this.registry.normalize(fullName));
487 }
488 }
489 /**
490 Returns an object that can be used to provide an owner to a
491 manually created instance.
492 @private
493 @method ownerInjection
494 @returns { Object }
495 */
496
497
498 ownerInjection() {
499 var injection = {};
500 (0, _owner.setOwner)(injection, this.owner);
501 return injection;
502 }
503 /**
504 Given a fullName, return the corresponding factory. The consumer of the factory
505 is responsible for the destruction of any factory instances, as there is no
506 way for the container to ensure instances are destroyed when it itself is
507 destroyed.
508 @public
509 @method factoryFor
510 @param {String} fullName
511 @param {Object} [options]
512 @param {String} [options.source] The fullname of the request source (used for local lookup)
513 @return {any}
514 */
515
516
517 factoryFor(fullName, options = {}) {
518 if (this.isDestroyed) {
519 throw new Error(`Can not call \`.factoryFor\` after the owner has been destroyed`);
520 }
521
522 var normalizedName = this.registry.normalize(fullName);
523 (true && !(this.registry.isValidFullName(normalizedName)) && (0, _debug.assert)('fullName must be a proper full name', this.registry.isValidFullName(normalizedName)));
524 (true && !(false
525 /* EMBER_MODULE_UNIFICATION */
526 || !options.namespace) && (0, _debug.assert)('EMBER_MODULE_UNIFICATION must be enabled to pass a namespace option to factoryFor', false || !options.namespace));
527
528 if (options.source || options.namespace) {
529 normalizedName = this.registry.expandLocalLookup(fullName, options);
530
531 if (!normalizedName) {
532 return;
533 }
534 }
535
536 return factoryFor(this, normalizedName, fullName);
537 }
538
539 }
540
541 _exports.Container = Container;
542
543 if (true
544 /* DEBUG */
545 ) {
546 Container._leakTracking = leakTracking;
547 }
548 /*
549 * Wrap a factory manager in a proxy which will not permit properties to be
550 * set on the manager.
551 */
552
553
554 function wrapManagerInDeprecationProxy(manager) {
555 if (_utils.HAS_NATIVE_PROXY) {
556 var validator = {
557 set(_obj, prop) {
558 throw new Error(`You attempted to set "${prop}" on a factory manager created by container#factoryFor. A factory manager is a read-only construct.`);
559 }
560
561 }; // Note:
562 // We have to proxy access to the manager here so that private property
563 // access doesn't cause the above errors to occur.
564
565 var m = manager;
566 var proxiedManager = {
567 class: m.class,
568
569 create(props) {
570 return m.create(props);
571 }
572
573 };
574 return new Proxy(proxiedManager, validator);
575 }
576
577 return manager;
578 }
579
580 function isSingleton(container, fullName) {
581 return container.registry.getOption(fullName, 'singleton') !== false;
582 }
583
584 function isInstantiatable(container, fullName) {
585 return container.registry.getOption(fullName, 'instantiate') !== false;
586 }
587
588 function lookup(container, fullName, options = {}) {
589 (true && !(false
590 /* EMBER_MODULE_UNIFICATION */
591 || !options.namespace) && (0, _debug.assert)('EMBER_MODULE_UNIFICATION must be enabled to pass a namespace option to lookup', false || !options.namespace));
592 var normalizedName = fullName;
593
594 if (options.source || options.namespace) {
595 normalizedName = container.registry.expandLocalLookup(fullName, options);
596
597 if (!normalizedName) {
598 return;
599 }
600 }
601
602 if (options.singleton !== false) {
603 var cached = container.cache[normalizedName];
604
605 if (cached !== undefined) {
606 return cached;
607 }
608 }
609
610 return instantiateFactory(container, normalizedName, fullName, options);
611 }
612
613 function factoryFor(container, normalizedName, fullName) {
614 var cached = container.factoryManagerCache[normalizedName];
615
616 if (cached !== undefined) {
617 return cached;
618 }
619
620 var factory = container.registry.resolve(normalizedName);
621
622 if (factory === undefined) {
623 return;
624 }
625
626 if (true
627 /* DEBUG */
628 && factory && typeof factory._onLookup === 'function') {
629 factory._onLookup(fullName);
630 }
631
632 var manager = new FactoryManager(container, factory, fullName, normalizedName);
633
634 if (true
635 /* DEBUG */
636 ) {
637 manager = wrapManagerInDeprecationProxy(manager);
638 }
639
640 container.factoryManagerCache[normalizedName] = manager;
641 return manager;
642 }
643
644 function isSingletonClass(container, fullName, {
645 instantiate,
646 singleton
647 }) {
648 return singleton !== false && !instantiate && isSingleton(container, fullName) && !isInstantiatable(container, fullName);
649 }
650
651 function isSingletonInstance(container, fullName, {
652 instantiate,
653 singleton
654 }) {
655 return singleton !== false && instantiate !== false && isSingleton(container, fullName) && isInstantiatable(container, fullName);
656 }
657
658 function isFactoryClass(container, fullname, {
659 instantiate,
660 singleton
661 }) {
662 return instantiate === false && (singleton === false || !isSingleton(container, fullname)) && !isInstantiatable(container, fullname);
663 }
664
665 function isFactoryInstance(container, fullName, {
666 instantiate,
667 singleton
668 }) {
669 return instantiate !== false && (singleton !== false || isSingleton(container, fullName)) && isInstantiatable(container, fullName);
670 }
671
672 function instantiateFactory(container, normalizedName, fullName, options) {
673 var factoryManager = factoryFor(container, normalizedName, fullName);
674
675 if (factoryManager === undefined) {
676 return;
677 } // SomeClass { singleton: true, instantiate: true } | { singleton: true } | { instantiate: true } | {}
678 // By default majority of objects fall into this case
679
680
681 if (isSingletonInstance(container, fullName, options)) {
682 var instance = container.cache[normalizedName] = factoryManager.create(); // if this lookup happened _during_ destruction (emits a deprecation, but
683 // is still possible) ensure that it gets destroyed
684
685 if (container.isDestroying) {
686 if (typeof instance.destroy === 'function') {
687 instance.destroy();
688 }
689 }
690
691 return instance;
692 } // SomeClass { singleton: false, instantiate: true }
693
694
695 if (isFactoryInstance(container, fullName, options)) {
696 return factoryManager.create();
697 } // SomeClass { singleton: true, instantiate: false } | { instantiate: false } | { singleton: false, instantiation: false }
698
699
700 if (isSingletonClass(container, fullName, options) || isFactoryClass(container, fullName, options)) {
701 return factoryManager.class;
702 }
703
704 throw new Error('Could not create factory');
705 }
706
707 function processInjections(container, injections, result) {
708 if (true
709 /* DEBUG */
710 ) {
711 container.registry.validateInjections(injections);
712 }
713
714 var hash = result.injections;
715
716 for (var i = 0; i < injections.length; i++) {
717 var {
718 property,
719 specifier,
720 source
721 } = injections[i];
722
723 if (source) {
724 hash[property] = lookup(container, specifier, {
725 source
726 });
727 } else {
728 hash[property] = lookup(container, specifier);
729 }
730
731 if (!result.isDynamic) {
732 result.isDynamic = !isSingleton(container, specifier);
733 }
734 }
735 }
736
737 function buildInjections(container, typeInjections, injections) {
738 var injectionsHash = {};
739 (0, _owner.setOwner)(injectionsHash, container.owner);
740 var result = {
741 injections: injectionsHash,
742 isDynamic: false
743 };
744
745 if (typeInjections !== undefined) {
746 processInjections(container, typeInjections, result);
747 }
748
749 if (injections !== undefined) {
750 processInjections(container, injections, result);
751 }
752
753 return result;
754 }
755
756 function injectionsFor(container, fullName) {
757 var registry = container.registry;
758 var [type] = fullName.split(':');
759 var typeInjections = registry.getTypeInjections(type);
760 var injections = registry.getInjections(fullName);
761 return buildInjections(container, typeInjections, injections);
762 }
763
764 function destroyDestroyables(container) {
765 var cache = container.cache;
766 var keys = Object.keys(cache);
767
768 for (var i = 0; i < keys.length; i++) {
769 var key = keys[i];
770 var value = cache[key];
771
772 if (value.destroy) {
773 value.destroy();
774 }
775 }
776 }
777
778 function resetCache(container) {
779 container.cache = (0, _utils.dictionary)(null);
780 container.factoryManagerCache = (0, _utils.dictionary)(null);
781 }
782
783 function resetMember(container, fullName) {
784 var member = container.cache[fullName];
785 delete container.factoryManagerCache[fullName];
786
787 if (member) {
788 delete container.cache[fullName];
789
790 if (member.destroy) {
791 member.destroy();
792 }
793 }
794 }
795
796 var INIT_FACTORY = (0, _utils.symbol)('INIT_FACTORY');
797 _exports.INIT_FACTORY = INIT_FACTORY;
798
799 function getFactoryFor(obj) {
800 return obj[INIT_FACTORY];
801 }
802
803 function setFactoryFor(obj, factory) {
804 obj[INIT_FACTORY] = factory;
805 }
806
807 class FactoryManager {
808 constructor(container, factory, fullName, normalizedName) {
809 this.container = container;
810 this.owner = container.owner;
811 this.class = factory;
812 this.fullName = fullName;
813 this.normalizedName = normalizedName;
814 this.madeToString = undefined;
815 this.injections = undefined;
816 setFactoryFor(this, this);
817 }
818
819 toString() {
820 if (this.madeToString === undefined) {
821 this.madeToString = this.container.registry.makeToString(this.class, this.fullName);
822 }
823
824 return this.madeToString;
825 }
826
827 create(options) {
828 var {
829 container
830 } = this;
831
832 if (container.isDestroyed) {
833 throw new Error(`Can not create new instances after the owner has been destroyed (you attempted to create ${this.fullName})`);
834 }
835
836 var props = this.injections;
837
838 if (props === undefined) {
839 var {
840 injections,
841 isDynamic
842 } = injectionsFor(this.container, this.normalizedName);
843 setFactoryFor(injections, this);
844 props = injections;
845
846 if (!isDynamic) {
847 this.injections = injections;
848 }
849 }
850
851 if (options !== undefined) {
852 props = (0, _polyfills.assign)({}, props, options);
853 }
854
855 if (true
856 /* DEBUG */
857 ) {
858 var lazyInjections;
859 var validationCache = this.container.validationCache; // Ensure that all lazy injections are valid at instantiation time
860
861 if (!validationCache[this.fullName] && this.class && typeof this.class._lazyInjections === 'function') {
862 lazyInjections = this.class._lazyInjections();
863 lazyInjections = this.container.registry.normalizeInjectionsHash(lazyInjections);
864 this.container.registry.validateInjections(lazyInjections);
865 }
866
867 validationCache[this.fullName] = true;
868 (true && !(typeof this.class.create === 'function') && (0, _debug.assert)(`Failed to create an instance of '${this.normalizedName}'. Most likely an improperly defined class or an invalid module export.`, typeof this.class.create === 'function'));
869 }
870
871 return this.class.create(props);
872 }
873
874 }
875
876 var VALID_FULL_NAME_REGEXP = /^[^:]+:[^:]+$/;
877 /**
878 A registry used to store factory and option information keyed
879 by type.
880
881 A `Registry` stores the factory and option information needed by a
882 `Container` to instantiate and cache objects.
883
884 The API for `Registry` is still in flux and should not be considered stable.
885
886 @private
887 @class Registry
888 @since 1.11.0
889 */
890
891 class Registry {
892 constructor(options = {}) {
893 this.fallback = options.fallback || null;
894 this.resolver = options.resolver || null;
895 this.registrations = (0, _utils.dictionary)(options.registrations || null);
896 this._typeInjections = (0, _utils.dictionary)(null);
897 this._injections = (0, _utils.dictionary)(null);
898 this._localLookupCache = Object.create(null);
899 this._normalizeCache = (0, _utils.dictionary)(null);
900 this._resolveCache = (0, _utils.dictionary)(null);
901 this._failSet = new Set();
902 this._options = (0, _utils.dictionary)(null);
903 this._typeOptions = (0, _utils.dictionary)(null);
904 }
905 /**
906 A backup registry for resolving registrations when no matches can be found.
907 @private
908 @property fallback
909 @type Registry
910 */
911
912 /**
913 An object that has a `resolve` method that resolves a name.
914 @private
915 @property resolver
916 @type Resolver
917 */
918
919 /**
920 @private
921 @property registrations
922 @type InheritingDict
923 */
924
925 /**
926 @private
927 @property _typeInjections
928 @type InheritingDict
929 */
930
931 /**
932 @private
933 @property _injections
934 @type InheritingDict
935 */
936
937 /**
938 @private
939 @property _normalizeCache
940 @type InheritingDict
941 */
942
943 /**
944 @private
945 @property _resolveCache
946 @type InheritingDict
947 */
948
949 /**
950 @private
951 @property _options
952 @type InheritingDict
953 */
954
955 /**
956 @private
957 @property _typeOptions
958 @type InheritingDict
959 */
960
961 /**
962 Creates a container based on this registry.
963 @private
964 @method container
965 @param {Object} options
966 @return {Container} created container
967 */
968
969
970 container(options) {
971 return new Container(this, options);
972 }
973 /**
974 Registers a factory for later injection.
975 Example:
976 ```javascript
977 let registry = new Registry();
978 registry.register('model:user', Person, {singleton: false });
979 registry.register('fruit:favorite', Orange);
980 registry.register('communication:main', Email, {singleton: false});
981 ```
982 @private
983 @method register
984 @param {String} fullName
985 @param {Function} factory
986 @param {Object} options
987 */
988
989
990 register(fullName, factory, options = {}) {
991 (true && !(this.isValidFullName(fullName)) && (0, _debug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
992 (true && !(factory !== undefined) && (0, _debug.assert)(`Attempting to register an unknown factory: '${fullName}'`, factory !== undefined));
993 var normalizedName = this.normalize(fullName);
994 (true && !(!this._resolveCache[normalizedName]) && (0, _debug.assert)(`Cannot re-register: '${fullName}', as it has already been resolved.`, !this._resolveCache[normalizedName]));
995
996 this._failSet.delete(normalizedName);
997
998 this.registrations[normalizedName] = factory;
999 this._options[normalizedName] = options;
1000 }
1001 /**
1002 Unregister a fullName
1003 ```javascript
1004 let registry = new Registry();
1005 registry.register('model:user', User);
1006 registry.resolve('model:user').create() instanceof User //=> true
1007 registry.unregister('model:user')
1008 registry.resolve('model:user') === undefined //=> true
1009 ```
1010 @private
1011 @method unregister
1012 @param {String} fullName
1013 */
1014
1015
1016 unregister(fullName) {
1017 (true && !(this.isValidFullName(fullName)) && (0, _debug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
1018 var normalizedName = this.normalize(fullName);
1019 this._localLookupCache = Object.create(null);
1020 delete this.registrations[normalizedName];
1021 delete this._resolveCache[normalizedName];
1022 delete this._options[normalizedName];
1023
1024 this._failSet.delete(normalizedName);
1025 }
1026 /**
1027 Given a fullName return the corresponding factory.
1028 By default `resolve` will retrieve the factory from
1029 the registry.
1030 ```javascript
1031 let registry = new Registry();
1032 registry.register('api:twitter', Twitter);
1033 registry.resolve('api:twitter') // => Twitter
1034 ```
1035 Optionally the registry can be provided with a custom resolver.
1036 If provided, `resolve` will first provide the custom resolver
1037 the opportunity to resolve the fullName, otherwise it will fallback
1038 to the registry.
1039 ```javascript
1040 let registry = new Registry();
1041 registry.resolver = function(fullName) {
1042 // lookup via the module system of choice
1043 };
1044 // the twitter factory is added to the module system
1045 registry.resolve('api:twitter') // => Twitter
1046 ```
1047 @private
1048 @method resolve
1049 @param {String} fullName
1050 @param {Object} [options]
1051 @param {String} [options.source] the fullname of the request source (used for local lookups)
1052 @return {Function} fullName's factory
1053 */
1054
1055
1056 resolve(fullName, options) {
1057 var factory = resolve(this, this.normalize(fullName), options);
1058
1059 if (factory === undefined && this.fallback !== null) {
1060 factory = this.fallback.resolve(...arguments);
1061 }
1062
1063 return factory;
1064 }
1065 /**
1066 A hook that can be used to describe how the resolver will
1067 attempt to find the factory.
1068 For example, the default Ember `.describe` returns the full
1069 class name (including namespace) where Ember's resolver expects
1070 to find the `fullName`.
1071 @private
1072 @method describe
1073 @param {String} fullName
1074 @return {string} described fullName
1075 */
1076
1077
1078 describe(fullName) {
1079 if (this.resolver !== null && this.resolver.lookupDescription) {
1080 return this.resolver.lookupDescription(fullName);
1081 } else if (this.fallback !== null) {
1082 return this.fallback.describe(fullName);
1083 } else {
1084 return fullName;
1085 }
1086 }
1087 /**
1088 A hook to enable custom fullName normalization behavior
1089 @private
1090 @method normalizeFullName
1091 @param {String} fullName
1092 @return {string} normalized fullName
1093 */
1094
1095
1096 normalizeFullName(fullName) {
1097 if (this.resolver !== null && this.resolver.normalize) {
1098 return this.resolver.normalize(fullName);
1099 } else if (this.fallback !== null) {
1100 return this.fallback.normalizeFullName(fullName);
1101 } else {
1102 return fullName;
1103 }
1104 }
1105 /**
1106 Normalize a fullName based on the application's conventions
1107 @private
1108 @method normalize
1109 @param {String} fullName
1110 @return {string} normalized fullName
1111 */
1112
1113
1114 normalize(fullName) {
1115 return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this.normalizeFullName(fullName));
1116 }
1117 /**
1118 @method makeToString
1119 @private
1120 @param {any} factory
1121 @param {string} fullName
1122 @return {function} toString function
1123 */
1124
1125
1126 makeToString(factory, fullName) {
1127 if (this.resolver !== null && this.resolver.makeToString) {
1128 return this.resolver.makeToString(factory, fullName);
1129 } else if (this.fallback !== null) {
1130 return this.fallback.makeToString(factory, fullName);
1131 } else {
1132 return factory.toString();
1133 }
1134 }
1135 /**
1136 Given a fullName check if the container is aware of its factory
1137 or singleton instance.
1138 @private
1139 @method has
1140 @param {String} fullName
1141 @param {Object} [options]
1142 @param {String} [options.source] the fullname of the request source (used for local lookups)
1143 @return {Boolean}
1144 */
1145
1146
1147 has(fullName, options) {
1148 if (!this.isValidFullName(fullName)) {
1149 return false;
1150 }
1151
1152 var source = options && options.source && this.normalize(options.source);
1153 var namespace = options && options.namespace || undefined;
1154 return has(this, this.normalize(fullName), source, namespace);
1155 }
1156 /**
1157 Allow registering options for all factories of a type.
1158 ```javascript
1159 let registry = new Registry();
1160 let container = registry.container();
1161 // if all of type `connection` must not be singletons
1162 registry.optionsForType('connection', { singleton: false });
1163 registry.register('connection:twitter', TwitterConnection);
1164 registry.register('connection:facebook', FacebookConnection);
1165 let twitter = container.lookup('connection:twitter');
1166 let twitter2 = container.lookup('connection:twitter');
1167 twitter === twitter2; // => false
1168 let facebook = container.lookup('connection:facebook');
1169 let facebook2 = container.lookup('connection:facebook');
1170 facebook === facebook2; // => false
1171 ```
1172 @private
1173 @method optionsForType
1174 @param {String} type
1175 @param {Object} options
1176 */
1177
1178
1179 optionsForType(type, options) {
1180 this._typeOptions[type] = options;
1181 }
1182
1183 getOptionsForType(type) {
1184 var optionsForType = this._typeOptions[type];
1185
1186 if (optionsForType === undefined && this.fallback !== null) {
1187 optionsForType = this.fallback.getOptionsForType(type);
1188 }
1189
1190 return optionsForType;
1191 }
1192 /**
1193 @private
1194 @method options
1195 @param {String} fullName
1196 @param {Object} options
1197 */
1198
1199
1200 options(fullName, options) {
1201 var normalizedName = this.normalize(fullName);
1202 this._options[normalizedName] = options;
1203 }
1204
1205 getOptions(fullName) {
1206 var normalizedName = this.normalize(fullName);
1207 var options = this._options[normalizedName];
1208
1209 if (options === undefined && this.fallback !== null) {
1210 options = this.fallback.getOptions(fullName);
1211 }
1212
1213 return options;
1214 }
1215
1216 getOption(fullName, optionName) {
1217 var options = this._options[fullName];
1218
1219 if (options !== undefined && options[optionName] !== undefined) {
1220 return options[optionName];
1221 }
1222
1223 var type = fullName.split(':')[0];
1224 options = this._typeOptions[type];
1225
1226 if (options && options[optionName] !== undefined) {
1227 return options[optionName];
1228 } else if (this.fallback !== null) {
1229 return this.fallback.getOption(fullName, optionName);
1230 }
1231
1232 return undefined;
1233 }
1234 /**
1235 Used only via `injection`.
1236 Provides a specialized form of injection, specifically enabling
1237 all objects of one type to be injected with a reference to another
1238 object.
1239 For example, provided each object of type `controller` needed a `router`.
1240 one would do the following:
1241 ```javascript
1242 let registry = new Registry();
1243 let container = registry.container();
1244 registry.register('router:main', Router);
1245 registry.register('controller:user', UserController);
1246 registry.register('controller:post', PostController);
1247 registry.typeInjection('controller', 'router', 'router:main');
1248 let user = container.lookup('controller:user');
1249 let post = container.lookup('controller:post');
1250 user.router instanceof Router; //=> true
1251 post.router instanceof Router; //=> true
1252 // both controllers share the same router
1253 user.router === post.router; //=> true
1254 ```
1255 @private
1256 @method typeInjection
1257 @param {String} type
1258 @param {String} property
1259 @param {String} fullName
1260 */
1261
1262
1263 typeInjection(type, property, fullName) {
1264 (true && !(this.isValidFullName(fullName)) && (0, _debug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
1265 var fullNameType = fullName.split(':')[0];
1266 (true && !(fullNameType !== type) && (0, _debug.assert)(`Cannot inject a '${fullName}' on other ${type}(s).`, fullNameType !== type));
1267 var injections = this._typeInjections[type] || (this._typeInjections[type] = []);
1268 injections.push({
1269 property,
1270 specifier: fullName
1271 });
1272 }
1273 /**
1274 Defines injection rules.
1275 These rules are used to inject dependencies onto objects when they
1276 are instantiated.
1277 Two forms of injections are possible:
1278 * Injecting one fullName on another fullName
1279 * Injecting one fullName on a type
1280 Example:
1281 ```javascript
1282 let registry = new Registry();
1283 let container = registry.container();
1284 registry.register('source:main', Source);
1285 registry.register('model:user', User);
1286 registry.register('model:post', Post);
1287 // injecting one fullName on another fullName
1288 // eg. each user model gets a post model
1289 registry.injection('model:user', 'post', 'model:post');
1290 // injecting one fullName on another type
1291 registry.injection('model', 'source', 'source:main');
1292 let user = container.lookup('model:user');
1293 let post = container.lookup('model:post');
1294 user.source instanceof Source; //=> true
1295 post.source instanceof Source; //=> true
1296 user.post instanceof Post; //=> true
1297 // and both models share the same source
1298 user.source === post.source; //=> true
1299 ```
1300 @private
1301 @method injection
1302 @param {String} factoryName
1303 @param {String} property
1304 @param {String} injectionName
1305 */
1306
1307
1308 injection(fullName, property, injectionName) {
1309 (true && !(this.isValidFullName(injectionName)) && (0, _debug.assert)(`Invalid injectionName, expected: 'type:name' got: ${injectionName}`, this.isValidFullName(injectionName)));
1310 var normalizedInjectionName = this.normalize(injectionName);
1311
1312 if (fullName.indexOf(':') === -1) {
1313 return this.typeInjection(fullName, property, normalizedInjectionName);
1314 }
1315
1316 (true && !(this.isValidFullName(fullName)) && (0, _debug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
1317 var normalizedName = this.normalize(fullName);
1318 var injections = this._injections[normalizedName] || (this._injections[normalizedName] = []);
1319 injections.push({
1320 property,
1321 specifier: normalizedInjectionName
1322 });
1323 }
1324 /**
1325 @private
1326 @method knownForType
1327 @param {String} type the type to iterate over
1328 */
1329
1330
1331 knownForType(type) {
1332 var localKnown = (0, _utils.dictionary)(null);
1333 var registeredNames = Object.keys(this.registrations);
1334
1335 for (var index = 0; index < registeredNames.length; index++) {
1336 var fullName = registeredNames[index];
1337 var itemType = fullName.split(':')[0];
1338
1339 if (itemType === type) {
1340 localKnown[fullName] = true;
1341 }
1342 }
1343
1344 var fallbackKnown, resolverKnown;
1345
1346 if (this.fallback !== null) {
1347 fallbackKnown = this.fallback.knownForType(type);
1348 }
1349
1350 if (this.resolver !== null && this.resolver.knownForType) {
1351 resolverKnown = this.resolver.knownForType(type);
1352 }
1353
1354 return (0, _polyfills.assign)({}, fallbackKnown, localKnown, resolverKnown);
1355 }
1356
1357 isValidFullName(fullName) {
1358 return VALID_FULL_NAME_REGEXP.test(fullName);
1359 }
1360
1361 getInjections(fullName) {
1362 var injections = this._injections[fullName];
1363
1364 if (this.fallback !== null) {
1365 var fallbackInjections = this.fallback.getInjections(fullName);
1366
1367 if (fallbackInjections !== undefined) {
1368 injections = injections === undefined ? fallbackInjections : injections.concat(fallbackInjections);
1369 }
1370 }
1371
1372 return injections;
1373 }
1374
1375 getTypeInjections(type) {
1376 var injections = this._typeInjections[type];
1377
1378 if (this.fallback !== null) {
1379 var fallbackInjections = this.fallback.getTypeInjections(type);
1380
1381 if (fallbackInjections !== undefined) {
1382 injections = injections === undefined ? fallbackInjections : injections.concat(fallbackInjections);
1383 }
1384 }
1385
1386 return injections;
1387 }
1388 /**
1389 Given a fullName and a source fullName returns the fully resolved
1390 fullName. Used to allow for local lookup.
1391 ```javascript
1392 let registry = new Registry();
1393 // the twitter factory is added to the module system
1394 registry.expandLocalLookup('component:post-title', { source: 'template:post' }) // => component:post/post-title
1395 ```
1396 @private
1397 @method expandLocalLookup
1398 @param {String} fullName
1399 @param {Object} [options]
1400 @param {String} [options.source] the fullname of the request source (used for local lookups)
1401 @return {String} fullName
1402 */
1403
1404
1405 expandLocalLookup(fullName, options) {
1406 if (this.resolver !== null && this.resolver.expandLocalLookup) {
1407 (true && !(this.isValidFullName(fullName)) && (0, _debug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
1408 (true && !(!options.source || this.isValidFullName(options.source)) && (0, _debug.assert)('options.source must be a proper full name', !options.source || this.isValidFullName(options.source)));
1409 var normalizedFullName = this.normalize(fullName);
1410 var normalizedSource = this.normalize(options.source);
1411 return expandLocalLookup(this, normalizedFullName, normalizedSource, options.namespace);
1412 } else if (this.fallback !== null) {
1413 return this.fallback.expandLocalLookup(fullName, options);
1414 } else {
1415 return null;
1416 }
1417 }
1418
1419 }
1420
1421 _exports.Registry = Registry;
1422
1423 if (true
1424 /* DEBUG */
1425 ) {
1426 var proto = Registry.prototype;
1427
1428 proto.normalizeInjectionsHash = function (hash) {
1429 var injections = [];
1430
1431 for (var key in hash) {
1432 if (Object.prototype.hasOwnProperty.call(hash, key)) {
1433 var {
1434 specifier,
1435 source,
1436 namespace
1437 } = hash[key];
1438 (true && !(this.isValidFullName(specifier)) && (0, _debug.assert)(`Expected a proper full name, given '${specifier}'`, this.isValidFullName(specifier)));
1439 injections.push({
1440 property: key,
1441 specifier,
1442 source,
1443 namespace
1444 });
1445 }
1446 }
1447
1448 return injections;
1449 };
1450
1451 proto.validateInjections = function (injections) {
1452 if (!injections) {
1453 return;
1454 }
1455
1456 for (var i = 0; i < injections.length; i++) {
1457 var {
1458 specifier,
1459 source,
1460 namespace
1461 } = injections[i];
1462 (true && !(this.has(specifier, {
1463 source,
1464 namespace
1465 })) && (0, _debug.assert)(`Attempting to inject an unknown injection: '${specifier}'`, this.has(specifier, {
1466 source,
1467 namespace
1468 })));
1469 }
1470 };
1471 }
1472
1473 function expandLocalLookup(registry, normalizedName, normalizedSource, namespace) {
1474 var cache = registry._localLookupCache;
1475 var normalizedNameCache = cache[normalizedName];
1476
1477 if (!normalizedNameCache) {
1478 normalizedNameCache = cache[normalizedName] = Object.create(null);
1479 }
1480
1481 var cacheKey = namespace || normalizedSource;
1482 var cached = normalizedNameCache[cacheKey];
1483
1484 if (cached !== undefined) {
1485 return cached;
1486 }
1487
1488 var expanded = registry.resolver.expandLocalLookup(normalizedName, normalizedSource, namespace);
1489 return normalizedNameCache[cacheKey] = expanded;
1490 }
1491
1492 function resolve(registry, _normalizedName, options) {
1493 var normalizedName = _normalizedName; // when `source` is provided expand normalizedName
1494 // and source into the full normalizedName
1495
1496 if (options !== undefined && (options.source || options.namespace)) {
1497 normalizedName = registry.expandLocalLookup(_normalizedName, options);
1498
1499 if (!normalizedName) {
1500 return;
1501 }
1502 }
1503
1504 var cached = registry._resolveCache[normalizedName];
1505
1506 if (cached !== undefined) {
1507 return cached;
1508 }
1509
1510 if (registry._failSet.has(normalizedName)) {
1511 return;
1512 }
1513
1514 var resolved;
1515
1516 if (registry.resolver) {
1517 resolved = registry.resolver.resolve(normalizedName);
1518 }
1519
1520 if (resolved === undefined) {
1521 resolved = registry.registrations[normalizedName];
1522 }
1523
1524 if (resolved === undefined) {
1525 registry._failSet.add(normalizedName);
1526 } else {
1527 registry._resolveCache[normalizedName] = resolved;
1528 }
1529
1530 return resolved;
1531 }
1532
1533 function has(registry, fullName, source, namespace) {
1534 return registry.resolve(fullName, {
1535 source,
1536 namespace
1537 }) !== undefined;
1538 }
1539
1540 var privateNames = (0, _utils.dictionary)(null);
1541 var privateSuffix = `${Math.random()}${Date.now()}`.replace('.', '');
1542
1543 function privatize([fullName]) {
1544 var name = privateNames[fullName];
1545
1546 if (name) {
1547 return name;
1548 }
1549
1550 var [type, rawName] = fullName.split(':');
1551 return privateNames[fullName] = (0, _utils.intern)(`${type}:${rawName}-${privateSuffix}`);
1552 }
1553 /*
1554 Public API for the container is still in flux.
1555 The public API, specified on the application namespace should be considered the stable API.
1556 // @module container
1557 @private
1558 */
1559
1560});
1561define("@ember/-internals/environment/index", ["exports", "@ember/deprecated-features"], function (_exports, _deprecatedFeatures) {
1562 "use strict";
1563
1564 Object.defineProperty(_exports, "__esModule", {
1565 value: true
1566 });
1567 _exports.getLookup = getLookup;
1568 _exports.setLookup = setLookup;
1569 _exports.getENV = getENV;
1570 _exports.ENV = _exports.context = _exports.global = void 0;
1571
1572 // from lodash to catch fake globals
1573 function checkGlobal(value) {
1574 return value && value.Object === Object ? value : undefined;
1575 } // element ids can ruin global miss checks
1576
1577
1578 function checkElementIdShadowing(value) {
1579 return value && value.nodeType === undefined ? value : undefined;
1580 } // export real global
1581
1582
1583 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
1584 new Function('return this')(); // eval outside of strict mode
1585
1586 _exports.global = global$1;
1587
1588 var context = function (global, Ember) {
1589 return Ember === undefined ? {
1590 imports: global,
1591 exports: global,
1592 lookup: global
1593 } : {
1594 // import jQuery
1595 imports: Ember.imports || global,
1596 // export Ember
1597 exports: Ember.exports || global,
1598 // search for Namespaces
1599 lookup: Ember.lookup || global
1600 };
1601 }(global$1, global$1.Ember);
1602
1603 _exports.context = context;
1604
1605 function getLookup() {
1606 return context.lookup;
1607 }
1608
1609 function setLookup(value) {
1610 context.lookup = value;
1611 }
1612 /**
1613 The hash of environment variables used to control various configuration
1614 settings. To specify your own or override default settings, add the
1615 desired properties to a global hash named `EmberENV` (or `ENV` for
1616 backwards compatibility with earlier versions of Ember). The `EmberENV`
1617 hash must be created before loading Ember.
1618
1619 @class EmberENV
1620 @type Object
1621 @public
1622 */
1623
1624
1625 var ENV = {
1626 ENABLE_OPTIONAL_FEATURES: false,
1627
1628 /**
1629 Determines whether Ember should add to `Array`, `Function`, and `String`
1630 native object prototypes, a few extra methods in order to provide a more
1631 friendly API.
1632 We generally recommend leaving this option set to true however, if you need
1633 to turn it off, you can add the configuration property
1634 `EXTEND_PROTOTYPES` to `EmberENV` and set it to `false`.
1635 Note, when disabled (the default configuration for Ember Addons), you will
1636 instead have to access all methods and functions from the Ember
1637 namespace.
1638 @property EXTEND_PROTOTYPES
1639 @type Boolean
1640 @default true
1641 @for EmberENV
1642 @public
1643 */
1644 EXTEND_PROTOTYPES: {
1645 Array: true,
1646 Function: true,
1647 String: true
1648 },
1649
1650 /**
1651 The `LOG_STACKTRACE_ON_DEPRECATION` property, when true, tells Ember to log
1652 a full stack trace during deprecation warnings.
1653 @property LOG_STACKTRACE_ON_DEPRECATION
1654 @type Boolean
1655 @default true
1656 @for EmberENV
1657 @public
1658 */
1659 LOG_STACKTRACE_ON_DEPRECATION: true,
1660
1661 /**
1662 The `LOG_VERSION` property, when true, tells Ember to log versions of all
1663 dependent libraries in use.
1664 @property LOG_VERSION
1665 @type Boolean
1666 @default true
1667 @for EmberENV
1668 @public
1669 */
1670 LOG_VERSION: true,
1671 RAISE_ON_DEPRECATION: false,
1672 STRUCTURED_PROFILE: false,
1673
1674 /**
1675 Whether to insert a `<div class="ember-view" />` wrapper around the
1676 application template. See RFC #280.
1677 This is not intended to be set directly, as the implementation may change in
1678 the future. Use `@ember/optional-features` instead.
1679 @property _APPLICATION_TEMPLATE_WRAPPER
1680 @for EmberENV
1681 @type Boolean
1682 @default true
1683 @private
1684 */
1685 _APPLICATION_TEMPLATE_WRAPPER: true,
1686
1687 /**
1688 Whether to use Glimmer Component semantics (as opposed to the classic "Curly"
1689 components semantics) for template-only components. See RFC #278.
1690 This is not intended to be set directly, as the implementation may change in
1691 the future. Use `@ember/optional-features` instead.
1692 @property _TEMPLATE_ONLY_GLIMMER_COMPONENTS
1693 @for EmberENV
1694 @type Boolean
1695 @default false
1696 @private
1697 */
1698 _TEMPLATE_ONLY_GLIMMER_COMPONENTS: false,
1699
1700 /**
1701 Whether to perform extra bookkeeping needed to make the `captureRenderTree`
1702 API work.
1703 This has to be set before the ember JavaScript code is evaluated. This is
1704 usually done by setting `window.EmberENV = { _DEBUG_RENDER_TREE: true };`
1705 before the "vendor" `<script>` tag in `index.html`.
1706 Setting the flag after Ember is already loaded will not work correctly. It
1707 may appear to work somewhat, but fundamentally broken.
1708 This is not intended to be set directly. Ember Inspector will enable the
1709 flag on behalf of the user as needed.
1710 This flag is always on in development mode.
1711 The flag is off by default in production mode, due to the cost associated
1712 with the the bookkeeping work.
1713 The expected flow is that Ember Inspector will ask the user to refresh the
1714 page after enabling the feature. It could also offer a feature where the
1715 user add some domains to the "always on" list. In either case, Ember
1716 Inspector will inject the code on the page to set the flag if needed.
1717 @property _DEBUG_RENDER_TREE
1718 @for EmberENV
1719 @type Boolean
1720 @default false
1721 @private
1722 */
1723 _DEBUG_RENDER_TREE: true
1724 /* DEBUG */
1725 ,
1726
1727 /**
1728 Whether the app is using jQuery. See RFC #294.
1729 This is not intended to be set directly, as the implementation may change in
1730 the future. Use `@ember/optional-features` instead.
1731 @property _JQUERY_INTEGRATION
1732 @for EmberENV
1733 @type Boolean
1734 @default true
1735 @private
1736 */
1737 _JQUERY_INTEGRATION: true,
1738
1739 /**
1740 Whether the app defaults to using async observers.
1741 This is not intended to be set directly, as the implementation may change in
1742 the future. Use `@ember/optional-features` instead.
1743 @property _DEFAULT_ASYNC_OBSERVERS
1744 @for EmberENV
1745 @type Boolean
1746 @default false
1747 @private
1748 */
1749 _DEFAULT_ASYNC_OBSERVERS: false,
1750
1751 /**
1752 Controls the maximum number of scheduled rerenders without "settling". In general,
1753 applications should not need to modify this environment variable, but please
1754 open an issue so that we can determine if a better default value is needed.
1755 @property _RERENDER_LOOP_LIMIT
1756 @for EmberENV
1757 @type number
1758 @default 1000
1759 @private
1760 */
1761 _RERENDER_LOOP_LIMIT: 1000,
1762 EMBER_LOAD_HOOKS: {},
1763 FEATURES: {}
1764 };
1765 _exports.ENV = ENV;
1766
1767 (EmberENV => {
1768 if (typeof EmberENV !== 'object' || EmberENV === null) return;
1769
1770 for (var flag in EmberENV) {
1771 if (!Object.prototype.hasOwnProperty.call(EmberENV, flag) || flag === 'EXTEND_PROTOTYPES' || flag === 'EMBER_LOAD_HOOKS') continue;
1772 var defaultValue = ENV[flag];
1773
1774 if (defaultValue === true) {
1775 ENV[flag] = EmberENV[flag] !== false;
1776 } else if (defaultValue === false) {
1777 ENV[flag] = EmberENV[flag] === true;
1778 }
1779 }
1780
1781 var {
1782 EXTEND_PROTOTYPES
1783 } = EmberENV;
1784
1785 if (EXTEND_PROTOTYPES !== undefined) {
1786 if (typeof EXTEND_PROTOTYPES === 'object' && EXTEND_PROTOTYPES !== null) {
1787 ENV.EXTEND_PROTOTYPES.String = EXTEND_PROTOTYPES.String !== false;
1788
1789 if (_deprecatedFeatures.FUNCTION_PROTOTYPE_EXTENSIONS) {
1790 ENV.EXTEND_PROTOTYPES.Function = EXTEND_PROTOTYPES.Function !== false;
1791 }
1792
1793 ENV.EXTEND_PROTOTYPES.Array = EXTEND_PROTOTYPES.Array !== false;
1794 } else {
1795 var isEnabled = EXTEND_PROTOTYPES !== false;
1796 ENV.EXTEND_PROTOTYPES.String = isEnabled;
1797
1798 if (_deprecatedFeatures.FUNCTION_PROTOTYPE_EXTENSIONS) {
1799 ENV.EXTEND_PROTOTYPES.Function = isEnabled;
1800 }
1801
1802 ENV.EXTEND_PROTOTYPES.Array = isEnabled;
1803 }
1804 } // TODO this does not seem to be used by anything,
1805 // can we remove it? do we need to deprecate it?
1806
1807
1808 var {
1809 EMBER_LOAD_HOOKS
1810 } = EmberENV;
1811
1812 if (typeof EMBER_LOAD_HOOKS === 'object' && EMBER_LOAD_HOOKS !== null) {
1813 for (var hookName in EMBER_LOAD_HOOKS) {
1814 if (!Object.prototype.hasOwnProperty.call(EMBER_LOAD_HOOKS, hookName)) continue;
1815 var hooks = EMBER_LOAD_HOOKS[hookName];
1816
1817 if (Array.isArray(hooks)) {
1818 ENV.EMBER_LOAD_HOOKS[hookName] = hooks.filter(hook => typeof hook === 'function');
1819 }
1820 }
1821 }
1822
1823 var {
1824 FEATURES
1825 } = EmberENV;
1826
1827 if (typeof FEATURES === 'object' && FEATURES !== null) {
1828 for (var feature in FEATURES) {
1829 if (!Object.prototype.hasOwnProperty.call(FEATURES, feature)) continue;
1830 ENV.FEATURES[feature] = FEATURES[feature] === true;
1831 }
1832 }
1833
1834 if (true
1835 /* DEBUG */
1836 ) {
1837 ENV._DEBUG_RENDER_TREE = true;
1838 }
1839 })(global$1.EmberENV);
1840
1841 function getENV() {
1842 return ENV;
1843 }
1844});
1845define("@ember/-internals/error-handling/index", ["exports"], function (_exports) {
1846 "use strict";
1847
1848 Object.defineProperty(_exports, "__esModule", {
1849 value: true
1850 });
1851 _exports.getOnerror = getOnerror;
1852 _exports.setOnerror = setOnerror;
1853 _exports.getDispatchOverride = getDispatchOverride;
1854 _exports.setDispatchOverride = setDispatchOverride;
1855 _exports.onErrorTarget = void 0;
1856 var onerror;
1857 var onErrorTarget = {
1858 get onerror() {
1859 return onerror;
1860 }
1861
1862 }; // Ember.onerror getter
1863
1864 _exports.onErrorTarget = onErrorTarget;
1865
1866 function getOnerror() {
1867 return onerror;
1868 } // Ember.onerror setter
1869
1870
1871 function setOnerror(handler) {
1872 onerror = handler;
1873 }
1874
1875 var dispatchOverride; // allows testing adapter to override dispatch
1876
1877 function getDispatchOverride() {
1878 return dispatchOverride;
1879 }
1880
1881 function setDispatchOverride(handler) {
1882 dispatchOverride = handler;
1883 }
1884});
1885define("@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) {
1886 "use strict";
1887
1888 Object.defineProperty(_exports, "__esModule", {
1889 value: true
1890 });
1891 Object.defineProperty(_exports, "DataAdapter", {
1892 enumerable: true,
1893 get: function () {
1894 return _data_adapter.default;
1895 }
1896 });
1897 Object.defineProperty(_exports, "ContainerDebugAdapter", {
1898 enumerable: true,
1899 get: function () {
1900 return _container_debug_adapter.default;
1901 }
1902 });
1903});
1904define("@ember/-internals/extension-support/lib/container_debug_adapter", ["exports", "@ember/string", "@ember/-internals/runtime"], function (_exports, _string, _runtime) {
1905 "use strict";
1906
1907 Object.defineProperty(_exports, "__esModule", {
1908 value: true
1909 });
1910 _exports.default = void 0;
1911
1912 /**
1913 @module @ember/debug
1914 */
1915
1916 /**
1917 The `ContainerDebugAdapter` helps the container and resolver interface
1918 with tools that debug Ember such as the
1919 [Ember Inspector](https://github.com/emberjs/ember-inspector)
1920 for Chrome and Firefox.
1921
1922 This class can be extended by a custom resolver implementer
1923 to override some of the methods with library-specific code.
1924
1925 The methods likely to be overridden are:
1926
1927 * `canCatalogEntriesByType`
1928 * `catalogEntriesByType`
1929
1930 The adapter will need to be registered
1931 in the application's container as `container-debug-adapter:main`.
1932
1933 Example:
1934
1935 ```javascript
1936 Application.initializer({
1937 name: "containerDebugAdapter",
1938
1939 initialize(application) {
1940 application.register('container-debug-adapter:main', require('app/container-debug-adapter'));
1941 }
1942 });
1943 ```
1944
1945 @class ContainerDebugAdapter
1946 @extends EmberObject
1947 @since 1.5.0
1948 @public
1949 */
1950 var _default = _runtime.Object.extend({
1951 /**
1952 The resolver instance of the application
1953 being debugged. This property will be injected
1954 on creation.
1955 @property resolver
1956 @default null
1957 @public
1958 */
1959 resolver: null,
1960
1961 /**
1962 Returns true if it is possible to catalog a list of available
1963 classes in the resolver for a given type.
1964 @method canCatalogEntriesByType
1965 @param {String} type The type. e.g. "model", "controller", "route".
1966 @return {boolean} whether a list is available for this type.
1967 @public
1968 */
1969 canCatalogEntriesByType(type) {
1970 if (type === 'model' || type === 'template') {
1971 return false;
1972 }
1973
1974 return true;
1975 },
1976
1977 /**
1978 Returns the available classes a given type.
1979 @method catalogEntriesByType
1980 @param {String} type The type. e.g. "model", "controller", "route".
1981 @return {Array} An array of strings.
1982 @public
1983 */
1984 catalogEntriesByType(type) {
1985 var namespaces = (0, _runtime.A)(_runtime.Namespace.NAMESPACES);
1986 var types = (0, _runtime.A)();
1987 var typeSuffixRegex = new RegExp(`${(0, _string.classify)(type)}$`);
1988 namespaces.forEach(namespace => {
1989 for (var key in namespace) {
1990 if (!Object.prototype.hasOwnProperty.call(namespace, key)) {
1991 continue;
1992 }
1993
1994 if (typeSuffixRegex.test(key)) {
1995 var klass = namespace[key];
1996
1997 if ((0, _runtime.typeOf)(klass) === 'class') {
1998 types.push((0, _string.dasherize)(key.replace(typeSuffixRegex, '')));
1999 }
2000 }
2001 }
2002 });
2003 return types;
2004 }
2005
2006 });
2007
2008 _exports.default = _default;
2009});
2010define("@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) {
2011 "use strict";
2012
2013 Object.defineProperty(_exports, "__esModule", {
2014 value: true
2015 });
2016 _exports.default = void 0;
2017
2018 /**
2019 @module @ember/debug
2020 */
2021
2022 /**
2023 The `DataAdapter` helps a data persistence library
2024 interface with tools that debug Ember such
2025 as the [Ember Inspector](https://github.com/emberjs/ember-inspector)
2026 for Chrome and Firefox.
2027
2028 This class will be extended by a persistence library
2029 which will override some of the methods with
2030 library-specific code.
2031
2032 The methods likely to be overridden are:
2033
2034 * `getFilters`
2035 * `detect`
2036 * `columnsForType`
2037 * `getRecords`
2038 * `getRecordColumnValues`
2039 * `getRecordKeywords`
2040 * `getRecordFilterValues`
2041 * `getRecordColor`
2042 * `observeRecord`
2043
2044 The adapter will need to be registered
2045 in the application's container as `dataAdapter:main`.
2046
2047 Example:
2048
2049 ```javascript
2050 Application.initializer({
2051 name: "data-adapter",
2052
2053 initialize: function(application) {
2054 application.register('data-adapter:main', DS.DataAdapter);
2055 }
2056 });
2057 ```
2058
2059 @class DataAdapter
2060 @extends EmberObject
2061 @public
2062 */
2063 var _default = _runtime.Object.extend({
2064 init() {
2065 this._super(...arguments);
2066
2067 this.releaseMethods = (0, _runtime.A)();
2068 },
2069
2070 /**
2071 The container-debug-adapter which is used
2072 to list all models.
2073 @property containerDebugAdapter
2074 @default undefined
2075 @since 1.5.0
2076 @public
2077 **/
2078 containerDebugAdapter: undefined,
2079
2080 /**
2081 The number of attributes to send
2082 as columns. (Enough to make the record
2083 identifiable).
2084 @private
2085 @property attributeLimit
2086 @default 3
2087 @since 1.3.0
2088 */
2089 attributeLimit: 3,
2090
2091 /**
2092 Ember Data > v1.0.0-beta.18
2093 requires string model names to be passed
2094 around instead of the actual factories.
2095 This is a stamp for the Ember Inspector
2096 to differentiate between the versions
2097 to be able to support older versions too.
2098 @public
2099 @property acceptsModelName
2100 */
2101 acceptsModelName: true,
2102
2103 /**
2104 Stores all methods that clear observers.
2105 These methods will be called on destruction.
2106 @private
2107 @property releaseMethods
2108 @since 1.3.0
2109 */
2110 releaseMethods: (0, _runtime.A)(),
2111
2112 /**
2113 Specifies how records can be filtered.
2114 Records returned will need to have a `filterValues`
2115 property with a key for every name in the returned array.
2116 @public
2117 @method getFilters
2118 @return {Array} List of objects defining filters.
2119 The object should have a `name` and `desc` property.
2120 */
2121 getFilters() {
2122 return (0, _runtime.A)();
2123 },
2124
2125 /**
2126 Fetch the model types and observe them for changes.
2127 @public
2128 @method watchModelTypes
2129 @param {Function} typesAdded Callback to call to add types.
2130 Takes an array of objects containing wrapped types (returned from `wrapModelType`).
2131 @param {Function} typesUpdated Callback to call when a type has changed.
2132 Takes an array of objects containing wrapped types.
2133 @return {Function} Method to call to remove all observers
2134 */
2135 watchModelTypes(typesAdded, typesUpdated) {
2136 var modelTypes = this.getModelTypes();
2137 var releaseMethods = (0, _runtime.A)();
2138 var typesToSend;
2139 typesToSend = modelTypes.map(type => {
2140 var klass = type.klass;
2141 var wrapped = this.wrapModelType(klass, type.name);
2142 releaseMethods.push(this.observeModelType(type.name, typesUpdated));
2143 return wrapped;
2144 });
2145 typesAdded(typesToSend);
2146
2147 var release = () => {
2148 releaseMethods.forEach(fn => fn());
2149 this.releaseMethods.removeObject(release);
2150 };
2151
2152 this.releaseMethods.pushObject(release);
2153 return release;
2154 },
2155
2156 _nameToClass(type) {
2157 if (typeof type === 'string') {
2158 var owner = (0, _owner.getOwner)(this);
2159 var Factory = owner.factoryFor(`model:${type}`);
2160 type = Factory && Factory.class;
2161 }
2162
2163 return type;
2164 },
2165
2166 /**
2167 Fetch the records of a given type and observe them for changes.
2168 @public
2169 @method watchRecords
2170 @param {String} modelName The model name.
2171 @param {Function} recordsAdded Callback to call to add records.
2172 Takes an array of objects containing wrapped records.
2173 The object should have the following properties:
2174 columnValues: {Object} The key and value of a table cell.
2175 object: {Object} The actual record object.
2176 @param {Function} recordsUpdated Callback to call when a record has changed.
2177 Takes an array of objects containing wrapped records.
2178 @param {Function} recordsRemoved Callback to call when a record has removed.
2179 Takes the following parameters:
2180 index: The array index where the records were removed.
2181 count: The number of records removed.
2182 @return {Function} Method to call to remove all observers.
2183 */
2184 watchRecords(modelName, recordsAdded, recordsUpdated, recordsRemoved) {
2185 var releaseMethods = (0, _runtime.A)();
2186
2187 var klass = this._nameToClass(modelName);
2188
2189 var records = this.getRecords(klass, modelName);
2190 var release;
2191
2192 function recordUpdated(updatedRecord) {
2193 recordsUpdated([updatedRecord]);
2194 }
2195
2196 var recordsToSend = records.map(record => {
2197 releaseMethods.push(this.observeRecord(record, recordUpdated));
2198 return this.wrapRecord(record);
2199 });
2200
2201 var contentDidChange = (array, idx, removedCount, addedCount) => {
2202 for (var i = idx; i < idx + addedCount; i++) {
2203 var record = (0, _metal.objectAt)(array, i);
2204 var wrapped = this.wrapRecord(record);
2205 releaseMethods.push(this.observeRecord(record, recordUpdated));
2206 recordsAdded([wrapped]);
2207 }
2208
2209 if (removedCount) {
2210 recordsRemoved(idx, removedCount);
2211 }
2212 };
2213
2214 var observer = {
2215 didChange: contentDidChange,
2216
2217 willChange() {
2218 return this;
2219 }
2220
2221 };
2222 (0, _metal.addArrayObserver)(records, this, observer);
2223
2224 release = () => {
2225 releaseMethods.forEach(fn => fn());
2226 (0, _metal.removeArrayObserver)(records, this, observer);
2227 this.releaseMethods.removeObject(release);
2228 };
2229
2230 recordsAdded(recordsToSend);
2231 this.releaseMethods.pushObject(release);
2232 return release;
2233 },
2234
2235 /**
2236 Clear all observers before destruction
2237 @private
2238 @method willDestroy
2239 */
2240 willDestroy() {
2241 this._super(...arguments);
2242
2243 this.releaseMethods.forEach(fn => fn());
2244 },
2245
2246 /**
2247 Detect whether a class is a model.
2248 Test that against the model class
2249 of your persistence library.
2250 @public
2251 @method detect
2252 @return boolean Whether the class is a model class or not.
2253 */
2254 detect() {
2255 return false;
2256 },
2257
2258 /**
2259 Get the columns for a given model type.
2260 @public
2261 @method columnsForType
2262 @return {Array} An array of columns of the following format:
2263 name: {String} The name of the column.
2264 desc: {String} Humanized description (what would show in a table column name).
2265 */
2266 columnsForType() {
2267 return (0, _runtime.A)();
2268 },
2269
2270 /**
2271 Adds observers to a model type class.
2272 @private
2273 @method observeModelType
2274 @param {String} modelName The model type name.
2275 @param {Function} typesUpdated Called when a type is modified.
2276 @return {Function} The function to call to remove observers.
2277 */
2278 observeModelType(modelName, typesUpdated) {
2279 var klass = this._nameToClass(modelName);
2280
2281 var records = this.getRecords(klass, modelName);
2282
2283 function onChange() {
2284 typesUpdated([this.wrapModelType(klass, modelName)]);
2285 }
2286
2287 var observer = {
2288 didChange(array, idx, removedCount, addedCount) {
2289 // Only re-fetch records if the record count changed
2290 // (which is all we care about as far as model types are concerned).
2291 if (removedCount > 0 || addedCount > 0) {
2292 (0, _runloop.scheduleOnce)('actions', this, onChange);
2293 }
2294 },
2295
2296 willChange() {
2297 return this;
2298 }
2299
2300 };
2301 (0, _metal.addArrayObserver)(records, this, observer);
2302
2303 var release = () => (0, _metal.removeArrayObserver)(records, this, observer);
2304
2305 return release;
2306 },
2307
2308 /**
2309 Wraps a given model type and observes changes to it.
2310 @private
2311 @method wrapModelType
2312 @param {Class} klass A model class.
2313 @param {String} modelName Name of the class.
2314 @return {Object} Contains the wrapped type and the function to remove observers
2315 Format:
2316 type: {Object} The wrapped type.
2317 The wrapped type has the following format:
2318 name: {String} The name of the type.
2319 count: {Integer} The number of records available.
2320 columns: {Columns} An array of columns to describe the record.
2321 object: {Class} The actual Model type class.
2322 release: {Function} The function to remove observers.
2323 */
2324 wrapModelType(klass, name) {
2325 var records = this.getRecords(klass, name);
2326 var typeToSend;
2327 typeToSend = {
2328 name,
2329 count: (0, _metal.get)(records, 'length'),
2330 columns: this.columnsForType(klass),
2331 object: klass
2332 };
2333 return typeToSend;
2334 },
2335
2336 /**
2337 Fetches all models defined in the application.
2338 @private
2339 @method getModelTypes
2340 @return {Array} Array of model types.
2341 */
2342 getModelTypes() {
2343 var containerDebugAdapter = this.get('containerDebugAdapter');
2344 var types;
2345
2346 if (containerDebugAdapter.canCatalogEntriesByType('model')) {
2347 types = containerDebugAdapter.catalogEntriesByType('model');
2348 } else {
2349 types = this._getObjectsOnNamespaces();
2350 } // New adapters return strings instead of classes.
2351
2352
2353 types = (0, _runtime.A)(types).map(name => {
2354 return {
2355 klass: this._nameToClass(name),
2356 name
2357 };
2358 });
2359 types = (0, _runtime.A)(types).filter(type => this.detect(type.klass));
2360 return (0, _runtime.A)(types);
2361 },
2362
2363 /**
2364 Loops over all namespaces and all objects
2365 attached to them.
2366 @private
2367 @method _getObjectsOnNamespaces
2368 @return {Array} Array of model type strings.
2369 */
2370 _getObjectsOnNamespaces() {
2371 var namespaces = (0, _runtime.A)(_runtime.Namespace.NAMESPACES);
2372 var types = (0, _runtime.A)();
2373 namespaces.forEach(namespace => {
2374 for (var key in namespace) {
2375 if (!Object.prototype.hasOwnProperty.call(namespace, key)) {
2376 continue;
2377 } // Even though we will filter again in `getModelTypes`,
2378 // we should not call `lookupFactory` on non-models
2379
2380
2381 if (!this.detect(namespace[key])) {
2382 continue;
2383 }
2384
2385 var name = (0, _string.dasherize)(key);
2386 types.push(name);
2387 }
2388 });
2389 return types;
2390 },
2391
2392 /**
2393 Fetches all loaded records for a given type.
2394 @public
2395 @method getRecords
2396 @return {Array} An array of records.
2397 This array will be observed for changes,
2398 so it should update when new records are added/removed.
2399 */
2400 getRecords() {
2401 return (0, _runtime.A)();
2402 },
2403
2404 /**
2405 Wraps a record and observers changes to it.
2406 @private
2407 @method wrapRecord
2408 @param {Object} record The record instance.
2409 @return {Object} The wrapped record. Format:
2410 columnValues: {Array}
2411 searchKeywords: {Array}
2412 */
2413 wrapRecord(record) {
2414 var recordToSend = {
2415 object: record
2416 };
2417 recordToSend.columnValues = this.getRecordColumnValues(record);
2418 recordToSend.searchKeywords = this.getRecordKeywords(record);
2419 recordToSend.filterValues = this.getRecordFilterValues(record);
2420 recordToSend.color = this.getRecordColor(record);
2421 return recordToSend;
2422 },
2423
2424 /**
2425 Gets the values for each column.
2426 @public
2427 @method getRecordColumnValues
2428 @return {Object} Keys should match column names defined
2429 by the model type.
2430 */
2431 getRecordColumnValues() {
2432 return {};
2433 },
2434
2435 /**
2436 Returns keywords to match when searching records.
2437 @public
2438 @method getRecordKeywords
2439 @return {Array} Relevant keywords for search.
2440 */
2441 getRecordKeywords() {
2442 return (0, _runtime.A)();
2443 },
2444
2445 /**
2446 Returns the values of filters defined by `getFilters`.
2447 @public
2448 @method getRecordFilterValues
2449 @param {Object} record The record instance.
2450 @return {Object} The filter values.
2451 */
2452 getRecordFilterValues() {
2453 return {};
2454 },
2455
2456 /**
2457 Each record can have a color that represents its state.
2458 @public
2459 @method getRecordColor
2460 @param {Object} record The record instance
2461 @return {String} The records color.
2462 Possible options: black, red, blue, green.
2463 */
2464 getRecordColor() {
2465 return null;
2466 },
2467
2468 /**
2469 Observes all relevant properties and re-sends the wrapped record
2470 when a change occurs.
2471 @public
2472 @method observerRecord
2473 @return {Function} The function to call to remove all observers.
2474 */
2475 observeRecord() {
2476 return function () {};
2477 }
2478
2479 });
2480
2481 _exports.default = _default;
2482});
2483define("@ember/-internals/glimmer/index", ["exports", "@ember/polyfills", "@glimmer/opcode-compiler", "@ember/-internals/metal", "@ember/-internals/owner", "@ember/-internals/runtime", "@ember/-internals/utils", "@ember/-internals/views", "@ember/debug", "@glimmer/reference", "@glimmer/runtime", "@glimmer/validator", "@ember/-internals/browser-environment", "@ember/instrumentation", "@ember/service", "@ember/runloop", "@ember/-internals/environment", "@glimmer/util", "@ember/deprecated-features", "@ember/string", "@ember/-internals/container", "@glimmer/node", "@ember/-internals/routing", "@ember/component/template-only", "@ember/error", "rsvp"], function (_exports, _polyfills, _opcodeCompiler, _metal, _owner, _runtime, _utils, _views, _debug, _reference, _runtime2, _validator, _browserEnvironment, _instrumentation, _service, _runloop, _environment2, _util, _deprecatedFeatures, _string, _container, _node, _routing, _templateOnly, _error, _rsvp) {
2484 "use strict";
2485
2486 Object.defineProperty(_exports, "__esModule", {
2487 value: true
2488 });
2489 _exports.template = template;
2490 _exports.helper = helper;
2491 _exports.escapeExpression = escapeExpression;
2492 _exports.htmlSafe = htmlSafe;
2493 _exports.isHTMLSafe = isHTMLSafe;
2494 _exports._resetRenderers = _resetRenderers;
2495 _exports.renderSettled = renderSettled;
2496 _exports.getTemplate = getTemplate;
2497 _exports.setTemplate = setTemplate;
2498 _exports.hasTemplate = hasTemplate;
2499 _exports.getTemplates = getTemplates;
2500 _exports.setTemplates = setTemplates;
2501 _exports.setupEngineRegistry = setupEngineRegistry;
2502 _exports.setupApplicationRegistry = setupApplicationRegistry;
2503 _exports._registerMacros = registerMacros;
2504 _exports.capabilities = capabilities;
2505 _exports.setComponentManager = setComponentManager;
2506 _exports.getComponentManager = getComponentManager;
2507 _exports.setModifierManager = setModifierManager;
2508 _exports.getModifierManager = getModifierManager;
2509 _exports.modifierCapabilities = capabilities$1;
2510 _exports.setComponentTemplate = setComponentTemplate;
2511 _exports.getComponentTemplate = getComponentTemplate;
2512 Object.defineProperty(_exports, "DOMChanges", {
2513 enumerable: true,
2514 get: function () {
2515 return _runtime2.DOMChanges;
2516 }
2517 });
2518 Object.defineProperty(_exports, "DOMTreeConstruction", {
2519 enumerable: true,
2520 get: function () {
2521 return _runtime2.DOMTreeConstruction;
2522 }
2523 });
2524 Object.defineProperty(_exports, "isSerializationFirstNode", {
2525 enumerable: true,
2526 get: function () {
2527 return _runtime2.isSerializationFirstNode;
2528 }
2529 });
2530 Object.defineProperty(_exports, "NodeDOMTreeConstruction", {
2531 enumerable: true,
2532 get: function () {
2533 return _node.NodeDOMTreeConstruction;
2534 }
2535 });
2536 _exports.OutletView = _exports.INVOKE = _exports.AbstractComponentManager = _exports._experimentalMacros = _exports.InteractiveRenderer = _exports.InertRenderer = _exports.Renderer = _exports.SafeString = _exports.Helper = _exports.Component = _exports.LinkComponent = _exports.TextArea = _exports.TextField = _exports.Checkbox = _exports.templateCacheCounters = _exports.RootTemplate = void 0;
2537
2538 function isTemplateFactory(template) {
2539 return typeof template === 'function';
2540 }
2541
2542 var counters = {
2543 cacheHit: 0,
2544 cacheMiss: 0
2545 };
2546 _exports.templateCacheCounters = counters;
2547
2548 function template(json) {
2549 var glimmerFactory = (0, _opcodeCompiler.templateFactory)(json);
2550 var cache = new WeakMap();
2551 var meta = glimmerFactory.meta;
2552
2553 var factory = owner => {
2554 var result = cache.get(owner);
2555
2556 if (result === undefined) {
2557 counters.cacheMiss++;
2558 result = glimmerFactory.create((0, _polyfills.assign)({
2559 owner
2560 }, meta));
2561 cache.set(owner, result);
2562 } else {
2563 counters.cacheHit++;
2564 }
2565
2566 return result;
2567 };
2568
2569 factory.__id = glimmerFactory.id;
2570 factory.__meta = meta;
2571 return factory;
2572 }
2573
2574 var RootTemplate = template({
2575 "id": "s5o9bxSn",
2576 "block": "{\"symbols\":[],\"statements\":[[1,[30,[36,0],[[32,0]],null]]],\"hasEval\":false,\"upvars\":[\"component\"]}",
2577 "meta": {
2578 "moduleName": "packages/@ember/-internals/glimmer/lib/templates/root.hbs"
2579 }
2580 });
2581 _exports.RootTemplate = RootTemplate;
2582 var ARGS = (0, _utils.enumerableSymbol)('ARGS');
2583 var HAS_BLOCK = (0, _utils.enumerableSymbol)('HAS_BLOCK');
2584 var DIRTY_TAG = (0, _utils.symbol)('DIRTY_TAG');
2585 var IS_DISPATCHING_ATTRS = (0, _utils.symbol)('IS_DISPATCHING_ATTRS');
2586 var BOUNDS = (0, _utils.symbol)('BOUNDS');
2587 /**
2588 @module @ember/component
2589 */
2590
2591 /**
2592 A component is an isolated piece of UI, represented by a template and an
2593 optional class. When a component has a class, its template's `this` value
2594 is an instance of the component class.
2595
2596 ## Template-only Components
2597
2598 The simplest way to create a component is to create a template file in
2599 `app/templates/components`. For example, if you name a template
2600 `app/templates/components/person-profile.hbs`:
2601
2602 ```app/templates/components/person-profile.hbs
2603 <h1>{{@person.name}}</h1>
2604 <img src={{@person.avatar}}>
2605 <p class='signature'>{{@person.signature}}</p>
2606 ```
2607
2608 You will be able to use `<PersonProfile />` to invoke this component elsewhere
2609 in your application:
2610
2611 ```app/templates/application.hbs
2612 <PersonProfile @person={{this.currentUser}} />
2613 ```
2614
2615 Note that component names are capitalized here in order to distinguish them
2616 from regular HTML elements, but they are dasherized in the file system.
2617
2618 While the angle bracket invocation form is generally preferred, it is also
2619 possible to invoke the same component with the `{{person-profile}}` syntax:
2620
2621 ```app/templates/application.hbs
2622 {{person-profile person=this.currentUser}}
2623 ```
2624
2625 Note that with this syntax, you use dashes in the component name and
2626 arguments are passed without the `@` sign.
2627
2628 In both cases, Ember will render the content of the component template we
2629 created above. The end result will be something like this:
2630
2631 ```html
2632 <h1>Tomster</h1>
2633 <img src="https://emberjs.com/tomster.jpg">
2634 <p class='signature'>Out of office this week</p>
2635 ```
2636
2637 ## File System Nesting
2638
2639 Components can be nested inside sub-folders for logical groupping. For
2640 example, if we placed our template in
2641 `app/templates/components/person/short-profile.hbs`, we can invoke it as
2642 `<Person::ShortProfile />`:
2643
2644 ```app/templates/application.hbs
2645 <Person::ShortProfile @person={{this.currentUser}} />
2646 ```
2647
2648 Or equivalently, `{{person/short-profile}}`:
2649
2650 ```app/templates/application.hbs
2651 {{person/short-profile person=this.currentUser}}
2652 ```
2653
2654 ## Yielding Contents
2655
2656 You can use `yield` inside a template to include the **contents** of any block
2657 attached to the component. The block will be executed in its original context:
2658
2659 ```handlebars
2660 <PersonProfile @person={{this.currentUser}}>
2661 <p>Admin mode</p>
2662 {{! Executed in the current context. }}
2663 </PersonProfile>
2664 ```
2665
2666 or
2667
2668 ```handlebars
2669 {{#person-profile person=this.currentUser}}
2670 <p>Admin mode</p>
2671 {{! Executed in the current context. }}
2672 {{/person-profile}}
2673 ```
2674
2675 ```app/templates/components/person-profile.hbs
2676 <h1>{{@person.name}}</h1>
2677 {{yield}}
2678 ```
2679
2680 ## Customizing Components With JavaScript
2681
2682 If you want to customize the component in order to handle events, transform
2683 arguments or maintain internal state, you implement a subclass of `Component`.
2684
2685 One example is to add computed properties to your component:
2686
2687 ```app/components/person-profile.js
2688 import Component from '@ember/component';
2689
2690 export default Component.extend({
2691 displayName: computed('person.title', 'person.firstName', 'person.lastName', function() {
2692 let { title, firstName, lastName } = this;
2693
2694 if (title) {
2695 return `${title} ${lastName}`;
2696 } else {
2697 return `${firstName} ${lastName}`;
2698 }
2699 })
2700 });
2701 ```
2702
2703 And then use it in the component's template:
2704
2705 ```app/templates/components/person-profile.hbs
2706 <h1>{{this.displayName}}</h1>
2707 {{yield}}
2708 ```
2709
2710 ## Customizing a Component's HTML Element in JavaScript
2711
2712 ### HTML Tag
2713
2714 The default HTML tag name used for a component's HTML representation is `div`.
2715 This can be customized by setting the `tagName` property.
2716
2717 Consider the following component class:
2718
2719 ```app/components/emphasized-paragraph.js
2720 import Component from '@ember/component';
2721
2722 export default Component.extend({
2723 tagName: 'em'
2724 });
2725 ```
2726
2727 When invoked, this component would produce output that looks something like
2728 this:
2729
2730 ```html
2731 <em id="ember1" class="ember-view"></em>
2732 ```
2733
2734 ### HTML `class` Attribute
2735
2736 The HTML `class` attribute of a component's tag can be set by providing a
2737 `classNames` property that is set to an array of strings:
2738
2739 ```app/components/my-widget.js
2740 import Component from '@ember/component';
2741
2742 export default Component.extend({
2743 classNames: ['my-class', 'my-other-class']
2744 });
2745 ```
2746
2747 Invoking this component will produce output that looks like this:
2748
2749 ```html
2750 <div id="ember1" class="ember-view my-class my-other-class"></div>
2751 ```
2752
2753 `class` attribute values can also be set by providing a `classNameBindings`
2754 property set to an array of properties names for the component. The return
2755 value of these properties will be added as part of the value for the
2756 components's `class` attribute. These properties can be computed properties:
2757
2758 ```app/components/my-widget.js
2759 import Component from '@ember/component';
2760 import { computed } from '@ember/object';
2761
2762 export default Component.extend({
2763 classNames: ['my-class', 'my-other-class'],
2764 classNameBindings: ['propertyA', 'propertyB'],
2765
2766 propertyA: 'from-a',
2767 propertyB: computed(function() {
2768 if (someLogic) { return 'from-b'; }
2769 })
2770 });
2771 ```
2772
2773 Invoking this component will produce HTML that looks like:
2774
2775 ```html
2776 <div id="ember1" class="ember-view my-class my-other-class from-a from-b"></div>
2777 ```
2778
2779 Note that `classNames` and `classNameBindings` is in addition to the `class`
2780 attribute passed with the angle bracket invocation syntax. Therefore, if this
2781 component was invoked like so:
2782
2783 ```handlebars
2784 <MyWidget class="from-invocation" />
2785 ```
2786
2787 The resulting HTML will look similar to this:
2788
2789 ```html
2790 <div id="ember1" class="from-invocation ember-view my-class my-other-class from-a from-b"></div>
2791 ```
2792
2793 If the value of a class name binding returns a boolean the property name
2794 itself will be used as the class name if the property is true. The class name
2795 will not be added if the value is `false` or `undefined`.
2796
2797 ```app/components/my-widget.js
2798 import Component from '@ember/component';
2799
2800 export default Component.extend({
2801 classNameBindings: ['hovered'],
2802
2803 hovered: true
2804 });
2805 ```
2806
2807 Invoking this component will produce HTML that looks like:
2808
2809 ```html
2810 <div id="ember1" class="ember-view hovered"></div>
2811 ```
2812
2813 ### Custom Class Names for Boolean Values
2814
2815 When using boolean class name bindings you can supply a string value other
2816 than the property name for use as the `class` HTML attribute by appending the
2817 preferred value after a ":" character when defining the binding:
2818
2819 ```app/components/my-widget.js
2820 import Component from '@ember/component';
2821
2822 export default Component.extend({
2823 classNameBindings: ['awesome:so-very-cool'],
2824
2825 awesome: true
2826 });
2827 ```
2828
2829 Invoking this component will produce HTML that looks like:
2830
2831 ```html
2832 <div id="ember1" class="ember-view so-very-cool"></div>
2833 ```
2834
2835 Boolean value class name bindings whose property names are in a
2836 camelCase-style format will be converted to a dasherized format:
2837
2838 ```app/components/my-widget.js
2839 import Component from '@ember/component';
2840
2841 export default Component.extend({
2842 classNameBindings: ['isUrgent'],
2843
2844 isUrgent: true
2845 });
2846 ```
2847
2848 Invoking this component will produce HTML that looks like:
2849
2850 ```html
2851 <div id="ember1" class="ember-view is-urgent"></div>
2852 ```
2853
2854 Class name bindings can also refer to object values that are found by
2855 traversing a path relative to the component itself:
2856
2857 ```app/components/my-widget.js
2858 import Component from '@ember/component';
2859 import EmberObject from '@ember/object';
2860
2861 export default Component.extend({
2862 classNameBindings: ['messages.empty'],
2863
2864 messages: EmberObject.create({
2865 empty: true
2866 })
2867 });
2868 ```
2869
2870 Invoking this component will produce HTML that looks like:
2871
2872 ```html
2873 <div id="ember1" class="ember-view empty"></div>
2874 ```
2875
2876 If you want to add a class name for a property which evaluates to true and
2877 and a different class name if it evaluates to false, you can pass a binding
2878 like this:
2879
2880 ```app/components/my-widget.js
2881 import Component from '@ember/component';
2882
2883 export default Component.extend({
2884 classNameBindings: ['isEnabled:enabled:disabled'],
2885 isEnabled: true
2886 });
2887 ```
2888
2889 Invoking this component will produce HTML that looks like:
2890
2891 ```html
2892 <div id="ember1" class="ember-view enabled"></div>
2893 ```
2894
2895 When isEnabled is `false`, the resulting HTML representation looks like this:
2896
2897 ```html
2898 <div id="ember1" class="ember-view disabled"></div>
2899 ```
2900
2901 This syntax offers the convenience to add a class if a property is `false`:
2902
2903 ```app/components/my-widget.js
2904 import Component from '@ember/component';
2905
2906 // Applies no class when isEnabled is true and class 'disabled' when isEnabled is false
2907 export default Component.extend({
2908 classNameBindings: ['isEnabled::disabled'],
2909 isEnabled: true
2910 });
2911 ```
2912
2913 Invoking this component when the `isEnabled` property is true will produce
2914 HTML that looks like:
2915
2916 ```html
2917 <div id="ember1" class="ember-view"></div>
2918 ```
2919
2920 Invoking it when the `isEnabled` property on the component is `false` will
2921 produce HTML that looks like:
2922
2923 ```html
2924 <div id="ember1" class="ember-view disabled"></div>
2925 ```
2926
2927 Updates to the value of a class name binding will result in automatic update
2928 of the HTML `class` attribute in the component's rendered HTML
2929 representation. If the value becomes `false` or `undefined` the class name
2930 will be removed.
2931
2932 Both `classNames` and `classNameBindings` are concatenated properties. See
2933 [EmberObject](/ember/release/classes/EmberObject) documentation for more
2934 information about concatenated properties.
2935
2936 ### Other HTML Attributes
2937
2938 The HTML attribute section of a component's tag can be set by providing an
2939 `attributeBindings` property set to an array of property names on the component.
2940 The return value of these properties will be used as the value of the component's
2941 HTML associated attribute:
2942
2943 ```app/components/my-anchor.js
2944 import Component from '@ember/component';
2945
2946 export default Component.extend({
2947 tagName: 'a',
2948 attributeBindings: ['href'],
2949
2950 href: 'http://google.com'
2951 });
2952 ```
2953
2954 Invoking this component will produce HTML that looks like:
2955
2956 ```html
2957 <a id="ember1" class="ember-view" href="http://google.com"></a>
2958 ```
2959
2960 One property can be mapped on to another by placing a ":" between
2961 the source property and the destination property:
2962
2963 ```app/components/my-anchor.js
2964 import Component from '@ember/component';
2965
2966 export default Component.extend({
2967 tagName: 'a',
2968 attributeBindings: ['url:href'],
2969
2970 url: 'http://google.com'
2971 });
2972 ```
2973
2974 Invoking this component will produce HTML that looks like:
2975
2976 ```html
2977 <a id="ember1" class="ember-view" href="http://google.com"></a>
2978 ```
2979
2980 HTML attributes passed with angle bracket invocations will take precedence
2981 over those specified in `attributeBindings`. Therefore, if this component was
2982 invoked like so:
2983
2984 ```handlebars
2985 <MyAnchor href="http://bing.com" @url="http://google.com" />
2986 ```
2987
2988 The resulting HTML will looks like this:
2989
2990 ```html
2991 <a id="ember1" class="ember-view" href="http://bing.com"></a>
2992 ```
2993
2994 Note that the `href` attribute is ultimately set to `http://bing.com`,
2995 despite it having attribute binidng to the `url` property, which was
2996 set to `http://google.com`.
2997
2998 Namespaced attributes (e.g. `xlink:href`) are supported, but have to be
2999 mapped, since `:` is not a valid character for properties in Javascript:
3000
3001 ```app/components/my-use.js
3002 import Component from '@ember/component';
3003
3004 export default Component.extend({
3005 tagName: 'use',
3006 attributeBindings: ['xlinkHref:xlink:href'],
3007
3008 xlinkHref: '#triangle'
3009 });
3010 ```
3011
3012 Invoking this component will produce HTML that looks like:
3013
3014 ```html
3015 <use xlink:href="#triangle"></use>
3016 ```
3017
3018 If the value of a property monitored by `attributeBindings` is a boolean, the
3019 attribute will be present or absent depending on the value:
3020
3021 ```app/components/my-text-input.js
3022 import Component from '@ember/component';
3023
3024 export default Component.extend({
3025 tagName: 'input',
3026 attributeBindings: ['disabled'],
3027
3028 disabled: false
3029 });
3030 ```
3031
3032 Invoking this component will produce HTML that looks like:
3033
3034 ```html
3035 <input id="ember1" class="ember-view" />
3036 ```
3037
3038 `attributeBindings` can refer to computed properties:
3039
3040 ```app/components/my-text-input.js
3041 import Component from '@ember/component';
3042 import { computed } from '@ember/object';
3043
3044 export default Component.extend({
3045 tagName: 'input',
3046 attributeBindings: ['disabled'],
3047
3048 disabled: computed(function() {
3049 if (someLogic) {
3050 return true;
3051 } else {
3052 return false;
3053 }
3054 })
3055 });
3056 ```
3057
3058 To prevent setting an attribute altogether, use `null` or `undefined` as the
3059 value of the property used in `attributeBindings`:
3060
3061 ```app/components/my-text-input.js
3062 import Component from '@ember/component';
3063
3064 export default Component.extend({
3065 tagName: 'form',
3066 attributeBindings: ['novalidate'],
3067 novalidate: null
3068 });
3069 ```
3070
3071 Updates to the property of an attribute binding will result in automatic
3072 update of the HTML attribute in the component's HTML output.
3073
3074 `attributeBindings` is a concatenated property. See
3075 [EmberObject](/ember/release/classes/EmberObject) documentation for more
3076 information about concatenated properties.
3077
3078 ## Layouts
3079
3080 The `layout` property can be used to dynamically specify a template associated
3081 with a component class, instead of relying on Ember to link together a
3082 component class and a template based on file names.
3083
3084 In general, applications should not use this feature, but it's commonly used
3085 in addons for historical reasons.
3086
3087 The `layout` property should be set to the default export of a template
3088 module, which is the name of a template file without the `.hbs` extension.
3089
3090 ```app/templates/components/person-profile.hbs
3091 <h1>Person's Title</h1>
3092 <div class='details'>{{yield}}</div>
3093 ```
3094
3095 ```app/components/person-profile.js
3096 import Component from '@ember/component';
3097 import layout from '../templates/components/person-profile';
3098
3099 export default Component.extend({
3100 layout
3101 });
3102 ```
3103
3104 If you invoke the component:
3105
3106 ```handlebars
3107 <PersonProfile>
3108 <h2>Chief Basket Weaver</h2>
3109 <h3>Fisherman Industries</h3>
3110 </PersonProfile>
3111 ```
3112
3113 or
3114
3115 ```handlebars
3116 {{#person-profile}}
3117 <h2>Chief Basket Weaver</h2>
3118 <h3>Fisherman Industries</h3>
3119 {{/person-profile}}
3120 ```
3121
3122 It will result in the following HTML output:
3123
3124 ```html
3125 <h1>Person's Title</h1>
3126 <div class="details">
3127 <h2>Chief Basket Weaver</h2>
3128 <h3>Fisherman Industries</h3>
3129 </div>
3130 ```
3131
3132 ## Handling Browser Events
3133
3134 Components can respond to user-initiated events in one of three ways: passing
3135 actions with angle bracket invocation, adding event handler methods to the
3136 component's class, or adding actions to the component's template.
3137
3138 ### Passing Actions With Angle Bracket Invocation
3139
3140 For one-off events specific to particular instance of a component, it is possible
3141 to pass actions to the component's element using angle bracket invocation syntax.
3142
3143 ```handlebars
3144 <MyWidget {{action 'firstWidgetClicked'}} />
3145
3146 <MyWidget {{action 'secondWidgetClicked'}} />
3147 ```
3148
3149 In this case, when the first component is clicked on, Ember will invoke the
3150 `firstWidgetClicked` action. When the second component is clicked on, Ember
3151 will invoke the `secondWidgetClicked` action instead.
3152
3153 Besides `{{action}}`, it is also possible to pass any arbitrary element modifiers
3154 using the angle bracket invocation syntax.
3155
3156 ### Event Handler Methods
3157
3158 Components can also respond to user-initiated events by implementing a method
3159 that matches the event name. This approach is appropriate when the same event
3160 should be handled by all instances of the same component.
3161
3162 An event object will be passed as the argument to the event handler method.
3163
3164 ```app/components/my-widget.js
3165 import Component from '@ember/component';
3166
3167 export default Component.extend({
3168 click(event) {
3169 // `event.target` is either the component's element or one of its children
3170 let tag = event.target.tagName.toLowerCase();
3171 console.log('clicked on a `<${tag}>` HTML element!');
3172 }
3173 });
3174 ```
3175
3176 In this example, whenever the user clicked anywhere inside the component, it
3177 will log a message to the console.
3178
3179 It is possible to handle event types other than `click` by implementing the
3180 following event handler methods. In addition, custom events can be registered
3181 by using `Application.customEvents`.
3182
3183 Touch events:
3184
3185 * `touchStart`
3186 * `touchMove`
3187 * `touchEnd`
3188 * `touchCancel`
3189
3190 Keyboard events:
3191
3192 * `keyDown`
3193 * `keyUp`
3194 * `keyPress`
3195
3196 Mouse events:
3197
3198 * `mouseDown`
3199 * `mouseUp`
3200 * `contextMenu`
3201 * `click`
3202 * `doubleClick`
3203 * `focusIn`
3204 * `focusOut`
3205
3206 Form events:
3207
3208 * `submit`
3209 * `change`
3210 * `focusIn`
3211 * `focusOut`
3212 * `input`
3213
3214 Drag and drop events:
3215
3216 * `dragStart`
3217 * `drag`
3218 * `dragEnter`
3219 * `dragLeave`
3220 * `dragOver`
3221 * `dragEnd`
3222 * `drop`
3223
3224 ### `{{action}}` Helper
3225
3226 Instead of handling all events of a particular type anywhere inside the
3227 component's element, you may instead want to limit it to a particular
3228 element in the component's template. In this case, it would be more
3229 convenient to implement an action instead.
3230
3231 For example, you could implement the action `hello` for the `person-profile`
3232 component:
3233
3234 ```app/components/person-profile.js
3235 import Component from '@ember/component';
3236
3237 export default Component.extend({
3238 actions: {
3239 hello(name) {
3240 console.log("Hello", name);
3241 }
3242 }
3243 });
3244 ```
3245
3246 And then use it in the component's template:
3247
3248 ```app/templates/components/person-profile.hbs
3249 <h1>{{@person.name}}</h1>
3250
3251 <button {{action 'hello' @person.name}}>
3252 Say Hello to {{@person.name}}
3253 </button>
3254 ```
3255
3256 When the user clicks the button, Ember will invoke the `hello` action,
3257 passing in the current value of `@person.name` as an argument.
3258
3259 See [Ember.Templates.helpers.action](/ember/release/classes/Ember.Templates.helpers/methods/action?anchor=action).
3260
3261 @class Component
3262 @extends Ember.CoreView
3263 @uses Ember.TargetActionSupport
3264 @uses Ember.ClassNamesSupport
3265 @uses Ember.ActionSupport
3266 @uses Ember.ViewMixin
3267 @uses Ember.ViewStateSupport
3268 @public
3269 */
3270
3271 var Component = _views.CoreView.extend(_views.ChildViewsSupport, _views.ViewStateSupport, _views.ClassNamesSupport, _runtime.TargetActionSupport, _views.ActionSupport, _views.ViewMixin, {
3272 isComponent: true,
3273
3274 init() {
3275 this._super(...arguments);
3276
3277 this[IS_DISPATCHING_ATTRS] = false;
3278 this[DIRTY_TAG] = (0, _validator.createTag)();
3279 this[BOUNDS] = null;
3280
3281 if (true
3282 /* DEBUG */
3283 && this.renderer._destinedForDOM && this.tagName === '') {
3284 var eventNames = [];
3285 var eventDispatcher = (0, _owner.getOwner)(this).lookup('event_dispatcher:main');
3286 var events = eventDispatcher && eventDispatcher._finalEvents || {}; // tslint:disable-next-line:forin
3287
3288 for (var key in events) {
3289 var methodName = events[key];
3290
3291 if (typeof this[methodName] === 'function') {
3292 eventNames.push(methodName);
3293 }
3294 } // If in a tagless component, assert that no event handlers are defined
3295
3296
3297 (true && !(!eventNames.length) && (0, _debug.assert)( // tslint:disable-next-line:max-line-length
3298 `You can not define \`${eventNames}\` function(s) to handle DOM event in the \`${this}\` tagless component since it doesn't have any DOM element.`, !eventNames.length));
3299 }
3300
3301 (true && !(this.mouseEnter === undefined) && (0, _debug.deprecate)(`${this}: Using \`mouseEnter\` event handler methods in components has been deprecated.`, this.mouseEnter === undefined, {
3302 id: 'ember-views.event-dispatcher.mouseenter-leave-move',
3303 until: '4.0.0',
3304 url: 'https://emberjs.com/deprecations/v3.x#toc_component-mouseenter-leave-move'
3305 }));
3306 (true && !(this.mouseLeave === undefined) && (0, _debug.deprecate)(`${this}: Using \`mouseLeave\` event handler methods in components has been deprecated.`, this.mouseLeave === undefined, {
3307 id: 'ember-views.event-dispatcher.mouseenter-leave-move',
3308 until: '4.0.0',
3309 url: 'https://emberjs.com/deprecations/v3.x#toc_component-mouseenter-leave-move'
3310 }));
3311 (true && !(this.mouseMove === undefined) && (0, _debug.deprecate)(`${this}: Using \`mouseMove\` event handler methods in components has been deprecated.`, this.mouseMove === undefined, {
3312 id: 'ember-views.event-dispatcher.mouseenter-leave-move',
3313 until: '4.0.0',
3314 url: 'https://emberjs.com/deprecations/v3.x#toc_component-mouseenter-leave-move'
3315 }));
3316 },
3317
3318 rerender() {
3319 (0, _validator.dirtyTag)(this[DIRTY_TAG]);
3320
3321 this._super();
3322 },
3323
3324 [_metal.PROPERTY_DID_CHANGE](key, value) {
3325 if (this[IS_DISPATCHING_ATTRS]) {
3326 return;
3327 }
3328
3329 var args = this[ARGS];
3330 var reference = args !== undefined ? args[key] : undefined;
3331
3332 if (reference !== undefined && reference[_reference.UPDATE_REFERENCED_VALUE] !== undefined) {
3333 reference[_reference.UPDATE_REFERENCED_VALUE](arguments.length === 2 ? value : (0, _metal.get)(this, key));
3334 }
3335 },
3336
3337 getAttr(key) {
3338 // TODO Intimate API should be deprecated
3339 return this.get(key);
3340 },
3341
3342 /**
3343 Normally, Ember's component model is "write-only". The component takes a
3344 bunch of attributes that it got passed in, and uses them to render its
3345 template.
3346 One nice thing about this model is that if you try to set a value to the
3347 same thing as last time, Ember (through HTMLBars) will avoid doing any
3348 work on the DOM.
3349 This is not just a performance optimization. If an attribute has not
3350 changed, it is important not to clobber the element's "hidden state".
3351 For example, if you set an input's `value` to the same value as before,
3352 it will clobber selection state and cursor position. In other words,
3353 setting an attribute is not **always** idempotent.
3354 This method provides a way to read an element's attribute and also
3355 update the last value Ember knows about at the same time. This makes
3356 setting an attribute idempotent.
3357 In particular, what this means is that if you get an `<input>` element's
3358 `value` attribute and then re-render the template with the same value,
3359 it will avoid clobbering the cursor and selection position.
3360 Since most attribute sets are idempotent in the browser, you typically
3361 can get away with reading attributes using jQuery, but the most reliable
3362 way to do so is through this method.
3363 @method readDOMAttr
3364 @param {String} name the name of the attribute
3365 @return String
3366 @public
3367 */
3368 readDOMAttr(name) {
3369 // TODO revisit this
3370 var _element = (0, _views.getViewElement)(this);
3371
3372 (true && !(_element !== null) && (0, _debug.assert)(`Cannot call \`readDOMAttr\` on ${this} which does not have an element`, _element !== null));
3373 var element = _element;
3374 var isSVG = element.namespaceURI === "http://www.w3.org/2000/svg"
3375 /* SVG */
3376 ;
3377 var {
3378 type,
3379 normalized
3380 } = (0, _runtime2.normalizeProperty)(element, name);
3381
3382 if (isSVG || type === 'attr') {
3383 return element.getAttribute(normalized);
3384 }
3385
3386 return element[normalized];
3387 },
3388
3389 /**
3390 The WAI-ARIA role of the control represented by this view. For example, a
3391 button may have a role of type 'button', or a pane may have a role of
3392 type 'alertdialog'. This property is used by assistive software to help
3393 visually challenged users navigate rich web applications.
3394 The full list of valid WAI-ARIA roles is available at:
3395 [https://www.w3.org/TR/wai-aria/#roles_categorization](https://www.w3.org/TR/wai-aria/#roles_categorization)
3396 @property ariaRole
3397 @type String
3398 @default null
3399 @public
3400 */
3401
3402 /**
3403 Enables components to take a list of parameters as arguments.
3404 For example, a component that takes two parameters with the names
3405 `name` and `age`:
3406 ```app/components/my-component.js
3407 import Component from '@ember/component';
3408 let MyComponent = Component.extend();
3409 MyComponent.reopenClass({
3410 positionalParams: ['name', 'age']
3411 });
3412 export default MyComponent;
3413 ```
3414 It can then be invoked like this:
3415 ```hbs
3416 {{my-component "John" 38}}
3417 ```
3418 The parameters can be referred to just like named parameters:
3419 ```hbs
3420 Name: {{name}}, Age: {{age}}.
3421 ```
3422 Using a string instead of an array allows for an arbitrary number of
3423 parameters:
3424 ```app/components/my-component.js
3425 import Component from '@ember/component';
3426 let MyComponent = Component.extend();
3427 MyComponent.reopenClass({
3428 positionalParams: 'names'
3429 });
3430 export default MyComponent;
3431 ```
3432 It can then be invoked like this:
3433 ```hbs
3434 {{my-component "John" "Michael" "Scott"}}
3435 ```
3436 The parameters can then be referred to by enumerating over the list:
3437 ```hbs
3438 {{#each names as |name|}}{{name}}{{/each}}
3439 ```
3440 @static
3441 @public
3442 @property positionalParams
3443 @since 1.13.0
3444 */
3445
3446 /**
3447 Called when the attributes passed into the component have been updated.
3448 Called both during the initial render of a container and during a rerender.
3449 Can be used in place of an observer; code placed here will be executed
3450 every time any attribute updates.
3451 @method didReceiveAttrs
3452 @public
3453 @since 1.13.0
3454 */
3455 didReceiveAttrs() {},
3456
3457 /**
3458 Called when the attributes passed into the component have been updated.
3459 Called both during the initial render of a container and during a rerender.
3460 Can be used in place of an observer; code placed here will be executed
3461 every time any attribute updates.
3462 @event didReceiveAttrs
3463 @public
3464 @since 1.13.0
3465 */
3466
3467 /**
3468 Called after a component has been rendered, both on initial render and
3469 in subsequent rerenders.
3470 @method didRender
3471 @public
3472 @since 1.13.0
3473 */
3474 didRender() {},
3475
3476 /**
3477 Called after a component has been rendered, both on initial render and
3478 in subsequent rerenders.
3479 @event didRender
3480 @public
3481 @since 1.13.0
3482 */
3483
3484 /**
3485 Called before a component has been rendered, both on initial render and
3486 in subsequent rerenders.
3487 @method willRender
3488 @public
3489 @since 1.13.0
3490 */
3491 willRender() {},
3492
3493 /**
3494 Called before a component has been rendered, both on initial render and
3495 in subsequent rerenders.
3496 @event willRender
3497 @public
3498 @since 1.13.0
3499 */
3500
3501 /**
3502 Called when the attributes passed into the component have been changed.
3503 Called only during a rerender, not during an initial render.
3504 @method didUpdateAttrs
3505 @public
3506 @since 1.13.0
3507 */
3508 didUpdateAttrs() {},
3509
3510 /**
3511 Called when the attributes passed into the component have been changed.
3512 Called only during a rerender, not during an initial render.
3513 @event didUpdateAttrs
3514 @public
3515 @since 1.13.0
3516 */
3517
3518 /**
3519 Called when the component is about to update and rerender itself.
3520 Called only during a rerender, not during an initial render.
3521 @method willUpdate
3522 @public
3523 @since 1.13.0
3524 */
3525 willUpdate() {},
3526
3527 /**
3528 Called when the component is about to update and rerender itself.
3529 Called only during a rerender, not during an initial render.
3530 @event willUpdate
3531 @public
3532 @since 1.13.0
3533 */
3534
3535 /**
3536 Called when the component has updated and rerendered itself.
3537 Called only during a rerender, not during an initial render.
3538 @method didUpdate
3539 @public
3540 @since 1.13.0
3541 */
3542 didUpdate() {}
3543
3544 });
3545
3546 _exports.Component = Component;
3547
3548 Component.toString = () => '@ember/component';
3549
3550 Component.reopenClass({
3551 isComponentFactory: true,
3552 positionalParams: []
3553 });
3554 var layout = template({
3555 "id": "SWbqsLhV",
3556 "block": "{\"symbols\":[],\"statements\":[],\"hasEval\":false,\"upvars\":[]}",
3557 "meta": {
3558 "moduleName": "packages/@ember/-internals/glimmer/lib/templates/empty.hbs"
3559 }
3560 });
3561 /**
3562 @module @ember/component
3563 */
3564
3565 /**
3566 The internal class used to create text inputs when the `{{input}}`
3567 helper is used with `type` of `checkbox`.
3568
3569 See [Ember.Templates.helpers.input](/ember/release/classes/Ember.Templates.helpers/methods/input?anchor=input) for usage details.
3570
3571 ## Direct manipulation of `checked`
3572
3573 The `checked` attribute of an `Checkbox` object should always be set
3574 through the Ember object or by interacting with its rendered element
3575 representation via the mouse, keyboard, or touch. Updating the value of the
3576 checkbox via jQuery will result in the checked value of the object and its
3577 element losing synchronization.
3578
3579 ## Layout and LayoutName properties
3580
3581 Because HTML `input` elements are self closing `layout` and `layoutName`
3582 properties will not be applied.
3583
3584 @class Checkbox
3585 @extends Component
3586 @public
3587 */
3588
3589 var Checkbox = Component.extend({
3590 layout,
3591
3592 /**
3593 By default, this component will add the `ember-checkbox` class to the component's element.
3594 @property classNames
3595 @type Array | String
3596 @default ['ember-checkbox']
3597 @public
3598 */
3599 classNames: ['ember-checkbox'],
3600 tagName: 'input',
3601
3602 /**
3603 By default this component will forward a number of arguments to attributes on the the
3604 component's element:
3605 * indeterminate
3606 * disabled
3607 * tabindex
3608 * name
3609 * autofocus
3610 * required
3611 * form
3612 When invoked with curly braces, this is the exhaustive list of HTML attributes you can
3613 customize (i.e. `{{input type="checkbox" disabled=true}}`).
3614 When invoked with angle bracket invocation, this list is irrelevant, because you can use HTML
3615 attribute syntax to customize the element (i.e.
3616 `<Input @type="checkbox" disabled data-custom="custom value" />`). However, `@type` and
3617 `@checked` must be passed as named arguments, not attributes.
3618 @property attributeBindings
3619 @type Array | String
3620 @default ['type', 'checked', 'indeterminate', 'disabled', 'tabindex', 'name', 'autofocus', 'required', 'form']
3621 @public
3622 */
3623 attributeBindings: ['type', 'checked', 'indeterminate', 'disabled', 'tabindex', 'name', 'autofocus', 'required', 'form'],
3624
3625 /**
3626 Sets the `type` attribute of the `Checkbox`'s element
3627 @property disabled
3628 @default false
3629 @private
3630 */
3631 type: 'checkbox',
3632
3633 /**
3634 Sets the `disabled` attribute of the `Checkbox`'s element
3635 @property disabled
3636 @default false
3637 @public
3638 */
3639 disabled: false,
3640
3641 /**
3642 Corresponds to the `indeterminate` property of the `Checkbox`'s element
3643 @property disabled
3644 @default false
3645 @public
3646 */
3647 indeterminate: false,
3648
3649 /**
3650 Whenever the checkbox is inserted into the DOM, perform initialization steps, which include
3651 setting the indeterminate property if needed.
3652 If this method is overridden, `super` must be called.
3653 @method
3654 @public
3655 */
3656 didInsertElement() {
3657 this._super(...arguments);
3658
3659 this.element.indeterminate = Boolean(this.indeterminate);
3660 },
3661
3662 /**
3663 Whenever the `change` event is fired on the checkbox, update its `checked` property to reflect
3664 whether the checkbox is checked.
3665 If this method is overridden, `super` must be called.
3666 @method
3667 @public
3668 */
3669 change() {
3670 (0, _metal.set)(this, 'checked', this.element.checked);
3671 }
3672
3673 });
3674 _exports.Checkbox = Checkbox;
3675
3676 if (true
3677 /* DEBUG */
3678 ) {
3679 var UNSET = {};
3680 Checkbox.reopen({
3681 value: UNSET,
3682
3683 didReceiveAttrs() {
3684 this._super();
3685
3686 (true && !(!(this.type === 'checkbox' && this.value !== UNSET)) && (0, _debug.assert)("`<Input @type='checkbox' @value={{...}} />` is not supported; " + "please use `<Input @type='checkbox' @checked={{...}} />` instead.", !(this.type === 'checkbox' && this.value !== UNSET)));
3687 }
3688
3689 });
3690 }
3691
3692 Checkbox.toString = () => '@ember/component/checkbox';
3693 /**
3694 @module @ember/component
3695 */
3696
3697
3698 var inputTypes = _browserEnvironment.hasDOM ? Object.create(null) : null;
3699
3700 function canSetTypeOfInput(type) {
3701 // if running in outside of a browser always return
3702 // the original type
3703 if (!_browserEnvironment.hasDOM) {
3704 return Boolean(type);
3705 }
3706
3707 if (type in inputTypes) {
3708 return inputTypes[type];
3709 }
3710
3711 var inputTypeTestElement = document.createElement('input');
3712
3713 try {
3714 inputTypeTestElement.type = type;
3715 } catch (e) {// ignored
3716 }
3717
3718 return inputTypes[type] = inputTypeTestElement.type === type;
3719 }
3720 /**
3721 The internal class used to create text inputs when the `Input` component is used with `type` of `text`.
3722
3723 See [Ember.Templates.components.Input](/ember/release/classes/Ember.Templates.components/methods/Input?anchor=Input) for usage details.
3724
3725 ## Layout and LayoutName properties
3726
3727 Because HTML `input` elements are self closing `layout` and `layoutName`
3728 properties will not be applied.
3729
3730 @class TextField
3731 @extends Component
3732 @uses Ember.TextSupport
3733 @public
3734 */
3735
3736
3737 var TextField = Component.extend(_views.TextSupport, {
3738 layout,
3739
3740 /**
3741 By default, this component will add the `ember-text-field` class to the component's element.
3742 @property classNames
3743 @type Array | String
3744 @default ['ember-text-field']
3745 @public
3746 */
3747 classNames: ['ember-text-field'],
3748 tagName: 'input',
3749
3750 /**
3751 By default this component will forward a number of arguments to attributes on the the
3752 component's element:
3753 * accept
3754 * autocomplete
3755 * autosave
3756 * dir
3757 * formaction
3758 * formenctype
3759 * formmethod
3760 * formnovalidate
3761 * formtarget
3762 * height
3763 * inputmode
3764 * lang
3765 * list
3766 * type
3767 * max
3768 * min
3769 * multiple
3770 * name
3771 * pattern
3772 * size
3773 * step
3774 * value
3775 * width
3776 When invoked with `{{input type="text"}}`, you can only customize these attributes. When invoked
3777 with `<Input @type="text" />`, you can just use HTML attributes directly.
3778 @property attributeBindings
3779 @type Array | String
3780 @default ['accept', 'autocomplete', 'autosave', 'dir', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'height', 'inputmode', 'lang', 'list', 'type', 'max', 'min', 'multiple', 'name', 'pattern', 'size', 'step', 'value', 'width']
3781 @public
3782 */
3783 attributeBindings: ['accept', 'autocomplete', 'autosave', 'dir', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'height', 'inputmode', 'lang', 'list', 'type', 'max', 'min', 'multiple', 'name', 'pattern', 'size', 'step', 'value', 'width'],
3784
3785 /**
3786 As the user inputs text, this property is updated to reflect the `value` property of the HTML
3787 element.
3788 @property value
3789 @type String
3790 @default ""
3791 @public
3792 */
3793 value: '',
3794
3795 /**
3796 The `type` attribute of the input element.
3797 @property type
3798 @type String
3799 @default "text"
3800 @public
3801 */
3802 type: (0, _metal.computed)({
3803 get() {
3804 return 'text';
3805 },
3806
3807 set(_key, value) {
3808 var type = 'text';
3809
3810 if (canSetTypeOfInput(value)) {
3811 type = value;
3812 }
3813
3814 return type;
3815 }
3816
3817 }),
3818
3819 /**
3820 The `size` of the text field in characters.
3821 @property size
3822 @type String
3823 @default null
3824 @public
3825 */
3826 size: null,
3827
3828 /**
3829 The `pattern` attribute of input element.
3830 @property pattern
3831 @type String
3832 @default null
3833 @public
3834 */
3835 pattern: null,
3836
3837 /**
3838 The `min` attribute of input element used with `type="number"` or `type="range"`.
3839 @property min
3840 @type String
3841 @default null
3842 @since 1.4.0
3843 @public
3844 */
3845 min: null,
3846
3847 /**
3848 The `max` attribute of input element used with `type="number"` or `type="range"`.
3849 @property max
3850 @type String
3851 @default null
3852 @since 1.4.0
3853 @public
3854 */
3855 max: null
3856 });
3857 _exports.TextField = TextField;
3858
3859 TextField.toString = () => '@ember/component/text-field';
3860 /**
3861 @module @ember/component
3862 */
3863
3864 /**
3865 The `Textarea` component inserts a new instance of `<textarea>` tag into the template.
3866
3867 The `@value` argument provides the content of the `<textarea>`.
3868
3869 This template:
3870
3871 ```handlebars
3872 <Textarea @value="A bunch of text" />
3873 ```
3874
3875 Would result in the following HTML:
3876
3877 ```html
3878 <textarea class="ember-text-area">
3879 A bunch of text
3880 </textarea>
3881 ```
3882
3883 The `@value` argument is two-way bound. If the user types text into the textarea, the `@value`
3884 argument is updated. If the `@value` argument is updated, the text in the textarea is updated.
3885
3886 In the following example, the `writtenWords` property on the component will be updated as the user
3887 types 'Lots of text' into the text area of their browser's window.
3888
3889 ```app/components/word-editor.js
3890 import Component from '@glimmer/component';
3891 import { tracked } from '@glimmer/tracking';
3892
3893 export default class WordEditorComponent extends Component {
3894 @tracked writtenWords = "Lots of text that IS bound";
3895 }
3896 ```
3897
3898 ```handlebars
3899 <Textarea @value={{writtenWords}} />
3900 ```
3901
3902 Would result in the following HTML:
3903
3904 ```html
3905 <textarea class="ember-text-area">
3906 Lots of text that IS bound
3907 </textarea>
3908 ```
3909
3910 If you wanted a one way binding, you could use the `<textarea>` element directly, and use the
3911 `value` DOM property and the `input` event.
3912
3913 ### Actions
3914
3915 The `Textarea` component takes a number of arguments with callbacks that are invoked in
3916 response to user events.
3917
3918 * `enter`
3919 * `insert-newline`
3920 * `escape-press`
3921 * `focus-in`
3922 * `focus-out`
3923 * `key-press`
3924
3925 These callbacks are passed to `Textarea` like this:
3926
3927 ```handlebars
3928 <Textarea @value={{this.searchWord}} @enter={{this.query}} />
3929 ```
3930
3931 ## Classic Invocation Syntax
3932
3933 The `Textarea` component can also be invoked using curly braces, just like any other Ember
3934 component.
3935
3936 For example, this is an invocation using angle-bracket notation:
3937
3938 ```handlebars
3939 <Textarea @value={{this.searchWord}} @enter={{this.query}} />
3940 ```
3941
3942 You could accomplish the same thing using classic invocation:
3943
3944 ```handlebars
3945 {{textarea value=this.searchWord enter=this.query}}
3946 ```
3947
3948 The main difference is that angle-bracket invocation supports any HTML attribute using HTML
3949 attribute syntax, because attributes and arguments have different syntax when using angle-bracket
3950 invocation. Curly brace invocation, on the other hand, only has a single syntax for arguments,
3951 and components must manually map attributes onto component arguments.
3952
3953 When using classic invocation with `{{textarea}}`, only the following attributes are mapped onto
3954 arguments:
3955
3956 * rows
3957 * cols
3958 * name
3959 * selectionEnd
3960 * selectionStart
3961 * autocomplete
3962 * wrap
3963 * lang
3964 * dir
3965 * value
3966
3967 ## Classic `layout` and `layoutName` properties
3968
3969 Because HTML `textarea` elements do not contain inner HTML the `layout` and
3970 `layoutName` properties will not be applied.
3971
3972 @method Textarea
3973 @for Ember.Templates.components
3974 @see {TextArea}
3975 @public
3976 */
3977
3978 /**
3979 See Ember.Templates.components.Textarea.
3980
3981 @method textarea
3982 @for Ember.Templates.helpers
3983 @see {Ember.Templates.components.textarea}
3984 @public
3985 */
3986
3987 /**
3988 The internal representation used for `Textarea` invocations.
3989
3990 @class TextArea
3991 @extends Component
3992 @see {Ember.Templates.components.Textarea}
3993 @uses Ember.TextSupport
3994 @public
3995 */
3996
3997
3998 var TextArea = Component.extend(_views.TextSupport, {
3999 classNames: ['ember-text-area'],
4000 layout,
4001 tagName: 'textarea',
4002 attributeBindings: ['rows', 'cols', 'name', 'selectionEnd', 'selectionStart', 'autocomplete', 'wrap', 'lang', 'dir', 'value'],
4003 rows: null,
4004 cols: null
4005 });
4006 _exports.TextArea = TextArea;
4007
4008 TextArea.toString = () => '@ember/component/text-area';
4009
4010 var layout$1 = template({
4011 "id": "uDKxl8ne",
4012 "block": "{\"symbols\":[\"&default\"],\"statements\":[[6,[37,0],[[27,[32,1]]],null,[[\"default\",\"else\"],[{\"statements\":[[18,1,null]],\"parameters\":[]},{\"statements\":[[1,[32,0,[\"linkTitle\"]]]],\"parameters\":[]}]]]],\"hasEval\":false,\"upvars\":[\"if\"]}",
4013 "meta": {
4014 "moduleName": "packages/@ember/-internals/glimmer/lib/templates/link-to.hbs"
4015 }
4016 });
4017 /**
4018 @module ember
4019 */
4020
4021 /**
4022 The `LinkTo` component renders a link to the supplied `routeName` passing an optionally
4023 supplied model to the route as its `model` context of the route. The block for `LinkTo`
4024 becomes the contents of the rendered element:
4025
4026 ```handlebars
4027 <LinkTo @route='photoGallery'>
4028 Great Hamster Photos
4029 </LinkTo>
4030 ```
4031
4032 This will result in:
4033
4034 ```html
4035 <a href="/hamster-photos">
4036 Great Hamster Photos
4037 </a>
4038 ```
4039
4040 ### Disabling the `LinkTo` component
4041
4042 The `LinkTo` component can be disabled by using the `disabled` argument. A disabled link
4043 doesn't result in a transition when activated, and adds the `disabled` class to the `<a>`
4044 element.
4045
4046 (The class name to apply to the element can be overridden by using the `disabledClass`
4047 argument)
4048
4049 ```handlebars
4050 <LinkTo @route='photoGallery' @disabled={{true}}>
4051 Great Hamster Photos
4052 </LinkTo>
4053 ```
4054
4055 ### Handling `href`
4056
4057 `<LinkTo>` will use your application's Router to fill the element's `href` property with a URL
4058 that matches the path to the supplied `routeName`.
4059
4060 ### Handling current route
4061
4062 The `LinkTo` component will apply a CSS class name of 'active' when the application's current
4063 route matches the supplied routeName. For example, if the application's current route is
4064 'photoGallery.recent', then the following invocation of `LinkTo`:
4065
4066 ```handlebars
4067 <LinkTo @route='photoGallery.recent'>
4068 Great Hamster Photos
4069 </LinkTo>
4070 ```
4071
4072 will result in
4073
4074 ```html
4075 <a href="/hamster-photos/this-week" class="active">
4076 Great Hamster Photos
4077 </a>
4078 ```
4079
4080 The CSS class used for active classes can be customized by passing an `activeClass` argument:
4081
4082 ```handlebars
4083 <LinkTo @route='photoGallery.recent' @activeClass="current-url">
4084 Great Hamster Photos
4085 </LinkTo>
4086 ```
4087
4088 ```html
4089 <a href="/hamster-photos/this-week" class="current-url">
4090 Great Hamster Photos
4091 </a>
4092 ```
4093
4094 ### Keeping a link active for other routes
4095
4096 If you need a link to be 'active' even when it doesn't match the current route, you can use the
4097 `current-when` argument.
4098
4099 ```handlebars
4100 <LinkTo @route='photoGallery' @current-when='photos'>
4101 Photo Gallery
4102 </LinkTo>
4103 ```
4104
4105 This may be helpful for keeping links active for:
4106
4107 * non-nested routes that are logically related
4108 * some secondary menu approaches
4109 * 'top navigation' with 'sub navigation' scenarios
4110
4111 A link will be active if `current-when` is `true` or the current
4112 route is the route this link would transition to.
4113
4114 To match multiple routes 'space-separate' the routes:
4115
4116 ```handlebars
4117 <LinkTo @route='gallery' @current-when='photos drawings paintings'>
4118 Art Gallery
4119 </LinkTo>
4120 ```
4121
4122 ### Supplying a model
4123
4124 An optional `model` argument can be used for routes whose
4125 paths contain dynamic segments. This argument will become
4126 the model context of the linked route:
4127
4128 ```javascript
4129 Router.map(function() {
4130 this.route("photoGallery", {path: "hamster-photos/:photo_id"});
4131 });
4132 ```
4133
4134 ```handlebars
4135 <LinkTo @route='photoGallery' @model={{this.aPhoto}}>
4136 {{aPhoto.title}}
4137 </LinkTo>
4138 ```
4139
4140 ```html
4141 <a href="/hamster-photos/42">
4142 Tomster
4143 </a>
4144 ```
4145
4146 ### Supplying multiple models
4147
4148 For deep-linking to route paths that contain multiple
4149 dynamic segments, the `models` argument can be used.
4150
4151 As the router transitions through the route path, each
4152 supplied model argument will become the context for the
4153 route with the dynamic segments:
4154
4155 ```javascript
4156 Router.map(function() {
4157 this.route("photoGallery", { path: "hamster-photos/:photo_id" }, function() {
4158 this.route("comment", {path: "comments/:comment_id"});
4159 });
4160 });
4161 ```
4162
4163 This argument will become the model context of the linked route:
4164
4165 ```handlebars
4166 <LinkTo @route='photoGallery.comment' @models={{array this.aPhoto this.comment}}>
4167 {{comment.body}}
4168 </LinkTo>
4169 ```
4170
4171 ```html
4172 <a href="/hamster-photos/42/comments/718">
4173 A+++ would snuggle again.
4174 </a>
4175 ```
4176
4177 ### Supplying an explicit dynamic segment value
4178
4179 If you don't have a model object available to pass to `LinkTo`,
4180 an optional string or integer argument can be passed for routes whose
4181 paths contain dynamic segments. This argument will become the value
4182 of the dynamic segment:
4183
4184 ```javascript
4185 Router.map(function() {
4186 this.route("photoGallery", { path: "hamster-photos/:photo_id" });
4187 });
4188 ```
4189
4190 ```handlebars
4191 <LinkTo @route='photoGallery' @model={{aPhotoId}}>
4192 {{this.aPhoto.title}}
4193 </LinkTo>
4194 ```
4195
4196 ```html
4197 <a href="/hamster-photos/42">
4198 Tomster
4199 </a>
4200 ```
4201
4202 When transitioning into the linked route, the `model` hook will
4203 be triggered with parameters including this passed identifier.
4204
4205 ### Allowing Default Action
4206
4207 By default the `<LinkTo>` component prevents the default browser action by calling
4208 `preventDefault()` to avoid reloading the browser page.
4209
4210 If you need to trigger a full browser reload pass `@preventDefault={{false}}`:
4211
4212 ```handlebars
4213 <LinkTo @route='photoGallery' @model={{this.aPhotoId}} @preventDefault={{false}}>
4214 {{this.aPhotoId.title}}
4215 </LinkTo>
4216 ```
4217
4218 ### Supplying a `tagName`
4219
4220 By default `<LinkTo>` renders an `<a>` element. This can be overridden for a single use of
4221 `<LinkTo>` by supplying a `tagName` argument:
4222
4223 ```handlebars
4224 <LinkTo @route='photoGallery' @tagName='li'>
4225 Great Hamster Photos
4226 </LinkTo>
4227 ```
4228
4229 This produces:
4230
4231 ```html
4232 <li>
4233 Great Hamster Photos
4234 </li>
4235 ```
4236
4237 In general, this is not recommended. Instead, you can use the `transition-to` helper together
4238 with a click event handler on the HTML tag of your choosing.
4239
4240 ### Supplying query parameters
4241
4242 If you need to add optional key-value pairs that appear to the right of the ? in a URL,
4243 you can use the `query` argument.
4244
4245 ```handlebars
4246 <LinkTo @route='photoGallery' @query={{hash page=1 per_page=20}}>
4247 Great Hamster Photos
4248 </LinkTo>
4249 ```
4250
4251 This will result in:
4252
4253 ```html
4254 <a href="/hamster-photos?page=1&per_page=20">
4255 Great Hamster Photos
4256 </a>
4257 ```
4258
4259 @for Ember.Templates.components
4260 @method LinkTo
4261 @see {LinkComponent}
4262 @public
4263 */
4264
4265 /**
4266 @module @ember/routing
4267 */
4268
4269 /**
4270 See [Ember.Templates.components.LinkTo](/ember/release/classes/Ember.Templates.components/methods/input?anchor=LinkTo).
4271
4272 @for Ember.Templates.helpers
4273 @method link-to
4274 @see {Ember.Templates.components.LinkTo}
4275 @public
4276 **/
4277
4278 /**
4279 `LinkComponent` is the internal component invoked with `<LinkTo>` or `{{link-to}}`.
4280
4281 @class LinkComponent
4282 @extends Component
4283 @see {Ember.Templates.components.LinkTo}
4284 @public
4285 **/
4286
4287 var UNDEFINED = Object.freeze({
4288 toString() {
4289 return 'UNDEFINED';
4290 }
4291
4292 });
4293 var EMPTY_QUERY_PARAMS = Object.freeze({});
4294 var LinkComponent = Component.extend({
4295 layout: layout$1,
4296 tagName: 'a',
4297
4298 /**
4299 @property route
4300 @public
4301 */
4302 route: UNDEFINED,
4303
4304 /**
4305 @property model
4306 @public
4307 */
4308 model: UNDEFINED,
4309
4310 /**
4311 @property models
4312 @public
4313 */
4314 models: UNDEFINED,
4315
4316 /**
4317 @property query
4318 @public
4319 */
4320 query: UNDEFINED,
4321
4322 /**
4323 Used to determine when this `LinkComponent` is active.
4324 @property current-when
4325 @public
4326 */
4327 'current-when': null,
4328
4329 /**
4330 Sets the `title` attribute of the `LinkComponent`'s HTML element.
4331 @property title
4332 @default null
4333 @public
4334 **/
4335 title: null,
4336
4337 /**
4338 Sets the `rel` attribute of the `LinkComponent`'s HTML element.
4339 @property rel
4340 @default null
4341 @public
4342 **/
4343 rel: null,
4344
4345 /**
4346 Sets the `tabindex` attribute of the `LinkComponent`'s HTML element.
4347 @property tabindex
4348 @default null
4349 @public
4350 **/
4351 tabindex: null,
4352
4353 /**
4354 Sets the `target` attribute of the `LinkComponent`'s HTML element.
4355 @since 1.8.0
4356 @property target
4357 @default null
4358 @public
4359 **/
4360 target: null,
4361
4362 /**
4363 The CSS class to apply to `LinkComponent`'s element when its `active`
4364 property is `true`.
4365 @property activeClass
4366 @type String
4367 @default active
4368 @public
4369 **/
4370 activeClass: 'active',
4371
4372 /**
4373 The CSS class to apply to `LinkComponent`'s element when its `loading`
4374 property is `true`.
4375 @property loadingClass
4376 @type String
4377 @default loading
4378 @private
4379 **/
4380 loadingClass: 'loading',
4381
4382 /**
4383 The CSS class to apply to a `LinkComponent`'s element when its `disabled`
4384 property is `true`.
4385 @property disabledClass
4386 @type String
4387 @default disabled
4388 @private
4389 **/
4390 disabledClass: 'disabled',
4391
4392 /**
4393 Determines whether the `LinkComponent` will trigger routing via
4394 the `replaceWith` routing strategy.
4395 @property replace
4396 @type Boolean
4397 @default false
4398 @public
4399 **/
4400 replace: false,
4401
4402 /**
4403 By default this component will forward `href`, `title`, `rel`, `tabindex`, and `target`
4404 arguments to attributes on the component's element. When invoked with `{{link-to}}`, you can
4405 only customize these attributes. When invoked with `<LinkTo>`, you can just use HTML
4406 attributes directly.
4407 @property attributeBindings
4408 @type Array | String
4409 @default ['title', 'rel', 'tabindex', 'target']
4410 @public
4411 */
4412 attributeBindings: ['href', 'title', 'rel', 'tabindex', 'target'],
4413
4414 /**
4415 By default this component will set classes on its element when any of the following arguments
4416 are truthy:
4417 * active
4418 * loading
4419 * disabled
4420 When these arguments are truthy, a class with the same name will be set on the element. When
4421 falsy, the associated class will not be on the element.
4422 @property classNameBindings
4423 @type Array
4424 @default ['active', 'loading', 'disabled', 'ember-transitioning-in', 'ember-transitioning-out']
4425 @public
4426 */
4427 classNameBindings: ['active', 'loading', 'disabled', 'transitioningIn', 'transitioningOut'],
4428
4429 /**
4430 By default this component responds to the `click` event. When the component element is an
4431 `<a>` element, activating the link in another way, such as using the keyboard, triggers the
4432 click event.
4433 @property eventName
4434 @type String
4435 @default click
4436 @private
4437 */
4438 eventName: 'click',
4439
4440 // this is doc'ed here so it shows up in the events
4441 // section of the API documentation, which is where
4442 // people will likely go looking for it.
4443
4444 /**
4445 Triggers the `LinkComponent`'s routing behavior. If
4446 `eventName` is changed to a value other than `click`
4447 the routing behavior will trigger on that custom event
4448 instead.
4449 @event click
4450 @private
4451 */
4452
4453 /**
4454 An overridable method called when `LinkComponent` objects are instantiated.
4455 Example:
4456 ```app/components/my-link.js
4457 import LinkComponent from '@ember/routing/link-component';
4458 export default LinkComponent.extend({
4459 init() {
4460 this._super(...arguments);
4461 console.log('Event is ' + this.get('eventName'));
4462 }
4463 });
4464 ```
4465 NOTE: If you do override `init` for a framework class like `Component`,
4466 be sure to call `this._super(...arguments)` in your
4467 `init` declaration! If you don't, Ember may not have an opportunity to
4468 do important setup work, and you'll see strange behavior in your
4469 application.
4470 @method init
4471 @private
4472 */
4473 init() {
4474 this._super(...arguments); // Map desired event name to invoke function
4475
4476
4477 var {
4478 eventName
4479 } = this;
4480 this.on(eventName, this, this._invoke);
4481 },
4482
4483 _routing: (0, _service.inject)('-routing'),
4484 _currentRoute: (0, _metal.alias)('_routing.currentRouteName'),
4485 _currentRouterState: (0, _metal.alias)('_routing.currentState'),
4486 _targetRouterState: (0, _metal.alias)('_routing.targetState'),
4487 _route: (0, _metal.computed)('route', '_currentRouterState', function computeLinkToComponentRoute() {
4488 var {
4489 route
4490 } = this;
4491 return route === UNDEFINED ? this._currentRoute : route;
4492 }),
4493 _models: (0, _metal.computed)('model', 'models', function computeLinkToComponentModels() {
4494 var {
4495 model,
4496 models
4497 } = this;
4498 (true && !(model === UNDEFINED || models === UNDEFINED) && (0, _debug.assert)('You cannot provide both the `@model` and `@models` arguments to the <LinkTo> component.', model === UNDEFINED || models === UNDEFINED));
4499
4500 if (model !== UNDEFINED) {
4501 return [model];
4502 } else if (models !== UNDEFINED) {
4503 (true && !(Array.isArray(models)) && (0, _debug.assert)('The `@models` argument must be an array.', Array.isArray(models)));
4504 return models;
4505 } else {
4506 return [];
4507 }
4508 }),
4509 _query: (0, _metal.computed)('query', function computeLinkToComponentQuery() {
4510 var {
4511 query
4512 } = this;
4513
4514 if (query === UNDEFINED) {
4515 return EMPTY_QUERY_PARAMS;
4516 } else {
4517 return (0, _polyfills.assign)({}, query);
4518 }
4519 }),
4520
4521 /**
4522 Accessed as a classname binding to apply the component's `disabledClass`
4523 CSS `class` to the element when the link is disabled.
4524 When `true`, interactions with the element will not trigger route changes.
4525 @property disabled
4526 @private
4527 */
4528 disabled: (0, _metal.computed)({
4529 get(_key) {
4530 // always returns false for `get` because (due to the `set` just below)
4531 // the cached return value from the set will prevent this getter from _ever_
4532 // being called after a set has occurred
4533 return false;
4534 },
4535
4536 set(_key, value) {
4537 this._isDisabled = value;
4538 return value ? this.disabledClass : false;
4539 }
4540
4541 }),
4542
4543 /**
4544 Accessed as a classname binding to apply the component's `activeClass`
4545 CSS `class` to the element when the link is active.
4546 This component is considered active when its `currentWhen` property is `true`
4547 or the application's current route is the route this component would trigger
4548 transitions into.
4549 The `currentWhen` property can match against multiple routes by separating
4550 route names using the ` ` (space) character.
4551 @property active
4552 @private
4553 */
4554 active: (0, _metal.computed)('activeClass', '_active', function computeLinkToComponentActiveClass() {
4555 return this._active ? this.activeClass : false;
4556 }),
4557 _active: (0, _metal.computed)('_currentRouterState', '_route', '_models', '_query', 'loading', 'current-when', function computeLinkToComponentActive() {
4558 var {
4559 _currentRouterState: state
4560 } = this;
4561
4562 if (state) {
4563 return this._isActive(state);
4564 } else {
4565 return false;
4566 }
4567 }),
4568 willBeActive: (0, _metal.computed)('_currentRouterState', '_targetRouterState', '_route', '_models', '_query', 'loading', 'current-when', function computeLinkToComponentWillBeActive() {
4569 var {
4570 _currentRouterState: current,
4571 _targetRouterState: target
4572 } = this;
4573
4574 if (current === target) {
4575 return;
4576 }
4577
4578 return this._isActive(target);
4579 }),
4580
4581 _isActive(routerState) {
4582 if (this.loading) {
4583 return false;
4584 }
4585
4586 var currentWhen = this['current-when'];
4587
4588 if (typeof currentWhen === 'boolean') {
4589 return currentWhen;
4590 }
4591
4592 var isCurrentWhenSpecified = Boolean(currentWhen);
4593
4594 if (isCurrentWhenSpecified) {
4595 currentWhen = currentWhen.split(' ');
4596 } else {
4597 currentWhen = [this._route];
4598 }
4599
4600 var {
4601 _models: models,
4602 _query: query,
4603 _routing: routing
4604 } = this;
4605
4606 for (var i = 0; i < currentWhen.length; i++) {
4607 if (routing.isActiveForRoute(models, query, currentWhen[i], routerState, isCurrentWhenSpecified)) {
4608 return true;
4609 }
4610 }
4611
4612 return false;
4613 },
4614
4615 transitioningIn: (0, _metal.computed)('_active', 'willBeActive', function computeLinkToComponentTransitioningIn() {
4616 if (this.willBeActive === true && !this._active) {
4617 return 'ember-transitioning-in';
4618 } else {
4619 return false;
4620 }
4621 }),
4622 transitioningOut: (0, _metal.computed)('_active', 'willBeActive', function computeLinkToComponentTransitioningOut() {
4623 if (this.willBeActive === false && this._active) {
4624 return 'ember-transitioning-out';
4625 } else {
4626 return false;
4627 }
4628 }),
4629
4630 /**
4631 Event handler that invokes the link, activating the associated route.
4632 @method _invoke
4633 @param {Event} event
4634 @private
4635 */
4636 _invoke(event) {
4637 if (!(0, _views.isSimpleClick)(event)) {
4638 return true;
4639 }
4640
4641 var {
4642 bubbles,
4643 preventDefault
4644 } = this;
4645 var target = this.element.target;
4646 var isSelf = !target || target === '_self';
4647
4648 if (preventDefault !== false && isSelf) {
4649 event.preventDefault();
4650 }
4651
4652 if (bubbles === false) {
4653 event.stopPropagation();
4654 }
4655
4656 if (this._isDisabled) {
4657 return false;
4658 }
4659
4660 if (this.loading) {
4661 // tslint:disable-next-line:max-line-length
4662 (true && (0, _debug.warn)('This link is in an inactive loading state because at least one of its models ' + 'currently has a null/undefined value, or the provided route name is invalid.', false, {
4663 id: 'ember-glimmer.link-to.inactive-loading-state'
4664 }));
4665 return false;
4666 }
4667
4668 if (!isSelf) {
4669 return false;
4670 }
4671
4672 var {
4673 _route: routeName,
4674 _models: models,
4675 _query: queryParams,
4676 replace: shouldReplace
4677 } = this;
4678 var payload = {
4679 queryParams,
4680 routeName
4681 };
4682 (0, _instrumentation.flaggedInstrument)('interaction.link-to', payload, this._generateTransition(payload, routeName, models, queryParams, shouldReplace));
4683 return false;
4684 },
4685
4686 _generateTransition(payload, qualifiedRouteName, models, queryParams, shouldReplace) {
4687 var {
4688 _routing: routing
4689 } = this;
4690 return () => {
4691 payload.transition = routing.transitionTo(qualifiedRouteName, models, queryParams, shouldReplace);
4692 };
4693 },
4694
4695 /**
4696 Sets the element's `href` attribute to the url for
4697 the `LinkComponent`'s targeted route.
4698 If the `LinkComponent`'s `tagName` is changed to a value other
4699 than `a`, this property will be ignored.
4700 @property href
4701 @private
4702 */
4703 href: (0, _metal.computed)('_currentRouterState', '_route', '_models', '_query', 'tagName', 'loading', 'loadingHref', function computeLinkToComponentHref() {
4704 if (this.tagName !== 'a') {
4705 return;
4706 }
4707
4708 if (this.loading) {
4709 return this.loadingHref;
4710 }
4711
4712 var {
4713 _route: route,
4714 _models: models,
4715 _query: query,
4716 _routing: routing
4717 } = this;
4718
4719 if (true
4720 /* DEBUG */
4721 ) {
4722 /*
4723 * Unfortunately, to get decent error messages, we need to do this.
4724 * In some future state we should be able to use a "feature flag"
4725 * which allows us to strip this without needing to call it twice.
4726 *
4727 * if (isDebugBuild()) {
4728 * // Do the useful debug thing, probably including try/catch.
4729 * } else {
4730 * // Do the performant thing.
4731 * }
4732 */
4733 try {
4734 return routing.generateURL(route, models, query);
4735 } catch (e) {
4736 // tslint:disable-next-line:max-line-length
4737 (true && !(false) && (0, _debug.assert)(`You attempted to generate a link for the "${this.route}" route, but did not ` + `pass the models required for generating its dynamic segments. ` + e.message));
4738 }
4739 } else {
4740 return routing.generateURL(route, models, query);
4741 }
4742 }),
4743 loading: (0, _metal.computed)('_route', '_modelsAreLoaded', 'loadingClass', function computeLinkToComponentLoading() {
4744 var {
4745 _route: route,
4746 _modelsAreLoaded: loaded
4747 } = this;
4748
4749 if (!loaded || route === null || route === undefined) {
4750 return this.loadingClass;
4751 }
4752 }),
4753 _modelsAreLoaded: (0, _metal.computed)('_models', function computeLinkToComponentModelsAreLoaded() {
4754 var {
4755 _models: models
4756 } = this;
4757
4758 for (var i = 0; i < models.length; i++) {
4759 var model = models[i];
4760
4761 if (model === null || model === undefined) {
4762 return false;
4763 }
4764 }
4765
4766 return true;
4767 }),
4768
4769 /**
4770 The default href value to use while a link-to is loading.
4771 Only applies when tagName is 'a'
4772 @property loadingHref
4773 @type String
4774 @default #
4775 @private
4776 */
4777 loadingHref: '#',
4778
4779 didReceiveAttrs() {
4780 var {
4781 disabledWhen
4782 } = this;
4783
4784 if (disabledWhen !== undefined) {
4785 this.set('disabled', disabledWhen);
4786 }
4787
4788 var {
4789 params
4790 } = this;
4791
4792 if (!params || params.length === 0) {
4793 (true && !(!(this.route === UNDEFINED && this.model === UNDEFINED && this.models === UNDEFINED && this.query === UNDEFINED)) && (0, _debug.assert)('You must provide at least one of the `@route`, `@model`, `@models` or `@query` argument to `<LinkTo>`.', !(this.route === UNDEFINED && this.model === UNDEFINED && this.models === UNDEFINED && this.query === UNDEFINED)));
4794 var {
4795 _models: models
4796 } = this;
4797
4798 if (models.length > 0) {
4799 var lastModel = models[models.length - 1];
4800
4801 if (typeof lastModel === 'object' && lastModel !== null && lastModel.isQueryParams) {
4802 this.query = lastModel.values;
4803 models.pop();
4804 }
4805 }
4806
4807 return;
4808 }
4809
4810 params = params.slice(); // Process the positional arguments, in order.
4811 // 1. Inline link title comes first, if present.
4812
4813 if (!this[HAS_BLOCK]) {
4814 this.set('linkTitle', params.shift());
4815 } // 2. The last argument is possibly the `query` object.
4816
4817
4818 var queryParams = params[params.length - 1];
4819
4820 if (queryParams && queryParams.isQueryParams) {
4821 this.set('query', params.pop().values);
4822 } else {
4823 this.set('query', UNDEFINED);
4824 } // 3. If there is a `route`, it is now at index 0.
4825
4826
4827 if (params.length === 0) {
4828 this.set('route', UNDEFINED);
4829 } else {
4830 this.set('route', params.shift());
4831 } // 4. Any remaining indices (if any) are `models`.
4832
4833
4834 this.set('model', UNDEFINED);
4835 this.set('models', params);
4836 }
4837
4838 });
4839 _exports.LinkComponent = LinkComponent;
4840
4841 LinkComponent.toString = () => '@ember/routing/link-component';
4842
4843 LinkComponent.reopenClass({
4844 positionalParams: 'params'
4845 });
4846 /**
4847 @module @ember/component
4848 */
4849
4850 var RECOMPUTE_TAG = (0, _utils.symbol)('RECOMPUTE_TAG');
4851
4852 function isHelperFactory(helper) {
4853 return typeof helper === 'object' && helper !== null && helper.class && helper.class.isHelperFactory;
4854 }
4855
4856 function isClassHelper(helper) {
4857 return helper.destroy !== undefined;
4858 }
4859 /**
4860 Ember Helpers are functions that can compute values, and are used in templates.
4861 For example, this code calls a helper named `format-currency`:
4862
4863 ```app/templates/application.hbs
4864 <Cost @cents={{230}} />
4865 ```
4866
4867 ```app/components/cost.hbs
4868 <div>{{format-currency @cents currency="$"}}</div>
4869 ```
4870
4871 Additionally a helper can be called as a nested helper.
4872 In this example, we show the formatted currency value if the `showMoney`
4873 named argument is truthy.
4874
4875 ```handlebars
4876 {{if @showMoney (format-currency @cents currency="$")}}
4877 ```
4878
4879 Helpers defined using a class must provide a `compute` function. For example:
4880
4881 ```app/helpers/format-currency.js
4882 import Helper from '@ember/component/helper';
4883
4884 export default class extends Helper {
4885 compute([cents], { currency }) {
4886 return `${currency}${cents * 0.01}`;
4887 }
4888 }
4889 ```
4890
4891 Each time the input to a helper changes, the `compute` function will be
4892 called again.
4893
4894 As instances, these helpers also have access to the container and will accept
4895 injected dependencies.
4896
4897 Additionally, class helpers can call `recompute` to force a new computation.
4898
4899 @class Helper
4900 @public
4901 @since 1.13.0
4902 */
4903
4904
4905 var Helper = _runtime.FrameworkObject.extend({
4906 init() {
4907 this._super(...arguments);
4908
4909 this[RECOMPUTE_TAG] = (0, _validator.createTag)();
4910 },
4911
4912 /**
4913 On a class-based helper, it may be useful to force a recomputation of that
4914 helpers value. This is akin to `rerender` on a component.
4915 For example, this component will rerender when the `currentUser` on a
4916 session service changes:
4917 ```app/helpers/current-user-email.js
4918 import Helper from '@ember/component/helper'
4919 import { inject as service } from '@ember/service'
4920 import { observer } from '@ember/object'
4921 export default Helper.extend({
4922 session: service(),
4923 onNewUser: observer('session.currentUser', function() {
4924 this.recompute();
4925 }),
4926 compute() {
4927 return this.get('session.currentUser.email');
4928 }
4929 });
4930 ```
4931 @method recompute
4932 @public
4933 @since 1.13.0
4934 */
4935 recompute() {
4936 (0, _runloop.join)(() => (0, _validator.dirtyTag)(this[RECOMPUTE_TAG]));
4937 }
4938
4939 });
4940
4941 _exports.Helper = Helper;
4942 Helper.isHelperFactory = true;
4943
4944 class Wrapper {
4945 constructor(compute) {
4946 this.compute = compute;
4947 this.isHelperFactory = true;
4948 }
4949
4950 create() {
4951 // needs new instance or will leak containers
4952 return {
4953 compute: this.compute
4954 };
4955 }
4956
4957 }
4958 /**
4959 In many cases it is not necessary to use the full `Helper` class.
4960 The `helper` method create pure-function helpers without instances.
4961 For example:
4962
4963 ```app/helpers/format-currency.js
4964 import { helper } from '@ember/component/helper';
4965
4966 export default helper(function([cents], {currency}) {
4967 return `${currency}${cents * 0.01}`;
4968 });
4969 ```
4970
4971 @static
4972 @param {Function} helper The helper function
4973 @method helper
4974 @for @ember/component/helper
4975 @public
4976 @since 1.13.0
4977 */
4978
4979
4980 function helper(helperFn) {
4981 return new Wrapper(helperFn);
4982 }
4983 /**
4984 @module @ember/template
4985 */
4986
4987
4988 class SafeString {
4989 constructor(string) {
4990 this.string = string;
4991 }
4992
4993 toString() {
4994 return `${this.string}`;
4995 }
4996
4997 toHTML() {
4998 return this.toString();
4999 }
5000
5001 }
5002
5003 _exports.SafeString = SafeString;
5004 var escape = {
5005 '&': '&amp;',
5006 '<': '&lt;',
5007 '>': '&gt;',
5008 '"': '&quot;',
5009 "'": '&#x27;',
5010 '`': '&#x60;',
5011 '=': '&#x3D;'
5012 };
5013 var possible = /[&<>"'`=]/;
5014 var badChars = /[&<>"'`=]/g;
5015
5016 function escapeChar(chr) {
5017 return escape[chr];
5018 }
5019
5020 function escapeExpression(string) {
5021 if (typeof string !== 'string') {
5022 // don't escape SafeStrings, since they're already safe
5023 if (string && string.toHTML) {
5024 return string.toHTML();
5025 } else if (string === null || string === undefined) {
5026 return '';
5027 } else if (!string) {
5028 return String(string);
5029 } // Force a string conversion as this will be done by the append regardless and
5030 // the regex test will do this transparently behind the scenes, causing issues if
5031 // an object's to string has escaped characters in it.
5032
5033
5034 string = String(string);
5035 }
5036
5037 if (!possible.test(string)) {
5038 return string;
5039 }
5040
5041 return string.replace(badChars, escapeChar);
5042 }
5043 /**
5044 Mark a string as safe for unescaped output with Ember templates. If you
5045 return HTML from a helper, use this function to
5046 ensure Ember's rendering layer does not escape the HTML.
5047
5048 ```javascript
5049 import { htmlSafe } from '@ember/template';
5050
5051 htmlSafe('<div>someString</div>')
5052 ```
5053
5054 @method htmlSafe
5055 @for @ember/template
5056 @static
5057 @return {SafeString} A string that will not be HTML escaped by Handlebars.
5058 @public
5059 */
5060
5061
5062 function htmlSafe(str) {
5063 if (str === null || str === undefined) {
5064 str = '';
5065 } else if (typeof str !== 'string') {
5066 str = String(str);
5067 }
5068
5069 return new SafeString(str);
5070 }
5071 /**
5072 Detects if a string was decorated using `htmlSafe`.
5073
5074 ```javascript
5075 import { htmlSafe, isHTMLSafe } from '@ember/template';
5076
5077 var plainString = 'plain string',
5078 safeString = htmlSafe('<div>someValue</div>');
5079
5080 isHTMLSafe(plainString); // false
5081 isHTMLSafe(safeString); // true
5082 ```
5083
5084 @method isHTMLSafe
5085 @for @ember/template
5086 @static
5087 @return {Boolean} `true` if the string was decorated with `htmlSafe`, `false` otherwise.
5088 @public
5089 */
5090
5091
5092 function isHTMLSafe(str) {
5093 return str !== null && typeof str === 'object' && typeof str.toHTML === 'function';
5094 }
5095
5096 function isStaticComponentManager(_manager, capabilities) {
5097 return !capabilities.dynamicLayout;
5098 }
5099
5100 class CompileTimeResolver {
5101 constructor(resolver) {
5102 this.resolver = resolver;
5103 }
5104
5105 lookupHelper(name, referrer) {
5106 return this.resolver.lookupHelper(name, referrer);
5107 }
5108
5109 lookupModifier(name, referrer) {
5110 return this.resolver.lookupModifier(name, referrer);
5111 }
5112
5113 lookupComponent(name, referrer) {
5114 var definitionHandle = this.resolver.lookupComponentHandle(name, referrer);
5115
5116 if (definitionHandle === null) {
5117 return null;
5118 }
5119
5120 var {
5121 manager,
5122 state
5123 } = this.resolver.resolve(definitionHandle);
5124 var capabilities = manager.getCapabilities(state);
5125
5126 if (!isStaticComponentManager(manager, capabilities)) {
5127 return {
5128 handle: definitionHandle,
5129 capabilities,
5130 compilable: null
5131 };
5132 }
5133
5134 return {
5135 handle: definitionHandle,
5136 capabilities,
5137 compilable: manager.getJitStaticLayout(state, this.resolver)
5138 };
5139 }
5140
5141 lookupPartial(name, referrer) {
5142 return this.resolver.lookupPartial(name, referrer);
5143 }
5144
5145 resolve(handle) {
5146 return this.resolver.resolve(handle);
5147 }
5148
5149 } // implements the ComponentManager interface as defined in glimmer:
5150 // tslint:disable-next-line:max-line-length
5151 // https://github.com/glimmerjs/glimmer-vm/blob/v0.24.0-beta.4/packages/%40glimmer/runtime/lib/component/interfaces.ts#L21
5152
5153
5154 class AbstractManager {
5155 prepareArgs(_state, _args) {
5156 return null;
5157 }
5158
5159 didCreateElement(_component, _element, _operations) {// noop
5160 }
5161
5162 didRenderLayout(_component, _bounds) {// noop
5163 }
5164
5165 didCreate(_bucket) {// noop
5166 }
5167
5168 update(_bucket, _dynamicScope) {// noop
5169 }
5170
5171 didUpdateLayout(_bucket, _bounds) {// noop
5172 }
5173
5174 didUpdate(_bucket) {// noop
5175 }
5176
5177 }
5178
5179 _exports.AbstractComponentManager = AbstractManager;
5180
5181 function instrumentationPayload(def) {
5182 return {
5183 object: `${def.name}:${def.outlet}`
5184 };
5185 }
5186
5187 var CAPABILITIES = {
5188 dynamicLayout: false,
5189 dynamicTag: false,
5190 prepareArgs: false,
5191 createArgs: _environment2.ENV._DEBUG_RENDER_TREE,
5192 attributeHook: false,
5193 elementHook: false,
5194 createCaller: false,
5195 dynamicScope: true,
5196 updateHook: _environment2.ENV._DEBUG_RENDER_TREE,
5197 createInstance: true,
5198 wrapped: false,
5199 willDestroy: false
5200 };
5201
5202 class OutletComponentManager extends AbstractManager {
5203 create(environment, definition, args, dynamicScope) {
5204 var parentStateRef = dynamicScope.outletState;
5205 var currentStateRef = definition.ref;
5206 dynamicScope.outletState = currentStateRef;
5207 var state = {
5208 self: new _reference.ComponentRootReference(definition.controller, environment),
5209 environment,
5210 finalize: (0, _instrumentation._instrumentStart)('render.outlet', instrumentationPayload, definition)
5211 };
5212
5213 if (_environment2.ENV._DEBUG_RENDER_TREE) {
5214 state.outlet = {
5215 name: definition.outlet
5216 };
5217 environment.extra.debugRenderTree.create(state.outlet, {
5218 type: 'outlet',
5219 name: state.outlet.name,
5220 args: _runtime2.EMPTY_ARGS,
5221 instance: undefined,
5222 template: undefined
5223 });
5224 var parentState = parentStateRef.value();
5225 var parentOwner = parentState && parentState.render && parentState.render.owner;
5226 var currentOwner = currentStateRef.value().render.owner;
5227
5228 if (parentOwner && parentOwner !== currentOwner) {
5229 var engine = currentOwner;
5230 (true && !(typeof currentOwner.mountPoint === 'string') && (0, _debug.assert)('invalid engine: missing mountPoint', typeof currentOwner.mountPoint === 'string'));
5231 (true && !(currentOwner.routable === true) && (0, _debug.assert)('invalid engine: missing routable', currentOwner.routable === true));
5232 var mountPoint = engine.mountPoint;
5233 state.engine = {
5234 mountPoint
5235 };
5236 environment.extra.debugRenderTree.create(state.engine, {
5237 type: 'engine',
5238 name: mountPoint,
5239 args: _runtime2.EMPTY_ARGS,
5240 instance: engine,
5241 template: undefined
5242 });
5243 }
5244
5245 environment.extra.debugRenderTree.create(state, {
5246 type: 'route-template',
5247 name: definition.name,
5248 args: args.capture(),
5249 instance: definition.controller,
5250 template: definition.template
5251 });
5252 (0, _runtime2.registerDestructor)(state, () => {
5253 state.environment.extra.debugRenderTree.willDestroy(state);
5254
5255 if (state.engine) {
5256 state.environment.extra.debugRenderTree.willDestroy(state.engine);
5257 }
5258
5259 state.environment.extra.debugRenderTree.willDestroy(state.outlet);
5260 });
5261 }
5262
5263 return state;
5264 }
5265
5266 getJitStaticLayout({
5267 template
5268 }, _resolver) {
5269 // The router has already resolved the template
5270 return (0, _util.unwrapTemplate)(template).asLayout();
5271 }
5272
5273 getCapabilities() {
5274 return CAPABILITIES;
5275 }
5276
5277 getSelf({
5278 self
5279 }) {
5280 return self;
5281 }
5282
5283 getTag() {
5284 if (_environment2.ENV._DEBUG_RENDER_TREE) {
5285 // returning a const tag skips the update hook (VM BUG?)
5286 return (0, _validator.createTag)();
5287 } else {
5288 // an outlet has no hooks
5289 return _validator.CONSTANT_TAG;
5290 }
5291 }
5292
5293 didRenderLayout(state, bounds) {
5294 state.finalize();
5295
5296 if (_environment2.ENV._DEBUG_RENDER_TREE) {
5297 state.environment.extra.debugRenderTree.didRender(state, bounds);
5298
5299 if (state.engine) {
5300 state.environment.extra.debugRenderTree.didRender(state.engine, bounds);
5301 }
5302
5303 state.environment.extra.debugRenderTree.didRender(state.outlet, bounds);
5304 }
5305 }
5306
5307 update(state) {
5308 if (_environment2.ENV._DEBUG_RENDER_TREE) {
5309 state.environment.extra.debugRenderTree.update(state.outlet);
5310
5311 if (state.engine) {
5312 state.environment.extra.debugRenderTree.update(state.engine);
5313 }
5314
5315 state.environment.extra.debugRenderTree.update(state);
5316 }
5317 }
5318
5319 didUpdateLayout(state, bounds) {
5320 if (_environment2.ENV._DEBUG_RENDER_TREE) {
5321 state.environment.extra.debugRenderTree.didRender(state, bounds);
5322
5323 if (state.engine) {
5324 state.environment.extra.debugRenderTree.didRender(state.engine, bounds);
5325 }
5326
5327 state.environment.extra.debugRenderTree.didRender(state.outlet, bounds);
5328 }
5329 }
5330
5331 getDestroyable(state) {
5332 if (_environment2.ENV._DEBUG_RENDER_TREE) {
5333 return state;
5334 } else {
5335 return null;
5336 }
5337 }
5338
5339 }
5340
5341 var OUTLET_MANAGER = new OutletComponentManager();
5342
5343 class OutletComponentDefinition {
5344 constructor(state, manager = OUTLET_MANAGER) {
5345 this.state = state;
5346 this.manager = manager;
5347 }
5348
5349 }
5350
5351 function createRootOutlet(outletView) {
5352 if (_environment2.ENV._APPLICATION_TEMPLATE_WRAPPER) {
5353 var WRAPPED_CAPABILITIES = (0, _polyfills.assign)({}, CAPABILITIES, {
5354 dynamicTag: true,
5355 elementHook: true,
5356 wrapped: true
5357 });
5358 var WrappedOutletComponentManager = class extends OutletComponentManager {
5359 getTagName(_component) {
5360 return 'div';
5361 }
5362
5363 getJitStaticLayout({
5364 template
5365 }) {
5366 // The router has already resolved the template
5367 return (0, _util.unwrapTemplate)(template).asWrappedLayout();
5368 }
5369
5370 getCapabilities() {
5371 return WRAPPED_CAPABILITIES;
5372 }
5373
5374 didCreateElement(component, element, _operations) {
5375 // to add GUID id and class
5376 element.setAttribute('class', 'ember-view');
5377 element.setAttribute('id', (0, _utils.guidFor)(component));
5378 }
5379
5380 };
5381 var WRAPPED_OUTLET_MANAGER = new WrappedOutletComponentManager();
5382 return new OutletComponentDefinition(outletView.state, WRAPPED_OUTLET_MANAGER);
5383 } else {
5384 return new OutletComponentDefinition(outletView.state);
5385 }
5386 }
5387
5388 function NOOP() {}
5389 /**
5390 @module ember
5391 */
5392
5393 /**
5394 Represents the internal state of the component.
5395
5396 @class ComponentStateBucket
5397 @private
5398 */
5399
5400
5401 class ComponentStateBucket {
5402 constructor(environment, component, args, finalizer, hasWrappedElement) {
5403 this.environment = environment;
5404 this.component = component;
5405 this.args = args;
5406 this.finalizer = finalizer;
5407 this.hasWrappedElement = hasWrappedElement;
5408 this.classRef = null;
5409 this.classRef = null;
5410 this.argsRevision = args === null ? 0 : (0, _validator.valueForTag)(args.tag);
5411 this.rootRef = new _reference.ComponentRootReference(component, environment);
5412 (0, _runtime2.registerDestructor)(this, () => this.willDestroy(), true);
5413 (0, _runtime2.registerDestructor)(this, () => this.component.destroy());
5414 }
5415
5416 willDestroy() {
5417 var {
5418 component,
5419 environment
5420 } = this;
5421
5422 if (environment.isInteractive) {
5423 component.trigger('willDestroyElement');
5424 component.trigger('willClearRender');
5425 var element = (0, _views.getViewElement)(component);
5426
5427 if (element) {
5428 (0, _views.clearElementView)(element);
5429 (0, _views.clearViewElement)(component);
5430 }
5431 }
5432
5433 component.renderer.unregister(component);
5434 }
5435
5436 finalize() {
5437 var {
5438 finalizer
5439 } = this;
5440 finalizer();
5441 this.finalizer = NOOP;
5442 }
5443
5444 }
5445
5446 class EmberHelperRootReference extends _reference.HelperRootReference {
5447 constructor(helper$$1, args, env) {
5448 var fnWrapper = args => {
5449 var {
5450 positional,
5451 named
5452 } = args;
5453 var positionalValue = positional.value();
5454 var namedValue = named.value();
5455 var ret;
5456
5457 if (true
5458 /* DEBUG */
5459 ) {
5460 (0, _debug.debugFreeze)(positionalValue);
5461 (0, _debug.debugFreeze)(namedValue);
5462 (0, _validator.deprecateMutationsInAutotrackingTransaction)(() => {
5463 ret = helper$$1.compute(positionalValue, namedValue);
5464 });
5465 } else {
5466 ret = helper$$1.compute(positionalValue, namedValue);
5467 }
5468
5469 if (helper$$1[RECOMPUTE_TAG]) {
5470 (0, _validator.consumeTag)(helper$$1[RECOMPUTE_TAG]);
5471 }
5472
5473 return ret;
5474 };
5475
5476 if (true
5477 /* DEBUG */
5478 ) {
5479 var debugName = isClassHelper(helper$$1) ? (0, _utils.getDebugName)(helper$$1) : (0, _utils.getDebugName)(helper$$1.compute);
5480 super(fnWrapper, args, env, debugName);
5481 } else {
5482 super(fnWrapper, args, env);
5483 }
5484 }
5485
5486 }
5487
5488 class UnboundRootReference extends _reference.RootReference {
5489 constructor(inner, env, parent, key) {
5490 super(env);
5491 this.inner = inner;
5492 this.env = env;
5493
5494 if (true
5495 /* DEBUG */
5496 ) {
5497 env.setTemplatePathDebugContext(this, key || 'this', parent || null);
5498 }
5499 }
5500
5501 value() {
5502 return this.inner;
5503 }
5504
5505 get(key) {
5506 var value = this.value();
5507
5508 if ((0, _utils.isObject)(value)) {
5509 // root of interop with ember objects
5510 return new UnboundPropertyReference(value[key], this.env, this, key);
5511 } else {
5512 return _runtime2.PrimitiveReference.create(value);
5513 }
5514 }
5515
5516 }
5517
5518 class UnboundPropertyReference extends UnboundRootReference {}
5519
5520 function referenceFromParts(root, parts) {
5521 var reference = root;
5522
5523 for (var i = 0; i < parts.length; i++) {
5524 reference = reference.get(parts[i]);
5525 }
5526
5527 return reference;
5528 }
5529
5530 function referenceForKey(rootRef, key) {
5531 return rootRef.get(key);
5532 }
5533
5534 function referenceForParts(rootRef, parts) {
5535 var isAttrs = parts[0] === 'attrs'; // TODO deprecate this
5536
5537 if (isAttrs) {
5538 parts.shift();
5539
5540 if (parts.length === 1) {
5541 return referenceForKey(rootRef, parts[0]);
5542 }
5543 }
5544
5545 return referenceFromParts(rootRef, parts);
5546 }
5547
5548 var AttributeBinding = {
5549 parse(microsyntax) {
5550 var colonIndex = microsyntax.indexOf(':');
5551
5552 if (colonIndex === -1) {
5553 (true && !(microsyntax !== 'class') && (0, _debug.assert)('You cannot use class as an attributeBinding, use classNameBindings instead.', microsyntax !== 'class'));
5554 return [microsyntax, microsyntax, true];
5555 } else {
5556 var prop = microsyntax.substring(0, colonIndex);
5557 var attribute = microsyntax.substring(colonIndex + 1);
5558 (true && !(attribute !== 'class') && (0, _debug.assert)('You cannot use class as an attributeBinding, use classNameBindings instead.', attribute !== 'class'));
5559 return [prop, attribute, false];
5560 }
5561 },
5562
5563 install(component, rootRef, parsed, operations, env) {
5564 var [prop, attribute, isSimple] = parsed;
5565
5566 if (attribute === 'id') {
5567 var elementId = (0, _metal.get)(component, prop);
5568
5569 if (elementId === undefined || elementId === null) {
5570 elementId = component.elementId;
5571 }
5572
5573 elementId = _runtime2.PrimitiveReference.create(elementId);
5574 operations.setAttribute('id', elementId, true, null); // operations.addStaticAttribute(element, 'id', elementId);
5575
5576 return;
5577 }
5578
5579 var isPath = prop.indexOf('.') > -1;
5580 var reference = isPath ? referenceForParts(rootRef, prop.split('.')) : referenceForKey(rootRef, prop);
5581 (true && !(!(isSimple && isPath)) && (0, _debug.assert)(`Illegal attributeBinding: '${prop}' is not a valid attribute name.`, !(isSimple && isPath)));
5582
5583 if (_deprecatedFeatures.EMBER_COMPONENT_IS_VISIBLE && attribute === 'style' && StyleBindingReference !== undefined) {
5584 reference = new StyleBindingReference(rootRef, reference, referenceForKey(rootRef, 'isVisible'), env);
5585 }
5586
5587 operations.setAttribute(attribute, reference, false, null); // operations.addDynamicAttribute(element, attribute, reference, false);
5588 }
5589
5590 };
5591 var DISPLAY_NONE = 'display: none;';
5592 var SAFE_DISPLAY_NONE = htmlSafe(DISPLAY_NONE);
5593 var StyleBindingReference;
5594 var installIsVisibleBinding;
5595
5596 if (_deprecatedFeatures.EMBER_COMPONENT_IS_VISIBLE) {
5597 StyleBindingReference = class {
5598 constructor(parent, inner, isVisible, env) {
5599 this.inner = inner;
5600 this.isVisible = isVisible;
5601 this.env = env;
5602 this.tag = (0, _validator.combine)([inner.tag, isVisible.tag]);
5603
5604 if (true
5605 /* DEBUG */
5606 ) {
5607 env.setTemplatePathDebugContext(this, 'style', parent);
5608 }
5609 }
5610
5611 value() {
5612 var value = this.inner.value();
5613 var isVisible = this.isVisible.value();
5614
5615 if (isVisible !== undefined) {
5616 (true && !(false) && (0, _debug.deprecate)(`The \`isVisible\` property on classic component classes is deprecated. Was accessed ${this.env.getTemplatePathDebugContext(this).replace(/^W/, 'w')}`, false, {
5617 id: 'ember-component.is-visible',
5618 until: '4.0.0',
5619 url: 'https://deprecations.emberjs.com/v3.x#toc_ember-component-is-visible'
5620 }));
5621 }
5622
5623 if (isVisible !== false) {
5624 return value;
5625 } else if (!value) {
5626 return SAFE_DISPLAY_NONE;
5627 } else {
5628 var style = value + ' ' + DISPLAY_NONE;
5629 return isHTMLSafe(value) ? htmlSafe(style) : style;
5630 }
5631 }
5632
5633 get() {
5634 return _runtime2.UNDEFINED_REFERENCE;
5635 }
5636
5637 };
5638
5639 installIsVisibleBinding = (rootRef, operations, environment) => {
5640 operations.setAttribute('style', new StyleBindingReference(rootRef, _runtime2.UNDEFINED_REFERENCE, rootRef.get('isVisible'), environment), false, null);
5641 };
5642 }
5643
5644 var ClassNameBinding = {
5645 install(_element, rootRef, microsyntax, operations) {
5646 var [prop, truthy, falsy] = microsyntax.split(':');
5647 var isStatic = prop === '';
5648
5649 if (isStatic) {
5650 operations.setAttribute('class', _runtime2.PrimitiveReference.create(truthy), true, null);
5651 } else {
5652 var isPath = prop.indexOf('.') > -1;
5653 var parts = isPath ? prop.split('.') : [];
5654 var value = isPath ? referenceForParts(rootRef, parts) : referenceForKey(rootRef, prop);
5655 var ref;
5656
5657 if (truthy === undefined) {
5658 ref = new SimpleClassNameBindingReference(value, isPath ? parts[parts.length - 1] : prop);
5659 } else {
5660 ref = new ColonClassNameBindingReference(value, truthy, falsy);
5661 }
5662
5663 operations.setAttribute('class', ref, false, null);
5664 }
5665 }
5666
5667 };
5668
5669 class SimpleClassNameBindingReference {
5670 constructor(inner, path) {
5671 this.inner = inner;
5672 this.path = path;
5673 this.tag = inner.tag;
5674 this.dasherizedPath = null;
5675 }
5676
5677 value() {
5678 var value = this.inner.value();
5679
5680 if (value === true) {
5681 var {
5682 path,
5683 dasherizedPath
5684 } = this;
5685 return dasherizedPath || (this.dasherizedPath = (0, _string.dasherize)(path));
5686 } else if (value || value === 0) {
5687 return String(value);
5688 } else {
5689 return null;
5690 }
5691 }
5692
5693 }
5694
5695 class ColonClassNameBindingReference {
5696 constructor(inner, truthy = null, falsy = null) {
5697 this.inner = inner;
5698 this.truthy = truthy;
5699 this.falsy = falsy;
5700 this.tag = inner.tag;
5701 }
5702
5703 value() {
5704 var {
5705 inner,
5706 truthy,
5707 falsy
5708 } = this;
5709 return inner.value() ? truthy : falsy;
5710 }
5711
5712 }
5713 /**
5714 @module ember
5715 */
5716
5717 /**
5718 The `mut` helper lets you __clearly specify__ that a child `Component` can update the
5719 (mutable) value passed to it, which will __change the value of the parent component__.
5720
5721 To specify that a parameter is mutable, when invoking the child `Component`:
5722
5723 ```handlebars
5724 <MyChild @childClickCount={{fn (mut totalClicks)}} />
5725 ```
5726
5727 or
5728
5729 ```handlebars
5730 {{my-child childClickCount=(mut totalClicks)}}
5731 ```
5732
5733 The child `Component` can then modify the parent's value just by modifying its own
5734 property:
5735
5736 ```javascript
5737 // my-child.js
5738 export default Component.extend({
5739 click() {
5740 this.incrementProperty('childClickCount');
5741 }
5742 });
5743 ```
5744
5745 Note that for curly components (`{{my-component}}`) the bindings are already mutable,
5746 making the `mut` unnecessary.
5747
5748 Additionally, the `mut` helper can be combined with the `fn` helper to
5749 mutate a value. For example:
5750
5751 ```handlebars
5752 <MyChild @childClickCount={{this.totalClicks}} @click-count-change={{fn (mut totalClicks))}} />
5753 ```
5754
5755 or
5756
5757 ```handlebars
5758 {{my-child childClickCount=totalClicks click-count-change=(fn (mut totalClicks))}}
5759 ```
5760
5761 The child `Component` would invoke the function with the new click value:
5762
5763 ```javascript
5764 // my-child.js
5765 export default Component.extend({
5766 click() {
5767 this.get('click-count-change')(this.get('childClickCount') + 1);
5768 }
5769 });
5770 ```
5771
5772 The `mut` helper changes the `totalClicks` value to what was provided as the `fn` argument.
5773
5774 The `mut` helper, when used with `fn`, will return a function that
5775 sets the value passed to `mut` to its first argument. As an example, we can create a
5776 button that increments a value passing the value directly to the `fn`:
5777
5778 ```handlebars
5779 {{! inc helper is not provided by Ember }}
5780 <button onclick={{fn (mut count) (inc count)}}>
5781 Increment count
5782 </button>
5783 ```
5784
5785 @method mut
5786 @param {Object} [attr] the "two-way" attribute that can be modified.
5787 @for Ember.Templates.helpers
5788 @public
5789 */
5790
5791
5792 var INVOKE = (0, _utils.symbol)('INVOKE');
5793 _exports.INVOKE = INVOKE;
5794 var SOURCE = (0, _utils.symbol)('SOURCE');
5795
5796 class MutReference extends _reference.RootReference {
5797 constructor(inner, env) {
5798 super(env);
5799 this.inner = inner;
5800 this.tag = inner.tag;
5801 this[SOURCE] = inner;
5802 }
5803
5804 value() {
5805 return this.inner.value();
5806 }
5807
5808 get(key) {
5809 return this.inner.get(key);
5810 }
5811
5812 [_reference.UPDATE_REFERENCED_VALUE](value) {
5813 return this.inner[_reference.UPDATE_REFERENCED_VALUE](value);
5814 }
5815
5816 [INVOKE](value) {
5817 return this.inner[_reference.UPDATE_REFERENCED_VALUE](value);
5818 }
5819
5820 }
5821
5822 function unMut(ref) {
5823 return ref[SOURCE] || ref;
5824 }
5825
5826 function mut(args, vm) {
5827 var rawRef = args.positional.at(0);
5828
5829 if (typeof rawRef[INVOKE] === 'function') {
5830 return rawRef;
5831 } // TODO: Improve this error message. This covers at least two distinct
5832 // cases:
5833 //
5834 // 1. (mut "not a path") – passing a literal, result from a helper
5835 // invocation, etc
5836 //
5837 // 2. (mut receivedValue) – passing a value received from the caller
5838 // that was originally derived from a literal, result from a helper
5839 // invocation, etc
5840 //
5841 // This message is alright for the first case, but could be quite
5842 // confusing for the second case.
5843
5844
5845 (true && !(rawRef[_reference.UPDATE_REFERENCED_VALUE] !== undefined) && (0, _debug.assert)('You can only pass a path to mut', rawRef[_reference.UPDATE_REFERENCED_VALUE] !== undefined));
5846 return new MutReference(rawRef, vm.env);
5847 }
5848 /**
5849 @module ember
5850 */
5851
5852
5853 var ACTION = (0, _utils.symbol)('ACTION');
5854 /**
5855 The `{{action}}` helper provides a way to pass triggers for behavior (usually
5856 just a function) between components, and into components from controllers.
5857
5858 ### Passing functions with the action helper
5859
5860 There are three contexts an action helper can be used in. The first two
5861 contexts to discuss are attribute context, and Handlebars value context.
5862
5863 ```handlebars
5864 {{! An example of attribute context }}
5865 <div onclick={{action "save"}}></div>
5866 {{! Examples of Handlebars value context }}
5867 {{input on-input=(action "save")}}
5868 {{yield (action "refreshData") andAnotherParam}}
5869 ```
5870
5871 In these contexts,
5872 the helper is called a "closure action" helper. Its behavior is simple:
5873 If passed a function name, read that function off the `actions` property
5874 of the current context. Once that function is read, or immediately if a function was
5875 passed, create a closure over that function and any arguments.
5876 The resulting value of an action helper used this way is simply a function.
5877
5878 For example, in the attribute context:
5879
5880 ```handlebars
5881 {{! An example of attribute context }}
5882 <div onclick={{action "save"}}></div>
5883 ```
5884
5885 The resulting template render logic would be:
5886
5887 ```js
5888 var div = document.createElement('div');
5889 var actionFunction = (function(context){
5890 return function() {
5891 return context.actions.save.apply(context, arguments);
5892 };
5893 })(context);
5894 div.onclick = actionFunction;
5895 ```
5896
5897 Thus when the div is clicked, the action on that context is called.
5898 Because the `actionFunction` is just a function, closure actions can be
5899 passed between components and still execute in the correct context.
5900
5901 Here is an example action handler on a component:
5902
5903 ```app/components/my-component.js
5904 import Component from '@glimmer/component';
5905 import { action } from '@ember/object';
5906
5907 export default class extends Component {
5908 @action
5909 save() {
5910 this.model.save();
5911 }
5912 }
5913 ```
5914
5915 Actions are always looked up on the `actions` property of the current context.
5916 This avoids collisions in the naming of common actions, such as `destroy`.
5917 Two options can be passed to the `action` helper when it is used in this way.
5918
5919 * `target=someProperty` will look to `someProperty` instead of the current
5920 context for the `actions` hash. This can be useful when targeting a
5921 service for actions.
5922 * `value="target.value"` will read the path `target.value` off the first
5923 argument to the action when it is called and rewrite the first argument
5924 to be that value. This is useful when attaching actions to event listeners.
5925
5926 ### Invoking an action
5927
5928 Closure actions curry both their scope and any arguments. When invoked, any
5929 additional arguments are added to the already curried list.
5930 Actions should be invoked using the [sendAction](/ember/release/classes/Component/methods/sendAction?anchor=sendAction)
5931 method. The first argument to `sendAction` is the action to be called, and
5932 additional arguments are passed to the action function. This has interesting
5933 properties combined with currying of arguments. For example:
5934
5935 ```app/components/update-name.js
5936 import Component from '@glimmer/component';
5937 import { action } from '@ember/object';
5938
5939 export default class extends Component {
5940 @action
5941 setName(model, name) {
5942 model.set('name', name);
5943 }
5944 }
5945 ```
5946
5947 ```app/components/update-name.hbs
5948 {{input on-input=(action (action 'setName' @model) value="target.value")}}
5949 ```
5950
5951 The first argument (`@model`) was curried over, and the run-time argument (`event`)
5952 becomes a second argument. Action calls can be nested this way because each simply
5953 returns a function. Any function can be passed to the `{{action}}` helper, including
5954 other actions.
5955
5956 Actions invoked with `sendAction` have the same currying behavior as demonstrated
5957 with `on-input` above. For example:
5958
5959 ```app/components/my-input.js
5960 import Component from '@glimmer/component';
5961 import { action } from '@ember/object';
5962
5963 export default class extends Component {
5964 @action
5965 setName(model, name) {
5966 model.set('name', name);
5967 }
5968 }
5969 ```
5970
5971 ```handlebars
5972 <MyInput @submit={{action 'setName' @model}} />
5973 ```
5974
5975 or
5976
5977 ```handlebars
5978 {{my-input submit=(action 'setName' @model)}}
5979 ```
5980
5981 ```app/components/my-component.js
5982 import Component from '@ember/component';
5983
5984 export default Component.extend({
5985 click() {
5986 // Note that model is not passed, it was curried in the template
5987 this.sendAction('submit', 'bob');
5988 }
5989 });
5990 ```
5991
5992 ### Attaching actions to DOM elements
5993
5994 The third context of the `{{action}}` helper can be called "element space".
5995 For example:
5996
5997 ```handlebars
5998 {{! An example of element space }}
5999 <div {{action "save"}}></div>
6000 ```
6001
6002 Used this way, the `{{action}}` helper provides a useful shortcut for
6003 registering an HTML element in a template for a single DOM event and
6004 forwarding that interaction to the template's context (controller or component).
6005 If the context of a template is a controller, actions used this way will
6006 bubble to routes when the controller does not implement the specified action.
6007 Once an action hits a route, it will bubble through the route hierarchy.
6008
6009 ### Event Propagation
6010
6011 `{{action}}` helpers called in element space can control event bubbling. Note
6012 that the closure style actions cannot.
6013
6014 Events triggered through the action helper will automatically have
6015 `.preventDefault()` called on them. You do not need to do so in your event
6016 handlers. If you need to allow event propagation (to handle file inputs for
6017 example) you can supply the `preventDefault=false` option to the `{{action}}` helper:
6018
6019 ```handlebars
6020 <div {{action "sayHello" preventDefault=false}}>
6021 <input type="file" />
6022 <input type="checkbox" />
6023 </div>
6024 ```
6025
6026 To disable bubbling, pass `bubbles=false` to the helper:
6027
6028 ```handlebars
6029 <button {{action 'edit' post bubbles=false}}>Edit</button>
6030 ```
6031
6032 To disable bubbling with closure style actions you must create your own
6033 wrapper helper that makes use of `event.stopPropagation()`:
6034
6035 ```handlebars
6036 <div onclick={{disable-bubbling (action "sayHello")}}>Hello</div>
6037 ```
6038
6039 ```app/helpers/disable-bubbling.js
6040 import { helper } from '@ember/component/helper';
6041
6042 export function disableBubbling([action]) {
6043 return function(event) {
6044 event.stopPropagation();
6045 return action(event);
6046 };
6047 }
6048 export default helper(disableBubbling);
6049 ```
6050
6051 If you need the default handler to trigger you should either register your
6052 own event handler, or use event methods on your view class. See
6053 ["Responding to Browser Events"](/ember/release/classes/Component)
6054 in the documentation for `Component` for more information.
6055
6056 ### Specifying DOM event type
6057
6058 `{{action}}` helpers called in element space can specify an event type.
6059 By default the `{{action}}` helper registers for DOM `click` events. You can
6060 supply an `on` option to the helper to specify a different DOM event name:
6061
6062 ```handlebars
6063 <div {{action "anActionName" on="doubleClick"}}>
6064 click me
6065 </div>
6066 ```
6067
6068 See ["Event Names"](/ember/release/classes/Component) for a list of
6069 acceptable DOM event names.
6070
6071 ### Specifying whitelisted modifier keys
6072
6073 `{{action}}` helpers called in element space can specify modifier keys.
6074 By default the `{{action}}` helper will ignore click events with pressed modifier
6075 keys. You can supply an `allowedKeys` option to specify which keys should not be ignored.
6076
6077 ```handlebars
6078 <div {{action "anActionName" allowedKeys="alt"}}>
6079 click me
6080 </div>
6081 ```
6082
6083 This way the action will fire when clicking with the alt key pressed down.
6084 Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys.
6085
6086 ```handlebars
6087 <div {{action "anActionName" allowedKeys="any"}}>
6088 click me with any key pressed
6089 </div>
6090 ```
6091
6092 ### Specifying a Target
6093
6094 A `target` option can be provided to the helper to change
6095 which object will receive the method call. This option must be a path
6096 to an object, accessible in the current context:
6097
6098 ```app/templates/application.hbs
6099 <div {{action "anActionName" target=someService}}>
6100 click me
6101 </div>
6102 ```
6103
6104 ```app/controllers/application.js
6105 import Controller from '@ember/controller';
6106 import { inject as service } from '@ember/service';
6107
6108 export default class extends Controller {
6109 @service someService;
6110 }
6111 ```
6112
6113 @method action
6114 @for Ember.Templates.helpers
6115 @public
6116 */
6117
6118 function action(args, vm) {
6119 var {
6120 named,
6121 positional
6122 } = args;
6123 var capturedArgs = positional.capture(); // The first two argument slots are reserved.
6124 // pos[0] is the context (or `this`)
6125 // pos[1] is the action name or function
6126 // Anything else is an action argument.
6127
6128 var [context, action, ...restArgs] = capturedArgs.references; // TODO: Is there a better way of doing this?
6129
6130 var debugKey = action.propertyKey;
6131 var target = named.has('target') ? named.get('target') : context;
6132 var processArgs = makeArgsProcessor(named.has('value') && named.get('value'), restArgs);
6133 var fn;
6134
6135 if (typeof action[INVOKE] === 'function') {
6136 fn = makeClosureAction(action, action, action[INVOKE], processArgs, debugKey);
6137 } else if ((0, _validator.isConstTagged)(target) && (0, _validator.isConstTagged)(action)) {
6138 fn = makeClosureAction(context.value(), target.value(), action.value(), processArgs, debugKey);
6139 } else {
6140 fn = makeDynamicClosureAction(context.value(), target, action, processArgs, debugKey);
6141 }
6142
6143 fn[ACTION] = true;
6144 return new UnboundRootReference(fn, vm.env);
6145 }
6146
6147 function NOOP$1(args) {
6148 return args;
6149 }
6150
6151 function makeArgsProcessor(valuePathRef, actionArgsRef) {
6152 var mergeArgs;
6153
6154 if (actionArgsRef.length > 0) {
6155 mergeArgs = args => {
6156 return actionArgsRef.map(ref => ref.value()).concat(args);
6157 };
6158 }
6159
6160 var readValue;
6161
6162 if (valuePathRef) {
6163 readValue = args => {
6164 var valuePath = valuePathRef.value();
6165
6166 if (valuePath && args.length > 0) {
6167 args[0] = (0, _metal.get)(args[0], valuePath);
6168 }
6169
6170 return args;
6171 };
6172 }
6173
6174 if (mergeArgs && readValue) {
6175 return args => {
6176 return readValue(mergeArgs(args));
6177 };
6178 } else {
6179 return mergeArgs || readValue || NOOP$1;
6180 }
6181 }
6182
6183 function makeDynamicClosureAction(context, targetRef, actionRef, processArgs, debugKey) {
6184 // We don't allow undefined/null values, so this creates a throw-away action to trigger the assertions
6185 if (true
6186 /* DEBUG */
6187 ) {
6188 makeClosureAction(context, targetRef.value(), actionRef.value(), processArgs, debugKey);
6189 }
6190
6191 return (...args) => {
6192 return makeClosureAction(context, targetRef.value(), actionRef.value(), processArgs, debugKey)(...args);
6193 };
6194 }
6195
6196 function makeClosureAction(context, target, action, processArgs, debugKey) {
6197 var self;
6198 var fn;
6199 (true && !(action !== undefined && action !== null) && (0, _debug.assert)(`Action passed is null or undefined in (action) from ${target}.`, action !== undefined && action !== null));
6200
6201 if (typeof action[INVOKE] === 'function') {
6202 self = action;
6203 fn = action[INVOKE];
6204 } else {
6205 var typeofAction = typeof action;
6206
6207 if (typeofAction === 'string') {
6208 self = target;
6209 fn = target.actions && target.actions[action];
6210 (true && !(fn) && (0, _debug.assert)(`An action named '${action}' was not found in ${target}`, fn));
6211 } else if (typeofAction === 'function') {
6212 self = context;
6213 fn = action;
6214 } else {
6215 // tslint:disable-next-line:max-line-length
6216 (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));
6217 }
6218 }
6219
6220 return (...args) => {
6221 var payload = {
6222 target: self,
6223 args,
6224 label: '@glimmer/closure-action'
6225 };
6226 return (0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => {
6227 return (0, _runloop.join)(self, fn, ...processArgs(args));
6228 });
6229 };
6230 } // inputs needed by CurlyComponents (attrs and props, with mutable
6231 // cells, etc).
6232
6233
6234 function processComponentArgs(namedArgs) {
6235 var keys = namedArgs.names;
6236 var attrs = namedArgs.value();
6237 var props = Object.create(null);
6238 var args = Object.create(null);
6239 props[ARGS] = args;
6240
6241 for (var i = 0; i < keys.length; i++) {
6242 var name = keys[i];
6243 var ref = namedArgs.get(name);
6244 var value = attrs[name];
6245
6246 if (typeof value === 'function' && value[ACTION]) {
6247 attrs[name] = value;
6248 } else if (ref[_reference.UPDATE_REFERENCED_VALUE]) {
6249 attrs[name] = new MutableCell(ref, value);
6250 }
6251
6252 args[name] = ref;
6253 props[name] = value;
6254 }
6255
6256 props.attrs = attrs;
6257 return props;
6258 }
6259
6260 var REF = (0, _utils.symbol)('REF');
6261
6262 class MutableCell {
6263 constructor(ref, value) {
6264 this[_views.MUTABLE_CELL] = true;
6265 this[REF] = ref;
6266 this.value = value;
6267 }
6268
6269 update(val) {
6270 this[REF][_reference.UPDATE_REFERENCED_VALUE](val);
6271 }
6272
6273 }
6274
6275 var __rest = undefined && undefined.__rest || function (s, e) {
6276 var t = {};
6277
6278 for (var p in s) {
6279 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
6280 }
6281
6282 if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
6283 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
6284 }
6285 return t;
6286 };
6287
6288 function aliasIdToElementId(args, props) {
6289 if (args.named.has('id')) {
6290 // tslint:disable-next-line:max-line-length
6291 (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')));
6292 props.elementId = props.id;
6293 }
6294 } // We must traverse the attributeBindings in reverse keeping track of
6295 // what has already been applied. This is essentially refining the concatenated
6296 // properties applying right to left.
6297
6298
6299 function applyAttributeBindings(attributeBindings, component, rootRef, operations, environment) {
6300 var seen = [];
6301 var i = attributeBindings.length - 1;
6302
6303 while (i !== -1) {
6304 var binding = attributeBindings[i];
6305 var parsed = AttributeBinding.parse(binding);
6306 var attribute = parsed[1];
6307
6308 if (seen.indexOf(attribute) === -1) {
6309 seen.push(attribute);
6310 AttributeBinding.install(component, rootRef, parsed, operations, environment);
6311 }
6312
6313 i--;
6314 }
6315
6316 if (seen.indexOf('id') === -1) {
6317 var id$$1 = component.elementId ? component.elementId : (0, _utils.guidFor)(component);
6318 operations.setAttribute('id', _runtime2.PrimitiveReference.create(id$$1), false, null);
6319 }
6320
6321 if (_deprecatedFeatures.EMBER_COMPONENT_IS_VISIBLE && installIsVisibleBinding !== undefined && seen.indexOf('style') === -1) {
6322 installIsVisibleBinding(rootRef, operations, environment);
6323 }
6324 }
6325
6326 var DEFAULT_LAYOUT = (0, _container.privatize)`template:components/-default`;
6327 var EMPTY_POSITIONAL_ARGS = [];
6328 (0, _debug.debugFreeze)(EMPTY_POSITIONAL_ARGS);
6329
6330 class CurlyComponentManager extends AbstractManager {
6331 templateFor(component) {
6332 var {
6333 layout,
6334 layoutName
6335 } = component;
6336 var owner = (0, _owner.getOwner)(component);
6337 var factory;
6338
6339 if (layout === undefined) {
6340 if (layoutName !== undefined) {
6341 var _factory = owner.lookup(`template:${layoutName}`);
6342
6343 (true && !(_factory !== undefined) && (0, _debug.assert)(`Layout \`${layoutName}\` not found!`, _factory !== undefined));
6344 factory = _factory;
6345 } else {
6346 factory = owner.lookup(DEFAULT_LAYOUT);
6347 }
6348 } else if (isTemplateFactory(layout)) {
6349 factory = layout;
6350 } else {
6351 // we were provided an instance already
6352 return layout;
6353 }
6354
6355 return factory(owner);
6356 }
6357
6358 getJitStaticLayout(state, _resolver) {
6359 return (0, _util.unwrapTemplate)(state.template).asLayout();
6360 }
6361
6362 getJitDynamicLayout(bucket) {
6363 var component = bucket.component;
6364 var template$$1 = this.templateFor(component);
6365
6366 if (_environment2.ENV._DEBUG_RENDER_TREE) {
6367 bucket.environment.extra.debugRenderTree.setTemplate(bucket, template$$1);
6368 }
6369
6370 return template$$1;
6371 }
6372
6373 getTagName(state) {
6374 var {
6375 component,
6376 hasWrappedElement
6377 } = state;
6378
6379 if (!hasWrappedElement) {
6380 return null;
6381 }
6382
6383 return component && component.tagName || 'div';
6384 }
6385
6386 getCapabilities(state) {
6387 return state.capabilities;
6388 }
6389
6390 prepareArgs(state, args) {
6391 if (args.named.has('__ARGS__')) {
6392 var _a = args.named.capture().map,
6393 {
6394 __ARGS__
6395 } = _a,
6396 rest = __rest(_a, ["__ARGS__"]);
6397
6398 var prepared = {
6399 positional: EMPTY_POSITIONAL_ARGS,
6400 named: (0, _polyfills.assign)({}, rest, __ARGS__.value())
6401 };
6402 return prepared;
6403 }
6404
6405 var {
6406 positionalParams
6407 } = state.ComponentClass.class; // early exits
6408
6409 if (positionalParams === undefined || positionalParams === null || args.positional.length === 0) {
6410 return null;
6411 }
6412
6413 var named;
6414
6415 if (typeof positionalParams === 'string') {
6416 (true && !(!args.named.has(positionalParams)) && (0, _debug.assert)(`You cannot specify positional parameters and the hash argument \`${positionalParams}\`.`, !args.named.has(positionalParams)));
6417 named = {
6418 [positionalParams]: args.positional.capture()
6419 };
6420 (0, _polyfills.assign)(named, args.named.capture().map);
6421 } else if (Array.isArray(positionalParams) && positionalParams.length > 0) {
6422 var count = Math.min(positionalParams.length, args.positional.length);
6423 named = {};
6424 (0, _polyfills.assign)(named, args.named.capture().map);
6425
6426 for (var i = 0; i < count; i++) {
6427 var name = positionalParams[i];
6428 (true && !(!args.named.has(name)) && (0, _debug.assert)(`You cannot specify both a positional param (at position ${i}) and the hash argument \`${name}\`.`, !args.named.has(name)));
6429 named[name] = args.positional.at(i);
6430 }
6431 } else {
6432 return null;
6433 }
6434
6435 return {
6436 positional: _util.EMPTY_ARRAY,
6437 named
6438 };
6439 }
6440 /*
6441 * This hook is responsible for actually instantiating the component instance.
6442 * It also is where we perform additional bookkeeping to support legacy
6443 * features like exposed by view mixins like ChildViewSupport, ActionSupport,
6444 * etc.
6445 */
6446
6447
6448 create(environment, state, args, dynamicScope, callerSelfRef, hasBlock) {
6449 // Get the nearest concrete component instance from the scope. "Virtual"
6450 // components will be skipped.
6451 var parentView = dynamicScope.view; // Get the Ember.Component subclass to instantiate for this component.
6452
6453 var factory = state.ComponentClass; // Capture the arguments, which tells Glimmer to give us our own, stable
6454 // copy of the Arguments object that is safe to hold on to between renders.
6455
6456 var capturedArgs = args.named.capture();
6457 var props = processComponentArgs(capturedArgs); // Alias `id` argument to `elementId` property on the component instance.
6458
6459 aliasIdToElementId(args, props); // Set component instance's parentView property to point to nearest concrete
6460 // component.
6461
6462 props.parentView = parentView; // Set whether this component was invoked with a block
6463 // (`{{#my-component}}{{/my-component}}`) or without one
6464 // (`{{my-component}}`).
6465
6466 props[HAS_BLOCK] = hasBlock; // Save the current `this` context of the template as the component's
6467 // `_target`, so bubbled actions are routed to the right place.
6468
6469 props._target = callerSelfRef.value(); // static layout asserts CurriedDefinition
6470
6471 if (state.template) {
6472 props.layout = state.template;
6473 } // caller:
6474 // <FaIcon @name="bug" />
6475 //
6476 // callee:
6477 // <i class="fa-{{@name}}"></i>
6478 // Now that we've built up all of the properties to set on the component instance,
6479 // actually create it.
6480
6481
6482 var component = factory.create(props);
6483 var finalizer = (0, _instrumentation._instrumentStart)('render.component', initialRenderInstrumentDetails, component); // We become the new parentView for downstream components, so save our
6484 // component off on the dynamic scope.
6485
6486 dynamicScope.view = component; // Unless we're the root component, we need to add ourselves to our parent
6487 // component's childViews array.
6488
6489 if (parentView !== null && parentView !== undefined) {
6490 (0, _views.addChildView)(parentView, component);
6491 }
6492
6493 component.trigger('didReceiveAttrs');
6494 var hasWrappedElement = component.tagName !== ''; // We usually do this in the `didCreateElement`, but that hook doesn't fire for tagless components
6495
6496 if (!hasWrappedElement) {
6497 if (environment.isInteractive) {
6498 component.trigger('willRender');
6499 }
6500
6501 component._transitionTo('hasElement');
6502
6503 if (environment.isInteractive) {
6504 component.trigger('willInsertElement');
6505 }
6506 } // Track additional lifecycle metadata about this component in a state bucket.
6507 // Essentially we're saving off all the state we'll need in the future.
6508
6509
6510 var bucket = new ComponentStateBucket(environment, component, capturedArgs, finalizer, hasWrappedElement);
6511
6512 if (args.named.has('class')) {
6513 bucket.classRef = args.named.get('class');
6514 }
6515
6516 if (true
6517 /* DEBUG */
6518 ) {
6519 processComponentInitializationAssertions(component, props);
6520 }
6521
6522 if (environment.isInteractive && hasWrappedElement) {
6523 component.trigger('willRender');
6524 }
6525
6526 if (_environment2.ENV._DEBUG_RENDER_TREE) {
6527 environment.extra.debugRenderTree.create(bucket, {
6528 type: 'component',
6529 name: state.name,
6530 args: args.capture(),
6531 instance: component,
6532 template: state.template
6533 });
6534 (0, _runtime2.registerDestructor)(bucket, () => {
6535 environment.extra.debugRenderTree.willDestroy(bucket);
6536 });
6537 }
6538
6539 return bucket;
6540 }
6541
6542 getSelf({
6543 rootRef
6544 }) {
6545 return rootRef;
6546 }
6547
6548 didCreateElement({
6549 component,
6550 classRef,
6551 environment,
6552 rootRef
6553 }, element, operations) {
6554 (0, _views.setViewElement)(component, element);
6555 (0, _views.setElementView)(element, component);
6556 var {
6557 attributeBindings,
6558 classNames,
6559 classNameBindings
6560 } = component;
6561
6562 if (attributeBindings && attributeBindings.length) {
6563 applyAttributeBindings(attributeBindings, component, rootRef, operations, environment);
6564 } else {
6565 var id$$1 = component.elementId ? component.elementId : (0, _utils.guidFor)(component);
6566 operations.setAttribute('id', _runtime2.PrimitiveReference.create(id$$1), false, null);
6567
6568 if (_deprecatedFeatures.EMBER_COMPONENT_IS_VISIBLE) {
6569 installIsVisibleBinding(rootRef, operations, environment);
6570 }
6571 }
6572
6573 if (classRef) {
6574 var ref = new SimpleClassNameBindingReference(classRef, classRef['propertyKey']);
6575 operations.setAttribute('class', ref, false, null);
6576 }
6577
6578 if (classNames && classNames.length) {
6579 classNames.forEach(name => {
6580 operations.setAttribute('class', _runtime2.PrimitiveReference.create(name), false, null);
6581 });
6582 }
6583
6584 if (classNameBindings && classNameBindings.length) {
6585 classNameBindings.forEach(binding => {
6586 ClassNameBinding.install(element, rootRef, binding, operations);
6587 });
6588 }
6589
6590 operations.setAttribute('class', _runtime2.PrimitiveReference.create('ember-view'), false, null);
6591
6592 if ('ariaRole' in component) {
6593 operations.setAttribute('role', referenceForKey(rootRef, 'ariaRole'), false, null);
6594 }
6595
6596 component._transitionTo('hasElement');
6597
6598 if (environment.isInteractive) {
6599 component.trigger('willInsertElement');
6600 }
6601 }
6602
6603 didRenderLayout(bucket, bounds) {
6604 bucket.component[BOUNDS] = bounds;
6605 bucket.finalize();
6606
6607 if (_environment2.ENV._DEBUG_RENDER_TREE) {
6608 bucket.environment.extra.debugRenderTree.didRender(bucket, bounds);
6609 }
6610 }
6611
6612 getTag({
6613 args,
6614 component
6615 }) {
6616 return args ? (0, _validator.combine)([args.tag, component[DIRTY_TAG]]) : component[DIRTY_TAG];
6617 }
6618
6619 didCreate({
6620 component,
6621 environment
6622 }) {
6623 if (environment.isInteractive) {
6624 component._transitionTo('inDOM');
6625
6626 component.trigger('didInsertElement');
6627 component.trigger('didRender');
6628 }
6629 }
6630
6631 update(bucket) {
6632 var {
6633 component,
6634 args,
6635 argsRevision,
6636 environment
6637 } = bucket;
6638
6639 if (_environment2.ENV._DEBUG_RENDER_TREE) {
6640 environment.extra.debugRenderTree.update(bucket);
6641 }
6642
6643 bucket.finalizer = (0, _instrumentation._instrumentStart)('render.component', rerenderInstrumentDetails, component);
6644
6645 if (args && !(0, _validator.validateTag)(args.tag, argsRevision)) {
6646 var props = processComponentArgs(args);
6647 bucket.argsRevision = (0, _validator.valueForTag)(args.tag);
6648 component[IS_DISPATCHING_ATTRS] = true;
6649 component.setProperties(props);
6650 component[IS_DISPATCHING_ATTRS] = false;
6651 component.trigger('didUpdateAttrs');
6652 component.trigger('didReceiveAttrs');
6653 }
6654
6655 if (environment.isInteractive) {
6656 component.trigger('willUpdate');
6657 component.trigger('willRender');
6658 }
6659 }
6660
6661 didUpdateLayout(bucket, bounds) {
6662 bucket.finalize();
6663
6664 if (_environment2.ENV._DEBUG_RENDER_TREE) {
6665 bucket.environment.extra.debugRenderTree.didRender(bucket, bounds);
6666 }
6667 }
6668
6669 didUpdate({
6670 component,
6671 environment
6672 }) {
6673 if (environment.isInteractive) {
6674 component.trigger('didUpdate');
6675 component.trigger('didRender');
6676 }
6677 }
6678
6679 getDestroyable(bucket) {
6680 return bucket;
6681 }
6682
6683 }
6684
6685 function processComponentInitializationAssertions(component, props) {
6686 (true && !((() => {
6687 var {
6688 classNameBindings
6689 } = component;
6690
6691 for (var i = 0; i < classNameBindings.length; i++) {
6692 var binding = classNameBindings[i];
6693
6694 if (typeof binding !== 'string' || binding.length === 0) {
6695 return false;
6696 }
6697 }
6698
6699 return true;
6700 })()) && (0, _debug.assert)(`classNameBindings must be non-empty strings: ${component}`, (() => {
6701 var {
6702 classNameBindings
6703 } = component;
6704
6705 for (var i = 0; i < classNameBindings.length; i++) {
6706 var binding = classNameBindings[i];
6707
6708 if (typeof binding !== 'string' || binding.length === 0) {
6709 return false;
6710 }
6711 }
6712
6713 return true;
6714 })()));
6715 (true && !((() => {
6716 var {
6717 classNameBindings
6718 } = component;
6719
6720 for (var i = 0; i < classNameBindings.length; i++) {
6721 var binding = classNameBindings[i];
6722
6723 if (binding.split(' ').length > 1) {
6724 return false;
6725 }
6726 }
6727
6728 return true;
6729 })()) && (0, _debug.assert)(`classNameBindings must not have spaces in them: ${component}`, (() => {
6730 var {
6731 classNameBindings
6732 } = component;
6733
6734 for (var i = 0; i < classNameBindings.length; i++) {
6735 var binding = classNameBindings[i];
6736
6737 if (binding.split(' ').length > 1) {
6738 return false;
6739 }
6740 }
6741
6742 return true;
6743 })()));
6744 (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));
6745 (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 !== ''));
6746 (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));
6747 }
6748
6749 function initialRenderInstrumentDetails(component) {
6750 return component.instrumentDetails({
6751 initialRender: true
6752 });
6753 }
6754
6755 function rerenderInstrumentDetails(component) {
6756 return component.instrumentDetails({
6757 initialRender: false
6758 });
6759 }
6760
6761 var CURLY_CAPABILITIES = {
6762 dynamicLayout: true,
6763 dynamicTag: true,
6764 prepareArgs: true,
6765 createArgs: true,
6766 attributeHook: true,
6767 elementHook: true,
6768 createCaller: true,
6769 dynamicScope: true,
6770 updateHook: true,
6771 createInstance: true,
6772 wrapped: true,
6773 willDestroy: true
6774 };
6775 var CURLY_COMPONENT_MANAGER = new CurlyComponentManager();
6776
6777 class CurlyComponentDefinition {
6778 constructor(name, ComponentClass, template$$1, args) {
6779 this.name = name;
6780 this.ComponentClass = ComponentClass;
6781 this.template = template$$1;
6782 this.args = args;
6783 this.manager = CURLY_COMPONENT_MANAGER;
6784 this.state = {
6785 name,
6786 ComponentClass,
6787 template: template$$1,
6788 capabilities: CURLY_CAPABILITIES
6789 };
6790 }
6791
6792 }
6793
6794 class RootComponentManager extends CurlyComponentManager {
6795 constructor(component) {
6796 super();
6797 this.component = component;
6798 }
6799
6800 getJitStaticLayout(_state) {
6801 var template = this.templateFor(this.component);
6802 return (0, _util.unwrapTemplate)(template).asWrappedLayout();
6803 }
6804
6805 create(environment, state, _args, dynamicScope) {
6806 var component = this.component;
6807 var finalizer = (0, _instrumentation._instrumentStart)('render.component', initialRenderInstrumentDetails, component);
6808 dynamicScope.view = component;
6809 var hasWrappedElement = component.tagName !== ''; // We usually do this in the `didCreateElement`, but that hook doesn't fire for tagless components
6810
6811 if (!hasWrappedElement) {
6812 if (environment.isInteractive) {
6813 component.trigger('willRender');
6814 }
6815
6816 component._transitionTo('hasElement');
6817
6818 if (environment.isInteractive) {
6819 component.trigger('willInsertElement');
6820 }
6821 }
6822
6823 if (true
6824 /* DEBUG */
6825 ) {
6826 processComponentInitializationAssertions(component, {});
6827 }
6828
6829 var bucket = new ComponentStateBucket(environment, component, null, finalizer, hasWrappedElement);
6830
6831 if (_environment2.ENV._DEBUG_RENDER_TREE) {
6832 environment.extra.debugRenderTree.create(bucket, {
6833 type: 'component',
6834 name: state.name,
6835 args: _runtime2.EMPTY_ARGS,
6836 instance: component,
6837 template: state.template
6838 });
6839 }
6840
6841 return bucket;
6842 }
6843
6844 } // ROOT is the top-level template it has nothing but one yield.
6845 // it is supposed to have a dummy element
6846
6847
6848 var ROOT_CAPABILITIES = {
6849 dynamicLayout: false,
6850 dynamicTag: true,
6851 prepareArgs: false,
6852 createArgs: false,
6853 attributeHook: true,
6854 elementHook: true,
6855 createCaller: true,
6856 dynamicScope: true,
6857 updateHook: true,
6858 createInstance: true,
6859 wrapped: true,
6860 willDestroy: false
6861 };
6862
6863 class RootComponentDefinition {
6864 constructor(component) {
6865 this.component = component;
6866 var manager = new RootComponentManager(component);
6867 this.manager = manager;
6868 var factory = (0, _container.getFactoryFor)(component);
6869 this.state = {
6870 name: factory.fullName.slice(10),
6871 capabilities: ROOT_CAPABILITIES,
6872 ComponentClass: factory
6873 };
6874 }
6875
6876 getTag({
6877 component
6878 }) {
6879 return component[DIRTY_TAG];
6880 }
6881
6882 }
6883 /* globals module, URL */
6884
6885
6886 var nodeURL;
6887 var parsingNode;
6888
6889 function installProtocolForURL(environment) {
6890 var protocol;
6891
6892 if (_browserEnvironment.hasDOM) {
6893 protocol = browserProtocolForURL.call(environment, 'foobar:baz');
6894 } // Test to see if our DOM implementation parses
6895 // and normalizes URLs.
6896
6897
6898 if (protocol === 'foobar:') {
6899 // Swap in the method that doesn't do this test now that
6900 // we know it works.
6901 environment.protocolForURL = browserProtocolForURL;
6902 } else if (typeof URL === 'object') {
6903 // URL globally provided, likely from FastBoot's sandbox
6904 nodeURL = URL;
6905 environment.protocolForURL = nodeProtocolForURL;
6906 } else if (typeof module !== 'undefined' && typeof module.require === 'function') {
6907 // Otherwise, we need to fall back to our own URL parsing.
6908 // Global `require` is shadowed by Ember's loader so we have to use the fully
6909 // qualified `module.require`.
6910 // tslint:disable-next-line:no-require-imports
6911 nodeURL = module.require('url');
6912 environment.protocolForURL = nodeProtocolForURL;
6913 } else {
6914 throw new Error('Could not find valid URL parsing mechanism for URL Sanitization');
6915 }
6916 }
6917
6918 function browserProtocolForURL(url) {
6919 if (!parsingNode) {
6920 parsingNode = document.createElement('a');
6921 }
6922
6923 parsingNode.href = url;
6924 return parsingNode.protocol;
6925 }
6926
6927 function nodeProtocolForURL(url) {
6928 var protocol = null;
6929
6930 if (typeof url === 'string') {
6931 protocol = nodeURL.parse(url).protocol;
6932 }
6933
6934 return protocol === null ? ':' : protocol;
6935 }
6936
6937 var GUID = 0;
6938
6939 function isPathNode(node) {
6940 return node.type === 'root' || node.type === 'argument' || node.type === 'property' || node.type === 'iterator';
6941 }
6942
6943 class Ref {
6944 constructor(value) {
6945 this.id = GUID++;
6946 this.value = value;
6947 }
6948
6949 get() {
6950 return this.value;
6951 }
6952
6953 release() {
6954 (true && !(this.value !== null) && (0, _debug.assert)('BUG: double release?', this.value !== null));
6955 this.value = null;
6956 }
6957
6958 toString() {
6959 var label = `Ref ${this.id}`;
6960
6961 if (this.value === null) {
6962 return `${label} (released)`;
6963 } else {
6964 try {
6965 return `${label}: ${this.value}`;
6966 } catch (_a) {
6967 return label;
6968 }
6969 }
6970 }
6971
6972 }
6973
6974 var _repeat = String.prototype.repeat || function (count) {
6975 return new Array(count + 1).join(this);
6976 };
6977
6978 function repeatString(str, count) {
6979 return _repeat.call(str, count);
6980 }
6981
6982 class DebugRenderTree {
6983 constructor() {
6984 this.stack = new _util.Stack();
6985 this.refs = new WeakMap();
6986 this.roots = new Set();
6987 this.nodes = new WeakMap();
6988 this.pathNodes = new WeakMap();
6989 }
6990
6991 begin() {
6992 this.reset();
6993 }
6994
6995 create(state, node) {
6996 var internalNode = (0, _polyfills.assign)({}, node, {
6997 bounds: null,
6998 refs: new Set(),
6999 paths: new Set()
7000 });
7001 this.nodes.set(state, internalNode);
7002 this.appendChild(internalNode, state);
7003 this.enter(state);
7004 }
7005
7006 update(state) {
7007 this.enter(state);
7008 } // for dynamic layouts
7009
7010
7011 setTemplate(state, template) {
7012 this.nodeFor(state).template = template;
7013 }
7014
7015 didRender(state, bounds) {
7016 (true && !(this.stack.current === state) && (0, _debug.assert)(`BUG: expecting ${this.stack.current}, got ${state}`, this.stack.current === state));
7017 this.nodeFor(state).bounds = bounds;
7018 this.exit();
7019 }
7020
7021 willDestroy(state) {
7022 (0, _util.expect)(this.refs.get(state), 'BUG: missing ref').release();
7023 }
7024
7025 commit() {
7026 this.reset();
7027 }
7028
7029 capture() {
7030 return this.captureRefs(this.roots);
7031 }
7032
7033 createPath(pathRef, name, type, parentRef) {
7034 (true && !(!this.pathNodes.has(pathRef)) && (0, _debug.assert)('BUG: Attempted to register a path that had already been registered', !this.pathNodes.has(pathRef)));
7035 var {
7036 current
7037 } = this.stack;
7038
7039 if (current === null) {
7040 // Not currently in a rendering context, don't register the node
7041 return;
7042 }
7043
7044 var currentNode = (0, _util.expect)(this.nodes.get(current), 'BUG: Attempted to create a path, but there is no current render node');
7045 var parent;
7046
7047 if (parentRef === null) {
7048 parent = currentNode;
7049 } else {
7050 var {
7051 named
7052 } = currentNode.args;
7053 var refIndex = named.references.indexOf(parentRef);
7054
7055 if (refIndex !== -1) {
7056 parent = {
7057 parent: currentNode,
7058 type: 'argument',
7059 name: `@${named.names[refIndex]}`,
7060 paths: new Set()
7061 };
7062 } else if (this.pathNodes.has(parentRef)) {
7063 parent = this.pathNodes.get(parentRef);
7064 } else {
7065 // Some RootReferences get created before a component context has been
7066 // setup (root, curly). This is mainly because the debugRenderTree is
7067 // tied to the manager hooks, and not built into the VM directly. In
7068 // these cases, we setup the path lazily when the first property is
7069 // accessed.
7070 this.createPath(parentRef, 'this', 'root', null);
7071 parent = this.pathNodes.get(parentRef);
7072 }
7073 }
7074
7075 var pathNode = {
7076 name,
7077 type,
7078 parent,
7079 paths: new Set()
7080 };
7081 parent.paths.add(pathNode);
7082 this.pathNodes.set(pathRef, pathNode);
7083 }
7084
7085 logRenderStackForPath(pathRef) {
7086 var node = (0, _util.expect)(this.pathNodes.get(pathRef), 'BUG: Attempted to create a log for a path reference, but no node exist for that reference');
7087 var pathParts = [];
7088
7089 while (node !== undefined && isPathNode(node)) {
7090 if (node.type === 'iterator') {
7091 // Iterator items are a combination of their own name (the key of the item) and
7092 // their parent, the iterable itself.
7093 var part = `${node.parent.name}[${node.name}]`;
7094 pathParts.push(part);
7095 node = node.parent;
7096 } else {
7097 pathParts.unshift(node.name);
7098 }
7099
7100 node = node.parent;
7101 }
7102
7103 var messageParts = [pathParts.join('.')];
7104
7105 while (node !== undefined) {
7106 if (node.type === 'outlet' || node.name === '-top-level') {
7107 node = node.parent;
7108 continue;
7109 }
7110
7111 messageParts.unshift(node.name);
7112 node = node.parent;
7113 }
7114
7115 return messageParts.map((part, index) => `${repeatString(' ', index * 2)}${part}`).join('\n');
7116 }
7117
7118 reset() {
7119 if (this.stack.size !== 0) {
7120 // We probably encountered an error during the rendering loop. This will
7121 // likely trigger undefined behavior and memory leaks as the error left
7122 // things in an inconsistent state. It is recommended that the user
7123 // refresh the page.
7124 // TODO: We could warn here? But this happens all the time in our tests?
7125 while (!this.stack.isEmpty()) {
7126 this.stack.pop();
7127 }
7128 }
7129 }
7130
7131 enter(state) {
7132 this.stack.push(state);
7133 }
7134
7135 exit() {
7136 (true && !(this.stack.size !== 0) && (0, _debug.assert)('BUG: unbalanced pop', this.stack.size !== 0));
7137 this.stack.pop();
7138 }
7139
7140 nodeFor(state) {
7141 return (0, _util.expect)(this.nodes.get(state), 'BUG: missing node');
7142 }
7143
7144 appendChild(node, state) {
7145 (true && !(!this.refs.has(state)) && (0, _debug.assert)('BUG: child already appended', !this.refs.has(state)));
7146 var parent = this.stack.current;
7147 var ref = new Ref(state);
7148 this.refs.set(state, ref);
7149
7150 if (parent) {
7151 var parentNode = this.nodeFor(parent);
7152 parentNode.refs.add(ref);
7153 node.parent = parentNode;
7154 } else {
7155 this.roots.add(ref);
7156 }
7157 }
7158
7159 captureRefs(refs) {
7160 var captured = [];
7161 refs.forEach(ref => {
7162 var state = ref.get();
7163
7164 if (state) {
7165 captured.push(this.captureNode(`render-node:${ref.id}`, state));
7166 } else {
7167 refs.delete(ref);
7168 }
7169 });
7170 return captured;
7171 }
7172
7173 captureNode(id, state) {
7174 var node = this.nodeFor(state);
7175 var {
7176 type,
7177 name,
7178 args,
7179 instance,
7180 refs
7181 } = node;
7182 var template = this.captureTemplate(node);
7183 var bounds = this.captureBounds(node);
7184 var children = this.captureRefs(refs);
7185 return {
7186 id,
7187 type,
7188 name,
7189 args: args.value(),
7190 instance,
7191 template,
7192 bounds,
7193 children
7194 };
7195 }
7196
7197 captureTemplate({
7198 template
7199 }) {
7200 return template && (0, _util.unwrapTemplate)(template).referrer.moduleName || null;
7201 }
7202
7203 captureBounds(node) {
7204 var bounds = (0, _util.expect)(node.bounds, 'BUG: missing bounds');
7205 var parentElement = bounds.parentElement();
7206 var firstNode = bounds.firstNode();
7207 var lastNode = bounds.lastNode();
7208 return {
7209 parentElement,
7210 firstNode,
7211 lastNode
7212 };
7213 }
7214
7215 }
7216 /**
7217 @module ember
7218 */
7219
7220 /**
7221 The `{{#each}}` helper loops over elements in a collection. It is an extension
7222 of the base Handlebars `{{#each}}` helper.
7223
7224 The default behavior of `{{#each}}` is to yield its inner block once for every
7225 item in an array passing the item as the first block parameter.
7226
7227 Assuming the `@developers` argument contains this array:
7228
7229 ```javascript
7230 [{ name: 'Yehuda' },{ name: 'Tom' }, { name: 'Paul' }];
7231 ```
7232
7233 ```handlebars
7234 <ul>
7235 {{#each @developers as |person|}}
7236 <li>Hello, {{person.name}}!</li>
7237 {{/each}}
7238 </ul>
7239 ```
7240
7241 The same rules apply to arrays of primitives.
7242
7243 ```javascript
7244 ['Yehuda', 'Tom', 'Paul']
7245 ```
7246
7247 ```handlebars
7248 <ul>
7249 {{#each @developerNames as |name|}}
7250 <li>Hello, {{name}}!</li>
7251 {{/each}}
7252 </ul>
7253 ```
7254
7255 During iteration, the index of each item in the array is provided as a second block
7256 parameter.
7257
7258 ```handlebars
7259 <ul>
7260 {{#each @developers as |person index|}}
7261 <li>Hello, {{person.name}}! You're number {{index}} in line</li>
7262 {{/each}}
7263 </ul>
7264 ```
7265
7266 ### Specifying Keys
7267
7268 In order to improve rendering speed, Ember will try to reuse the DOM elements
7269 where possible. Specifically, if the same item is present in the array both
7270 before and after the change, its DOM output will be reused.
7271
7272 The `key` option is used to tell Ember how to determine if the items in the
7273 array being iterated over with `{{#each}}` has changed between renders. By
7274 default the item's object identity is used.
7275
7276 This is usually sufficient, so in most cases, the `key` option is simply not
7277 needed. However, in some rare cases, the objects' identities may change even
7278 though they represent the same underlying data.
7279
7280 For example:
7281
7282 ```javascript
7283 people.map(person => {
7284 return { ...person, type: 'developer' };
7285 });
7286 ```
7287
7288 In this case, each time the `people` array is `map`-ed over, it will produce
7289 an new array with completely different objects between renders. In these cases,
7290 you can help Ember determine how these objects related to each other with the
7291 `key` option:
7292
7293 ```handlebars
7294 <ul>
7295 {{#each @developers key="name" as |person|}}
7296 <li>Hello, {{person.name}}!</li>
7297 {{/each}}
7298 </ul>
7299 ```
7300
7301 By doing so, Ember will use the value of the property specified (`person.name`
7302 in the example) to find a "match" from the previous render. That is, if Ember
7303 has previously seen an object from the `@developers` array with a matching
7304 name, its DOM elements will be re-used.
7305
7306 There are two special values for `key`:
7307
7308 * `@index` - The index of the item in the array.
7309 * `@identity` - The item in the array itself.
7310
7311 ### {{else}} condition
7312
7313 `{{#each}}` can have a matching `{{else}}`. The contents of this block will render
7314 if the collection is empty.
7315
7316 ```handlebars
7317 <ul>
7318 {{#each @developers as |person|}}
7319 <li>{{person.name}} is available!</li>
7320 {{else}}
7321 <li>Sorry, nobody is available for this task.</li>
7322 {{/each}}
7323 </ul>
7324 ```
7325
7326 @method each
7327 @for Ember.Templates.helpers
7328 @public
7329 */
7330
7331 /**
7332 The `{{each-in}}` helper loops over properties on an object.
7333
7334 For example, given this component definition:
7335
7336 ```app/components/developer-details.js
7337 import Component from '@glimmer/component';
7338 import { tracked } from '@glimmer/tracking';
7339
7340 export default class extends Component {
7341 @tracked developer = {
7342 "name": "Shelly Sails",
7343 "age": 42
7344 };
7345 }
7346 ```
7347
7348 This template would display all properties on the `developer`
7349 object in a list:
7350
7351 ```app/components/developer-details.hbs
7352 <ul>
7353 {{#each-in this.developer as |key value|}}
7354 <li>{{key}}: {{value}}</li>
7355 {{/each-in}}
7356 </ul>
7357 ```
7358
7359 Outputting their name and age.
7360
7361 @method each-in
7362 @for Ember.Templates.helpers
7363 @public
7364 @since 2.1.0
7365 */
7366
7367
7368 class EachInReference {
7369 constructor(inner) {
7370 this.inner = inner;
7371 this.valueTag = (0, _validator.createUpdatableTag)();
7372 this.tag = (0, _validator.combine)([inner.tag, this.valueTag]);
7373 }
7374
7375 value() {
7376 var iterable = this.inner.value();
7377 var tag = (0, _metal.tagForObject)(iterable);
7378
7379 if ((0, _utils.isProxy)(iterable)) {
7380 // this is because the each-in doesn't actually get(proxy, 'key') but bypasses it
7381 // and the proxy's tag is lazy updated on access
7382 iterable = (0, _runtime._contentFor)(iterable);
7383 }
7384
7385 (0, _validator.updateTag)(this.valueTag, tag);
7386 return new EachInWrapper(iterable);
7387 }
7388
7389 get(key) {
7390 return this.inner.get(key);
7391 }
7392
7393 }
7394
7395 class EachInWrapper {
7396 constructor(inner) {
7397 this.inner = inner;
7398 }
7399
7400 }
7401
7402 function eachIn(args) {
7403 return new EachInReference(args.positional.at(0));
7404 }
7405
7406 function toIterator(iterable) {
7407 if (iterable instanceof EachInWrapper) {
7408 return toEachInIterator(iterable.inner);
7409 } else {
7410 return toEachIterator(iterable);
7411 }
7412 }
7413
7414 function toEachInIterator(iterable) {
7415 if (!isIndexable(iterable)) {
7416 return null;
7417 }
7418
7419 if (Array.isArray(iterable) || (0, _utils.isEmberArray)(iterable)) {
7420 return ObjectIterator.fromIndexable(iterable);
7421 } else if (_utils.HAS_NATIVE_SYMBOL && isNativeIterable(iterable)) {
7422 return MapLikeNativeIterator.from(iterable);
7423 } else if (hasForEach(iterable)) {
7424 return ObjectIterator.fromForEachable(iterable);
7425 } else {
7426 return ObjectIterator.fromIndexable(iterable);
7427 }
7428 }
7429
7430 function toEachIterator(iterable) {
7431 if (!(0, _utils.isObject)(iterable)) {
7432 return null;
7433 }
7434
7435 if (Array.isArray(iterable)) {
7436 return ArrayIterator.from(iterable);
7437 } else if ((0, _utils.isEmberArray)(iterable)) {
7438 return EmberArrayIterator.from(iterable);
7439 } else if (_utils.HAS_NATIVE_SYMBOL && isNativeIterable(iterable)) {
7440 return ArrayLikeNativeIterator.from(iterable);
7441 } else if (hasForEach(iterable)) {
7442 return ArrayIterator.fromForEachable(iterable);
7443 } else {
7444 return null;
7445 }
7446 }
7447
7448 class BoundedIterator {
7449 constructor(length) {
7450 this.length = length;
7451 this.position = 0;
7452 }
7453
7454 isEmpty() {
7455 return false;
7456 }
7457
7458 memoFor(position) {
7459 return position;
7460 }
7461
7462 next() {
7463 var {
7464 length,
7465 position
7466 } = this;
7467
7468 if (position >= length) {
7469 return null;
7470 }
7471
7472 var value = this.valueFor(position);
7473 var memo = this.memoFor(position);
7474 this.position++;
7475 return {
7476 value,
7477 memo
7478 };
7479 }
7480
7481 }
7482
7483 class ArrayIterator extends BoundedIterator {
7484 constructor(array) {
7485 super(array.length);
7486 this.array = array;
7487 }
7488
7489 static from(iterable) {
7490 return iterable.length > 0 ? new this(iterable) : null;
7491 }
7492
7493 static fromForEachable(object) {
7494 var array = [];
7495 object.forEach(item => array.push(item));
7496 return this.from(array);
7497 }
7498
7499 valueFor(position) {
7500 return this.array[position];
7501 }
7502
7503 }
7504
7505 class EmberArrayIterator extends BoundedIterator {
7506 constructor(array) {
7507 super(array.length);
7508 this.array = array;
7509 }
7510
7511 static from(iterable) {
7512 return iterable.length > 0 ? new this(iterable) : null;
7513 }
7514
7515 valueFor(position) {
7516 return (0, _metal.objectAt)(this.array, position);
7517 }
7518
7519 }
7520
7521 class ObjectIterator extends BoundedIterator {
7522 constructor(keys, values) {
7523 super(values.length);
7524 this.keys = keys;
7525 this.values = values;
7526 }
7527
7528 static fromIndexable(obj) {
7529 var keys = Object.keys(obj);
7530 var {
7531 length
7532 } = keys;
7533
7534 if (length === 0) {
7535 return null;
7536 } else {
7537 var values = [];
7538
7539 for (var i = 0; i < length; i++) {
7540 var value = void 0;
7541 var key = keys[i];
7542 value = obj[key]; // Add the tag of the returned value if it is an array, since arrays
7543 // should always cause updates if they are consumed and then changed
7544
7545 if ((0, _validator.isTracking)()) {
7546 (0, _validator.consumeTag)((0, _validator.tagFor)(obj, key));
7547
7548 if (Array.isArray(value)) {
7549 (0, _validator.consumeTag)((0, _validator.tagFor)(value, '[]'));
7550 }
7551 }
7552
7553 values.push(value);
7554 }
7555
7556 return new this(keys, values);
7557 }
7558 }
7559
7560 static fromForEachable(obj) {
7561 var keys = [];
7562 var values = [];
7563 var length = 0;
7564 var isMapLike = false; // Not using an arrow function here so we can get an accurate `arguments`
7565
7566 obj.forEach(function (value, key) {
7567 isMapLike = isMapLike || arguments.length >= 2;
7568
7569 if (isMapLike) {
7570 keys.push(key);
7571 }
7572
7573 values.push(value);
7574 length++;
7575 });
7576
7577 if (length === 0) {
7578 return null;
7579 } else if (isMapLike) {
7580 return new this(keys, values);
7581 } else {
7582 return new ArrayIterator(values);
7583 }
7584 }
7585
7586 valueFor(position) {
7587 return this.values[position];
7588 }
7589
7590 memoFor(position) {
7591 return this.keys[position];
7592 }
7593
7594 }
7595
7596 class NativeIterator {
7597 constructor(iterable, result) {
7598 this.iterable = iterable;
7599 this.result = result;
7600 this.position = 0;
7601 }
7602
7603 static from(iterable) {
7604 var iterator = iterable[Symbol.iterator]();
7605 var result = iterator.next();
7606 var {
7607 done
7608 } = result;
7609
7610 if (done) {
7611 return null;
7612 } else {
7613 return new this(iterator, result);
7614 }
7615 }
7616
7617 isEmpty() {
7618 return false;
7619 }
7620
7621 next() {
7622 var {
7623 iterable,
7624 result,
7625 position
7626 } = this;
7627
7628 if (result.done) {
7629 return null;
7630 }
7631
7632 var value = this.valueFor(result, position);
7633 var memo = this.memoFor(result, position);
7634 this.position++;
7635 this.result = iterable.next();
7636 return {
7637 value,
7638 memo
7639 };
7640 }
7641
7642 }
7643
7644 class ArrayLikeNativeIterator extends NativeIterator {
7645 valueFor(result) {
7646 return result.value;
7647 }
7648
7649 memoFor(_result, position) {
7650 return position;
7651 }
7652
7653 }
7654
7655 class MapLikeNativeIterator extends NativeIterator {
7656 valueFor(result) {
7657 return result.value[1];
7658 }
7659
7660 memoFor(result) {
7661 return result.value[0];
7662 }
7663
7664 }
7665
7666 function hasForEach(value) {
7667 return typeof value['forEach'] === 'function';
7668 }
7669
7670 function isNativeIterable(value) {
7671 return typeof value[Symbol.iterator] === 'function';
7672 }
7673
7674 function isIndexable(value) {
7675 return value !== null && (typeof value === 'object' || typeof value === 'function');
7676 }
7677
7678 function toBool(predicate) {
7679 if ((0, _utils.isProxy)(predicate)) {
7680 (0, _validator.consumeTag)((0, _metal.tagForProperty)(predicate, 'content'));
7681 return Boolean((0, _metal.get)(predicate, 'isTruthy'));
7682 } else if ((0, _runtime.isArray)(predicate)) {
7683 (0, _validator.consumeTag)((0, _metal.tagForProperty)(predicate, '[]'));
7684 return predicate.length !== 0;
7685 } else {
7686 return Boolean(predicate);
7687 }
7688 } // Setup global environment
7689 // Autotracking
7690
7691
7692 (0, _validator.setPropertyDidChange)(() => _runloop.backburner.ensureInstance());
7693
7694 if (true
7695 /* DEBUG */
7696 ) {
7697 (0, _validator.setAutotrackingTransactionEnv)({
7698 assert(message) {
7699 (true && !(false) && (0, _debug.assert)(message, false));
7700 },
7701
7702 deprecate(message) {
7703 (true && !(false) && (0, _debug.deprecate)(message, false, {
7704 id: 'autotracking.mutation-after-consumption',
7705 until: '4.0.0'
7706 }));
7707 },
7708
7709 debugMessage(obj, keyName) {
7710 var dirtyString = keyName ? `\`${keyName}\` on \`${(0, _utils.getDebugName)(obj)}\`` : `\`${(0, _utils.getDebugName)(obj)}\``;
7711 return `You attempted to update ${dirtyString}, but it had already been used previously in the same computation. Attempting to update a value after using it in a computation can cause logical errors, infinite revalidation bugs, and performance issues, and is not supported.`;
7712 }
7713
7714 });
7715 } // Destruction
7716
7717
7718 (0, _runtime2.setScheduleDestroy)((destroyable, destructor) => {
7719 (0, _runloop.schedule)('actions', null, destructor, destroyable);
7720 });
7721 (0, _runtime2.setScheduleDestroyed)(finalizeDestructor => {
7722 (0, _runloop.schedule)('destroy', null, finalizeDestructor);
7723 });
7724
7725 class EmberEnvironmentExtra {
7726 constructor(owner) {
7727 this.owner = owner;
7728
7729 if (_environment2.ENV._DEBUG_RENDER_TREE) {
7730 this._debugRenderTree = new DebugRenderTree();
7731 }
7732 }
7733
7734 get debugRenderTree() {
7735 if (_environment2.ENV._DEBUG_RENDER_TREE) {
7736 return this._debugRenderTree;
7737 } else {
7738 throw new Error("Can't access debug render tree outside of the inspector (_DEBUG_RENDER_TREE flag is disabled)");
7739 }
7740 }
7741
7742 begin() {
7743 if (_environment2.ENV._DEBUG_RENDER_TREE) {
7744 this.debugRenderTree.begin();
7745 }
7746 }
7747
7748 commit() {
7749 if (_environment2.ENV._DEBUG_RENDER_TREE) {
7750 this.debugRenderTree.commit();
7751 }
7752 }
7753
7754 }
7755
7756 class EmberEnvironmentDelegate {
7757 constructor(owner, isInteractive) {
7758 this.toBool = toBool;
7759 this.toIterator = toIterator;
7760 this.getProp = _metal._getProp;
7761 this.getPath = _metal.get;
7762 this.setPath = _metal.set;
7763 this.extra = new EmberEnvironmentExtra(owner);
7764 this.isInteractive = isInteractive;
7765 installProtocolForURL(this);
7766 } // this gets clobbered by installPlatformSpecificProtocolForURL
7767 // it really should just delegate to a platform specific injection
7768
7769
7770 protocolForURL(s) {
7771 return s;
7772 }
7773
7774 getTemplatePathDebugContext(pathRef) {
7775 var stack = this.extra.debugRenderTree.logRenderStackForPath(pathRef);
7776 return `While rendering:\n\n${stack}`;
7777 }
7778
7779 setTemplatePathDebugContext(pathRef, desc, parentRef) {
7780 var type = 'root';
7781
7782 if (pathRef instanceof _reference.IterationItemReference) {
7783 type = 'iterator';
7784 } else if (pathRef instanceof _reference.PropertyReference) {
7785 type = 'property';
7786 }
7787
7788 this.extra.debugRenderTree.createPath(pathRef, desc, type, parentRef);
7789 }
7790
7791 onTransactionBegin() {
7792 this.extra.begin();
7793 }
7794
7795 onTransactionCommit() {
7796 this.extra.commit();
7797 }
7798
7799 }
7800
7801 if (true
7802 /* DEBUG */
7803 ) {
7804 class StyleAttributeManager extends _runtime2.SimpleDynamicAttribute {
7805 set(dom, value, env) {
7806 (true && (0, _debug.warn)((0, _views.constructStyleDeprecationMessage)(value), (() => {
7807 if (value === null || value === undefined || isHTMLSafe(value)) {
7808 return true;
7809 }
7810
7811 return false;
7812 })(), {
7813 id: 'ember-htmlbars.style-xss-warning'
7814 }));
7815 super.set(dom, value, env);
7816 }
7817
7818 update(value, env) {
7819 (true && (0, _debug.warn)((0, _views.constructStyleDeprecationMessage)(value), (() => {
7820 if (value === null || value === undefined || isHTMLSafe(value)) {
7821 return true;
7822 }
7823
7824 return false;
7825 })(), {
7826 id: 'ember-htmlbars.style-xss-warning'
7827 }));
7828 super.update(value, env);
7829 }
7830
7831 }
7832
7833 EmberEnvironmentDelegate.prototype.attributeFor = function (element, attribute, isTrusting, namespace) {
7834 if (attribute === 'style' && !isTrusting) {
7835 return new StyleAttributeManager({
7836 element,
7837 name: attribute,
7838 namespace
7839 });
7840 }
7841
7842 return (0, _runtime2.dynamicAttribute)(element, attribute, namespace);
7843 };
7844 }
7845
7846 var CAPABILITIES$1 = {
7847 dynamicLayout: false,
7848 dynamicTag: false,
7849 prepareArgs: false,
7850 createArgs: true,
7851 attributeHook: false,
7852 elementHook: false,
7853 createCaller: false,
7854 dynamicScope: true,
7855 updateHook: true,
7856 createInstance: true,
7857 wrapped: false,
7858 willDestroy: false
7859 };
7860
7861 function capabilities(managerAPI, options = {}) {
7862 (true && !(managerAPI === '3.4' || managerAPI === '3.13') && (0, _debug.assert)('Invalid component manager compatibility specified', managerAPI === '3.4' || managerAPI === '3.13'));
7863 var updateHook = true;
7864 {
7865 updateHook = managerAPI === '3.13' ? Boolean(options.updateHook) : true;
7866 }
7867 return {
7868 asyncLifeCycleCallbacks: Boolean(options.asyncLifecycleCallbacks),
7869 destructor: Boolean(options.destructor),
7870 updateHook
7871 };
7872 }
7873
7874 function hasAsyncLifeCycleCallbacks(delegate) {
7875 return delegate.capabilities.asyncLifeCycleCallbacks;
7876 }
7877
7878 function hasUpdateHook(delegate) {
7879 return delegate.capabilities.updateHook;
7880 }
7881
7882 function hasAsyncUpdateHook(delegate) {
7883 return hasAsyncLifeCycleCallbacks(delegate) && hasUpdateHook(delegate);
7884 }
7885
7886 function hasDestructors(delegate) {
7887 return delegate.capabilities.destructor;
7888 }
7889 /**
7890 The CustomComponentManager allows addons to provide custom component
7891 implementations that integrate seamlessly into Ember. This is accomplished
7892 through a delegate, registered with the custom component manager, which
7893 implements a set of hooks that determine component behavior.
7894
7895 To create a custom component manager, instantiate a new CustomComponentManager
7896 class and pass the delegate as the first argument:
7897
7898 ```js
7899 let manager = new CustomComponentManager({
7900 // ...delegate implementation...
7901 });
7902 ```
7903
7904 ## Delegate Hooks
7905
7906 Throughout the lifecycle of a component, the component manager will invoke
7907 delegate hooks that are responsible for surfacing those lifecycle changes to
7908 the end developer.
7909
7910 * `create()` - invoked when a new instance of a component should be created
7911 * `update()` - invoked when the arguments passed to a component change
7912 * `getContext()` - returns the object that should be
7913 */
7914
7915
7916 class CustomComponentManager extends AbstractManager {
7917 create(env, definition, args) {
7918 var {
7919 delegate
7920 } = definition;
7921 var capturedArgs = args.capture();
7922 var namedArgs = capturedArgs.named;
7923 var value;
7924 var namedArgsProxy = {};
7925 {
7926 var getTag = key => {
7927 return namedArgs.get(key).tag;
7928 };
7929
7930 if (_utils.HAS_NATIVE_PROXY) {
7931 var handler = {
7932 get(_target, prop) {
7933 if (namedArgs.has(prop)) {
7934 var ref = namedArgs.get(prop);
7935 (0, _validator.consumeTag)(ref.tag);
7936 return ref.value();
7937 } else if (prop === _metal.CUSTOM_TAG_FOR) {
7938 return getTag;
7939 }
7940 },
7941
7942 has(_target, prop) {
7943 return namedArgs.has(prop);
7944 },
7945
7946 ownKeys(_target) {
7947 return namedArgs.names;
7948 },
7949
7950 getOwnPropertyDescriptor(_target, prop) {
7951 (true && !(namedArgs.has(prop)) && (0, _debug.assert)('args proxies do not have real property descriptors, so you should never need to call getOwnPropertyDescriptor yourself. This code exists for enumerability, such as in for-in loops and Object.keys()', namedArgs.has(prop)));
7952 return {
7953 enumerable: true,
7954 configurable: true
7955 };
7956 }
7957
7958 };
7959
7960 if (true
7961 /* DEBUG */
7962 ) {
7963 handler.set = function (_target, prop) {
7964 (true && !(false) && (0, _debug.assert)(`You attempted to set ${definition.ComponentClass.class}#${String(prop)} on a components arguments. Component arguments are immutable and cannot be updated directly, they always represent the values that are passed to your component. If you want to set default values, you should use a getter instead`));
7965 return false;
7966 };
7967 }
7968
7969 namedArgsProxy = new Proxy(namedArgsProxy, handler);
7970 } else {
7971 Object.defineProperty(namedArgsProxy, _metal.CUSTOM_TAG_FOR, {
7972 configurable: false,
7973 enumerable: false,
7974 value: getTag
7975 });
7976 namedArgs.names.forEach(name => {
7977 Object.defineProperty(namedArgsProxy, name, {
7978 enumerable: true,
7979 configurable: true,
7980
7981 get() {
7982 var ref = namedArgs.get(name);
7983 (0, _validator.consumeTag)(ref.tag);
7984 return ref.value();
7985 }
7986
7987 });
7988 });
7989 }
7990
7991 value = {
7992 named: namedArgsProxy,
7993 positional: capturedArgs.positional.value()
7994 };
7995 }
7996 var component = delegate.createComponent(definition.ComponentClass.class, value);
7997 var bucket = new CustomComponentState(delegate, component, capturedArgs, env, namedArgsProxy);
7998
7999 if (_environment2.ENV._DEBUG_RENDER_TREE) {
8000 env.extra.debugRenderTree.create(bucket, {
8001 type: 'component',
8002 name: definition.name,
8003 args: args.capture(),
8004 instance: component,
8005 template: definition.template
8006 });
8007 (0, _runtime2.registerDestructor)(bucket, () => {
8008 env.extra.debugRenderTree.willDestroy(bucket);
8009 });
8010 }
8011
8012 return bucket;
8013 }
8014
8015 update(bucket) {
8016 if (_environment2.ENV._DEBUG_RENDER_TREE) {
8017 bucket.env.extra.debugRenderTree.update(bucket);
8018 }
8019
8020 var {
8021 delegate,
8022 component,
8023 args,
8024 namedArgsProxy
8025 } = bucket;
8026 var value;
8027 {
8028 value = {
8029 named: namedArgsProxy,
8030 positional: args.positional.value()
8031 };
8032 }
8033
8034 if (hasUpdateHook(delegate)) {
8035 delegate.updateComponent(component, value);
8036 }
8037 }
8038
8039 didCreate({
8040 delegate,
8041 component
8042 }) {
8043 if (hasAsyncLifeCycleCallbacks(delegate)) {
8044 delegate.didCreateComponent(component);
8045 }
8046 }
8047
8048 didUpdate({
8049 delegate,
8050 component
8051 }) {
8052 if (hasAsyncUpdateHook(delegate)) {
8053 delegate.didUpdateComponent(component);
8054 }
8055 }
8056
8057 getContext({
8058 delegate,
8059 component
8060 }) {
8061 delegate.getContext(component);
8062 }
8063
8064 getSelf({
8065 env,
8066 delegate,
8067 component
8068 }) {
8069 return new _reference.ComponentRootReference(delegate.getContext(component), env);
8070 }
8071
8072 getDestroyable(bucket) {
8073 return bucket;
8074 }
8075
8076 getCapabilities({
8077 delegate
8078 }) {
8079 return (0, _polyfills.assign)({}, CAPABILITIES$1, {
8080 updateHook: _environment2.ENV._DEBUG_RENDER_TREE || delegate.capabilities.updateHook
8081 });
8082 }
8083
8084 getTag({
8085 args
8086 }) {
8087 if ((0, _validator.isConstTagged)(args)) {
8088 // returning a const tag skips the update hook (VM BUG?)
8089 return (0, _validator.createTag)();
8090 } else {
8091 return args.tag;
8092 }
8093 }
8094
8095 didRenderLayout(bucket, bounds) {
8096 if (_environment2.ENV._DEBUG_RENDER_TREE) {
8097 bucket.env.extra.debugRenderTree.didRender(bucket, bounds);
8098 }
8099 }
8100
8101 didUpdateLayout(bucket, bounds) {
8102 if (_environment2.ENV._DEBUG_RENDER_TREE) {
8103 bucket.env.extra.debugRenderTree.didRender(bucket, bounds);
8104 }
8105 }
8106
8107 getJitStaticLayout(state) {
8108 return (0, _util.unwrapTemplate)(state.template).asLayout();
8109 }
8110
8111 }
8112
8113 var CUSTOM_COMPONENT_MANAGER = new CustomComponentManager();
8114 /**
8115 * Stores internal state about a component instance after it's been created.
8116 */
8117
8118 class CustomComponentState {
8119 constructor(delegate, component, args, env, namedArgsProxy) {
8120 this.delegate = delegate;
8121 this.component = component;
8122 this.args = args;
8123 this.env = env;
8124 this.namedArgsProxy = namedArgsProxy;
8125
8126 if (hasDestructors(delegate)) {
8127 (0, _runtime2.registerDestructor)(this, () => delegate.destroyComponent(component));
8128 }
8129 }
8130
8131 }
8132
8133 class CustomManagerDefinition {
8134 constructor(name, ComponentClass, delegate, template) {
8135 this.name = name;
8136 this.ComponentClass = ComponentClass;
8137 this.delegate = delegate;
8138 this.template = template;
8139 this.manager = CUSTOM_COMPONENT_MANAGER;
8140 this.state = {
8141 name,
8142 ComponentClass,
8143 template,
8144 delegate
8145 };
8146 }
8147
8148 }
8149
8150 class InternalComponentDefinition {
8151 constructor(manager, ComponentClass, layout) {
8152 this.manager = manager;
8153 this.state = {
8154 ComponentClass,
8155 layout
8156 };
8157 }
8158
8159 }
8160
8161 class InternalManager extends AbstractManager {
8162 constructor(owner) {
8163 super();
8164 this.owner = owner;
8165 }
8166
8167 getJitStaticLayout({
8168 layout: template
8169 }) {
8170 return (0, _util.unwrapTemplate)(template).asLayout();
8171 }
8172
8173 }
8174
8175 var CAPABILITIES$2 = {
8176 dynamicLayout: false,
8177 dynamicTag: false,
8178 prepareArgs: false,
8179 createArgs: _environment2.ENV._DEBUG_RENDER_TREE,
8180 attributeHook: false,
8181 elementHook: false,
8182 createCaller: false,
8183 dynamicScope: false,
8184 updateHook: _environment2.ENV._DEBUG_RENDER_TREE,
8185 createInstance: true,
8186 wrapped: false,
8187 willDestroy: false
8188 };
8189
8190 class TemplateOnlyComponentManager extends AbstractManager {
8191 getJitStaticLayout({
8192 template
8193 }) {
8194 return (0, _util.unwrapTemplate)(template).asLayout();
8195 }
8196
8197 getCapabilities() {
8198 return CAPABILITIES$2;
8199 }
8200
8201 create(environment, {
8202 name,
8203 template
8204 }, args) {
8205 if (_environment2.ENV._DEBUG_RENDER_TREE) {
8206 var bucket = {
8207 environment
8208 };
8209 environment.extra.debugRenderTree.create(bucket, {
8210 type: 'component',
8211 name: name,
8212 args: args.capture(),
8213 instance: null,
8214 template
8215 });
8216 (0, _runtime2.registerDestructor)(bucket, () => {
8217 bucket.environment.extra.debugRenderTree.willDestroy(bucket);
8218 });
8219 return bucket;
8220 } else {
8221 return null;
8222 }
8223 }
8224
8225 getSelf() {
8226 return _runtime2.NULL_REFERENCE;
8227 }
8228
8229 getTag() {
8230 if (_environment2.ENV._DEBUG_RENDER_TREE) {
8231 // returning a const tag skips the update hook (VM BUG?)
8232 return (0, _validator.createTag)();
8233 } else {
8234 // an outlet has no hooks
8235 return _validator.CONSTANT_TAG;
8236 }
8237 }
8238
8239 getDestroyable(bucket) {
8240 if (_environment2.ENV._DEBUG_RENDER_TREE) {
8241 return bucket;
8242 } else {
8243 return null;
8244 }
8245 }
8246
8247 didRenderLayout(bucket, bounds) {
8248 if (_environment2.ENV._DEBUG_RENDER_TREE) {
8249 bucket.environment.extra.debugRenderTree.didRender(bucket, bounds);
8250 }
8251 }
8252
8253 update(bucket) {
8254 if (_environment2.ENV._DEBUG_RENDER_TREE) {
8255 bucket.environment.extra.debugRenderTree.update(bucket);
8256 }
8257 }
8258
8259 didUpdateLayout(bucket, bounds) {
8260 if (_environment2.ENV._DEBUG_RENDER_TREE) {
8261 bucket.environment.extra.debugRenderTree.didRender(bucket, bounds);
8262 }
8263 }
8264
8265 }
8266
8267 var MANAGER = new TemplateOnlyComponentManager();
8268
8269 class TemplateOnlyComponentDefinition {
8270 constructor(name, template) {
8271 this.name = name;
8272 this.template = template;
8273 this.manager = MANAGER;
8274 }
8275
8276 get state() {
8277 return this;
8278 }
8279
8280 }
8281
8282 var helper$1;
8283
8284 if (true
8285 /* DEBUG */
8286 ) {
8287 class ComponentAssertionReference {
8288 constructor(component, message) {
8289 this.component = component;
8290 this.message = message;
8291 this.tag = component.tag;
8292 }
8293
8294 value() {
8295 var value = this.component.value();
8296 (true && !(typeof value !== 'string') && (0, _debug.assert)(this.message, typeof value !== 'string'));
8297 return value;
8298 }
8299
8300 get(property) {
8301 return this.component.get(property);
8302 }
8303
8304 }
8305
8306 helper$1 = args => new ComponentAssertionReference(args.positional.at(0), args.positional.at(1).value());
8307 } else {
8308 helper$1 = args => args.positional.at(0);
8309 }
8310
8311 var componentAssertionHelper = helper$1;
8312 var helper$2;
8313
8314 if (true
8315 /* DEBUG */
8316 ) {
8317 class InElementNullCheckReference {
8318 constructor(inner) {
8319 this.inner = inner;
8320 this.tag = inner.tag;
8321 }
8322
8323 value() {
8324 var value = this.inner.value();
8325 (true && !(value !== null && value !== undefined) && (0, _debug.assert)('You cannot pass a null or undefined destination element to in-element', value !== null && value !== undefined));
8326 return value;
8327 }
8328
8329 get(key) {
8330 return this.inner.get(key);
8331 }
8332
8333 }
8334
8335 helper$2 = args => new InElementNullCheckReference(args.positional.at(0));
8336 } else {
8337 helper$2 = args => args.positional.at(0);
8338 }
8339
8340 var inElementNullCheckHelper = helper$2;
8341
8342 function normalizeClass({
8343 positional
8344 }) {
8345 var classNameParts = positional.at(0).value().split('.');
8346 var className = classNameParts[classNameParts.length - 1];
8347 var value = positional.at(1).value();
8348
8349 if (value === true) {
8350 return (0, _string.dasherize)(className);
8351 } else if (!value && value !== 0) {
8352 return '';
8353 } else {
8354 return String(value);
8355 }
8356 }
8357
8358 function normalizeClassHelper(args, vm) {
8359 return new _reference.HelperRootReference(normalizeClass, args.capture(), vm.env);
8360 }
8361 /**
8362 @module ember
8363 */
8364
8365 /**
8366 This reference is used to get the `[]` tag of iterables, so we can trigger
8367 updates to `{{each}}` when it changes. It is put into place by a template
8368 transform at build time, similar to the (-each-in) helper
8369 */
8370
8371
8372 class TrackArrayReference {
8373 constructor(inner) {
8374 this.inner = inner;
8375 this.valueTag = (0, _validator.createUpdatableTag)();
8376 this.tag = (0, _validator.combine)([inner.tag, this.valueTag]);
8377 }
8378
8379 value() {
8380 var iterable = this.inner.value();
8381 var tag = (0, _utils.isObject)(iterable) ? (0, _metal.tagForProperty)(iterable, '[]') : _validator.CONSTANT_TAG;
8382 (0, _validator.updateTag)(this.valueTag, tag);
8383 return iterable;
8384 }
8385
8386 get(key) {
8387 return this.inner.get(key);
8388 }
8389
8390 }
8391
8392 function trackArray(args) {
8393 return new TrackArrayReference(args.positional.at(0));
8394 }
8395 /**
8396 @module ember
8397 */
8398
8399 /**
8400 Use the `{{array}}` helper to create an array to pass as an option to your
8401 components.
8402
8403 ```handlebars
8404 <MyComponent @people={{array
8405 'Tom Dade'
8406 'Yehuda Katz'
8407 this.myOtherPerson}}
8408 />
8409 ```
8410 or
8411 ```handlebars
8412 {{my-component people=(array
8413 'Tom Dade'
8414 'Yehuda Katz'
8415 this.myOtherPerson)
8416 }}
8417 ```
8418
8419 Would result in an object such as:
8420
8421 ```js
8422 ['Tom Date', 'Yehuda Katz', this.get('myOtherPerson')]
8423 ```
8424
8425 Where the 3rd item in the array is bound to updates of the `myOtherPerson` property.
8426
8427 @method array
8428 @for Ember.Templates.helpers
8429 @param {Array} options
8430 @return {Array} Array
8431 @since 3.8.0
8432 @public
8433 */
8434
8435
8436 function array(args) {
8437 return args.positional.capture();
8438 }
8439
8440 var isEmpty = value => {
8441 return value === null || value === undefined || typeof value.toString !== 'function';
8442 };
8443
8444 var normalizeTextValue = value => {
8445 if (isEmpty(value)) {
8446 return '';
8447 }
8448
8449 return String(value);
8450 };
8451 /**
8452 @module ember
8453 */
8454
8455 /**
8456 Concatenates the given arguments into a string.
8457
8458 Example:
8459
8460 ```handlebars
8461 {{some-component name=(concat firstName " " lastName)}}
8462
8463 {{! would pass name="<first name value> <last name value>" to the component}}
8464 ```
8465
8466 or for angle bracket invocation, you actually don't need concat at all.
8467
8468 ```handlebars
8469 <SomeComponent @name="{{firstName}} {{lastName}}" />
8470 ```
8471
8472 @public
8473 @method concat
8474 @for Ember.Templates.helpers
8475 @since 1.13.0
8476 */
8477
8478
8479 function concat({
8480 positional
8481 }) {
8482 return positional.value().map(normalizeTextValue).join('');
8483 }
8484
8485 function concat$1(args, vm) {
8486 return new _reference.HelperRootReference(concat, args.capture(), vm.env);
8487 }
8488
8489 function buildUntouchableThis(source) {
8490 var context = null;
8491
8492 if (true
8493 /* DEBUG */
8494 && _utils.HAS_NATIVE_PROXY) {
8495 var assertOnProperty = property => {
8496 (true && !(false) && (0, _debug.assert)(`You accessed \`this.${String(property)}\` from a function passed to the ${source}, but the function itself was not bound to a valid \`this\` context. Consider updating to usage of \`@action\`.`));
8497 };
8498
8499 context = new Proxy({}, {
8500 get(_target, property) {
8501 assertOnProperty(property);
8502 },
8503
8504 set(_target, property) {
8505 assertOnProperty(property);
8506 return false;
8507 },
8508
8509 has(_target, property) {
8510 assertOnProperty(property);
8511 return false;
8512 }
8513
8514 });
8515 }
8516
8517 return context;
8518 }
8519
8520 var context = buildUntouchableThis('`fn` helper');
8521 /**
8522 @module ember
8523 */
8524
8525 /**
8526 The `fn` helper allows you to ensure a function that you are passing off
8527 to another component, helper, or modifier has access to arguments that are
8528 available in the template.
8529
8530 For example, if you have an `each` helper looping over a number of items, you
8531 may need to pass a function that expects to receive the item as an argument
8532 to a component invoked within the loop. Here's how you could use the `fn`
8533 helper to pass both the function and its arguments together:
8534
8535 ```app/templates/components/items-listing.hbs
8536 {{#each @items as |item|}}
8537 <DisplayItem @item=item @select={{fn this.handleSelected item}} />
8538 {{/each}}
8539 ```
8540
8541 ```app/components/items-list.js
8542 import Component from '@glimmer/component';
8543 import { action } from '@ember/object';
8544
8545 export default class ItemsList extends Component {
8546 @action
8547 handleSelected(item) {
8548 // ...snip...
8549 }
8550 }
8551 ```
8552
8553 In this case the `display-item` component will receive a normal function
8554 that it can invoke. When it invokes the function, the `handleSelected`
8555 function will receive the `item` and any arguments passed, thanks to the
8556 `fn` helper.
8557
8558 Let's take look at what that means in a couple circumstances:
8559
8560 - When invoked as `this.args.select()` the `handleSelected` function will
8561 receive the `item` from the loop as its first and only argument.
8562 - When invoked as `this.args.select('foo')` the `handleSelected` function
8563 will receive the `item` from the loop as its first argument and the
8564 string `'foo'` as its second argument.
8565
8566 In the example above, we used `@action` to ensure that `handleSelected` is
8567 properly bound to the `items-list`, but let's explore what happens if we
8568 left out `@action`:
8569
8570 ```app/components/items-list.js
8571 import Component from '@glimmer/component';
8572
8573 export default class ItemsList extends Component {
8574 handleSelected(item) {
8575 // ...snip...
8576 }
8577 }
8578 ```
8579
8580 In this example, when `handleSelected` is invoked inside the `display-item`
8581 component, it will **not** have access to the component instance. In other
8582 words, it will have no `this` context, so please make sure your functions
8583 are bound (via `@action` or other means) before passing into `fn`!
8584
8585 See also [partial application](https://en.wikipedia.org/wiki/Partial_application).
8586
8587 @method fn
8588 @for Ember.Templates.helpers
8589 @public
8590 @since 3.11.0
8591 */
8592
8593 function fn({
8594 positional
8595 }, env) {
8596 var callbackRef = positional.at(0);
8597 (true && !(callbackRef !== undefined) && (0, _debug.assert)(`You must pass a function as the \`fn\` helpers first argument.`, callbackRef !== undefined));
8598
8599 if (true
8600 /* DEBUG */
8601 && typeof callbackRef[INVOKE] !== 'function') {
8602 var callback = callbackRef.value();
8603 (true && !(typeof callback === 'function') && (0, _debug.assert)(`You must pass a function as the \`fn\` helpers first argument, you passed ${callback === null ? 'null' : typeof callback}. ${env.getTemplatePathDebugContext(callbackRef)}`, typeof callback === 'function'));
8604 }
8605
8606 return (...invocationArgs) => {
8607 var [fn, ...args] = positional.value();
8608
8609 if (typeof callbackRef[INVOKE] === 'function') {
8610 // references with the INVOKE symbol expect the function behind
8611 // the symbol to be bound to the reference
8612 return callbackRef[INVOKE](...args, ...invocationArgs);
8613 } else {
8614 return fn.call(context, ...args, ...invocationArgs);
8615 }
8616 };
8617 }
8618
8619 function fn$1(args, vm) {
8620 var callback = fn;
8621
8622 if (true
8623 /* DEBUG */
8624 ) {
8625 callback = args => {
8626 return fn(args, vm.env);
8627 };
8628 }
8629
8630 return new _reference.HelperRootReference(callback, args.capture(), vm.env);
8631 }
8632 /**
8633 @module ember
8634 */
8635
8636 /**
8637 Dynamically look up a property on an object. The second argument to `{{get}}`
8638 should have a string value, although it can be bound.
8639
8640 For example, these two usages are equivalent:
8641
8642 ```app/components/developer-detail.js
8643 import Component from '@glimmer/component';
8644 import { tracked } from '@glimmer/tracking';
8645
8646 export default class extends Component {
8647 @tracked developer = {
8648 name: "Sandi Metz",
8649 language: "Ruby"
8650 }
8651 }
8652 ```
8653
8654 ```handlebars
8655 {{this.developer.name}}
8656 {{get this.developer "name"}}
8657 ```
8658
8659 If there were several facts about a person, the `{{get}}` helper can dynamically
8660 pick one:
8661
8662 ```app/templates/application.hbs
8663 <DeveloperDetail @factName="language" />
8664 ```
8665
8666 ```handlebars
8667 {{get this.developer @factName}}
8668 ```
8669
8670 For a more complex example, this template would allow the user to switch
8671 between showing the user's height and weight with a click:
8672
8673 ```app/components/developer-detail.js
8674 import Component from '@glimmer/component';
8675 import { tracked } from '@glimmer/tracking';
8676
8677 export default class extends Component {
8678 @tracked developer = {
8679 name: "Sandi Metz",
8680 language: "Ruby"
8681 }
8682
8683 @tracked currentFact = 'name'
8684
8685 @action
8686 showFact(fact) {
8687 this.currentFact = fact;
8688 }
8689 }
8690 ```
8691
8692 ```app/components/developer-detail.js
8693 {{get this.developer this.currentFact}}
8694
8695 <button {{on 'click' (fn this.showFact "name")}}>Show name</button>
8696 <button {{on 'click' (fn this.showFact "language")}}>Show language</button>
8697 ```
8698
8699 The `{{get}}` helper can also respect mutable values itself. For example:
8700
8701 ```app/components/developer-detail.js
8702 <Input @value={{mut (get this.person this.currentFact)}} />
8703
8704 <button {{on 'click' (fn this.showFact "name")}}>Show name</button>
8705 <button {{on 'click' (fn this.showFact "language")}}>Show language</button>
8706 ```
8707
8708 Would allow the user to swap what fact is being displayed, and also edit
8709 that fact via a two-way mutable binding.
8710
8711 @public
8712 @method get
8713 @for Ember.Templates.helpers
8714 @since 2.1.0
8715 */
8716
8717
8718 function get$1(args, vm) {
8719 var sourceReference = args.positional.at(0);
8720 var pathReference = args.positional.at(1);
8721
8722 if ((0, _validator.isConstTagged)(pathReference)) {
8723 // Since the path is constant, we can create a normal chain of property
8724 // references. The source reference will update like normal, and all of the
8725 // child references will update accordingly.
8726 var path = pathReference.value();
8727
8728 if (path === undefined || path === null || path === '') {
8729 return _runtime2.NULL_REFERENCE;
8730 } else if (typeof path === 'string' && path.indexOf('.') > -1) {
8731 return referenceFromParts(sourceReference, path.split('.'));
8732 } else {
8733 return sourceReference.get(String(path));
8734 }
8735 } else {
8736 return new GetHelperRootReference(args.capture(), vm.env);
8737 }
8738 }
8739
8740 function get$2({
8741 positional
8742 }) {
8743 var source = positional.at(0).value();
8744
8745 if ((0, _utils.isObject)(source)) {
8746 var path = positional.at(1).value();
8747 return (0, _metal.get)(source, String(path));
8748 }
8749 }
8750
8751 class GetHelperRootReference extends _reference.HelperRootReference {
8752 constructor(args, env) {
8753 super(get$2, args, env);
8754 this.sourceReference = args.positional.at(0);
8755 this.pathReference = args.positional.at(1);
8756 }
8757
8758 [_reference.UPDATE_REFERENCED_VALUE](value) {
8759 var source = this.sourceReference.value();
8760
8761 if ((0, _utils.isObject)(source)) {
8762 var path = String(this.pathReference.value());
8763 (0, _metal.set)(source, path, value);
8764 }
8765 }
8766
8767 }
8768 /**
8769 @module ember
8770 */
8771
8772 /**
8773 Use the `{{hash}}` helper to create a hash to pass as an option to your
8774 components. This is specially useful for contextual components where you can
8775 just yield a hash:
8776
8777 ```handlebars
8778 {{yield (hash
8779 name='Sarah'
8780 title=office
8781 )}}
8782 ```
8783
8784 Would result in an object such as:
8785
8786 ```js
8787 { name: 'Sarah', title: this.get('office') }
8788 ```
8789
8790 Where the `title` is bound to updates of the `office` property.
8791
8792 Note that the hash is an empty object with no prototype chain, therefore
8793 common methods like `toString` are not available in the resulting hash.
8794 If you need to use such a method, you can use the `call` or `apply`
8795 approach:
8796
8797 ```js
8798 function toString(obj) {
8799 return Object.prototype.toString.apply(obj);
8800 }
8801 ```
8802
8803 @method hash
8804 @for Ember.Templates.helpers
8805 @param {Object} options
8806 @return {Object} Hash
8807 @since 2.3.0
8808 @public
8809 */
8810
8811
8812 function hash(args) {
8813 return args.named.capture();
8814 }
8815 /**
8816 @module ember
8817 */
8818
8819
8820 function ifHelper({
8821 positional
8822 }) {
8823 (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));
8824 var condition = positional.at(0);
8825 var truthyValue = positional.at(1);
8826 var falsyValue = positional.at(2);
8827
8828 if (toBool(condition.value()) === true) {
8829 return truthyValue.value();
8830 } else {
8831 return falsyValue !== undefined ? falsyValue.value() : undefined;
8832 }
8833 }
8834
8835 function unless({
8836 positional
8837 }) {
8838 (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));
8839 var condition = positional.at(0);
8840 var truthyValue = positional.at(2);
8841 var falsyValue = positional.at(1);
8842
8843 if (toBool(condition.value()) === true) {
8844 return truthyValue !== undefined ? truthyValue.value() : undefined;
8845 } else {
8846 return falsyValue.value();
8847 }
8848 }
8849 /**
8850 The `if` helper allows you to conditionally render one of two branches,
8851 depending on the "truthiness" of a property.
8852 For example the following values are all falsey: `false`, `undefined`, `null`, `""`, `0`, `NaN` or an empty array.
8853
8854 This helper has two forms, block and inline.
8855
8856 ## Block form
8857
8858 You can use the block form of `if` to conditionally render a section of the template.
8859
8860 To use it, pass the conditional value to the `if` helper,
8861 using the block form to wrap the section of template you want to conditionally render.
8862 Like so:
8863
8864 ```app/templates/application.hbs
8865 <Weather />
8866 ```
8867
8868 ```app/components/weather.hbs
8869 {{! will not render because greeting is undefined}}
8870 {{#if @isRaining}}
8871 Yes, grab an umbrella!
8872 {{/if}}
8873 ```
8874
8875 You can also define what to show if the property is falsey by using
8876 the `else` helper.
8877
8878 ```app/components/weather.hbs
8879 {{#if @isRaining}}
8880 Yes, grab an umbrella!
8881 {{else}}
8882 No, it's lovely outside!
8883 {{/if}}
8884 ```
8885
8886 You are also able to combine `else` and `if` helpers to create more complex
8887 conditional logic.
8888
8889 For the following template:
8890
8891 ```app/components/weather.hbs
8892 {{#if @isRaining}}
8893 Yes, grab an umbrella!
8894 {{else if @isCold}}
8895 Grab a coat, it's chilly!
8896 {{else}}
8897 No, it's lovely outside!
8898 {{/if}}
8899 ```
8900
8901 If you call it by saying `isCold` is true:
8902
8903 ```app/templates/application.hbs
8904 <Weather @isCold={{true}} />
8905 ```
8906
8907 Then `Grab a coat, it's chilly!` will be rendered.
8908
8909 ## Inline form
8910
8911 The inline `if` helper conditionally renders a single property or string.
8912
8913 In this form, the `if` helper receives three arguments, the conditional value,
8914 the value to render when truthy, and the value to render when falsey.
8915
8916 For example, if `useLongGreeting` is truthy, the following:
8917
8918 ```app/templates/application.hbs
8919 <Greeting @useLongGreeting={{true}} />
8920 ```
8921
8922 ```app/components/greeting.hbs
8923 {{if @useLongGreeting "Hello" "Hi"}} Alex
8924 ```
8925
8926 Will render:
8927
8928 ```html
8929 Hello Alex
8930 ```
8931
8932 One detail to keep in mind is that both branches of the `if` helper will be evaluated,
8933 so if you have `{{if condition "foo" (expensive-operation "bar")`,
8934 `expensive-operation` will always calculate.
8935
8936 @method if
8937 @for Ember.Templates.helpers
8938 @public
8939 */
8940
8941
8942 function inlineIf(args, vm) {
8943 return new _reference.HelperRootReference(ifHelper, args.capture(), vm.env);
8944 }
8945 /**
8946 The `unless` helper is the inverse of the `if` helper. It displays if a value
8947 is falsey ("not true" or "is false"). Example values that will display with
8948 `unless`: `false`, `undefined`, `null`, `""`, `0`, `NaN` or an empty array.
8949
8950 ## Inline form
8951
8952 The inline `unless` helper conditionally renders a single property or string.
8953 This helper acts like a ternary operator. If the first property is falsy,
8954 the second argument will be displayed, otherwise, the third argument will be
8955 displayed
8956
8957 For example, if you pass a falsey `useLongGreeting` to the `Greeting` component:
8958
8959 ```app/templates/application.hbs
8960 <Greeting @useLongGreeting={{false}} />
8961 ```
8962
8963 ```app/components/greeting.hbs
8964 {{unless @useLongGreeting "Hi" "Hello"}} Ben
8965 ```
8966
8967 Then it will display:
8968
8969 ```html
8970 Hi Ben
8971 ```
8972
8973 ## Block form
8974
8975 Like the `if` helper, the `unless` helper also has a block form.
8976
8977 The following will not render anything:
8978
8979 ```app/templates/application.hbs
8980 <Greeting />
8981 ```
8982
8983 ```app/components/greeting.hbs
8984 {{#unless @greeting}}
8985 No greeting was found. Why not set one?
8986 {{/unless}}
8987 ```
8988
8989 You can also use an `else` helper with the `unless` block. The
8990 `else` will display if the value is truthy.
8991
8992 If you have the following component:
8993
8994 ```app/components/logged-in.hbs
8995 {{#unless @userData}}
8996 Please login.
8997 {{else}}
8998 Welcome back!
8999 {{/unless}}
9000 ```
9001
9002 Calling it with a truthy `userData`:
9003
9004 ```app/templates/application.hbs
9005 <LoggedIn @userData={{hash username="Zoey"}} />
9006 ```
9007
9008 Will render:
9009
9010 ```html
9011 Welcome back!
9012 ```
9013
9014 and calling it with a falsey `userData`:
9015
9016 ```app/templates/application.hbs
9017 <LoggedIn @userData={{false}} />
9018 ```
9019
9020 Will render:
9021
9022 ```html
9023 Please login.
9024 ```
9025
9026 @method unless
9027 @for Ember.Templates.helpers
9028 @public
9029 */
9030
9031
9032 function inlineUnless(args, vm) {
9033 return new _reference.HelperRootReference(unless, args.capture(), vm.env);
9034 }
9035 /**
9036 @module ember
9037 */
9038
9039 /**
9040 `log` allows you to output the value of variables in the current rendering
9041 context. `log` also accepts primitive types such as strings or numbers.
9042
9043 ```handlebars
9044 {{log "myVariable:" myVariable }}
9045 ```
9046
9047 @method log
9048 @for Ember.Templates.helpers
9049 @param {Array} params
9050 @public
9051 */
9052
9053
9054 function log({
9055 positional
9056 }) {
9057 /* eslint-disable no-console */
9058 console.log(...positional.value());
9059 /* eslint-enable no-console */
9060 }
9061
9062 function log$1(args, vm) {
9063 return new _reference.HelperRootReference(log, args.capture(), vm.env);
9064 }
9065 /**
9066 @module ember
9067 */
9068
9069 /**
9070 This is a helper to be used in conjunction with the link-to helper.
9071 It will supply url query parameters to the target route.
9072
9073 @example In this example we are setting the `direction` query param to the value `"asc"`
9074
9075 ```app/templates/application.hbs
9076 <LinkTo
9077 @route="posts"
9078 {{query-params direction="asc"}}
9079 >
9080 Sort
9081 </LinkTo>
9082 ```
9083
9084 @method query-params
9085 @for Ember.Templates.helpers
9086 @param {Object} hash takes a hash of query parameters
9087 @return {Object} A `QueryParams` object for `{{link-to}}`
9088 @public
9089 */
9090
9091
9092 function queryParams({
9093 positional,
9094 named
9095 }) {
9096 // tslint:disable-next-line:max-line-length
9097 (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));
9098 return new _routing.QueryParams((0, _polyfills.assign)({}, named.value()));
9099 }
9100
9101 function queryParams$1(args, vm) {
9102 return new _reference.HelperRootReference(queryParams, args.capture(), vm.env);
9103 }
9104 /**
9105 The `readonly` helper let's you specify that a binding is one-way only,
9106 instead of two-way.
9107 When you pass a `readonly` binding from an outer context (e.g. parent component),
9108 to to an inner context (e.g. child component), you are saying that changing that
9109 property in the inner context does not change the value in the outer context.
9110
9111 To specify that a binding is read-only, when invoking the child `Component`:
9112
9113 ```app/components/my-parent.js
9114 export default Component.extend({
9115 totalClicks: 3
9116 });
9117 ```
9118
9119 ```app/templates/components/my-parent.hbs
9120 {{log totalClicks}} // -> 3
9121 <MyChild @childClickCount={{readonly totalClicks}} />
9122 ```
9123 ```
9124 {{my-child childClickCount=(readonly totalClicks)}}
9125 ```
9126
9127 Now, when you update `childClickCount`:
9128
9129 ```app/components/my-child.js
9130 export default Component.extend({
9131 click() {
9132 this.incrementProperty('childClickCount');
9133 }
9134 });
9135 ```
9136
9137 The value updates in the child component, but not the parent component:
9138
9139 ```app/templates/components/my-child.hbs
9140 {{log childClickCount}} //-> 4
9141 ```
9142
9143 ```app/templates/components/my-parent.hbs
9144 {{log totalClicks}} //-> 3
9145 <MyChild @childClickCount={{readonly totalClicks}} />
9146 ```
9147 or
9148 ```app/templates/components/my-parent.hbs
9149 {{log totalClicks}} //-> 3
9150 {{my-child childClickCount=(readonly totalClicks)}}
9151 ```
9152
9153 ### Objects and Arrays
9154
9155 When passing a property that is a complex object (e.g. object, array) instead of a primitive object (e.g. number, string),
9156 only the reference to the object is protected using the readonly helper.
9157 This means that you can change properties of the object both on the parent component, as well as the child component.
9158 The `readonly` binding behaves similar to the `const` keyword in JavaScript.
9159
9160 Let's look at an example:
9161
9162 First let's set up the parent component:
9163
9164 ```app/components/my-parent.js
9165 import Component from '@ember/component';
9166
9167 export default Component.extend({
9168 clicks: null,
9169
9170 init() {
9171 this._super(...arguments);
9172 this.set('clicks', { total: 3 });
9173 }
9174 });
9175 ```
9176
9177 ```app/templates/components/my-parent.hbs
9178 {{log clicks.total}} //-> 3
9179 <MyChild @childClicks={{readonly clicks}} />
9180 ```
9181 ```app/templates/components/my-parent.hbs
9182 {{log clicks.total}} //-> 3
9183 {{my-child childClicks=(readonly clicks)}}
9184 ```
9185
9186 Now, if you update the `total` property of `childClicks`:
9187
9188 ```app/components/my-child.js
9189 import Component from '@ember/component';
9190
9191 export default Component.extend({
9192 click() {
9193 this.get('clicks').incrementProperty('total');
9194 }
9195 });
9196 ```
9197
9198 You will see the following happen:
9199
9200 ```app/templates/components/my-parent.hbs
9201 {{log clicks.total}} //-> 4
9202 <MyChild @childClicks={{readonly clicks}} />
9203 ```
9204 or
9205 ```app/templates/components/my-parent.hbs
9206 {{log clicks.total}} //-> 4
9207 {{my-child childClicks=(readonly clicks)}}
9208 ```
9209
9210 ```app/templates/components/my-child.hbs
9211 {{log childClicks.total}} //-> 4
9212 ```
9213
9214 @method readonly
9215 @param {Object} [attr] the read-only attribute.
9216 @for Ember.Templates.helpers
9217 @private
9218 */
9219
9220
9221 class ReadonlyReference extends _reference.RootReference {
9222 constructor(inner, env) {
9223 super(env);
9224 this.inner = inner;
9225 this.tag = inner.tag;
9226 }
9227
9228 get [INVOKE]() {
9229 return this.inner[INVOKE];
9230 }
9231
9232 value() {
9233 return this.inner.value();
9234 }
9235
9236 get(key) {
9237 return this.inner.get(key);
9238 }
9239
9240 }
9241
9242 function readonly(args, vm) {
9243 var ref = unMut(args.positional.at(0));
9244 return new ReadonlyReference(ref, vm.env);
9245 }
9246 /**
9247 @module ember
9248 */
9249
9250 /**
9251 The `{{unbound}}` helper disconnects the one-way binding of a property,
9252 essentially freezing its value at the moment of rendering. For example,
9253 in this example the display of the variable `name` will not change even
9254 if it is set with a new value:
9255
9256 ```handlebars
9257 {{unbound this.name}}
9258 ```
9259
9260 Like any helper, the `unbound` helper can accept a nested helper expression.
9261 This allows for custom helpers to be rendered unbound:
9262
9263 ```handlebars
9264 {{unbound (some-custom-helper)}}
9265 {{unbound (capitalize this.name)}}
9266 {{! You can use any helper, including unbound, in a nested expression }}
9267 {{capitalize (unbound this.name)}}
9268 ```
9269
9270 The `unbound` helper only accepts a single argument, and it return an
9271 unbound value.
9272
9273 @method unbound
9274 @for Ember.Templates.helpers
9275 @public
9276 */
9277
9278
9279 function unbound(args, vm) {
9280 (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));
9281 return new UnboundRootReference(args.positional.at(0).value(), vm.env);
9282 }
9283
9284 var MODIFIERS = ['alt', 'shift', 'meta', 'ctrl'];
9285 var POINTER_EVENT_TYPE_REGEX = /^click|mouse|touch/;
9286
9287 function isAllowedEvent(event, allowedKeys) {
9288 if (allowedKeys === null || allowedKeys === undefined) {
9289 if (POINTER_EVENT_TYPE_REGEX.test(event.type)) {
9290 return (0, _views.isSimpleClick)(event);
9291 } else {
9292 allowedKeys = '';
9293 }
9294 }
9295
9296 if (allowedKeys.indexOf('any') >= 0) {
9297 return true;
9298 }
9299
9300 for (var i = 0; i < MODIFIERS.length; i++) {
9301 if (event[MODIFIERS[i] + 'Key'] && allowedKeys.indexOf(MODIFIERS[i]) === -1) {
9302 return false;
9303 }
9304 }
9305
9306 return true;
9307 }
9308
9309 var ActionHelper = {
9310 // registeredActions is re-exported for compatibility with older plugins
9311 // that were using this undocumented API.
9312 registeredActions: _views.ActionManager.registeredActions,
9313
9314 registerAction(actionState) {
9315 var {
9316 actionId
9317 } = actionState;
9318 _views.ActionManager.registeredActions[actionId] = actionState;
9319 return actionId;
9320 },
9321
9322 unregisterAction(actionState) {
9323 var {
9324 actionId
9325 } = actionState;
9326 delete _views.ActionManager.registeredActions[actionId];
9327 }
9328
9329 };
9330
9331 class ActionState {
9332 constructor(element, actionId, actionName, actionArgs, namedArgs, positionalArgs, implicitTarget, dom, tag) {
9333 this.element = element;
9334 this.actionId = actionId;
9335 this.actionName = actionName;
9336 this.actionArgs = actionArgs;
9337 this.namedArgs = namedArgs;
9338 this.positional = positionalArgs;
9339 this.implicitTarget = implicitTarget;
9340 this.dom = dom;
9341 this.eventName = this.getEventName();
9342 this.tag = tag;
9343 (0, _runtime2.registerDestructor)(this, () => ActionHelper.unregisterAction(this));
9344 }
9345
9346 getEventName() {
9347 return this.namedArgs.get('on').value() || 'click';
9348 }
9349
9350 getActionArgs() {
9351 var result = new Array(this.actionArgs.length);
9352
9353 for (var i = 0; i < this.actionArgs.length; i++) {
9354 result[i] = this.actionArgs[i].value();
9355 }
9356
9357 return result;
9358 }
9359
9360 getTarget() {
9361 var {
9362 implicitTarget,
9363 namedArgs
9364 } = this;
9365 var target;
9366
9367 if (namedArgs.has('target')) {
9368 target = namedArgs.get('target').value();
9369 } else {
9370 target = implicitTarget.value();
9371 }
9372
9373 return target;
9374 }
9375
9376 handler(event) {
9377 var {
9378 actionName,
9379 namedArgs
9380 } = this;
9381 var bubbles = namedArgs.get('bubbles');
9382 var preventDefault = namedArgs.get('preventDefault');
9383 var allowedKeys = namedArgs.get('allowedKeys');
9384 var target = this.getTarget();
9385 var shouldBubble = bubbles.value() !== false;
9386
9387 if (!isAllowedEvent(event, allowedKeys.value())) {
9388 return true;
9389 }
9390
9391 if (preventDefault.value() !== false) {
9392 event.preventDefault();
9393 }
9394
9395 if (!shouldBubble) {
9396 event.stopPropagation();
9397 }
9398
9399 (0, _runloop.join)(() => {
9400 var args = this.getActionArgs();
9401 var payload = {
9402 args,
9403 target,
9404 name: null
9405 };
9406
9407 if (typeof actionName[INVOKE] === 'function') {
9408 (0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => {
9409 actionName[INVOKE].apply(actionName, args);
9410 });
9411 return;
9412 }
9413
9414 if (typeof actionName === 'function') {
9415 (0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => {
9416 actionName.apply(target, args);
9417 });
9418 return;
9419 }
9420
9421 payload.name = actionName;
9422
9423 if (target.send) {
9424 (0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => {
9425 target.send.apply(target, [actionName, ...args]);
9426 });
9427 } else {
9428 (true && !(typeof target[actionName] === 'function') && (0, _debug.assert)(`The action '${actionName}' did not exist on ${target}`, typeof target[actionName] === 'function'));
9429 (0, _instrumentation.flaggedInstrument)('interaction.ember-action', payload, () => {
9430 target[actionName].apply(target, args);
9431 });
9432 }
9433 });
9434 return shouldBubble;
9435 }
9436
9437 } // implements ModifierManager<Action>
9438
9439
9440 class ActionModifierManager {
9441 create(element, _state, args, _dynamicScope, dom) {
9442 var {
9443 named,
9444 positional,
9445 tag
9446 } = args.capture();
9447 var implicitTarget;
9448 var actionName;
9449 var actionNameRef;
9450
9451 if (positional.length > 1) {
9452 implicitTarget = positional.at(0);
9453 actionNameRef = positional.at(1);
9454
9455 if (actionNameRef[INVOKE]) {
9456 actionName = actionNameRef;
9457 } else {
9458 var actionLabel = actionNameRef.propertyKey;
9459 actionName = actionNameRef.value();
9460 (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'));
9461 }
9462 }
9463
9464 var actionArgs = []; // The first two arguments are (1) `this` and (2) the action name.
9465 // Everything else is a param.
9466
9467 for (var i = 2; i < positional.length; i++) {
9468 actionArgs.push(positional.at(i));
9469 }
9470
9471 var actionId = (0, _utils.uuid)();
9472 var actionState = new ActionState(element, actionId, actionName, actionArgs, named, positional, implicitTarget, dom, tag);
9473 (true && !(actionState.eventName !== 'mouseEnter' && actionState.eventName !== 'mouseLeave' && actionState.eventName !== 'mouseMove') && (0, _debug.deprecate)(`Using the \`{{action}}\` modifier with \`${actionState.eventName}\` events has been deprecated.`, actionState.eventName !== 'mouseEnter' && actionState.eventName !== 'mouseLeave' && actionState.eventName !== 'mouseMove', {
9474 id: 'ember-views.event-dispatcher.mouseenter-leave-move',
9475 until: '4.0.0',
9476 url: 'https://emberjs.com/deprecations/v3.x#toc_action-mouseenter-leave-move'
9477 }));
9478 return actionState;
9479 }
9480
9481 install(actionState) {
9482 var {
9483 dom,
9484 element,
9485 actionId
9486 } = actionState;
9487 ActionHelper.registerAction(actionState);
9488 dom.setAttribute(element, 'data-ember-action', '');
9489 dom.setAttribute(element, `data-ember-action-${actionId}`, actionId);
9490 }
9491
9492 update(actionState) {
9493 var {
9494 positional
9495 } = actionState;
9496 var actionNameRef = positional.at(1);
9497
9498 if (!actionNameRef[INVOKE]) {
9499 actionState.actionName = actionNameRef.value();
9500 }
9501
9502 actionState.eventName = actionState.getEventName();
9503 }
9504
9505 getTag(actionState) {
9506 return actionState.tag;
9507 }
9508
9509 getDestroyable(actionState) {
9510 return actionState;
9511 }
9512
9513 }
9514
9515 var debugRenderMessage;
9516
9517 if (true
9518 /* DEBUG */
9519 ) {
9520 debugRenderMessage = renderingStack => {
9521 return `While rendering:\n----------------\n${renderingStack.replace(/^/gm, ' ')}`;
9522 };
9523 }
9524
9525 var debugRenderMessage$1 = debugRenderMessage;
9526
9527 function capabilities$1(managerAPI, optionalFeatures = {}) {
9528 (true && !(managerAPI === '3.13') && (0, _debug.assert)('Invalid modifier manager compatibility specified', managerAPI === '3.13'));
9529 return {
9530 disableAutoTracking: Boolean(optionalFeatures.disableAutoTracking)
9531 };
9532 }
9533
9534 class CustomModifierDefinition {
9535 constructor(name, ModifierClass, delegate, isInteractive) {
9536 this.name = name;
9537 this.ModifierClass = ModifierClass;
9538 this.delegate = delegate;
9539 this.state = {
9540 ModifierClass,
9541 name,
9542 delegate
9543 };
9544 this.manager = isInteractive ? CUSTOM_INTERACTIVE_MODIFIER_MANAGER : CUSTOM_NON_INTERACTIVE_MODIFIER_MANAGER;
9545 }
9546
9547 }
9548
9549 class CustomModifierState {
9550 constructor(element, delegate, modifier, args) {
9551 this.element = element;
9552 this.delegate = delegate;
9553 this.modifier = modifier;
9554 this.args = args;
9555 this.tag = (0, _validator.createUpdatableTag)();
9556 (0, _runtime2.registerDestructor)(this, () => delegate.destroyModifier(modifier, args.value()));
9557 }
9558
9559 }
9560 /**
9561 The CustomModifierManager allows addons to provide custom modifier
9562 implementations that integrate seamlessly into Ember. This is accomplished
9563 through a delegate, registered with the custom modifier manager, which
9564 implements a set of hooks that determine modifier behavior.
9565 To create a custom modifier manager, instantiate a new CustomModifierManager
9566 class and pass the delegate as the first argument:
9567
9568 ```js
9569 let manager = new CustomModifierManager({
9570 // ...delegate implementation...
9571 });
9572 ```
9573
9574 ## Delegate Hooks
9575
9576 Throughout the lifecycle of a modifier, the modifier manager will invoke
9577 delegate hooks that are responsible for surfacing those lifecycle changes to
9578 the end developer.
9579 * `createModifier()` - invoked when a new instance of a modifier should be created
9580 * `installModifier()` - invoked when the modifier is installed on the element
9581 * `updateModifier()` - invoked when the arguments passed to a modifier change
9582 * `destroyModifier()` - invoked when the modifier is about to be destroyed
9583 */
9584
9585
9586 class InteractiveCustomModifierManager {
9587 create(element, definition, args) {
9588 var {
9589 delegate,
9590 ModifierClass
9591 } = definition;
9592 var capturedArgs = args.capture();
9593 var instance = definition.delegate.createModifier(ModifierClass, capturedArgs.value());
9594 return new CustomModifierState(element, delegate, instance, capturedArgs);
9595 }
9596
9597 getTag({
9598 args,
9599 tag
9600 }) {
9601 return (0, _validator.combine)([tag, args.tag]);
9602 }
9603
9604 install(state) {
9605 var {
9606 element,
9607 args,
9608 delegate,
9609 modifier,
9610 tag
9611 } = state;
9612 (true && !(typeof delegate.capabilities === 'object' && delegate.capabilities !== null) && (0, _debug.assert)('Custom modifier managers must define their capabilities using the capabilities() helper function', typeof delegate.capabilities === 'object' && delegate.capabilities !== null));
9613 var {
9614 capabilities
9615 } = delegate;
9616
9617 if (capabilities.disableAutoTracking === true) {
9618 (0, _validator.untrack)(() => delegate.installModifier(modifier, element, args.value()));
9619 } else {
9620 var combinedTrackingTag = (0, _validator.track)(() => delegate.installModifier(modifier, element, args.value()), true
9621 /* DEBUG */
9622 && debugRenderMessage$1(`(instance of a \`${(0, _utils.getDebugName)(modifier)}\` modifier)`));
9623 (0, _validator.updateTag)(tag, combinedTrackingTag);
9624 }
9625 }
9626
9627 update(state) {
9628 var {
9629 args,
9630 delegate,
9631 modifier,
9632 tag
9633 } = state;
9634 var {
9635 capabilities
9636 } = delegate;
9637
9638 if (capabilities.disableAutoTracking === true) {
9639 (0, _validator.untrack)(() => delegate.updateModifier(modifier, args.value()));
9640 } else {
9641 var combinedTrackingTag = (0, _validator.track)(() => delegate.updateModifier(modifier, args.value()), true
9642 /* DEBUG */
9643 && debugRenderMessage$1(`(instance of a \`${(0, _utils.getDebugName)(modifier)}\` modifier)`));
9644 (0, _validator.updateTag)(tag, combinedTrackingTag);
9645 }
9646 }
9647
9648 getDestroyable(state) {
9649 return state;
9650 }
9651
9652 }
9653
9654 class NonInteractiveCustomModifierManager {
9655 create() {
9656 return null;
9657 }
9658
9659 getTag() {
9660 return _validator.CONSTANT_TAG;
9661 }
9662
9663 install() {}
9664
9665 update() {}
9666
9667 getDestroyable() {
9668 return null;
9669 }
9670
9671 }
9672
9673 var CUSTOM_INTERACTIVE_MODIFIER_MANAGER = new InteractiveCustomModifierManager();
9674 var CUSTOM_NON_INTERACTIVE_MODIFIER_MANAGER = new NonInteractiveCustomModifierManager();
9675 var untouchableContext = buildUntouchableThis('`on` modifier');
9676 /**
9677 @module ember
9678 */
9679
9680 /*
9681 Internet Explorer 11 does not support `once` and also does not support
9682 passing `eventOptions`. In some situations it then throws a weird script
9683 error, like:
9684
9685 ```
9686 Could not complete the operation due to error 80020101
9687 ```
9688
9689 This flag determines, whether `{ once: true }` and thus also event options in
9690 general are supported.
9691 */
9692
9693 var SUPPORTS_EVENT_OPTIONS = (() => {
9694 try {
9695 var div = document.createElement('div');
9696 var counter = 0;
9697 div.addEventListener('click', () => counter++, {
9698 once: true
9699 });
9700 var event;
9701
9702 if (typeof Event === 'function') {
9703 event = new Event('click');
9704 } else {
9705 event = document.createEvent('Event');
9706 event.initEvent('click', true, true);
9707 }
9708
9709 div.dispatchEvent(event);
9710 div.dispatchEvent(event);
9711 return counter === 1;
9712 } catch (error) {
9713 return false;
9714 }
9715 })();
9716
9717 class OnModifierState {
9718 constructor(owner, element, args) {
9719 this.shouldUpdate = true;
9720 this.owner = owner;
9721 this.element = element;
9722 this.args = args;
9723 this.tag = args.tag;
9724 }
9725
9726 updateFromArgs() {
9727 var {
9728 args
9729 } = this;
9730 var {
9731 once,
9732 passive,
9733 capture
9734 } = args.named.value();
9735
9736 if (once !== this.once) {
9737 this.once = once;
9738 this.shouldUpdate = true;
9739 }
9740
9741 if (passive !== this.passive) {
9742 this.passive = passive;
9743 this.shouldUpdate = true;
9744 }
9745
9746 if (capture !== this.capture) {
9747 this.capture = capture;
9748 this.shouldUpdate = true;
9749 }
9750
9751 var options;
9752
9753 if (once || passive || capture) {
9754 options = this.options = {
9755 once,
9756 passive,
9757 capture
9758 };
9759 } else {
9760 this.options = undefined;
9761 }
9762
9763 (true && !(args.positional.at(0) !== undefined && typeof args.positional.at(0).value() === 'string') && (0, _debug.assert)('You must pass a valid DOM event name as the first argument to the `on` modifier', args.positional.at(0) !== undefined && typeof args.positional.at(0).value() === 'string'));
9764 var eventName = args.positional.at(0).value();
9765
9766 if (eventName !== this.eventName) {
9767 this.eventName = eventName;
9768 this.shouldUpdate = true;
9769 }
9770
9771 var userProvidedCallbackReference = args.positional.at(1);
9772
9773 if (true
9774 /* DEBUG */
9775 ) {
9776 (true && !(args.positional.at(1) !== undefined) && (0, _debug.assert)(`You must pass a function as the second argument to the \`on\` modifier.`, args.positional.at(1) !== undefined)); // hardcoding `renderer:-dom` here because we guard for `this.isInteractive` before instantiating OnModifierState, it can never be created when the renderer is `renderer:-inert`
9777
9778 var renderer = (0, _util.expect)(this.owner.lookup('renderer:-dom'), `BUG: owner is missing renderer:-dom`);
9779 var stack = renderer.debugRenderTree.logRenderStackForPath(userProvidedCallbackReference);
9780 var value = userProvidedCallbackReference.value();
9781 (true && !(typeof value === 'function') && (0, _debug.assert)(`You must pass a function as the second argument to the \`on\` modifier, you passed ${value === null ? 'null' : typeof value}. While rendering:\n\n${stack}`, typeof value === 'function'));
9782 }
9783
9784 var userProvidedCallback = userProvidedCallbackReference.value();
9785
9786 if (userProvidedCallback !== this.userProvidedCallback) {
9787 this.userProvidedCallback = userProvidedCallback;
9788 this.shouldUpdate = true;
9789 }
9790
9791 (true && !(args.positional.length === 2) && (0, _debug.assert)(`You can only pass two positional arguments (event name and callback) to the \`on\` modifier, but you provided ${args.positional.length}. Consider using the \`fn\` helper to provide additional arguments to the \`on\` callback.`, args.positional.length === 2));
9792 var needsCustomCallback = SUPPORTS_EVENT_OPTIONS === false && once ||
9793 /* needs manual once implementation */
9794 true
9795 /* DEBUG */
9796 && passive
9797 /* needs passive enforcement */
9798 ;
9799
9800 if (this.shouldUpdate) {
9801 if (needsCustomCallback) {
9802 var callback = this.callback = function (event) {
9803 if (true
9804 /* DEBUG */
9805 && passive) {
9806 event.preventDefault = () => {
9807 (true && !(false) && (0, _debug.assert)(`You marked this listener as 'passive', meaning that you must not call 'event.preventDefault()': \n\n${userProvidedCallback}`));
9808 };
9809 }
9810
9811 if (!SUPPORTS_EVENT_OPTIONS && once) {
9812 removeEventListener(this, eventName, callback, options);
9813 }
9814
9815 return userProvidedCallback.call(untouchableContext, event);
9816 };
9817 } else if (true
9818 /* DEBUG */
9819 ) {
9820 // prevent the callback from being bound to the element
9821 this.callback = userProvidedCallback.bind(untouchableContext);
9822 } else {
9823 this.callback = userProvidedCallback;
9824 }
9825 }
9826 }
9827
9828 }
9829
9830 var adds = 0;
9831 var removes = 0;
9832
9833 function removeEventListener(element, eventName, callback, options) {
9834 removes++;
9835
9836 if (SUPPORTS_EVENT_OPTIONS) {
9837 // when options are supported, use them across the board
9838 element.removeEventListener(eventName, callback, options);
9839 } else if (options !== undefined && options.capture) {
9840 // used only in the following case:
9841 //
9842 // `{ once: true | false, passive: true | false, capture: true }
9843 //
9844 // `once` is handled via a custom callback that removes after first
9845 // invocation so we only care about capture here as a boolean
9846 element.removeEventListener(eventName, callback, true);
9847 } else {
9848 // used only in the following cases:
9849 //
9850 // * where there is no options
9851 // * `{ once: true | false, passive: true | false, capture: false }
9852 element.removeEventListener(eventName, callback);
9853 }
9854 }
9855
9856 function addEventListener(element, eventName, callback, options) {
9857 adds++;
9858
9859 if (SUPPORTS_EVENT_OPTIONS) {
9860 // when options are supported, use them across the board
9861 element.addEventListener(eventName, callback, options);
9862 } else if (options !== undefined && options.capture) {
9863 // used only in the following case:
9864 //
9865 // `{ once: true | false, passive: true | false, capture: true }
9866 //
9867 // `once` is handled via a custom callback that removes after first
9868 // invocation so we only care about capture here as a boolean
9869 element.addEventListener(eventName, callback, true);
9870 } else {
9871 // used only in the following cases:
9872 //
9873 // * where there is no options
9874 // * `{ once: true | false, passive: true | false, capture: false }
9875 element.addEventListener(eventName, callback);
9876 }
9877 }
9878 /**
9879 The `{{on}}` modifier lets you easily add event listeners (it uses
9880 [EventTarget.addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
9881 internally).
9882
9883 For example, if you'd like to run a function on your component when a `<button>`
9884 in the components template is clicked you might do something like:
9885
9886 ```app/components/like-post.hbs
9887 <button {{on 'click' this.saveLike}}>Like this post!</button>
9888 ```
9889
9890 ```app/components/like-post.js
9891 import Component from '@glimmer/component';
9892 import { action } from '@ember/object';
9893
9894 export default class LikePostComponent extends Component {
9895 @action
9896 saveLike() {
9897 // someone likes your post!
9898 // better send a request off to your server...
9899 }
9900 }
9901 ```
9902
9903 ### Arguments
9904
9905 `{{on}}` accepts two positional arguments, and a few named arguments.
9906
9907 The positional arguments are:
9908
9909 - `event` -- the name to use when calling `addEventListener`
9910 - `callback` -- the function to be passed to `addEventListener`
9911
9912 The named arguments are:
9913
9914 - capture -- a `true` value indicates that events of this type will be dispatched
9915 to the registered listener before being dispatched to any EventTarget beneath it
9916 in the DOM tree.
9917 - once -- indicates that the listener should be invoked at most once after being
9918 added. If true, the listener would be automatically removed when invoked.
9919 - passive -- if `true`, indicates that the function specified by listener will never
9920 call preventDefault(). If a passive listener does call preventDefault(), the user
9921 agent will do nothing other than generate a console warning. See
9922 [Improving scrolling performance with passive listeners](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Improving_scrolling_performance_with_passive_listeners)
9923 to learn more.
9924
9925 The callback function passed to `{{on}}` will receive any arguments that are passed
9926 to the event handler. Most commonly this would be the `event` itself.
9927
9928 If you would like to pass additional arguments to the function you should use
9929 the `{{fn}}` helper.
9930
9931 For example, in our example case above if you'd like to pass in the post that
9932 was being liked when the button is clicked you could do something like:
9933
9934 ```app/components/like-post.hbs
9935 <button {{on 'click' (fn this.saveLike @post)}}>Like this post!</button>
9936 ```
9937
9938 In this case, the `saveLike` function will receive two arguments: the value
9939 of `@post` and the click event. The click event will always be the last
9940 argument passed to the handler because `{{fn}}` injects custom arguments
9941 first.
9942
9943 ### Function Context
9944
9945 In the example above, we used `@action` to ensure that `likePost` is
9946 properly bound to the `items-list`, but let's explore what happens if we
9947 left out `@action`:
9948
9949 ```app/components/like-post.js
9950 import Component from '@glimmer/component';
9951
9952 export default class LikePostComponent extends Component {
9953 saveLike() {
9954 // ...snip...
9955 }
9956 }
9957 ```
9958
9959 In this example, when the button is clicked `saveLike` will be invoked,
9960 it will **not** have access to the component instance. In other
9961 words, it will have no `this` context, so please make sure your functions
9962 are bound (via `@action` or other means) before passing into `on`!
9963
9964 @method on
9965 @for Ember.Templates.helpers
9966 @public
9967 @since 3.11.0
9968 */
9969
9970
9971 class OnModifierManager {
9972 constructor(owner, isInteractive) {
9973 this.SUPPORTS_EVENT_OPTIONS = SUPPORTS_EVENT_OPTIONS;
9974 this.isInteractive = isInteractive;
9975 this.owner = owner;
9976 }
9977
9978 get counters() {
9979 return {
9980 adds,
9981 removes
9982 };
9983 }
9984
9985 create(element, _state, args) {
9986 if (!this.isInteractive) {
9987 return null;
9988 }
9989
9990 var capturedArgs = args.capture();
9991 return new OnModifierState(this.owner, element, capturedArgs);
9992 }
9993
9994 getTag(state) {
9995 if (state === null) {
9996 return _validator.CONSTANT_TAG;
9997 }
9998
9999 return state.tag;
10000 }
10001
10002 install(state) {
10003 if (state === null) {
10004 return;
10005 }
10006
10007 state.updateFromArgs();
10008 var {
10009 element,
10010 eventName,
10011 callback,
10012 options
10013 } = state;
10014 addEventListener(element, eventName, callback, options);
10015 (0, _runtime2.registerDestructor)(state, () => removeEventListener(element, eventName, callback, options));
10016 state.shouldUpdate = false;
10017 }
10018
10019 update(state) {
10020 if (state === null) {
10021 return;
10022 } // stash prior state for el.removeEventListener
10023
10024
10025 var {
10026 element,
10027 eventName,
10028 callback,
10029 options
10030 } = state;
10031 state.updateFromArgs();
10032
10033 if (!state.shouldUpdate) {
10034 return;
10035 } // use prior state values for removal
10036
10037
10038 removeEventListener(element, eventName, callback, options); // read updated values from the state object
10039
10040 addEventListener(state.element, state.eventName, state.callback, state.options);
10041 state.shouldUpdate = false;
10042 }
10043
10044 getDestroyable(state) {
10045 return state;
10046 }
10047
10048 }
10049
10050 var CAPABILITIES$3 = {
10051 dynamicLayout: true,
10052 dynamicTag: false,
10053 prepareArgs: false,
10054 createArgs: true,
10055 attributeHook: false,
10056 elementHook: false,
10057 createCaller: true,
10058 dynamicScope: true,
10059 updateHook: true,
10060 createInstance: true,
10061 wrapped: false,
10062 willDestroy: false
10063 }; // TODO
10064 // This "disables" the "@model" feature by making the arg untypable syntatically
10065 // Delete this when EMBER_ROUTING_MODEL_ARG has shipped
10066
10067 var MODEL_ARG_NAME = 'model';
10068
10069 class MountManager extends AbstractManager {
10070 getJitDynamicLayout(state, _) {
10071 var templateFactory$$1 = state.engine.lookup('template:application');
10072 var template = templateFactory$$1(state.engine);
10073
10074 if (_environment2.ENV._DEBUG_RENDER_TREE) {
10075 state.environment.extra.debugRenderTree.setTemplate(state.controller, template);
10076 }
10077
10078 return template;
10079 }
10080
10081 getCapabilities() {
10082 return CAPABILITIES$3;
10083 }
10084
10085 create(environment, {
10086 name
10087 }, args) {
10088 // TODO
10089 // mount is a runtime helper, this shouldn't use dynamic layout
10090 // we should resolve the engine app template in the helper
10091 // it also should use the owner that looked up the mount helper.
10092 var engine = environment.extra.owner.buildChildEngineInstance(name);
10093 engine.boot();
10094 var applicationFactory = engine.factoryFor(`controller:application`);
10095 var controllerFactory = applicationFactory || (0, _routing.generateControllerFactory)(engine, 'application');
10096 var controller;
10097 var self;
10098 var bucket;
10099 var modelRef;
10100
10101 if (args.named.has(MODEL_ARG_NAME)) {
10102 modelRef = args.named.get(MODEL_ARG_NAME);
10103 }
10104
10105 if (modelRef === undefined) {
10106 controller = controllerFactory.create();
10107 self = new _reference.ComponentRootReference(controller, environment);
10108 bucket = {
10109 engine,
10110 controller,
10111 self,
10112 environment
10113 };
10114 } else {
10115 var model = modelRef.value();
10116 controller = controllerFactory.create({
10117 model
10118 });
10119 self = new _reference.ComponentRootReference(controller, environment);
10120 bucket = {
10121 engine,
10122 controller,
10123 self,
10124 modelRef,
10125 environment
10126 };
10127 }
10128
10129 if (_environment2.ENV._DEBUG_RENDER_TREE) {
10130 environment.extra.debugRenderTree.create(bucket, {
10131 type: 'engine',
10132 name,
10133 args: args.capture(),
10134 instance: engine,
10135 template: undefined
10136 });
10137 environment.extra.debugRenderTree.create(controller, {
10138 type: 'route-template',
10139 name: 'application',
10140 args: args.capture(),
10141 instance: controller,
10142 // set in getDynamicLayout
10143 template: undefined
10144 });
10145 (0, _runtime2.registerDestructor)(engine, () => {
10146 environment.extra.debugRenderTree.willDestroy(controller);
10147 environment.extra.debugRenderTree.willDestroy(bucket);
10148 });
10149 }
10150
10151 return bucket;
10152 }
10153
10154 getSelf({
10155 self
10156 }) {
10157 return self;
10158 }
10159
10160 getTag(state) {
10161 var tag = _validator.CONSTANT_TAG;
10162
10163 if (state.modelRef) {
10164 tag = state.modelRef.tag;
10165 }
10166
10167 if (_environment2.ENV._DEBUG_RENDER_TREE && (0, _validator.isConstTag)(tag)) {
10168 tag = (0, _validator.createTag)();
10169 }
10170
10171 return tag;
10172 }
10173
10174 getDestroyable(bucket) {
10175 return bucket.engine;
10176 }
10177
10178 didRenderLayout(bucket, bounds) {
10179 if (_environment2.ENV._DEBUG_RENDER_TREE) {
10180 bucket.environment.extra.debugRenderTree.didRender(bucket.controller, bounds);
10181 bucket.environment.extra.debugRenderTree.didRender(bucket, bounds);
10182 }
10183 }
10184
10185 update(bucket) {
10186 var {
10187 controller,
10188 environment,
10189 modelRef
10190 } = bucket;
10191
10192 if (modelRef !== undefined) {
10193 controller.set('model', modelRef.value());
10194 }
10195
10196 if (_environment2.ENV._DEBUG_RENDER_TREE) {
10197 environment.extra.debugRenderTree.update(bucket);
10198 environment.extra.debugRenderTree.update(bucket.controller);
10199 }
10200 }
10201
10202 didUpdateLayout(bucket, bounds) {
10203 if (_environment2.ENV._DEBUG_RENDER_TREE) {
10204 bucket.environment.extra.debugRenderTree.didRender(bucket.controller, bounds);
10205 bucket.environment.extra.debugRenderTree.didRender(bucket, bounds);
10206 }
10207 }
10208
10209 }
10210
10211 var MOUNT_MANAGER = new MountManager();
10212
10213 class MountDefinition {
10214 constructor(name) {
10215 this.manager = MOUNT_MANAGER;
10216 this.state = {
10217 name
10218 };
10219 }
10220
10221 }
10222 /**
10223 @module ember
10224 */
10225
10226
10227 function mountHelper(args, vm) {
10228 var env = vm.env;
10229 var nameRef = args.positional.at(0);
10230 var captured = null;
10231 (true && !(args.positional.length === 1) && (0, _debug.assert)('You can only pass a single positional argument to the {{mount}} helper, e.g. {{mount "chat-engine"}}.', args.positional.length === 1));
10232
10233 if (true
10234 /* DEBUG */
10235 && args.named) {
10236 var keys = args.named.names;
10237 var extra = keys.filter(k => k !== 'model');
10238 (true && !(extra.length === 0) && (0, _debug.assert)('You can only pass a `model` argument to the {{mount}} helper, ' + 'e.g. {{mount "profile-engine" model=this.profile}}. ' + `You passed ${extra.join(',')}.`, extra.length === 0));
10239 } // TODO: the functionality to create a proper CapturedArgument should be
10240 // exported by glimmer, or that it should provide an overload for `curry`
10241 // that takes `PreparedArguments`
10242
10243
10244 if (args.named.has('model')) {
10245 (true && !(args.named.length === 1) && (0, _debug.assert)('[BUG] this should already be checked by the macro', args.named.length === 1));
10246 var named = args.named.capture();
10247 var {
10248 tag
10249 } = named; // TODO delete me after EMBER_ROUTING_MODEL_ARG has shipped
10250
10251 if (true
10252 /* DEBUG */
10253 && MODEL_ARG_NAME !== 'model') {
10254 (true && !(named['_map'] === null) && (0, _debug.assert)('[BUG] named._map is not null', named['_map'] === null));
10255 named.names = [MODEL_ARG_NAME];
10256 }
10257
10258 captured = {
10259 tag,
10260 positional: _runtime2.EMPTY_ARGS.positional,
10261 named,
10262 length: 1,
10263
10264 value() {
10265 return {
10266 named: this.named.value(),
10267 positional: this.positional.value()
10268 };
10269 }
10270
10271 };
10272 }
10273
10274 return new DynamicEngineReference(nameRef, env, captured);
10275 }
10276 /**
10277 The `{{mount}}` helper lets you embed a routeless engine in a template.
10278 Mounting an engine will cause an instance to be booted and its `application`
10279 template to be rendered.
10280
10281 For example, the following template mounts the `ember-chat` engine:
10282
10283 ```handlebars
10284 {{! application.hbs }}
10285 {{mount "ember-chat"}}
10286 ```
10287
10288 Additionally, you can also pass in a `model` argument that will be
10289 set as the engines model. This can be an existing object:
10290
10291 ```
10292 <div>
10293 {{mount 'admin' model=userSettings}}
10294 </div>
10295 ```
10296
10297 Or an inline `hash`, and you can even pass components:
10298
10299 ```
10300 <div>
10301 <h1>Application template!</h1>
10302 {{mount 'admin' model=(hash
10303 title='Secret Admin'
10304 signInButton=(component 'sign-in-button')
10305 )}}
10306 </div>
10307 ```
10308
10309 @method mount
10310 @param {String} name Name of the engine to mount.
10311 @param {Object} [model] Object that will be set as
10312 the model of the engine.
10313 @for Ember.Templates.helpers
10314 @public
10315 */
10316
10317
10318 class DynamicEngineReference {
10319 constructor(nameRef, env, args) {
10320 this.nameRef = nameRef;
10321 this.env = env;
10322 this.args = args;
10323 this._lastName = null;
10324 this._lastDef = null;
10325 this.tag = nameRef.tag;
10326 }
10327
10328 value() {
10329 var {
10330 env,
10331 nameRef,
10332 args
10333 } = this;
10334 var name = nameRef.value();
10335
10336 if (typeof name === 'string') {
10337 if (this._lastName === name) {
10338 return this._lastDef;
10339 }
10340
10341 (true && !(env.extra.owner.hasRegistration(`engine:${name}`)) && (0, _debug.assert)(`You used \`{{mount '${name}'}}\`, but the engine '${name}' can not be found.`, env.extra.owner.hasRegistration(`engine:${name}`)));
10342
10343 if (!env.extra.owner.hasRegistration(`engine:${name}`)) {
10344 return null;
10345 }
10346
10347 this._lastName = name;
10348 this._lastDef = (0, _runtime2.curry)(new MountDefinition(name), args);
10349 return this._lastDef;
10350 } else {
10351 (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));
10352 this._lastDef = null;
10353 this._lastName = null;
10354 return null;
10355 }
10356 }
10357
10358 get() {
10359 return _runtime2.UNDEFINED_REFERENCE;
10360 }
10361
10362 }
10363 /**
10364 * Represents the root outlet.
10365 */
10366
10367
10368 class RootOutletReference {
10369 constructor(outletState) {
10370 this.outletState = outletState;
10371 this.tag = (0, _validator.createTag)();
10372 }
10373
10374 get(key) {
10375 return new PathReference(this, key);
10376 }
10377
10378 value() {
10379 return this.outletState;
10380 }
10381
10382 update(state) {
10383 this.outletState.outlets.main = state;
10384 (0, _validator.dirtyTag)(this.tag);
10385 }
10386
10387 }
10388 /**
10389 * Represents the connected outlet.
10390 */
10391
10392
10393 class OutletReference {
10394 constructor(parentStateRef, outletNameRef) {
10395 this.parentStateRef = parentStateRef;
10396 this.outletNameRef = outletNameRef;
10397 this.tag = (0, _validator.combine)([parentStateRef.tag, outletNameRef.tag]);
10398 }
10399
10400 value() {
10401 var outletState = this.parentStateRef.value();
10402 var outlets = outletState === undefined ? undefined : outletState.outlets;
10403 return outlets === undefined ? undefined : outlets[this.outletNameRef.value()];
10404 }
10405
10406 get(key) {
10407 return new PathReference(this, key);
10408 }
10409
10410 }
10411 /**
10412 * Outlet state is dirtied from root.
10413 * This just using the parent tag for dirtiness.
10414 */
10415
10416
10417 class PathReference {
10418 constructor(parent, key) {
10419 this.parent = parent;
10420 this.key = key;
10421 this.tag = parent.tag;
10422 }
10423
10424 get(key) {
10425 return new PathReference(this, key);
10426 }
10427
10428 value() {
10429 var parent = this.parent.value();
10430 return parent && parent[this.key];
10431 }
10432
10433 }
10434 /**
10435 The `{{outlet}}` helper lets you specify where a child route will render in
10436 your template. An important use of the `{{outlet}}` helper is in your
10437 application's `application.hbs` file:
10438
10439 ```app/templates/application.hbs
10440 <MyHeader />
10441
10442 <div class="my-dynamic-content">
10443 <!-- this content will change based on the current route, which depends on the current URL -->
10444 {{outlet}}
10445 </div>
10446
10447 <MyFooter />
10448 ```
10449
10450 You may also specify a name for the `{{outlet}}`, which is useful when using more than one
10451 `{{outlet}}` in a template:
10452
10453 ```app/templates/application.hbs
10454 {{outlet "menu"}}
10455 {{outlet "sidebar"}}
10456 {{outlet "main"}}
10457 ```
10458
10459 Your routes can then render into a specific one of these `outlet`s by specifying the `outlet`
10460 attribute in your `renderTemplate` function:
10461
10462 ```app/routes/menu.js
10463 import Route from '@ember/routing/route';
10464
10465 export default class MenuRoute extends Route {
10466 renderTemplate() {
10467 this.render({ outlet: 'menu' });
10468 }
10469 }
10470 ```
10471
10472 See the [routing guide](https://guides.emberjs.com/release/routing/rendering-a-template/) for more
10473 information on how your `route` interacts with the `{{outlet}}` helper.
10474 Note: Your content __will not render__ if there isn't an `{{outlet}}` for it.
10475
10476 @method outlet
10477 @param {String} [name]
10478 @for Ember.Templates.helpers
10479 @public
10480 */
10481
10482
10483 function outletHelper(args, vm) {
10484 var scope = vm.dynamicScope();
10485 var nameRef;
10486
10487 if (args.positional.length === 0) {
10488 nameRef = new _reference.ConstReference('main');
10489 } else {
10490 nameRef = args.positional.at(0);
10491 }
10492
10493 return new OutletComponentReference(new OutletReference(scope.outletState, nameRef), vm.env);
10494 }
10495
10496 class OutletModelReference extends _reference.RootReference {
10497 constructor(parent, env) {
10498 super(env);
10499 this.parent = parent;
10500 this.tag = parent.tag;
10501 }
10502
10503 value() {
10504 var state = this.parent.value();
10505
10506 if (state === undefined) {
10507 return undefined;
10508 }
10509
10510 var {
10511 render
10512 } = state;
10513
10514 if (render === undefined) {
10515 return undefined;
10516 }
10517
10518 return render.model;
10519 }
10520
10521 }
10522
10523 if (true
10524 /* DEBUG */
10525 ) {
10526 OutletModelReference.prototype['debugLogName'] = '@model';
10527 }
10528
10529 class OutletComponentReference {
10530 constructor(outletRef, env) {
10531 this.outletRef = outletRef;
10532 this.env = env;
10533 this.definition = null;
10534 this.lastState = null; // The router always dirties the root state.
10535
10536 this.tag = outletRef.tag;
10537 }
10538
10539 value() {
10540 var state = stateFor(this.outletRef);
10541
10542 if (validate(state, this.lastState)) {
10543 return this.definition;
10544 }
10545
10546 this.lastState = state;
10547 var definition = null;
10548
10549 if (state !== null) {
10550 var args = makeArgs(this.outletRef, this.env);
10551 definition = (0, _runtime2.curry)(new OutletComponentDefinition(state), args);
10552 }
10553
10554 return this.definition = definition;
10555 }
10556
10557 get(_key) {
10558 return _runtime2.UNDEFINED_REFERENCE;
10559 }
10560
10561 }
10562
10563 function makeArgs(outletRef, env) {
10564 var tag = outletRef.tag;
10565 var modelRef = new OutletModelReference(outletRef, env);
10566 var map = (0, _util.dict)();
10567 map.model = modelRef; // TODO: the functionailty to create a proper CapturedArgument should be
10568 // exported by glimmer, or that it should provide an overload for `curry`
10569 // that takes `PreparedArguments`
10570
10571 return {
10572 tag,
10573 positional: _runtime2.EMPTY_ARGS.positional,
10574 named: {
10575 tag,
10576 map,
10577 names: ['model'],
10578 references: [modelRef],
10579 length: 1,
10580
10581 has(key) {
10582 return key === 'model';
10583 },
10584
10585 get(key) {
10586 return key === 'model' ? modelRef : _runtime2.UNDEFINED_REFERENCE;
10587 },
10588
10589 value() {
10590 var model = modelRef.value();
10591 return {
10592 model
10593 };
10594 }
10595
10596 },
10597 length: 1,
10598
10599 value() {
10600 return {
10601 named: this.named.value(),
10602 positional: this.positional.value()
10603 };
10604 }
10605
10606 };
10607 }
10608
10609 function stateFor(ref) {
10610 var outlet = ref.value();
10611 if (outlet === undefined) return null;
10612 var render = outlet.render;
10613 if (render === undefined) return null;
10614 var template$$1 = render.template;
10615 if (template$$1 === undefined) return null; // this guard can be removed once @ember/test-helpers@1.6.0 has "aged out"
10616 // and is no longer considered supported
10617
10618 if (isTemplateFactory(template$$1)) {
10619 template$$1 = template$$1(render.owner);
10620 }
10621
10622 return {
10623 ref,
10624 name: render.name,
10625 outlet: render.outlet,
10626 template: template$$1,
10627 controller: render.controller,
10628 model: render.model
10629 };
10630 }
10631
10632 function validate(state, lastState) {
10633 if (state === null) {
10634 return lastState === null;
10635 }
10636
10637 if (lastState === null) {
10638 return false;
10639 }
10640
10641 return state.template === lastState.template && state.controller === lastState.controller;
10642 }
10643
10644 var TEMPLATES = new WeakMap();
10645 var getPrototypeOf = Object.getPrototypeOf;
10646
10647 function setComponentTemplate(factory, obj) {
10648 (true && !(obj !== null && (typeof obj === 'object' || typeof obj === 'function')) && (0, _debug.assert)(`Cannot call \`setComponentTemplate\` on \`${(0, _utils.toString)(obj)}\``, obj !== null && (typeof obj === 'object' || typeof obj === 'function')));
10649 (true && !(!TEMPLATES.has(obj)) && (0, _debug.assert)(`Cannot call \`setComponentTemplate\` multiple times on the same class (\`${obj}\`)`, !TEMPLATES.has(obj)));
10650 TEMPLATES.set(obj, factory);
10651 return obj;
10652 }
10653
10654 function getComponentTemplate(obj) {
10655 var pointer = obj;
10656
10657 while (pointer !== undefined && pointer !== null) {
10658 var _template = TEMPLATES.get(pointer);
10659
10660 if (_template !== undefined) {
10661 return _template;
10662 }
10663
10664 pointer = getPrototypeOf(pointer);
10665 }
10666
10667 return null;
10668 }
10669
10670 var MANAGERS = new WeakMap();
10671 var getPrototypeOf$1 = Object.getPrototypeOf;
10672
10673 function setManager(wrapper, obj) {
10674 MANAGERS.set(obj, wrapper);
10675 return obj;
10676 }
10677
10678 function getManager(obj) {
10679 var pointer = obj;
10680
10681 while (pointer !== undefined && pointer !== null) {
10682 var manager = MANAGERS.get(pointer);
10683
10684 if (manager !== undefined) {
10685 return manager;
10686 }
10687
10688 pointer = getPrototypeOf$1(pointer);
10689 }
10690
10691 return null;
10692 }
10693
10694 function setModifierManager(factory, obj) {
10695 return setManager({
10696 factory,
10697 internal: false,
10698 type: 'modifier'
10699 }, obj);
10700 }
10701
10702 function getModifierManager(obj) {
10703 var wrapper = getManager(obj);
10704
10705 if (wrapper && !wrapper.internal && wrapper.type === 'modifier') {
10706 return wrapper.factory;
10707 } else {
10708 return undefined;
10709 }
10710 }
10711
10712 function instrumentationPayload$1(name) {
10713 return {
10714 object: `component:${name}`
10715 };
10716 }
10717
10718 function makeOptions(moduleName, namespace) {
10719 return {
10720 source: moduleName !== undefined ? `template:${moduleName}` : undefined,
10721 namespace
10722 };
10723 }
10724
10725 function componentFor(name, owner, options) {
10726 var fullName = `component:${name}`;
10727 return owner.factoryFor(fullName, options) || null;
10728 }
10729
10730 function layoutFor(name, owner, options) {
10731 var templateFullName = `template:components/${name}`;
10732 return owner.lookup(templateFullName, options) || null;
10733 }
10734
10735 function lookupComponentPair(owner, name, options) {
10736 var component = componentFor(name, owner, options);
10737 {
10738 if (component !== null && component.class !== undefined) {
10739 var _layout = getComponentTemplate(component.class);
10740
10741 if (_layout !== null) {
10742 return {
10743 component,
10744 layout: _layout
10745 };
10746 }
10747 }
10748 }
10749 var layout = layoutFor(name, owner, options);
10750
10751 if (component === null && layout === null) {
10752 return null;
10753 } else {
10754 return {
10755 component,
10756 layout
10757 };
10758 }
10759 }
10760
10761 function lookupComponent(owner, name, options) {
10762 if (options.source || options.namespace) {
10763 var pair = lookupComponentPair(owner, name, options);
10764
10765 if (pair !== null) {
10766 return pair;
10767 }
10768 }
10769
10770 return lookupComponentPair(owner, name);
10771 }
10772
10773 var lookupPartial;
10774 var templateFor;
10775 var parseUnderscoredName;
10776
10777 if (_deprecatedFeatures.PARTIALS) {
10778 lookupPartial = function (templateName, owner) {
10779 (true && !(false) && (0, _debug.deprecate)(`The use of \`{{partial}}\` is deprecated, please refactor the "${templateName}" partial to a component`, false, {
10780 id: 'ember-views.partial',
10781 until: '4.0.0',
10782 url: 'https://deprecations.emberjs.com/v3.x#toc_ember-views-partial'
10783 }));
10784
10785 if (templateName === null) {
10786 return;
10787 }
10788
10789 var template = templateFor(owner, parseUnderscoredName(templateName), templateName);
10790 (true && !(Boolean(template)) && (0, _debug.assert)(`Unable to find partial with name "${templateName}"`, Boolean(template)));
10791 return template;
10792 };
10793
10794 templateFor = function (owner, underscored, name) {
10795 if (_deprecatedFeatures.PARTIALS) {
10796 if (!name) {
10797 return;
10798 }
10799
10800 (true && !(name.indexOf('.') === -1) && (0, _debug.assert)(`templateNames are not allowed to contain periods: ${name}`, name.indexOf('.') === -1));
10801
10802 if (!owner) {
10803 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');
10804 }
10805
10806 return owner.lookup(`template:${underscored}`) || owner.lookup(`template:${name}`);
10807 }
10808 };
10809
10810 parseUnderscoredName = function (templateName) {
10811 var nameParts = templateName.split('/');
10812 var lastPart = nameParts[nameParts.length - 1];
10813 nameParts[nameParts.length - 1] = `_${lastPart}`;
10814 return nameParts.join('/');
10815 };
10816 }
10817
10818 var BUILTINS_HELPERS = {
10819 if: inlineIf,
10820 action,
10821 array,
10822 concat: concat$1,
10823 fn: fn$1,
10824 get: get$1,
10825 hash,
10826 log: log$1,
10827 mut,
10828 'query-params': queryParams$1,
10829 readonly,
10830 unbound,
10831 unless: inlineUnless,
10832 '-hash': hash,
10833 '-each-in': eachIn,
10834 '-normalize-class': normalizeClassHelper,
10835 '-track-array': trackArray,
10836 '-get-dynamic-var': _runtime2.getDynamicVar,
10837 '-mount': mountHelper,
10838 '-outlet': outletHelper,
10839 '-assert-implicit-component-helper-argument': componentAssertionHelper,
10840 '-in-el-null': inElementNullCheckHelper
10841 };
10842
10843 class RuntimeResolver {
10844 constructor(owner, isInteractive) {
10845 this.handles = [undefined];
10846 this.objToHandle = new WeakMap();
10847 this.builtInHelpers = BUILTINS_HELPERS;
10848 this.componentDefinitionCache = new Map();
10849 this.componentDefinitionCount = 0;
10850 this.helperDefinitionCount = 0;
10851 this.isInteractive = isInteractive;
10852 this.builtInModifiers = {
10853 action: {
10854 manager: new ActionModifierManager(),
10855 state: null
10856 },
10857 on: {
10858 manager: new OnModifierManager(owner, isInteractive),
10859 state: null
10860 }
10861 };
10862 }
10863 /*** IRuntimeResolver ***/
10864
10865 /**
10866 * public componentDefHandleCount = 0;
10867 * Called while executing Append Op.PushDynamicComponentManager if string
10868 */
10869
10870
10871 lookupComponent(name, meta) {
10872 var handle = this.lookupComponentHandle(name, meta);
10873
10874 if (handle === null) {
10875 (true && !(false) && (0, _debug.assert)(`Could not find component named "${name}" (no component or template with that name was found)`));
10876 return null;
10877 }
10878
10879 return this.resolve(handle);
10880 }
10881
10882 lookupComponentHandle(name, meta) {
10883 var nextHandle = this.handles.length;
10884 var handle = this.handle(this._lookupComponentDefinition(name, meta));
10885 (true && !(!(name === 'text-area' && handle === null)) && (0, _debug.assert)('Could not find component `<TextArea />` (did you mean `<Textarea />`?)', !(name === 'text-area' && handle === null)));
10886
10887 if (nextHandle === handle) {
10888 this.componentDefinitionCount++;
10889 }
10890
10891 return handle;
10892 }
10893 /**
10894 * Called by RuntimeConstants to lookup unresolved handles.
10895 */
10896
10897
10898 resolve(handle) {
10899 return this.handles[handle];
10900 } // End IRuntimeResolver
10901
10902 /**
10903 * Called by CompileTimeLookup compiling Unknown or Helper OpCode
10904 */
10905
10906
10907 lookupHelper(name, meta) {
10908 var nextHandle = this.handles.length;
10909
10910 var helper$$1 = this._lookupHelper(name, meta);
10911
10912 if (helper$$1 !== null) {
10913 var handle = this.handle(helper$$1);
10914
10915 if (nextHandle === handle) {
10916 this.helperDefinitionCount++;
10917 }
10918
10919 return handle;
10920 }
10921
10922 return null;
10923 }
10924 /**
10925 * Called by CompileTimeLookup compiling the
10926 */
10927
10928
10929 lookupModifier(name, meta) {
10930 return this.handle(this._lookupModifier(name, meta));
10931 }
10932 /**
10933 * Called by CompileTimeLookup to lookup partial
10934 */
10935
10936
10937 lookupPartial(name, meta) {
10938 if (_deprecatedFeatures.PARTIALS) {
10939 var partial = this._lookupPartial(name, meta);
10940
10941 return this.handle(partial);
10942 } else {
10943 return null;
10944 }
10945 } // TODO: This isn't necessary in all embedding environments, we should likely
10946 // make it optional within Glimmer-VM
10947
10948
10949 compilable() {} // end CompileTimeLookup
10950 // needed for lazy compile time lookup
10951
10952
10953 handle(obj) {
10954 if (obj === undefined || obj === null) {
10955 return null;
10956 }
10957
10958 var handle = this.objToHandle.get(obj);
10959
10960 if (handle === undefined) {
10961 handle = this.handles.push(obj) - 1;
10962 this.objToHandle.set(obj, handle);
10963 }
10964
10965 return handle;
10966 }
10967
10968 _lookupHelper(_name, meta) {
10969 (true && !(!(this.builtInHelpers[_name] && meta.owner.hasRegistration(`helper:${_name}`))) && (0, _debug.assert)(`You attempted to overwrite the built-in helper "${_name}" which is not allowed. Please rename the helper.`, !(this.builtInHelpers[_name] && meta.owner.hasRegistration(`helper:${_name}`))));
10970 var helper$$1 = this.builtInHelpers[_name];
10971
10972 if (helper$$1 !== undefined) {
10973 return helper$$1;
10974 }
10975
10976 var {
10977 moduleName
10978 } = meta;
10979 var owner = meta.owner;
10980 var name = _name;
10981 var namespace = undefined;
10982 var options = makeOptions(moduleName, namespace);
10983 var factory = owner.factoryFor(`helper:${name}`, options) || owner.factoryFor(`helper:${name}`);
10984
10985 if (!isHelperFactory(factory)) {
10986 return null;
10987 }
10988
10989 return (args, vm) => {
10990 var helper$$1 = factory.create();
10991
10992 if (isClassHelper(helper$$1)) {
10993 var helperDestroyable = {}; // Do this so that `destroy` gets called correctly
10994
10995 (0, _runtime2.registerDestructor)(helperDestroyable, () => helper$$1.destroy(), true);
10996 vm.associateDestroyable(helperDestroyable);
10997 } else if (true
10998 /* DEBUG */
10999 ) {
11000 // Bind to null in case someone accidentally passed an unbound function
11001 // in, and attempts use `this` on it.
11002 //
11003 // TODO: Update buildUntouchableThis to be flexible enough to provide a
11004 // nice error message here.
11005 helper$$1.compute = helper$$1.compute.bind(null);
11006 }
11007
11008 return new EmberHelperRootReference(helper$$1, args.capture(), vm.env);
11009 };
11010 }
11011
11012 _lookupPartial(name, meta) {
11013 var owner = meta.owner;
11014 var templateFactory$$1 = lookupPartial(name, owner);
11015 var template = templateFactory$$1(owner);
11016 return new _opcodeCompiler.PartialDefinitionImpl(name, template);
11017 }
11018
11019 _lookupModifier(name, meta) {
11020 var builtin = this.builtInModifiers[name];
11021
11022 if (builtin === undefined) {
11023 var owner = meta.owner;
11024 var modifier = owner.factoryFor(`modifier:${name}`);
11025
11026 if (modifier !== undefined) {
11027 var managerFactory = getModifierManager(modifier.class);
11028 var manager = managerFactory(owner);
11029 return new CustomModifierDefinition(name, modifier, manager, this.isInteractive);
11030 }
11031 }
11032
11033 return builtin;
11034 }
11035
11036 _parseNameForNamespace(_name) {
11037 var name = _name;
11038 var namespace = undefined;
11039
11040 var namespaceDelimiterOffset = _name.indexOf('::');
11041
11042 if (namespaceDelimiterOffset !== -1) {
11043 name = _name.slice(namespaceDelimiterOffset + 2);
11044 namespace = _name.slice(0, namespaceDelimiterOffset);
11045 }
11046
11047 return {
11048 name,
11049 namespace
11050 };
11051 }
11052
11053 _lookupComponentDefinition(_name, meta) {
11054 var name = _name;
11055 var namespace = undefined;
11056 var owner = meta.owner;
11057 var {
11058 moduleName
11059 } = meta;
11060 var pair = lookupComponent(owner, name, makeOptions(moduleName, namespace));
11061
11062 if (pair === null) {
11063 return null;
11064 }
11065
11066 var layout;
11067 var key;
11068
11069 if (pair.component === null) {
11070 key = layout = pair.layout(owner);
11071 } else {
11072 key = pair.component;
11073 }
11074
11075 var cachedComponentDefinition = this.componentDefinitionCache.get(key);
11076
11077 if (cachedComponentDefinition !== undefined) {
11078 return cachedComponentDefinition;
11079 }
11080
11081 if (layout === undefined && pair.layout !== null) {
11082 layout = pair.layout(owner);
11083 }
11084
11085 var finalizer = (0, _instrumentation._instrumentStart)('render.getComponentDefinition', instrumentationPayload$1, name);
11086 var definition = null;
11087
11088 if (pair.component === null) {
11089 if (_environment2.ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS) {
11090 definition = new TemplateOnlyComponentDefinition(name, layout);
11091 }
11092 } else if (true
11093 /* EMBER_GLIMMER_SET_COMPONENT_TEMPLATE */
11094 && (0, _templateOnly.isTemplateOnlyComponent)(pair.component.class)) {
11095 definition = new TemplateOnlyComponentDefinition(name, layout);
11096 }
11097
11098 if (pair.component !== null) {
11099 (true && !(pair.component.class !== undefined) && (0, _debug.assert)(`missing component class ${name}`, pair.component.class !== undefined));
11100 var ComponentClass = pair.component.class;
11101 var wrapper = getManager(ComponentClass);
11102
11103 if (wrapper !== null && wrapper.type === 'component') {
11104 var {
11105 factory
11106 } = wrapper;
11107
11108 if (wrapper.internal) {
11109 (true && !(pair.layout !== null) && (0, _debug.assert)(`missing layout for internal component ${name}`, pair.layout !== null));
11110 definition = new InternalComponentDefinition(factory(owner), ComponentClass, layout);
11111 } else {
11112 definition = new CustomManagerDefinition(name, pair.component, factory(owner), layout !== undefined ? layout : owner.lookup((0, _container.privatize)`template:components/-default`)(owner));
11113 }
11114 }
11115 }
11116
11117 if (definition === null) {
11118 definition = new CurlyComponentDefinition(name, pair.component || owner.factoryFor((0, _container.privatize)`component:-default`), layout);
11119 }
11120
11121 finalizer();
11122 this.componentDefinitionCache.set(key, definition);
11123 return definition;
11124 }
11125
11126 }
11127
11128 function hashToArgs(hash) {
11129 if (hash === null) return null;
11130 var names = hash[0].map(key => `@${key}`);
11131 return [names, hash[1]];
11132 }
11133
11134 var experimentalMacros = []; // This is a private API to allow for experimental macros
11135 // to be created in user space. Registering a macro should
11136 // should be done in an initializer.
11137
11138 _exports._experimentalMacros = experimentalMacros;
11139
11140 function registerMacros(macro) {
11141 experimentalMacros.push(macro);
11142 }
11143
11144 function refineInlineSyntax(name, params, hash, context) {
11145 var component = context.resolver.lookupComponent(name, context.meta.referrer);
11146
11147 if (component !== null) {
11148 return (0, _opcodeCompiler.staticComponent)(component, [params === null ? [] : params, hashToArgs(hash), _opcodeCompiler.EMPTY_BLOCKS]);
11149 }
11150
11151 return _opcodeCompiler.UNHANDLED;
11152 }
11153
11154 function refineBlockSyntax(name, params, hash, blocks, context) {
11155 var handle = context.resolver.lookupComponent(name, context.meta.referrer);
11156
11157 if (handle !== null) {
11158 return (0, _opcodeCompiler.staticComponent)(handle, [params, hashToArgs(hash), blocks]);
11159 }
11160
11161 (true && !(context.meta.referrer.owner.hasRegistration(`helper:${name}`)) && (0, _debug.assert)(`A component or helper named "${name}" could not be found`, context.meta.referrer.owner.hasRegistration(`helper:${name}`)));
11162 (true && !(!(() => {
11163 var resolver = context.resolver['inner']['resolver'];
11164 var {
11165 moduleName,
11166 owner
11167 } = context.meta.referrer;
11168
11169 if (name === 'component' || resolver['builtInHelpers'][name]) {
11170 return true;
11171 }
11172
11173 var options = {
11174 source: `template:${moduleName}`
11175 };
11176 return owner.hasRegistration(`helper:${name}`, options) || owner.hasRegistration(`helper:${name}`);
11177 })()) && (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}}.`, !(() => {
11178 var resolver = context.resolver['inner']['resolver'];
11179 var {
11180 moduleName,
11181 owner
11182 } = context.meta.referrer;
11183
11184 if (name === 'component' || resolver['builtInHelpers'][name]) {
11185 return true;
11186 }
11187
11188 var options = {
11189 source: `template:${moduleName}`
11190 };
11191 return owner.hasRegistration(`helper:${name}`, options) || owner.hasRegistration(`helper:${name}`);
11192 })()));
11193 return _opcodeCompiler.NONE;
11194 }
11195
11196 function populateMacros(macros) {
11197 var {
11198 inlines,
11199 blocks
11200 } = macros;
11201 inlines.addMissing(refineInlineSyntax);
11202 blocks.addMissing(refineBlockSyntax);
11203
11204 for (var i = 0; i < experimentalMacros.length; i++) {
11205 var macro = experimentalMacros[i];
11206 macro(blocks, inlines);
11207 }
11208
11209 return {
11210 blocks,
11211 inlines
11212 };
11213 }
11214
11215 class DynamicScope {
11216 constructor(view, outletState) {
11217 this.view = view;
11218 this.outletState = outletState;
11219 }
11220
11221 child() {
11222 return new DynamicScope(this.view, this.outletState);
11223 }
11224
11225 get(key) {
11226 // tslint:disable-next-line:max-line-length
11227 (true && !(key === 'outletState') && (0, _debug.assert)(`Using \`-get-dynamic-scope\` is only supported for \`outletState\` (you used \`${key}\`).`, key === 'outletState'));
11228 return this.outletState;
11229 }
11230
11231 set(key, value) {
11232 // tslint:disable-next-line:max-line-length
11233 (true && !(key === 'outletState') && (0, _debug.assert)(`Using \`-with-dynamic-scope\` is only supported for \`outletState\` (you used \`${key}\`).`, key === 'outletState'));
11234 this.outletState = value;
11235 return value;
11236 }
11237
11238 }
11239
11240 class RootState {
11241 constructor(root, runtime, context, template, self, parentElement, dynamicScope, builder) {
11242 this.root = root;
11243 this.runtime = runtime;
11244 (true && !(template !== undefined) && (0, _debug.assert)(`You cannot render \`${self.value()}\` without a template.`, template !== undefined));
11245 this.id = (0, _views.getViewId)(root);
11246 this.result = undefined;
11247 this.destroyed = false;
11248
11249 this.render = () => {
11250 var layout = (0, _util.unwrapTemplate)(template).asLayout();
11251 var handle = layout.compile(context);
11252 var iterator = (0, _runtime2.renderJitMain)(runtime, context, self, builder(runtime.env, {
11253 element: parentElement,
11254 nextSibling: null
11255 }), (0, _util.unwrapHandle)(handle), dynamicScope);
11256 var iteratorResult;
11257
11258 do {
11259 iteratorResult = iterator.next();
11260 } while (!iteratorResult.done);
11261
11262 var result = this.result = iteratorResult.value; // override .render function after initial render
11263
11264 this.render = () => result.rerender({
11265 alwaysRevalidate: false
11266 });
11267 };
11268 }
11269
11270 isFor(possibleRoot) {
11271 return this.root === possibleRoot;
11272 }
11273
11274 destroy() {
11275 var {
11276 result,
11277 runtime: {
11278 env
11279 }
11280 } = this;
11281 this.destroyed = true;
11282 this.runtime = undefined;
11283 this.root = null;
11284 this.result = undefined;
11285 this.render = undefined;
11286
11287 if (result !== undefined) {
11288 /*
11289 Handles these scenarios:
11290 * When roots are removed during standard rendering process, a transaction exists already
11291 `.begin()` / `.commit()` are not needed.
11292 * When roots are being destroyed manually (`component.append(); component.destroy() case), no
11293 transaction exists already.
11294 * When roots are being destroyed during `Renderer#destroy`, no transaction exists
11295 */
11296 (0, _runtime2.inTransaction)(env, () => (0, _runtime2.destroy)(result));
11297 }
11298 }
11299
11300 }
11301
11302 var renderers = [];
11303
11304 function _resetRenderers() {
11305 renderers.length = 0;
11306 }
11307
11308 function register(renderer) {
11309 (true && !(renderers.indexOf(renderer) === -1) && (0, _debug.assert)('Cannot register the same renderer twice', renderers.indexOf(renderer) === -1));
11310 renderers.push(renderer);
11311 }
11312
11313 function deregister(renderer) {
11314 var index = renderers.indexOf(renderer);
11315 (true && !(index !== -1) && (0, _debug.assert)('Cannot deregister unknown unregistered renderer', index !== -1));
11316 renderers.splice(index, 1);
11317 }
11318
11319 function loopBegin() {
11320 for (var i = 0; i < renderers.length; i++) {
11321 renderers[i]._scheduleRevalidate();
11322 }
11323 }
11324
11325 function K() {
11326 /* noop */
11327 }
11328
11329 var renderSettledDeferred = null;
11330 /*
11331 Returns a promise which will resolve when rendering has settled. Settled in
11332 this context is defined as when all of the tags in use are "current" (e.g.
11333 `renderers.every(r => r._isValid())`). When this is checked at the _end_ of
11334 the run loop, this essentially guarantees that all rendering is completed.
11335
11336 @method renderSettled
11337 @returns {Promise<void>} a promise which fulfills when rendering has settled
11338 */
11339
11340 function renderSettled() {
11341 if (renderSettledDeferred === null) {
11342 renderSettledDeferred = _rsvp.default.defer(); // if there is no current runloop, the promise created above will not have
11343 // a chance to resolve (because its resolved in backburner's "end" event)
11344
11345 if (!(0, _runloop.getCurrentRunLoop)()) {
11346 // ensure a runloop has been kicked off
11347 _runloop.backburner.schedule('actions', null, K);
11348 }
11349 }
11350
11351 return renderSettledDeferred.promise;
11352 }
11353
11354 function resolveRenderPromise() {
11355 if (renderSettledDeferred !== null) {
11356 var resolve = renderSettledDeferred.resolve;
11357 renderSettledDeferred = null;
11358
11359 _runloop.backburner.join(null, resolve);
11360 }
11361 }
11362
11363 var loops = 0;
11364
11365 function loopEnd() {
11366 for (var i = 0; i < renderers.length; i++) {
11367 if (!renderers[i]._isValid()) {
11368 if (loops > _environment2.ENV._RERENDER_LOOP_LIMIT) {
11369 loops = 0; // TODO: do something better
11370
11371 renderers[i].destroy();
11372 throw new Error('infinite rendering invalidation detected');
11373 }
11374
11375 loops++;
11376 return _runloop.backburner.join(null, K);
11377 }
11378 }
11379
11380 loops = 0;
11381 resolveRenderPromise();
11382 }
11383
11384 _runloop.backburner.on('begin', loopBegin);
11385
11386 _runloop.backburner.on('end', loopEnd);
11387
11388 class Renderer {
11389 constructor(owner, document, env, rootTemplate, viewRegistry, destinedForDOM = false, builder = _runtime2.clientBuilder) {
11390 this._inRenderTransaction = false;
11391 this._lastRevision = -1;
11392 this._destroyed = false;
11393 this._rootTemplate = rootTemplate(owner);
11394 this._viewRegistry = viewRegistry;
11395 this._destinedForDOM = destinedForDOM;
11396 this._roots = [];
11397 this._removedRoots = [];
11398 this._builder = builder; // resolver is exposed for tests
11399
11400 var runtimeResolver = this._runtimeResolver = new RuntimeResolver(owner, env.isInteractive);
11401 var compileTimeResolver = new CompileTimeResolver(runtimeResolver);
11402 var context = this._context = (0, _opcodeCompiler.JitContext)(compileTimeResolver);
11403 populateMacros(context.macros);
11404 var runtimeEnvironmentDelegate = new EmberEnvironmentDelegate(owner, env.isInteractive);
11405 this._runtime = (0, _runtime2.JitRuntime)({
11406 appendOperations: env.hasDOM ? new _runtime2.DOMTreeConstruction(document) : new _node.NodeDOMTreeConstruction(document),
11407 updateOperations: new _runtime2.DOMChanges(document)
11408 }, runtimeEnvironmentDelegate, context, runtimeResolver);
11409 }
11410
11411 get debugRenderTree() {
11412 return this._runtime.env.extra.debugRenderTree;
11413 } // renderer HOOKS
11414
11415
11416 appendOutletView(view, target) {
11417 var definition = createRootOutlet(view);
11418
11419 this._appendDefinition(view, (0, _runtime2.curry)(definition), target);
11420 }
11421
11422 appendTo(view, target) {
11423 var definition = new RootComponentDefinition(view);
11424
11425 this._appendDefinition(view, (0, _runtime2.curry)(definition), target);
11426 }
11427
11428 _appendDefinition(root, definition, target) {
11429 var self = new UnboundRootReference(definition, this._runtime.env);
11430 var dynamicScope = new DynamicScope(null, _runtime2.UNDEFINED_REFERENCE);
11431 var rootState = new RootState(root, this._runtime, this._context, this._rootTemplate, self, target, dynamicScope, this._builder);
11432
11433 this._renderRoot(rootState);
11434 }
11435
11436 rerender() {
11437 this._scheduleRevalidate();
11438 }
11439
11440 register(view) {
11441 var id = (0, _views.getViewId)(view);
11442 (true && !(!this._viewRegistry[id]) && (0, _debug.assert)('Attempted to register a view with an id already in use: ' + id, !this._viewRegistry[id]));
11443 this._viewRegistry[id] = view;
11444 }
11445
11446 unregister(view) {
11447 delete this._viewRegistry[(0, _views.getViewId)(view)];
11448 }
11449
11450 remove(view) {
11451 view._transitionTo('destroying');
11452
11453 this.cleanupRootFor(view);
11454
11455 if (this._destinedForDOM) {
11456 view.trigger('didDestroyElement');
11457 }
11458 }
11459
11460 cleanupRootFor(view) {
11461 // no need to cleanup roots if we have already been destroyed
11462 if (this._destroyed) {
11463 return;
11464 }
11465
11466 var roots = this._roots; // traverse in reverse so we can remove items
11467 // without mucking up the index
11468
11469 var i = this._roots.length;
11470
11471 while (i--) {
11472 var root = roots[i];
11473
11474 if (root.isFor(view)) {
11475 root.destroy();
11476 roots.splice(i, 1);
11477 }
11478 }
11479 }
11480
11481 destroy() {
11482 if (this._destroyed) {
11483 return;
11484 }
11485
11486 this._destroyed = true;
11487
11488 this._clearAllRoots();
11489 }
11490
11491 getBounds(view) {
11492 var bounds = view[BOUNDS];
11493 (true && !(Boolean(bounds)) && (0, _debug.assert)('object passed to getBounds must have the BOUNDS symbol as a property', Boolean(bounds)));
11494 var parentElement = bounds.parentElement();
11495 var firstNode = bounds.firstNode();
11496 var lastNode = bounds.lastNode();
11497 return {
11498 parentElement,
11499 firstNode,
11500 lastNode
11501 };
11502 }
11503
11504 createElement(tagName) {
11505 return this._runtime.env.getAppendOperations().createElement(tagName);
11506 }
11507
11508 _renderRoot(root) {
11509 var {
11510 _roots: roots
11511 } = this;
11512 roots.push(root);
11513
11514 if (roots.length === 1) {
11515 register(this);
11516 }
11517
11518 this._renderRootsTransaction();
11519 }
11520
11521 _renderRoots() {
11522 var {
11523 _roots: roots,
11524 _runtime: runtime,
11525 _removedRoots: removedRoots
11526 } = this;
11527 var initialRootsLength;
11528
11529 do {
11530 initialRootsLength = roots.length;
11531 (0, _runtime2.inTransaction)(runtime.env, () => {
11532 // ensure that for the first iteration of the loop
11533 // each root is processed
11534 for (var i = 0; i < roots.length; i++) {
11535 var root = roots[i];
11536
11537 if (root.destroyed) {
11538 // add to the list of roots to be removed
11539 // they will be removed from `this._roots` later
11540 removedRoots.push(root); // skip over roots that have been marked as destroyed
11541
11542 continue;
11543 } // when processing non-initial reflush loops,
11544 // do not process more roots than needed
11545
11546
11547 if (i >= initialRootsLength) {
11548 continue;
11549 }
11550
11551 if (true
11552 /* DEBUG */
11553 ) {
11554 // run in an autotracking transaction to prevent backflow errors.
11555 // we use `bind` here to avoid creating a closure (and requiring a
11556 // hoisted variable).
11557 (0, _validator.runInAutotrackingTransaction)(root.render.bind(root));
11558 } else {
11559 root.render();
11560 }
11561 }
11562
11563 this._lastRevision = (0, _validator.valueForTag)(_validator.CURRENT_TAG);
11564 });
11565 } while (roots.length > initialRootsLength); // remove any roots that were destroyed during this transaction
11566
11567
11568 while (removedRoots.length) {
11569 var root = removedRoots.pop();
11570 var rootIndex = roots.indexOf(root);
11571 roots.splice(rootIndex, 1);
11572 }
11573
11574 if (this._roots.length === 0) {
11575 deregister(this);
11576 }
11577 }
11578
11579 _renderRootsTransaction() {
11580 if (this._inRenderTransaction) {
11581 // currently rendering roots, a new root was added and will
11582 // be processed by the existing _renderRoots invocation
11583 return;
11584 } // used to prevent calling _renderRoots again (see above)
11585 // while we are actively rendering roots
11586
11587
11588 this._inRenderTransaction = true;
11589 var completedWithoutError = false;
11590
11591 try {
11592 this._renderRoots();
11593
11594 completedWithoutError = true;
11595 } finally {
11596 if (!completedWithoutError) {
11597 this._lastRevision = (0, _validator.valueForTag)(_validator.CURRENT_TAG);
11598 }
11599
11600 this._inRenderTransaction = false;
11601 }
11602 }
11603
11604 _clearAllRoots() {
11605 var roots = this._roots;
11606
11607 for (var i = 0; i < roots.length; i++) {
11608 var root = roots[i];
11609 root.destroy();
11610 }
11611
11612 this._removedRoots.length = 0;
11613 this._roots = []; // if roots were present before destroying
11614 // deregister this renderer instance
11615
11616 if (roots.length) {
11617 deregister(this);
11618 }
11619 }
11620
11621 _scheduleRevalidate() {
11622 _runloop.backburner.scheduleOnce('render', this, this._revalidate);
11623 }
11624
11625 _isValid() {
11626 return this._destroyed || this._roots.length === 0 || (0, _validator.validateTag)(_validator.CURRENT_TAG, this._lastRevision);
11627 }
11628
11629 _revalidate() {
11630 if (this._isValid()) {
11631 return;
11632 }
11633
11634 this._renderRootsTransaction();
11635 }
11636
11637 }
11638
11639 _exports.Renderer = Renderer;
11640
11641 class InertRenderer extends Renderer {
11642 static create(props) {
11643 var {
11644 document,
11645 env,
11646 rootTemplate,
11647 _viewRegistry,
11648 builder
11649 } = props;
11650 return new this((0, _owner.getOwner)(props), document, env, rootTemplate, _viewRegistry, false, builder);
11651 }
11652
11653 getElement(_view) {
11654 throw new Error('Accessing `this.element` is not allowed in non-interactive environments (such as FastBoot).');
11655 }
11656
11657 }
11658
11659 _exports.InertRenderer = InertRenderer;
11660
11661 class InteractiveRenderer extends Renderer {
11662 static create(props) {
11663 var {
11664 document,
11665 env,
11666 rootTemplate,
11667 _viewRegistry,
11668 builder
11669 } = props;
11670 return new this((0, _owner.getOwner)(props), document, env, rootTemplate, _viewRegistry, true, builder);
11671 }
11672
11673 getElement(view) {
11674 return (0, _views.getViewElement)(view);
11675 }
11676
11677 }
11678
11679 _exports.InteractiveRenderer = InteractiveRenderer;
11680 var TEMPLATES$1 = {};
11681
11682 function setTemplates(templates) {
11683 TEMPLATES$1 = templates;
11684 }
11685
11686 function getTemplates() {
11687 return TEMPLATES$1;
11688 }
11689
11690 function getTemplate(name) {
11691 if (Object.prototype.hasOwnProperty.call(TEMPLATES$1, name)) {
11692 return TEMPLATES$1[name];
11693 }
11694 }
11695
11696 function hasTemplate(name) {
11697 return Object.prototype.hasOwnProperty.call(TEMPLATES$1, name);
11698 }
11699
11700 function setTemplate(name, template) {
11701 return TEMPLATES$1[name] = template;
11702 }
11703
11704 var CAPABILITIES$4 = {
11705 dynamicLayout: false,
11706 dynamicTag: false,
11707 prepareArgs: true,
11708 createArgs: true,
11709 attributeHook: false,
11710 elementHook: false,
11711 createCaller: true,
11712 dynamicScope: false,
11713 updateHook: true,
11714 createInstance: true,
11715 wrapped: false,
11716 willDestroy: false
11717 };
11718 var EMPTY_POSITIONAL_ARGS$1 = [];
11719 (0, _debug.debugFreeze)(EMPTY_POSITIONAL_ARGS$1);
11720
11721 class InputComponentManager extends InternalManager {
11722 getCapabilities() {
11723 return CAPABILITIES$4;
11724 }
11725
11726 prepareArgs(_state, args) {
11727 (true && !(args.positional.length === 0) && (0, _debug.assert)('The `<Input />` component does not take any positional arguments', args.positional.length === 0));
11728 var __ARGS__ = args.named.capture().map;
11729 return {
11730 positional: EMPTY_POSITIONAL_ARGS$1,
11731 named: {
11732 __ARGS__: new _reference.ConstReference(__ARGS__),
11733 type: args.named.get('type')
11734 }
11735 };
11736 }
11737
11738 create(env, {
11739 ComponentClass,
11740 layout
11741 }, args, _dynamicScope, caller) {
11742 (true && !((0, _validator.isConstTagged)(caller)) && (0, _debug.assert)('caller must be const', (0, _validator.isConstTagged)(caller)));
11743 var type = args.named.get('type');
11744 var instance = ComponentClass.create({
11745 caller: caller.value(),
11746 type: type.value()
11747 });
11748 var state = {
11749 env,
11750 type,
11751 instance
11752 };
11753
11754 if (_environment2.ENV._DEBUG_RENDER_TREE) {
11755 env.extra.debugRenderTree.create(state, {
11756 type: 'component',
11757 name: 'input',
11758 args: args.capture(),
11759 instance,
11760 template: layout
11761 });
11762 (0, _runtime2.registerDestructor)(instance, () => env.extra.debugRenderTree.willDestroy(state));
11763 }
11764
11765 return state;
11766 }
11767
11768 getSelf({
11769 env,
11770 instance
11771 }) {
11772 return new _reference.ComponentRootReference(instance, env);
11773 }
11774
11775 getTag() {
11776 if (_environment2.ENV._DEBUG_RENDER_TREE) {
11777 // returning a const tag skips the update hook (VM BUG?)
11778 return (0, _validator.createTag)();
11779 } else {
11780 // an outlet has no hooks
11781 return _validator.CONSTANT_TAG;
11782 }
11783 }
11784
11785 didRenderLayout(state, bounds) {
11786 if (_environment2.ENV._DEBUG_RENDER_TREE) {
11787 state.env.extra.debugRenderTree.didRender(state, bounds);
11788 }
11789 }
11790
11791 update(state) {
11792 (0, _metal.set)(state.instance, 'type', state.type.value());
11793
11794 if (_environment2.ENV._DEBUG_RENDER_TREE) {
11795 state.env.extra.debugRenderTree.update(state);
11796 }
11797 }
11798
11799 didUpdateLayout(state, bounds) {
11800 if (_environment2.ENV._DEBUG_RENDER_TREE) {
11801 state.env.extra.debugRenderTree.didRender(state, bounds);
11802 }
11803 }
11804
11805 getDestroyable(state) {
11806 return state.instance;
11807 }
11808
11809 }
11810
11811 var InputComponentManagerFactory = owner => {
11812 return new InputComponentManager(owner);
11813 };
11814 /**
11815 @module @ember/component
11816 */
11817
11818 /**
11819 See [Ember.Templates.components.Input](/ember/release/classes/Ember.Templates.components/methods/Input?anchor=Input).
11820
11821 @method input
11822 @for Ember.Templates.helpers
11823 @param {Hash} options
11824 @public
11825 */
11826
11827 /**
11828 The `Input` component lets you create an HTML `<input>` element.
11829
11830 ```handlebars
11831 <Input @value="987" />
11832 ```
11833
11834 creates an `<input>` element with `type="text"` and value set to 987.
11835
11836 ### Text field
11837
11838 If no `type` argument is specified, a default of type 'text' is used.
11839
11840 ```handlebars
11841 Search:
11842 <Input @value={{this.searchWord}} />
11843 ```
11844
11845 In this example, the initial value in the `<input>` will be set to the value of
11846 `this.searchWord`. If the user changes the text, the value of `this.searchWord` will also be
11847 updated.
11848
11849 ### Actions
11850
11851 The `Input` component takes a number of arguments with callbacks that are invoked in response to
11852 user events.
11853
11854 * `enter`
11855 * `insert-newline`
11856 * `escape-press`
11857 * `focus-in`
11858 * `focus-out`
11859 * `key-down`
11860 * `key-press`
11861 * `key-up`
11862
11863 These callbacks are passed to `Input` like this:
11864
11865 ```handlebars
11866 <Input @value={{this.searchWord}} @enter={{this.query}} />
11867 ```
11868
11869 ### `<input>` HTML Attributes to Avoid
11870
11871 In most cases, if you want to pass an attribute to the underlying HTML `<input>` element, you
11872 can pass the attribute directly, just like any other Ember component.
11873
11874 ```handlebars
11875 <Input @type="text" size="10" />
11876 ```
11877
11878 In this example, the `size` attribute will be applied to the underlying `<input>` element in the
11879 outputted HTML.
11880
11881 However, there are a few attributes where you **must** use the `@` version.
11882
11883 * `@type`: This argument is used to control which Ember component is used under the hood
11884 * `@value`: The `@value` argument installs a two-way binding onto the element. If you wanted a
11885 one-way binding, use `<input>` with the `value` property and the `input` event instead.
11886 * `@checked` (for checkboxes): like `@value`, the `@checked` argument installs a two-way binding
11887 onto the element. If you wanted a one-way binding, use `<input type="checkbox">` with
11888 `checked` and the `input` event instead.
11889
11890 ### Extending `TextField`
11891
11892 Internally, `<Input @type="text" />` creates an instance of `TextField`, passing arguments from
11893 the helper to `TextField`'s `create` method. Subclassing `TextField` is supported but not
11894 recommended.
11895
11896 See [TextField](/ember/release/classes/TextField)
11897
11898 ### Checkbox
11899
11900 To create an `<input type="checkbox">`:
11901
11902 ```handlebars
11903 Emberize Everything:
11904 <Input @type="checkbox" @checked={{this.isEmberized}} name="isEmberized" />
11905 ```
11906
11907 This will bind the checked state of this checkbox to the value of `isEmberized` -- if either one
11908 changes, it will be reflected in the other.
11909
11910 ### Extending `Checkbox`
11911
11912 Internally, `<Input @type="checkbox" />` creates an instance of `Checkbox`. Subclassing
11913 `TextField` is supported but not recommended.
11914
11915 See [Checkbox](/ember/release/classes/Checkbox)
11916
11917 @method Input
11918 @for Ember.Templates.components
11919 @see {TextField}
11920 @see {Checkbox}
11921 @param {Hash} options
11922 @public
11923 */
11924
11925
11926 var Input = _runtime.Object.extend({
11927 isCheckbox: (0, _metal.computed)('type', function () {
11928 return this.type === 'checkbox';
11929 })
11930 });
11931
11932 setManager({
11933 factory: InputComponentManagerFactory,
11934 internal: true,
11935 type: 'component'
11936 }, Input);
11937
11938 Input.toString = () => '@ember/component/input';
11939 /**
11940 @module ember
11941 */
11942
11943 /**
11944 Calls [String.loc](/ember/release/classes/String/methods/loc?anchor=loc) with the
11945 provided string. This is a convenient way to localize text within a template.
11946 For example:
11947
11948 ```javascript
11949 Ember.STRINGS = {
11950 '_welcome_': 'Bonjour'
11951 };
11952 ```
11953
11954 ```handlebars
11955 <div class='message'>
11956 {{loc '_welcome_'}}
11957 </div>
11958 ```
11959
11960 ```html
11961 <div class='message'>
11962 Bonjour
11963 </div>
11964 ```
11965
11966 See [String.loc](/ember/release/classes/String/methods/loc?anchor=loc) for how to
11967 set up localized string references.
11968
11969 @method loc
11970 @for Ember.Templates.helpers
11971 @param {String} str The string to format.
11972 @see {String#loc}
11973 @public
11974 */
11975
11976
11977 var loc$1 = helper(function (params) {
11978 return _string.loc.apply(null, params
11979 /* let the other side handle errors */
11980 );
11981 });
11982 var ComponentTemplate = template({
11983 "id": "RLf1peEf",
11984 "block": "{\"symbols\":[\"&default\"],\"statements\":[[18,1,null]],\"hasEval\":false,\"upvars\":[]}",
11985 "meta": {
11986 "moduleName": "packages/@ember/-internals/glimmer/lib/templates/component.hbs"
11987 }
11988 });
11989 var InputTemplate = template({
11990 "id": "ExnzE3OS",
11991 "block": "{\"symbols\":[\"Checkbox\",\"TextField\",\"@__ARGS__\",\"&attrs\"],\"statements\":[[6,[37,2],[[30,[36,1],[\"-checkbox\"],null],[30,[36,1],[\"-text-field\"],null]],null,[[\"default\"],[{\"statements\":[[6,[37,0],[[32,0,[\"isCheckbox\"]]],null,[[\"default\",\"else\"],[{\"statements\":[[8,[32,1],[[17,4]],[[\"@target\",\"@__ARGS__\"],[[32,0,[\"caller\"]],[32,3]]],null]],\"parameters\":[]},{\"statements\":[[8,[32,2],[[17,4]],[[\"@target\",\"@__ARGS__\"],[[32,0,[\"caller\"]],[32,3]]],null]],\"parameters\":[]}]]]],\"parameters\":[1,2]}]]]],\"hasEval\":false,\"upvars\":[\"if\",\"component\",\"let\"]}",
11992 "meta": {
11993 "moduleName": "packages/@ember/-internals/glimmer/lib/templates/input.hbs"
11994 }
11995 });
11996 var OutletTemplate = template({
11997 "id": "vA+C0Wde",
11998 "block": "{\"symbols\":[],\"statements\":[[1,[30,[36,1],[[30,[36,0],null,null]],null]]],\"hasEval\":false,\"upvars\":[\"-outlet\",\"component\"]}",
11999 "meta": {
12000 "moduleName": "packages/@ember/-internals/glimmer/lib/templates/outlet.hbs"
12001 }
12002 });
12003 var TOP_LEVEL_NAME = '-top-level';
12004 var TOP_LEVEL_OUTLET = 'main';
12005
12006 class OutletView {
12007 constructor(_environment, renderer, owner, template) {
12008 this._environment = _environment;
12009 this.renderer = renderer;
12010 this.owner = owner;
12011 this.template = template;
12012 var ref = this.ref = new RootOutletReference({
12013 outlets: {
12014 main: undefined
12015 },
12016 render: {
12017 owner: owner,
12018 into: undefined,
12019 outlet: TOP_LEVEL_OUTLET,
12020 name: TOP_LEVEL_NAME,
12021 controller: undefined,
12022 model: undefined,
12023 template
12024 }
12025 });
12026 this.state = {
12027 ref,
12028 name: TOP_LEVEL_NAME,
12029 outlet: TOP_LEVEL_OUTLET,
12030 template,
12031 controller: undefined,
12032 model: undefined
12033 };
12034 }
12035
12036 static extend(injections) {
12037 return class extends OutletView {
12038 static create(options) {
12039 if (options) {
12040 return super.create((0, _polyfills.assign)({}, injections, options));
12041 } else {
12042 return super.create(injections);
12043 }
12044 }
12045
12046 };
12047 }
12048
12049 static reopenClass(injections) {
12050 (0, _polyfills.assign)(this, injections);
12051 }
12052
12053 static create(options) {
12054 var {
12055 _environment,
12056 renderer,
12057 template: templateFactory$$1
12058 } = options;
12059 var owner = (0, _owner.getOwner)(options);
12060 var template = templateFactory$$1(owner);
12061 return new OutletView(_environment, renderer, owner, template);
12062 }
12063
12064 appendTo(selector) {
12065 var target;
12066
12067 if (this._environment.hasDOM) {
12068 target = typeof selector === 'string' ? document.querySelector(selector) : selector;
12069 } else {
12070 target = selector;
12071 }
12072
12073 (0, _runloop.schedule)('render', this.renderer, 'appendOutletView', this, target);
12074 }
12075
12076 rerender() {
12077 /**/
12078 }
12079
12080 setOutletState(state) {
12081 this.ref.update(state);
12082 }
12083
12084 destroy() {
12085 /**/
12086 }
12087
12088 }
12089
12090 _exports.OutletView = OutletView;
12091
12092 function setupApplicationRegistry(registry) {
12093 registry.injection('renderer', 'env', '-environment:main'); // because we are using injections we can't use instantiate false
12094 // we need to use bind() to copy the function so factory for
12095 // association won't leak
12096
12097 registry.register('service:-dom-builder', {
12098 create({
12099 bootOptions
12100 }) {
12101 var {
12102 _renderMode
12103 } = bootOptions;
12104
12105 switch (_renderMode) {
12106 case 'serialize':
12107 return _node.serializeBuilder.bind(null);
12108
12109 case 'rehydrate':
12110 return _runtime2.rehydrationBuilder.bind(null);
12111
12112 default:
12113 return _runtime2.clientBuilder.bind(null);
12114 }
12115 }
12116
12117 });
12118 registry.injection('service:-dom-builder', 'bootOptions', '-environment:main');
12119 registry.injection('renderer', 'builder', 'service:-dom-builder');
12120 registry.register((0, _container.privatize)`template:-root`, RootTemplate);
12121 registry.injection('renderer', 'rootTemplate', (0, _container.privatize)`template:-root`);
12122 registry.register('renderer:-dom', InteractiveRenderer);
12123 registry.register('renderer:-inert', InertRenderer);
12124 registry.injection('renderer', 'document', 'service:-document');
12125 }
12126
12127 function setupEngineRegistry(registry) {
12128 registry.optionsForType('template', {
12129 instantiate: false
12130 });
12131 registry.register('view:-outlet', OutletView);
12132 registry.register('template:-outlet', OutletTemplate);
12133 registry.injection('view:-outlet', 'template', 'template:-outlet');
12134 registry.register((0, _container.privatize)`template:components/-default`, ComponentTemplate);
12135 registry.optionsForType('helper', {
12136 instantiate: false
12137 });
12138 registry.register('helper:loc', loc$1);
12139 registry.register('component:-text-field', TextField);
12140 registry.register('component:-checkbox', Checkbox);
12141 registry.register('component:link-to', LinkComponent);
12142 registry.register('component:input', Input);
12143 registry.register('template:components/input', InputTemplate);
12144 registry.register('component:textarea', TextArea);
12145
12146 if (!_environment2.ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS) {
12147 registry.register((0, _container.privatize)`component:-default`, Component);
12148 }
12149 }
12150
12151 function setComponentManager(stringOrFunction, obj) {
12152 var factory;
12153
12154 if (_deprecatedFeatures.COMPONENT_MANAGER_STRING_LOOKUP && typeof stringOrFunction === 'string') {
12155 (true && !(false) && (0, _debug.deprecate)('Passing the name of the component manager to "setupComponentManager" is deprecated. Please pass a function that produces an instance of the manager.', false, {
12156 id: 'deprecate-string-based-component-manager',
12157 until: '4.0.0',
12158 url: 'https://emberjs.com/deprecations/v3.x/#toc_component-manager-string-lookup'
12159 }));
12160
12161 factory = function (owner) {
12162 return owner.lookup(`component-manager:${stringOrFunction}`);
12163 };
12164 } else {
12165 factory = stringOrFunction;
12166 }
12167
12168 return setManager({
12169 factory,
12170 internal: false,
12171 type: 'component'
12172 }, obj);
12173 }
12174
12175 function getComponentManager(obj) {
12176 var wrapper = getManager(obj);
12177
12178 if (wrapper && !wrapper.internal && wrapper.type === 'component') {
12179 return wrapper.factory;
12180 } else {
12181 return undefined;
12182 }
12183 }
12184 /**
12185 [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.
12186
12187 ### Showing a property
12188
12189 Templates manage the flow of an application's UI, and display state (through
12190 the DOM) to a user. For example, given a component with the property "name",
12191 that component's template can use the name in several ways:
12192
12193 ```app/components/person-profile.js
12194 import Component from '@ember/component';
12195
12196 export default Component.extend({
12197 name: 'Jill'
12198 });
12199 ```
12200
12201 ```app/components/person-profile.hbs
12202 {{this.name}}
12203 <div>{{this.name}}</div>
12204 <span data-name={{this.name}}></span>
12205 ```
12206
12207 Any time the "name" property on the component changes, the DOM will be
12208 updated.
12209
12210 Properties can be chained as well:
12211
12212 ```handlebars
12213 {{@aUserModel.name}}
12214 <div>{{@listOfUsers.firstObject.name}}</div>
12215 ```
12216
12217 ### Using Ember helpers
12218
12219 When content is passed in mustaches `{{}}`, Ember will first try to find a helper
12220 or component with that name. For example, the `if` helper:
12221
12222 ```app/components/person-profile.hbs
12223 {{if this.name "I have a name" "I have no name"}}
12224 <span data-has-name={{if this.name true}}></span>
12225 ```
12226
12227 The returned value is placed where the `{{}}` is called. The above style is
12228 called "inline". A second style of helper usage is called "block". For example:
12229
12230 ```handlebars
12231 {{#if this.name}}
12232 I have a name
12233 {{else}}
12234 I have no name
12235 {{/if}}
12236 ```
12237
12238 The block form of helpers allows you to control how the UI is created based
12239 on the values of properties.
12240 A third form of helper is called "nested". For example here the concat
12241 helper will add " Doe" to a displayed name if the person has no last name:
12242
12243 ```handlebars
12244 <span data-name={{concat this.firstName (
12245 if this.lastName (concat " " this.lastName) "Doe"
12246 )}}></span>
12247 ```
12248
12249 Ember's built-in helpers are described under the [Ember.Templates.helpers](/ember/release/classes/Ember.Templates.helpers)
12250 namespace. Documentation on creating custom helpers can be found under
12251 [helper](/ember/release/functions/@ember%2Fcomponent%2Fhelper/helper) (or
12252 under [Helper](/ember/release/classes/Helper) if a helper requires access to
12253 dependency injection).
12254
12255 ### Invoking a Component
12256
12257 Ember components represent state to the UI of an application. Further
12258 reading on components can be found under [Component](/ember/release/classes/Component).
12259
12260 @module @ember/component
12261 @main @ember/component
12262 @public
12263 */
12264
12265});
12266define("@ember/-internals/meta/index", ["exports", "@ember/-internals/meta/lib/meta"], function (_exports, _meta) {
12267 "use strict";
12268
12269 Object.defineProperty(_exports, "__esModule", {
12270 value: true
12271 });
12272 Object.defineProperty(_exports, "counters", {
12273 enumerable: true,
12274 get: function () {
12275 return _meta.counters;
12276 }
12277 });
12278 Object.defineProperty(_exports, "Meta", {
12279 enumerable: true,
12280 get: function () {
12281 return _meta.Meta;
12282 }
12283 });
12284 Object.defineProperty(_exports, "meta", {
12285 enumerable: true,
12286 get: function () {
12287 return _meta.meta;
12288 }
12289 });
12290 Object.defineProperty(_exports, "peekMeta", {
12291 enumerable: true,
12292 get: function () {
12293 return _meta.peekMeta;
12294 }
12295 });
12296 Object.defineProperty(_exports, "setMeta", {
12297 enumerable: true,
12298 get: function () {
12299 return _meta.setMeta;
12300 }
12301 });
12302 Object.defineProperty(_exports, "UNDEFINED", {
12303 enumerable: true,
12304 get: function () {
12305 return _meta.UNDEFINED;
12306 }
12307 });
12308});
12309define("@ember/-internals/meta/lib/meta", ["exports", "@ember/-internals/utils", "@ember/debug", "@glimmer/runtime"], function (_exports, _utils, _debug, _runtime) {
12310 "use strict";
12311
12312 Object.defineProperty(_exports, "__esModule", {
12313 value: true
12314 });
12315 _exports.setMeta = setMeta;
12316 _exports.peekMeta = peekMeta;
12317 _exports.counters = _exports.meta = _exports.Meta = _exports.UNDEFINED = void 0;
12318 var objectPrototype = Object.prototype;
12319 var counters;
12320 _exports.counters = counters;
12321
12322 if (true
12323 /* DEBUG */
12324 ) {
12325 _exports.counters = counters = {
12326 peekCalls: 0,
12327 peekPrototypeWalks: 0,
12328 setCalls: 0,
12329 deleteCalls: 0,
12330 metaCalls: 0,
12331 metaInstantiated: 0,
12332 matchingListenersCalls: 0,
12333 observerEventsCalls: 0,
12334 addToListenersCalls: 0,
12335 removeFromListenersCalls: 0,
12336 removeAllListenersCalls: 0,
12337 listenersInherited: 0,
12338 listenersFlattened: 0,
12339 parentListenersUsed: 0,
12340 flattenedListenersCalls: 0,
12341 reopensAfterFlatten: 0,
12342 readableLazyChainsCalls: 0,
12343 writableLazyChainsCalls: 0
12344 };
12345 }
12346 /**
12347 @module ember
12348 */
12349
12350
12351 var UNDEFINED = (0, _utils.symbol)('undefined');
12352 _exports.UNDEFINED = UNDEFINED;
12353 var currentListenerVersion = 1;
12354
12355 class Meta {
12356 // DEBUG
12357 constructor(obj) {
12358 this._listenersVersion = 1;
12359 this._inheritedEnd = -1;
12360 this._flattenedVersion = 0;
12361
12362 if (true
12363 /* DEBUG */
12364 ) {
12365 counters.metaInstantiated++;
12366 }
12367
12368 this._parent = undefined;
12369 this._descriptors = undefined;
12370 this._mixins = undefined;
12371 this._lazyChains = undefined;
12372 this._values = undefined;
12373 this._tags = undefined;
12374 this._revisions = undefined; // initial value for all flags right now is false
12375 // see FLAGS const for detailed list of flags used
12376
12377 this._isInit = false; // used only internally
12378
12379 this.source = obj;
12380 this.proto = obj.constructor === undefined ? undefined : obj.constructor.prototype;
12381 this._listeners = undefined;
12382 }
12383
12384 get parent() {
12385 var parent = this._parent;
12386
12387 if (parent === undefined) {
12388 var proto = getPrototypeOf(this.source);
12389 this._parent = parent = proto === null || proto === objectPrototype ? null : meta(proto);
12390 }
12391
12392 return parent;
12393 } // These methods are here to prevent errors in legacy compat with some addons
12394 // that used them as intimate API
12395
12396
12397 setSourceDestroying() {
12398 (true && !(false) && (0, _debug.deprecate)('setSourceDestroying is deprecated, use the destroy() API to destroy the object directly instead', false, {
12399 id: 'meta-destruction-apis',
12400 until: '3.25.0'
12401 }));
12402 }
12403
12404 setSourceDestroyed() {
12405 (true && !(false) && (0, _debug.deprecate)('setSourceDestroyed is deprecated, use the destroy() API to destroy the object directly instead', false, {
12406 id: 'meta-destruction-apis',
12407 until: '3.25.0'
12408 }));
12409 }
12410
12411 isSourceDestroying() {
12412 (true && !(false) && (0, _debug.deprecate)('isSourceDestroying is deprecated, use the isDestroying() API to check the object destruction state directly instead', false, {
12413 id: 'meta-destruction-apis',
12414 until: '3.25.0'
12415 }));
12416 return (0, _runtime.isDestroying)(this.source);
12417 }
12418
12419 isSourceDestroyed() {
12420 (true && !(false) && (0, _debug.deprecate)('isSourceDestroyed is deprecated, use the isDestroyed() API to check the object destruction state directly instead', false, {
12421 id: 'meta-destruction-apis',
12422 until: '3.25.0'
12423 }));
12424 return (0, _runtime.isDestroyed)(this.source);
12425 }
12426
12427 setInitializing() {
12428 this._isInit = true;
12429 }
12430
12431 unsetInitializing() {
12432 this._isInit = false;
12433 }
12434
12435 isInitializing() {
12436 return this._isInit;
12437 }
12438
12439 isPrototypeMeta(obj) {
12440 return this.proto === this.source && this.source === obj;
12441 }
12442
12443 _getOrCreateOwnMap(key) {
12444 return this[key] || (this[key] = Object.create(null));
12445 }
12446
12447 _getOrCreateOwnSet(key) {
12448 return this[key] || (this[key] = new Set());
12449 }
12450
12451 _findInheritedMap(key, subkey) {
12452 var pointer = this;
12453
12454 while (pointer !== null) {
12455 var map = pointer[key];
12456
12457 if (map !== undefined) {
12458 var value = map.get(subkey);
12459
12460 if (value !== undefined) {
12461 return value;
12462 }
12463 }
12464
12465 pointer = pointer.parent;
12466 }
12467 }
12468
12469 _hasInInheritedSet(key, value) {
12470 var pointer = this;
12471
12472 while (pointer !== null) {
12473 var set = pointer[key];
12474
12475 if (set !== undefined && set.has(value)) {
12476 return true;
12477 }
12478
12479 pointer = pointer.parent;
12480 }
12481
12482 return false;
12483 }
12484
12485 valueFor(key) {
12486 var values = this._values;
12487 return values !== undefined ? values[key] : undefined;
12488 }
12489
12490 setValueFor(key, value) {
12491 var values = this._getOrCreateOwnMap('_values');
12492
12493 values[key] = value;
12494 }
12495
12496 revisionFor(key) {
12497 var revisions = this._revisions;
12498 return revisions !== undefined ? revisions[key] : undefined;
12499 }
12500
12501 setRevisionFor(key, revision) {
12502 var revisions = this._getOrCreateOwnMap('_revisions');
12503
12504 revisions[key] = revision;
12505 }
12506
12507 writableLazyChainsFor(key) {
12508 if (true
12509 /* DEBUG */
12510 ) {
12511 counters.writableLazyChainsCalls++;
12512 }
12513
12514 var lazyChains = this._getOrCreateOwnMap('_lazyChains');
12515
12516 var chains = lazyChains[key];
12517
12518 if (chains === undefined) {
12519 chains = lazyChains[key] = [];
12520 }
12521
12522 return chains;
12523 }
12524
12525 readableLazyChainsFor(key) {
12526 if (true
12527 /* DEBUG */
12528 ) {
12529 counters.readableLazyChainsCalls++;
12530 }
12531
12532 var lazyChains = this._lazyChains;
12533
12534 if (lazyChains !== undefined) {
12535 return lazyChains[key];
12536 }
12537
12538 return undefined;
12539 }
12540
12541 addMixin(mixin) {
12542 (true && !(!(0, _runtime.isDestroyed)(this.source)) && (0, _debug.assert)((0, _runtime.isDestroyed)(this.source) ? `Cannot add mixins of \`${(0, _utils.toString)(mixin)}\` on \`${(0, _utils.toString)(this.source)}\` call addMixin after it has been destroyed.` : '', !(0, _runtime.isDestroyed)(this.source)));
12543
12544 var set = this._getOrCreateOwnSet('_mixins');
12545
12546 set.add(mixin);
12547 }
12548
12549 hasMixin(mixin) {
12550 return this._hasInInheritedSet('_mixins', mixin);
12551 }
12552
12553 forEachMixins(fn) {
12554 var pointer = this;
12555 var seen;
12556
12557 while (pointer !== null) {
12558 var set = pointer._mixins;
12559
12560 if (set !== undefined) {
12561 seen = seen === undefined ? new Set() : seen; // TODO cleanup typing here
12562
12563 set.forEach(mixin => {
12564 if (!seen.has(mixin)) {
12565 seen.add(mixin);
12566 fn(mixin);
12567 }
12568 });
12569 }
12570
12571 pointer = pointer.parent;
12572 }
12573 }
12574
12575 writeDescriptors(subkey, value) {
12576 (true && !(!(0, _runtime.isDestroyed)(this.source)) && (0, _debug.assert)((0, _runtime.isDestroyed)(this.source) ? `Cannot update descriptors for \`${subkey}\` on \`${(0, _utils.toString)(this.source)}\` after it has been destroyed.` : '', !(0, _runtime.isDestroyed)(this.source)));
12577 var map = this._descriptors || (this._descriptors = new Map());
12578 map.set(subkey, value);
12579 }
12580
12581 peekDescriptors(subkey) {
12582 var possibleDesc = this._findInheritedMap('_descriptors', subkey);
12583
12584 return possibleDesc === UNDEFINED ? undefined : possibleDesc;
12585 }
12586
12587 removeDescriptors(subkey) {
12588 this.writeDescriptors(subkey, UNDEFINED);
12589 }
12590
12591 forEachDescriptors(fn) {
12592 var pointer = this;
12593 var seen;
12594
12595 while (pointer !== null) {
12596 var map = pointer._descriptors;
12597
12598 if (map !== undefined) {
12599 seen = seen === undefined ? new Set() : seen;
12600 map.forEach((value, key) => {
12601 if (!seen.has(key)) {
12602 seen.add(key);
12603
12604 if (value !== UNDEFINED) {
12605 fn(key, value);
12606 }
12607 }
12608 });
12609 }
12610
12611 pointer = pointer.parent;
12612 }
12613 }
12614
12615 addToListeners(eventName, target, method, once, sync) {
12616 if (true
12617 /* DEBUG */
12618 ) {
12619 counters.addToListenersCalls++;
12620 }
12621
12622 this.pushListener(eventName, target, method, once ? 1
12623 /* ONCE */
12624 : 0
12625 /* ADD */
12626 , sync);
12627 }
12628
12629 removeFromListeners(eventName, target, method) {
12630 if (true
12631 /* DEBUG */
12632 ) {
12633 counters.removeFromListenersCalls++;
12634 }
12635
12636 this.pushListener(eventName, target, method, 2
12637 /* REMOVE */
12638 );
12639 }
12640
12641 pushListener(event, target, method, kind, sync = false) {
12642 var listeners = this.writableListeners();
12643 var i = indexOfListener(listeners, event, target, method); // remove if found listener was inherited
12644
12645 if (i !== -1 && i < this._inheritedEnd) {
12646 listeners.splice(i, 1);
12647 this._inheritedEnd--;
12648 i = -1;
12649 } // if not found, push. Note that we must always push if a listener is not
12650 // found, even in the case of a function listener remove, because we may be
12651 // attempting to add or remove listeners _before_ flattening has occurred.
12652
12653
12654 if (i === -1) {
12655 (true && !(!(this.isPrototypeMeta(this.source) && typeof method === 'function')) && (0, _debug.assert)('You cannot add function listeners to prototypes. Convert the listener to a string listener, or add it to the instance instead.', !(this.isPrototypeMeta(this.source) && typeof method === 'function')));
12656 (true && !(!(!this.isPrototypeMeta(this.source) && typeof method === 'function' && kind === 2
12657 /* REMOVE */
12658 )) && (0, _debug.assert)('You attempted to remove a function listener which did not exist on the instance, which means you may have attempted to remove it before it was added.', !(!this.isPrototypeMeta(this.source) && typeof method === 'function' && kind === 2)));
12659 listeners.push({
12660 event,
12661 target,
12662 method,
12663 kind,
12664 sync
12665 });
12666 } else {
12667 var listener = listeners[i]; // If the listener is our own listener and we are trying to remove it, we
12668 // want to splice it out entirely so we don't hold onto a reference.
12669
12670 if (kind === 2
12671 /* REMOVE */
12672 && listener.kind !== 2
12673 /* REMOVE */
12674 ) {
12675 listeners.splice(i, 1);
12676 } else {
12677 (true && !(!(listener.kind === 0
12678 /* ADD */
12679 && kind === 0
12680 /* ADD */
12681 && listener.sync !== sync)) && (0, _debug.assert)(`You attempted to add an observer for the same method on '${event.split(':')[0]}' twice to ${target} as both sync and async. Observers must be either sync or async, they cannot be both. This is likely a mistake, you should either remove the code that added the observer a second time, or update it to always be sync or async. The method was ${method}.`, !(listener.kind === 0 && kind === 0 && listener.sync !== sync))); // update own listener
12682
12683 listener.kind = kind;
12684 listener.sync = sync;
12685 }
12686 }
12687 }
12688
12689 writableListeners() {
12690 // Check if we need to invalidate and reflatten. We need to do this if we
12691 // have already flattened (flattened version is the current version) and
12692 // we are either writing to a prototype meta OR we have never inherited, and
12693 // may have cached the parent's listeners.
12694 if (this._flattenedVersion === currentListenerVersion && (this.source === this.proto || this._inheritedEnd === -1)) {
12695 if (true
12696 /* DEBUG */
12697 ) {
12698 counters.reopensAfterFlatten++;
12699 }
12700
12701 currentListenerVersion++;
12702 } // Inherited end has not been set, then we have never created our own
12703 // listeners, but may have cached the parent's
12704
12705
12706 if (this._inheritedEnd === -1) {
12707 this._inheritedEnd = 0;
12708 this._listeners = [];
12709 }
12710
12711 return this._listeners;
12712 }
12713 /**
12714 Flattening is based on a global revision counter. If the revision has
12715 bumped it means that somewhere in a class inheritance chain something has
12716 changed, so we need to reflatten everything. This can only happen if:
12717 1. A meta has been flattened (listener has been called)
12718 2. The meta is a prototype meta with children who have inherited its
12719 listeners
12720 3. A new listener is subsequently added to the meta (e.g. via `.reopen()`)
12721 This is a very rare occurrence, so while the counter is global it shouldn't
12722 be updated very often in practice.
12723 */
12724
12725
12726 flattenedListeners() {
12727 if (true
12728 /* DEBUG */
12729 ) {
12730 counters.flattenedListenersCalls++;
12731 }
12732
12733 if (this._flattenedVersion < currentListenerVersion) {
12734 if (true
12735 /* DEBUG */
12736 ) {
12737 counters.listenersFlattened++;
12738 }
12739
12740 var parent = this.parent;
12741
12742 if (parent !== null) {
12743 // compute
12744 var parentListeners = parent.flattenedListeners();
12745
12746 if (parentListeners !== undefined) {
12747 if (this._listeners === undefined) {
12748 // If this instance doesn't have any of its own listeners (writableListeners
12749 // has never been called) then we don't need to do any flattening, return
12750 // the parent's listeners instead.
12751 if (true
12752 /* DEBUG */
12753 ) {
12754 counters.parentListenersUsed++;
12755 }
12756
12757 this._listeners = parentListeners;
12758 } else {
12759 var listeners = this._listeners;
12760
12761 if (this._inheritedEnd > 0) {
12762 listeners.splice(0, this._inheritedEnd);
12763 this._inheritedEnd = 0;
12764 }
12765
12766 for (var i = 0; i < parentListeners.length; i++) {
12767 var listener = parentListeners[i];
12768 var index = indexOfListener(listeners, listener.event, listener.target, listener.method);
12769
12770 if (index === -1) {
12771 if (true
12772 /* DEBUG */
12773 ) {
12774 counters.listenersInherited++;
12775 }
12776
12777 listeners.unshift(listener);
12778 this._inheritedEnd++;
12779 }
12780 }
12781 }
12782 }
12783 }
12784
12785 this._flattenedVersion = currentListenerVersion;
12786 }
12787
12788 return this._listeners;
12789 }
12790
12791 matchingListeners(eventName) {
12792 var listeners = this.flattenedListeners();
12793 var result;
12794
12795 if (true
12796 /* DEBUG */
12797 ) {
12798 counters.matchingListenersCalls++;
12799 }
12800
12801 if (listeners !== undefined) {
12802 for (var index = 0; index < listeners.length; index++) {
12803 var listener = listeners[index]; // REMOVE listeners are placeholders that tell us not to
12804 // inherit, so they never match. Only ADD and ONCE can match.
12805
12806 if (listener.event === eventName && (listener.kind === 0
12807 /* ADD */
12808 || listener.kind === 1
12809 /* ONCE */
12810 )) {
12811 if (result === undefined) {
12812 // we create this array only after we've found a listener that
12813 // matches to avoid allocations when no matches are found.
12814 result = [];
12815 }
12816
12817 result.push(listener.target, listener.method, listener.kind === 1
12818 /* ONCE */
12819 );
12820 }
12821 }
12822 }
12823
12824 return result;
12825 }
12826
12827 observerEvents() {
12828 var listeners = this.flattenedListeners();
12829 var result;
12830
12831 if (true
12832 /* DEBUG */
12833 ) {
12834 counters.observerEventsCalls++;
12835 }
12836
12837 if (listeners !== undefined) {
12838 for (var index = 0; index < listeners.length; index++) {
12839 var listener = listeners[index]; // REMOVE listeners are placeholders that tell us not to
12840 // inherit, so they never match. Only ADD and ONCE can match.
12841
12842 if ((listener.kind === 0
12843 /* ADD */
12844 || listener.kind === 1
12845 /* ONCE */
12846 ) && listener.event.indexOf(':change') !== -1) {
12847 if (result === undefined) {
12848 // we create this array only after we've found a listener that
12849 // matches to avoid allocations when no matches are found.
12850 result = [];
12851 }
12852
12853 result.push(listener);
12854 }
12855 }
12856 }
12857
12858 return result;
12859 }
12860
12861 }
12862
12863 _exports.Meta = Meta;
12864 var getPrototypeOf = Object.getPrototypeOf;
12865 var metaStore = new WeakMap();
12866
12867 function setMeta(obj, meta) {
12868 (true && !(obj !== null) && (0, _debug.assert)('Cannot call `setMeta` on null', obj !== null));
12869 (true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `setMeta` on undefined', obj !== undefined));
12870 (true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`setMeta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'));
12871
12872 if (true
12873 /* DEBUG */
12874 ) {
12875 counters.setCalls++;
12876 }
12877
12878 metaStore.set(obj, meta);
12879 }
12880
12881 function peekMeta(obj) {
12882 (true && !(obj !== null) && (0, _debug.assert)('Cannot call `peekMeta` on null', obj !== null));
12883 (true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `peekMeta` on undefined', obj !== undefined));
12884 (true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`peekMeta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'));
12885
12886 if (true
12887 /* DEBUG */
12888 ) {
12889 counters.peekCalls++;
12890 }
12891
12892 var meta = metaStore.get(obj);
12893
12894 if (meta !== undefined) {
12895 return meta;
12896 }
12897
12898 var pointer = getPrototypeOf(obj);
12899
12900 while (pointer !== null) {
12901 if (true
12902 /* DEBUG */
12903 ) {
12904 counters.peekPrototypeWalks++;
12905 }
12906
12907 meta = metaStore.get(pointer);
12908
12909 if (meta !== undefined) {
12910 if (meta.proto !== pointer) {
12911 // The meta was a prototype meta which was not marked as initializing.
12912 // This can happen when a prototype chain was created manually via
12913 // Object.create() and the source object does not have a constructor.
12914 meta.proto = pointer;
12915 }
12916
12917 return meta;
12918 }
12919
12920 pointer = getPrototypeOf(pointer);
12921 }
12922
12923 return null;
12924 }
12925 /**
12926 Retrieves the meta hash for an object. If `writable` is true ensures the
12927 hash is writable for this object as well.
12928
12929 The meta object contains information about computed property descriptors as
12930 well as any watched properties and other information. You generally will
12931 not access this information directly but instead work with higher level
12932 methods that manipulate this hash indirectly.
12933
12934 @method meta
12935 @for Ember
12936 @private
12937
12938 @param {Object} obj The object to retrieve meta for
12939 @param {Boolean} [writable=true] Pass `false` if you do not intend to modify
12940 the meta hash, allowing the method to avoid making an unnecessary copy.
12941 @return {Object} the meta hash for an object
12942 */
12943
12944
12945 var meta = function meta(obj) {
12946 (true && !(obj !== null) && (0, _debug.assert)('Cannot call `meta` on null', obj !== null));
12947 (true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `meta` on undefined', obj !== undefined));
12948 (true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`meta\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'));
12949
12950 if (true
12951 /* DEBUG */
12952 ) {
12953 counters.metaCalls++;
12954 }
12955
12956 var maybeMeta = peekMeta(obj); // remove this code, in-favor of explicit parent
12957
12958 if (maybeMeta !== null && maybeMeta.source === obj) {
12959 return maybeMeta;
12960 }
12961
12962 var newMeta = new Meta(obj);
12963 setMeta(obj, newMeta);
12964 return newMeta;
12965 };
12966
12967 _exports.meta = meta;
12968
12969 if (true
12970 /* DEBUG */
12971 ) {
12972 meta._counters = counters;
12973 }
12974
12975 function indexOfListener(listeners, event, target, method) {
12976 for (var i = listeners.length - 1; i >= 0; i--) {
12977 var listener = listeners[i];
12978
12979 if (listener.event === event && listener.target === target && listener.method === method) {
12980 return i;
12981 }
12982 }
12983
12984 return -1;
12985 }
12986});
12987define("@ember/-internals/metal/index", ["exports", "@ember/-internals/meta", "@ember/-internals/utils", "@ember/debug", "@ember/-internals/environment", "@ember/runloop", "@glimmer/runtime", "@glimmer/validator", "@ember/polyfills", "@ember/error", "ember/version", "@ember/deprecated-features", "@ember/-internals/owner"], function (_exports, _meta2, _utils, _debug, _environment, _runloop, _runtime, _validator, _polyfills, _error, _version, _deprecatedFeatures, _owner) {
12988 "use strict";
12989
12990 Object.defineProperty(_exports, "__esModule", {
12991 value: true
12992 });
12993 _exports.computed = computed;
12994 _exports.autoComputed = autoComputed;
12995 _exports.isComputed = isComputed;
12996 _exports.getCachedValueFor = getCachedValueFor;
12997 _exports.alias = alias;
12998 _exports.deprecateProperty = deprecateProperty;
12999 _exports._getPath = _getPath;
13000 _exports.get = get;
13001 _exports.getWithDefault = getWithDefault;
13002 _exports._getProp = _getProp;
13003 _exports.set = set;
13004 _exports.trySet = trySet;
13005 _exports.objectAt = objectAt;
13006 _exports.replace = replace;
13007 _exports.replaceInNativeArray = replaceInNativeArray;
13008 _exports.addArrayObserver = addArrayObserver;
13009 _exports.removeArrayObserver = removeArrayObserver;
13010 _exports.arrayContentWillChange = arrayContentWillChange;
13011 _exports.arrayContentDidChange = arrayContentDidChange;
13012 _exports.eachProxyArrayWillChange = eachProxyArrayWillChange;
13013 _exports.eachProxyArrayDidChange = eachProxyArrayDidChange;
13014 _exports.addListener = addListener;
13015 _exports.hasListeners = hasListeners;
13016 _exports.on = on;
13017 _exports.removeListener = removeListener;
13018 _exports.sendEvent = sendEvent;
13019 _exports.isNone = isNone;
13020 _exports.isEmpty = isEmpty;
13021 _exports.isBlank = isBlank;
13022 _exports.isPresent = isPresent;
13023 _exports.beginPropertyChanges = beginPropertyChanges;
13024 _exports.changeProperties = changeProperties;
13025 _exports.endPropertyChanges = endPropertyChanges;
13026 _exports.notifyPropertyChange = notifyPropertyChange;
13027 _exports.defineProperty = defineProperty;
13028 _exports.isElementDescriptor = isElementDescriptor;
13029 _exports.nativeDescDecorator = nativeDescDecorator;
13030 _exports.descriptorForDecorator = descriptorForDecorator;
13031 _exports.descriptorForProperty = descriptorForProperty;
13032 _exports.isClassicDecorator = isClassicDecorator;
13033 _exports.setClassicDecorator = setClassicDecorator;
13034 _exports.getProperties = getProperties;
13035 _exports.setProperties = setProperties;
13036 _exports.expandProperties = expandProperties;
13037 _exports.addObserver = addObserver;
13038 _exports.activateObserver = activateObserver;
13039 _exports.removeObserver = removeObserver;
13040 _exports.flushAsyncObservers = flushAsyncObservers;
13041 _exports.mixin = mixin;
13042 _exports.observer = observer;
13043 _exports.applyMixin = applyMixin;
13044 _exports.inject = inject;
13045 _exports.tagForProperty = tagForProperty;
13046 _exports.tagForObject = tagForObject;
13047 _exports.markObjectAsDirty = markObjectAsDirty;
13048 _exports.tracked = tracked;
13049 _exports.addNamespace = addNamespace;
13050 _exports.classToString = classToString;
13051 _exports.findNamespace = findNamespace;
13052 _exports.findNamespaces = findNamespaces;
13053 _exports.processNamespace = processNamespace;
13054 _exports.processAllNamespaces = processAllNamespaces;
13055 _exports.removeNamespace = removeNamespace;
13056 _exports.isNamespaceSearchDisabled = isSearchDisabled;
13057 _exports.setNamespaceSearchDisabled = setSearchDisabled;
13058 Object.defineProperty(_exports, "createCache", {
13059 enumerable: true,
13060 get: function () {
13061 return _validator.createCache;
13062 }
13063 });
13064 Object.defineProperty(_exports, "getValue", {
13065 enumerable: true,
13066 get: function () {
13067 return _validator.getValue;
13068 }
13069 });
13070 Object.defineProperty(_exports, "isConst", {
13071 enumerable: true,
13072 get: function () {
13073 return _validator.isConst;
13074 }
13075 });
13076 _exports.NAMESPACES_BY_ID = _exports.NAMESPACES = _exports.CUSTOM_TAG_FOR = _exports.DEBUG_INJECTION_FUNCTIONS = _exports.aliasMethod = _exports.Mixin = _exports.SYNC_OBSERVERS = _exports.ASYNC_OBSERVERS = _exports.Libraries = _exports.libraries = _exports.PROPERTY_DID_CHANGE = _exports.PROXY_CONTENT = _exports.ComputedProperty = _exports._globalsComputed = void 0;
13077
13078 /**
13079 @module @ember/object
13080 */
13081
13082 /*
13083 The event system uses a series of nested hashes to store listeners on an
13084 object. When a listener is registered, or when an event arrives, these
13085 hashes are consulted to determine which target and action pair to invoke.
13086
13087 The hashes are stored in the object's meta hash, and look like this:
13088
13089 // Object's meta hash
13090 {
13091 listeners: { // variable name: `listenerSet`
13092 "foo:change": [ // variable name: `actions`
13093 target, method, once
13094 ]
13095 }
13096 }
13097
13098 */
13099
13100 /**
13101 Add an event listener
13102
13103 @method addListener
13104 @static
13105 @for @ember/object/events
13106 @param obj
13107 @param {String} eventName
13108 @param {Object|Function} target A target object or a function
13109 @param {Function|String} method A function or the name of a function to be called on `target`
13110 @param {Boolean} once A flag whether a function should only be called once
13111 @public
13112 */
13113 function addListener(obj, eventName, target, method, once, sync = true) {
13114 (true && !(Boolean(obj) && Boolean(eventName)) && (0, _debug.assert)('You must pass at least an object and event name to addListener', Boolean(obj) && Boolean(eventName)));
13115
13116 if (!method && 'function' === typeof target) {
13117 method = target;
13118 target = null;
13119 }
13120
13121 (0, _meta2.meta)(obj).addToListeners(eventName, target, method, once === true, sync);
13122 }
13123 /**
13124 Remove an event listener
13125
13126 Arguments should match those passed to `addListener`.
13127
13128 @method removeListener
13129 @static
13130 @for @ember/object/events
13131 @param obj
13132 @param {String} eventName
13133 @param {Object|Function} target A target object or a function
13134 @param {Function|String} method A function or the name of a function to be called on `target`
13135 @public
13136 */
13137
13138
13139 function removeListener(obj, eventName, targetOrFunction, functionOrName) {
13140 (true && !(Boolean(obj) && Boolean(eventName) && (typeof targetOrFunction === 'function' || typeof targetOrFunction === 'object' && Boolean(functionOrName))) && (0, _debug.assert)('You must pass at least an object, event name, and method or target and method/method name to removeListener', Boolean(obj) && Boolean(eventName) && (typeof targetOrFunction === 'function' || typeof targetOrFunction === 'object' && Boolean(functionOrName))));
13141 var target, method;
13142
13143 if (typeof targetOrFunction === 'object') {
13144 target = targetOrFunction;
13145 method = functionOrName;
13146 } else {
13147 target = null;
13148 method = targetOrFunction;
13149 }
13150
13151 var m = (0, _meta2.meta)(obj);
13152 m.removeFromListeners(eventName, target, method);
13153 }
13154 /**
13155 Send an event. The execution of suspended listeners
13156 is skipped, and once listeners are removed. A listener without
13157 a target is executed on the passed object. If an array of actions
13158 is not passed, the actions stored on the passed object are invoked.
13159
13160 @method sendEvent
13161 @static
13162 @for @ember/object/events
13163 @param obj
13164 @param {String} eventName
13165 @param {Array} params Optional parameters for each listener.
13166 @return {Boolean} if the event was delivered to one or more actions
13167 @public
13168 */
13169
13170
13171 function sendEvent(obj, eventName, params, actions, _meta) {
13172 if (actions === undefined) {
13173 var meta$$1 = _meta === undefined ? (0, _meta2.peekMeta)(obj) : _meta;
13174 actions = meta$$1 !== null ? meta$$1.matchingListeners(eventName) : undefined;
13175 }
13176
13177 if (actions === undefined || actions.length === 0) {
13178 return false;
13179 }
13180
13181 for (var i = actions.length - 3; i >= 0; i -= 3) {
13182 // looping in reverse for once listeners
13183 var target = actions[i];
13184 var method = actions[i + 1];
13185 var once = actions[i + 2];
13186
13187 if (!method) {
13188 continue;
13189 }
13190
13191 if (once) {
13192 removeListener(obj, eventName, target, method);
13193 }
13194
13195 if (!target) {
13196 target = obj;
13197 }
13198
13199 var type = typeof method;
13200
13201 if (type === 'string' || type === 'symbol') {
13202 method = target[method];
13203 }
13204
13205 method.apply(target, params);
13206 }
13207
13208 return true;
13209 }
13210 /**
13211 @private
13212 @method hasListeners
13213 @static
13214 @for @ember/object/events
13215 @param obj
13216 @param {String} eventName
13217 @return {Boolean} if `obj` has listeners for event `eventName`
13218 */
13219
13220
13221 function hasListeners(obj, eventName) {
13222 var meta$$1 = (0, _meta2.peekMeta)(obj);
13223
13224 if (meta$$1 === null) {
13225 return false;
13226 }
13227
13228 var matched = meta$$1.matchingListeners(eventName);
13229 return matched !== undefined && matched.length > 0;
13230 }
13231 /**
13232 Define a property as a function that should be executed when
13233 a specified event or events are triggered.
13234
13235 ``` javascript
13236 import EmberObject from '@ember/object';
13237 import { on } from '@ember/object/evented';
13238 import { sendEvent } from '@ember/object/events';
13239
13240 let Job = EmberObject.extend({
13241 logCompleted: on('completed', function() {
13242 console.log('Job completed!');
13243 })
13244 });
13245
13246 let job = Job.create();
13247
13248 sendEvent(job, 'completed'); // Logs 'Job completed!'
13249 ```
13250
13251 @method on
13252 @static
13253 @for @ember/object/evented
13254 @param {String} eventNames*
13255 @param {Function} func
13256 @return {Function} the listener function, passed as last argument to on(...)
13257 @public
13258 */
13259
13260
13261 function on(...args) {
13262 var func = args.pop();
13263 var events = args;
13264 (true && !(typeof func === 'function') && (0, _debug.assert)('on expects function as last argument', typeof func === 'function'));
13265 (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)));
13266 (0, _utils.setListeners)(func, events);
13267 return func;
13268 }
13269
13270 var AFTER_OBSERVERS = ':change';
13271
13272 function changeEvent(keyName) {
13273 return keyName + AFTER_OBSERVERS;
13274 }
13275
13276 var SYNC_DEFAULT = !_environment.ENV._DEFAULT_ASYNC_OBSERVERS;
13277 var SYNC_OBSERVERS = new Map();
13278 _exports.SYNC_OBSERVERS = SYNC_OBSERVERS;
13279 var ASYNC_OBSERVERS = new Map();
13280 /**
13281 @module @ember/object
13282 */
13283
13284 /**
13285 @method addObserver
13286 @static
13287 @for @ember/object/observers
13288 @param obj
13289 @param {String} path
13290 @param {Object|Function} target
13291 @param {Function|String} [method]
13292 @public
13293 */
13294
13295 _exports.ASYNC_OBSERVERS = ASYNC_OBSERVERS;
13296
13297 function addObserver(obj, path, target, method, sync = SYNC_DEFAULT) {
13298 var eventName = changeEvent(path);
13299 addListener(obj, eventName, target, method, false, sync);
13300 var meta$$1 = (0, _meta2.peekMeta)(obj);
13301
13302 if (meta$$1 === null || !(meta$$1.isPrototypeMeta(obj) || meta$$1.isInitializing())) {
13303 activateObserver(obj, eventName, sync);
13304 }
13305 }
13306 /**
13307 @method removeObserver
13308 @static
13309 @for @ember/object/observers
13310 @param obj
13311 @param {String} path
13312 @param {Object|Function} target
13313 @param {Function|String} [method]
13314 @public
13315 */
13316
13317
13318 function removeObserver(obj, path, target, method, sync = SYNC_DEFAULT) {
13319 var eventName = changeEvent(path);
13320 var meta$$1 = (0, _meta2.peekMeta)(obj);
13321
13322 if (meta$$1 === null || !(meta$$1.isPrototypeMeta(obj) || meta$$1.isInitializing())) {
13323 deactivateObserver(obj, eventName, sync);
13324 }
13325
13326 removeListener(obj, eventName, target, method);
13327 }
13328
13329 function getOrCreateActiveObserversFor(target, sync) {
13330 var observerMap = sync === true ? SYNC_OBSERVERS : ASYNC_OBSERVERS;
13331
13332 if (!observerMap.has(target)) {
13333 observerMap.set(target, new Map());
13334 (0, _runtime.registerDestructor)(target, () => destroyObservers(target), true);
13335 }
13336
13337 return observerMap.get(target);
13338 }
13339
13340 function activateObserver(target, eventName, sync = false) {
13341 var activeObservers = getOrCreateActiveObserversFor(target, sync);
13342
13343 if (activeObservers.has(eventName)) {
13344 activeObservers.get(eventName).count++;
13345 } else {
13346 var [path] = eventName.split(':');
13347 var tag = getChainTagsForKey(target, path, (0, _validator.tagMetaFor)(target), (0, _meta2.peekMeta)(target));
13348 activeObservers.set(eventName, {
13349 count: 1,
13350 path,
13351 tag,
13352 lastRevision: (0, _validator.valueForTag)(tag),
13353 suspended: false
13354 });
13355 }
13356 }
13357
13358 var DEACTIVATE_SUSPENDED = false;
13359 var SCHEDULED_DEACTIVATE = [];
13360
13361 function deactivateObserver(target, eventName, sync = false) {
13362 if (DEACTIVATE_SUSPENDED === true) {
13363 SCHEDULED_DEACTIVATE.push([target, eventName, sync]);
13364 return;
13365 }
13366
13367 var observerMap = sync === true ? SYNC_OBSERVERS : ASYNC_OBSERVERS;
13368 var activeObservers = observerMap.get(target);
13369
13370 if (activeObservers !== undefined) {
13371 var _observer = activeObservers.get(eventName);
13372
13373 _observer.count--;
13374
13375 if (_observer.count === 0) {
13376 activeObservers.delete(eventName);
13377
13378 if (activeObservers.size === 0) {
13379 observerMap.delete(target);
13380 }
13381 }
13382 }
13383 }
13384
13385 function suspendedObserverDeactivation() {
13386 DEACTIVATE_SUSPENDED = true;
13387 }
13388
13389 function resumeObserverDeactivation() {
13390 DEACTIVATE_SUSPENDED = false;
13391
13392 for (var [target, eventName, sync] of SCHEDULED_DEACTIVATE) {
13393 deactivateObserver(target, eventName, sync);
13394 }
13395
13396 SCHEDULED_DEACTIVATE = [];
13397 }
13398 /**
13399 * Primarily used for cases where we are redefining a class, e.g. mixins/reopen
13400 * being applied later. Revalidates all the observers, resetting their tags.
13401 *
13402 * @private
13403 * @param target
13404 */
13405
13406
13407 function revalidateObservers(target) {
13408 if (ASYNC_OBSERVERS.has(target)) {
13409 ASYNC_OBSERVERS.get(target).forEach(observer => {
13410 observer.tag = getChainTagsForKey(target, observer.path, (0, _validator.tagMetaFor)(target), (0, _meta2.peekMeta)(target));
13411 observer.lastRevision = (0, _validator.valueForTag)(observer.tag);
13412 });
13413 }
13414
13415 if (SYNC_OBSERVERS.has(target)) {
13416 SYNC_OBSERVERS.get(target).forEach(observer => {
13417 observer.tag = getChainTagsForKey(target, observer.path, (0, _validator.tagMetaFor)(target), (0, _meta2.peekMeta)(target));
13418 observer.lastRevision = (0, _validator.valueForTag)(observer.tag);
13419 });
13420 }
13421 }
13422
13423 var lastKnownRevision = 0;
13424
13425 function flushAsyncObservers(shouldSchedule = true) {
13426 var currentRevision = (0, _validator.valueForTag)(_validator.CURRENT_TAG);
13427
13428 if (lastKnownRevision === currentRevision) {
13429 return;
13430 }
13431
13432 lastKnownRevision = currentRevision;
13433 ASYNC_OBSERVERS.forEach((activeObservers, target) => {
13434 var meta$$1 = (0, _meta2.peekMeta)(target);
13435 activeObservers.forEach((observer, eventName) => {
13436 if (!(0, _validator.validateTag)(observer.tag, observer.lastRevision)) {
13437 var sendObserver = () => {
13438 try {
13439 sendEvent(target, eventName, [target, observer.path], undefined, meta$$1);
13440 } finally {
13441 observer.tag = getChainTagsForKey(target, observer.path, (0, _validator.tagMetaFor)(target), (0, _meta2.peekMeta)(target));
13442 observer.lastRevision = (0, _validator.valueForTag)(observer.tag);
13443 }
13444 };
13445
13446 if (shouldSchedule) {
13447 (0, _runloop.schedule)('actions', sendObserver);
13448 } else {
13449 sendObserver();
13450 }
13451 }
13452 });
13453 });
13454 }
13455
13456 function flushSyncObservers() {
13457 // When flushing synchronous observers, we know that something has changed (we
13458 // only do this during a notifyPropertyChange), so there's no reason to check
13459 // a global revision.
13460 SYNC_OBSERVERS.forEach((activeObservers, target) => {
13461 var meta$$1 = (0, _meta2.peekMeta)(target);
13462 activeObservers.forEach((observer, eventName) => {
13463 if (!observer.suspended && !(0, _validator.validateTag)(observer.tag, observer.lastRevision)) {
13464 try {
13465 observer.suspended = true;
13466 sendEvent(target, eventName, [target, observer.path], undefined, meta$$1);
13467 } finally {
13468 observer.tag = getChainTagsForKey(target, observer.path, (0, _validator.tagMetaFor)(target), (0, _meta2.peekMeta)(target));
13469 observer.lastRevision = (0, _validator.valueForTag)(observer.tag);
13470 observer.suspended = false;
13471 }
13472 }
13473 });
13474 });
13475 }
13476
13477 function setObserverSuspended(target, property, suspended) {
13478 var activeObservers = SYNC_OBSERVERS.get(target);
13479
13480 if (!activeObservers) {
13481 return;
13482 }
13483
13484 var observer = activeObservers.get(changeEvent(property));
13485
13486 if (observer) {
13487 observer.suspended = suspended;
13488 }
13489 }
13490
13491 function destroyObservers(target) {
13492 if (SYNC_OBSERVERS.size > 0) SYNC_OBSERVERS.delete(target);
13493 if (ASYNC_OBSERVERS.size > 0) ASYNC_OBSERVERS.delete(target);
13494 }
13495
13496 var CUSTOM_TAG_FOR = (0, _utils.enumerableSymbol)('CUSTOM_TAG_FOR'); // This is exported for `@tracked`, but should otherwise be avoided. Use `tagForObject`.
13497
13498 _exports.CUSTOM_TAG_FOR = CUSTOM_TAG_FOR;
13499 var SELF_TAG = (0, _utils.symbol)('SELF_TAG');
13500
13501 function tagForProperty(obj, propertyKey, addMandatorySetter = false, meta$$1) {
13502 if (typeof obj[CUSTOM_TAG_FOR] === 'function') {
13503 return obj[CUSTOM_TAG_FOR](propertyKey, addMandatorySetter);
13504 }
13505
13506 var tag = (0, _validator.tagFor)(obj, propertyKey, meta$$1);
13507
13508 if (true
13509 /* DEBUG */
13510 && addMandatorySetter) {
13511 (0, _utils.setupMandatorySetter)(tag, obj, propertyKey);
13512 }
13513
13514 return tag;
13515 }
13516
13517 function tagForObject(obj) {
13518 if ((0, _utils.isObject)(obj)) {
13519 if (true
13520 /* DEBUG */
13521 ) {
13522 (true && !(!(0, _runtime.isDestroyed)(obj)) && (0, _debug.assert)((0, _runtime.isDestroyed)(obj) ? `Cannot create a new tag for \`${(0, _utils.toString)(obj)}\` after it has been destroyed.` : '', !(0, _runtime.isDestroyed)(obj)));
13523 }
13524
13525 return (0, _validator.tagFor)(obj, SELF_TAG);
13526 }
13527
13528 return _validator.CONSTANT_TAG;
13529 }
13530
13531 function markObjectAsDirty(obj, propertyKey) {
13532 (0, _validator.dirtyTagFor)(obj, propertyKey);
13533 (0, _validator.dirtyTagFor)(obj, SELF_TAG);
13534 }
13535 /**
13536 @module ember
13537 @private
13538 */
13539
13540
13541 var PROPERTY_DID_CHANGE = (0, _utils.enumerableSymbol)('PROPERTY_DID_CHANGE');
13542 _exports.PROPERTY_DID_CHANGE = PROPERTY_DID_CHANGE;
13543 var deferred = 0;
13544 /**
13545 This function is called just after an object property has changed.
13546 It will notify any observers and clear caches among other things.
13547
13548 Normally you will not need to call this method directly but if for some
13549 reason you can't directly watch a property you can invoke this method
13550 manually.
13551
13552 @method notifyPropertyChange
13553 @for @ember/object
13554 @param {Object} obj The object with the property that will change
13555 @param {String} keyName The property key (or path) that will change.
13556 @param {Meta} [_meta] The objects meta.
13557 @param {unknown} [value] The new value to set for the property
13558 @return {void}
13559 @since 3.1.0
13560 @public
13561 */
13562
13563 function notifyPropertyChange(obj, keyName, _meta, value) {
13564 var meta$$1 = _meta === undefined ? (0, _meta2.peekMeta)(obj) : _meta;
13565
13566 if (meta$$1 !== null && (meta$$1.isInitializing() || meta$$1.isPrototypeMeta(obj))) {
13567 return;
13568 }
13569
13570 markObjectAsDirty(obj, keyName);
13571
13572 if (deferred <= 0) {
13573 flushSyncObservers();
13574 }
13575
13576 if (PROPERTY_DID_CHANGE in obj) {
13577 // we need to check the arguments length here; there's a check in `PROPERTY_DID_CHANGE`
13578 // that checks its arguments length, so we have to explicitly not call this with `value`
13579 // if it is not passed to `notifyPropertyChange`
13580 if (arguments.length === 4) {
13581 obj[PROPERTY_DID_CHANGE](keyName, value);
13582 } else {
13583 obj[PROPERTY_DID_CHANGE](keyName);
13584 }
13585 }
13586 }
13587 /**
13588 @method beginPropertyChanges
13589 @chainable
13590 @private
13591 */
13592
13593
13594 function beginPropertyChanges() {
13595 deferred++;
13596 suspendedObserverDeactivation();
13597 }
13598 /**
13599 @method endPropertyChanges
13600 @private
13601 */
13602
13603
13604 function endPropertyChanges() {
13605 deferred--;
13606
13607 if (deferred <= 0) {
13608 flushSyncObservers();
13609 resumeObserverDeactivation();
13610 }
13611 }
13612 /**
13613 Make a series of property changes together in an
13614 exception-safe way.
13615
13616 ```javascript
13617 Ember.changeProperties(function() {
13618 obj1.set('foo', mayBlowUpWhenSet);
13619 obj2.set('bar', baz);
13620 });
13621 ```
13622
13623 @method changeProperties
13624 @param {Function} callback
13625 @private
13626 */
13627
13628
13629 function changeProperties(callback) {
13630 beginPropertyChanges();
13631
13632 try {
13633 callback();
13634 } finally {
13635 endPropertyChanges();
13636 }
13637 }
13638
13639 function arrayContentWillChange(array, startIdx, removeAmt, addAmt) {
13640 // if no args are passed assume everything changes
13641 if (startIdx === undefined) {
13642 startIdx = 0;
13643 removeAmt = addAmt = -1;
13644 } else {
13645 if (removeAmt === undefined) {
13646 removeAmt = -1;
13647 }
13648
13649 if (addAmt === undefined) {
13650 addAmt = -1;
13651 }
13652 }
13653
13654 sendEvent(array, '@array:before', [array, startIdx, removeAmt, addAmt]);
13655 return array;
13656 }
13657
13658 function arrayContentDidChange(array, startIdx, removeAmt, addAmt, notify = true) {
13659 // if no args are passed assume everything changes
13660 if (startIdx === undefined) {
13661 startIdx = 0;
13662 removeAmt = addAmt = -1;
13663 } else {
13664 if (removeAmt === undefined) {
13665 removeAmt = -1;
13666 }
13667
13668 if (addAmt === undefined) {
13669 addAmt = -1;
13670 }
13671 }
13672
13673 var meta$$1 = (0, _meta2.peekMeta)(array);
13674
13675 if (notify) {
13676 if (addAmt < 0 || removeAmt < 0 || addAmt - removeAmt !== 0) {
13677 notifyPropertyChange(array, 'length', meta$$1);
13678 }
13679
13680 notifyPropertyChange(array, '[]', meta$$1);
13681 }
13682
13683 sendEvent(array, '@array:change', [array, startIdx, removeAmt, addAmt]);
13684
13685 if (meta$$1 !== null) {
13686 var length = array.length;
13687 var addedAmount = addAmt === -1 ? 0 : addAmt;
13688 var removedAmount = removeAmt === -1 ? 0 : removeAmt;
13689 var delta = addedAmount - removedAmount;
13690 var previousLength = length - delta;
13691 var normalStartIdx = startIdx < 0 ? previousLength + startIdx : startIdx;
13692
13693 if (meta$$1.revisionFor('firstObject') !== undefined && normalStartIdx === 0) {
13694 notifyPropertyChange(array, 'firstObject', meta$$1);
13695 }
13696
13697 if (meta$$1.revisionFor('lastObject') !== undefined) {
13698 var previousLastIndex = previousLength - 1;
13699 var lastAffectedIndex = normalStartIdx + removedAmount;
13700
13701 if (previousLastIndex < lastAffectedIndex) {
13702 notifyPropertyChange(array, 'lastObject', meta$$1);
13703 }
13704 }
13705 }
13706
13707 return array;
13708 }
13709
13710 var EMPTY_ARRAY = Object.freeze([]);
13711
13712 function objectAt(array, index) {
13713 if (Array.isArray(array)) {
13714 return array[index];
13715 } else {
13716 return array.objectAt(index);
13717 }
13718 }
13719
13720 function replace(array, start, deleteCount, items = EMPTY_ARRAY) {
13721 if (Array.isArray(array)) {
13722 replaceInNativeArray(array, start, deleteCount, items);
13723 } else {
13724 array.replace(start, deleteCount, items);
13725 }
13726 }
13727
13728 var CHUNK_SIZE = 60000; // To avoid overflowing the stack, we splice up to CHUNK_SIZE items at a time.
13729 // See https://code.google.com/p/chromium/issues/detail?id=56588 for more details.
13730
13731 function replaceInNativeArray(array, start, deleteCount, items) {
13732 arrayContentWillChange(array, start, deleteCount, items.length);
13733
13734 if (items.length <= CHUNK_SIZE) {
13735 array.splice(start, deleteCount, ...items);
13736 } else {
13737 array.splice(start, deleteCount);
13738
13739 for (var i = 0; i < items.length; i += CHUNK_SIZE) {
13740 var chunk = items.slice(i, i + CHUNK_SIZE);
13741 array.splice(start + i, 0, ...chunk);
13742 }
13743 }
13744
13745 arrayContentDidChange(array, start, deleteCount, items.length);
13746 }
13747
13748 function arrayObserversHelper(obj, target, opts, operation, notify) {
13749 var willChange = opts && opts.willChange || 'arrayWillChange';
13750 var didChange = opts && opts.didChange || 'arrayDidChange';
13751 var hasObservers = obj.hasArrayObservers;
13752 operation(obj, '@array:before', target, willChange);
13753 operation(obj, '@array:change', target, didChange);
13754
13755 if (hasObservers === notify) {
13756 notifyPropertyChange(obj, 'hasArrayObservers');
13757 }
13758
13759 return obj;
13760 }
13761
13762 function addArrayObserver(array, target, opts) {
13763 return arrayObserversHelper(array, target, opts, addListener, false);
13764 }
13765
13766 function removeArrayObserver(array, target, opts) {
13767 return arrayObserversHelper(array, target, opts, removeListener, true);
13768 }
13769
13770 var CHAIN_PASS_THROUGH = new _polyfills._WeakSet();
13771
13772 function finishLazyChains(meta$$1, key, value) {
13773 var lazyTags = meta$$1.readableLazyChainsFor(key);
13774
13775 if (lazyTags === undefined) {
13776 return;
13777 }
13778
13779 if ((0, _utils.isObject)(value)) {
13780 for (var i = 0; i < lazyTags.length; i++) {
13781 var [tag, deps] = lazyTags[i];
13782 (0, _validator.updateTag)(tag, getChainTagsForKey(value, deps, (0, _validator.tagMetaFor)(value), (0, _meta2.peekMeta)(value)));
13783 }
13784 }
13785
13786 lazyTags.length = 0;
13787 }
13788
13789 function getChainTagsForKeys(obj, keys, tagMeta, meta$$1) {
13790 var tags = [];
13791
13792 for (var i = 0; i < keys.length; i++) {
13793 getChainTags(tags, obj, keys[i], tagMeta, meta$$1);
13794 }
13795
13796 return (0, _validator.combine)(tags);
13797 }
13798
13799 function getChainTagsForKey(obj, key, tagMeta, meta$$1) {
13800 return (0, _validator.combine)(getChainTags([], obj, key, tagMeta, meta$$1));
13801 }
13802
13803 function getChainTags(chainTags, obj, path, tagMeta, meta$$1) {
13804 var current = obj;
13805 var currentTagMeta = tagMeta;
13806 var currentMeta = meta$$1;
13807 var pathLength = path.length;
13808 var segmentEnd = -1; // prevent closures
13809
13810 var segment, descriptor; // eslint-disable-next-line no-constant-condition
13811
13812 while (true) {
13813 var lastSegmentEnd = segmentEnd + 1;
13814 segmentEnd = path.indexOf('.', lastSegmentEnd);
13815
13816 if (segmentEnd === -1) {
13817 segmentEnd = pathLength;
13818 }
13819
13820 segment = path.slice(lastSegmentEnd, segmentEnd); // If the segment is an @each, we can process it and then break
13821
13822 if (segment === '@each' && segmentEnd !== pathLength) {
13823 lastSegmentEnd = segmentEnd + 1;
13824 segmentEnd = path.indexOf('.', lastSegmentEnd); // There should be exactly one segment after an `@each` (i.e. `@each.foo`, not `@each.foo.bar`)
13825
13826 (true && !(segmentEnd === -1) && (0, _debug.deprecate)(`When using @each in a dependent-key or an observer, ` + `you can only chain one property level deep after ` + `the @each. That is, \`${path.slice(0, segmentEnd)}\` ` + `is allowed but \`${path}\` (which is what you passed) ` + `is not.\n\n` + `This was never supported. Currently, the extra segments ` + `are silently ignored, i.e. \`${path}\` behaves exactly ` + `the same as \`${path.slice(0, segmentEnd)}\`. ` + `In the future, this will throw an error.\n\n` + `If the current behavior is acceptable for your use case, ` + `please remove the extraneous segments by changing your ` + `key to \`${path.slice(0, segmentEnd)}\`. ` + `Otherwise, please create an intermediary computed property ` + `or switch to using tracked properties.`, segmentEnd === -1, {
13827 until: '3.17.0',
13828 id: 'ember-metal.computed-deep-each'
13829 }));
13830 var arrLength = current.length;
13831
13832 if (typeof arrLength !== 'number' || // TODO: should the second test be `isEmberArray` instead?
13833 !(Array.isArray(current) || 'objectAt' in current)) {
13834 // If the current object isn't an array, there's nothing else to do,
13835 // we don't watch individual properties. Break out of the loop.
13836 break;
13837 } else if (arrLength === 0) {
13838 // Fast path for empty arrays
13839 chainTags.push(tagForProperty(current, '[]'));
13840 break;
13841 }
13842
13843 if (segmentEnd === -1) {
13844 segment = path.slice(lastSegmentEnd);
13845 } else {
13846 // Deprecated, remove once we turn the deprecation into an assertion
13847 segment = path.slice(lastSegmentEnd, segmentEnd);
13848 } // Push the tags for each item's property
13849
13850
13851 for (var i = 0; i < arrLength; i++) {
13852 var item = objectAt(current, i);
13853
13854 if (item) {
13855 (true && !(typeof item === 'object') && (0, _debug.assert)(`When using @each to observe the array \`${current.toString()}\`, the items in the array must be objects`, typeof item === 'object'));
13856 chainTags.push(tagForProperty(item, segment, true));
13857 }
13858 } // Push the tag for the array length itself
13859
13860
13861 chainTags.push(tagForProperty(current, '[]', true, currentTagMeta));
13862 break;
13863 }
13864
13865 var propertyTag = tagForProperty(current, segment, true, currentTagMeta);
13866 descriptor = currentMeta !== null ? currentMeta.peekDescriptors(segment) : undefined;
13867 chainTags.push(propertyTag); // If we're at the end of the path, processing the last segment, and it's
13868 // not an alias, we should _not_ get the last value, since we already have
13869 // its tag. There's no reason to access it and do more work.
13870
13871 if (segmentEnd === pathLength) {
13872 // If the key was an alias, we should always get the next value in order to
13873 // bootstrap the alias. This is because aliases, unlike other CPs, should
13874 // always be in sync with the aliased value.
13875 if (CHAIN_PASS_THROUGH.has(descriptor)) {
13876 // tslint:disable-next-line: no-unused-expression
13877 current[segment];
13878 }
13879
13880 break;
13881 }
13882
13883 if (descriptor === undefined) {
13884 // If the descriptor is undefined, then its a normal property, so we should
13885 // lookup the value to chain off of like normal.
13886 if (!(segment in current) && typeof current.unknownProperty === 'function') {
13887 current = current.unknownProperty(segment);
13888 } else {
13889 current = current[segment];
13890 }
13891 } else if (CHAIN_PASS_THROUGH.has(descriptor)) {
13892 current = current[segment];
13893 } else {
13894 // If the descriptor is defined, then its a normal CP (not an alias, which
13895 // would have been handled earlier). We get the last revision to check if
13896 // the CP is still valid, and if so we use the cached value. If not, then
13897 // we create a lazy chain lookup, and the next time the CP is calculated,
13898 // it will update that lazy chain.
13899 var instanceMeta = currentMeta.source === current ? currentMeta : (0, _meta2.meta)(current);
13900 var lastRevision = instanceMeta.revisionFor(segment);
13901
13902 if (lastRevision !== undefined && (0, _validator.validateTag)(propertyTag, lastRevision)) {
13903 current = instanceMeta.valueFor(segment);
13904 } else {
13905 // use metaFor here to ensure we have the meta for the instance
13906 var lazyChains = instanceMeta.writableLazyChainsFor(segment);
13907 var rest = path.substr(segmentEnd + 1);
13908 var placeholderTag = (0, _validator.createUpdatableTag)();
13909 lazyChains.push([placeholderTag, rest]);
13910 chainTags.push(placeholderTag);
13911 break;
13912 }
13913 }
13914
13915 if (!(0, _utils.isObject)(current)) {
13916 // we've hit the end of the chain for now, break out
13917 break;
13918 }
13919
13920 currentTagMeta = (0, _validator.tagMetaFor)(current);
13921 currentMeta = (0, _meta2.peekMeta)(current);
13922 }
13923
13924 return chainTags;
13925 }
13926
13927 function isElementDescriptor(args) {
13928 var [maybeTarget, maybeKey, maybeDesc] = args;
13929 return (// Ensure we have the right number of args
13930 args.length === 3 && ( // Make sure the target is a class or object (prototype)
13931 typeof maybeTarget === 'function' || typeof maybeTarget === 'object' && maybeTarget !== null) && // Make sure the key is a string
13932 typeof maybeKey === 'string' && ( // Make sure the descriptor is the right shape
13933 typeof maybeDesc === 'object' && maybeDesc !== null || maybeDesc === undefined)
13934 );
13935 }
13936
13937 function nativeDescDecorator(propertyDesc) {
13938 var decorator = function () {
13939 return propertyDesc;
13940 };
13941
13942 setClassicDecorator(decorator);
13943 return decorator;
13944 }
13945 /**
13946 Objects of this type can implement an interface to respond to requests to
13947 get and set. The default implementation handles simple properties.
13948
13949 @class Descriptor
13950 @private
13951 */
13952
13953
13954 class ComputedDescriptor {
13955 constructor() {
13956 this.enumerable = true;
13957 this.configurable = true;
13958 this._dependentKeys = undefined;
13959 this._meta = undefined;
13960 }
13961
13962 setup(_obj, keyName, _propertyDesc, meta$$1) {
13963 meta$$1.writeDescriptors(keyName, this);
13964 }
13965
13966 teardown(_obj, keyName, meta$$1) {
13967 meta$$1.removeDescriptors(keyName);
13968 }
13969
13970 }
13971
13972 function DESCRIPTOR_GETTER_FUNCTION(name, descriptor) {
13973 return function CPGETTER_FUNCTION() {
13974 return descriptor.get(this, name);
13975 };
13976 }
13977
13978 function DESCRIPTOR_SETTER_FUNCTION(name, descriptor) {
13979 return function CPSETTER_FUNCTION(value) {
13980 return descriptor.set(this, name, value);
13981 };
13982 }
13983
13984 function makeComputedDecorator(desc, DecoratorClass) {
13985 var decorator = function COMPUTED_DECORATOR(target, key, propertyDesc, maybeMeta, isClassicDecorator) {
13986 (true && !(isClassicDecorator || !propertyDesc || !propertyDesc.get || propertyDesc.get.toString().indexOf('CPGETTER_FUNCTION') === -1) && (0, _debug.assert)(`Only one computed property decorator can be applied to a class field or accessor, but '${key}' was decorated twice. You may have added the decorator to both a getter and setter, which is unnecessary.`, isClassicDecorator || !propertyDesc || !propertyDesc.get || propertyDesc.get.toString().indexOf('CPGETTER_FUNCTION') === -1));
13987 var meta$$1 = arguments.length === 3 ? (0, _meta2.meta)(target) : maybeMeta;
13988 desc.setup(target, key, propertyDesc, meta$$1);
13989 var computedDesc = {
13990 enumerable: desc.enumerable,
13991 configurable: desc.configurable,
13992 get: DESCRIPTOR_GETTER_FUNCTION(key, desc),
13993 set: DESCRIPTOR_SETTER_FUNCTION(key, desc)
13994 };
13995 return computedDesc;
13996 };
13997
13998 setClassicDecorator(decorator, desc);
13999 Object.setPrototypeOf(decorator, DecoratorClass.prototype);
14000 return decorator;
14001 } /////////////
14002
14003
14004 var DECORATOR_DESCRIPTOR_MAP = new WeakMap();
14005 /**
14006 Returns the CP descriptor associated with `obj` and `keyName`, if any.
14007
14008 @method descriptorForProperty
14009 @param {Object} obj the object to check
14010 @param {String} keyName the key to check
14011 @return {Descriptor}
14012 @private
14013 */
14014
14015 function descriptorForProperty(obj, keyName, _meta) {
14016 (true && !(obj !== null) && (0, _debug.assert)('Cannot call `descriptorForProperty` on null', obj !== null));
14017 (true && !(obj !== undefined) && (0, _debug.assert)('Cannot call `descriptorForProperty` on undefined', obj !== undefined));
14018 (true && !(typeof obj === 'object' || typeof obj === 'function') && (0, _debug.assert)(`Cannot call \`descriptorForProperty\` on ${typeof obj}`, typeof obj === 'object' || typeof obj === 'function'));
14019 var meta$$1 = _meta === undefined ? (0, _meta2.peekMeta)(obj) : _meta;
14020
14021 if (meta$$1 !== null) {
14022 return meta$$1.peekDescriptors(keyName);
14023 }
14024 }
14025
14026 function descriptorForDecorator(dec) {
14027 return DECORATOR_DESCRIPTOR_MAP.get(dec);
14028 }
14029 /**
14030 Check whether a value is a decorator
14031
14032 @method isClassicDecorator
14033 @param {any} possibleDesc the value to check
14034 @return {boolean}
14035 @private
14036 */
14037
14038
14039 function isClassicDecorator(dec) {
14040 return typeof dec === 'function' && DECORATOR_DESCRIPTOR_MAP.has(dec);
14041 }
14042 /**
14043 Set a value as a decorator
14044
14045 @method setClassicDecorator
14046 @param {function} decorator the value to mark as a decorator
14047 @private
14048 */
14049
14050
14051 function setClassicDecorator(dec, value = true) {
14052 DECORATOR_DESCRIPTOR_MAP.set(dec, value);
14053 }
14054 /**
14055 @module @ember/object
14056 */
14057
14058
14059 var END_WITH_EACH_REGEX = /\.@each$/;
14060 /**
14061 Expands `pattern`, invoking `callback` for each expansion.
14062
14063 The only pattern supported is brace-expansion, anything else will be passed
14064 once to `callback` directly.
14065
14066 Example
14067
14068 ```js
14069 import { expandProperties } from '@ember/object/computed';
14070
14071 function echo(arg){ console.log(arg); }
14072
14073 expandProperties('foo.bar', echo); //=> 'foo.bar'
14074 expandProperties('{foo,bar}', echo); //=> 'foo', 'bar'
14075 expandProperties('foo.{bar,baz}', echo); //=> 'foo.bar', 'foo.baz'
14076 expandProperties('{foo,bar}.baz', echo); //=> 'foo.baz', 'bar.baz'
14077 expandProperties('foo.{bar,baz}.[]', echo) //=> 'foo.bar.[]', 'foo.baz.[]'
14078 expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs'
14079 expandProperties('{foo}.bar.{baz}') //=> 'foo.bar.baz'
14080 ```
14081
14082 @method expandProperties
14083 @static
14084 @for @ember/object/computed
14085 @public
14086 @param {String} pattern The property pattern to expand.
14087 @param {Function} callback The callback to invoke. It is invoked once per
14088 expansion, and is passed the expansion.
14089 */
14090
14091 function expandProperties(pattern, callback) {
14092 (true && !(typeof pattern === 'string') && (0, _debug.assert)(`A computed property key must be a string, you passed ${typeof pattern} ${pattern}`, typeof pattern === 'string'));
14093 (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
14094
14095 (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));
14096 var start = pattern.indexOf('{');
14097
14098 if (start < 0) {
14099 callback(pattern.replace(END_WITH_EACH_REGEX, '.[]'));
14100 } else {
14101 dive('', pattern, start, callback);
14102 }
14103 }
14104
14105 function dive(prefix, pattern, start, callback) {
14106 var end = pattern.indexOf('}'),
14107 i = 0,
14108 newStart,
14109 arrayLength;
14110 var tempArr = pattern.substring(start + 1, end).split(',');
14111 var after = pattern.substring(end + 1);
14112 prefix = prefix + pattern.substring(0, start);
14113 arrayLength = tempArr.length;
14114
14115 while (i < arrayLength) {
14116 newStart = after.indexOf('{');
14117
14118 if (newStart < 0) {
14119 callback((prefix + tempArr[i++] + after).replace(END_WITH_EACH_REGEX, '.[]'));
14120 } else {
14121 dive(prefix + tempArr[i++], after, newStart, callback);
14122 }
14123 }
14124 }
14125 /**
14126 @module @ember/object
14127 */
14128
14129 /**
14130 NOTE: This is a low-level method used by other parts of the API. You almost
14131 never want to call this method directly. Instead you should use
14132 `mixin()` to define new properties.
14133
14134 Defines a property on an object. This method works much like the ES5
14135 `Object.defineProperty()` method except that it can also accept computed
14136 properties and other special descriptors.
14137
14138 Normally this method takes only three parameters. However if you pass an
14139 instance of `Descriptor` as the third param then you can pass an
14140 optional value as the fourth parameter. This is often more efficient than
14141 creating new descriptor hashes for each property.
14142
14143 ## Examples
14144
14145 ```javascript
14146 import { defineProperty, computed } from '@ember/object';
14147
14148 // ES5 compatible mode
14149 defineProperty(contact, 'firstName', {
14150 writable: true,
14151 configurable: false,
14152 enumerable: true,
14153 value: 'Charles'
14154 });
14155
14156 // define a simple property
14157 defineProperty(contact, 'lastName', undefined, 'Jolley');
14158
14159 // define a computed property
14160 defineProperty(contact, 'fullName', computed('firstName', 'lastName', function() {
14161 return this.firstName+' '+this.lastName;
14162 }));
14163 ```
14164
14165 @public
14166 @method defineProperty
14167 @static
14168 @for @ember/object
14169 @param {Object} obj the object to define this property on. This may be a prototype.
14170 @param {String} keyName the name of the property
14171 @param {Descriptor} [desc] an instance of `Descriptor` (typically a
14172 computed property) or an ES5 descriptor.
14173 You must provide this or `data` but not both.
14174 @param {*} [data] something other than a descriptor, that will
14175 become the explicit value of this property.
14176 */
14177
14178
14179 function defineProperty(obj, keyName, desc, data, _meta) {
14180 var meta$$1 = _meta === undefined ? (0, _meta2.meta)(obj) : _meta;
14181 var previousDesc = descriptorForProperty(obj, keyName, meta$$1);
14182 var wasDescriptor = previousDesc !== undefined;
14183
14184 if (wasDescriptor) {
14185 previousDesc.teardown(obj, keyName, meta$$1);
14186 }
14187
14188 if (isClassicDecorator(desc)) {
14189 defineDecorator(obj, keyName, desc, meta$$1);
14190 } else if (desc === null || desc === undefined) {
14191 defineValue(obj, keyName, data, wasDescriptor, true);
14192 } else {
14193 // fallback to ES5
14194 Object.defineProperty(obj, keyName, desc);
14195 } // if key is being watched, override chains that
14196 // were initialized with the prototype
14197
14198
14199 if (!meta$$1.isPrototypeMeta(obj)) {
14200 revalidateObservers(obj);
14201 }
14202 }
14203
14204 function defineDecorator(obj, keyName, desc, meta$$1) {
14205 var propertyDesc;
14206
14207 if (true
14208 /* DEBUG */
14209 ) {
14210 propertyDesc = desc(obj, keyName, undefined, meta$$1, true);
14211 } else {
14212 propertyDesc = desc(obj, keyName, undefined, meta$$1);
14213 }
14214
14215 Object.defineProperty(obj, keyName, propertyDesc); // pass the decorator function forward for backwards compat
14216
14217 return desc;
14218 }
14219
14220 function defineValue(obj, keyName, value, wasDescriptor, enumerable = true) {
14221 if (wasDescriptor === true || enumerable === false) {
14222 Object.defineProperty(obj, keyName, {
14223 configurable: true,
14224 enumerable,
14225 writable: true,
14226 value
14227 });
14228 } else {
14229 if (true
14230 /* DEBUG */
14231 ) {
14232 (0, _utils.setWithMandatorySetter)(obj, keyName, value);
14233 } else {
14234 obj[keyName] = value;
14235 }
14236 }
14237
14238 return value;
14239 }
14240
14241 var firstDotIndexCache = new _utils.Cache(1000, key => key.indexOf('.'));
14242
14243 function isPath(path) {
14244 return typeof path === 'string' && firstDotIndexCache.get(path) !== -1;
14245 }
14246 /**
14247 @module @ember/object
14248 */
14249
14250
14251 var PROXY_CONTENT = (0, _utils.symbol)('PROXY_CONTENT');
14252 _exports.PROXY_CONTENT = PROXY_CONTENT;
14253 var getPossibleMandatoryProxyValue;
14254
14255 if (true
14256 /* DEBUG */
14257 && _utils.HAS_NATIVE_PROXY) {
14258 getPossibleMandatoryProxyValue = function getPossibleMandatoryProxyValue(obj, keyName) {
14259 var content = obj[PROXY_CONTENT];
14260
14261 if (content === undefined) {
14262 return obj[keyName];
14263 } else {
14264 /* global Reflect */
14265 return Reflect.get(content, keyName, obj);
14266 }
14267 };
14268 } // ..........................................................
14269 // GET AND SET
14270 //
14271 // If we are on a platform that supports accessors we can use those.
14272 // Otherwise simulate accessors by looking up the property directly on the
14273 // object.
14274
14275 /**
14276 Gets the value of a property on an object. If the property is computed,
14277 the function will be invoked. If the property is not defined but the
14278 object implements the `unknownProperty` method then that will be invoked.
14279
14280 ```javascript
14281 import { get } from '@ember/object';
14282 get(obj, "name");
14283 ```
14284
14285 If you plan to run on IE8 and older browsers then you should use this
14286 method anytime you want to retrieve a property on an object that you don't
14287 know for sure is private. (Properties beginning with an underscore '_'
14288 are considered private.)
14289
14290 On all newer browsers, you only need to use this method to retrieve
14291 properties if the property might not be defined on the object and you want
14292 to respect the `unknownProperty` handler. Otherwise you can ignore this
14293 method.
14294
14295 Note that if the object itself is `undefined`, this method will throw
14296 an error.
14297
14298 @method get
14299 @for @ember/object
14300 @static
14301 @param {Object} obj The object to retrieve from.
14302 @param {String} keyName The property key to retrieve
14303 @return {Object} the property value or `null`.
14304 @public
14305 */
14306
14307
14308 function get(obj, keyName) {
14309 (true && !(arguments.length === 2) && (0, _debug.assert)(`Get must be called with two arguments; an object and a property key`, arguments.length === 2));
14310 (true && !(obj !== undefined && obj !== null) && (0, _debug.assert)(`Cannot call get with '${keyName}' on an undefined object.`, obj !== undefined && obj !== null));
14311 (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)));
14312 (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));
14313 return isPath(keyName) ? _getPath(obj, keyName) : _getProp(obj, keyName);
14314 }
14315
14316 function _getProp(obj, keyName) {
14317 var type = typeof obj;
14318 var isObject$$1 = type === 'object';
14319 var isFunction = type === 'function';
14320 var isObjectLike = isObject$$1 || isFunction;
14321 var value;
14322
14323 if (isObjectLike) {
14324 if (true
14325 /* DEBUG */
14326 && _utils.HAS_NATIVE_PROXY) {
14327 value = getPossibleMandatoryProxyValue(obj, keyName);
14328 } else {
14329 value = obj[keyName];
14330 }
14331
14332 if (value === undefined && isObject$$1 && !(keyName in obj) && typeof obj.unknownProperty === 'function') {
14333 if (true
14334 /* DEBUG */
14335 ) {
14336 (0, _validator.deprecateMutationsInAutotrackingTransaction)(() => {
14337 value = obj.unknownProperty(keyName);
14338 });
14339 } else {
14340 value = obj.unknownProperty(keyName);
14341 }
14342 }
14343
14344 if ((0, _validator.isTracking)()) {
14345 (0, _validator.consumeTag)((0, _validator.tagFor)(obj, keyName));
14346
14347 if (Array.isArray(value) || (0, _utils.isEmberArray)(value)) {
14348 // Add the tag of the returned value if it is an array, since arrays
14349 // should always cause updates if they are consumed and then changed
14350 (0, _validator.consumeTag)((0, _validator.tagFor)(value, '[]'));
14351 }
14352 }
14353 } else {
14354 value = obj[keyName];
14355 }
14356
14357 return value;
14358 }
14359
14360 function _getPath(root, path) {
14361 var obj = root;
14362 var parts = typeof path === 'string' ? path.split('.') : path;
14363
14364 for (var i = 0; i < parts.length; i++) {
14365 if (obj === undefined || obj === null || obj.isDestroyed) {
14366 return undefined;
14367 }
14368
14369 obj = _getProp(obj, parts[i]);
14370 }
14371
14372 return obj;
14373 }
14374 /**
14375 Retrieves the value of a property from an Object, or a default value in the
14376 case that the property returns `undefined`.
14377
14378 ```javascript
14379 import { getWithDefault } from '@ember/object';
14380 getWithDefault(person, 'lastName', 'Doe');
14381 ```
14382
14383 @method getWithDefault
14384 @for @ember/object
14385 @static
14386 @param {Object} obj The object to retrieve from.
14387 @param {String} keyName The name of the property to retrieve
14388 @param {Object} defaultValue The value to return if the property value is undefined
14389 @return {Object} The property value or the defaultValue.
14390 @public
14391 @deprecated
14392 */
14393
14394
14395 function getWithDefault(root, key, defaultValue) {
14396 (true && !(false) && (0, _debug.deprecate)('Using getWithDefault has been deprecated. Instead, consider using Ember get and explicitly checking for undefined.', false, {
14397 id: 'ember-metal.get-with-default',
14398 until: '4.0.0',
14399 url: 'https://deprecations.emberjs.com/v3.x#toc_ember-metal-get-with-default'
14400 }));
14401 var value = get(root, key);
14402
14403 if (value === undefined) {
14404 return defaultValue;
14405 }
14406
14407 return value;
14408 }
14409
14410 _getProp('foo', 'a');
14411
14412 _getProp('foo', 1);
14413
14414 _getProp({}, 'a');
14415
14416 _getProp({}, 1);
14417
14418 _getProp({
14419 unkonwnProperty() {}
14420
14421 }, 'a');
14422
14423 _getProp({
14424 unkonwnProperty() {}
14425
14426 }, 1);
14427
14428 get({}, 'foo');
14429 get({}, 'foo.bar');
14430 var fakeProxy = {};
14431 (0, _utils.setProxy)(fakeProxy);
14432 (0, _validator.track)(() => _getProp({}, 'a'));
14433 (0, _validator.track)(() => _getProp({}, 1));
14434 (0, _validator.track)(() => _getProp({
14435 a: []
14436 }, 'a'));
14437 (0, _validator.track)(() => _getProp({
14438 a: fakeProxy
14439 }, 'a'));
14440 /**
14441 @module @ember/object
14442 */
14443
14444 /**
14445 Sets the value of a property on an object, respecting computed properties
14446 and notifying observers and other listeners of the change.
14447 If the specified property is not defined on the object and the object
14448 implements the `setUnknownProperty` method, then instead of setting the
14449 value of the property on the object, its `setUnknownProperty` handler
14450 will be invoked with the two parameters `keyName` and `value`.
14451
14452 ```javascript
14453 import { set } from '@ember/object';
14454 set(obj, "name", value);
14455 ```
14456
14457 @method set
14458 @static
14459 @for @ember/object
14460 @param {Object} obj The object to modify.
14461 @param {String} keyName The property key to set
14462 @param {Object} value The value to set
14463 @return {Object} the passed value.
14464 @public
14465 */
14466
14467 function set(obj, keyName, value, tolerant) {
14468 (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));
14469 (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'));
14470 (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)));
14471 (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));
14472
14473 if (obj.isDestroyed) {
14474 (true && !(tolerant) && (0, _debug.assert)(`calling set on destroyed object: ${(0, _utils.toString)(obj)}.${keyName} = ${(0, _utils.toString)(value)}`, tolerant));
14475 return;
14476 }
14477
14478 if (isPath(keyName)) {
14479 return setPath(obj, keyName, value, tolerant);
14480 }
14481
14482 var descriptor = descriptorForProperty(obj, keyName);
14483
14484 if (descriptor !== undefined) {
14485 descriptor.set(obj, keyName, value);
14486 return value;
14487 }
14488
14489 var currentValue;
14490
14491 if (true
14492 /* DEBUG */
14493 && _utils.HAS_NATIVE_PROXY) {
14494 currentValue = getPossibleMandatoryProxyValue(obj, keyName);
14495 } else {
14496 currentValue = obj[keyName];
14497 }
14498
14499 if (currentValue === undefined && 'object' === typeof obj && !(keyName in obj) && typeof obj.setUnknownProperty === 'function') {
14500 /* unknown property */
14501 obj.setUnknownProperty(keyName, value);
14502 } else {
14503 if (true
14504 /* DEBUG */
14505 ) {
14506 (0, _utils.setWithMandatorySetter)(obj, keyName, value);
14507 } else {
14508 obj[keyName] = value;
14509 }
14510
14511 if (currentValue !== value) {
14512 notifyPropertyChange(obj, keyName);
14513 }
14514 }
14515
14516 return value;
14517 }
14518
14519 function setPath(root, path, value, tolerant) {
14520 var parts = path.split('.');
14521 var keyName = parts.pop();
14522 (true && !(keyName.trim().length > 0) && (0, _debug.assert)('Property set failed: You passed an empty path', keyName.trim().length > 0));
14523
14524 var newRoot = _getPath(root, parts);
14525
14526 if (newRoot !== null && newRoot !== undefined) {
14527 return set(newRoot, keyName, value);
14528 } else if (!tolerant) {
14529 throw new _error.default(`Property set failed: object in path "${parts.join('.')}" could not be found.`);
14530 }
14531 }
14532 /**
14533 Error-tolerant form of `set`. Will not blow up if any part of the
14534 chain is `undefined`, `null`, or destroyed.
14535
14536 This is primarily used when syncing bindings, which may try to update after
14537 an object has been destroyed.
14538
14539 ```javascript
14540 import { trySet } from '@ember/object';
14541
14542 let obj = { name: "Zoey" };
14543 trySet(obj, "contacts.twitter", "@emberjs");
14544 ```
14545
14546 @method trySet
14547 @static
14548 @for @ember/object
14549 @param {Object} root The object to modify.
14550 @param {String} path The property path to set
14551 @param {Object} value The value to set
14552 @public
14553 */
14554
14555
14556 function trySet(root, path, value) {
14557 return set(root, path, value, true);
14558 }
14559 /**
14560 @module @ember/object
14561 */
14562
14563
14564 var DEEP_EACH_REGEX = /\.@each\.[^.]+\./;
14565
14566 function noop() {}
14567 /**
14568 `@computed` is a decorator that turns a JavaScript getter and setter into a
14569 computed property, which is a _cached, trackable value_. By default the getter
14570 will only be called once and the result will be cached. You can specify
14571 various properties that your computed property depends on. This will force the
14572 cached result to be cleared if the dependencies are modified, and lazily recomputed the next time something asks for it.
14573
14574 In the following example we decorate a getter - `fullName` - by calling
14575 `computed` with the property dependencies (`firstName` and `lastName`) as
14576 arguments. The `fullName` getter will be called once (regardless of how many
14577 times it is accessed) as long as its dependencies do not change. Once
14578 `firstName` or `lastName` are updated any future calls to `fullName` will
14579 incorporate the new values, and any watchers of the value such as templates
14580 will be updated:
14581
14582 ```javascript
14583 import { computed, set } from '@ember/object';
14584
14585 class Person {
14586 constructor(firstName, lastName) {
14587 set(this, 'firstName', firstName);
14588 set(this, 'lastName', lastName);
14589 }
14590
14591 @computed('firstName', 'lastName')
14592 get fullName() {
14593 return `${this.firstName} ${this.lastName}`;
14594 }
14595 });
14596
14597 let tom = new Person('Tom', 'Dale');
14598
14599 tom.fullName; // 'Tom Dale'
14600 ```
14601
14602 You can also provide a setter, which will be used when updating the computed
14603 property. Ember's `set` function must be used to update the property
14604 since it will also notify observers of the property:
14605
14606 ```javascript
14607 import { computed, set } from '@ember/object';
14608
14609 class Person {
14610 constructor(firstName, lastName) {
14611 set(this, 'firstName', firstName);
14612 set(this, 'lastName', lastName);
14613 }
14614
14615 @computed('firstName', 'lastName')
14616 get fullName() {
14617 return `${this.firstName} ${this.lastName}`;
14618 }
14619
14620 set fullName(value) {
14621 let [firstName, lastName] = value.split(' ');
14622
14623 set(this, 'firstName', firstName);
14624 set(this, 'lastName', lastName);
14625 }
14626 });
14627
14628 let person = new Person();
14629
14630 set(person, 'fullName', 'Peter Wagenet');
14631 person.firstName; // 'Peter'
14632 person.lastName; // 'Wagenet'
14633 ```
14634
14635 You can also pass a getter function or object with `get` and `set` functions
14636 as the last argument to the computed decorator. This allows you to define
14637 computed property _macros_:
14638
14639 ```js
14640 import { computed } from '@ember/object';
14641
14642 function join(...keys) {
14643 return computed(...keys, function() {
14644 return keys.map(key => this[key]).join(' ');
14645 });
14646 }
14647
14648 class Person {
14649 @join('firstName', 'lastName')
14650 fullName;
14651 }
14652 ```
14653
14654 Note that when defined this way, getters and setters receive the _key_ of the
14655 property they are decorating as the first argument. Setters receive the value
14656 they are setting to as the second argument instead. Additionally, setters must
14657 _return_ the value that should be cached:
14658
14659 ```javascript
14660 import { computed, set } from '@ember/object';
14661
14662 function fullNameMacro(firstNameKey, lastNameKey) {
14663 return computed(firstNameKey, lastNameKey, {
14664 get() {
14665 return `${this[firstNameKey]} ${this[lastNameKey]}`;
14666 }
14667
14668 set(key, value) {
14669 let [firstName, lastName] = value.split(' ');
14670
14671 set(this, firstNameKey, firstName);
14672 set(this, lastNameKey, lastName);
14673
14674 return value;
14675 }
14676 });
14677 }
14678
14679 class Person {
14680 constructor(firstName, lastName) {
14681 set(this, 'firstName', firstName);
14682 set(this, 'lastName', lastName);
14683 }
14684
14685 @fullNameMacro('firstName', 'lastName') fullName;
14686 });
14687
14688 let person = new Person();
14689
14690 set(person, 'fullName', 'Peter Wagenet');
14691 person.firstName; // 'Peter'
14692 person.lastName; // 'Wagenet'
14693 ```
14694
14695 Computed properties can also be used in classic classes. To do this, we
14696 provide the getter and setter as the last argument like we would for a macro,
14697 and we assign it to a property on the class definition. This is an _anonymous_
14698 computed macro:
14699
14700 ```javascript
14701 import EmberObject, { computed, set } from '@ember/object';
14702
14703 let Person = EmberObject.extend({
14704 // these will be supplied by `create`
14705 firstName: null,
14706 lastName: null,
14707
14708 fullName: computed('firstName', 'lastName', {
14709 get() {
14710 return `${this.firstName} ${this.lastName}`;
14711 }
14712
14713 set(key, value) {
14714 let [firstName, lastName] = value.split(' ');
14715
14716 set(this, 'firstName', firstName);
14717 set(this, 'lastName', lastName);
14718
14719 return value;
14720 }
14721 })
14722 });
14723
14724 let tom = Person.create({
14725 firstName: 'Tom',
14726 lastName: 'Dale'
14727 });
14728
14729 tom.get('fullName') // 'Tom Dale'
14730 ```
14731
14732 You can overwrite computed property without setters with a normal property (no
14733 longer computed) that won't change if dependencies change. You can also mark
14734 computed property as `.readOnly()` and block all attempts to set it.
14735
14736 ```javascript
14737 import { computed, set } from '@ember/object';
14738
14739 class Person {
14740 constructor(firstName, lastName) {
14741 set(this, 'firstName', firstName);
14742 set(this, 'lastName', lastName);
14743 }
14744
14745 @computed('firstName', 'lastName').readOnly()
14746 get fullName() {
14747 return `${this.firstName} ${this.lastName}`;
14748 }
14749 });
14750
14751 let person = new Person();
14752 person.set('fullName', 'Peter Wagenet'); // Uncaught Error: Cannot set read-only property "fullName" on object: <(...):emberXXX>
14753 ```
14754
14755 Additional resources:
14756 - [Decorators RFC](https://github.com/emberjs/rfcs/blob/master/text/0408-decorators.md)
14757 - [New CP syntax RFC](https://github.com/emberjs/rfcs/blob/master/text/0011-improved-cp-syntax.md)
14758 - [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)
14759
14760 @class ComputedProperty
14761 @public
14762 */
14763
14764
14765 class ComputedProperty extends ComputedDescriptor {
14766 constructor(args) {
14767 super();
14768 this._volatile = false;
14769 this._readOnly = false;
14770 this._hasConfig = false;
14771 this._getter = undefined;
14772 this._setter = undefined;
14773 var maybeConfig = args[args.length - 1];
14774
14775 if (typeof maybeConfig === 'function' || maybeConfig !== null && typeof maybeConfig === 'object') {
14776 this._hasConfig = true;
14777 var config = args.pop();
14778
14779 if (typeof config === 'function') {
14780 (true && !(!isClassicDecorator(config)) && (0, _debug.assert)(`You attempted to pass a computed property instance to computed(). Computed property instances are decorator functions, and cannot be passed to computed() because they cannot be turned into decorators twice`, !isClassicDecorator(config)));
14781 this._getter = config;
14782 } else {
14783 var objectConfig = config;
14784 (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)));
14785 (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')));
14786 (true && !(Boolean(objectConfig.get) || Boolean(objectConfig.set)) && (0, _debug.assert)('Computed properties must receive a getter or a setter, you passed none.', Boolean(objectConfig.get) || Boolean(objectConfig.set)));
14787 this._getter = objectConfig.get || noop;
14788 this._setter = objectConfig.set;
14789 }
14790 }
14791
14792 if (args.length > 0) {
14793 this._property(...args);
14794 }
14795 }
14796
14797 setup(obj, keyName, propertyDesc, meta$$1) {
14798 super.setup(obj, keyName, propertyDesc, meta$$1);
14799 (true && !(!(propertyDesc && typeof propertyDesc.value === 'function')) && (0, _debug.assert)(`@computed can only be used on accessors or fields, attempted to use it with ${keyName} but that was a method. Try converting it to a getter (e.g. \`get ${keyName}() {}\`)`, !(propertyDesc && typeof propertyDesc.value === 'function')));
14800 (true && !(!propertyDesc || !propertyDesc.initializer) && (0, _debug.assert)(`@computed can only be used on empty fields. ${keyName} has an initial value (e.g. \`${keyName} = someValue\`)`, !propertyDesc || !propertyDesc.initializer));
14801 (true && !(!(this._hasConfig && propertyDesc && (typeof propertyDesc.get === 'function' || typeof propertyDesc.set === 'function'))) && (0, _debug.assert)(`Attempted to apply a computed property that already has a getter/setter to a ${keyName}, but it is a method or an accessor. If you passed @computed a function or getter/setter (e.g. \`@computed({ get() { ... } })\`), then it must be applied to a field`, !(this._hasConfig && propertyDesc && (typeof propertyDesc.get === 'function' || typeof propertyDesc.set === 'function'))));
14802
14803 if (true
14804 /* DEBUG */
14805 ) {
14806 _validator.ALLOW_CYCLES.set((0, _validator.tagFor)(obj, keyName), true);
14807 }
14808
14809 if (this._hasConfig === false) {
14810 (true && !(propertyDesc && (typeof propertyDesc.get === 'function' || typeof propertyDesc.set === 'function')) && (0, _debug.assert)(`Attempted to use @computed on ${keyName}, but it did not have a getter or a setter. You must either pass a get a function or getter/setter to @computed directly (e.g. \`@computed({ get() { ... } })\`) or apply @computed directly to a getter/setter`, propertyDesc && (typeof propertyDesc.get === 'function' || typeof propertyDesc.set === 'function')));
14811 var {
14812 get: _get2,
14813 set: set$$1
14814 } = propertyDesc;
14815
14816 if (_get2 !== undefined) {
14817 this._getter = _get2;
14818 }
14819
14820 if (set$$1 !== undefined) {
14821 this._setter = function setterWrapper(_key, value) {
14822 var ret = set$$1.call(this, value);
14823
14824 if (_get2 !== undefined) {
14825 return typeof ret === 'undefined' ? _get2.call(this) : ret;
14826 }
14827
14828 return ret;
14829 };
14830 }
14831 }
14832 }
14833
14834 _property(...passedArgs) {
14835 var args = [];
14836
14837 function addArg(property) {
14838 (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, {
14839 id: 'ember-metal.computed-deep-each'
14840 }));
14841 args.push(property);
14842 }
14843
14844 for (var i = 0; i < passedArgs.length; i++) {
14845 expandProperties(passedArgs[i], addArg);
14846 }
14847
14848 this._dependentKeys = args;
14849 }
14850
14851 get(obj, keyName) {
14852 if (this._volatile) {
14853 return this._getter.call(obj, keyName);
14854 }
14855
14856 var meta$$1 = (0, _meta2.meta)(obj);
14857 var tagMeta = (0, _validator.tagMetaFor)(obj);
14858 var propertyTag = (0, _validator.tagFor)(obj, keyName, tagMeta);
14859 var ret;
14860 var revision = meta$$1.revisionFor(keyName);
14861
14862 if (revision !== undefined && (0, _validator.validateTag)(propertyTag, revision)) {
14863 ret = meta$$1.valueFor(keyName);
14864 } else {
14865 // For backwards compatibility, we only throw if the CP has any dependencies. CPs without dependencies
14866 // should be allowed, even after the object has been destroyed, which is why we check _dependentKeys.
14867 (true && !(this._dependentKeys === undefined || !(0, _runtime.isDestroyed)(obj)) && (0, _debug.assert)(`Attempted to access the computed ${obj}.${keyName} on a destroyed object, which is not allowed`, this._dependentKeys === undefined || !(0, _runtime.isDestroyed)(obj)));
14868 var {
14869 _getter,
14870 _dependentKeys
14871 } = this; // Create a tracker that absorbs any trackable actions inside the CP
14872
14873 (0, _validator.untrack)(() => {
14874 ret = _getter.call(obj, keyName);
14875 });
14876
14877 if (_dependentKeys !== undefined) {
14878 (0, _validator.updateTag)(propertyTag, getChainTagsForKeys(obj, _dependentKeys, tagMeta, meta$$1));
14879 }
14880
14881 meta$$1.setValueFor(keyName, ret);
14882 meta$$1.setRevisionFor(keyName, (0, _validator.valueForTag)(propertyTag));
14883 finishLazyChains(meta$$1, keyName, ret);
14884 }
14885
14886 (0, _validator.consumeTag)(propertyTag); // Add the tag of the returned value if it is an array, since arrays
14887 // should always cause updates if they are consumed and then changed
14888
14889 if (Array.isArray(ret)) {
14890 (0, _validator.consumeTag)((0, _validator.tagFor)(ret, '[]'));
14891 }
14892
14893 return ret;
14894 }
14895
14896 set(obj, keyName, value) {
14897 if (this._readOnly) {
14898 this._throwReadOnlyError(obj, keyName);
14899 }
14900
14901 if (!this._setter) {
14902 return this.clobberSet(obj, keyName, value);
14903 }
14904
14905 if (this._volatile) {
14906 return this.volatileSet(obj, keyName, value);
14907 }
14908
14909 var meta$$1 = (0, _meta2.meta)(obj); // ensure two way binding works when the component has defined a computed
14910 // property with both a setter and dependent keys, in that scenario without
14911 // the sync observer added below the caller's value will never be updated
14912 //
14913 // See GH#18147 / GH#19028 for details.
14914
14915 if ( // ensure that we only run this once, while the component is being instantiated
14916 meta$$1.isInitializing() && this._dependentKeys !== undefined && this._dependentKeys.length > 0 && // These two properties are set on Ember.Component
14917 typeof obj[PROPERTY_DID_CHANGE] === 'function' && obj.isComponent) {
14918 addObserver(obj, keyName, () => {
14919 obj[PROPERTY_DID_CHANGE](keyName);
14920 }, undefined, true);
14921 }
14922
14923 var ret;
14924
14925 try {
14926 beginPropertyChanges();
14927 ret = this._set(obj, keyName, value, meta$$1);
14928 finishLazyChains(meta$$1, keyName, ret);
14929 var tagMeta = (0, _validator.tagMetaFor)(obj);
14930 var propertyTag = (0, _validator.tagFor)(obj, keyName, tagMeta);
14931 var {
14932 _dependentKeys
14933 } = this;
14934
14935 if (_dependentKeys !== undefined) {
14936 (0, _validator.updateTag)(propertyTag, getChainTagsForKeys(obj, _dependentKeys, tagMeta, meta$$1));
14937 }
14938
14939 meta$$1.setRevisionFor(keyName, (0, _validator.valueForTag)(propertyTag));
14940 } finally {
14941 endPropertyChanges();
14942 }
14943
14944 return ret;
14945 }
14946
14947 _throwReadOnlyError(obj, keyName) {
14948 throw new _error.default(`Cannot set read-only property "${keyName}" on object: ${(0, _utils.inspect)(obj)}`);
14949 }
14950
14951 clobberSet(obj, keyName, value) {
14952 (true && !(false) && (0, _debug.deprecate)(`The ${(0, _utils.toString)(obj)}#${keyName} computed property was just overridden. This removes the computed property and replaces it with a plain value, and has been deprecated. If you want this behavior, consider defining a setter which does it manually.`, false, {
14953 id: 'computed-property.override',
14954 until: '4.0.0',
14955 url: 'https://emberjs.com/deprecations/v3.x#toc_computed-property-override'
14956 }));
14957 var cachedValue = (0, _meta2.meta)(obj).valueFor(keyName);
14958 defineProperty(obj, keyName, null, cachedValue);
14959 set(obj, keyName, value);
14960 return value;
14961 }
14962
14963 volatileSet(obj, keyName, value) {
14964 return this._setter.call(obj, keyName, value);
14965 }
14966
14967 _set(obj, keyName, value, meta$$1) {
14968 var hadCachedValue = meta$$1.revisionFor(keyName) !== undefined;
14969 var cachedValue = meta$$1.valueFor(keyName);
14970 var ret;
14971 var {
14972 _setter
14973 } = this;
14974 setObserverSuspended(obj, keyName, true);
14975
14976 try {
14977 ret = _setter.call(obj, keyName, value, cachedValue);
14978 } finally {
14979 setObserverSuspended(obj, keyName, false);
14980 } // allows setter to return the same value that is cached already
14981
14982
14983 if (hadCachedValue && cachedValue === ret) {
14984 return ret;
14985 }
14986
14987 meta$$1.setValueFor(keyName, ret);
14988 notifyPropertyChange(obj, keyName, meta$$1, value);
14989 return ret;
14990 }
14991 /* called before property is overridden */
14992
14993
14994 teardown(obj, keyName, meta$$1) {
14995 if (!this._volatile) {
14996 if (meta$$1.revisionFor(keyName) !== undefined) {
14997 meta$$1.setRevisionFor(keyName, undefined);
14998 meta$$1.setValueFor(keyName, undefined);
14999 }
15000 }
15001
15002 super.teardown(obj, keyName, meta$$1);
15003 }
15004
15005 }
15006
15007 _exports.ComputedProperty = ComputedProperty;
15008
15009 class AutoComputedProperty extends ComputedProperty {
15010 get(obj, keyName) {
15011 if (this._volatile) {
15012 return this._getter.call(obj, keyName);
15013 }
15014
15015 var meta$$1 = (0, _meta2.meta)(obj);
15016 var tagMeta = (0, _validator.tagMetaFor)(obj);
15017 var propertyTag = (0, _validator.tagFor)(obj, keyName, tagMeta);
15018 var ret;
15019 var revision = meta$$1.revisionFor(keyName);
15020
15021 if (revision !== undefined && (0, _validator.validateTag)(propertyTag, revision)) {
15022 ret = meta$$1.valueFor(keyName);
15023 } else {
15024 (true && !(!(0, _runtime.isDestroyed)(obj)) && (0, _debug.assert)(`Attempted to access the computed ${obj}.${keyName} on a destroyed object, which is not allowed`, !(0, _runtime.isDestroyed)(obj)));
15025 var {
15026 _getter
15027 } = this; // Create a tracker that absorbs any trackable actions inside the CP
15028
15029 var tag = (0, _validator.track)(() => {
15030 ret = _getter.call(obj, keyName);
15031 });
15032 (0, _validator.updateTag)(propertyTag, tag);
15033 meta$$1.setValueFor(keyName, ret);
15034 meta$$1.setRevisionFor(keyName, (0, _validator.valueForTag)(propertyTag));
15035 finishLazyChains(meta$$1, keyName, ret);
15036 }
15037
15038 (0, _validator.consumeTag)(propertyTag); // Add the tag of the returned value if it is an array, since arrays
15039 // should always cause updates if they are consumed and then changed
15040
15041 if (Array.isArray(ret)) {
15042 (0, _validator.consumeTag)((0, _validator.tagFor)(ret, '[]', tagMeta));
15043 }
15044
15045 return ret;
15046 }
15047
15048 } // TODO: This class can be svelted once `meta` has been deprecated
15049
15050
15051 class ComputedDecoratorImpl extends Function {
15052 /**
15053 Call on a computed property to set it into read-only mode. When in this
15054 mode the computed property will throw an error when set.
15055 Example:
15056 ```javascript
15057 import { computed, set } from '@ember/object';
15058 class Person {
15059 @computed().readOnly()
15060 get guid() {
15061 return 'guid-guid-guid';
15062 }
15063 }
15064 let person = new Person();
15065 set(person, 'guid', 'new-guid'); // will throw an exception
15066 ```
15067 Classic Class Example:
15068 ```javascript
15069 import EmberObject, { computed } from '@ember/object';
15070 let Person = EmberObject.extend({
15071 guid: computed(function() {
15072 return 'guid-guid-guid';
15073 }).readOnly()
15074 });
15075 let person = Person.create();
15076 person.set('guid', 'new-guid'); // will throw an exception
15077 ```
15078 @method readOnly
15079 @return {ComputedProperty} this
15080 @chainable
15081 @public
15082 */
15083 readOnly() {
15084 var desc = descriptorForDecorator(this);
15085 (true && !(!(desc._setter && desc._setter !== desc._getter)) && (0, _debug.assert)('Computed properties that define a setter using the new syntax cannot be read-only', !(desc._setter && desc._setter !== desc._getter)));
15086 desc._readOnly = true;
15087 return this;
15088 }
15089 /**
15090 Call on a computed property to set it into non-cached mode. When in this
15091 mode the computed property will not automatically cache the return value.
15092 It also does not automatically fire any change events. You must manually notify
15093 any changes if you want to observe this property.
15094 Dependency keys have no effect on volatile properties as they are for cache
15095 invalidation and notification when cached value is invalidated.
15096 Example:
15097 ```javascript
15098 import { computed } from '@ember/object';
15099 class CallCounter {
15100 _calledCount = 0;
15101 @computed().volatile()
15102 get calledCount() {
15103 return this._calledCount++;
15104 }
15105 }
15106 ```
15107 Classic Class Example:
15108 ```javascript
15109 import EmberObject, { computed } from '@ember/object';
15110 let CallCounter = EmberObject.extend({
15111 _calledCount: 0,
15112 value: computed(function() {
15113 return this._calledCount++;
15114 }).volatile()
15115 });
15116 ```
15117 @method volatile
15118 @deprecated
15119 @return {ComputedProperty} this
15120 @chainable
15121 @public
15122 */
15123
15124
15125 volatile() {
15126 (true && !(false) && (0, _debug.deprecate)('Setting a computed property as volatile has been deprecated. Instead, consider using a native getter with native class syntax.', false, {
15127 id: 'computed-property.volatile',
15128 until: '4.0.0',
15129 url: 'https://emberjs.com/deprecations/v3.x#toc_computed-property-volatile'
15130 }));
15131 descriptorForDecorator(this)._volatile = true;
15132 return this;
15133 }
15134 /**
15135 Sets the dependent keys on this computed property. Pass any number of
15136 arguments containing key paths that this computed property depends on.
15137 Example:
15138 ```javascript
15139 import EmberObject, { computed } from '@ember/object';
15140 class President {
15141 constructor(firstName, lastName) {
15142 set(this, 'firstName', firstName);
15143 set(this, 'lastName', lastName);
15144 }
15145 // Tell Ember that this computed property depends on firstName
15146 // and lastName
15147 @computed().property('firstName', 'lastName')
15148 get fullName() {
15149 return `${this.firstName} ${this.lastName}`;
15150 }
15151 }
15152 let president = new President('Barack', 'Obama');
15153 president.fullName; // 'Barack Obama'
15154 ```
15155 Classic Class Example:
15156 ```javascript
15157 import EmberObject, { computed } from '@ember/object';
15158 let President = EmberObject.extend({
15159 fullName: computed(function() {
15160 return this.get('firstName') + ' ' + this.get('lastName');
15161 // Tell Ember that this computed property depends on firstName
15162 // and lastName
15163 }).property('firstName', 'lastName')
15164 });
15165 let president = President.create({
15166 firstName: 'Barack',
15167 lastName: 'Obama'
15168 });
15169 president.get('fullName'); // 'Barack Obama'
15170 ```
15171 @method property
15172 @deprecated
15173 @param {String} path* zero or more property paths
15174 @return {ComputedProperty} this
15175 @chainable
15176 @public
15177 */
15178
15179
15180 property(...keys) {
15181 (true && !(false) && (0, _debug.deprecate)('Setting dependency keys using the `.property()` modifier has been deprecated. Pass the dependency keys directly to computed as arguments instead. If you are using `.property()` on a computed property macro, consider refactoring your macro to receive additional dependent keys in its initial declaration.', false, {
15182 id: 'computed-property.property',
15183 until: '4.0.0',
15184 url: 'https://emberjs.com/deprecations/v3.x#toc_computed-property-property'
15185 }));
15186
15187 descriptorForDecorator(this)._property(...keys);
15188
15189 return this;
15190 }
15191 /**
15192 In some cases, you may want to annotate computed properties with additional
15193 metadata about how they function or what values they operate on. For example,
15194 computed property functions may close over variables that are then no longer
15195 available for introspection. You can pass a hash of these values to a
15196 computed property.
15197 Example:
15198 ```javascript
15199 import { computed } from '@ember/object';
15200 import Person from 'my-app/utils/person';
15201 class Store {
15202 @computed().meta({ type: Person })
15203 get person() {
15204 let personId = this.personId;
15205 return Person.create({ id: personId });
15206 }
15207 }
15208 ```
15209 Classic Class Example:
15210 ```javascript
15211 import { computed } from '@ember/object';
15212 import Person from 'my-app/utils/person';
15213 const Store = EmberObject.extend({
15214 person: computed(function() {
15215 let personId = this.get('personId');
15216 return Person.create({ id: personId });
15217 }).meta({ type: Person })
15218 });
15219 ```
15220 The hash that you pass to the `meta()` function will be saved on the
15221 computed property descriptor under the `_meta` key. Ember runtime
15222 exposes a public API for retrieving these values from classes,
15223 via the `metaForProperty()` function.
15224 @method meta
15225 @param {Object} meta
15226 @chainable
15227 @public
15228 */
15229
15230
15231 meta(meta$$1) {
15232 var prop = descriptorForDecorator(this);
15233
15234 if (arguments.length === 0) {
15235 return prop._meta || {};
15236 } else {
15237 prop._meta = meta$$1;
15238 return this;
15239 }
15240 } // TODO: Remove this when we can provide alternatives in the ecosystem to
15241 // addons such as ember-macro-helpers that use it.
15242
15243
15244 get _getter() {
15245 return descriptorForDecorator(this)._getter;
15246 } // TODO: Refactor this, this is an internal API only
15247
15248
15249 set enumerable(value) {
15250 descriptorForDecorator(this).enumerable = value;
15251 }
15252
15253 }
15254
15255 function computed(...args) {
15256 (true && !(!(isElementDescriptor(args.slice(0, 3)) && args.length === 5 && args[4] === true)) && (0, _debug.assert)(`@computed can only be used directly as a native decorator. If you're using tracked in classic classes, add parenthesis to call it like a function: computed()`, !(isElementDescriptor(args.slice(0, 3)) && args.length === 5 && args[4] === true)));
15257
15258 if (isElementDescriptor(args)) {
15259 var decorator = makeComputedDecorator(new ComputedProperty([]), ComputedDecoratorImpl);
15260 return decorator(args[0], args[1], args[2]);
15261 }
15262
15263 return makeComputedDecorator(new ComputedProperty(args), ComputedDecoratorImpl);
15264 }
15265
15266 function autoComputed(...config) {
15267 return makeComputedDecorator(new AutoComputedProperty(config), ComputedDecoratorImpl);
15268 }
15269 /**
15270 Allows checking if a given property on an object is a computed property. For the most part,
15271 this doesn't matter (you would normally just access the property directly and use its value),
15272 but for some tooling specific scenarios (e.g. the ember-inspector) it is important to
15273 differentiate if a property is a computed property or a "normal" property.
15274
15275 This will work on either a class's prototype or an instance itself.
15276
15277 @static
15278 @method isComputed
15279 @for @ember/debug
15280 @private
15281 */
15282
15283
15284 function isComputed(obj, key) {
15285 return Boolean(descriptorForProperty(obj, key));
15286 }
15287
15288 var _globalsComputed = computed.bind(null);
15289
15290 _exports._globalsComputed = _globalsComputed;
15291
15292 function getCachedValueFor(obj, key) {
15293 var meta$$1 = (0, _meta2.peekMeta)(obj);
15294
15295 if (meta$$1) {
15296 return meta$$1.valueFor(key);
15297 }
15298 }
15299
15300 function alias(altKey) {
15301 (true && !(!isElementDescriptor(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @alias as a decorator directly, but it requires a `altKey` parameter', !isElementDescriptor(Array.prototype.slice.call(arguments))));
15302 return makeComputedDecorator(new AliasedProperty(altKey), AliasDecoratorImpl);
15303 } // TODO: This class can be svelted once `meta` has been deprecated
15304
15305
15306 class AliasDecoratorImpl extends Function {
15307 readOnly() {
15308 descriptorForDecorator(this).readOnly();
15309 return this;
15310 }
15311
15312 oneWay() {
15313 descriptorForDecorator(this).oneWay();
15314 return this;
15315 }
15316
15317 meta(meta$$1) {
15318 var prop = descriptorForDecorator(this);
15319
15320 if (arguments.length === 0) {
15321 return prop._meta || {};
15322 } else {
15323 prop._meta = meta$$1;
15324 }
15325 }
15326
15327 }
15328
15329 class AliasedProperty extends ComputedDescriptor {
15330 constructor(altKey) {
15331 super();
15332 this.altKey = altKey;
15333 }
15334
15335 setup(obj, keyName, propertyDesc, meta$$1) {
15336 (true && !(this.altKey !== keyName) && (0, _debug.assert)(`Setting alias '${keyName}' on self`, this.altKey !== keyName));
15337 super.setup(obj, keyName, propertyDesc, meta$$1);
15338 CHAIN_PASS_THROUGH.add(this);
15339 }
15340
15341 get(obj, keyName) {
15342 var ret;
15343 var meta$$1 = (0, _meta2.meta)(obj);
15344 var tagMeta = (0, _validator.tagMetaFor)(obj);
15345 var propertyTag = (0, _validator.tagFor)(obj, keyName, tagMeta); // We don't use the tag since CPs are not automatic, we just want to avoid
15346 // anything tracking while we get the altKey
15347
15348 (0, _validator.untrack)(() => {
15349 ret = get(obj, this.altKey);
15350 });
15351 var lastRevision = meta$$1.revisionFor(keyName);
15352
15353 if (lastRevision === undefined || !(0, _validator.validateTag)(propertyTag, lastRevision)) {
15354 (0, _validator.updateTag)(propertyTag, getChainTagsForKey(obj, this.altKey, tagMeta, meta$$1));
15355 meta$$1.setRevisionFor(keyName, (0, _validator.valueForTag)(propertyTag));
15356 finishLazyChains(meta$$1, keyName, ret);
15357 }
15358
15359 (0, _validator.consumeTag)(propertyTag);
15360 return ret;
15361 }
15362
15363 set(obj, _keyName, value) {
15364 return set(obj, this.altKey, value);
15365 }
15366
15367 readOnly() {
15368 this.set = AliasedProperty_readOnlySet;
15369 }
15370
15371 oneWay() {
15372 this.set = AliasedProperty_oneWaySet;
15373 }
15374
15375 }
15376
15377 function AliasedProperty_readOnlySet(obj, keyName) {
15378 // eslint-disable-line no-unused-vars
15379 throw new _error.default(`Cannot set read-only property '${keyName}' on object: ${(0, _utils.inspect)(obj)}`);
15380 }
15381
15382 function AliasedProperty_oneWaySet(obj, keyName, value) {
15383 defineProperty(obj, keyName, null);
15384 return set(obj, keyName, value);
15385 }
15386 /**
15387 @module ember
15388 */
15389
15390 /**
15391 Used internally to allow changing properties in a backwards compatible way, and print a helpful
15392 deprecation warning.
15393
15394 @method deprecateProperty
15395 @param {Object} object The object to add the deprecated property to.
15396 @param {String} deprecatedKey The property to add (and print deprecation warnings upon accessing).
15397 @param {String} newKey The property that will be aliased.
15398 @private
15399 @since 1.7.0
15400 */
15401
15402
15403 function deprecateProperty(object, deprecatedKey, newKey, options) {
15404 function _deprecate() {
15405 (true && !(false) && (0, _debug.deprecate)(`Usage of \`${deprecatedKey}\` is deprecated, use \`${newKey}\` instead.`, false, options));
15406 }
15407
15408 Object.defineProperty(object, deprecatedKey, {
15409 configurable: true,
15410 enumerable: false,
15411
15412 set(value) {
15413 _deprecate();
15414
15415 set(this, newKey, value);
15416 },
15417
15418 get() {
15419 _deprecate();
15420
15421 return get(this, newKey);
15422 }
15423
15424 });
15425 }
15426
15427 var EACH_PROXIES = new WeakMap();
15428
15429 function eachProxyArrayWillChange(array, idx, removedCnt, addedCnt) {
15430 var eachProxy = EACH_PROXIES.get(array);
15431
15432 if (eachProxy !== undefined) {
15433 eachProxy.arrayWillChange(array, idx, removedCnt, addedCnt);
15434 }
15435 }
15436
15437 function eachProxyArrayDidChange(array, idx, removedCnt, addedCnt) {
15438 var eachProxy = EACH_PROXIES.get(array);
15439
15440 if (eachProxy !== undefined) {
15441 eachProxy.arrayDidChange(array, idx, removedCnt, addedCnt);
15442 }
15443 }
15444 /**
15445 @module @ember/utils
15446 */
15447
15448 /**
15449 Returns true if the passed value is null or undefined. This avoids errors
15450 from JSLint complaining about use of ==, which can be technically
15451 confusing.
15452
15453 ```javascript
15454 isNone(); // true
15455 isNone(null); // true
15456 isNone(undefined); // true
15457 isNone(''); // false
15458 isNone([]); // false
15459 isNone(function() {}); // false
15460 ```
15461
15462 @method isNone
15463 @static
15464 @for @ember/utils
15465 @param {Object} obj Value to test
15466 @return {Boolean}
15467 @public
15468 */
15469
15470
15471 function isNone(obj) {
15472 return obj === null || obj === undefined;
15473 }
15474 /**
15475 @module @ember/utils
15476 */
15477
15478 /**
15479 Verifies that a value is `null` or `undefined`, an empty string, or an empty
15480 array.
15481
15482 Constrains the rules on `isNone` by returning true for empty strings and
15483 empty arrays.
15484
15485 If the value is an object with a `size` property of type number, it is used
15486 to check emptiness.
15487
15488 ```javascript
15489 isEmpty(); // true
15490 isEmpty(null); // true
15491 isEmpty(undefined); // true
15492 isEmpty(''); // true
15493 isEmpty([]); // true
15494 isEmpty({ size: 0}); // true
15495 isEmpty({}); // false
15496 isEmpty('Adam Hawkins'); // false
15497 isEmpty([0,1,2]); // false
15498 isEmpty('\n\t'); // false
15499 isEmpty(' '); // false
15500 isEmpty({ size: 1 }) // false
15501 isEmpty({ size: () => 0 }) // false
15502 ```
15503
15504 @method isEmpty
15505 @static
15506 @for @ember/utils
15507 @param {Object} obj Value to test
15508 @return {Boolean}
15509 @public
15510 */
15511
15512
15513 function isEmpty(obj) {
15514 var none = obj === null || obj === undefined;
15515
15516 if (none) {
15517 return none;
15518 }
15519
15520 if (typeof obj.size === 'number') {
15521 return !obj.size;
15522 }
15523
15524 var objectType = typeof obj;
15525
15526 if (objectType === 'object') {
15527 var size = get(obj, 'size');
15528
15529 if (typeof size === 'number') {
15530 return !size;
15531 }
15532 }
15533
15534 if (typeof obj.length === 'number' && objectType !== 'function') {
15535 return !obj.length;
15536 }
15537
15538 if (objectType === 'object') {
15539 var length = get(obj, 'length');
15540
15541 if (typeof length === 'number') {
15542 return !length;
15543 }
15544 }
15545
15546 return false;
15547 }
15548 /**
15549 @module @ember/utils
15550 */
15551
15552 /**
15553 A value is blank if it is empty or a whitespace string.
15554
15555 ```javascript
15556 import { isBlank } from '@ember/utils';
15557
15558 isBlank(); // true
15559 isBlank(null); // true
15560 isBlank(undefined); // true
15561 isBlank(''); // true
15562 isBlank([]); // true
15563 isBlank('\n\t'); // true
15564 isBlank(' '); // true
15565 isBlank({}); // false
15566 isBlank('\n\t Hello'); // false
15567 isBlank('Hello world'); // false
15568 isBlank([1,2,3]); // false
15569 ```
15570
15571 @method isBlank
15572 @static
15573 @for @ember/utils
15574 @param {Object} obj Value to test
15575 @return {Boolean}
15576 @since 1.5.0
15577 @public
15578 */
15579
15580
15581 function isBlank(obj) {
15582 return isEmpty(obj) || typeof obj === 'string' && /\S/.test(obj) === false;
15583 }
15584 /**
15585 @module @ember/utils
15586 */
15587
15588 /**
15589 A value is present if it not `isBlank`.
15590
15591 ```javascript
15592 isPresent(); // false
15593 isPresent(null); // false
15594 isPresent(undefined); // false
15595 isPresent(''); // false
15596 isPresent(' '); // false
15597 isPresent('\n\t'); // false
15598 isPresent([]); // false
15599 isPresent({ length: 0 }); // false
15600 isPresent(false); // true
15601 isPresent(true); // true
15602 isPresent('string'); // true
15603 isPresent(0); // true
15604 isPresent(function() {}); // true
15605 isPresent({}); // true
15606 isPresent('\n\t Hello'); // true
15607 isPresent([1, 2, 3]); // true
15608 ```
15609
15610 @method isPresent
15611 @static
15612 @for @ember/utils
15613 @param {Object} obj Value to test
15614 @return {Boolean}
15615 @since 1.8.0
15616 @public
15617 */
15618
15619
15620 function isPresent(obj) {
15621 return !isBlank(obj);
15622 }
15623 /**
15624 @module ember
15625 */
15626
15627 /**
15628 Helper class that allows you to register your library with Ember.
15629
15630 Singleton created at `Ember.libraries`.
15631
15632 @class Libraries
15633 @constructor
15634 @private
15635 */
15636
15637
15638 class Libraries {
15639 constructor() {
15640 this._registry = [];
15641 this._coreLibIndex = 0;
15642 }
15643
15644 _getLibraryByName(name) {
15645 var libs = this._registry;
15646 var count = libs.length;
15647
15648 for (var i = 0; i < count; i++) {
15649 if (libs[i].name === name) {
15650 return libs[i];
15651 }
15652 }
15653
15654 return undefined;
15655 }
15656
15657 register(name, version, isCoreLibrary) {
15658 var index = this._registry.length;
15659
15660 if (!this._getLibraryByName(name)) {
15661 if (isCoreLibrary) {
15662 index = this._coreLibIndex++;
15663 }
15664
15665 this._registry.splice(index, 0, {
15666 name,
15667 version
15668 });
15669 } else {
15670 (true && (0, _debug.warn)(`Library "${name}" is already registered with Ember.`, false, {
15671 id: 'ember-metal.libraries-register'
15672 }));
15673 }
15674 }
15675
15676 registerCoreLibrary(name, version) {
15677 this.register(name, version, true);
15678 }
15679
15680 deRegister(name) {
15681 var lib = this._getLibraryByName(name);
15682
15683 var index;
15684
15685 if (lib) {
15686 index = this._registry.indexOf(lib);
15687
15688 this._registry.splice(index, 1);
15689 }
15690 }
15691
15692 }
15693
15694 _exports.Libraries = Libraries;
15695
15696 if (true
15697 /* DEBUG */
15698 ) {
15699 Libraries.prototype.logVersions = function () {
15700 var libs = this._registry;
15701 var nameLengths = libs.map(item => get(item, 'name.length'));
15702 var maxNameLength = Math.max.apply(null, nameLengths);
15703 (0, _debug.debug)('-------------------------------');
15704
15705 for (var i = 0; i < libs.length; i++) {
15706 var lib = libs[i];
15707 var spaces = new Array(maxNameLength - lib.name.length + 1).join(' ');
15708 (0, _debug.debug)([lib.name, spaces, ' : ', lib.version].join(''));
15709 }
15710
15711 (0, _debug.debug)('-------------------------------');
15712 };
15713 }
15714
15715 var LIBRARIES = new Libraries();
15716 _exports.libraries = LIBRARIES;
15717 LIBRARIES.registerCoreLibrary('Ember', _version.default);
15718 /**
15719 @module @ember/object
15720 */
15721
15722 /**
15723 To get multiple properties at once, call `getProperties`
15724 with an object followed by a list of strings or an array:
15725
15726 ```javascript
15727 import { getProperties } from '@ember/object';
15728
15729 getProperties(record, 'firstName', 'lastName', 'zipCode');
15730 // { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
15731 ```
15732
15733 is equivalent to:
15734
15735 ```javascript
15736 import { getProperties } from '@ember/object';
15737
15738 getProperties(record, ['firstName', 'lastName', 'zipCode']);
15739 // { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
15740 ```
15741
15742 @method getProperties
15743 @static
15744 @for @ember/object
15745 @param {Object} obj
15746 @param {String...|Array} list of keys to get
15747 @return {Object}
15748 @public
15749 */
15750
15751 function getProperties(obj, keys) {
15752 var ret = {};
15753 var propertyNames = arguments;
15754 var i = 1;
15755
15756 if (arguments.length === 2 && Array.isArray(keys)) {
15757 i = 0;
15758 propertyNames = arguments[1];
15759 }
15760
15761 for (; i < propertyNames.length; i++) {
15762 ret[propertyNames[i]] = get(obj, propertyNames[i]);
15763 }
15764
15765 return ret;
15766 }
15767 /**
15768 @module @ember/object
15769 */
15770
15771 /**
15772 Set a list of properties on an object. These properties are set inside
15773 a single `beginPropertyChanges` and `endPropertyChanges` batch, so
15774 observers will be buffered.
15775
15776 ```javascript
15777 import EmberObject from '@ember/object';
15778 let anObject = EmberObject.create();
15779
15780 anObject.setProperties({
15781 firstName: 'Stanley',
15782 lastName: 'Stuart',
15783 age: 21
15784 });
15785 ```
15786
15787 @method setProperties
15788 @static
15789 @for @ember/object
15790 @param obj
15791 @param {Object} properties
15792 @return properties
15793 @public
15794 */
15795
15796
15797 function setProperties(obj, properties) {
15798 if (properties === null || typeof properties !== 'object') {
15799 return properties;
15800 }
15801
15802 changeProperties(() => {
15803 var props = Object.keys(properties);
15804 var propertyName;
15805
15806 for (var i = 0; i < props.length; i++) {
15807 propertyName = props[i];
15808 set(obj, propertyName, properties[propertyName]);
15809 }
15810 });
15811 return properties;
15812 } // move into its own package
15813 // it is needed by Mixin for classToString
15814 // maybe move it into environment
15815
15816
15817 var hasOwnProperty = Object.prototype.hasOwnProperty;
15818 var searchDisabled = false;
15819 var flags = {
15820 _set: 0,
15821 _unprocessedNamespaces: false,
15822
15823 get unprocessedNamespaces() {
15824 return this._unprocessedNamespaces;
15825 },
15826
15827 set unprocessedNamespaces(v) {
15828 this._set++;
15829 this._unprocessedNamespaces = v;
15830 }
15831
15832 };
15833 var unprocessedMixins = false;
15834 var NAMESPACES = [];
15835 _exports.NAMESPACES = NAMESPACES;
15836 var NAMESPACES_BY_ID = Object.create(null);
15837 _exports.NAMESPACES_BY_ID = NAMESPACES_BY_ID;
15838
15839 function addNamespace(namespace) {
15840 flags.unprocessedNamespaces = true;
15841 NAMESPACES.push(namespace);
15842 }
15843
15844 function removeNamespace(namespace) {
15845 var name = (0, _utils.getName)(namespace);
15846 delete NAMESPACES_BY_ID[name];
15847 NAMESPACES.splice(NAMESPACES.indexOf(namespace), 1);
15848
15849 if (name in _environment.context.lookup && namespace === _environment.context.lookup[name]) {
15850 _environment.context.lookup[name] = undefined;
15851 }
15852 }
15853
15854 function findNamespaces() {
15855 if (!flags.unprocessedNamespaces) {
15856 return;
15857 }
15858
15859 var lookup = _environment.context.lookup;
15860 var keys = Object.keys(lookup);
15861
15862 for (var i = 0; i < keys.length; i++) {
15863 var key = keys[i]; // Only process entities that start with uppercase A-Z
15864
15865 if (!isUppercase(key.charCodeAt(0))) {
15866 continue;
15867 }
15868
15869 var obj = tryIsNamespace(lookup, key);
15870
15871 if (obj) {
15872 (0, _utils.setName)(obj, key);
15873 }
15874 }
15875 }
15876
15877 function findNamespace(name) {
15878 if (!searchDisabled) {
15879 processAllNamespaces();
15880 }
15881
15882 return NAMESPACES_BY_ID[name];
15883 }
15884
15885 function processNamespace(namespace) {
15886 _processNamespace([namespace.toString()], namespace, new Set());
15887 }
15888
15889 function processAllNamespaces() {
15890 var unprocessedNamespaces = flags.unprocessedNamespaces;
15891
15892 if (unprocessedNamespaces) {
15893 findNamespaces();
15894 flags.unprocessedNamespaces = false;
15895 }
15896
15897 if (unprocessedNamespaces || unprocessedMixins) {
15898 var namespaces = NAMESPACES;
15899
15900 for (var i = 0; i < namespaces.length; i++) {
15901 processNamespace(namespaces[i]);
15902 }
15903
15904 unprocessedMixins = false;
15905 }
15906 }
15907
15908 function classToString() {
15909 var name = (0, _utils.getName)(this);
15910
15911 if (name !== void 0) {
15912 return name;
15913 }
15914
15915 name = calculateToString(this);
15916 (0, _utils.setName)(this, name);
15917 return name;
15918 }
15919
15920 function isSearchDisabled() {
15921 return searchDisabled;
15922 }
15923
15924 function setSearchDisabled(flag) {
15925 searchDisabled = Boolean(flag);
15926 }
15927
15928 function setUnprocessedMixins() {
15929 unprocessedMixins = true;
15930 }
15931
15932 function _processNamespace(paths, root, seen) {
15933 var idx = paths.length;
15934 var id = paths.join('.');
15935 NAMESPACES_BY_ID[id] = root;
15936 (0, _utils.setName)(root, id); // Loop over all of the keys in the namespace, looking for classes
15937
15938 for (var key in root) {
15939 if (!hasOwnProperty.call(root, key)) {
15940 continue;
15941 }
15942
15943 var obj = root[key]; // If we are processing the `Ember` namespace, for example, the
15944 // `paths` will start with `["Ember"]`. Every iteration through
15945 // the loop will update the **second** element of this list with
15946 // the key, so processing `Ember.View` will make the Array
15947 // `['Ember', 'View']`.
15948
15949 paths[idx] = key; // If we have found an unprocessed class
15950
15951 if (obj && obj.toString === classToString && (0, _utils.getName)(obj) === void 0) {
15952 // Replace the class' `toString` with the dot-separated path
15953 (0, _utils.setName)(obj, paths.join('.')); // Support nested namespaces
15954 } else if (obj && obj.isNamespace) {
15955 // Skip aliased namespaces
15956 if (seen.has(obj)) {
15957 continue;
15958 }
15959
15960 seen.add(obj); // Process the child namespace
15961
15962 _processNamespace(paths, obj, seen);
15963 }
15964 }
15965
15966 paths.length = idx; // cut out last item
15967 }
15968
15969 function isUppercase(code) {
15970 return code >= 65 && code <= 90 // A
15971 ; // Z
15972 }
15973
15974 function tryIsNamespace(lookup, prop) {
15975 try {
15976 var obj = lookup[prop];
15977 return (obj !== null && typeof obj === 'object' || typeof obj === 'function') && obj.isNamespace && obj;
15978 } catch (e) {// continue
15979 }
15980 }
15981
15982 function calculateToString(target) {
15983 var str;
15984
15985 if (!searchDisabled) {
15986 processAllNamespaces();
15987 str = (0, _utils.getName)(target);
15988
15989 if (str !== void 0) {
15990 return str;
15991 }
15992
15993 var superclass = target;
15994
15995 do {
15996 superclass = Object.getPrototypeOf(superclass);
15997
15998 if (superclass === Function.prototype || superclass === Object.prototype) {
15999 break;
16000 }
16001
16002 str = (0, _utils.getName)(target);
16003
16004 if (str !== void 0) {
16005 str = `(subclass of ${str})`;
16006 break;
16007 }
16008 } while (str === void 0);
16009 }
16010
16011 return str || '(unknown)';
16012 }
16013 /**
16014 @module @ember/object
16015 */
16016
16017
16018 var a_concat = Array.prototype.concat;
16019 var {
16020 isArray
16021 } = Array;
16022
16023 function extractAccessors(properties) {
16024 if (properties !== undefined) {
16025 var keys = Object.keys(properties);
16026
16027 for (var i = 0; i < keys.length; i++) {
16028 var key = keys[i];
16029 var desc = Object.getOwnPropertyDescriptor(properties, key);
16030
16031 if (desc.get !== undefined || desc.set !== undefined) {
16032 Object.defineProperty(properties, key, {
16033 value: nativeDescDecorator(desc)
16034 });
16035 }
16036 }
16037 }
16038
16039 return properties;
16040 }
16041
16042 function concatenatedMixinProperties(concatProp, props, values, base) {
16043 // reset before adding each new mixin to pickup concats from previous
16044 var concats = values[concatProp] || base[concatProp];
16045
16046 if (props[concatProp]) {
16047 concats = concats ? a_concat.call(concats, props[concatProp]) : props[concatProp];
16048 }
16049
16050 return concats;
16051 }
16052
16053 function giveDecoratorSuper(key, decorator, property, descs) {
16054 if (property === true) {
16055 return decorator;
16056 }
16057
16058 var originalGetter = property._getter;
16059
16060 if (originalGetter === undefined) {
16061 return decorator;
16062 }
16063
16064 var superDesc = descs[key]; // Check to see if the super property is a decorator first, if so load its descriptor
16065
16066 var superProperty = typeof superDesc === 'function' ? descriptorForDecorator(superDesc) : superDesc;
16067
16068 if (superProperty === undefined || superProperty === true) {
16069 return decorator;
16070 }
16071
16072 var superGetter = superProperty._getter;
16073
16074 if (superGetter === undefined) {
16075 return decorator;
16076 }
16077
16078 var get = (0, _utils.wrap)(originalGetter, superGetter);
16079 var set;
16080 var originalSetter = property._setter;
16081 var superSetter = superProperty._setter;
16082
16083 if (superSetter !== undefined) {
16084 if (originalSetter !== undefined) {
16085 set = (0, _utils.wrap)(originalSetter, superSetter);
16086 } else {
16087 // If the super property has a setter, we default to using it no matter what.
16088 // This is clearly very broken and weird, but it's what was here so we have
16089 // to keep it until the next major at least.
16090 //
16091 // TODO: Add a deprecation here.
16092 set = superSetter;
16093 }
16094 } else {
16095 set = originalSetter;
16096 } // only create a new CP if we must
16097
16098
16099 if (get !== originalGetter || set !== originalSetter) {
16100 // Since multiple mixins may inherit from the same parent, we need
16101 // to clone the computed property so that other mixins do not receive
16102 // the wrapped version.
16103 var dependentKeys = property._dependentKeys || [];
16104 var newProperty = new ComputedProperty([...dependentKeys, {
16105 get,
16106 set
16107 }]);
16108 newProperty._readOnly = property._readOnly;
16109 newProperty._volatile = property._volatile;
16110 newProperty._meta = property._meta;
16111 newProperty.enumerable = property.enumerable;
16112 return makeComputedDecorator(newProperty, ComputedProperty);
16113 }
16114
16115 return decorator;
16116 }
16117
16118 function giveMethodSuper(key, method, values, descs) {
16119 // Methods overwrite computed properties, and do not call super to them.
16120 if (descs[key] !== undefined) {
16121 return method;
16122 } // Find the original method in a parent mixin
16123
16124
16125 var superMethod = values[key]; // Only wrap the new method if the original method was a function
16126
16127 if (typeof superMethod === 'function') {
16128 return (0, _utils.wrap)(method, superMethod);
16129 }
16130
16131 return method;
16132 }
16133
16134 function applyConcatenatedProperties(key, value, values) {
16135 var baseValue = values[key];
16136 var ret = (0, _utils.makeArray)(baseValue).concat((0, _utils.makeArray)(value));
16137
16138 if (true
16139 /* DEBUG */
16140 ) {
16141 // it is possible to use concatenatedProperties with strings (which cannot be frozen)
16142 // only freeze objects...
16143 if (typeof ret === 'object' && ret !== null) {
16144 // prevent mutating `concatenatedProperties` array after it is applied
16145 Object.freeze(ret);
16146 }
16147 }
16148
16149 return ret;
16150 }
16151
16152 function applyMergedProperties(key, value, values) {
16153 var baseValue = values[key];
16154 (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)));
16155
16156 if (!baseValue) {
16157 return value;
16158 }
16159
16160 var newBase = (0, _polyfills.assign)({}, baseValue);
16161 var hasFunction = false;
16162 var props = Object.keys(value);
16163
16164 for (var i = 0; i < props.length; i++) {
16165 var prop = props[i];
16166 var propValue = value[prop];
16167
16168 if (typeof propValue === 'function') {
16169 hasFunction = true;
16170 newBase[prop] = giveMethodSuper(prop, propValue, baseValue, {});
16171 } else {
16172 newBase[prop] = propValue;
16173 }
16174 }
16175
16176 if (hasFunction) {
16177 newBase._super = _utils.ROOT;
16178 }
16179
16180 return newBase;
16181 }
16182
16183 function mergeMixins(mixins, meta$$1, descs, values, base, keys, keysWithSuper) {
16184 var currentMixin;
16185
16186 for (var i = 0; i < mixins.length; i++) {
16187 currentMixin = mixins[i];
16188 (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]'));
16189
16190 if (MIXINS.has(currentMixin)) {
16191 if (meta$$1.hasMixin(currentMixin)) {
16192 continue;
16193 }
16194
16195 meta$$1.addMixin(currentMixin);
16196 var {
16197 properties,
16198 mixins: _mixins
16199 } = currentMixin;
16200
16201 if (properties !== undefined) {
16202 mergeProps(meta$$1, properties, descs, values, base, keys, keysWithSuper);
16203 } else if (_mixins !== undefined) {
16204 mergeMixins(_mixins, meta$$1, descs, values, base, keys, keysWithSuper);
16205
16206 if (currentMixin._without !== undefined) {
16207 currentMixin._without.forEach(keyName => {
16208 // deleting the key means we won't process the value
16209 var index = keys.indexOf(keyName);
16210
16211 if (index !== -1) {
16212 keys.splice(index, 1);
16213 }
16214 });
16215 }
16216 }
16217 } else {
16218 mergeProps(meta$$1, currentMixin, descs, values, base, keys, keysWithSuper);
16219 }
16220 }
16221 }
16222
16223 function mergeProps(meta$$1, props, descs, values, base, keys, keysWithSuper) {
16224 var concats = concatenatedMixinProperties('concatenatedProperties', props, values, base);
16225 var mergings = concatenatedMixinProperties('mergedProperties', props, values, base);
16226 var propKeys = Object.keys(props);
16227
16228 for (var i = 0; i < propKeys.length; i++) {
16229 var key = propKeys[i];
16230 var value = props[key];
16231 if (value === undefined) continue;
16232
16233 if (keys.indexOf(key) === -1) {
16234 keys.push(key);
16235 var desc = meta$$1.peekDescriptors(key);
16236
16237 if (desc === undefined) {
16238 // The superclass did not have a CP, which means it may have
16239 // observers or listeners on that property.
16240 var prev = values[key] = base[key];
16241
16242 if (typeof prev === 'function') {
16243 updateObserversAndListeners(base, key, prev, false);
16244 }
16245 } else {
16246 descs[key] = desc; // The super desc will be overwritten on descs, so save off the fact that
16247 // there was a super so we know to Object.defineProperty when writing
16248 // the value
16249
16250 keysWithSuper.push(key);
16251 desc.teardown(base, key, meta$$1);
16252 }
16253 }
16254
16255 var isFunction = typeof value === 'function';
16256
16257 if (isFunction) {
16258 var _desc2 = descriptorForDecorator(value);
16259
16260 if (_desc2 !== undefined) {
16261 // Wrap descriptor function to implement _super() if needed
16262 descs[key] = giveDecoratorSuper(key, value, _desc2, descs);
16263 values[key] = undefined;
16264 continue;
16265 }
16266 }
16267
16268 if (concats && concats.indexOf(key) >= 0 || key === 'concatenatedProperties' || key === 'mergedProperties') {
16269 value = applyConcatenatedProperties(key, value, values);
16270 } else if (mergings && mergings.indexOf(key) > -1) {
16271 value = applyMergedProperties(key, value, values);
16272 } else if (isFunction) {
16273 value = giveMethodSuper(key, value, values, descs);
16274 }
16275
16276 values[key] = value;
16277 descs[key] = undefined;
16278 }
16279 }
16280
16281 var followMethodAlias;
16282
16283 if (_deprecatedFeatures.ALIAS_METHOD) {
16284 followMethodAlias = function (obj, alias, descs, values) {
16285 var altKey = alias.methodName;
16286 var possibleDesc;
16287 var desc = descs[altKey];
16288 var value = values[altKey];
16289
16290 if (desc !== undefined || value !== undefined) {// do nothing
16291 } else if ((possibleDesc = descriptorForProperty(obj, altKey)) !== undefined) {
16292 desc = possibleDesc;
16293 value = undefined;
16294 } else {
16295 desc = undefined;
16296 value = obj[altKey];
16297 }
16298
16299 return {
16300 desc,
16301 value
16302 };
16303 };
16304 }
16305
16306 function updateObserversAndListeners(obj, key, fn, add) {
16307 var meta$$1 = (0, _utils.observerListenerMetaFor)(fn);
16308 if (meta$$1 === undefined) return;
16309 var {
16310 observers,
16311 listeners
16312 } = meta$$1;
16313
16314 if (observers !== undefined) {
16315 var updateObserver = add ? addObserver : removeObserver;
16316
16317 for (var i = 0; i < observers.paths.length; i++) {
16318 updateObserver(obj, observers.paths[i], null, key, observers.sync);
16319 }
16320 }
16321
16322 if (listeners !== undefined) {
16323 var updateListener = add ? addListener : removeListener;
16324
16325 for (var _i = 0; _i < listeners.length; _i++) {
16326 updateListener(obj, listeners[_i], null, key);
16327 }
16328 }
16329 }
16330
16331 function applyMixin(obj, mixins, _hideKeys = false) {
16332 var descs = Object.create(null);
16333 var values = Object.create(null);
16334 var meta$$1 = (0, _meta2.meta)(obj);
16335 var keys = [];
16336 var keysWithSuper = [];
16337 obj._super = _utils.ROOT; // Go through all mixins and hashes passed in, and:
16338 //
16339 // * Handle concatenated properties
16340 // * Handle merged properties
16341 // * Set up _super wrapping if necessary
16342 // * Set up computed property descriptors
16343 // * Copying `toString` in broken browsers
16344
16345 mergeMixins(mixins, meta$$1, descs, values, obj, keys, keysWithSuper);
16346
16347 for (var i = 0; i < keys.length; i++) {
16348 var key = keys[i];
16349 var value = values[key];
16350 var desc = descs[key];
16351
16352 if (_deprecatedFeatures.ALIAS_METHOD) {
16353 while (value !== undefined && isAlias(value)) {
16354 var followed = followMethodAlias(obj, value, descs, values);
16355 desc = followed.desc;
16356 value = followed.value;
16357 }
16358 }
16359
16360 if (value !== undefined) {
16361 if (typeof value === 'function') {
16362 updateObserversAndListeners(obj, key, value, true);
16363 }
16364
16365 defineValue(obj, key, value, keysWithSuper.indexOf(key) !== -1, !_hideKeys);
16366 } else if (desc !== undefined) {
16367 defineDecorator(obj, key, desc, meta$$1);
16368 }
16369 }
16370
16371 if (!meta$$1.isPrototypeMeta(obj)) {
16372 revalidateObservers(obj);
16373 }
16374
16375 return obj;
16376 }
16377 /**
16378 @method mixin
16379 @param obj
16380 @param mixins*
16381 @return obj
16382 @private
16383 */
16384
16385
16386 function mixin(obj, ...args) {
16387 applyMixin(obj, args);
16388 return obj;
16389 }
16390
16391 var MIXINS = new _polyfills._WeakSet();
16392 /**
16393 The `Mixin` class allows you to create mixins, whose properties can be
16394 added to other classes. For instance,
16395
16396 ```javascript
16397 import Mixin from '@ember/object/mixin';
16398
16399 const EditableMixin = Mixin.create({
16400 edit() {
16401 console.log('starting to edit');
16402 this.set('isEditing', true);
16403 },
16404 isEditing: false
16405 });
16406 ```
16407
16408 ```javascript
16409 import EmberObject from '@ember/object';
16410 import EditableMixin from '../mixins/editable';
16411
16412 // Mix mixins into classes by passing them as the first arguments to
16413 // `.extend.`
16414 const Comment = EmberObject.extend(EditableMixin, {
16415 post: null
16416 });
16417
16418 let comment = Comment.create({
16419 post: somePost
16420 });
16421
16422 comment.edit(); // outputs 'starting to edit'
16423 ```
16424
16425 Note that Mixins are created with `Mixin.create`, not
16426 `Mixin.extend`.
16427
16428 Note that mixins extend a constructor's prototype so arrays and object literals
16429 defined as properties will be shared amongst objects that implement the mixin.
16430 If you want to define a property in a mixin that is not shared, you can define
16431 it either as a computed property or have it be created on initialization of the object.
16432
16433 ```javascript
16434 // filters array will be shared amongst any object implementing mixin
16435 import Mixin from '@ember/object/mixin';
16436 import { A } from '@ember/array';
16437
16438 const FilterableMixin = Mixin.create({
16439 filters: A()
16440 });
16441 ```
16442
16443 ```javascript
16444 import Mixin from '@ember/object/mixin';
16445 import { A } from '@ember/array';
16446 import { computed } from '@ember/object';
16447
16448 // filters will be a separate array for every object implementing the mixin
16449 const FilterableMixin = Mixin.create({
16450 filters: computed(function() {
16451 return A();
16452 })
16453 });
16454 ```
16455
16456 ```javascript
16457 import Mixin from '@ember/object/mixin';
16458 import { A } from '@ember/array';
16459
16460 // filters will be created as a separate array during the object's initialization
16461 const Filterable = Mixin.create({
16462 filters: null,
16463
16464 init() {
16465 this._super(...arguments);
16466 this.set("filters", A());
16467 }
16468 });
16469 ```
16470
16471 @class Mixin
16472 @public
16473 */
16474
16475 class Mixin {
16476 constructor(mixins, properties) {
16477 MIXINS.add(this);
16478 this.properties = extractAccessors(properties);
16479 this.mixins = buildMixinsArray(mixins);
16480 this.ownerConstructor = undefined;
16481 this._without = undefined;
16482
16483 if (true
16484 /* DEBUG */
16485 ) {
16486 /*
16487 In debug builds, we seal mixins to help avoid performance pitfalls.
16488 In IE11 there is a quirk that prevents sealed objects from being added
16489 to a WeakMap. Unfortunately, the mixin system currently relies on
16490 weak maps in `guidFor`, so we need to prime the guid cache weak map.
16491 */
16492 (0, _utils.guidFor)(this);
16493 Object.seal(this);
16494 }
16495 }
16496 /**
16497 @method create
16498 @for @ember/object/mixin
16499 @static
16500 @param arguments*
16501 @public
16502 */
16503
16504
16505 static create(...args) {
16506 setUnprocessedMixins();
16507 var M = this;
16508 return new M(args, undefined);
16509 } // returns the mixins currently applied to the specified object
16510 // TODO: Make `mixin`
16511
16512
16513 static mixins(obj) {
16514 var meta$$1 = (0, _meta2.peekMeta)(obj);
16515 var ret = [];
16516
16517 if (meta$$1 === null) {
16518 return ret;
16519 }
16520
16521 meta$$1.forEachMixins(currentMixin => {
16522 // skip primitive mixins since these are always anonymous
16523 if (!currentMixin.properties) {
16524 ret.push(currentMixin);
16525 }
16526 });
16527 return ret;
16528 }
16529 /**
16530 @method reopen
16531 @param arguments*
16532 @private
16533 */
16534
16535
16536 reopen(...args) {
16537 if (args.length === 0) {
16538 return;
16539 }
16540
16541 if (this.properties) {
16542 var currentMixin = new Mixin(undefined, this.properties);
16543 this.properties = undefined;
16544 this.mixins = [currentMixin];
16545 } else if (!this.mixins) {
16546 this.mixins = [];
16547 }
16548
16549 this.mixins = this.mixins.concat(buildMixinsArray(args));
16550 return this;
16551 }
16552 /**
16553 @method apply
16554 @param obj
16555 @return applied object
16556 @private
16557 */
16558
16559
16560 apply(obj, _hideKeys = false) {
16561 // Ember.NativeArray is a normal Ember.Mixin that we mix into `Array.prototype` when prototype extensions are enabled
16562 // mutating a native object prototype like this should _not_ result in enumerable properties being added (or we have significant
16563 // issues with things like deep equality checks from test frameworks, or things like jQuery.extend(true, [], [])).
16564 //
16565 // _hideKeys disables enumerablity when applying the mixin. This is a hack, and we should stop mutating the array prototype by default 😫
16566 return applyMixin(obj, [this], _hideKeys);
16567 }
16568
16569 applyPartial(obj) {
16570 return applyMixin(obj, [this]);
16571 }
16572 /**
16573 @method detect
16574 @param obj
16575 @return {Boolean}
16576 @private
16577 */
16578
16579
16580 detect(obj) {
16581 if (typeof obj !== 'object' || obj === null) {
16582 return false;
16583 }
16584
16585 if (MIXINS.has(obj)) {
16586 return _detect(obj, this);
16587 }
16588
16589 var meta$$1 = (0, _meta2.peekMeta)(obj);
16590
16591 if (meta$$1 === null) {
16592 return false;
16593 }
16594
16595 return meta$$1.hasMixin(this);
16596 }
16597
16598 without(...args) {
16599 var ret = new Mixin([this]);
16600 ret._without = args;
16601 return ret;
16602 }
16603
16604 keys() {
16605 return _keys(this);
16606 }
16607
16608 toString() {
16609 return '(unknown mixin)';
16610 }
16611
16612 }
16613
16614 _exports.Mixin = Mixin;
16615
16616 function buildMixinsArray(mixins) {
16617 var length = mixins && mixins.length || 0;
16618 var m = undefined;
16619
16620 if (length > 0) {
16621 m = new Array(length);
16622
16623 for (var i = 0; i < length; i++) {
16624 var x = mixins[i];
16625 (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]'));
16626
16627 if (MIXINS.has(x)) {
16628 m[i] = x;
16629 } else {
16630 m[i] = new Mixin(undefined, x);
16631 }
16632 }
16633 }
16634
16635 return m;
16636 }
16637
16638 Mixin.prototype.toString = classToString;
16639
16640 if (true
16641 /* DEBUG */
16642 ) {
16643 Object.seal(Mixin.prototype);
16644 }
16645
16646 function _detect(curMixin, targetMixin, seen = new Set()) {
16647 if (seen.has(curMixin)) {
16648 return false;
16649 }
16650
16651 seen.add(curMixin);
16652
16653 if (curMixin === targetMixin) {
16654 return true;
16655 }
16656
16657 var mixins = curMixin.mixins;
16658
16659 if (mixins) {
16660 return mixins.some(mixin => _detect(mixin, targetMixin, seen));
16661 }
16662
16663 return false;
16664 }
16665
16666 function _keys(mixin, ret = new Set(), seen = new Set()) {
16667 if (seen.has(mixin)) {
16668 return;
16669 }
16670
16671 seen.add(mixin);
16672
16673 if (mixin.properties) {
16674 var props = Object.keys(mixin.properties);
16675
16676 for (var i = 0; i < props.length; i++) {
16677 ret.add(props[i]);
16678 }
16679 } else if (mixin.mixins) {
16680 mixin.mixins.forEach(x => _keys(x, ret, seen));
16681 }
16682
16683 return ret;
16684 }
16685
16686 var AliasImpl;
16687 var isAlias;
16688
16689 if (_deprecatedFeatures.ALIAS_METHOD) {
16690 var ALIASES = new _polyfills._WeakSet();
16691
16692 isAlias = alias => {
16693 return ALIASES.has(alias);
16694 };
16695
16696 AliasImpl = class AliasImpl {
16697 constructor(methodName) {
16698 this.methodName = methodName;
16699 ALIASES.add(this);
16700 }
16701
16702 };
16703 }
16704 /**
16705 Makes a method available via an additional name.
16706
16707 ```app/utils/person.js
16708 import EmberObject, {
16709 aliasMethod
16710 } from '@ember/object';
16711
16712 export default EmberObject.extend({
16713 name() {
16714 return 'Tomhuda Katzdale';
16715 },
16716 moniker: aliasMethod('name')
16717 });
16718 ```
16719
16720 ```javascript
16721 let goodGuy = Person.create();
16722
16723 goodGuy.name(); // 'Tomhuda Katzdale'
16724 goodGuy.moniker(); // 'Tomhuda Katzdale'
16725 ```
16726
16727 @method aliasMethod
16728 @static
16729 @deprecated Use a shared utility method instead
16730 @for @ember/object
16731 @param {String} methodName name of the method to alias
16732 @public
16733 */
16734
16735
16736 var aliasMethod;
16737 _exports.aliasMethod = aliasMethod;
16738
16739 if (_deprecatedFeatures.ALIAS_METHOD) {
16740 _exports.aliasMethod = aliasMethod = function aliasMethod(methodName) {
16741 (true && !(false) && (0, _debug.deprecate)(`You attempted to alias '${methodName}, but aliasMethod has been deprecated. Consider extracting the method into a shared utility function.`, false, {
16742 id: 'object.alias-method',
16743 until: '4.0.0',
16744 url: 'https://emberjs.com/deprecations/v3.x#toc_object-alias-method'
16745 }));
16746 return new AliasImpl(methodName);
16747 };
16748 }
16749
16750 function observer(...args) {
16751 var funcOrDef = args.pop();
16752 (true && !(typeof funcOrDef === 'function' || typeof funcOrDef === 'object' && funcOrDef !== null) && (0, _debug.assert)('observer must be provided a function or an observer definition', typeof funcOrDef === 'function' || typeof funcOrDef === 'object' && funcOrDef !== null));
16753 var func, dependentKeys, sync;
16754
16755 if (typeof funcOrDef === 'function') {
16756 func = funcOrDef;
16757 dependentKeys = args;
16758 sync = !_environment.ENV._DEFAULT_ASYNC_OBSERVERS;
16759 } else {
16760 func = funcOrDef.fn;
16761 dependentKeys = funcOrDef.dependentKeys;
16762 sync = funcOrDef.sync;
16763 }
16764
16765 (true && !(typeof func === 'function') && (0, _debug.assert)('observer called without a function', typeof func === 'function'));
16766 (true && !(Array.isArray(dependentKeys) && dependentKeys.length > 0 && dependentKeys.every(p => typeof p === 'string' && Boolean(p.length))) && (0, _debug.assert)('observer called without valid path', Array.isArray(dependentKeys) && dependentKeys.length > 0 && dependentKeys.every(p => typeof p === 'string' && Boolean(p.length))));
16767 (true && !(typeof sync === 'boolean') && (0, _debug.assert)('observer called without sync', typeof sync === 'boolean'));
16768 var paths = [];
16769
16770 for (var i = 0; i < dependentKeys.length; ++i) {
16771 expandProperties(dependentKeys[i], path => paths.push(path));
16772 }
16773
16774 (0, _utils.setObservers)(func, {
16775 paths,
16776 sync
16777 });
16778 return func;
16779 }
16780
16781 var DEBUG_INJECTION_FUNCTIONS;
16782 _exports.DEBUG_INJECTION_FUNCTIONS = DEBUG_INJECTION_FUNCTIONS;
16783
16784 if (true
16785 /* DEBUG */
16786 ) {
16787 _exports.DEBUG_INJECTION_FUNCTIONS = DEBUG_INJECTION_FUNCTIONS = new WeakMap();
16788 }
16789
16790 function inject(type, ...args) {
16791 (true && !(typeof type === 'string') && (0, _debug.assert)('a string type must be provided to inject', typeof type === 'string'));
16792 var calledAsDecorator = isElementDescriptor(args);
16793 var source, namespace;
16794 var name = calledAsDecorator ? undefined : args[0];
16795 var options = calledAsDecorator ? undefined : args[1];
16796
16797 var getInjection = function (propertyName) {
16798 var owner = (0, _owner.getOwner)(this) || this.container; // fallback to `container` for backwards compat
16799
16800 (true && !(Boolean(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.`, Boolean(owner)));
16801 return owner.lookup(`${type}:${name || propertyName}`, {
16802 source,
16803 namespace
16804 });
16805 };
16806
16807 if (true
16808 /* DEBUG */
16809 ) {
16810 DEBUG_INJECTION_FUNCTIONS.set(getInjection, {
16811 namespace,
16812 source,
16813 type,
16814 name
16815 });
16816 }
16817
16818 var decorator = computed({
16819 get: getInjection,
16820
16821 set(keyName, value) {
16822 defineProperty(this, keyName, null, value);
16823 }
16824
16825 });
16826
16827 if (calledAsDecorator) {
16828 return decorator(args[0], args[1], args[2]);
16829 } else {
16830 return decorator;
16831 }
16832 }
16833
16834 function tracked(...args) {
16835 (true && !(!(isElementDescriptor(args.slice(0, 3)) && args.length === 5 && args[4] === true)) && (0, _debug.assert)(`@tracked can only be used directly as a native decorator. If you're using tracked in classic classes, add parenthesis to call it like a function: tracked()`, !(isElementDescriptor(args.slice(0, 3)) && args.length === 5 && args[4] === true)));
16836
16837 if (!isElementDescriptor(args)) {
16838 var propertyDesc = args[0];
16839 (true && !(args.length === 0 || typeof propertyDesc === 'object' && propertyDesc !== null) && (0, _debug.assert)(`tracked() may only receive an options object containing 'value' or 'initializer', received ${propertyDesc}`, args.length === 0 || typeof propertyDesc === 'object' && propertyDesc !== null));
16840
16841 if (true
16842 /* DEBUG */
16843 && propertyDesc) {
16844 var keys = Object.keys(propertyDesc);
16845 (true && !(keys.length <= 1 && (keys[0] === undefined || keys[0] === 'value' || keys[0] === 'initializer')) && (0, _debug.assert)(`The options object passed to tracked() may only contain a 'value' or 'initializer' property, not both. Received: [${keys}]`, keys.length <= 1 && (keys[0] === undefined || keys[0] === 'value' || keys[0] === 'initializer')));
16846 (true && !(!('initializer' in propertyDesc) || typeof propertyDesc.initializer === 'function') && (0, _debug.assert)(`The initializer passed to tracked must be a function. Received ${propertyDesc.initializer}`, !('initializer' in propertyDesc) || typeof propertyDesc.initializer === 'function'));
16847 }
16848
16849 var initializer = propertyDesc ? propertyDesc.initializer : undefined;
16850 var value = propertyDesc ? propertyDesc.value : undefined;
16851
16852 var decorator = function (target, key, _desc, _meta, isClassicDecorator$$1) {
16853 (true && !(isClassicDecorator$$1) && (0, _debug.assert)(`You attempted to set a default value for ${key} with the @tracked({ value: 'default' }) syntax. You can only use this syntax with classic classes. For native classes, you can use class initializers: @tracked field = 'default';`, isClassicDecorator$$1));
16854 var fieldDesc = {
16855 initializer: initializer || (() => value)
16856 };
16857 return descriptorForField([target, key, fieldDesc]);
16858 };
16859
16860 setClassicDecorator(decorator);
16861 return decorator;
16862 }
16863
16864 return descriptorForField(args);
16865 }
16866
16867 if (true
16868 /* DEBUG */
16869 ) {
16870 // Normally this isn't a classic decorator, but we want to throw a helpful
16871 // error in development so we need it to treat it like one
16872 setClassicDecorator(tracked);
16873 }
16874
16875 function descriptorForField([target, key, desc]) {
16876 (true && !(!desc || !desc.value && !desc.get && !desc.set) && (0, _debug.assert)(`You attempted to use @tracked on ${key}, but that element is not a class field. @tracked is only usable on class fields. Native getters and setters will autotrack add any tracked fields they encounter, so there is no need mark getters and setters with @tracked.`, !desc || !desc.value && !desc.get && !desc.set));
16877 var {
16878 getter,
16879 setter
16880 } = (0, _validator.trackedData)(key, desc ? desc.initializer : undefined);
16881
16882 function get() {
16883 var value = getter(this); // Add the tag of the returned value if it is an array, since arrays
16884 // should always cause updates if they are consumed and then changed
16885
16886 if (Array.isArray(value) || (0, _utils.isEmberArray)(value)) {
16887 (0, _validator.consumeTag)((0, _validator.tagFor)(value, '[]'));
16888 }
16889
16890 return value;
16891 }
16892
16893 function set(newValue) {
16894 setter(this, newValue);
16895 (0, _validator.dirtyTagFor)(this, SELF_TAG);
16896 }
16897
16898 var newDesc = {
16899 enumerable: true,
16900 configurable: true,
16901 isTracked: true,
16902 get,
16903 set
16904 };
16905 (0, _meta2.meta)(target).writeDescriptors(key, new TrackedDescriptor(get, set));
16906 return newDesc;
16907 }
16908
16909 class TrackedDescriptor {
16910 constructor(_get, _set) {
16911 this._get = _get;
16912 this._set = _set;
16913 CHAIN_PASS_THROUGH.add(this);
16914 }
16915
16916 get(obj) {
16917 return this._get.call(obj);
16918 }
16919
16920 set(obj, _key, value) {
16921 this._set.call(obj, value);
16922 }
16923
16924 }
16925 /**
16926 Ember uses caching based on trackable values to avoid updating large portions
16927 of the application. This caching is exposed via a cache primitive that can be
16928 used to cache a specific computation, so that it will not update and will
16929 return the cached value until a tracked value used in its computation has
16930 updated.
16931
16932 @module @glimmer/tracking/primitives/cache
16933 @category EMBER_CACHE_API
16934 @public
16935 */
16936
16937 /**
16938 Receives a function, and returns a wrapped version of it that memoizes based on
16939 _autotracking_. The function will only rerun whenever any tracked values used
16940 within it have changed. Otherwise, it will return the previous value.
16941
16942 ```js
16943 import { tracked } from '@glimmer/tracking';
16944 import { createCache, getValue } from '@glimmer/tracking/primitives/cache';
16945
16946 class State {
16947 @tracked value;
16948 }
16949
16950 let state = new State();
16951 let computeCount = 0;
16952
16953 let counter = createCache(() => {
16954 // consume the state. Now, `counter` will
16955 // only rerun if `state.value` changes.
16956 state.value;
16957
16958 return ++computeCount;
16959 });
16960
16961 getValue(counter); // 1
16962
16963 // returns the same value because no tracked state has changed
16964 getValue(counter); // 1
16965
16966 state.value = 'foo';
16967
16968 // reruns because a tracked value used in the function has changed,
16969 // incermenting the counter
16970 getValue(counter); // 2
16971 ```
16972
16973 @method createCache
16974 @category EMBER_CACHE_API
16975 @static
16976 @for @glimmer/tracking/primitives/cache
16977 @public
16978 */
16979
16980 /**
16981 Gets the value of a cache created with `createCache`.
16982
16983 ```js
16984 import { tracked } from '@glimmer/tracking';
16985 import { createCache, getValue } from '@glimmer/tracking/primitives/cache';
16986
16987 let computeCount = 0;
16988
16989 let counter = createCache(() => {
16990 return ++computeCount;
16991 });
16992
16993 getValue(counter); // 1
16994 ```
16995
16996 @method getValue
16997 @category EMBER_CACHE_API
16998 @static
16999 @for @glimmer/tracking/primitives/cache
17000 @public
17001 */
17002
17003 /**
17004 Can be used to check if a memoized function is _constant_. If no tracked state
17005 was used while running a memoized function, it will never rerun, because nothing
17006 can invalidate its result. `isConst` can be used to determine if a memoized
17007 function is constant or not, in order to optimize code surrounding that
17008 function.
17009
17010 ```js
17011 import { tracked } from '@glimmer/tracking';
17012 import { createCache, getValue, isConst } from '@glimmer/tracking/primitives/cache';
17013
17014 class State {
17015 @tracked value;
17016 }
17017
17018 let state = new State();
17019 let computeCount = 0;
17020
17021 let counter = createCache(() => {
17022 // consume the state
17023 state.value;
17024
17025 return computeCount++;
17026 });
17027
17028 let constCounter = createCache(() => {
17029 return computeCount++;
17030 });
17031
17032 getValue(counter);
17033 getValue(constCounter);
17034
17035 isConst(counter); // false
17036 isConst(constCounter); // true
17037 ```
17038
17039 If called on a cache that hasn't been accessed yet, it will throw an
17040 error. This is because there's no way to know if the function will be constant
17041 or not yet, and so this helps prevent missing an optimization opportunity on
17042 accident.
17043
17044 @method isConst
17045 @category EMBER_CACHE_API
17046 @static
17047 @for @glimmer/tracking/primitives/cache
17048 @public
17049 */
17050
17051});
17052define("@ember/-internals/owner/index", ["exports", "@ember/-internals/utils", "@ember/debug"], function (_exports, _utils, _debug) {
17053 "use strict";
17054
17055 Object.defineProperty(_exports, "__esModule", {
17056 value: true
17057 });
17058 _exports.getOwner = getOwner;
17059 _exports.setOwner = setOwner;
17060 _exports.OWNER = _exports.LEGACY_OWNER = void 0;
17061
17062 /**
17063 @module @ember/application
17064 */
17065 var LEGACY_OWNER = (0, _utils.enumerableSymbol)('LEGACY_OWNER');
17066 _exports.LEGACY_OWNER = LEGACY_OWNER;
17067 var OWNER = (0, _utils.symbol)('OWNER');
17068 /**
17069 Framework objects in an Ember application (components, services, routes, etc.)
17070 are created via a factory and dependency injection system. Each of these
17071 objects is the responsibility of an "owner", which handled its
17072 instantiation and manages its lifetime.
17073
17074 `getOwner` fetches the owner object responsible for an instance. This can
17075 be used to lookup or resolve other class instances, or register new factories
17076 into the owner.
17077
17078 For example, this component dynamically looks up a service based on the
17079 `audioType` passed as an argument:
17080
17081 ```app/components/play-audio.js
17082 import Component from '@glimmer/component';
17083 import { action } from '@ember/object';
17084 import { getOwner } from '@ember/application';
17085
17086 // Usage:
17087 //
17088 // <PlayAudio @audioType={{@model.audioType}} @audioFile={{@model.file}}/>
17089 //
17090 export default class extends Component {
17091 get audioService() {
17092 let owner = getOwner(this);
17093 return owner.lookup(`service:${this.args.audioType}`);
17094 }
17095
17096 @action
17097 onPlay() {
17098 let player = this.audioService;
17099 player.play(this.args.audioFile);
17100 }
17101 }
17102 ```
17103
17104 @method getOwner
17105 @static
17106 @for @ember/application
17107 @param {Object} object An object with an owner.
17108 @return {Object} An owner object.
17109 @since 2.3.0
17110 @public
17111 */
17112
17113 _exports.OWNER = OWNER;
17114
17115 function getOwner(object) {
17116 var owner = object[OWNER];
17117
17118 if (owner === undefined) {
17119 owner = object[LEGACY_OWNER];
17120 (true && !(owner === undefined) && (0, _debug.deprecate)(`You accessed the owner using \`getOwner\` on an object, but it was not set on that object with \`setOwner\`. You must use \`setOwner\` to set the owner on all objects. You cannot use Object.assign().`, owner === undefined, {
17121 id: 'owner.legacy-owner-injection',
17122 until: '3.25.0'
17123 }));
17124 }
17125
17126 return owner;
17127 }
17128 /**
17129 `setOwner` forces a new owner on a given object instance. This is primarily
17130 useful in some testing cases.
17131
17132 @method setOwner
17133 @static
17134 @for @ember/application
17135 @param {Object} object An object instance.
17136 @param {Object} object The new owner object of the object instance.
17137 @since 2.3.0
17138 @public
17139 */
17140
17141
17142 function setOwner(object, owner) {
17143 object[OWNER] = owner;
17144 object[LEGACY_OWNER] = owner;
17145 }
17146});
17147define("@ember/-internals/routing/index", ["exports", "@ember/-internals/routing/lib/ext/controller", "@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"], function (_exports, _controller, _api, _none_location, _hash_location, _history_location, _auto_location, _generate_controller, _controller_for, _dsl, _router, _route, _query_params, _routing, _router2, _cache) {
17148 "use strict";
17149
17150 Object.defineProperty(_exports, "__esModule", {
17151 value: true
17152 });
17153 Object.defineProperty(_exports, "Location", {
17154 enumerable: true,
17155 get: function () {
17156 return _api.default;
17157 }
17158 });
17159 Object.defineProperty(_exports, "NoneLocation", {
17160 enumerable: true,
17161 get: function () {
17162 return _none_location.default;
17163 }
17164 });
17165 Object.defineProperty(_exports, "HashLocation", {
17166 enumerable: true,
17167 get: function () {
17168 return _hash_location.default;
17169 }
17170 });
17171 Object.defineProperty(_exports, "HistoryLocation", {
17172 enumerable: true,
17173 get: function () {
17174 return _history_location.default;
17175 }
17176 });
17177 Object.defineProperty(_exports, "AutoLocation", {
17178 enumerable: true,
17179 get: function () {
17180 return _auto_location.default;
17181 }
17182 });
17183 Object.defineProperty(_exports, "generateController", {
17184 enumerable: true,
17185 get: function () {
17186 return _generate_controller.default;
17187 }
17188 });
17189 Object.defineProperty(_exports, "generateControllerFactory", {
17190 enumerable: true,
17191 get: function () {
17192 return _generate_controller.generateControllerFactory;
17193 }
17194 });
17195 Object.defineProperty(_exports, "controllerFor", {
17196 enumerable: true,
17197 get: function () {
17198 return _controller_for.default;
17199 }
17200 });
17201 Object.defineProperty(_exports, "RouterDSL", {
17202 enumerable: true,
17203 get: function () {
17204 return _dsl.default;
17205 }
17206 });
17207 Object.defineProperty(_exports, "Router", {
17208 enumerable: true,
17209 get: function () {
17210 return _router.default;
17211 }
17212 });
17213 Object.defineProperty(_exports, "Route", {
17214 enumerable: true,
17215 get: function () {
17216 return _route.default;
17217 }
17218 });
17219 Object.defineProperty(_exports, "QueryParams", {
17220 enumerable: true,
17221 get: function () {
17222 return _query_params.default;
17223 }
17224 });
17225 Object.defineProperty(_exports, "RoutingService", {
17226 enumerable: true,
17227 get: function () {
17228 return _routing.default;
17229 }
17230 });
17231 Object.defineProperty(_exports, "RouterService", {
17232 enumerable: true,
17233 get: function () {
17234 return _router2.default;
17235 }
17236 });
17237 Object.defineProperty(_exports, "BucketCache", {
17238 enumerable: true,
17239 get: function () {
17240 return _cache.default;
17241 }
17242 });
17243});
17244define("@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) {
17245 "use strict";
17246
17247 Object.defineProperty(_exports, "__esModule", {
17248 value: true
17249 });
17250 _exports.default = void 0;
17251
17252 /**
17253 @module ember
17254 */
17255 _controller_mixin.default.reopen({
17256 concatenatedProperties: ['queryParams'],
17257
17258 /**
17259 Defines which query parameters the controller accepts.
17260 If you give the names `['category','page']` it will bind
17261 the values of these query parameters to the variables
17262 `this.category` and `this.page`.
17263 By default, Ember coerces query parameter values using `toggleProperty`.
17264 This behavior may lead to unexpected results.
17265 Available queryParam types: `boolean`, `number`, `array`.
17266 If query param type not specified, it will be `string`.
17267 To explicitly configure a query parameter property so it coerces as expected, you must define a type property:
17268 ```javascript
17269 queryParams: [{
17270 category: {
17271 type: 'boolean'
17272 }
17273 }]
17274 ```
17275 @for Ember.ControllerMixin
17276 @property queryParams
17277 @public
17278 */
17279 queryParams: null,
17280
17281 /**
17282 This property is updated to various different callback functions depending on
17283 the current "state" of the backing route. It is used by
17284 `Controller.prototype._qpChanged`.
17285 The methods backing each state can be found in the `Route.prototype._qp` computed
17286 property return value (the `.states` property). The current values are listed here for
17287 the sanity of future travelers:
17288 * `inactive` - This state is used when this controller instance is not part of the active
17289 route hierarchy. Set in `Route.prototype._reset` (a `router.js` microlib hook) and
17290 `Route.prototype.actions.finalizeQueryParamChange`.
17291 * `active` - This state is used when this controller instance is part of the active
17292 route hierarchy. Set in `Route.prototype.actions.finalizeQueryParamChange`.
17293 * `allowOverrides` - This state is used in `Route.prototype.setup` (`route.js` microlib hook).
17294 @method _qpDelegate
17295 @private
17296 */
17297 _qpDelegate: null,
17298
17299 /**
17300 During `Route#setup` observers are created to invoke this method
17301 when any of the query params declared in `Controller#queryParams` property
17302 are changed.
17303 When invoked this method uses the currently active query param update delegate
17304 (see `Controller.prototype._qpDelegate` for details) and invokes it with
17305 the QP key/value being changed.
17306 @method _qpChanged
17307 @private
17308 */
17309 _qpChanged(controller, _prop) {
17310 var dotIndex = _prop.indexOf('.[]');
17311
17312 var prop = dotIndex === -1 ? _prop : _prop.slice(0, dotIndex);
17313 var delegate = controller._qpDelegate;
17314 var value = (0, _metal.get)(controller, prop);
17315 delegate(prop, value);
17316 },
17317
17318 /**
17319 Transition the application into another route. The route may
17320 be either a single route or route path:
17321 ```javascript
17322 aController.transitionToRoute('blogPosts');
17323 aController.transitionToRoute('blogPosts.recentEntries');
17324 ```
17325 Optionally supply a model for the route in question. The model
17326 will be serialized into the URL using the `serialize` hook of
17327 the route:
17328 ```javascript
17329 aController.transitionToRoute('blogPost', aPost);
17330 ```
17331 If a literal is passed (such as a number or a string), it will
17332 be treated as an identifier instead. In this case, the `model`
17333 hook of the route will be triggered:
17334 ```javascript
17335 aController.transitionToRoute('blogPost', 1);
17336 ```
17337 Multiple models will be applied last to first recursively up the
17338 route tree.
17339 ```app/router.js
17340 Router.map(function() {
17341 this.route('blogPost', { path: ':blogPostId' }, function() {
17342 this.route('blogComment', { path: ':blogCommentId', resetNamespace: true });
17343 });
17344 });
17345 ```
17346 ```javascript
17347 aController.transitionToRoute('blogComment', aPost, aComment);
17348 aController.transitionToRoute('blogComment', 1, 13);
17349 ```
17350 It is also possible to pass a URL (a string that starts with a
17351 `/`).
17352 ```javascript
17353 aController.transitionToRoute('/');
17354 aController.transitionToRoute('/blog/post/1/comment/13');
17355 aController.transitionToRoute('/blog/posts?sort=title');
17356 ```
17357 An options hash with a `queryParams` property may be provided as
17358 the final argument to add query parameters to the destination URL.
17359 ```javascript
17360 aController.transitionToRoute('blogPost', 1, {
17361 queryParams: { showComments: 'true' }
17362 });
17363 // if you just want to transition the query parameters without changing the route
17364 aController.transitionToRoute({ queryParams: { sort: 'date' } });
17365 ```
17366 See also [replaceRoute](/ember/release/classes/Ember.ControllerMixin/methods/replaceRoute?anchor=replaceRoute).
17367 @param {String} name the name of the route or a URL
17368 @param {...Object} models the model(s) or identifier(s) to be used
17369 while transitioning to the route.
17370 @param {Object} [options] optional hash with a queryParams property
17371 containing a mapping of query parameters
17372 @for Ember.ControllerMixin
17373 @method transitionToRoute
17374 @public
17375 */
17376 transitionToRoute(...args) {
17377 // target may be either another controller or a router
17378 var target = (0, _metal.get)(this, 'target');
17379 var method = target.transitionToRoute || target.transitionTo;
17380 return method.apply(target, (0, _utils.prefixRouteNameArg)(this, args));
17381 },
17382
17383 /**
17384 Transition into another route while replacing the current URL, if possible.
17385 This will replace the current history entry instead of adding a new one.
17386 Beside that, it is identical to `transitionToRoute` in all other respects.
17387 ```javascript
17388 aController.replaceRoute('blogPosts');
17389 aController.replaceRoute('blogPosts.recentEntries');
17390 ```
17391 Optionally supply a model for the route in question. The model
17392 will be serialized into the URL using the `serialize` hook of
17393 the route:
17394 ```javascript
17395 aController.replaceRoute('blogPost', aPost);
17396 ```
17397 If a literal is passed (such as a number or a string), it will
17398 be treated as an identifier instead. In this case, the `model`
17399 hook of the route will be triggered:
17400 ```javascript
17401 aController.replaceRoute('blogPost', 1);
17402 ```
17403 Multiple models will be applied last to first recursively up the
17404 route tree.
17405 ```app/router.js
17406 Router.map(function() {
17407 this.route('blogPost', { path: ':blogPostId' }, function() {
17408 this.route('blogComment', { path: ':blogCommentId', resetNamespace: true });
17409 });
17410 });
17411 ```
17412 ```
17413 aController.replaceRoute('blogComment', aPost, aComment);
17414 aController.replaceRoute('blogComment', 1, 13);
17415 ```
17416 It is also possible to pass a URL (a string that starts with a
17417 `/`).
17418 ```javascript
17419 aController.replaceRoute('/');
17420 aController.replaceRoute('/blog/post/1/comment/13');
17421 ```
17422 @param {String} name the name of the route or a URL
17423 @param {...Object} models the model(s) or identifier(s) to be used
17424 while transitioning to the route.
17425 @for Ember.ControllerMixin
17426 @method replaceRoute
17427 @public
17428 */
17429 replaceRoute(...args) {
17430 // target may be either another controller or a router
17431 var target = (0, _metal.get)(this, 'target');
17432 var method = target.replaceRoute || target.replaceWith;
17433 return method.apply(target, (0, _utils.prefixRouteNameArg)(this, args));
17434 }
17435
17436 });
17437
17438 var _default = _controller_mixin.default;
17439 _exports.default = _default;
17440});
17441define("@ember/-internals/routing/lib/location/api", ["exports", "@ember/debug"], function (_exports, _debug) {
17442 "use strict";
17443
17444 Object.defineProperty(_exports, "__esModule", {
17445 value: true
17446 });
17447 _exports.default = void 0;
17448
17449 /**
17450 @module @ember/routing
17451 */
17452
17453 /**
17454 Location returns an instance of the correct implementation of
17455 the `location` API.
17456
17457 ## Implementations
17458
17459 You can pass an implementation name (`hash`, `history`, `none`, `auto`) to force a
17460 particular implementation to be used in your application.
17461
17462 See [HashLocation](/ember/release/classes/HashLocation).
17463 See [HistoryLocation](/ember/release/classes/HistoryLocation).
17464 See [NoneLocation](/ember/release/classes/NoneLocation).
17465 See [AutoLocation](/ember/release/classes/AutoLocation).
17466
17467 ## Location API
17468
17469 Each location implementation must provide the following methods:
17470
17471 * implementation: returns the string name used to reference the implementation.
17472 * getURL: returns the current URL.
17473 * setURL(path): sets the current URL.
17474 * replaceURL(path): replace the current URL (optional).
17475 * onUpdateURL(callback): triggers the callback when the URL changes.
17476 * formatURL(url): formats `url` to be placed into `href` attribute.
17477 * detect() (optional): instructs the location to do any feature detection
17478 necessary. If the location needs to redirect to a different URL, it
17479 can cancel routing by setting the `cancelRouterSetup` property on itself
17480 to `false`.
17481
17482 Calling setURL or replaceURL will not trigger onUpdateURL callbacks.
17483
17484 ## Custom implementation
17485
17486 Ember scans `app/locations/*` for extending the Location API.
17487
17488 Example:
17489
17490 ```javascript
17491 import HistoryLocation from '@ember/routing/history-location';
17492
17493 export default class MyHistory {
17494 implementation: 'my-custom-history',
17495 constructor() {
17496 this._history = HistoryLocation.create(...arguments);
17497 }
17498 create() {
17499 return new this(...arguments);
17500 }
17501 pushState(path) {
17502 this._history.pushState(path);
17503 }
17504 }
17505 ```
17506
17507 @class Location
17508 @private
17509 */
17510 var _default = {
17511 /**
17512 This is deprecated in favor of using the container to lookup the location
17513 implementation as desired.
17514 For example:
17515 ```javascript
17516 // Given a location registered as follows:
17517 container.register('location:history-test', HistoryTestLocation);
17518 // You could create a new instance via:
17519 container.lookup('location:history-test');
17520 ```
17521 @method create
17522 @param {Object} options
17523 @return {Object} an instance of an implementation of the `location` API
17524 @deprecated Use the container to lookup the location implementation that you
17525 need.
17526 @private
17527 */
17528 create(options) {
17529 var implementation = options && options.implementation;
17530 (true && !(Boolean(implementation)) && (0, _debug.assert)("Location.create: you must specify a 'implementation' option", Boolean(implementation)));
17531 var implementationClass = this.implementations[implementation];
17532 (true && !(Boolean(implementationClass)) && (0, _debug.assert)(`Location.create: ${implementation} is not a valid implementation`, Boolean(implementationClass)));
17533 return implementationClass.create(...arguments);
17534 },
17535
17536 implementations: {}
17537 };
17538 _exports.default = _default;
17539});
17540define("@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) {
17541 "use strict";
17542
17543 Object.defineProperty(_exports, "__esModule", {
17544 value: true
17545 });
17546 _exports.getHistoryPath = getHistoryPath;
17547 _exports.getHashPath = getHashPath;
17548 _exports.default = void 0;
17549
17550 /**
17551 @module @ember/routing
17552 */
17553
17554 /**
17555 AutoLocation will select the best location option based off browser
17556 support with the priority order: history, hash, none.
17557
17558 Clean pushState paths accessed by hashchange-only browsers will be redirected
17559 to the hash-equivalent and vice versa so future transitions are consistent.
17560
17561 Keep in mind that since some of your users will use `HistoryLocation`, your
17562 server must serve the Ember app at all the routes you define.
17563
17564 Browsers that support the `history` API will use `HistoryLocation`, those that
17565 do not, but still support the `hashchange` event will use `HashLocation`, and
17566 in the rare case neither is supported will use `NoneLocation`.
17567
17568 Example:
17569
17570 ```app/router.js
17571 Router.map(function() {
17572 this.route('posts', function() {
17573 this.route('new');
17574 });
17575 });
17576
17577 Router.reopen({
17578 location: 'auto'
17579 });
17580 ```
17581
17582 This will result in a posts.new url of `/posts/new` for modern browsers that
17583 support the `history` api or `/#/posts/new` for older ones, like Internet
17584 Explorer 9 and below.
17585
17586 When a user visits a link to your application, they will be automatically
17587 upgraded or downgraded to the appropriate `Location` class, with the URL
17588 transformed accordingly, if needed.
17589
17590 Keep in mind that since some of your users will use `HistoryLocation`, your
17591 server must serve the Ember app at all the routes you define.
17592
17593 @class AutoLocation
17594 @static
17595 @protected
17596 */
17597 class AutoLocation extends _runtime.Object {
17598 constructor() {
17599 super(...arguments);
17600 this.implementation = 'auto';
17601 }
17602 /**
17603 Called by the router to instruct the location to do any feature detection
17604 necessary. In the case of AutoLocation, we detect whether to use history
17605 or hash concrete implementations.
17606 @private
17607 */
17608
17609
17610 detect() {
17611 var rootURL = this.rootURL;
17612 (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) === '/'));
17613 var implementation = detectImplementation({
17614 location: this.location,
17615 history: this.history,
17616 userAgent: this.userAgent,
17617 rootURL,
17618 documentMode: this.documentMode,
17619 global: this.global
17620 });
17621
17622 if (implementation === false) {
17623 (0, _metal.set)(this, 'cancelRouterSetup', true);
17624 implementation = 'none';
17625 }
17626
17627 var concrete = (0, _owner.getOwner)(this).lookup(`location:${implementation}`);
17628 (true && !(concrete !== undefined) && (0, _debug.assert)(`Could not find location '${implementation}'.`, concrete !== undefined));
17629 (0, _metal.set)(concrete, 'rootURL', rootURL);
17630 (0, _metal.set)(this, 'concreteImplementation', concrete);
17631 }
17632
17633 willDestroy() {
17634 var {
17635 concreteImplementation
17636 } = this;
17637
17638 if (concreteImplementation) {
17639 concreteImplementation.destroy();
17640 }
17641 }
17642
17643 }
17644
17645 _exports.default = AutoLocation;
17646 AutoLocation.reopen({
17647 /**
17648 @private
17649 Will be pre-pended to path upon state change.
17650 @since 1.5.1
17651 @property rootURL
17652 @default '/'
17653 */
17654 rootURL: '/',
17655 initState: delegateToConcreteImplementation('initState'),
17656 getURL: delegateToConcreteImplementation('getURL'),
17657 setURL: delegateToConcreteImplementation('setURL'),
17658 replaceURL: delegateToConcreteImplementation('replaceURL'),
17659 onUpdateURL: delegateToConcreteImplementation('onUpdateURL'),
17660 formatURL: delegateToConcreteImplementation('formatURL'),
17661
17662 /**
17663 @private
17664 The browser's `location` object. This is typically equivalent to
17665 `window.location`, but may be overridden for testing.
17666 @property location
17667 @default environment.location
17668 */
17669 location: _browserEnvironment.location,
17670
17671 /**
17672 @private
17673 The browser's `history` object. This is typically equivalent to
17674 `window.history`, but may be overridden for testing.
17675 @since 1.5.1
17676 @property history
17677 @default environment.history
17678 */
17679 history: _browserEnvironment.history,
17680
17681 /**
17682 @private
17683 The user agent's global variable. In browsers, this will be `window`.
17684 @since 1.11
17685 @property global
17686 @default window
17687 */
17688 global: _browserEnvironment.window,
17689
17690 /**
17691 @private
17692 The browser's `userAgent`. This is typically equivalent to
17693 `navigator.userAgent`, but may be overridden for testing.
17694 @since 1.5.1
17695 @property userAgent
17696 @default environment.history
17697 */
17698 userAgent: _browserEnvironment.userAgent,
17699
17700 /**
17701 @private
17702 This property is used by the router to know whether to cancel the routing
17703 setup process, which is needed while we redirect the browser.
17704 @since 1.5.1
17705 @property cancelRouterSetup
17706 @default false
17707 */
17708 cancelRouterSetup: false
17709 });
17710
17711 function delegateToConcreteImplementation(methodName) {
17712 return function (...args) {
17713 var {
17714 concreteImplementation
17715 } = this;
17716 (true && !(Boolean(concreteImplementation)) && (0, _debug.assert)("AutoLocation's detect() method should be called before calling any other hooks.", Boolean(concreteImplementation)));
17717 return (0, _utils.tryInvoke)(concreteImplementation, methodName, args);
17718 };
17719 }
17720
17721 function detectImplementation(options) {
17722 var {
17723 location,
17724 userAgent,
17725 history,
17726 documentMode,
17727 global,
17728 rootURL
17729 } = options;
17730 var implementation = 'none';
17731 var cancelRouterSetup = false;
17732 var currentPath = (0, _util.getFullPath)(location);
17733
17734 if ((0, _util.supportsHistory)(userAgent, history)) {
17735 var historyPath = getHistoryPath(rootURL, location); // If the browser supports history and we have a history path, we can use
17736 // the history location with no redirects.
17737
17738 if (currentPath === historyPath) {
17739 implementation = 'history';
17740 } else if (currentPath.substr(0, 2) === '/#') {
17741 history.replaceState({
17742 path: historyPath
17743 }, '', historyPath);
17744 implementation = 'history';
17745 } else {
17746 cancelRouterSetup = true;
17747 (0, _util.replacePath)(location, historyPath);
17748 }
17749 } else if ((0, _util.supportsHashChange)(documentMode, global)) {
17750 var hashPath = getHashPath(rootURL, location); // Be sure we're using a hashed path, otherwise let's switch over it to so
17751 // we start off clean and consistent. We'll count an index path with no
17752 // hash as "good enough" as well.
17753
17754 if (currentPath === hashPath || currentPath === '/' && hashPath === '/#/') {
17755 implementation = 'hash';
17756 } else {
17757 // Our URL isn't in the expected hash-supported format, so we want to
17758 // cancel the router setup and replace the URL to start off clean
17759 cancelRouterSetup = true;
17760 (0, _util.replacePath)(location, hashPath);
17761 }
17762 }
17763
17764 if (cancelRouterSetup) {
17765 return false;
17766 }
17767
17768 return implementation;
17769 }
17770 /**
17771 @private
17772
17773 Returns the current path as it should appear for HistoryLocation supported
17774 browsers. This may very well differ from the real current path (e.g. if it
17775 starts off as a hashed URL)
17776 */
17777
17778
17779 function getHistoryPath(rootURL, location) {
17780 var path = (0, _util.getPath)(location);
17781 var hash = (0, _util.getHash)(location);
17782 var query = (0, _util.getQuery)(location);
17783 var rootURLIndex = path.indexOf(rootURL);
17784 var routeHash, hashParts;
17785 (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
17786 // with `#/`. Anything else should NOT be considered a route and should
17787 // be passed straight through, without transformation.
17788
17789 if (hash.substr(0, 2) === '#/') {
17790 // There could be extra hash segments after the route
17791 hashParts = hash.substr(1).split('#'); // The first one is always the route url
17792
17793 routeHash = hashParts.shift(); // If the path already has a trailing slash, remove the one
17794 // from the hashed route so we don't double up.
17795
17796 if (path.charAt(path.length - 1) === '/') {
17797 routeHash = routeHash.substr(1);
17798 } // This is the "expected" final order
17799
17800
17801 path += routeHash + query;
17802
17803 if (hashParts.length) {
17804 path += `#${hashParts.join('#')}`;
17805 }
17806 } else {
17807 path += query + hash;
17808 }
17809
17810 return path;
17811 }
17812 /**
17813 @private
17814
17815 Returns the current path as it should appear for HashLocation supported
17816 browsers. This may very well differ from the real current path.
17817
17818 @method _getHashPath
17819 */
17820
17821
17822 function getHashPath(rootURL, location) {
17823 var path = rootURL;
17824 var historyPath = getHistoryPath(rootURL, location);
17825 var routePath = historyPath.substr(rootURL.length);
17826
17827 if (routePath !== '') {
17828 if (routePath[0] !== '/') {
17829 routePath = `/${routePath}`;
17830 }
17831
17832 path += `#${routePath}`;
17833 }
17834
17835 return path;
17836 }
17837});
17838define("@ember/-internals/routing/lib/location/hash_location", ["exports", "@ember/-internals/metal", "@ember/-internals/runtime", "@ember/runloop", "@ember/-internals/routing/lib/location/util"], function (_exports, _metal, _runtime, _runloop, _util) {
17839 "use strict";
17840
17841 Object.defineProperty(_exports, "__esModule", {
17842 value: true
17843 });
17844 _exports.default = void 0;
17845
17846 /**
17847 @module @ember/routing
17848 */
17849
17850 /**
17851 `HashLocation` implements the location API using the browser's
17852 hash. At present, it relies on a `hashchange` event existing in the
17853 browser.
17854
17855 Using `HashLocation` results in URLs with a `#` (hash sign) separating the
17856 server side URL portion of the URL from the portion that is used by Ember.
17857
17858 Example:
17859
17860 ```app/router.js
17861 Router.map(function() {
17862 this.route('posts', function() {
17863 this.route('new');
17864 });
17865 });
17866
17867 Router.reopen({
17868 location: 'hash'
17869 });
17870 ```
17871
17872 This will result in a posts.new url of `/#/posts/new`.
17873
17874 @class HashLocation
17875 @extends EmberObject
17876 @protected
17877 */
17878 class HashLocation extends _runtime.Object {
17879 constructor() {
17880 super(...arguments);
17881 this.implementation = 'hash';
17882 }
17883
17884 init() {
17885 (0, _metal.set)(this, 'location', this._location || window.location);
17886 this._hashchangeHandler = undefined;
17887 }
17888 /**
17889 @private
17890 Returns normalized location.hash
17891 @since 1.5.1
17892 @method getHash
17893 */
17894
17895
17896 getHash() {
17897 return (0, _util.getHash)(this.location);
17898 }
17899 /**
17900 Returns the normalized URL, constructed from `location.hash`.
17901 e.g. `#/foo` => `/foo` as well as `#/foo#bar` => `/foo#bar`.
17902 By convention, hashed paths must begin with a forward slash, otherwise they
17903 are not treated as a path so we can distinguish intent.
17904 @private
17905 @method getURL
17906 */
17907
17908
17909 getURL() {
17910 var originalPath = this.getHash().substr(1);
17911 var outPath = originalPath;
17912
17913 if (outPath[0] !== '/') {
17914 outPath = '/'; // Only add the # if the path isn't empty.
17915 // We do NOT want `/#` since the ampersand
17916 // is only included (conventionally) when
17917 // the location.hash has a value
17918
17919 if (originalPath) {
17920 outPath += `#${originalPath}`;
17921 }
17922 }
17923
17924 return outPath;
17925 }
17926 /**
17927 Set the `location.hash` and remembers what was set. This prevents
17928 `onUpdateURL` callbacks from triggering when the hash was set by
17929 `HashLocation`.
17930 @private
17931 @method setURL
17932 @param path {String}
17933 */
17934
17935
17936 setURL(path) {
17937 this.location.hash = path;
17938 (0, _metal.set)(this, 'lastSetURL', path);
17939 }
17940 /**
17941 Uses location.replace to update the url without a page reload
17942 or history modification.
17943 @private
17944 @method replaceURL
17945 @param path {String}
17946 */
17947
17948
17949 replaceURL(path) {
17950 this.location.replace(`#${path}`);
17951 (0, _metal.set)(this, 'lastSetURL', path);
17952 }
17953 /**
17954 Register a callback to be invoked when the hash changes. These
17955 callbacks will execute when the user presses the back or forward
17956 button, but not after `setURL` is invoked.
17957 @private
17958 @method onUpdateURL
17959 @param callback {Function}
17960 */
17961
17962
17963 onUpdateURL(callback) {
17964 this._removeEventListener();
17965
17966 this._hashchangeHandler = (0, _runloop.bind)(this, function () {
17967 var path = this.getURL();
17968
17969 if (this.lastSetURL === path) {
17970 return;
17971 }
17972
17973 (0, _metal.set)(this, 'lastSetURL', null);
17974 callback(path);
17975 });
17976 window.addEventListener('hashchange', this._hashchangeHandler);
17977 }
17978 /**
17979 Given a URL, formats it to be placed into the page as part
17980 of an element's `href` attribute.
17981 This is used, for example, when using the {{action}} helper
17982 to generate a URL based on an event.
17983 @private
17984 @method formatURL
17985 @param url {String}
17986 */
17987
17988
17989 formatURL(url) {
17990 return `#${url}`;
17991 }
17992 /**
17993 Cleans up the HashLocation event listener.
17994 @private
17995 @method willDestroy
17996 */
17997
17998
17999 willDestroy() {
18000 this._removeEventListener();
18001 }
18002
18003 _removeEventListener() {
18004 if (this._hashchangeHandler) {
18005 window.removeEventListener('hashchange', this._hashchangeHandler);
18006 }
18007 }
18008
18009 }
18010
18011 _exports.default = HashLocation;
18012});
18013define("@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) {
18014 "use strict";
18015
18016 Object.defineProperty(_exports, "__esModule", {
18017 value: true
18018 });
18019 _exports.default = void 0;
18020
18021 /**
18022 @module @ember/routing
18023 */
18024 var popstateFired = false;
18025
18026 function _uuid() {
18027 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
18028 var r, v;
18029 r = Math.random() * 16 | 0;
18030 v = c === 'x' ? r : r & 3 | 8;
18031 return v.toString(16);
18032 });
18033 }
18034 /**
18035 HistoryLocation implements the location API using the browser's
18036 history.pushState API.
18037
18038 Using `HistoryLocation` results in URLs that are indistinguishable from a
18039 standard URL. This relies upon the browser's `history` API.
18040
18041 Example:
18042
18043 ```app/router.js
18044 Router.map(function() {
18045 this.route('posts', function() {
18046 this.route('new');
18047 });
18048 });
18049
18050 Router.reopen({
18051 location: 'history'
18052 });
18053 ```
18054
18055 This will result in a posts.new url of `/posts/new`.
18056
18057 Keep in mind that your server must serve the Ember app at all the routes you
18058 define.
18059
18060 @class HistoryLocation
18061 @extends EmberObject
18062 @protected
18063 */
18064
18065
18066 class HistoryLocation extends _runtime.Object {
18067 constructor() {
18068 super(...arguments);
18069 this.implementation = 'history';
18070 /**
18071 Will be pre-pended to path upon state change
18072 @property rootURL
18073 @default '/'
18074 @private
18075 */
18076
18077 this.rootURL = '/';
18078 }
18079 /**
18080 @private
18081 Returns normalized location.hash
18082 @method getHash
18083 */
18084
18085
18086 getHash() {
18087 return (0, _util.getHash)(this.location);
18088 }
18089
18090 init() {
18091 this._super(...arguments);
18092
18093 var base = document.querySelector('base');
18094 var baseURL = '';
18095
18096 if (base !== null && base.hasAttribute('href')) {
18097 baseURL = base.getAttribute('href');
18098 }
18099
18100 (0, _metal.set)(this, 'baseURL', baseURL);
18101 (0, _metal.set)(this, 'location', this.location || window.location);
18102 this._popstateHandler = undefined;
18103 }
18104 /**
18105 Used to set state on first call to setURL
18106 @private
18107 @method initState
18108 */
18109
18110
18111 initState() {
18112 var history = this.history || window.history;
18113 (0, _metal.set)(this, 'history', history);
18114 var {
18115 state
18116 } = history;
18117 var path = this.formatURL(this.getURL());
18118
18119 if (state && state.path === path) {
18120 // preserve existing state
18121 // used for webkit workaround, since there will be no initial popstate event
18122 this._previousURL = this.getURL();
18123 } else {
18124 this.replaceState(path);
18125 }
18126 }
18127 /**
18128 Returns the current `location.pathname` without `rootURL` or `baseURL`
18129 @private
18130 @method getURL
18131 @return url {String}
18132 */
18133
18134
18135 getURL() {
18136 var {
18137 location,
18138 rootURL,
18139 baseURL
18140 } = this;
18141 var path = location.pathname; // remove trailing slashes if they exists
18142
18143 rootURL = rootURL.replace(/\/$/, '');
18144 baseURL = baseURL.replace(/\/$/, ''); // remove baseURL and rootURL from start of path
18145
18146 var url = path.replace(new RegExp(`^${baseURL}(?=/|$)`), '').replace(new RegExp(`^${rootURL}(?=/|$)`), '').replace(/\/\//g, '/'); // remove extra slashes
18147
18148 var search = location.search || '';
18149 url += search + this.getHash();
18150 return url;
18151 }
18152 /**
18153 Uses `history.pushState` to update the url without a page reload.
18154 @private
18155 @method setURL
18156 @param path {String}
18157 */
18158
18159
18160 setURL(path) {
18161 var {
18162 state
18163 } = this.history;
18164 path = this.formatURL(path);
18165
18166 if (!state || state.path !== path) {
18167 this.pushState(path);
18168 }
18169 }
18170 /**
18171 Uses `history.replaceState` to update the url without a page reload
18172 or history modification.
18173 @private
18174 @method replaceURL
18175 @param path {String}
18176 */
18177
18178
18179 replaceURL(path) {
18180 var {
18181 state
18182 } = this.history;
18183 path = this.formatURL(path);
18184
18185 if (!state || state.path !== path) {
18186 this.replaceState(path);
18187 }
18188 }
18189 /**
18190 Pushes a new state.
18191 @private
18192 @method pushState
18193 @param path {String}
18194 */
18195
18196
18197 pushState(path) {
18198 var state = {
18199 path,
18200 uuid: _uuid()
18201 };
18202 this.history.pushState(state, null, path); // used for webkit workaround
18203
18204 this._previousURL = this.getURL();
18205 }
18206 /**
18207 Replaces the current state.
18208 @private
18209 @method replaceState
18210 @param path {String}
18211 */
18212
18213
18214 replaceState(path) {
18215 var state = {
18216 path,
18217 uuid: _uuid()
18218 };
18219 this.history.replaceState(state, null, path); // used for webkit workaround
18220
18221 this._previousURL = this.getURL();
18222 }
18223 /**
18224 Register a callback to be invoked whenever the browser
18225 history changes, including using forward and back buttons.
18226 @private
18227 @method onUpdateURL
18228 @param callback {Function}
18229 */
18230
18231
18232 onUpdateURL(callback) {
18233 this._removeEventListener();
18234
18235 this._popstateHandler = () => {
18236 // Ignore initial page load popstate event in Chrome
18237 if (!popstateFired) {
18238 popstateFired = true;
18239
18240 if (this.getURL() === this._previousURL) {
18241 return;
18242 }
18243 }
18244
18245 callback(this.getURL());
18246 };
18247
18248 window.addEventListener('popstate', this._popstateHandler);
18249 }
18250 /**
18251 Used when using `{{action}}` helper. The url is always appended to the rootURL.
18252 @private
18253 @method formatURL
18254 @param url {String}
18255 @return formatted url {String}
18256 */
18257
18258
18259 formatURL(url) {
18260 var {
18261 rootURL,
18262 baseURL
18263 } = this;
18264
18265 if (url !== '') {
18266 // remove trailing slashes if they exists
18267 rootURL = rootURL.replace(/\/$/, '');
18268 baseURL = baseURL.replace(/\/$/, '');
18269 } else if (baseURL[0] === '/' && rootURL[0] === '/') {
18270 // if baseURL and rootURL both start with a slash
18271 // ... remove trailing slash from baseURL if it exists
18272 baseURL = baseURL.replace(/\/$/, '');
18273 }
18274
18275 return baseURL + rootURL + url;
18276 }
18277 /**
18278 Cleans up the HistoryLocation event listener.
18279 @private
18280 @method willDestroy
18281 */
18282
18283
18284 willDestroy() {
18285 this._removeEventListener();
18286 }
18287
18288 _removeEventListener() {
18289 if (this._popstateHandler) {
18290 window.removeEventListener('popstate', this._popstateHandler);
18291 }
18292 }
18293
18294 }
18295
18296 _exports.default = HistoryLocation;
18297});
18298define("@ember/-internals/routing/lib/location/none_location", ["exports", "@ember/-internals/metal", "@ember/-internals/runtime", "@ember/debug"], function (_exports, _metal, _runtime, _debug) {
18299 "use strict";
18300
18301 Object.defineProperty(_exports, "__esModule", {
18302 value: true
18303 });
18304 _exports.default = void 0;
18305
18306 /**
18307 @module @ember/routing
18308 */
18309
18310 /**
18311 NoneLocation does not interact with the browser. It is useful for
18312 testing, or when you need to manage state with your Router, but temporarily
18313 don't want it to muck with the URL (for example when you embed your
18314 application in a larger page).
18315
18316 Using `NoneLocation` causes Ember to not store the applications URL state
18317 in the actual URL. This is generally used for testing purposes, and is one
18318 of the changes made when calling `App.setupForTesting()`.
18319
18320 @class NoneLocation
18321 @extends EmberObject
18322 @protected
18323 */
18324 class NoneLocation extends _runtime.Object {
18325 constructor() {
18326 super(...arguments);
18327 this.implementation = 'none';
18328 }
18329
18330 detect() {
18331 var {
18332 rootURL
18333 } = this;
18334 (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) === '/'));
18335 }
18336 /**
18337 Returns the current path without `rootURL`.
18338 @private
18339 @method getURL
18340 @return {String} path
18341 */
18342
18343
18344 getURL() {
18345 var {
18346 path,
18347 rootURL
18348 } = this; // remove trailing slashes if they exists
18349
18350 rootURL = rootURL.replace(/\/$/, ''); // remove rootURL from url
18351
18352 return path.replace(new RegExp(`^${rootURL}(?=/|$)`), '');
18353 }
18354 /**
18355 Set the path and remembers what was set. Using this method
18356 to change the path will not invoke the `updateURL` callback.
18357 @private
18358 @method setURL
18359 @param path {String}
18360 */
18361
18362
18363 setURL(path) {
18364 (0, _metal.set)(this, 'path', path);
18365 }
18366 /**
18367 Register a callback to be invoked when the path changes. These
18368 callbacks will execute when the user presses the back or forward
18369 button, but not after `setURL` is invoked.
18370 @private
18371 @method onUpdateURL
18372 @param callback {Function}
18373 */
18374
18375
18376 onUpdateURL(callback) {
18377 this.updateCallback = callback;
18378 }
18379 /**
18380 Sets the path and calls the `updateURL` callback.
18381 @private
18382 @method handleURL
18383 @param url {String}
18384 */
18385
18386
18387 handleURL(url) {
18388 (0, _metal.set)(this, 'path', url);
18389 this.updateCallback(url);
18390 }
18391 /**
18392 Given a URL, formats it to be placed into the page as part
18393 of an element's `href` attribute.
18394 This is used, for example, when using the {{action}} helper
18395 to generate a URL based on an event.
18396 @private
18397 @method formatURL
18398 @param url {String}
18399 @return {String} url
18400 */
18401
18402
18403 formatURL(url) {
18404 var {
18405 rootURL
18406 } = this;
18407
18408 if (url !== '') {
18409 // remove trailing slashes if they exists
18410 rootURL = rootURL.replace(/\/$/, '');
18411 }
18412
18413 return rootURL + url;
18414 }
18415
18416 }
18417
18418 _exports.default = NoneLocation;
18419 NoneLocation.reopen({
18420 path: '',
18421
18422 /**
18423 Will be pre-pended to path.
18424 @private
18425 @property rootURL
18426 @default '/'
18427 */
18428 rootURL: '/'
18429 });
18430});
18431define("@ember/-internals/routing/lib/location/util", ["exports"], function (_exports) {
18432 "use strict";
18433
18434 Object.defineProperty(_exports, "__esModule", {
18435 value: true
18436 });
18437 _exports.getPath = getPath;
18438 _exports.getQuery = getQuery;
18439 _exports.getHash = getHash;
18440 _exports.getFullPath = getFullPath;
18441 _exports.getOrigin = getOrigin;
18442 _exports.supportsHashChange = supportsHashChange;
18443 _exports.supportsHistory = supportsHistory;
18444 _exports.replacePath = replacePath;
18445
18446 /**
18447 @private
18448
18449 Returns the current `location.pathname`, normalized for IE inconsistencies.
18450 */
18451 function getPath(location) {
18452 var pathname = location.pathname; // Various versions of IE/Opera don't always return a leading slash
18453
18454 if (pathname[0] !== '/') {
18455 pathname = `/${pathname}`;
18456 }
18457
18458 return pathname;
18459 }
18460 /**
18461 @private
18462
18463 Returns the current `location.search`.
18464 */
18465
18466
18467 function getQuery(location) {
18468 return location.search;
18469 }
18470 /**
18471 @private
18472
18473 Returns the hash or empty string
18474 */
18475
18476
18477 function getHash(location) {
18478 if (location.hash !== undefined) {
18479 return location.hash.substr(0);
18480 }
18481
18482 return '';
18483 }
18484
18485 function getFullPath(location) {
18486 return getPath(location) + getQuery(location) + getHash(location);
18487 }
18488
18489 function getOrigin(location) {
18490 var origin = location.origin; // Older browsers, especially IE, don't have origin
18491
18492 if (!origin) {
18493 origin = `${location.protocol}//${location.hostname}`;
18494
18495 if (location.port) {
18496 origin += `:${location.port}`;
18497 }
18498 }
18499
18500 return origin;
18501 }
18502 /*
18503 `documentMode` only exist in Internet Explorer, and it's tested because IE8 running in
18504 IE7 compatibility mode claims to support `onhashchange` but actually does not.
18505
18506 `global` is an object that may have an `onhashchange` property.
18507
18508 @private
18509 @function supportsHashChange
18510 */
18511
18512
18513 function supportsHashChange(documentMode, global) {
18514 return global && 'onhashchange' in global && (documentMode === undefined || documentMode > 7);
18515 }
18516 /*
18517 `userAgent` is a user agent string. We use user agent testing here, because
18518 the stock Android browser is known to have buggy versions of the History API,
18519 in some Android versions.
18520
18521 @private
18522 @function supportsHistory
18523 */
18524
18525
18526 function supportsHistory(userAgent, history) {
18527 // Boosted from Modernizr: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js
18528 // The stock browser on Android 2.2 & 2.3, and 4.0.x returns positive on history support
18529 // Unfortunately support is really buggy and there is no clean way to detect
18530 // these bugs, so we fall back to a user agent sniff :(
18531 // We only want Android 2 and 4.0, stock browser, and not Chrome which identifies
18532 // itself as 'Mobile Safari' as well, nor Windows Phone.
18533 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) {
18534 return false;
18535 }
18536
18537 return Boolean(history && 'pushState' in history);
18538 }
18539 /**
18540 Replaces the current location, making sure we explicitly include the origin
18541 to prevent redirecting to a different origin.
18542
18543 @private
18544 */
18545
18546
18547 function replacePath(location, path) {
18548 location.replace(getOrigin(location) + path);
18549 }
18550});
18551define("@ember/-internals/routing/lib/services/router", ["exports", "@ember/-internals/runtime", "@ember/debug", "@ember/object/computed", "@ember/polyfills", "@ember/service", "@ember/-internals/routing/lib/utils"], function (_exports, _runtime, _debug, _computed, _polyfills, _service, _utils) {
18552 "use strict";
18553
18554 Object.defineProperty(_exports, "__esModule", {
18555 value: true
18556 });
18557 _exports.default = void 0;
18558 var freezeRouteInfo;
18559
18560 if (true
18561 /* DEBUG */
18562 ) {
18563 freezeRouteInfo = transition => {
18564 if (transition.from !== null && !Object.isFrozen(transition.from)) {
18565 Object.freeze(transition.from);
18566 }
18567
18568 if (transition.to !== null && !Object.isFrozen(transition.to)) {
18569 Object.freeze(transition.to);
18570 }
18571 };
18572 }
18573
18574 function cleanURL(url, rootURL) {
18575 if (rootURL === '/') {
18576 return url;
18577 }
18578
18579 return url.substr(rootURL.length, url.length);
18580 }
18581 /**
18582 The Router service is the public API that provides access to the router.
18583
18584 The immediate benefit of the Router service is that you can inject it into components,
18585 giving them a friendly way to initiate transitions and ask questions about the current
18586 global router state.
18587
18588 In this example, the Router service is injected into a component to initiate a transition
18589 to a dedicated route:
18590
18591 ```app/components/example.js
18592 import Component from '@glimmer/component';
18593 import { action } from '@ember/object';
18594 import { inject as service } from '@ember/service';
18595
18596 export default class ExampleComponent extends Component {
18597 @service router;
18598
18599 @action
18600 next() {
18601 this.router.transitionTo('other.route');
18602 }
18603 }
18604 ```
18605
18606 Like any service, it can also be injected into helpers, routes, etc.
18607
18608 @public
18609 @extends Service
18610 @class RouterService
18611 */
18612
18613
18614 class RouterService extends _service.default {
18615 init() {
18616 super.init(...arguments);
18617
18618 this._router.on('routeWillChange', transition => {
18619 if (true
18620 /* DEBUG */
18621 ) {
18622 freezeRouteInfo(transition);
18623 }
18624
18625 this.trigger('routeWillChange', transition);
18626 });
18627
18628 this._router.on('routeDidChange', transition => {
18629 if (true
18630 /* DEBUG */
18631 ) {
18632 freezeRouteInfo(transition);
18633 }
18634
18635 this.trigger('routeDidChange', transition);
18636 });
18637 }
18638 /**
18639 Transition the application into another route. The route may
18640 be either a single route or route path:
18641 See [transitionTo](/ember/release/classes/Route/methods/transitionTo?anchor=transitionTo) for more info.
18642 Calling `transitionTo` from the Router service will cause default query parameter values to be included in the URL.
18643 This behavior is different from calling `transitionTo` on a route or `transitionToRoute` on a controller.
18644 See the [Router Service RFC](https://github.com/emberjs/rfcs/blob/master/text/0095-router-service.md#query-parameter-semantics) for more info.
18645 In the following example we use the Router service to navigate to a route with a
18646 specific model from a Component in the first action, and in the second we trigger
18647 a query-params only transition.
18648 ```app/components/example.js
18649 import Component from '@glimmer/component';
18650 import { action } from '@ember/object';
18651 import { inject as service } from '@ember/service';
18652 export default class extends Component {
18653 @service router;
18654 @action
18655 goToComments(post) {
18656 this.router.transitionTo('comments', post);
18657 }
18658 @action
18659 fetchMoreComments(latestComment) {
18660 this.router.transitionTo({
18661 queryParams: { commentsAfter: latestComment }
18662 });
18663 }
18664 }
18665 ```
18666 @method transitionTo
18667 @param {String} [routeNameOrUrl] the name of the route or a URL
18668 @param {...Object} [models] the model(s) or identifier(s) to be used while
18669 transitioning to the route.
18670 @param {Object} [options] optional hash with a queryParams property
18671 containing a mapping of query parameters. May be supplied as the only
18672 parameter to trigger a query-parameter-only transition.
18673 @return {Transition} the transition object associated with this
18674 attempted transition
18675 @public
18676 */
18677
18678
18679 transitionTo(...args) {
18680 if ((0, _utils.resemblesURL)(args[0])) {
18681 // NOTE: this `args[0] as string` cast is safe and TS correctly infers it
18682 // in 3.6+, so it can be removed when TS is upgraded.
18683 return this._router._doURLTransition('transitionTo', args[0]);
18684 }
18685
18686 var {
18687 routeName,
18688 models,
18689 queryParams
18690 } = (0, _utils.extractRouteArgs)(args);
18691
18692 var transition = this._router._doTransition(routeName, models, queryParams, true);
18693
18694 transition['_keepDefaultQueryParamValues'] = true;
18695 return transition;
18696 }
18697 /**
18698 Similar to `transitionTo`, but instead of adding the destination to the browser's URL history,
18699 it replaces the entry for the current route.
18700 When the user clicks the "back" button in the browser, there will be fewer steps.
18701 This is most commonly used to manage redirects in a way that does not cause confusing additions
18702 to the user's browsing history.
18703 See [replaceWith](/ember/release/classes/Route/methods/replaceWith?anchor=replaceWith) for more info.
18704 Calling `replaceWith` from the Router service will cause default query parameter values to be included in the URL.
18705 This behavior is different from calling `replaceWith` on a route.
18706 See the [Router Service RFC](https://github.com/emberjs/rfcs/blob/master/text/0095-router-service.md#query-parameter-semantics) for more info.
18707 Usage example:
18708 ```app/routes/application.js
18709 import Route from '@ember/routing/route';
18710 export default class extends Route {
18711 beforeModel() {
18712 if (!authorized()){
18713 this.replaceWith('unauthorized');
18714 }
18715 }
18716 });
18717 ```
18718 @method replaceWith
18719 @param {String} routeNameOrUrl the name of the route or a URL of the desired destination
18720 @param {...Object} models the model(s) or identifier(s) to be used while
18721 transitioning to the route i.e. an object of params to pass to the destination route
18722 @param {Object} [options] optional hash with a queryParams property
18723 containing a mapping of query parameters
18724 @return {Transition} the transition object associated with this
18725 attempted transition
18726 @public
18727 */
18728
18729
18730 replaceWith()
18731 /* routeNameOrUrl, ...models, options */
18732 {
18733 return this.transitionTo(...arguments).method('replace');
18734 }
18735 /**
18736 Generate a URL based on the supplied route name and optionally a model. The
18737 URL is returned as a string that can be used for any purpose.
18738 In this example, the URL for the `author.books` route for a given author
18739 is copied to the clipboard.
18740 ```app/templates/application.hbs
18741 <CopyLink @author={{hash id="tomster" name="Tomster"}} />
18742 ```
18743 ```app/components/copy-link.js
18744 import Component from '@glimmer/component';
18745 import { inject as service } from '@ember/service';
18746 import { action } from '@ember/object';
18747 export default class CopyLinkComponent extends Component {
18748 @service router;
18749 @service clipboard;
18750 @action
18751 copyBooksURL() {
18752 if (this.author) {
18753 const url = this.router.urlFor('author.books', this.args.author);
18754 this.clipboard.set(url);
18755 // Clipboard now has /author/tomster/books
18756 }
18757 }
18758 }
18759 ```
18760 Just like with `transitionTo` and `replaceWith`, `urlFor` can also handle
18761 query parameters.
18762 ```app/templates/application.hbs
18763 <CopyLink @author={{hash id="tomster" name="Tomster"}} />
18764 ```
18765 ```app/components/copy-link.js
18766 import Component from '@glimmer/component';
18767 import { inject as service } from '@ember/service';
18768 import { action } from '@ember/object';
18769 export default class CopyLinkComponent extends Component {
18770 @service router;
18771 @service clipboard;
18772 @action
18773 copyOnlyEmberBooksURL() {
18774 if (this.author) {
18775 const url = this.router.urlFor('author.books', this.author, {
18776 queryParams: { filter: 'emberjs' }
18777 });
18778 this.clipboard.set(url);
18779 // Clipboard now has /author/tomster/books?filter=emberjs
18780 }
18781 }
18782 }
18783 ```
18784 @method urlFor
18785 @param {String} routeName the name of the route
18786 @param {...Object} models the model(s) or identifier(s) to be used while
18787 transitioning to the route.
18788 @param {Object} [options] optional hash with a queryParams property
18789 containing a mapping of query parameters
18790 @return {String} the string representing the generated URL
18791 @public
18792 */
18793
18794
18795 urlFor(routeName, ...args) {
18796 return this._router.generate(routeName, ...args);
18797 }
18798 /**
18799 Returns `true` if `routeName/models/queryParams` is the active route, where `models` and `queryParams` are optional.
18800 See [model](api/ember/release/classes/Route/methods/model?anchor=model) and
18801 [queryParams](/api/ember/3.7/classes/Route/properties/queryParams?anchor=queryParams) for more information about these arguments.
18802 In the following example, `isActive` will return `true` if the current route is `/posts`.
18803 ```app/components/posts.js
18804 import Component from '@glimmer/component';
18805 import { inject as service } from '@ember/service';
18806 export default class extends Component {
18807 @service router;
18808 displayComments() {
18809 return this.get('router').isActive('posts');
18810 }
18811 });
18812 ```
18813 The next example includes a dynamic segment, and will return `true` if the current route is `/posts/1`,
18814 assuming the post has an id of 1:
18815 ```app/components/posts.js
18816 import Component from '@glimmer/component';
18817 import { inject as service } from '@ember/service';
18818 export default class extends Component {
18819 @service router;
18820 displayComments(post) {
18821 return this.get('router').isActive('posts', post.id);
18822 }
18823 });
18824 ```
18825 Where `post.id` is the id of a specific post, which is represented in the route as /posts/[post.id].
18826 If `post.id` is equal to 1, then isActive will return true if the current route is /posts/1, and false if the route is anything else.
18827 @method isActive
18828 @param {String} routeName the name of the route
18829 @param {...Object} models the model(s) or identifier(s) to be used when determining the active route.
18830 @param {Object} [options] optional hash with a queryParams property
18831 containing a mapping of query parameters
18832 @return {boolean} true if the provided routeName/models/queryParams are active
18833 @public
18834 */
18835
18836
18837 isActive(...args) {
18838 var {
18839 routeName,
18840 models,
18841 queryParams
18842 } = (0, _utils.extractRouteArgs)(args);
18843 var routerMicrolib = this._router._routerMicrolib; // UNSAFE: casting `routeName as string` here encodes the existing
18844 // assumption but may be wrong: `extractRouteArgs` correctly returns it as
18845 // `string | undefined`. There may be bugs if `isActiveIntent` does
18846 // not correctly account for `undefined` values for `routeName`. Spoilers:
18847 // it *does not* account for this being `undefined`.
18848
18849 if (!routerMicrolib.isActiveIntent(routeName, models)) {
18850 return false;
18851 }
18852
18853 var hasQueryParams = Object.keys(queryParams).length > 0;
18854
18855 if (hasQueryParams) {
18856 queryParams = (0, _polyfills.assign)({}, queryParams);
18857
18858 this._router._prepareQueryParams( // UNSAFE: casting `routeName as string` here encodes the existing
18859 // assumption but may be wrong: `extractRouteArgs` correctly returns it
18860 // as `string | undefined`. There may be bugs if `_prepareQueryParams`
18861 // does not correctly account for `undefined` values for `routeName`.
18862 // Spoilers: under the hood this currently uses router.js APIs which
18863 // *do not* account for this being `undefined`.
18864 routeName, models, // UNSAFE: downstream consumers treat this as `QueryParam`, which the
18865 // type system here *correctly* reports as incorrect, because it may be
18866 // just an empty object.
18867 queryParams, true
18868 /* fromRouterService */
18869 );
18870
18871 return (0, _utils.shallowEqual)(queryParams, routerMicrolib.state.queryParams);
18872 }
18873
18874 return true;
18875 }
18876 /**
18877 Takes a string URL and returns a `RouteInfo` for the leafmost route represented
18878 by the URL. Returns `null` if the URL is not recognized. This method expects to
18879 receive the actual URL as seen by the browser including the app's `rootURL`.
18880 See [RouteInfo](/ember/release/classes/RouteInfo) for more info.
18881 In the following example `recognize` is used to verify if a path belongs to our
18882 application before transitioning to it.
18883 ```
18884 import Component from '@ember/component';
18885 import { inject as service } from '@ember/service';
18886 export default class extends Component {
18887 @service router;
18888 path = '/';
18889 click() {
18890 if (this.router.recognize(this.path)) {
18891 this.router.transitionTo(this.path);
18892 }
18893 }
18894 }
18895 ```
18896 @method recognize
18897 @param {String} url
18898 @public
18899 */
18900
18901
18902 recognize(url) {
18903 (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));
18904 var internalURL = cleanURL(url, this.rootURL);
18905 return this._router._routerMicrolib.recognize(internalURL);
18906 }
18907 /**
18908 Takes a string URL and returns a promise that resolves to a
18909 `RouteInfoWithAttributes` for the leafmost route represented by the URL.
18910 The promise rejects if the URL is not recognized or an unhandled exception
18911 is encountered. This method expects to receive the actual URL as seen by
18912 the browser including the app's `rootURL`.
18913 @method recognizeAndLoad
18914 @param {String} url
18915 @public
18916 */
18917
18918
18919 recognizeAndLoad(url) {
18920 (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));
18921 var internalURL = cleanURL(url, this.rootURL);
18922 return this._router._routerMicrolib.recognizeAndLoad(internalURL);
18923 }
18924
18925 }
18926
18927 _exports.default = RouterService;
18928 RouterService.reopen(_runtime.Evented, {
18929 /**
18930 Name of the current route.
18931 This property represents the logical name of the route,
18932 which is comma separated.
18933 For the following router:
18934 ```app/router.js
18935 Router.map(function() {
18936 this.route('about');
18937 this.route('blog', function () {
18938 this.route('post', { path: ':post_id' });
18939 });
18940 });
18941 ```
18942 It will return:
18943 * `index` when you visit `/`
18944 * `about` when you visit `/about`
18945 * `blog.index` when you visit `/blog`
18946 * `blog.post` when you visit `/blog/some-post-id`
18947 @property currentRouteName
18948 @type String
18949 @public
18950 */
18951 currentRouteName: (0, _computed.readOnly)('_router.currentRouteName'),
18952
18953 /**
18954 Current URL for the application.
18955 This property represents the URL path for this route.
18956 For the following router:
18957 ```app/router.js
18958 Router.map(function() {
18959 this.route('about');
18960 this.route('blog', function () {
18961 this.route('post', { path: ':post_id' });
18962 });
18963 });
18964 ```
18965 It will return:
18966 * `/` when you visit `/`
18967 * `/about` when you visit `/about`
18968 * `/blog` when you visit `/blog`
18969 * `/blog/some-post-id` when you visit `/blog/some-post-id`
18970 @property currentURL
18971 @type String
18972 @public
18973 */
18974 currentURL: (0, _computed.readOnly)('_router.currentURL'),
18975
18976 /**
18977 The `location` property returns what implementation of the `location` API
18978 your application is using, which determines what type of URL is being used.
18979 See [Location](/ember/release/classes/Location) for more information.
18980 To force a particular `location` API implementation to be used in your
18981 application you can set a location type on your `config/environment`.
18982 For example, to set the `history` type:
18983 ```config/environment.js
18984 'use strict';
18985 module.exports = function(environment) {
18986 let ENV = {
18987 modulePrefix: 'router-service',
18988 environment,
18989 rootURL: '/',
18990 locationType: 'history',
18991 ...
18992 }
18993 }
18994 ```
18995 The following location types are available by default:
18996 `auto`, `hash`, `history`, `none`.
18997 See [HashLocation](/ember/release/classes/HashLocation).
18998 See [HistoryLocation](/ember/release/classes/HistoryLocation).
18999 See [NoneLocation](/ember/release/classes/NoneLocation).
19000 See [AutoLocation](/ember/release/classes/AutoLocation).
19001 @property location
19002 @default 'hash'
19003 @see {Location}
19004 @public
19005 */
19006 location: (0, _computed.readOnly)('_router.location'),
19007
19008 /**
19009 The `rootURL` property represents the URL of the root of
19010 the application, '/' by default.
19011 This prefix is assumed on all routes defined on this app.
19012 If you change the `rootURL` in your environment configuration
19013 like so:
19014 ```config/environment.js
19015 'use strict';
19016 module.exports = function(environment) {
19017 let ENV = {
19018 modulePrefix: 'router-service',
19019 environment,
19020 rootURL: '/my-root',
19021
19022 }
19023 ]
19024 ```
19025 This property will return `/my-root`.
19026 @property rootURL
19027 @default '/'
19028 @public
19029 */
19030 rootURL: (0, _computed.readOnly)('_router.rootURL'),
19031
19032 /**
19033 The `currentRoute` property contains metadata about the current leaf route.
19034 It returns a `RouteInfo` object that has information like the route name,
19035 params, query params and more.
19036 See [RouteInfo](/ember/release/classes/RouteInfo) for more info.
19037 This property is guaranteed to change whenever a route transition
19038 happens (even when that transition only changes parameters
19039 and doesn't change the active route).
19040 Usage example:
19041 ```app/components/header.js
19042 import Component from '@glimmer/component';
19043 import { inject as service } from '@ember/service';
19044 import { notEmpty } from '@ember/object/computed';
19045 export default class extends Component {
19046 @service router;
19047 @notEmpty('router.currentRoute.child') isChildRoute;
19048 });
19049 ```
19050 @property currentRoute
19051 @type RouteInfo
19052 @public
19053 */
19054 currentRoute: (0, _computed.readOnly)('_router.currentRoute')
19055 });
19056});
19057define("@ember/-internals/routing/lib/services/routing", ["exports", "@ember/object/computed", "@ember/polyfills", "@ember/service"], function (_exports, _computed, _polyfills, _service) {
19058 "use strict";
19059
19060 Object.defineProperty(_exports, "__esModule", {
19061 value: true
19062 });
19063 _exports.default = void 0;
19064
19065 /**
19066 @module ember
19067 */
19068
19069 /**
19070 The Routing service is used by LinkComponent, and provides facilities for
19071 the component/view layer to interact with the router.
19072
19073 This is a private service for internal usage only. For public usage,
19074 refer to the `Router` service.
19075
19076 @private
19077 @class RoutingService
19078 */
19079 class RoutingService extends _service.default {
19080 hasRoute(routeName) {
19081 return this.router.hasRoute(routeName);
19082 }
19083
19084 transitionTo(routeName, models, queryParams, shouldReplace) {
19085 var transition = this.router._doTransition(routeName, models, queryParams);
19086
19087 if (shouldReplace) {
19088 transition.method('replace');
19089 }
19090
19091 return transition;
19092 }
19093
19094 normalizeQueryParams(routeName, models, queryParams) {
19095 this.router._prepareQueryParams(routeName, models, queryParams);
19096 }
19097
19098 generateURL(routeName, models, queryParams) {
19099 var router = this.router; // return early when the router microlib is not present, which is the case for {{link-to}} in integration tests
19100
19101 if (!router._routerMicrolib) {
19102 return;
19103 }
19104
19105 var visibleQueryParams = {};
19106
19107 if (queryParams) {
19108 (0, _polyfills.assign)(visibleQueryParams, queryParams);
19109 this.normalizeQueryParams(routeName, models, visibleQueryParams);
19110 }
19111
19112 return router.generate(routeName, ...models, {
19113 queryParams: visibleQueryParams
19114 });
19115 }
19116
19117 isActiveForRoute(contexts, queryParams, routeName, routerState, isCurrentWhenSpecified) {
19118 var handlers = this.router._routerMicrolib.recognizer.handlersFor(routeName);
19119
19120 var leafName = handlers[handlers.length - 1].handler;
19121 var maximumContexts = numberOfContextsAcceptedByHandler(routeName, handlers); // NOTE: any ugliness in the calculation of activeness is largely
19122 // due to the fact that we support automatic normalizing of
19123 // `resource` -> `resource.index`, even though there might be
19124 // dynamic segments / query params defined on `resource.index`
19125 // which complicates (and makes somewhat ambiguous) the calculation
19126 // of activeness for links that link to `resource` instead of
19127 // directly to `resource.index`.
19128 // if we don't have enough contexts revert back to full route name
19129 // this is because the leaf route will use one of the contexts
19130
19131 if (contexts.length > maximumContexts) {
19132 routeName = leafName;
19133 }
19134
19135 return routerState.isActiveIntent(routeName, contexts, queryParams, !isCurrentWhenSpecified);
19136 }
19137
19138 }
19139
19140 _exports.default = RoutingService;
19141 RoutingService.reopen({
19142 targetState: (0, _computed.readOnly)('router.targetState'),
19143 currentState: (0, _computed.readOnly)('router.currentState'),
19144 currentRouteName: (0, _computed.readOnly)('router.currentRouteName'),
19145 currentPath: (0, _computed.readOnly)('router.currentPath')
19146 });
19147
19148 function numberOfContextsAcceptedByHandler(handlerName, handlerInfos) {
19149 var req = 0;
19150
19151 for (var i = 0; i < handlerInfos.length; i++) {
19152 req += handlerInfos[i].names.length;
19153
19154 if (handlerInfos[i].handler === handlerName) {
19155 break;
19156 }
19157 }
19158
19159 return req;
19160 }
19161});
19162define("@ember/-internals/routing/lib/system/cache", ["exports"], function (_exports) {
19163 "use strict";
19164
19165 Object.defineProperty(_exports, "__esModule", {
19166 value: true
19167 });
19168 _exports.default = void 0;
19169
19170 /**
19171 A two-tiered cache with support for fallback values when doing lookups.
19172 Uses "buckets" and then "keys" to cache values.
19173
19174 @private
19175 @class BucketCache
19176 */
19177 class BucketCache {
19178 constructor() {
19179 this.cache = new Map();
19180 }
19181
19182 has(bucketKey) {
19183 return this.cache.has(bucketKey);
19184 }
19185
19186 stash(bucketKey, key, value) {
19187 var bucket = this.cache.get(bucketKey);
19188
19189 if (bucket === undefined) {
19190 bucket = new Map();
19191 this.cache.set(bucketKey, bucket);
19192 }
19193
19194 bucket.set(key, value);
19195 }
19196
19197 lookup(bucketKey, prop, defaultValue) {
19198 if (!this.has(bucketKey)) {
19199 return defaultValue;
19200 }
19201
19202 var bucket = this.cache.get(bucketKey);
19203
19204 if (bucket.has(prop)) {
19205 return bucket.get(prop);
19206 } else {
19207 return defaultValue;
19208 }
19209 }
19210
19211 }
19212
19213 _exports.default = BucketCache;
19214});
19215define("@ember/-internals/routing/lib/system/controller_for", ["exports"], function (_exports) {
19216 "use strict";
19217
19218 Object.defineProperty(_exports, "__esModule", {
19219 value: true
19220 });
19221 _exports.default = controllerFor;
19222
19223 /**
19224 @module ember
19225 */
19226
19227 /**
19228 Finds a controller instance.
19229
19230 @for Ember
19231 @method controllerFor
19232 @private
19233 */
19234 function controllerFor(container, controllerName, lookupOptions) {
19235 return container.lookup(`controller:${controllerName}`, lookupOptions);
19236 }
19237});
19238define("@ember/-internals/routing/lib/system/dsl", ["exports", "@ember/debug", "@ember/polyfills"], function (_exports, _debug, _polyfills) {
19239 "use strict";
19240
19241 Object.defineProperty(_exports, "__esModule", {
19242 value: true
19243 });
19244 _exports.default = void 0;
19245 var uuid = 0;
19246
19247 function isCallback(value) {
19248 return typeof value === 'function';
19249 }
19250
19251 function isOptions(value) {
19252 return value !== null && typeof value === 'object';
19253 }
19254
19255 class DSLImpl {
19256 constructor(name = null, options) {
19257 this.explicitIndex = false;
19258 this.parent = name;
19259 this.enableLoadingSubstates = Boolean(options && options.enableLoadingSubstates);
19260 this.matches = [];
19261 this.options = options;
19262 }
19263
19264 route(name, _options, _callback) {
19265 var options;
19266 var callback = null;
19267 var dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
19268
19269 if (isCallback(_options)) {
19270 (true && !(arguments.length === 2) && (0, _debug.assert)('Unexpected arguments', arguments.length === 2));
19271 options = {};
19272 callback = _options;
19273 } else if (isCallback(_callback)) {
19274 (true && !(arguments.length === 3) && (0, _debug.assert)('Unexpected arguments', arguments.length === 3));
19275 (true && !(isOptions(_options)) && (0, _debug.assert)('Unexpected arguments', isOptions(_options)));
19276 options = _options;
19277 callback = _callback;
19278 } else {
19279 options = _options || {};
19280 }
19281
19282 (true && !((() => {
19283 if (options.overrideNameAssertion === true) {
19284 return true;
19285 }
19286
19287 return ['basic', 'application'].indexOf(name) === -1;
19288 })()) && (0, _debug.assert)(`'${name}' cannot be used as a route name.`, (() => {
19289 if (options.overrideNameAssertion === true) {
19290 return true;
19291 }
19292
19293 return ['basic', 'application'].indexOf(name) === -1;
19294 })()));
19295 (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));
19296
19297 if (this.enableLoadingSubstates) {
19298 createRoute(this, `${name}_loading`, {
19299 resetNamespace: options.resetNamespace
19300 });
19301 createRoute(this, `${name}_error`, {
19302 resetNamespace: options.resetNamespace,
19303 path: dummyErrorRoute
19304 });
19305 }
19306
19307 if (callback) {
19308 var fullName = getFullName(this, name, options.resetNamespace);
19309 var dsl = new DSLImpl(fullName, this.options);
19310 createRoute(dsl, 'loading');
19311 createRoute(dsl, 'error', {
19312 path: dummyErrorRoute
19313 });
19314 callback.call(dsl);
19315 createRoute(this, name, options, dsl.generate());
19316 } else {
19317 createRoute(this, name, options);
19318 }
19319 }
19320 /* eslint-enable no-dupe-class-members */
19321
19322
19323 push(url, name, callback, serialize) {
19324 var parts = name.split('.');
19325
19326 if (this.options.engineInfo) {
19327 var localFullName = name.slice(this.options.engineInfo.fullName.length + 1);
19328 var routeInfo = (0, _polyfills.assign)({
19329 localFullName
19330 }, this.options.engineInfo);
19331
19332 if (serialize) {
19333 routeInfo.serializeMethod = serialize;
19334 }
19335
19336 this.options.addRouteForEngine(name, routeInfo);
19337 } else if (serialize) {
19338 throw new Error(`Defining a route serializer on route '${name}' outside an Engine is not allowed.`);
19339 }
19340
19341 if (url === '' || url === '/' || parts[parts.length - 1] === 'index') {
19342 this.explicitIndex = true;
19343 }
19344
19345 this.matches.push(url, name, callback);
19346 }
19347
19348 generate() {
19349 var dslMatches = this.matches;
19350
19351 if (!this.explicitIndex) {
19352 this.route('index', {
19353 path: '/'
19354 });
19355 }
19356
19357 return match => {
19358 for (var i = 0; i < dslMatches.length; i += 3) {
19359 match(dslMatches[i]).to(dslMatches[i + 1], dslMatches[i + 2]);
19360 }
19361 };
19362 }
19363
19364 mount(_name, options = {}) {
19365 var engineRouteMap = this.options.resolveRouteMap(_name);
19366 var name = _name;
19367
19368 if (options.as) {
19369 name = options.as;
19370 }
19371
19372 var fullName = getFullName(this, name, options.resetNamespace);
19373 var engineInfo = {
19374 name: _name,
19375 instanceId: uuid++,
19376 mountPoint: fullName,
19377 fullName
19378 };
19379 var path = options.path;
19380
19381 if (typeof path !== 'string') {
19382 path = `/${name}`;
19383 }
19384
19385 var callback;
19386 var dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
19387
19388 if (engineRouteMap) {
19389 var shouldResetEngineInfo = false;
19390 var oldEngineInfo = this.options.engineInfo;
19391
19392 if (oldEngineInfo) {
19393 shouldResetEngineInfo = true;
19394 this.options.engineInfo = engineInfo;
19395 }
19396
19397 var optionsForChild = (0, _polyfills.assign)({
19398 engineInfo
19399 }, this.options);
19400 var childDSL = new DSLImpl(fullName, optionsForChild);
19401 createRoute(childDSL, 'loading');
19402 createRoute(childDSL, 'error', {
19403 path: dummyErrorRoute
19404 });
19405 engineRouteMap.class.call(childDSL);
19406 callback = childDSL.generate();
19407
19408 if (shouldResetEngineInfo) {
19409 this.options.engineInfo = oldEngineInfo;
19410 }
19411 }
19412
19413 var localFullName = 'application';
19414 var routeInfo = (0, _polyfills.assign)({
19415 localFullName
19416 }, engineInfo);
19417
19418 if (this.enableLoadingSubstates) {
19419 // These values are important to register the loading routes under their
19420 // proper names for the Router and within the Engine's registry.
19421 var substateName = `${name}_loading`;
19422 var _localFullName = `application_loading`;
19423
19424 var _routeInfo = (0, _polyfills.assign)({
19425 localFullName: _localFullName
19426 }, engineInfo);
19427
19428 createRoute(this, substateName, {
19429 resetNamespace: options.resetNamespace
19430 });
19431 this.options.addRouteForEngine(substateName, _routeInfo);
19432 substateName = `${name}_error`;
19433 _localFullName = `application_error`;
19434 _routeInfo = (0, _polyfills.assign)({
19435 localFullName: _localFullName
19436 }, engineInfo);
19437 createRoute(this, substateName, {
19438 resetNamespace: options.resetNamespace,
19439 path: dummyErrorRoute
19440 });
19441 this.options.addRouteForEngine(substateName, _routeInfo);
19442 }
19443
19444 this.options.addRouteForEngine(fullName, routeInfo);
19445 this.push(path, fullName, callback);
19446 }
19447
19448 }
19449
19450 _exports.default = DSLImpl;
19451
19452 function canNest(dsl) {
19453 return dsl.parent !== 'application';
19454 }
19455
19456 function getFullName(dsl, name, resetNamespace) {
19457 if (canNest(dsl) && resetNamespace !== true) {
19458 return `${dsl.parent}.${name}`;
19459 } else {
19460 return name;
19461 }
19462 }
19463
19464 function createRoute(dsl, name, options = {}, callback) {
19465 var fullName = getFullName(dsl, name, options.resetNamespace);
19466
19467 if (typeof options.path !== 'string') {
19468 options.path = `/${name}`;
19469 }
19470
19471 dsl.push(options.path, fullName, callback, options.serialize);
19472 }
19473});
19474define("@ember/-internals/routing/lib/system/engines", [], function () {
19475 "use strict";
19476});
19477define("@ember/-internals/routing/lib/system/generate_controller", ["exports", "@ember/-internals/metal", "@ember/debug"], function (_exports, _metal, _debug) {
19478 "use strict";
19479
19480 Object.defineProperty(_exports, "__esModule", {
19481 value: true
19482 });
19483 _exports.generateControllerFactory = generateControllerFactory;
19484 _exports.default = generateController;
19485
19486 /**
19487 @module ember
19488 */
19489
19490 /**
19491 Generates a controller factory
19492
19493 @for Ember
19494 @method generateControllerFactory
19495 @private
19496 */
19497 function generateControllerFactory(owner, controllerName) {
19498 var Factory = owner.factoryFor('controller:basic').class;
19499 Factory = Factory.extend({
19500 toString() {
19501 return `(generated ${controllerName} controller)`;
19502 }
19503
19504 });
19505 var fullName = `controller:${controllerName}`;
19506 owner.register(fullName, Factory);
19507 return owner.factoryFor(fullName);
19508 }
19509 /**
19510 Generates and instantiates a controller extending from `controller:basic`
19511 if present, or `Controller` if not.
19512
19513 @for Ember
19514 @method generateController
19515 @private
19516 @since 1.3.0
19517 */
19518
19519
19520 function generateController(owner, controllerName) {
19521 generateControllerFactory(owner, controllerName);
19522 var fullName = `controller:${controllerName}`;
19523 var instance = owner.lookup(fullName);
19524
19525 if (true
19526 /* DEBUG */
19527 ) {
19528 if ((0, _metal.get)(instance, 'namespace.LOG_ACTIVE_GENERATION')) {
19529 (0, _debug.info)(`generated -> ${fullName}`, {
19530 fullName
19531 });
19532 }
19533 }
19534
19535 return instance;
19536 }
19537});
19538define("@ember/-internals/routing/lib/system/query_params", ["exports"], function (_exports) {
19539 "use strict";
19540
19541 Object.defineProperty(_exports, "__esModule", {
19542 value: true
19543 });
19544 _exports.default = void 0;
19545
19546 class QueryParams {
19547 constructor(values = null) {
19548 this.isQueryParams = true;
19549 this.values = values;
19550 }
19551
19552 }
19553
19554 _exports.default = QueryParams;
19555});
19556define("@ember/-internals/routing/lib/system/route-info", [], function () {
19557 "use strict";
19558 /**
19559 A `RouteInfoWithAttributes` is an object that contains
19560 metadata, including the resolved value from the routes
19561 `model` hook. Like `RouteInfo`, a `RouteInfoWithAttributes`
19562 represents a specific route within a Transition.
19563 It is read-only and internally immutable. It is also not
19564 observable, because a Transition instance is never
19565 changed after creation.
19566
19567 @class RouteInfoWithAttributes
19568 @public
19569 */
19570
19571 /**
19572 The dot-separated, fully-qualified name of the
19573 route, like "people.index".
19574 @property {String} name
19575 @public
19576 */
19577
19578 /**
19579 The final segment of the fully-qualified name of
19580 the route, like "index"
19581 @property {String} localName
19582 @public
19583 */
19584
19585 /**
19586 The values of the route's parameters. These are the
19587 same params that are received as arguments to the
19588 route's model hook. Contains only the parameters
19589 valid for this route, if any (params for parent or
19590 child routes are not merged).
19591 @property {Object} params
19592 @public
19593 */
19594
19595 /**
19596 The ordered list of the names of the params
19597 required for this route. It will contain the same
19598 strings as `Object.keys(params)`, but here the order
19599 is significant. This allows users to correctly pass
19600 params into routes programmatically.
19601 @property {Array} paramNames
19602 @public
19603 */
19604
19605 /**
19606 The values of any queryParams on this route.
19607 @property {Object} queryParams
19608 @public
19609 */
19610
19611 /**
19612 This is the resolved return value from the
19613 route's model hook.
19614 @property {Object|Array|String} attributes
19615 @public
19616 */
19617
19618 /**
19619 Will contain the result `Route#buildRouteInfoMetadata`
19620 for the corresponding Route.
19621 @property {Any} metadata
19622 @public
19623 */
19624
19625 /**
19626 A reference to the parent route's RouteInfo.
19627 This can be used to traverse upward to the topmost
19628 `RouteInfo`.
19629 @property {RouteInfo|null} parent
19630 @public
19631 */
19632
19633 /**
19634 A reference to the child route's RouteInfo.
19635 This can be used to traverse downward to the
19636 leafmost `RouteInfo`.
19637 @property {RouteInfo|null} child
19638 @public
19639 */
19640
19641 /**
19642 Allows you to traverse through the linked list
19643 of `RouteInfo`s from the topmost to leafmost.
19644 Returns the first `RouteInfo` in the linked list
19645 for which the callback returns true.
19646
19647 This method is similar to the `find()` method
19648 defined in ECMAScript 2015.
19649
19650 The callback method you provide should have the
19651 following signature (all parameters are optional):
19652
19653 ```javascript
19654 function(item, index, array);
19655 ```
19656
19657 - `item` is the current item in the iteration.
19658 - `index` is the current index in the iteration.
19659 - `array` is the array itself.
19660
19661 It should return the `true` to include the item in
19662 the results, `false` otherwise.
19663
19664 Note that in addition to a callback, you can also
19665 pass an optional target object that will be set as
19666 `this` on the context.
19667
19668 @method find
19669 @param {Function} callback the callback to execute
19670 @param {Object} [target*] optional target to use
19671 @returns {Object} Found item or undefined
19672 @public
19673 */
19674
19675 /**
19676 A RouteInfo is an object that contains metadata
19677 about a specific route within a Transition. It is
19678 read-only and internally immutable. It is also not
19679 observable, because a Transition instance is never
19680 changed after creation.
19681
19682 @class RouteInfo
19683 @public
19684 */
19685
19686 /**
19687 The dot-separated, fully-qualified name of the
19688 route, like "people.index".
19689 @property {String} name
19690 @public
19691 */
19692
19693 /**
19694 The final segment of the fully-qualified name of
19695 the route, like "index"
19696 @property {String} localName
19697 @public
19698 */
19699
19700 /**
19701 The values of the route's parameters. These are the
19702 same params that are received as arguments to the
19703 route's `model` hook. Contains only the parameters
19704 valid for this route, if any (params for parent or
19705 child routes are not merged).
19706 @property {Object} params
19707 @public
19708 */
19709
19710 /**
19711 The ordered list of the names of the params
19712 required for this route. It will contain the same
19713 strings as Object.keys(params), but here the order
19714 is significant. This allows users to correctly pass
19715 params into routes programmatically.
19716 @property {Array} paramNames
19717 @public
19718 */
19719
19720 /**
19721 The values of any queryParams on this route.
19722 @property {Object} queryParams
19723 @public
19724 */
19725
19726 /**
19727 A reference to the parent route's `RouteInfo`.
19728 This can be used to traverse upward to the topmost
19729 `RouteInfo`.
19730 @property {RouteInfo|null} parent
19731 @public
19732 */
19733
19734 /**
19735 A reference to the child route's `RouteInfo`.
19736 This can be used to traverse downward to the
19737 leafmost `RouteInfo`.
19738 @property {RouteInfo|null} child
19739 @public
19740 */
19741
19742 /**
19743 Allows you to traverse through the linked list
19744 of `RouteInfo`s from the topmost to leafmost.
19745 Returns the first `RouteInfo` in the linked list
19746 for which the callback returns true.
19747
19748 This method is similar to the `find()` method
19749 defined in ECMAScript 2015.
19750
19751 The callback method you provide should have the
19752 following signature (all parameters are optional):
19753
19754 ```javascript
19755 function(item, index, array);
19756 ```
19757
19758 - `item` is the current item in the iteration.
19759 - `index` is the current index in the iteration.
19760 - `array` is the array itself.
19761
19762 It should return the `true` to include the item in
19763 the results, `false` otherwise.
19764
19765 Note that in addition to a callback, you can also
19766 pass an optional target object that will be set as
19767 `this` on the context.
19768
19769 @method find
19770 @param {Function} callback the callback to execute
19771 @param {Object} [target*] optional target to use
19772 @returns {Object} Found item or undefined
19773 @public
19774 */
19775});
19776define("@ember/-internals/routing/lib/system/route", ["exports", "@ember/polyfills", "@ember/-internals/metal", "@ember/-internals/owner", "@ember/-internals/runtime", "@ember/-internals/utils", "@ember/debug", "@ember/deprecated-features", "@ember/object/compat", "@ember/runloop", "@ember/string", "router_js", "@ember/-internals/routing/lib/utils", "@ember/-internals/routing/lib/system/generate_controller"], function (_exports, _polyfills, _metal, _owner, _runtime, _utils, _debug, _deprecatedFeatures, _compat, _runloop, _string, _router_js, _utils2, _generate_controller) {
19777 "use strict";
19778
19779 Object.defineProperty(_exports, "__esModule", {
19780 value: true
19781 });
19782 _exports.defaultSerialize = defaultSerialize;
19783 _exports.hasDefaultSerialize = hasDefaultSerialize;
19784 _exports.default = _exports.ROUTER_EVENT_DEPRECATIONS = _exports.ROUTE_CONNECTIONS = void 0;
19785 var ROUTE_CONNECTIONS = new WeakMap();
19786 _exports.ROUTE_CONNECTIONS = ROUTE_CONNECTIONS;
19787
19788 function defaultSerialize(model, params) {
19789 if (params.length < 1 || !model) {
19790 return;
19791 }
19792
19793 var object = {};
19794
19795 if (params.length === 1) {
19796 var [name] = params;
19797
19798 if (name in model) {
19799 object[name] = (0, _metal.get)(model, name);
19800 } else if (/_id$/.test(name)) {
19801 object[name] = (0, _metal.get)(model, 'id');
19802 }
19803 } else {
19804 object = (0, _metal.getProperties)(model, params);
19805 }
19806
19807 return object;
19808 }
19809
19810 function hasDefaultSerialize(route) {
19811 return route.serialize === defaultSerialize;
19812 }
19813 /**
19814 @module @ember/routing
19815 */
19816
19817 /**
19818 The `Route` class is used to define individual routes. Refer to
19819 the [routing guide](https://guides.emberjs.com/release/routing/) for documentation.
19820
19821 @class Route
19822 @extends EmberObject
19823 @uses ActionHandler
19824 @uses Evented
19825 @since 1.0.0
19826 @public
19827 */
19828
19829
19830 class Route extends _runtime.Object {
19831 constructor() {
19832 super(...arguments);
19833 this.context = {};
19834 }
19835 /**
19836 The name of the route, dot-delimited.
19837 For example, a route found at `app/routes/posts/post.js` will have
19838 a `routeName` of `posts.post`.
19839 @property routeName
19840 @for Route
19841 @type String
19842 @since 1.0.0
19843 @public
19844 */
19845
19846 /**
19847 The name of the route, dot-delimited, including the engine prefix
19848 if applicable.
19849 For example, a route found at `addon/routes/posts/post.js` within an
19850 engine named `admin` will have a `fullRouteName` of `admin.posts.post`.
19851 @property fullRouteName
19852 @for Route
19853 @type String
19854 @since 2.10.0
19855 @public
19856 */
19857
19858 /**
19859 Sets the name for this route, including a fully resolved name for routes
19860 inside engines.
19861 @private
19862 @method _setRouteName
19863 @param {String} name
19864 */
19865
19866
19867 _setRouteName(name) {
19868 this.routeName = name;
19869 this.fullRouteName = getEngineRouteName((0, _owner.getOwner)(this), name);
19870 }
19871 /**
19872 @private
19873 @method _stashNames
19874 */
19875
19876
19877 _stashNames(routeInfo, dynamicParent) {
19878 if (this._names) {
19879 return;
19880 }
19881
19882 var names = this._names = routeInfo['_names'];
19883
19884 if (!names.length) {
19885 routeInfo = dynamicParent;
19886 names = routeInfo && routeInfo['_names'] || [];
19887 }
19888
19889 var qps = (0, _metal.get)(this, '_qp.qps');
19890 var namePaths = new Array(names.length);
19891
19892 for (var a = 0; a < names.length; ++a) {
19893 namePaths[a] = `${routeInfo.name}.${names[a]}`;
19894 }
19895
19896 for (var i = 0; i < qps.length; ++i) {
19897 var qp = qps[i];
19898
19899 if (qp.scope === 'model') {
19900 qp.parts = namePaths;
19901 }
19902 }
19903 }
19904 /**
19905 @private
19906 @property _activeQPChanged
19907 */
19908
19909
19910 _activeQPChanged(qp, value) {
19911 this._router._activeQPChanged(qp.scopedPropertyName, value);
19912 }
19913 /**
19914 @private
19915 @method _updatingQPChanged
19916 */
19917
19918
19919 _updatingQPChanged(qp) {
19920 this._router._updatingQPChanged(qp.urlKey);
19921 }
19922 /**
19923 Returns a hash containing the parameters of an ancestor route.
19924 You may notice that `this.paramsFor` sometimes works when referring to a
19925 child route, but this behavior should not be relied upon as only ancestor
19926 routes are certain to be loaded in time.
19927 Example
19928 ```app/router.js
19929 // ...
19930 Router.map(function() {
19931 this.route('member', { path: ':name' }, function() {
19932 this.route('interest', { path: ':interest' });
19933 });
19934 });
19935 ```
19936 ```app/routes/member.js
19937 import Route from '@ember/routing/route';
19938 export default class MemberRoute extends Route {
19939 queryParams = {
19940 memberQp: { refreshModel: true }
19941 }
19942 }
19943 ```
19944 ```app/routes/member/interest.js
19945 import Route from '@ember/routing/route';
19946 export default class MemberInterestRoute Route {
19947 queryParams = {
19948 interestQp: { refreshModel: true }
19949 }
19950 model() {
19951 return this.paramsFor('member');
19952 }
19953 }
19954 ```
19955 If we visit `/turing/maths?memberQp=member&interestQp=interest` the model for
19956 the `member.interest` route is a hash with:
19957 * `name`: `turing`
19958 * `memberQp`: `member`
19959 @method paramsFor
19960 @param {String} name
19961 @return {Object} hash containing the parameters of the route `name`
19962 @since 1.4.0
19963 @public
19964 */
19965
19966
19967 paramsFor(name) {
19968 var route = (0, _owner.getOwner)(this).lookup(`route:${name}`);
19969
19970 if (route === undefined) {
19971 return {};
19972 }
19973
19974 var transition = this._router._routerMicrolib.activeTransition;
19975 var state = transition ? transition[_router_js.STATE_SYMBOL] : this._router._routerMicrolib.state;
19976 var fullName = route.fullRouteName;
19977 var params = (0, _polyfills.assign)({}, state.params[fullName]);
19978 var queryParams = getQueryParamsFor(route, state);
19979 return Object.keys(queryParams).reduce((params, key) => {
19980 (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]));
19981 params[key] = queryParams[key];
19982 return params;
19983 }, params);
19984 }
19985 /**
19986 Serializes the query parameter key
19987 @method serializeQueryParamKey
19988 @param {String} controllerPropertyName
19989 @private
19990 */
19991
19992
19993 serializeQueryParamKey(controllerPropertyName) {
19994 return controllerPropertyName;
19995 }
19996 /**
19997 Serializes value of the query parameter based on defaultValueType
19998 @method serializeQueryParam
19999 @param {Object} value
20000 @param {String} urlKey
20001 @param {String} defaultValueType
20002 @private
20003 */
20004
20005
20006 serializeQueryParam(value, _urlKey, defaultValueType) {
20007 // urlKey isn't used here, but anyone overriding
20008 // can use it to provide serialization specific
20009 // to a certain query param.
20010 return this._router._serializeQueryParam(value, defaultValueType);
20011 }
20012 /**
20013 Deserializes value of the query parameter based on defaultValueType
20014 @method deserializeQueryParam
20015 @param {Object} value
20016 @param {String} urlKey
20017 @param {String} defaultValueType
20018 @private
20019 */
20020
20021
20022 deserializeQueryParam(value, _urlKey, defaultValueType) {
20023 // urlKey isn't used here, but anyone overriding
20024 // can use it to provide deserialization specific
20025 // to a certain query param.
20026 return this._router._deserializeQueryParam(value, defaultValueType);
20027 }
20028 /**
20029 @private
20030 @property _optionsForQueryParam
20031 */
20032
20033
20034 _optionsForQueryParam(qp) {
20035 return (0, _metal.get)(this, `queryParams.${qp.urlKey}`) || (0, _metal.get)(this, `queryParams.${qp.prop}`) || {};
20036 }
20037 /**
20038 A hook you can use to reset controller values either when the model
20039 changes or the route is exiting.
20040 ```app/routes/articles.js
20041 import Route from '@ember/routing/route';
20042 export default class ArticlesRoute extends Route {
20043 resetController(controller, isExiting, transition) {
20044 if (isExiting && transition.targetName !== 'error') {
20045 controller.set('page', 1);
20046 }
20047 }
20048 }
20049 ```
20050 @method resetController
20051 @param {Controller} controller instance
20052 @param {Boolean} isExiting
20053 @param {Object} transition
20054 @since 1.7.0
20055 @public
20056 */
20057
20058
20059 resetController(_controller, _isExiting, _transition) {
20060 return this;
20061 }
20062 /**
20063 @private
20064 @method exit
20065 */
20066
20067
20068 exit() {
20069 this.deactivate();
20070 this.trigger('deactivate');
20071 this.teardownViews();
20072 }
20073 /**
20074 @private
20075 @method _internalReset
20076 @since 3.6.0
20077 */
20078
20079
20080 _internalReset(isExiting, transition) {
20081 var controller = this.controller;
20082 controller['_qpDelegate'] = (0, _metal.get)(this, '_qp.states.inactive');
20083 this.resetController(controller, isExiting, transition);
20084 }
20085 /**
20086 @private
20087 @method enter
20088 */
20089
20090
20091 enter() {
20092 ROUTE_CONNECTIONS.set(this, []);
20093 this.activate();
20094 this.trigger('activate');
20095 }
20096 /**
20097 The `willTransition` action is fired at the beginning of any
20098 attempted transition with a `Transition` object as the sole
20099 argument. This action can be used for aborting, redirecting,
20100 or decorating the transition from the currently active routes.
20101 A good example is preventing navigation when a form is
20102 half-filled out:
20103 ```app/routes/contact-form.js
20104 import Route from '@ember/routing/route';
20105 import { action } from '@ember/object';
20106 export default class ContactFormRoute extends Route {
20107 @action
20108 willTransition(transition) {
20109 if (this.controller.get('userHasEnteredData')) {
20110 this.controller.displayNavigationConfirm();
20111 transition.abort();
20112 }
20113 }
20114 }
20115 ```
20116 You can also redirect elsewhere by calling
20117 `this.transitionTo('elsewhere')` from within `willTransition`.
20118 Note that `willTransition` will not be fired for the
20119 redirecting `transitionTo`, since `willTransition` doesn't
20120 fire when there is already a transition underway. If you want
20121 subsequent `willTransition` actions to fire for the redirecting
20122 transition, you must first explicitly call
20123 `transition.abort()`.
20124 To allow the `willTransition` event to continue bubbling to the parent
20125 route, use `return true;`. When the `willTransition` method has a
20126 return value of `true` then the parent route's `willTransition` method
20127 will be fired, enabling "bubbling" behavior for the event.
20128 @event willTransition
20129 @param {Transition} transition
20130 @since 1.0.0
20131 @public
20132 */
20133
20134 /**
20135 The `didTransition` action is fired after a transition has
20136 successfully been completed. This occurs after the normal model
20137 hooks (`beforeModel`, `model`, `afterModel`, `setupController`)
20138 have resolved. The `didTransition` action has no arguments,
20139 however, it can be useful for tracking page views or resetting
20140 state on the controller.
20141 ```app/routes/login.js
20142 import Route from '@ember/routing/route';
20143 import { action } from '@ember/object';
20144 export default class LoginRoute extends Route {
20145 @action
20146 didTransition() {
20147 this.controller.get('errors.base').clear();
20148 return true; // Bubble the didTransition event
20149 }
20150 }
20151 ```
20152 @event didTransition
20153 @since 1.2.0
20154 @public
20155 */
20156
20157 /**
20158 The `loading` action is fired on the route when a route's `model`
20159 hook returns a promise that is not already resolved. The current
20160 `Transition` object is the first parameter and the route that
20161 triggered the loading event is the second parameter.
20162 ```app/routes/application.js
20163 import Route from '@ember/routing/route';
20164 import { action } from '@ember/object';
20165 export default class ApplicationRoute extends Route {
20166 @action
20167 loading(transition, route) {
20168 let controller = this.controllerFor('foo');
20169 controller.set('currentlyLoading', true);
20170 transition.finally(function() {
20171 controller.set('currentlyLoading', false);
20172 });
20173 }
20174 }
20175 ```
20176 @event loading
20177 @param {Transition} transition
20178 @param {Route} route The route that triggered the loading event
20179 @since 1.2.0
20180 @public
20181 */
20182
20183 /**
20184 When attempting to transition into a route, any of the hooks
20185 may return a promise that rejects, at which point an `error`
20186 action will be fired on the partially-entered routes, allowing
20187 for per-route error handling logic, or shared error handling
20188 logic defined on a parent route.
20189 Here is an example of an error handler that will be invoked
20190 for rejected promises from the various hooks on the route,
20191 as well as any unhandled errors from child routes:
20192 ```app/routes/admin.js
20193 import { reject } from 'rsvp';
20194 import Route from '@ember/routing/route';
20195 import { action } from '@ember/object';
20196 export default class AdminRoute extends Route {
20197 beforeModel() {
20198 return reject('bad things!');
20199 }
20200 @action
20201 error(error, transition) {
20202 // Assuming we got here due to the error in `beforeModel`,
20203 // we can expect that error === "bad things!",
20204 // but a promise model rejecting would also
20205 // call this hook, as would any errors encountered
20206 // in `afterModel`.
20207 // The `error` hook is also provided the failed
20208 // `transition`, which can be stored and later
20209 // `.retry()`d if desired.
20210 this.transitionTo('login');
20211 }
20212 }
20213 ```
20214 `error` actions that bubble up all the way to `ApplicationRoute`
20215 will fire a default error handler that logs the error. You can
20216 specify your own global default error handler by overriding the
20217 `error` handler on `ApplicationRoute`:
20218 ```app/routes/application.js
20219 import Route from '@ember/routing/route';
20220 import { action } from '@ember/object';
20221 export default class ApplicationRoute extends Route {
20222 @action
20223 error(error, transition) {
20224 this.controllerFor('banner').displayError(error.message);
20225 }
20226 }
20227 ```
20228 @event error
20229 @param {Error} error
20230 @param {Transition} transition
20231 @since 1.0.0
20232 @public
20233 */
20234
20235 /**
20236 This event is triggered when the router enters the route. It is
20237 not executed when the model for the route changes.
20238 ```app/routes/application.js
20239 import { on } from '@ember/object/evented';
20240 import Route from '@ember/routing/route';
20241 export default Route.extend({
20242 collectAnalytics: on('activate', function(){
20243 collectAnalytics();
20244 })
20245 });
20246 ```
20247 @event activate
20248 @since 1.9.0
20249 @public
20250 */
20251
20252 /**
20253 This event is triggered when the router completely exits this
20254 route. It is not executed when the model for the route changes.
20255 ```app/routes/index.js
20256 import { on } from '@ember/object/evented';
20257 import Route from '@ember/routing/route';
20258 export default Route.extend({
20259 trackPageLeaveAnalytics: on('deactivate', function(){
20260 trackPageLeaveAnalytics();
20261 })
20262 });
20263 ```
20264 @event deactivate
20265 @since 1.9.0
20266 @public
20267 */
20268
20269 /**
20270 This hook is executed when the router completely exits this route. It is
20271 not executed when the model for the route changes.
20272 @method deactivate
20273 @since 1.0.0
20274 @public
20275 */
20276
20277
20278 deactivate() {}
20279 /**
20280 This hook is executed when the router enters the route. It is not executed
20281 when the model for the route changes.
20282 @method activate
20283 @since 1.0.0
20284 @public
20285 */
20286
20287
20288 activate() {}
20289 /**
20290 Transition the application into another route. The route may
20291 be either a single route or route path:
20292 ```javascript
20293 this.transitionTo('blogPosts');
20294 this.transitionTo('blogPosts.recentEntries');
20295 ```
20296 Optionally supply a model for the route in question. The model
20297 will be serialized into the URL using the `serialize` hook of
20298 the route:
20299 ```javascript
20300 this.transitionTo('blogPost', aPost);
20301 ```
20302 If a literal is passed (such as a number or a string), it will
20303 be treated as an identifier instead. In this case, the `model`
20304 hook of the route will be triggered:
20305 ```javascript
20306 this.transitionTo('blogPost', 1);
20307 ```
20308 Multiple models will be applied last to first recursively up the
20309 route tree.
20310 ```app/routes.js
20311 // ...
20312 Router.map(function() {
20313 this.route('blogPost', { path:':blogPostId' }, function() {
20314 this.route('blogComment', { path: ':blogCommentId' });
20315 });
20316 });
20317 export default Router;
20318 ```
20319 ```javascript
20320 this.transitionTo('blogComment', aPost, aComment);
20321 this.transitionTo('blogComment', 1, 13);
20322 ```
20323 It is also possible to pass a URL (a string that starts with a
20324 `/`).
20325 ```javascript
20326 this.transitionTo('/');
20327 this.transitionTo('/blog/post/1/comment/13');
20328 this.transitionTo('/blog/posts?sort=title');
20329 ```
20330 An options hash with a `queryParams` property may be provided as
20331 the final argument to add query parameters to the destination URL.
20332 ```javascript
20333 this.transitionTo('blogPost', 1, {
20334 queryParams: { showComments: 'true' }
20335 });
20336 // if you just want to transition the query parameters without changing the route
20337 this.transitionTo({ queryParams: { sort: 'date' } });
20338 ```
20339 See also [replaceWith](#method_replaceWith).
20340 Simple Transition Example
20341 ```app/routes.js
20342 // ...
20343 Router.map(function() {
20344 this.route('index');
20345 this.route('secret');
20346 this.route('fourOhFour', { path: '*:' });
20347 });
20348 export default Router;
20349 ```
20350 ```app/routes/index.js
20351 import Route from '@ember/routing/route';
20352 import { action } from '@ember/object';
20353 export default class IndexRoute extends Route {
20354 @action
20355 moveToSecret(context) {
20356 if (authorized()) {
20357 this.transitionTo('secret', context);
20358 } else {
20359 this.transitionTo('fourOhFour');
20360 }
20361 }
20362 }
20363 ```
20364 Transition to a nested route
20365 ```app/router.js
20366 // ...
20367 Router.map(function() {
20368 this.route('articles', { path: '/articles' }, function() {
20369 this.route('new');
20370 });
20371 });
20372 export default Router;
20373 ```
20374 ```app/routes/index.js
20375 import Route from '@ember/routing/route';
20376 import { action } from '@ember/object';
20377 export default class IndexRoute extends Route {
20378 @action
20379 transitionToNewArticle() {
20380 this.transitionTo('articles.new');
20381 }
20382 }
20383 ```
20384 Multiple Models Example
20385 ```app/router.js
20386 // ...
20387 Router.map(function() {
20388 this.route('index');
20389 this.route('breakfast', { path: ':breakfastId' }, function() {
20390 this.route('cereal', { path: ':cerealId' });
20391 });
20392 });
20393 export default Router;
20394 ```
20395 ```app/routes/index.js
20396 import Route from '@ember/routing/route';
20397 import { action } from '@ember/object';
20398 export default class IndexRoute extends Route {
20399 @action
20400 moveToChocolateCereal() {
20401 let cereal = { cerealId: 'ChocolateYumminess' };
20402 let breakfast = { breakfastId: 'CerealAndMilk' };
20403 this.transitionTo('breakfast.cereal', breakfast, cereal);
20404 }
20405 }
20406 ```
20407 Nested Route with Query String Example
20408 ```app/routes.js
20409 // ...
20410 Router.map(function() {
20411 this.route('fruits', function() {
20412 this.route('apples');
20413 });
20414 });
20415 export default Router;
20416 ```
20417 ```app/routes/index.js
20418 import Route from '@ember/routing/route';
20419 export default class IndexRoute extends Route {
20420 @action
20421 transitionToApples() {
20422 this.transitionTo('fruits.apples', { queryParams: { color: 'red' } });
20423 }
20424 }
20425 ```
20426 @method transitionTo
20427 @param {String} [name] the name of the route or a URL.
20428 @param {...Object} [models] the model(s) or identifier(s) to be used while
20429 transitioning to the route.
20430 @param {Object} [options] optional hash with a queryParams property
20431 containing a mapping of query parameters. May be supplied as the only
20432 parameter to trigger a query-parameter-only transition.
20433 @return {Transition} the transition object associated with this
20434 attempted transition
20435 @since 1.0.0
20436 @public
20437 */
20438
20439
20440 transitionTo(...args) {
20441 // eslint-disable-line no-unused-vars
20442 return this._router.transitionTo(...(0, _utils2.prefixRouteNameArg)(this, args));
20443 }
20444 /**
20445 Perform a synchronous transition into another route without attempting
20446 to resolve promises, update the URL, or abort any currently active
20447 asynchronous transitions (i.e. regular transitions caused by
20448 `transitionTo` or URL changes).
20449 This method is handy for performing intermediate transitions on the
20450 way to a final destination route, and is called internally by the
20451 default implementations of the `error` and `loading` handlers.
20452 @method intermediateTransitionTo
20453 @param {String} name the name of the route
20454 @param {...Object} models the model(s) to be used while transitioning
20455 to the route.
20456 @since 1.2.0
20457 @public
20458 */
20459
20460
20461 intermediateTransitionTo(...args) {
20462 var [name, ...preparedArgs] = (0, _utils2.prefixRouteNameArg)(this, args);
20463
20464 this._router.intermediateTransitionTo(name, ...preparedArgs);
20465 }
20466 /**
20467 Refresh the model on this route and any child routes, firing the
20468 `beforeModel`, `model`, and `afterModel` hooks in a similar fashion
20469 to how routes are entered when transitioning in from other route.
20470 The current route params (e.g. `article_id`) will be passed in
20471 to the respective model hooks, and if a different model is returned,
20472 `setupController` and associated route hooks will re-fire as well.
20473 An example usage of this method is re-querying the server for the
20474 latest information using the same parameters as when the route
20475 was first entered.
20476 Note that this will cause `model` hooks to fire even on routes
20477 that were provided a model object when the route was initially
20478 entered.
20479 @method refresh
20480 @return {Transition} the transition object associated with this
20481 attempted transition
20482 @since 1.4.0
20483 @public
20484 */
20485
20486
20487 refresh() {
20488 return this._router._routerMicrolib.refresh(this);
20489 }
20490 /**
20491 Transition into another route while replacing the current URL, if possible.
20492 This will replace the current history entry instead of adding a new one.
20493 Beside that, it is identical to `transitionTo` in all other respects. See
20494 'transitionTo' for additional information regarding multiple models.
20495 Example
20496 ```app/router.js
20497 // ...
20498 Router.map(function() {
20499 this.route('index');
20500 this.route('secret');
20501 });
20502 export default Router;
20503 ```
20504 ```app/routes/secret.js
20505 import Route from '@ember/routing/route';
20506 export default class SecretRoute Route {
20507 afterModel() {
20508 if (!authorized()){
20509 this.replaceWith('index');
20510 }
20511 }
20512 }
20513 ```
20514 @method replaceWith
20515 @param {String} name the name of the route or a URL
20516 @param {...Object} models the model(s) or identifier(s) to be used while
20517 transitioning to the route.
20518 @param {Object} [options] optional hash with a queryParams property
20519 containing a mapping of query parameters
20520 @return {Transition} the transition object associated with this
20521 attempted transition
20522 @since 1.0.0
20523 @public
20524 */
20525
20526
20527 replaceWith(...args) {
20528 return this._router.replaceWith(...(0, _utils2.prefixRouteNameArg)(this, args));
20529 }
20530 /**
20531 This hook is the entry point for router.js
20532 @private
20533 @method setup
20534 */
20535
20536
20537 setup(context, transition) {
20538 var controllerName = this.controllerName || this.routeName;
20539 var definedController = this.controllerFor(controllerName, true);
20540 var controller;
20541
20542 if (definedController) {
20543 controller = definedController;
20544 } else {
20545 controller = this.generateController(controllerName);
20546 } // Assign the route's controller so that it can more easily be
20547 // referenced in action handlers. Side effects. Side effects everywhere.
20548
20549
20550 if (!this.controller) {
20551 var qp = (0, _metal.get)(this, '_qp');
20552 var propNames = qp !== undefined ? (0, _metal.get)(qp, 'propertyNames') : [];
20553 addQueryParamsObservers(controller, propNames);
20554 this.controller = controller;
20555 }
20556
20557 var queryParams = (0, _metal.get)(this, '_qp');
20558 var states = queryParams.states;
20559 controller._qpDelegate = states.allowOverrides;
20560
20561 if (transition) {
20562 // Update the model dep values used to calculate cache keys.
20563 (0, _utils2.stashParamNames)(this._router, transition[_router_js.STATE_SYMBOL].routeInfos);
20564 var cache = this._bucketCache;
20565 var params = transition[_router_js.PARAMS_SYMBOL];
20566 var allParams = queryParams.propertyNames;
20567 allParams.forEach(prop => {
20568 var aQp = queryParams.map[prop];
20569 aQp.values = params;
20570 var cacheKey = (0, _utils2.calculateCacheKey)(aQp.route.fullRouteName, aQp.parts, aQp.values);
20571 var value = cache.lookup(cacheKey, prop, aQp.undecoratedDefaultValue);
20572 (0, _metal.set)(controller, prop, value);
20573 });
20574 var qpValues = getQueryParamsFor(this, transition[_router_js.STATE_SYMBOL]);
20575 (0, _metal.setProperties)(controller, qpValues);
20576 }
20577
20578 this.setupController(controller, context, transition);
20579
20580 if (this._environment.options.shouldRender) {
20581 this.renderTemplate(controller, context);
20582 } // Setup can cause changes to QPs which need to be propogated immediately in
20583 // some situations. Eventually, we should work on making these async somehow.
20584
20585
20586 (0, _metal.flushAsyncObservers)(false);
20587 }
20588 /*
20589 Called when a query parameter for this route changes, regardless of whether the route
20590 is currently part of the active route hierarchy. This will update the query parameter's
20591 value in the cache so if this route becomes active, the cache value has been updated.
20592 */
20593
20594
20595 _qpChanged(prop, value, qp) {
20596 if (!qp) {
20597 return;
20598 } // Update model-dep cache
20599
20600
20601 var cache = this._bucketCache;
20602 var cacheKey = (0, _utils2.calculateCacheKey)(qp.route.fullRouteName, qp.parts, qp.values);
20603 cache.stash(cacheKey, prop, value);
20604 }
20605 /**
20606 This hook is the first of the route entry validation hooks
20607 called when an attempt is made to transition into a route
20608 or one of its children. It is called before `model` and
20609 `afterModel`, and is appropriate for cases when:
20610 1) A decision can be made to redirect elsewhere without
20611 needing to resolve the model first.
20612 2) Any async operations need to occur first before the
20613 model is attempted to be resolved.
20614 This hook is provided the current `transition` attempt
20615 as a parameter, which can be used to `.abort()` the transition,
20616 save it for a later `.retry()`, or retrieve values set
20617 on it from a previous hook. You can also just call
20618 `this.transitionTo` to another route to implicitly
20619 abort the `transition`.
20620 You can return a promise from this hook to pause the
20621 transition until the promise resolves (or rejects). This could
20622 be useful, for instance, for retrieving async code from
20623 the server that is required to enter a route.
20624 @method beforeModel
20625 @param {Transition} transition
20626 @return {any | Promise<any>} if the value returned from this hook is
20627 a promise, the transition will pause until the transition
20628 resolves. Otherwise, non-promise return values are not
20629 utilized in any way.
20630 @since 1.0.0
20631 @public
20632 */
20633
20634
20635 beforeModel() {}
20636 /**
20637 This hook is called after this route's model has resolved.
20638 It follows identical async/promise semantics to `beforeModel`
20639 but is provided the route's resolved model in addition to
20640 the `transition`, and is therefore suited to performing
20641 logic that can only take place after the model has already
20642 resolved.
20643 ```app/routes/posts.js
20644 import Route from '@ember/routing/route';
20645 export default class PostsRoute extends Route {
20646 afterModel(posts, transition) {
20647 if (posts.get('length') === 1) {
20648 this.transitionTo('post.show', posts.get('firstObject'));
20649 }
20650 }
20651 }
20652 ```
20653 Refer to documentation for `beforeModel` for a description
20654 of transition-pausing semantics when a promise is returned
20655 from this hook.
20656 @method afterModel
20657 @param {Object} resolvedModel the value returned from `model`,
20658 or its resolved value if it was a promise
20659 @param {Transition} transition
20660 @return {any | Promise<any>} if the value returned from this hook is
20661 a promise, the transition will pause until the transition
20662 resolves. Otherwise, non-promise return values are not
20663 utilized in any way.
20664 @since 1.0.0
20665 @public
20666 */
20667
20668
20669 afterModel() {}
20670 /**
20671 A hook you can implement to optionally redirect to another route.
20672 Calling `this.transitionTo` from inside of the `redirect` hook will
20673 abort the current transition (into the route that has implemented `redirect`).
20674 `redirect` and `afterModel` behave very similarly and are
20675 called almost at the same time, but they have an important
20676 distinction when calling `this.transitionTo` to a child route
20677 of the current route. From `afterModel`, this new transition
20678 invalidates the current transition, causing `beforeModel`,
20679 `model`, and `afterModel` hooks to be called again. But the
20680 same transition started from `redirect` does _not_ invalidate
20681 the current transition. In other words, by the time the `redirect`
20682 hook has been called, both the resolved model and the attempted
20683 entry into this route are considered fully validated.
20684 @method redirect
20685 @param {Object} model the model for this route
20686 @param {Transition} transition the transition object associated with the current transition
20687 @since 1.0.0
20688 @public
20689 */
20690
20691
20692 redirect() {}
20693 /**
20694 Called when the context is changed by router.js.
20695 @private
20696 @method contextDidChange
20697 */
20698
20699
20700 contextDidChange() {
20701 this.currentModel = this.context;
20702 }
20703 /**
20704 A hook you can implement to convert the URL into the model for
20705 this route.
20706 ```app/router.js
20707 // ...
20708 Router.map(function() {
20709 this.route('post', { path: '/posts/:post_id' });
20710 });
20711 export default Router;
20712 ```
20713 The model for the `post` route is `store.findRecord('post', params.post_id)`.
20714 By default, if your route has a dynamic segment ending in `_id`:
20715 * The model class is determined from the segment (`post_id`'s
20716 class is `App.Post`)
20717 * The find method is called on the model class with the value of
20718 the dynamic segment.
20719 Note that for routes with dynamic segments, this hook is not always
20720 executed. If the route is entered through a transition (e.g. when
20721 using the `link-to` Handlebars helper or the `transitionTo` method
20722 of routes), and a model context is already provided this hook
20723 is not called.
20724 A model context does not include a primitive string or number,
20725 which does cause the model hook to be called.
20726 Routes without dynamic segments will always execute the model hook.
20727 ```javascript
20728 // no dynamic segment, model hook always called
20729 this.transitionTo('posts');
20730 // model passed in, so model hook not called
20731 thePost = store.findRecord('post', 1);
20732 this.transitionTo('post', thePost);
20733 // integer passed in, model hook is called
20734 this.transitionTo('post', 1);
20735 // model id passed in, model hook is called
20736 // useful for forcing the hook to execute
20737 thePost = store.findRecord('post', 1);
20738 this.transitionTo('post', thePost.id);
20739 ```
20740 This hook follows the asynchronous/promise semantics
20741 described in the documentation for `beforeModel`. In particular,
20742 if a promise returned from `model` fails, the error will be
20743 handled by the `error` hook on `Route`.
20744 Example
20745 ```app/routes/post.js
20746 import Route from '@ember/routing/route';
20747 export default class PostRoute extends Route {
20748 model(params) {
20749 return this.store.findRecord('post', params.post_id);
20750 }
20751 }
20752 ```
20753 @method model
20754 @param {Object} params the parameters extracted from the URL
20755 @param {Transition} transition
20756 @return {any | Promise<any>} the model for this route. If
20757 a promise is returned, the transition will pause until
20758 the promise resolves, and the resolved value of the promise
20759 will be used as the model for this route.
20760 @since 1.0.0
20761 @public
20762 */
20763
20764
20765 model(params, transition) {
20766 var name, sawParams, value;
20767 var queryParams = (0, _metal.get)(this, '_qp.map');
20768
20769 for (var prop in params) {
20770 if (prop === 'queryParams' || queryParams && prop in queryParams) {
20771 continue;
20772 }
20773
20774 var match = prop.match(/^(.*)_id$/);
20775
20776 if (match !== null) {
20777 name = match[1];
20778 value = params[prop];
20779 }
20780
20781 sawParams = true;
20782 }
20783
20784 if (!name) {
20785 if (sawParams) {
20786 return (0, _polyfills.assign)({}, params);
20787 } else {
20788 if (transition.resolveIndex < 1) {
20789 return;
20790 }
20791
20792 return transition[_router_js.STATE_SYMBOL].routeInfos[transition.resolveIndex - 1].context;
20793 }
20794 }
20795
20796 return this.findModel(name, value);
20797 }
20798 /**
20799 @private
20800 @method deserialize
20801 @param {Object} params the parameters extracted from the URL
20802 @param {Transition} transition
20803 @return {any | Promise<any>} the model for this route.
20804 Router.js hook.
20805 */
20806
20807
20808 deserialize(_params, transition) {
20809 return this.model(this._paramsFor(this.routeName, _params), transition);
20810 }
20811 /**
20812 @method findModel
20813 @param {String} type the model type
20814 @param {Object} value the value passed to find
20815 @private
20816 */
20817
20818
20819 findModel(...args) {
20820 return (0, _metal.get)(this, 'store').find(...args);
20821 }
20822 /**
20823 A hook you can use to setup the controller for the current route.
20824 This method is called with the controller for the current route and the
20825 model supplied by the `model` hook.
20826 By default, the `setupController` hook sets the `model` property of
20827 the controller to the specified `model` when it is not `undefined`.
20828 If you implement the `setupController` hook in your Route, it will
20829 prevent this default behavior. If you want to preserve that behavior
20830 when implementing your `setupController` function, make sure to call
20831 `super`:
20832 ```app/routes/photos.js
20833 import Route from '@ember/routing/route';
20834 export default class PhotosRoute extends Route {
20835 model() {
20836 return this.store.findAll('photo');
20837 }
20838 setupController(controller, model) {
20839 super.setupController(controller, model);
20840 this.controllerFor('application').set('showingPhotos', true);
20841 }
20842 }
20843 ```
20844 The provided controller will be one resolved based on the name
20845 of this route.
20846 If no explicit controller is defined, Ember will automatically create one.
20847 As an example, consider the router:
20848 ```app/router.js
20849 // ...
20850 Router.map(function() {
20851 this.route('post', { path: '/posts/:post_id' });
20852 });
20853 export default Router;
20854 ```
20855 If you have defined a file for the post controller,
20856 the framework will use it.
20857 If it is not defined, a basic `Controller` instance would be used.
20858 @example Behavior of a basic Controller
20859 ```app/routes/post.js
20860 import Route from '@ember/routing/route';
20861 export default class PostRoute extends Route {
20862 setupController(controller, model) {
20863 controller.set('model', model);
20864 }
20865 });
20866 ```
20867 @method setupController
20868 @param {Controller} controller instance
20869 @param {Object} model
20870 @param {Object} transition
20871 @since 1.0.0
20872 @public
20873 */
20874
20875
20876 setupController(controller, context, _transition) {
20877 // eslint-disable-line no-unused-vars
20878 if (controller && context !== undefined) {
20879 (0, _metal.set)(controller, 'model', context);
20880 }
20881 }
20882 /**
20883 Returns the controller of the current route, or a parent (or any ancestor)
20884 route in a route hierarchy.
20885 The controller instance must already have been created, either through entering the
20886 associated route or using `generateController`.
20887 ```app/routes/post.js
20888 import Route from '@ember/routing/route';
20889 export default class PostRoute extends Route {
20890 setupController(controller, post) {
20891 super.setupController(controller, post);
20892 this.controllerFor('posts').set('currentPost', post);
20893 }
20894 }
20895 ```
20896 @method controllerFor
20897 @param {String} name the name of the route or controller
20898 @return {Controller}
20899 @since 1.0.0
20900 @public
20901 */
20902
20903
20904 controllerFor(name, _skipAssert) {
20905 var owner = (0, _owner.getOwner)(this);
20906 var route = owner.lookup(`route:${name}`);
20907
20908 if (route && route.controllerName) {
20909 name = route.controllerName;
20910 }
20911
20912 var controller = owner.lookup(`controller:${name}`); // NOTE: We're specifically checking that skipAssert is true, because according
20913 // to the old API the second parameter was model. We do not want people who
20914 // passed a model to skip the assertion.
20915
20916 (true && !(controller !== undefined || _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 !== undefined || _skipAssert === true));
20917 return controller;
20918 }
20919 /**
20920 Generates a controller for a route.
20921 Example
20922 ```app/routes/post.js
20923 import Route from '@ember/routing/route';
20924 export default class Post extends Route {
20925 setupController(controller, post) {
20926 super.setupController(controller, post);
20927 this.generateController('posts');
20928 }
20929 }
20930 ```
20931 @method generateController
20932 @param {String} name the name of the controller
20933 @private
20934 */
20935
20936
20937 generateController(name) {
20938 var owner = (0, _owner.getOwner)(this);
20939 return (0, _generate_controller.default)(owner, name);
20940 }
20941 /**
20942 Returns the resolved model of a parent (or any ancestor) route
20943 in a route hierarchy. During a transition, all routes
20944 must resolve a model object, and if a route
20945 needs access to a parent route's model in order to
20946 resolve a model (or just reuse the model from a parent),
20947 it can call `this.modelFor(theNameOfParentRoute)` to
20948 retrieve it. If the ancestor route's model was a promise,
20949 its resolved result is returned.
20950 Example
20951 ```app/router.js
20952 // ...
20953 Router.map(function() {
20954 this.route('post', { path: '/posts/:post_id' }, function() {
20955 this.route('comments');
20956 });
20957 });
20958 export default Router;
20959 ```
20960 ```app/routes/post/comments.js
20961 import Route from '@ember/routing/route';
20962 export default class PostCommentsRoute extends Route {
20963 model() {
20964 let post = this.modelFor('post');
20965 return post.comments;
20966 }
20967 }
20968 ```
20969 @method modelFor
20970 @param {String} name the name of the route
20971 @return {Object} the model object
20972 @since 1.0.0
20973 @public
20974 */
20975
20976
20977 modelFor(_name) {
20978 var name;
20979 var owner = (0, _owner.getOwner)(this);
20980 var transition = this._router && this._router._routerMicrolib ? this._router._routerMicrolib.activeTransition : undefined; // Only change the route name when there is an active transition.
20981 // Otherwise, use the passed in route name.
20982
20983 if (owner.routable && transition !== undefined) {
20984 name = getEngineRouteName(owner, _name);
20985 } else {
20986 name = _name;
20987 }
20988
20989 var route = owner.lookup(`route:${name}`); // If we are mid-transition, we want to try and look up
20990 // resolved parent contexts on the current transitionEvent.
20991
20992 if (transition !== undefined && transition !== null) {
20993 var modelLookupName = route && route.routeName || name;
20994
20995 if (Object.prototype.hasOwnProperty.call(transition.resolvedModels, modelLookupName)) {
20996 return transition.resolvedModels[modelLookupName];
20997 }
20998 }
20999
21000 return route && route.currentModel;
21001 }
21002 /**
21003 A hook you can use to render the template for the current route.
21004 This method is called with the controller for the current route and the
21005 model supplied by the `model` hook. By default, it renders the route's
21006 template, configured with the controller for the route.
21007 This method can be overridden to set up and render additional or
21008 alternative templates.
21009 ```app/routes/posts.js
21010 import Route from '@ember/routing/route';
21011 export default class PostsRoute extends Route {
21012 renderTemplate(controller, model) {
21013 let favController = this.controllerFor('favoritePost');
21014 // Render the `favoritePost` template into
21015 // the outlet `posts`, and display the `favoritePost`
21016 // controller.
21017 this.render('favoritePost', {
21018 outlet: 'posts',
21019 controller: favController
21020 });
21021 }
21022 }
21023 ```
21024 @method renderTemplate
21025 @param {Object} controller the route's controller
21026 @param {Object} model the route's model
21027 @since 1.0.0
21028 @public
21029 */
21030
21031
21032 renderTemplate(_controller, _model) {
21033 // eslint-disable-line no-unused-vars
21034 this.render();
21035 }
21036 /**
21037 `render` is used to render a template into a region of another template
21038 (indicated by an `{{outlet}}`). `render` is used both during the entry
21039 phase of routing (via the `renderTemplate` hook) and later in response to
21040 user interaction.
21041 For example, given the following minimal router and templates:
21042 ```app/router.js
21043 // ...
21044 Router.map(function() {
21045 this.route('photos');
21046 });
21047 export default Router;
21048 ```
21049 ```handlebars
21050 <!-- application.hbs -->
21051 <div class='something-in-the-app-hbs'>
21052 {{outlet "anOutletName"}}
21053 </div>
21054 ```
21055 ```handlebars
21056 <!-- photos.hbs -->
21057 <h1>Photos</h1>
21058 ```
21059 You can render `photos.hbs` into the `"anOutletName"` outlet of
21060 `application.hbs` by calling `render`:
21061 ```app/routes/post.js
21062 import Route from '@ember/routing/route';
21063 export default class PostRoute extends Route {
21064 renderTemplate() {
21065 this.render('photos', {
21066 into: 'application',
21067 outlet: 'anOutletName'
21068 })
21069 }
21070 }
21071 ```
21072 `render` additionally allows you to supply which `controller` and
21073 `model` objects should be loaded and associated with the rendered template.
21074 ```app/routes/posts.js
21075 import Route from '@ember/routing/route';
21076 export default class PostsRoute extends Route {
21077 renderTemplate(controller, model) {
21078 this.render('posts', { // the template to render, referenced by name
21079 into: 'application', // the template to render into, referenced by name
21080 outlet: 'anOutletName', // the outlet inside `options.into` to render into.
21081 controller: 'someControllerName', // the controller to use for this template, referenced by name
21082 model: model // the model to set on `options.controller`.
21083 })
21084 }
21085 }
21086 ```
21087 The string values provided for the template name, and controller
21088 will eventually pass through to the resolver for lookup. See
21089 Resolver for how these are mapped to JavaScript objects in your
21090 application. The template to render into needs to be related to either the
21091 current route or one of its ancestors.
21092 Not all options need to be passed to `render`. Default values will be used
21093 based on the name of the route specified in the router or the Route's
21094 `controllerName` and `templateName` properties.
21095 For example:
21096 ```app/router.js
21097 // ...
21098 Router.map(function() {
21099 this.route('index');
21100 this.route('post', { path: '/posts/:post_id' });
21101 });
21102 export default Router;
21103 ```
21104 ```app/routes/post.js
21105 import Route from '@ember/routing/route';
21106 export default class PostRoute extends Route {
21107 renderTemplate() {
21108 this.render(); // all defaults apply
21109 }
21110 }
21111 ```
21112 The name of the route, defined by the router, is `post`.
21113 The following equivalent default options will be applied when
21114 the Route calls `render`:
21115 ```javascript
21116 this.render('post', { // the template name associated with 'post' Route
21117 into: 'application', // the parent route to 'post' Route
21118 outlet: 'main', // {{outlet}} and {{outlet 'main'}} are synonymous,
21119 controller: 'post', // the controller associated with the 'post' Route
21120 })
21121 ```
21122 By default the controller's `model` will be the route's model, so it does not
21123 need to be passed unless you wish to change which model is being used.
21124 @method render
21125 @param {String} name the name of the template to render
21126 @param {Object} [options] the options
21127 @param {String} [options.into] the template to render into,
21128 referenced by name. Defaults to the parent template
21129 @param {String} [options.outlet] the outlet inside `options.into` to render into.
21130 Defaults to 'main'
21131 @param {String|Object} [options.controller] the controller to use for this template,
21132 referenced by name or as a controller instance. Defaults to the Route's paired controller
21133 @param {Object} [options.model] the model object to set on `options.controller`.
21134 Defaults to the return value of the Route's model hook
21135 @since 1.0.0
21136 @public
21137 */
21138
21139
21140 render(name, options) {
21141 var renderOptions = buildRenderOptions(this, name, options);
21142 ROUTE_CONNECTIONS.get(this).push(renderOptions);
21143 (0, _runloop.once)(this._router, '_setOutlets');
21144 }
21145 /**
21146 Disconnects a view that has been rendered into an outlet.
21147 You may pass any or all of the following options to `disconnectOutlet`:
21148 * `outlet`: the name of the outlet to clear (default: 'main')
21149 * `parentView`: the name of the view containing the outlet to clear
21150 (default: the view rendered by the parent route)
21151 Example:
21152 ```app/routes/application.js
21153 import Route from '@ember/routing/route';
21154 import { action } from '@ember/object';
21155 export default class ApplicationRoute extends Route {
21156 @action
21157 showModal(evt) {
21158 this.render(evt.modalName, {
21159 outlet: 'modal',
21160 into: 'application'
21161 });
21162 }
21163 @action
21164 hideModal() {
21165 this.disconnectOutlet({
21166 outlet: 'modal',
21167 parentView: 'application'
21168 });
21169 }
21170 }
21171 ```
21172 Alternatively, you can pass the `outlet` name directly as a string.
21173 Example:
21174 ```app/routes/application.js
21175 import Route from '@ember/routing/route';
21176 import { action } from '@ember/object';
21177 export default class ApplicationRoute extends Route {
21178 @action
21179 showModal(evt) {
21180 // ...
21181 }
21182 @action
21183 hideModal(evt) {
21184 this.disconnectOutlet('modal');
21185 }
21186 }
21187 ```
21188 @method disconnectOutlet
21189 @param {Object|String} options the options hash or outlet name
21190 @since 1.0.0
21191 @public
21192 */
21193
21194
21195 disconnectOutlet(options) {
21196 var outletName;
21197 var parentView;
21198
21199 if (options) {
21200 if (typeof options === 'string') {
21201 outletName = options;
21202 } else {
21203 outletName = options.outlet;
21204 parentView = options.parentView ? options.parentView.replace(/\//g, '.') : undefined;
21205 (true && !(!('outlet' in options && options.outlet === undefined)) && (0, _debug.assert)('You passed undefined as the outlet name.', !('outlet' in options && options.outlet === undefined)));
21206 }
21207 }
21208
21209 outletName = outletName || 'main';
21210
21211 this._disconnectOutlet(outletName, parentView);
21212
21213 var routeInfos = this._router._routerMicrolib.currentRouteInfos;
21214
21215 for (var i = 0; i < routeInfos.length; i++) {
21216 // This non-local state munging is sadly necessary to maintain
21217 // backward compatibility with our existing semantics, which allow
21218 // any route to disconnectOutlet things originally rendered by any
21219 // other route. This should all get cut in 2.0.
21220 routeInfos[i].route._disconnectOutlet(outletName, parentView);
21221 }
21222 }
21223
21224 _disconnectOutlet(outletName, parentView) {
21225 var parent = parentRoute(this);
21226
21227 if (parent && parentView === parent.routeName) {
21228 parentView = undefined;
21229 }
21230
21231 var connections = ROUTE_CONNECTIONS.get(this);
21232
21233 for (var i = 0; i < connections.length; i++) {
21234 var connection = connections[i];
21235
21236 if (connection.outlet === outletName && connection.into === parentView) {
21237 // This neuters the disconnected outlet such that it doesn't
21238 // render anything, but it leaves an entry in the outlet
21239 // hierarchy so that any existing other renders that target it
21240 // don't suddenly blow up. They will still stick themselves
21241 // into its outlets, which won't render anywhere. All of this
21242 // statefulness should get the machete in 2.0.
21243 connections[i] = {
21244 owner: connection.owner,
21245 into: connection.into,
21246 outlet: connection.outlet,
21247 name: connection.name,
21248 controller: undefined,
21249 template: undefined,
21250 model: undefined
21251 };
21252 (0, _runloop.once)(this._router, '_setOutlets');
21253 }
21254 }
21255 }
21256
21257 willDestroy() {
21258 this.teardownViews();
21259 }
21260 /**
21261 @private
21262 @method teardownViews
21263 */
21264
21265
21266 teardownViews() {
21267 var connections = ROUTE_CONNECTIONS.get(this);
21268
21269 if (connections !== undefined && connections.length > 0) {
21270 ROUTE_CONNECTIONS.set(this, []);
21271 (0, _runloop.once)(this._router, '_setOutlets');
21272 }
21273 }
21274 /**
21275 Allows you to produce custom metadata for the route.
21276 The return value of this method will be attached to
21277 its corresponding RouteInfoWithAttributes object.
21278 Example
21279 ```app/routes/posts/index.js
21280 import Route from '@ember/routing/route';
21281 export default class PostsIndexRoute extends Route {
21282 buildRouteInfoMetadata() {
21283 return { title: 'Posts Page' }
21284 }
21285 }
21286 ```
21287 ```app/routes/application.js
21288 import Route from '@ember/routing/route';
21289 import { inject as service } from '@ember/service';
21290 export default class ApplicationRoute extends Route {
21291 @service router
21292 constructor() {
21293 super(...arguments);
21294 this.router.on('routeDidChange', transition => {
21295 document.title = transition.to.metadata.title;
21296 // would update document's title to "Posts Page"
21297 });
21298 }
21299 }
21300 ```
21301 @method buildRouteInfoMetadata
21302 @return any
21303 @since 3.10.0
21304 @public
21305 */
21306
21307
21308 buildRouteInfoMetadata() {}
21309
21310 }
21311
21312 Route.reopenClass({
21313 isRouteFactory: true
21314 });
21315
21316 function parentRoute(route) {
21317 var routeInfo = routeInfoFor(route, route._router._routerMicrolib.state.routeInfos, -1);
21318 return routeInfo && routeInfo.route;
21319 }
21320
21321 function routeInfoFor(route, routeInfos, offset = 0) {
21322 if (!routeInfos) {
21323 return;
21324 }
21325
21326 var current;
21327
21328 for (var i = 0; i < routeInfos.length; i++) {
21329 current = routeInfos[i].route;
21330
21331 if (current === route) {
21332 return routeInfos[i + offset];
21333 }
21334 }
21335
21336 return;
21337 }
21338
21339 function buildRenderOptions(route, nameOrOptions, options) {
21340 var isDefaultRender = !nameOrOptions && !options;
21341
21342 var _name;
21343
21344 if (!isDefaultRender) {
21345 if (typeof nameOrOptions === 'object' && !options) {
21346 _name = route.templateName || route.routeName;
21347 options = nameOrOptions;
21348 } else {
21349 (true && !(!(0, _metal.isEmpty)(nameOrOptions)) && (0, _debug.assert)('The name in the given arguments is undefined or empty string', !(0, _metal.isEmpty)(nameOrOptions)));
21350 _name = nameOrOptions;
21351 }
21352 }
21353
21354 (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)));
21355 var owner = (0, _owner.getOwner)(route);
21356 var name, templateName, into, outlet, model;
21357 var controller = undefined;
21358
21359 if (options) {
21360 into = options.into && options.into.replace(/\//g, '.');
21361 outlet = options.outlet;
21362 controller = options.controller;
21363 model = options.model;
21364 }
21365
21366 outlet = outlet || 'main';
21367
21368 if (isDefaultRender) {
21369 name = route.routeName;
21370 templateName = route.templateName || name;
21371 } else {
21372 name = _name.replace(/\//g, '.');
21373 templateName = name;
21374 }
21375
21376 if (controller === undefined) {
21377 if (isDefaultRender) {
21378 controller = route.controllerName || owner.lookup(`controller:${name}`);
21379 } else {
21380 controller = owner.lookup(`controller:${name}`) || route.controllerName || route.routeName;
21381 }
21382 }
21383
21384 if (typeof controller === 'string') {
21385 var controllerName = controller;
21386 controller = owner.lookup(`controller:${controllerName}`);
21387 (true && !(isDefaultRender || controller !== undefined) && (0, _debug.assert)(`You passed \`controller: '${controllerName}'\` into the \`render\` method, but no such controller could be found.`, isDefaultRender || controller !== undefined));
21388 }
21389
21390 if (model === undefined) {
21391 model = route.currentModel;
21392 } else {
21393 controller.set('model', model);
21394 }
21395
21396 var template = owner.lookup(`template:${templateName}`);
21397 (true && !(isDefaultRender || template !== undefined) && (0, _debug.assert)(`Could not find "${templateName}" template, view, or component.`, isDefaultRender || template !== undefined));
21398 var parent;
21399
21400 if (into && (parent = parentRoute(route)) && into === parent.routeName) {
21401 into = undefined;
21402 }
21403
21404 var renderOptions = {
21405 owner,
21406 into,
21407 outlet,
21408 name,
21409 controller,
21410 model,
21411 template: template !== undefined ? template(owner) : route._topLevelViewTemplate(owner)
21412 };
21413
21414 if (true
21415 /* DEBUG */
21416 ) {
21417 var LOG_VIEW_LOOKUPS = (0, _metal.get)(route._router, 'namespace.LOG_VIEW_LOOKUPS');
21418
21419 if (LOG_VIEW_LOOKUPS && !template) {
21420 (0, _debug.info)(`Could not find "${name}" template. Nothing will be rendered`, {
21421 fullName: `template:${name}`
21422 });
21423 }
21424 }
21425
21426 return renderOptions;
21427 }
21428
21429 function getFullQueryParams(router, state) {
21430 if (state['fullQueryParams']) {
21431 return state['fullQueryParams'];
21432 }
21433
21434 state['fullQueryParams'] = {};
21435 (0, _polyfills.assign)(state['fullQueryParams'], state.queryParams);
21436
21437 router._deserializeQueryParams(state.routeInfos, state['fullQueryParams']);
21438
21439 return state['fullQueryParams'];
21440 }
21441
21442 function getQueryParamsFor(route, state) {
21443 state['queryParamsFor'] = state['queryParamsFor'] || {};
21444 var name = route.fullRouteName;
21445
21446 if (state['queryParamsFor'][name]) {
21447 return state['queryParamsFor'][name];
21448 }
21449
21450 var fullQueryParams = getFullQueryParams(route._router, state);
21451 var params = state['queryParamsFor'][name] = {}; // Copy over all the query params for this route/controller into params hash.
21452
21453 var qps = (0, _metal.get)(route, '_qp.qps');
21454
21455 for (var i = 0; i < qps.length; ++i) {
21456 // Put deserialized qp on params hash.
21457 var qp = qps[i];
21458 var qpValueWasPassedIn = (qp.prop in fullQueryParams);
21459 params[qp.prop] = qpValueWasPassedIn ? fullQueryParams[qp.prop] : copyDefaultValue(qp.defaultValue);
21460 }
21461
21462 return params;
21463 }
21464
21465 function copyDefaultValue(value) {
21466 if (Array.isArray(value)) {
21467 return (0, _runtime.A)(value.slice());
21468 }
21469
21470 return value;
21471 }
21472 /*
21473 Merges all query parameters from a controller with those from
21474 a route, returning a new object and avoiding any mutations to
21475 the existing objects.
21476 */
21477
21478
21479 function mergeEachQueryParams(controllerQP, routeQP) {
21480 var qps = {};
21481 var keysAlreadyMergedOrSkippable = {
21482 defaultValue: true,
21483 type: true,
21484 scope: true,
21485 as: true
21486 }; // first loop over all controller qps, merging them with any matching route qps
21487 // into a new empty object to avoid mutating.
21488
21489 for (var cqpName in controllerQP) {
21490 if (!Object.prototype.hasOwnProperty.call(controllerQP, cqpName)) {
21491 continue;
21492 }
21493
21494 var newControllerParameterConfiguration = {};
21495 (0, _polyfills.assign)(newControllerParameterConfiguration, controllerQP[cqpName], routeQP[cqpName]);
21496 qps[cqpName] = newControllerParameterConfiguration; // allows us to skip this QP when we check route QPs.
21497
21498 keysAlreadyMergedOrSkippable[cqpName] = true;
21499 } // loop over all route qps, skipping those that were merged in the first pass
21500 // because they also appear in controller qps
21501
21502
21503 for (var rqpName in routeQP) {
21504 if (!Object.prototype.hasOwnProperty.call(routeQP, rqpName) || keysAlreadyMergedOrSkippable[rqpName]) {
21505 continue;
21506 }
21507
21508 var newRouteParameterConfiguration = {};
21509 (0, _polyfills.assign)(newRouteParameterConfiguration, routeQP[rqpName], controllerQP[rqpName]);
21510 qps[rqpName] = newRouteParameterConfiguration;
21511 }
21512
21513 return qps;
21514 }
21515
21516 function addQueryParamsObservers(controller, propNames) {
21517 propNames.forEach(prop => {
21518 if ((0, _metal.descriptorForProperty)(controller, prop) === undefined) {
21519 var desc = (0, _utils.lookupDescriptor)(controller, prop);
21520
21521 if (desc !== null && (typeof desc.get === 'function' || typeof desc.set === 'function')) {
21522 (0, _metal.defineProperty)(controller, prop, (0, _compat.dependentKeyCompat)({
21523 get: desc.get,
21524 set: desc.set
21525 }));
21526 }
21527 }
21528
21529 (0, _metal.addObserver)(controller, `${prop}.[]`, controller, controller._qpChanged, false);
21530 });
21531 }
21532
21533 function getEngineRouteName(engine, routeName) {
21534 if (engine.routable) {
21535 var prefix = engine.mountPoint;
21536
21537 if (routeName === 'application') {
21538 return prefix;
21539 } else {
21540 return `${prefix}.${routeName}`;
21541 }
21542 }
21543
21544 return routeName;
21545 }
21546 /**
21547 A hook you can implement to convert the route's model into parameters
21548 for the URL.
21549
21550 ```app/router.js
21551 // ...
21552
21553 Router.map(function() {
21554 this.route('post', { path: '/posts/:post_id' });
21555 });
21556
21557 ```
21558
21559 ```app/routes/post.js
21560 import Route from '@ember/routing/route';
21561
21562 export default class PostRoute extends Route {
21563 model({ post_id }) {
21564 // the server returns `{ id: 12 }`
21565 return fetch(`/posts/${post_id}`;
21566 }
21567
21568 serialize(model) {
21569 // this will make the URL `/posts/12`
21570 return { post_id: model.id };
21571 }
21572 }
21573 ```
21574
21575 The default `serialize` method will insert the model's `id` into the
21576 route's dynamic segment (in this case, `:post_id`) if the segment contains '_id'.
21577 If the route has multiple dynamic segments or does not contain '_id', `serialize`
21578 will return `getProperties(model, params)`
21579
21580 This method is called when `transitionTo` is called with a context
21581 in order to populate the URL.
21582
21583 @method serialize
21584 @param {Object} model the routes model
21585 @param {Array} params an Array of parameter names for the current
21586 route (in the example, `['post_id']`.
21587 @return {Object} the serialized parameters
21588 @since 1.0.0
21589 @public
21590 */
21591
21592
21593 Route.prototype.serialize = defaultSerialize;
21594 Route.reopen(_runtime.ActionHandler, _runtime.Evented, {
21595 mergedProperties: ['queryParams'],
21596
21597 /**
21598 Configuration hash for this route's queryParams. The possible
21599 configuration options and their defaults are as follows
21600 (assuming a query param whose controller property is `page`):
21601 ```javascript
21602 queryParams: {
21603 page: {
21604 // By default, controller query param properties don't
21605 // cause a full transition when they are changed, but
21606 // rather only cause the URL to update. Setting
21607 // `refreshModel` to true will cause an "in-place"
21608 // transition to occur, whereby the model hooks for
21609 // this route (and any child routes) will re-fire, allowing
21610 // you to reload models (e.g., from the server) using the
21611 // updated query param values.
21612 refreshModel: false,
21613 // By default, changes to controller query param properties
21614 // cause the URL to update via `pushState`, which means an
21615 // item will be added to the browser's history, allowing
21616 // you to use the back button to restore the app to the
21617 // previous state before the query param property was changed.
21618 // Setting `replace` to true will use `replaceState` (or its
21619 // hash location equivalent), which causes no browser history
21620 // item to be added. This options name and default value are
21621 // the same as the `link-to` helper's `replace` option.
21622 replace: false,
21623 // By default, the query param URL key is the same name as
21624 // the controller property name. Use `as` to specify a
21625 // different URL key.
21626 as: 'page'
21627 }
21628 }
21629 ```
21630 @property queryParams
21631 @for Route
21632 @type Object
21633 @since 1.6.0
21634 @public
21635 */
21636 queryParams: {},
21637
21638 /**
21639 The name of the template to use by default when rendering this routes
21640 template.
21641 ```app/routes/posts/list.js
21642 import Route from '@ember/routing/route';
21643 export default class extends Route {
21644 templateName = 'posts/list'
21645 });
21646 ```
21647 ```app/routes/posts/index.js
21648 import PostsList from '../posts/list';
21649 export default class extends PostsList {};
21650 ```
21651 ```app/routes/posts/archived.js
21652 import PostsList from '../posts/list';
21653 export default class extends PostsList {};
21654 ```
21655 @property templateName
21656 @type String
21657 @default null
21658 @since 1.4.0
21659 @public
21660 */
21661 templateName: null,
21662
21663 /**
21664 @private
21665 @property _names
21666 */
21667 _names: null,
21668
21669 /**
21670 The name of the controller to associate with this route.
21671 By default, Ember will lookup a route's controller that matches the name
21672 of the route (i.e. `posts.new`). However,
21673 if you would like to define a specific controller to use, you can do so
21674 using this property.
21675 This is useful in many ways, as the controller specified will be:
21676 * passed to the `setupController` method.
21677 * used as the controller for the template being rendered by the route.
21678 * returned from a call to `controllerFor` for the route.
21679 @property controllerName
21680 @type String
21681 @default null
21682 @since 1.4.0
21683 @public
21684 */
21685 controllerName: null,
21686
21687 /**
21688 Store property provides a hook for data persistence libraries to inject themselves.
21689 By default, this store property provides the exact same functionality previously
21690 in the model hook.
21691 Currently, the required interface is:
21692 `store.find(modelName, findArguments)`
21693 @property store
21694 @type {Object}
21695 @private
21696 */
21697 store: (0, _metal.computed)({
21698 get() {
21699 var owner = (0, _owner.getOwner)(this);
21700 var routeName = this.routeName;
21701 var namespace = (0, _metal.get)(this, '_router.namespace');
21702 return {
21703 find(name, value) {
21704 var modelClass = owner.factoryFor(`model:${name}`);
21705 (true && !(Boolean(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.`, Boolean(modelClass)));
21706
21707 if (!modelClass) {
21708 return;
21709 }
21710
21711 modelClass = modelClass.class;
21712 (true && !(typeof modelClass.find === 'function') && (0, _debug.assert)(`${(0, _string.classify)(name)} has no method \`find\`.`, typeof modelClass.find === 'function'));
21713 return modelClass.find(value);
21714 }
21715
21716 };
21717 },
21718
21719 set(key, value) {
21720 (0, _metal.defineProperty)(this, key, null, value);
21721 }
21722
21723 }),
21724
21725 /**
21726 @private
21727 @property _qp
21728 */
21729 _qp: (0, _metal.computed)(function () {
21730 var combinedQueryParameterConfiguration;
21731 var controllerName = this.controllerName || this.routeName;
21732 var owner = (0, _owner.getOwner)(this);
21733 var controller = owner.lookup(`controller:${controllerName}`);
21734 var queryParameterConfiguraton = (0, _metal.get)(this, 'queryParams');
21735 var hasRouterDefinedQueryParams = Object.keys(queryParameterConfiguraton).length > 0;
21736
21737 if (controller) {
21738 // the developer has authored a controller class in their application for
21739 // this route find its query params and normalize their object shape them
21740 // merge in the query params for the route. As a mergedProperty,
21741 // Route#queryParams is always at least `{}`
21742 var controllerDefinedQueryParameterConfiguration = (0, _metal.get)(controller, 'queryParams') || {};
21743 var normalizedControllerQueryParameterConfiguration = (0, _utils2.normalizeControllerQueryParams)(controllerDefinedQueryParameterConfiguration);
21744 combinedQueryParameterConfiguration = mergeEachQueryParams(normalizedControllerQueryParameterConfiguration, queryParameterConfiguraton);
21745 } else if (hasRouterDefinedQueryParams) {
21746 // the developer has not defined a controller but *has* supplied route query params.
21747 // Generate a class for them so we can later insert default values
21748 controller = (0, _generate_controller.default)(owner, controllerName);
21749 combinedQueryParameterConfiguration = queryParameterConfiguraton;
21750 }
21751
21752 var qps = [];
21753 var map = {};
21754 var propertyNames = [];
21755
21756 for (var propName in combinedQueryParameterConfiguration) {
21757 if (!Object.prototype.hasOwnProperty.call(combinedQueryParameterConfiguration, propName)) {
21758 continue;
21759 } // to support the dubious feature of using unknownProperty
21760 // on queryParams configuration
21761
21762
21763 if (propName === 'unknownProperty' || propName === '_super') {
21764 // possible todo: issue deprecation warning?
21765 continue;
21766 }
21767
21768 var desc = combinedQueryParameterConfiguration[propName];
21769 var scope = desc.scope || 'model';
21770 var parts = void 0;
21771
21772 if (scope === 'controller') {
21773 parts = [];
21774 }
21775
21776 var urlKey = desc.as || this.serializeQueryParamKey(propName);
21777 var defaultValue = (0, _metal.get)(controller, propName);
21778 defaultValue = copyDefaultValue(defaultValue);
21779 var type = desc.type || (0, _runtime.typeOf)(defaultValue);
21780 var defaultValueSerialized = this.serializeQueryParam(defaultValue, urlKey, type);
21781 var scopedPropertyName = `${controllerName}:${propName}`;
21782 var qp = {
21783 undecoratedDefaultValue: (0, _metal.get)(controller, propName),
21784 defaultValue,
21785 serializedDefaultValue: defaultValueSerialized,
21786 serializedValue: defaultValueSerialized,
21787 type,
21788 urlKey,
21789 prop: propName,
21790 scopedPropertyName,
21791 controllerName,
21792 route: this,
21793 parts,
21794 values: null,
21795 scope
21796 };
21797 map[propName] = map[urlKey] = map[scopedPropertyName] = qp;
21798 qps.push(qp);
21799 propertyNames.push(propName);
21800 }
21801
21802 return {
21803 qps,
21804 map,
21805 propertyNames,
21806 states: {
21807 /*
21808 Called when a query parameter changes in the URL, this route cares
21809 about that query parameter, but the route is not currently
21810 in the active route hierarchy.
21811 */
21812 inactive: (prop, value) => {
21813 var qp = map[prop];
21814
21815 this._qpChanged(prop, value, qp);
21816 },
21817
21818 /*
21819 Called when a query parameter changes in the URL, this route cares
21820 about that query parameter, and the route is currently
21821 in the active route hierarchy.
21822 */
21823 active: (prop, value) => {
21824 var qp = map[prop];
21825
21826 this._qpChanged(prop, value, qp);
21827
21828 return this._activeQPChanged(qp, value);
21829 },
21830
21831 /*
21832 Called when a value of a query parameter this route handles changes in a controller
21833 and the route is currently in the active route hierarchy.
21834 */
21835 allowOverrides: (prop, value) => {
21836 var qp = map[prop];
21837
21838 this._qpChanged(prop, value, qp);
21839
21840 return this._updatingQPChanged(qp);
21841 }
21842 }
21843 };
21844 }),
21845
21846 /**
21847 Sends an action to the router, which will delegate it to the currently
21848 active route hierarchy per the bubbling rules explained under `actions`.
21849 Example
21850 ```app/router.js
21851 // ...
21852 Router.map(function() {
21853 this.route('index');
21854 });
21855 export default Router;
21856 ```
21857 ```app/routes/application.js
21858 import Route from '@ember/routing/route';
21859 import { action } from '@ember/object';
21860 export default class ApplicationRoute extends Route {
21861 @action
21862 track(arg) {
21863 console.log(arg, 'was clicked');
21864 }
21865 }
21866 ```
21867 ```app/routes/index.js
21868 import Route from '@ember/routing/route';
21869 import { action } from '@glimmer/tracking';
21870 export default class IndexRoute extends Route {
21871 @action
21872 trackIfDebug(arg) {
21873 if (debug) {
21874 this.send('track', arg);
21875 }
21876 }
21877 }
21878 ```
21879 @method send
21880 @param {String} name the name of the action to trigger
21881 @param {...*} args
21882 @since 1.0.0
21883 @public
21884 */
21885 send(...args) {
21886 (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));
21887
21888 if (this._router && this._router._routerMicrolib || !(0, _debug.isTesting)()) {
21889 this._router.send(...args);
21890 } else {
21891 var name = args.shift();
21892 var action = this.actions[name];
21893
21894 if (action) {
21895 return action.apply(this, args);
21896 }
21897 }
21898 },
21899
21900 /**
21901 The controller associated with this route.
21902 Example
21903 ```app/routes/form.js
21904 import Route from '@ember/routing/route';
21905 import { action } from '@ember/object';
21906 export default class FormRoute extends Route {
21907 @action
21908 willTransition(transition) {
21909 if (this.controller.get('userHasEnteredData') &&
21910 !confirm('Are you sure you want to abandon progress?')) {
21911 transition.abort();
21912 } else {
21913 // Bubble the `willTransition` action so that
21914 // parent routes can decide whether or not to abort.
21915 return true;
21916 }
21917 }
21918 }
21919 ```
21920 @property controller
21921 @type Controller
21922 @since 1.6.0
21923 @public
21924 */
21925 actions: {
21926 /**
21927 This action is called when one or more query params have changed. Bubbles.
21928 @method queryParamsDidChange
21929 @param changed {Object} Keys are names of query params that have changed.
21930 @param totalPresent {Object} Keys are names of query params that are currently set.
21931 @param removed {Object} Keys are names of query params that have been removed.
21932 @returns {boolean}
21933 @private
21934 */
21935 queryParamsDidChange(changed, _totalPresent, removed) {
21936 var qpMap = (0, _metal.get)(this, '_qp').map;
21937 var totalChanged = Object.keys(changed).concat(Object.keys(removed));
21938
21939 for (var i = 0; i < totalChanged.length; ++i) {
21940 var qp = qpMap[totalChanged[i]];
21941
21942 if (qp && (0, _metal.get)(this._optionsForQueryParam(qp), 'refreshModel') && this._router.currentState) {
21943 this.refresh();
21944 break;
21945 }
21946 }
21947
21948 return true;
21949 },
21950
21951 finalizeQueryParamChange(params, finalParams, transition) {
21952 if (this.fullRouteName !== 'application') {
21953 return true;
21954 } // Transition object is absent for intermediate transitions.
21955
21956
21957 if (!transition) {
21958 return;
21959 }
21960
21961 var routeInfos = transition[_router_js.STATE_SYMBOL].routeInfos;
21962 var router = this._router;
21963
21964 var qpMeta = router._queryParamsFor(routeInfos);
21965
21966 var changes = router._qpUpdates;
21967 var qpUpdated = false;
21968 var replaceUrl;
21969 (0, _utils2.stashParamNames)(router, routeInfos);
21970
21971 for (var i = 0; i < qpMeta.qps.length; ++i) {
21972 var qp = qpMeta.qps[i];
21973 var route = qp.route;
21974 var controller = route.controller;
21975 var presentKey = qp.urlKey in params && qp.urlKey; // Do a reverse lookup to see if the changed query
21976 // param URL key corresponds to a QP property on
21977 // this controller.
21978
21979 var value = void 0,
21980 svalue = void 0;
21981
21982 if (changes.has(qp.urlKey)) {
21983 // Value updated in/before setupController
21984 value = (0, _metal.get)(controller, qp.prop);
21985 svalue = route.serializeQueryParam(value, qp.urlKey, qp.type);
21986 } else {
21987 if (presentKey) {
21988 svalue = params[presentKey];
21989
21990 if (svalue !== undefined) {
21991 value = route.deserializeQueryParam(svalue, qp.urlKey, qp.type);
21992 }
21993 } else {
21994 // No QP provided; use default value.
21995 svalue = qp.serializedDefaultValue;
21996 value = copyDefaultValue(qp.defaultValue);
21997 }
21998 }
21999
22000 controller._qpDelegate = (0, _metal.get)(route, '_qp.states.inactive');
22001 var thisQueryParamChanged = svalue !== qp.serializedValue;
22002
22003 if (thisQueryParamChanged) {
22004 if (transition.queryParamsOnly && replaceUrl !== false) {
22005 var options = route._optionsForQueryParam(qp);
22006
22007 var replaceConfigValue = (0, _metal.get)(options, 'replace');
22008
22009 if (replaceConfigValue) {
22010 replaceUrl = true;
22011 } else if (replaceConfigValue === false) {
22012 // Explicit pushState wins over any other replaceStates.
22013 replaceUrl = false;
22014 }
22015 }
22016
22017 (0, _metal.set)(controller, qp.prop, value);
22018 qpUpdated = true;
22019 } // Stash current serialized value of controller.
22020
22021
22022 qp.serializedValue = svalue;
22023 var thisQueryParamHasDefaultValue = qp.serializedDefaultValue === svalue;
22024
22025 if (!thisQueryParamHasDefaultValue || transition._keepDefaultQueryParamValues) {
22026 finalParams.push({
22027 value: svalue,
22028 visible: true,
22029 key: presentKey || qp.urlKey
22030 });
22031 }
22032 } // Some QPs have been updated, and those changes need to be propogated
22033 // immediately. Eventually, we should work on making this async somehow.
22034
22035
22036 if (qpUpdated === true) {
22037 (0, _metal.flushAsyncObservers)(false);
22038 }
22039
22040 if (replaceUrl) {
22041 transition.method('replace');
22042 }
22043
22044 qpMeta.qps.forEach(qp => {
22045 var routeQpMeta = (0, _metal.get)(qp.route, '_qp');
22046 var finalizedController = qp.route.controller;
22047 finalizedController['_qpDelegate'] = (0, _metal.get)(routeQpMeta, 'states.active');
22048 });
22049
22050 router._qpUpdates.clear();
22051
22052 return;
22053 }
22054
22055 }
22056 });
22057 var ROUTER_EVENT_DEPRECATIONS;
22058 _exports.ROUTER_EVENT_DEPRECATIONS = ROUTER_EVENT_DEPRECATIONS;
22059
22060 if (_deprecatedFeatures.ROUTER_EVENTS) {
22061 _exports.ROUTER_EVENT_DEPRECATIONS = ROUTER_EVENT_DEPRECATIONS = {
22062 on(name) {
22063 this._super(...arguments);
22064
22065 var hasDidTransition = name === 'didTransition';
22066 var hasWillTransition = name === 'willTransition';
22067
22068 if (hasDidTransition) {
22069 (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, {
22070 id: 'deprecate-router-events',
22071 until: '4.0.0',
22072 url: 'https://emberjs.com/deprecations/v3.x#toc_deprecate-router-events'
22073 }));
22074 }
22075
22076 if (hasWillTransition) {
22077 (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, {
22078 id: 'deprecate-router-events',
22079 until: '4.0.0',
22080 url: 'https://emberjs.com/deprecations/v3.x#toc_deprecate-router-events'
22081 }));
22082 }
22083 }
22084
22085 };
22086 Route.reopen(ROUTER_EVENT_DEPRECATIONS, {
22087 _paramsFor(routeName, params) {
22088 var transition = this._router._routerMicrolib.activeTransition;
22089
22090 if (transition !== undefined) {
22091 return this.paramsFor(routeName);
22092 }
22093
22094 return params;
22095 }
22096
22097 });
22098 }
22099
22100 var _default = Route;
22101 _exports.default = _default;
22102});
22103define("@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) {
22104 "use strict";
22105
22106 Object.defineProperty(_exports, "__esModule", {
22107 value: true
22108 });
22109 _exports.triggerEvent = triggerEvent;
22110 _exports.default = void 0;
22111
22112 function defaultDidTransition(infos) {
22113 updatePaths(this);
22114
22115 this._cancelSlowTransitionTimer();
22116
22117 this.notifyPropertyChange('url');
22118 this.set('currentState', this.targetState); // Put this in the runloop so url will be accurate. Seems
22119 // less surprising than didTransition being out of sync.
22120
22121 (0, _runloop.once)(this, this.trigger, 'didTransition');
22122
22123 if (true
22124 /* DEBUG */
22125 ) {
22126 if ((0, _metal.get)(this, 'namespace').LOG_TRANSITIONS) {
22127 // eslint-disable-next-line no-console
22128 console.log(`Transitioned into '${EmberRouter._routePath(infos)}'`);
22129 }
22130 }
22131 }
22132
22133 function defaultWillTransition(oldInfos, newInfos, transition) {
22134 (0, _runloop.once)(this, this.trigger, 'willTransition', transition);
22135
22136 if (true
22137 /* DEBUG */
22138 ) {
22139 if ((0, _metal.get)(this, 'namespace').LOG_TRANSITIONS) {
22140 // eslint-disable-next-line no-console
22141 console.log(`Preparing to transition from '${EmberRouter._routePath(oldInfos)}' to '${EmberRouter._routePath(newInfos)}'`);
22142 }
22143 }
22144 }
22145
22146 function K() {
22147 return this;
22148 }
22149
22150 var {
22151 slice
22152 } = Array.prototype;
22153 /**
22154 The `EmberRouter` class manages the application state and URLs. Refer to
22155 the [routing guide](https://guides.emberjs.com/release/routing/) for documentation.
22156
22157 @class EmberRouter
22158 @extends EmberObject
22159 @uses Evented
22160 @public
22161 */
22162
22163 class EmberRouter extends _runtime.Object {
22164 constructor() {
22165 super(...arguments);
22166 this.currentURL = null;
22167 this.currentRouteName = null;
22168 this.currentPath = null;
22169 this.currentRoute = null;
22170 this._qpCache = Object.create(null);
22171 this._qpUpdates = new Set();
22172 this._queuedQPChanges = {};
22173 this._toplevelView = null;
22174 this._handledErrors = new Set();
22175 this._engineInstances = Object.create(null);
22176 this._engineInfoByRoute = Object.create(null);
22177 this.currentState = null;
22178 this.targetState = null;
22179
22180 this._resetQueuedQueryParameterChanges();
22181 }
22182
22183 _initRouterJs() {
22184 var location = (0, _metal.get)(this, 'location');
22185 var router = this;
22186 var owner = (0, _owner.getOwner)(this);
22187 var seen = Object.create(null);
22188
22189 class PrivateRouter extends _router_js.default {
22190 getRoute(name) {
22191 var routeName = name;
22192 var routeOwner = owner;
22193 var engineInfo = router._engineInfoByRoute[routeName];
22194
22195 if (engineInfo) {
22196 var engineInstance = router._getEngineInstance(engineInfo);
22197
22198 routeOwner = engineInstance;
22199 routeName = engineInfo.localFullName;
22200 }
22201
22202 var fullRouteName = `route:${routeName}`;
22203 var route = routeOwner.lookup(fullRouteName);
22204
22205 if (seen[name]) {
22206 return route;
22207 }
22208
22209 seen[name] = true;
22210
22211 if (!route) {
22212 var DefaultRoute = routeOwner.factoryFor('route:basic').class;
22213 routeOwner.register(fullRouteName, DefaultRoute.extend());
22214 route = routeOwner.lookup(fullRouteName);
22215
22216 if (true
22217 /* DEBUG */
22218 ) {
22219 if ((0, _metal.get)(router, 'namespace.LOG_ACTIVE_GENERATION')) {
22220 (0, _debug.info)(`generated -> ${fullRouteName}`, {
22221 fullName: fullRouteName
22222 });
22223 }
22224 }
22225 }
22226
22227 route._setRouteName(routeName);
22228
22229 if (engineInfo && !(0, _route.hasDefaultSerialize)(route)) {
22230 throw new Error('Defining a custom serialize method on an Engine route is not supported.');
22231 }
22232
22233 return route;
22234 }
22235
22236 getSerializer(name) {
22237 var engineInfo = router._engineInfoByRoute[name]; // If this is not an Engine route, we fall back to the handler for serialization
22238
22239 if (!engineInfo) {
22240 return;
22241 }
22242
22243 return engineInfo.serializeMethod || _route.defaultSerialize;
22244 }
22245
22246 updateURL(path) {
22247 (0, _runloop.once)(() => {
22248 location.setURL(path);
22249 (0, _metal.set)(router, 'currentURL', path);
22250 });
22251 }
22252
22253 didTransition(infos) {
22254 if (_deprecatedFeatures.ROUTER_EVENTS) {
22255 if (router.didTransition !== defaultDidTransition) {
22256 (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, {
22257 id: 'deprecate-router-events',
22258 until: '4.0.0',
22259 url: 'https://emberjs.com/deprecations/v3.x#toc_deprecate-router-events'
22260 }));
22261 }
22262 }
22263
22264 router.didTransition(infos);
22265 }
22266
22267 willTransition(oldInfos, newInfos, transition) {
22268 if (_deprecatedFeatures.ROUTER_EVENTS) {
22269 if (router.willTransition !== defaultWillTransition) {
22270 (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, {
22271 id: 'deprecate-router-events',
22272 until: '4.0.0',
22273 url: 'https://emberjs.com/deprecations/v3.x#toc_deprecate-router-events'
22274 }));
22275 }
22276 }
22277
22278 router.willTransition(oldInfos, newInfos, transition);
22279 }
22280
22281 triggerEvent(routeInfos, ignoreFailure, name, args) {
22282 return triggerEvent.bind(router)(routeInfos, ignoreFailure, name, args);
22283 }
22284
22285 routeWillChange(transition) {
22286 router.trigger('routeWillChange', transition);
22287 }
22288
22289 routeDidChange(transition) {
22290 router.set('currentRoute', transition.to);
22291 (0, _runloop.once)(() => {
22292 router.trigger('routeDidChange', transition);
22293 });
22294 }
22295
22296 transitionDidError(error, transition) {
22297 if (error.wasAborted || transition.isAborted) {
22298 // If the error was a transition erorr or the transition aborted
22299 // log the abort.
22300 return (0, _router_js.logAbort)(transition);
22301 } else {
22302 // Otherwise trigger the "error" event to attempt an intermediate
22303 // transition into an error substate
22304 transition.trigger(false, 'error', error.error, transition, error.route);
22305
22306 if (router._isErrorHandled(error.error)) {
22307 // If we handled the error with a substate just roll the state back on
22308 // the transition and send the "routeDidChange" event for landing on
22309 // the error substate and return the error.
22310 transition.rollback();
22311 this.routeDidChange(transition);
22312 return error.error;
22313 } else {
22314 // If it was not handled, abort the transition completely and return
22315 // the error.
22316 transition.abort();
22317 return error.error;
22318 }
22319 }
22320 }
22321
22322 replaceURL(url) {
22323 if (location.replaceURL) {
22324 var doReplaceURL = () => {
22325 location.replaceURL(url);
22326 (0, _metal.set)(router, 'currentURL', url);
22327 };
22328
22329 (0, _runloop.once)(doReplaceURL);
22330 } else {
22331 this.updateURL(url);
22332 }
22333 }
22334
22335 }
22336
22337 var routerMicrolib = this._routerMicrolib = new PrivateRouter();
22338 var dslCallbacks = this.constructor.dslCallbacks || [K];
22339
22340 var dsl = this._buildDSL();
22341
22342 dsl.route('application', {
22343 path: '/',
22344 resetNamespace: true,
22345 overrideNameAssertion: true
22346 }, function () {
22347 for (var i = 0; i < dslCallbacks.length; i++) {
22348 dslCallbacks[i].call(this);
22349 }
22350 });
22351
22352 if (true
22353 /* DEBUG */
22354 ) {
22355 if ((0, _metal.get)(this, 'namespace.LOG_TRANSITIONS_INTERNAL')) {
22356 routerMicrolib.log = console.log.bind(console); // eslint-disable-line no-console
22357 }
22358 }
22359
22360 routerMicrolib.map(dsl.generate());
22361 }
22362
22363 _buildDSL() {
22364 var enableLoadingSubstates = this._hasModuleBasedResolver();
22365
22366 var router = this;
22367 var owner = (0, _owner.getOwner)(this);
22368 var options = {
22369 enableLoadingSubstates,
22370
22371 resolveRouteMap(name) {
22372 return owner.factoryFor(`route-map:${name}`);
22373 },
22374
22375 addRouteForEngine(name, engineInfo) {
22376 if (!router._engineInfoByRoute[name]) {
22377 router._engineInfoByRoute[name] = engineInfo;
22378 }
22379 }
22380
22381 };
22382 return new _dsl.default(null, options);
22383 }
22384 /*
22385 Resets all pending query parameter changes.
22386 Called after transitioning to a new route
22387 based on query parameter changes.
22388 */
22389
22390
22391 _resetQueuedQueryParameterChanges() {
22392 this._queuedQPChanges = {};
22393 }
22394
22395 _hasModuleBasedResolver() {
22396 var owner = (0, _owner.getOwner)(this);
22397
22398 if (!owner) {
22399 return false;
22400 }
22401
22402 var resolver = (0, _metal.get)(owner, 'application.__registry__.resolver.moduleBasedResolver');
22403 return Boolean(resolver);
22404 }
22405 /**
22406 Initializes the current router instance and sets up the change handling
22407 event listeners used by the instances `location` implementation.
22408 A property named `initialURL` will be used to determine the initial URL.
22409 If no value is found `/` will be used.
22410 @method startRouting
22411 @private
22412 */
22413
22414
22415 startRouting() {
22416 var initialURL = (0, _metal.get)(this, 'initialURL');
22417
22418 if (this.setupRouter()) {
22419 if (initialURL === undefined) {
22420 initialURL = (0, _metal.get)(this, 'location').getURL();
22421 }
22422
22423 var initialTransition = this.handleURL(initialURL);
22424
22425 if (initialTransition && initialTransition.error) {
22426 throw initialTransition.error;
22427 }
22428 }
22429 }
22430
22431 setupRouter() {
22432 this._setupLocation();
22433
22434 var location = (0, _metal.get)(this, 'location'); // Allow the Location class to cancel the router setup while it refreshes
22435 // the page
22436
22437 if ((0, _metal.get)(location, 'cancelRouterSetup')) {
22438 return false;
22439 }
22440
22441 this._initRouterJs();
22442
22443 location.onUpdateURL(url => {
22444 this.handleURL(url);
22445 });
22446 return true;
22447 }
22448
22449 _setOutlets() {
22450 // This is triggered async during Route#willDestroy.
22451 // If the router is also being destroyed we do not want to
22452 // to create another this._toplevelView (and leak the renderer)
22453 if (this.isDestroying || this.isDestroyed) {
22454 return;
22455 }
22456
22457 var routeInfos = this._routerMicrolib.currentRouteInfos;
22458
22459 if (!routeInfos) {
22460 return;
22461 }
22462
22463 var defaultParentState;
22464 var liveRoutes = null;
22465
22466 for (var i = 0; i < routeInfos.length; i++) {
22467 var route = routeInfos[i].route;
22468
22469 var connections = _route.ROUTE_CONNECTIONS.get(route);
22470
22471 var ownState = void 0;
22472
22473 if (connections.length === 0) {
22474 ownState = representEmptyRoute(liveRoutes, defaultParentState, route);
22475 } else {
22476 for (var j = 0; j < connections.length; j++) {
22477 var appended = appendLiveRoute(liveRoutes, defaultParentState, connections[j]);
22478 liveRoutes = appended.liveRoutes;
22479 var {
22480 name,
22481 outlet
22482 } = appended.ownState.render;
22483
22484 if (name === route.routeName || outlet === 'main') {
22485 ownState = appended.ownState;
22486 }
22487 }
22488 }
22489
22490 defaultParentState = ownState;
22491 } // when a transitionTo happens after the validation phase
22492 // during the initial transition _setOutlets is called
22493 // when no routes are active. However, it will get called
22494 // again with the correct values during the next turn of
22495 // the runloop
22496
22497
22498 if (!liveRoutes) {
22499 return;
22500 }
22501
22502 if (!this._toplevelView) {
22503 var owner = (0, _owner.getOwner)(this);
22504 var OutletView = owner.factoryFor('view:-outlet');
22505 this._toplevelView = OutletView.create();
22506
22507 this._toplevelView.setOutletState(liveRoutes);
22508
22509 var instance = owner.lookup('-application-instance:main');
22510 instance.didCreateRootView(this._toplevelView);
22511 } else {
22512 this._toplevelView.setOutletState(liveRoutes);
22513 }
22514 }
22515
22516 handleURL(url) {
22517 // Until we have an ember-idiomatic way of accessing #hashes, we need to
22518 // remove it because router.js doesn't know how to handle it.
22519 var _url = url.split(/#(.+)?/)[0];
22520 return this._doURLTransition('handleURL', _url);
22521 }
22522
22523 _doURLTransition(routerJsMethod, url) {
22524 var transition = this._routerMicrolib[routerJsMethod](url || '/');
22525
22526 didBeginTransition(transition, this);
22527 return transition;
22528 }
22529 /**
22530 Transition the application into another route. The route may
22531 be either a single route or route path:
22532 See [transitionTo](/ember/release/classes/Route/methods/transitionTo?anchor=transitionTo) for more info.
22533 @method transitionTo
22534 @param {String} name the name of the route or a URL
22535 @param {...Object} models the model(s) or identifier(s) to be used while
22536 transitioning to the route.
22537 @param {Object} [options] optional hash with a queryParams property
22538 containing a mapping of query parameters
22539 @return {Transition} the transition object associated with this
22540 attempted transition
22541 @public
22542 */
22543
22544
22545 transitionTo(...args) {
22546 if ((0, _utils.resemblesURL)(args[0])) {
22547 (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));
22548 return this._doURLTransition('transitionTo', args[0]);
22549 }
22550
22551 var {
22552 routeName,
22553 models,
22554 queryParams
22555 } = (0, _utils.extractRouteArgs)(args);
22556 (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));
22557 return this._doTransition(routeName, models, queryParams);
22558 }
22559
22560 intermediateTransitionTo(name, ...args) {
22561 this._routerMicrolib.intermediateTransitionTo(name, ...args);
22562
22563 updatePaths(this);
22564
22565 if (true
22566 /* DEBUG */
22567 ) {
22568 var infos = this._routerMicrolib.currentRouteInfos;
22569
22570 if ((0, _metal.get)(this, 'namespace').LOG_TRANSITIONS) {
22571 // eslint-disable-next-line no-console
22572 console.log(`Intermediate-transitioned into '${EmberRouter._routePath(infos)}'`);
22573 }
22574 }
22575 }
22576
22577 replaceWith(...args) {
22578 return this.transitionTo(...args).method('replace');
22579 }
22580
22581 generate(name, ...args) {
22582 var url = this._routerMicrolib.generate(name, ...args);
22583
22584 return this.location.formatURL(url);
22585 }
22586 /**
22587 Determines if the supplied route is currently active.
22588 @method isActive
22589 @param routeName
22590 @return {Boolean}
22591 @private
22592 */
22593
22594
22595 isActive(routeName) {
22596 return this._routerMicrolib.isActive(routeName);
22597 }
22598 /**
22599 An alternative form of `isActive` that doesn't require
22600 manual concatenation of the arguments into a single
22601 array.
22602 @method isActiveIntent
22603 @param routeName
22604 @param models
22605 @param queryParams
22606 @return {Boolean}
22607 @private
22608 @since 1.7.0
22609 */
22610
22611
22612 isActiveIntent(routeName, models, queryParams) {
22613 return this.currentState.isActiveIntent(routeName, models, queryParams);
22614 }
22615
22616 send(name, ...args) {
22617 /*name, context*/
22618 this._routerMicrolib.trigger(name, ...args);
22619 }
22620 /**
22621 Does this router instance have the given route.
22622 @method hasRoute
22623 @return {Boolean}
22624 @private
22625 */
22626
22627
22628 hasRoute(route) {
22629 return this._routerMicrolib.hasRoute(route);
22630 }
22631 /**
22632 Resets the state of the router by clearing the current route
22633 handlers and deactivating them.
22634 @private
22635 @method reset
22636 */
22637
22638
22639 reset() {
22640 if (this._routerMicrolib) {
22641 this._routerMicrolib.reset();
22642 }
22643 }
22644
22645 willDestroy() {
22646 if (this._toplevelView) {
22647 this._toplevelView.destroy();
22648
22649 this._toplevelView = null;
22650 }
22651
22652 this._super(...arguments);
22653
22654 this.reset();
22655 var instances = this._engineInstances;
22656
22657 for (var name in instances) {
22658 for (var id in instances[name]) {
22659 (0, _runloop.run)(instances[name][id], 'destroy');
22660 }
22661 }
22662 }
22663 /*
22664 Called when an active route's query parameter has changed.
22665 These changes are batched into a runloop run and trigger
22666 a single transition.
22667 */
22668
22669
22670 _activeQPChanged(queryParameterName, newValue) {
22671 this._queuedQPChanges[queryParameterName] = newValue;
22672 (0, _runloop.once)(this, this._fireQueryParamTransition);
22673 }
22674
22675 _updatingQPChanged(queryParameterName) {
22676 this._qpUpdates.add(queryParameterName);
22677 }
22678 /*
22679 Triggers a transition to a route based on query parameter changes.
22680 This is called once per runloop, to batch changes.
22681 e.g.
22682 if these methods are called in succession:
22683 this._activeQPChanged('foo', '10');
22684 // results in _queuedQPChanges = { foo: '10' }
22685 this._activeQPChanged('bar', false);
22686 // results in _queuedQPChanges = { foo: '10', bar: false }
22687 _queuedQPChanges will represent both of these changes
22688 and the transition using `transitionTo` will be triggered
22689 once.
22690 */
22691
22692
22693 _fireQueryParamTransition() {
22694 this.transitionTo({
22695 queryParams: this._queuedQPChanges
22696 });
22697
22698 this._resetQueuedQueryParameterChanges();
22699 }
22700
22701 _setupLocation() {
22702 var location = this.location;
22703 var rootURL = this.rootURL;
22704 var owner = (0, _owner.getOwner)(this);
22705
22706 if ('string' === typeof location && owner) {
22707 var resolvedLocation = owner.lookup(`location:${location}`);
22708
22709 if (resolvedLocation !== undefined) {
22710 location = (0, _metal.set)(this, 'location', resolvedLocation);
22711 } else {
22712 // Allow for deprecated registration of custom location API's
22713 var options = {
22714 implementation: location
22715 };
22716 location = (0, _metal.set)(this, 'location', _api.default.create(options));
22717 }
22718 }
22719
22720 if (location !== null && typeof location === 'object') {
22721 if (rootURL) {
22722 (0, _metal.set)(location, 'rootURL', rootURL);
22723 } // Allow the location to do any feature detection, such as AutoLocation
22724 // detecting history support. This gives it a chance to set its
22725 // `cancelRouterSetup` property which aborts routing.
22726
22727
22728 if (typeof location.detect === 'function') {
22729 location.detect();
22730 } // ensure that initState is called AFTER the rootURL is set on
22731 // the location instance
22732
22733
22734 if (typeof location.initState === 'function') {
22735 location.initState();
22736 }
22737 }
22738 }
22739 /**
22740 Serializes the given query params according to their QP meta information.
22741 @private
22742 @method _serializeQueryParams
22743 @param {Arrray<RouteInfo>} routeInfos
22744 @param {Object} queryParams
22745 @return {Void}
22746 */
22747
22748
22749 _serializeQueryParams(routeInfos, queryParams) {
22750 forEachQueryParam(this, routeInfos, queryParams, (key, value, qp) => {
22751 if (qp) {
22752 delete queryParams[key];
22753 queryParams[qp.urlKey] = qp.route.serializeQueryParam(value, qp.urlKey, qp.type);
22754 } else if (value === undefined) {
22755 return; // We don't serialize undefined values
22756 } else {
22757 queryParams[key] = this._serializeQueryParam(value, (0, _runtime.typeOf)(value));
22758 }
22759 });
22760 }
22761 /**
22762 Serializes the value of a query parameter based on a type
22763 @private
22764 @method _serializeQueryParam
22765 @param {Object} value
22766 @param {String} type
22767 */
22768
22769
22770 _serializeQueryParam(value, type) {
22771 if (value === null || value === undefined) {
22772 return value;
22773 } else if (type === 'array') {
22774 return JSON.stringify(value);
22775 }
22776
22777 return `${value}`;
22778 }
22779 /**
22780 Deserializes the given query params according to their QP meta information.
22781 @private
22782 @method _deserializeQueryParams
22783 @param {Array<RouteInfo>} routeInfos
22784 @param {Object} queryParams
22785 @return {Void}
22786 */
22787
22788
22789 _deserializeQueryParams(routeInfos, queryParams) {
22790 forEachQueryParam(this, routeInfos, queryParams, (key, value, qp) => {
22791 // If we don't have QP meta info for a given key, then we do nothing
22792 // because all values will be treated as strings
22793 if (qp) {
22794 delete queryParams[key];
22795 queryParams[qp.prop] = qp.route.deserializeQueryParam(value, qp.urlKey, qp.type);
22796 }
22797 });
22798 }
22799 /**
22800 Deserializes the value of a query parameter based on a default type
22801 @private
22802 @method _deserializeQueryParam
22803 @param {Object} value
22804 @param {String} defaultType
22805 */
22806
22807
22808 _deserializeQueryParam(value, defaultType) {
22809 if (value === null || value === undefined) {
22810 return value;
22811 } else if (defaultType === 'boolean') {
22812 return value === 'true';
22813 } else if (defaultType === 'number') {
22814 return Number(value).valueOf();
22815 } else if (defaultType === 'array') {
22816 return (0, _runtime.A)(JSON.parse(value));
22817 }
22818
22819 return value;
22820 }
22821 /**
22822 Removes (prunes) any query params with default values from the given QP
22823 object. Default values are determined from the QP meta information per key.
22824 @private
22825 @method _pruneDefaultQueryParamValues
22826 @param {Array<RouteInfo>} routeInfos
22827 @param {Object} queryParams
22828 @return {Void}
22829 */
22830
22831
22832 _pruneDefaultQueryParamValues(routeInfos, queryParams) {
22833 var qps = this._queryParamsFor(routeInfos);
22834
22835 for (var key in queryParams) {
22836 var qp = qps.map[key];
22837
22838 if (qp && qp.serializedDefaultValue === queryParams[key]) {
22839 delete queryParams[key];
22840 }
22841 }
22842 }
22843
22844 _doTransition(_targetRouteName, models, _queryParams, _keepDefaultQueryParamValues) {
22845 var targetRouteName = _targetRouteName || (0, _utils.getActiveTargetName)(this._routerMicrolib);
22846
22847 (true && !(Boolean(targetRouteName) && this._routerMicrolib.hasRoute(targetRouteName)) && (0, _debug.assert)(`The route ${targetRouteName} was not found`, Boolean(targetRouteName) && this._routerMicrolib.hasRoute(targetRouteName)));
22848 var queryParams = {};
22849
22850 this._processActiveTransitionQueryParams(targetRouteName, models, queryParams, _queryParams);
22851
22852 (0, _polyfills.assign)(queryParams, _queryParams);
22853
22854 this._prepareQueryParams(targetRouteName, models, queryParams, Boolean(_keepDefaultQueryParamValues));
22855
22856 var transition = this._routerMicrolib.transitionTo(targetRouteName, ...models, {
22857 queryParams
22858 });
22859
22860 didBeginTransition(transition, this);
22861 return transition;
22862 }
22863
22864 _processActiveTransitionQueryParams(targetRouteName, models, queryParams, _queryParams) {
22865 // merge in any queryParams from the active transition which could include
22866 // queryParams from the url on initial load.
22867 if (!this._routerMicrolib.activeTransition) {
22868 return;
22869 }
22870
22871 var unchangedQPs = {};
22872 var qpUpdates = this._qpUpdates;
22873 var params = this._routerMicrolib.activeTransition[_router_js.QUERY_PARAMS_SYMBOL];
22874
22875 for (var key in params) {
22876 if (!qpUpdates.has(key)) {
22877 unchangedQPs[key] = params[key];
22878 }
22879 } // We need to fully scope queryParams so that we can create one object
22880 // that represents both passed-in queryParams and ones that aren't changed
22881 // from the active transition.
22882
22883
22884 this._fullyScopeQueryParams(targetRouteName, models, _queryParams);
22885
22886 this._fullyScopeQueryParams(targetRouteName, models, unchangedQPs);
22887
22888 (0, _polyfills.assign)(queryParams, unchangedQPs);
22889 }
22890 /**
22891 Prepares the query params for a URL or Transition. Restores any undefined QP
22892 keys/values, serializes all values, and then prunes any default values.
22893 @private
22894 @method _prepareQueryParams
22895 @param {String} targetRouteName
22896 @param {Array<Object>} models
22897 @param {Object} queryParams
22898 @param {boolean} keepDefaultQueryParamValues
22899 @return {Void}
22900 */
22901
22902
22903 _prepareQueryParams(targetRouteName, models, queryParams, _fromRouterService) {
22904 var state = calculatePostTransitionState(this, targetRouteName, models);
22905
22906 this._hydrateUnsuppliedQueryParams(state, queryParams, Boolean(_fromRouterService));
22907
22908 this._serializeQueryParams(state.routeInfos, queryParams);
22909
22910 if (!_fromRouterService) {
22911 this._pruneDefaultQueryParamValues(state.routeInfos, queryParams);
22912 }
22913 }
22914 /**
22915 Returns the meta information for the query params of a given route. This
22916 will be overridden to allow support for lazy routes.
22917 @private
22918 @method _getQPMeta
22919 @param {RouteInfo} routeInfo
22920 @return {Object}
22921 */
22922
22923
22924 _getQPMeta(routeInfo) {
22925 var route = routeInfo.route;
22926 return route && (0, _metal.get)(route, '_qp');
22927 }
22928 /**
22929 Returns a merged query params meta object for a given set of routeInfos.
22930 Useful for knowing what query params are available for a given route hierarchy.
22931 @private
22932 @method _queryParamsFor
22933 @param {Array<RouteInfo>} routeInfos
22934 @return {Object}
22935 */
22936
22937
22938 _queryParamsFor(routeInfos) {
22939 var routeInfoLength = routeInfos.length;
22940 var leafRouteName = routeInfos[routeInfoLength - 1].name;
22941 var cached = this._qpCache[leafRouteName];
22942
22943 if (cached !== undefined) {
22944 return cached;
22945 }
22946
22947 var shouldCache = true;
22948 var map = {};
22949 var qps = [];
22950 var qpsByUrlKey = true
22951 /* DEBUG */
22952 ? {} : null;
22953 var qpMeta;
22954 var qp;
22955 var urlKey;
22956 var qpOther;
22957
22958 for (var i = 0; i < routeInfoLength; ++i) {
22959 qpMeta = this._getQPMeta(routeInfos[i]);
22960
22961 if (!qpMeta) {
22962 shouldCache = false;
22963 continue;
22964 } // Loop over each QP to make sure we don't have any collisions by urlKey
22965
22966
22967 for (var _i = 0; _i < qpMeta.qps.length; _i++) {
22968 qp = qpMeta.qps[_i];
22969
22970 if (true
22971 /* DEBUG */
22972 ) {
22973 urlKey = qp.urlKey;
22974 qpOther = qpsByUrlKey[urlKey];
22975
22976 if (qpOther && qpOther.controllerName !== qp.controllerName) {
22977 (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));
22978 }
22979
22980 qpsByUrlKey[urlKey] = qp;
22981 }
22982
22983 qps.push(qp);
22984 }
22985
22986 (0, _polyfills.assign)(map, qpMeta.map);
22987 }
22988
22989 var finalQPMeta = {
22990 qps,
22991 map
22992 };
22993
22994 if (shouldCache) {
22995 this._qpCache[leafRouteName] = finalQPMeta;
22996 }
22997
22998 return finalQPMeta;
22999 }
23000 /**
23001 Maps all query param keys to their fully scoped property name of the form
23002 `controllerName:propName`.
23003 @private
23004 @method _fullyScopeQueryParams
23005 @param {String} leafRouteName
23006 @param {Array<Object>} contexts
23007 @param {Object} queryParams
23008 @return {Void}
23009 */
23010
23011
23012 _fullyScopeQueryParams(leafRouteName, contexts, queryParams) {
23013 var state = calculatePostTransitionState(this, leafRouteName, contexts);
23014 var routeInfos = state.routeInfos;
23015 var qpMeta;
23016
23017 for (var i = 0, len = routeInfos.length; i < len; ++i) {
23018 qpMeta = this._getQPMeta(routeInfos[i]);
23019
23020 if (!qpMeta) {
23021 continue;
23022 }
23023
23024 var qp = void 0;
23025 var presentProp = void 0;
23026
23027 for (var j = 0, qpLen = qpMeta.qps.length; j < qpLen; ++j) {
23028 qp = qpMeta.qps[j];
23029 presentProp = qp.prop in queryParams && qp.prop || qp.scopedPropertyName in queryParams && qp.scopedPropertyName || qp.urlKey in queryParams && qp.urlKey;
23030
23031 if (presentProp) {
23032 if (presentProp !== qp.scopedPropertyName) {
23033 queryParams[qp.scopedPropertyName] = queryParams[presentProp];
23034 delete queryParams[presentProp];
23035 }
23036 }
23037 }
23038 }
23039 }
23040 /**
23041 Hydrates (adds/restores) any query params that have pre-existing values into
23042 the given queryParams hash. This is what allows query params to be "sticky"
23043 and restore their last known values for their scope.
23044 @private
23045 @method _hydrateUnsuppliedQueryParams
23046 @param {TransitionState} state
23047 @param {Object} queryParams
23048 @return {Void}
23049 */
23050
23051
23052 _hydrateUnsuppliedQueryParams(state, queryParams, _fromRouterService) {
23053 var routeInfos = state.routeInfos;
23054 var appCache = this._bucketCache;
23055 var qpMeta;
23056 var qp;
23057 var presentProp;
23058
23059 for (var i = 0; i < routeInfos.length; ++i) {
23060 qpMeta = this._getQPMeta(routeInfos[i]);
23061
23062 if (!qpMeta) {
23063 continue;
23064 }
23065
23066 for (var j = 0, qpLen = qpMeta.qps.length; j < qpLen; ++j) {
23067 qp = qpMeta.qps[j];
23068 presentProp = qp.prop in queryParams && qp.prop || qp.scopedPropertyName in queryParams && qp.scopedPropertyName || qp.urlKey in queryParams && qp.urlKey;
23069 (true && !(function () {
23070 if (qp.urlKey === presentProp || qp.scopedPropertyName === presentProp) {
23071 return true;
23072 }
23073
23074 if (_fromRouterService && presentProp !== false && qp.urlKey !== qp.prop) {
23075 // assumptions (mainly from current transitionTo_test):
23076 // - this is only supposed to be run when there is an alias to a query param and the alias is used to set the param
23077 // - when there is no alias: qp.urlKey == qp.prop
23078 return false;
23079 }
23080
23081 return true;
23082 }()) && (0, _debug.assert)(`You passed the \`${presentProp}\` query parameter during a transition into ${qp.route.routeName}, please update to ${qp.urlKey}`, function () {
23083 if (qp.urlKey === presentProp || qp.scopedPropertyName === presentProp) {
23084 return true;
23085 }
23086
23087 if (_fromRouterService && presentProp !== false && qp.urlKey !== qp.prop) {
23088 return false;
23089 }
23090
23091 return true;
23092 }()));
23093
23094 if (presentProp) {
23095 if (presentProp !== qp.scopedPropertyName) {
23096 queryParams[qp.scopedPropertyName] = queryParams[presentProp];
23097 delete queryParams[presentProp];
23098 }
23099 } else {
23100 var cacheKey = (0, _utils.calculateCacheKey)(qp.route.fullRouteName, qp.parts, state.params);
23101 queryParams[qp.scopedPropertyName] = appCache.lookup(cacheKey, qp.prop, qp.defaultValue);
23102 }
23103 }
23104 }
23105 }
23106
23107 _scheduleLoadingEvent(transition, originRoute) {
23108 this._cancelSlowTransitionTimer();
23109
23110 this._slowTransitionTimer = (0, _runloop.scheduleOnce)('routerTransitions', this, '_handleSlowTransition', transition, originRoute);
23111 }
23112
23113 _handleSlowTransition(transition, originRoute) {
23114 if (!this._routerMicrolib.activeTransition) {
23115 // Don't fire an event if we've since moved on from
23116 // the transition that put us in a loading state.
23117 return;
23118 }
23119
23120 var targetState = new _router_state.default(this, this._routerMicrolib, this._routerMicrolib.activeTransition[_router_js.STATE_SYMBOL]);
23121 this.set('targetState', targetState);
23122 transition.trigger(true, 'loading', transition, originRoute);
23123 }
23124
23125 _cancelSlowTransitionTimer() {
23126 if (this._slowTransitionTimer) {
23127 (0, _runloop.cancel)(this._slowTransitionTimer);
23128 }
23129
23130 this._slowTransitionTimer = null;
23131 } // These three helper functions are used to ensure errors aren't
23132 // re-raised if they're handled in a route's error action.
23133
23134
23135 _markErrorAsHandled(error) {
23136 this._handledErrors.add(error);
23137 }
23138
23139 _isErrorHandled(error) {
23140 return this._handledErrors.has(error);
23141 }
23142
23143 _clearHandledError(error) {
23144 this._handledErrors.delete(error);
23145 }
23146
23147 _getEngineInstance({
23148 name,
23149 instanceId,
23150 mountPoint
23151 }) {
23152 var engineInstances = this._engineInstances;
23153
23154 if (!engineInstances[name]) {
23155 engineInstances[name] = Object.create(null);
23156 }
23157
23158 var engineInstance = engineInstances[name][instanceId];
23159
23160 if (!engineInstance) {
23161 var owner = (0, _owner.getOwner)(this);
23162 (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}`)));
23163 engineInstance = owner.buildChildEngineInstance(name, {
23164 routable: true,
23165 mountPoint
23166 });
23167 engineInstance.boot();
23168 engineInstances[name][instanceId] = engineInstance;
23169 }
23170
23171 return engineInstance;
23172 }
23173
23174 }
23175 /*
23176 Helper function for iterating over routes in a set of routeInfos that are
23177 at or above the given origin route. Example: if `originRoute` === 'foo.bar'
23178 and the routeInfos given were for 'foo.bar.baz', then the given callback
23179 will be invoked with the routes for 'foo.bar', 'foo', and 'application'
23180 individually.
23181
23182 If the callback returns anything other than `true`, then iteration will stop.
23183
23184 @private
23185 @param {Route} originRoute
23186 @param {Array<RouteInfo>} routeInfos
23187 @param {Function} callback
23188 @return {Void}
23189 */
23190
23191
23192 function forEachRouteAbove(routeInfos, callback) {
23193 for (var i = routeInfos.length - 1; i >= 0; --i) {
23194 var routeInfo = routeInfos[i];
23195 var route = routeInfo.route; // routeInfo.handler being `undefined` generally means either:
23196 //
23197 // 1. an error occurred during creation of the route in question
23198 // 2. the route is across an async boundary (e.g. within an engine)
23199 //
23200 // In both of these cases, we cannot invoke the callback on that specific
23201 // route, because it just doesn't exist...
23202
23203 if (route === undefined) {
23204 continue;
23205 }
23206
23207 if (callback(route, routeInfo) !== true) {
23208 return;
23209 }
23210 }
23211 } // These get invoked when an action bubbles above ApplicationRoute
23212 // and are not meant to be overridable.
23213
23214
23215 var defaultActionHandlers = {
23216 willResolveModel(_routeInfos, transition, originRoute) {
23217 this._scheduleLoadingEvent(transition, originRoute);
23218 },
23219
23220 // Attempt to find an appropriate error route or substate to enter.
23221 error(routeInfos, error, transition) {
23222 var router = this;
23223 var routeInfoWithError = routeInfos[routeInfos.length - 1];
23224 forEachRouteAbove(routeInfos, (route, routeInfo) => {
23225 // We don't check the leaf most routeInfo since that would
23226 // technically be below where we're at in the route hierarchy.
23227 if (routeInfo !== routeInfoWithError) {
23228 // Check for the existence of an 'error' route.
23229 var errorRouteName = findRouteStateName(route, 'error');
23230
23231 if (errorRouteName) {
23232 router._markErrorAsHandled(error);
23233
23234 router.intermediateTransitionTo(errorRouteName, error);
23235 return false;
23236 }
23237 } // Check for an 'error' substate route
23238
23239
23240 var errorSubstateName = findRouteSubstateName(route, 'error');
23241
23242 if (errorSubstateName) {
23243 router._markErrorAsHandled(error);
23244
23245 router.intermediateTransitionTo(errorSubstateName, error);
23246 return false;
23247 }
23248
23249 return true;
23250 });
23251 logError(error, `Error while processing route: ${transition.targetName}`);
23252 },
23253
23254 // Attempt to find an appropriate loading route or substate to enter.
23255 loading(routeInfos, transition) {
23256 var router = this;
23257 var routeInfoWithSlowLoading = routeInfos[routeInfos.length - 1];
23258 forEachRouteAbove(routeInfos, (route, routeInfo) => {
23259 // We don't check the leaf most routeInfos since that would
23260 // technically be below where we're at in the route hierarchy.
23261 if (routeInfo !== routeInfoWithSlowLoading) {
23262 // Check for the existence of a 'loading' route.
23263 var loadingRouteName = findRouteStateName(route, 'loading');
23264
23265 if (loadingRouteName) {
23266 router.intermediateTransitionTo(loadingRouteName);
23267 return false;
23268 }
23269 } // Check for loading substate
23270
23271
23272 var loadingSubstateName = findRouteSubstateName(route, 'loading');
23273
23274 if (loadingSubstateName) {
23275 router.intermediateTransitionTo(loadingSubstateName);
23276 return false;
23277 } // Don't bubble above pivot route.
23278
23279
23280 return transition.pivotHandler !== route;
23281 });
23282 }
23283
23284 };
23285
23286 function logError(_error, initialMessage) {
23287 var errorArgs = [];
23288 var error;
23289
23290 if (_error && typeof _error === 'object' && typeof _error.errorThrown === 'object') {
23291 error = _error.errorThrown;
23292 } else {
23293 error = _error;
23294 }
23295
23296 if (initialMessage) {
23297 errorArgs.push(initialMessage);
23298 }
23299
23300 if (error) {
23301 if (error.message) {
23302 errorArgs.push(error.message);
23303 }
23304
23305 if (error.stack) {
23306 errorArgs.push(error.stack);
23307 }
23308
23309 if (typeof error === 'string') {
23310 errorArgs.push(error);
23311 }
23312 }
23313
23314 console.error(...errorArgs); //eslint-disable-line no-console
23315 }
23316 /**
23317 Finds the name of the substate route if it exists for the given route. A
23318 substate route is of the form `route_state`, such as `foo_loading`.
23319
23320 @private
23321 @param {Route} route
23322 @param {String} state
23323 @return {String}
23324 */
23325
23326
23327 function findRouteSubstateName(route, state) {
23328 var owner = (0, _owner.getOwner)(route);
23329 var {
23330 routeName,
23331 fullRouteName,
23332 _router: router
23333 } = route;
23334 var substateName = `${routeName}_${state}`;
23335 var substateNameFull = `${fullRouteName}_${state}`;
23336 return routeHasBeenDefined(owner, router, substateName, substateNameFull) ? substateNameFull : '';
23337 }
23338 /**
23339 Finds the name of the state route if it exists for the given route. A state
23340 route is of the form `route.state`, such as `foo.loading`. Properly Handles
23341 `application` named routes.
23342
23343 @private
23344 @param {Route} route
23345 @param {String} state
23346 @return {String}
23347 */
23348
23349
23350 function findRouteStateName(route, state) {
23351 var owner = (0, _owner.getOwner)(route);
23352 var {
23353 routeName,
23354 fullRouteName,
23355 _router: router
23356 } = route;
23357 var stateName = routeName === 'application' ? state : `${routeName}.${state}`;
23358 var stateNameFull = fullRouteName === 'application' ? state : `${fullRouteName}.${state}`;
23359 return routeHasBeenDefined(owner, router, stateName, stateNameFull) ? stateNameFull : '';
23360 }
23361 /**
23362 Determines whether or not a route has been defined by checking that the route
23363 is in the Router's map and the owner has a registration for that route.
23364
23365 @private
23366 @param {Owner} owner
23367 @param {Router} router
23368 @param {String} localName
23369 @param {String} fullName
23370 @return {Boolean}
23371 */
23372
23373
23374 function routeHasBeenDefined(owner, router, localName, fullName) {
23375 var routerHasRoute = router.hasRoute(fullName);
23376 var ownerHasRoute = owner.hasRegistration(`template:${localName}`) || owner.hasRegistration(`route:${localName}`);
23377 return routerHasRoute && ownerHasRoute;
23378 }
23379
23380 function triggerEvent(routeInfos, ignoreFailure, name, args) {
23381 if (!routeInfos) {
23382 if (ignoreFailure) {
23383 return;
23384 }
23385
23386 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.`);
23387 }
23388
23389 var eventWasHandled = false;
23390 var routeInfo, handler, actionHandler;
23391
23392 for (var i = routeInfos.length - 1; i >= 0; i--) {
23393 routeInfo = routeInfos[i];
23394 handler = routeInfo.route;
23395 actionHandler = handler && handler.actions && handler.actions[name];
23396
23397 if (actionHandler) {
23398 if (actionHandler.apply(handler, args) === true) {
23399 eventWasHandled = true;
23400 } else {
23401 // Should only hit here if a non-bubbling error action is triggered on a route.
23402 if (name === 'error') {
23403 handler._router._markErrorAsHandled(args[0]);
23404 }
23405
23406 return;
23407 }
23408 }
23409 }
23410
23411 var defaultHandler = defaultActionHandlers[name];
23412
23413 if (defaultHandler) {
23414 defaultHandler.apply(this, [routeInfos, ...args]);
23415 return;
23416 }
23417
23418 if (!eventWasHandled && !ignoreFailure) {
23419 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.`);
23420 }
23421 }
23422
23423 function calculatePostTransitionState(emberRouter, leafRouteName, contexts) {
23424 var state = emberRouter._routerMicrolib.applyIntent(leafRouteName, contexts);
23425
23426 var {
23427 routeInfos,
23428 params
23429 } = state;
23430
23431 for (var i = 0; i < routeInfos.length; ++i) {
23432 var routeInfo = routeInfos[i]; // If the routeInfo is not resolved, we serialize the context into params
23433
23434 if (!routeInfo.isResolved) {
23435 params[routeInfo.name] = routeInfo.serialize(routeInfo.context);
23436 } else {
23437 params[routeInfo.name] = routeInfo.params;
23438 }
23439 }
23440
23441 return state;
23442 }
23443
23444 function updatePaths(router) {
23445 var infos = router._routerMicrolib.currentRouteInfos;
23446
23447 if (infos.length === 0) {
23448 return;
23449 }
23450
23451 var path = EmberRouter._routePath(infos);
23452
23453 var currentRouteName = infos[infos.length - 1].name;
23454 var currentURL = router.get('location').getURL();
23455 (0, _metal.set)(router, 'currentPath', path);
23456 (0, _metal.set)(router, 'currentRouteName', currentRouteName);
23457 (0, _metal.set)(router, 'currentURL', currentURL);
23458 var appController = (0, _owner.getOwner)(router).lookup('controller:application');
23459
23460 if (!appController) {
23461 // appController might not exist when top-level loading/error
23462 // substates have been entered since ApplicationRoute hasn't
23463 // actually been entered at that point.
23464 return;
23465 }
23466
23467 if (_deprecatedFeatures.APP_CTRL_ROUTER_PROPS) {
23468 if (!('currentPath' in appController)) {
23469 Object.defineProperty(appController, 'currentPath', {
23470 get() {
23471 (true && !(false) && (0, _debug.deprecate)('Accessing `currentPath` on `controller:application` is deprecated, use the `currentPath` property on `service:router` instead.', false, {
23472 id: 'application-controller.router-properties',
23473 until: '4.0.0',
23474 url: 'https://emberjs.com/deprecations/v3.x#toc_application-controller-router-properties'
23475 }));
23476 return (0, _metal.get)(router, 'currentPath');
23477 }
23478
23479 });
23480 }
23481
23482 (0, _metal.notifyPropertyChange)(appController, 'currentPath');
23483
23484 if (!('currentRouteName' in appController)) {
23485 Object.defineProperty(appController, 'currentRouteName', {
23486 get() {
23487 (true && !(false) && (0, _debug.deprecate)('Accessing `currentRouteName` on `controller:application` is deprecated, use the `currentRouteName` property on `service:router` instead.', false, {
23488 id: 'application-controller.router-properties',
23489 until: '4.0.0',
23490 url: 'https://emberjs.com/deprecations/v3.x#toc_application-controller-router-properties'
23491 }));
23492 return (0, _metal.get)(router, 'currentRouteName');
23493 }
23494
23495 });
23496 }
23497
23498 (0, _metal.notifyPropertyChange)(appController, 'currentRouteName');
23499 }
23500 }
23501
23502 EmberRouter.reopenClass({
23503 /**
23504 The `Router.map` function allows you to define mappings from URLs to routes
23505 in your application. These mappings are defined within the
23506 supplied callback function using `this.route`.
23507 The first parameter is the name of the route which is used by default as the
23508 path name as well.
23509 The second parameter is the optional options hash. Available options are:
23510 * `path`: allows you to provide your own path as well as mark dynamic
23511 segments.
23512 * `resetNamespace`: false by default; when nesting routes, ember will
23513 combine the route names to form the fully-qualified route name, which is
23514 used with `{{link-to}}` or manually transitioning to routes. Setting
23515 `resetNamespace: true` will cause the route not to inherit from its
23516 parent route's names. This is handy for preventing extremely long route names.
23517 Keep in mind that the actual URL path behavior is still retained.
23518 The third parameter is a function, which can be used to nest routes.
23519 Nested routes, by default, will have the parent route tree's route name and
23520 path prepended to it's own.
23521 ```app/router.js
23522 Router.map(function(){
23523 this.route('post', { path: '/post/:post_id' }, function() {
23524 this.route('edit');
23525 this.route('comments', { resetNamespace: true }, function() {
23526 this.route('new');
23527 });
23528 });
23529 });
23530 ```
23531 @method map
23532 @param callback
23533 @public
23534 */
23535 map(callback) {
23536 if (!this.dslCallbacks) {
23537 this.dslCallbacks = [];
23538 this.reopenClass({
23539 dslCallbacks: this.dslCallbacks
23540 });
23541 }
23542
23543 this.dslCallbacks.push(callback);
23544 return this;
23545 },
23546
23547 _routePath(routeInfos) {
23548 var path = []; // We have to handle coalescing resource names that
23549 // are prefixed with their parent's names, e.g.
23550 // ['foo', 'foo.bar.baz'] => 'foo.bar.baz', not 'foo.foo.bar.baz'
23551
23552 function intersectionMatches(a1, a2) {
23553 for (var i = 0; i < a1.length; ++i) {
23554 if (a1[i] !== a2[i]) {
23555 return false;
23556 }
23557 }
23558
23559 return true;
23560 }
23561
23562 var name, nameParts, oldNameParts;
23563
23564 for (var i = 1; i < routeInfos.length; i++) {
23565 name = routeInfos[i].name;
23566 nameParts = name.split('.');
23567 oldNameParts = slice.call(path);
23568
23569 while (oldNameParts.length) {
23570 if (intersectionMatches(oldNameParts, nameParts)) {
23571 break;
23572 }
23573
23574 oldNameParts.shift();
23575 }
23576
23577 path.push(...nameParts.slice(oldNameParts.length));
23578 }
23579
23580 return path.join('.');
23581 }
23582
23583 });
23584
23585 function didBeginTransition(transition, router) {
23586 var routerState = new _router_state.default(router, router._routerMicrolib, transition[_router_js.STATE_SYMBOL]);
23587
23588 if (!router.currentState) {
23589 router.set('currentState', routerState);
23590 }
23591
23592 router.set('targetState', routerState);
23593 transition.promise = transition.catch(error => {
23594 if (router._isErrorHandled(error)) {
23595 router._clearHandledError(error);
23596 } else {
23597 throw error;
23598 }
23599 }, 'Transition Error');
23600 }
23601
23602 function forEachQueryParam(router, routeInfos, queryParams, callback) {
23603 var qpCache = router._queryParamsFor(routeInfos);
23604
23605 for (var key in queryParams) {
23606 if (!Object.prototype.hasOwnProperty.call(queryParams, key)) {
23607 continue;
23608 }
23609
23610 var value = queryParams[key];
23611 var qp = qpCache.map[key];
23612 callback(key, value, qp);
23613 }
23614 }
23615
23616 function findLiveRoute(liveRoutes, name) {
23617 if (!liveRoutes) {
23618 return;
23619 }
23620
23621 var stack = [liveRoutes];
23622
23623 while (stack.length > 0) {
23624 var test = stack.shift();
23625
23626 if (test.render.name === name) {
23627 return test;
23628 }
23629
23630 var outlets = test.outlets;
23631
23632 for (var outletName in outlets) {
23633 stack.push(outlets[outletName]);
23634 }
23635 }
23636
23637 return;
23638 }
23639
23640 function appendLiveRoute(liveRoutes, defaultParentState, renderOptions) {
23641 var ownState = {
23642 render: renderOptions,
23643 outlets: Object.create(null),
23644 wasUsed: false
23645 };
23646 var target;
23647
23648 if (renderOptions.into) {
23649 target = findLiveRoute(liveRoutes, renderOptions.into);
23650 } else {
23651 target = defaultParentState;
23652 }
23653
23654 if (target) {
23655 (0, _metal.set)(target.outlets, renderOptions.outlet, ownState);
23656 } else {
23657 liveRoutes = ownState;
23658 }
23659
23660 return {
23661 liveRoutes,
23662 ownState
23663 };
23664 }
23665
23666 function representEmptyRoute(liveRoutes, defaultParentState, {
23667 routeName
23668 }) {
23669 // the route didn't render anything
23670 var alreadyAppended = findLiveRoute(liveRoutes, routeName);
23671
23672 if (alreadyAppended) {
23673 // But some other route has already rendered our default
23674 // template, so that becomes the default target for any
23675 // children we may have.
23676 return alreadyAppended;
23677 } else {
23678 // Create an entry to represent our default template name,
23679 // just so other routes can target it and inherit its place
23680 // in the outlet hierarchy.
23681 defaultParentState.outlets.main = {
23682 render: {
23683 name: routeName,
23684 outlet: 'main'
23685 },
23686 outlets: {}
23687 };
23688 return defaultParentState;
23689 }
23690 }
23691
23692 EmberRouter.reopen(_runtime.Evented, {
23693 /**
23694 Handles updating the paths and notifying any listeners of the URL
23695 change.
23696 Triggers the router level `didTransition` hook.
23697 For example, to notify google analytics when the route changes,
23698 you could use this hook. (Note: requires also including GA scripts, etc.)
23699 ```javascript
23700 import config from './config/environment';
23701 import EmberRouter from '@ember/routing/router';
23702 import { inject as service } from '@ember/service';
23703 let Router = EmberRouter.extend({
23704 location: config.locationType,
23705 router: service(),
23706 didTransition: function() {
23707 this._super(...arguments);
23708 ga('send', 'pageview', {
23709 page: this.router.currentURL,
23710 title: this.router.currentRouteName,
23711 });
23712 }
23713 });
23714 ```
23715 @method didTransition
23716 @public
23717 @since 1.2.0
23718 */
23719 didTransition: defaultDidTransition,
23720
23721 /**
23722 Handles notifying any listeners of an impending URL
23723 change.
23724 Triggers the router level `willTransition` hook.
23725 @method willTransition
23726 @public
23727 @since 1.11.0
23728 */
23729 willTransition: defaultWillTransition,
23730
23731 /**
23732 Represents the URL of the root of the application, often '/'. This prefix is
23733 assumed on all routes defined on this router.
23734 @property rootURL
23735 @default '/'
23736 @public
23737 */
23738 rootURL: '/',
23739
23740 /**
23741 The `location` property determines the type of URL's that your
23742 application will use.
23743 The following location types are currently available:
23744 * `history` - use the browser's history API to make the URLs look just like any standard URL
23745 * `hash` - use `#` to separate the server part of the URL from the Ember part: `/blog/#/posts/new`
23746 * `none` - do not store the Ember URL in the actual browser URL (mainly used for testing)
23747 * `auto` - use the best option based on browser capabilities: `history` if possible, then `hash` if possible, otherwise `none`
23748 This value is defaulted to `auto` by the `locationType` setting of `/config/environment.js`
23749 @property location
23750 @default 'hash'
23751 @see {Location}
23752 @public
23753 */
23754 location: 'hash',
23755
23756 /**
23757 Represents the current URL.
23758 @property url
23759 @type {String}
23760 @private
23761 */
23762 url: (0, _metal.computed)(function () {
23763 var location = (0, _metal.get)(this, 'location');
23764
23765 if (typeof location === 'string') {
23766 return undefined;
23767 }
23768
23769 return location.getURL();
23770 })
23771 });
23772
23773 if (_deprecatedFeatures.ROUTER_EVENTS) {
23774 EmberRouter.reopen(_route.ROUTER_EVENT_DEPRECATIONS);
23775 }
23776
23777 var _default = EmberRouter;
23778 _exports.default = _default;
23779});
23780define("@ember/-internals/routing/lib/system/router_state", ["exports", "@ember/polyfills", "@ember/-internals/routing/lib/utils"], function (_exports, _polyfills, _utils) {
23781 "use strict";
23782
23783 Object.defineProperty(_exports, "__esModule", {
23784 value: true
23785 });
23786 _exports.default = void 0;
23787
23788 class RouterState {
23789 constructor(emberRouter, router, routerJsState) {
23790 this.emberRouter = emberRouter;
23791 this.router = router;
23792 this.routerJsState = routerJsState;
23793 }
23794
23795 isActiveIntent(routeName, models, queryParams, queryParamsMustMatch) {
23796 var state = this.routerJsState;
23797
23798 if (!this.router.isActiveIntent(routeName, models, undefined, state)) {
23799 return false;
23800 }
23801
23802 if (queryParamsMustMatch && Object.keys(queryParams).length > 0) {
23803 var visibleQueryParams = (0, _polyfills.assign)({}, queryParams);
23804
23805 this.emberRouter._prepareQueryParams(routeName, models, visibleQueryParams);
23806
23807 return (0, _utils.shallowEqual)(visibleQueryParams, state.queryParams);
23808 }
23809
23810 return true;
23811 }
23812
23813 }
23814
23815 _exports.default = RouterState;
23816});
23817define("@ember/-internals/routing/lib/system/transition", [], function () {
23818 "use strict";
23819 /**
23820 A Transition is a thennable (a promise-like object) that represents
23821 an attempt to transition to another route. It can be aborted, either
23822 explicitly via `abort` or by attempting another transition while a
23823 previous one is still underway. An aborted transition can also
23824 be `retry()`d later.
23825
23826 @class Transition
23827 @public
23828 */
23829
23830 /**
23831 The Transition's internal promise. Calling `.then` on this property
23832 is that same as calling `.then` on the Transition object itself, but
23833 this property is exposed for when you want to pass around a
23834 Transition's promise, but not the Transition object itself, since
23835 Transition object can be externally `abort`ed, while the promise
23836 cannot.
23837
23838 @property promise
23839 @type {Object}
23840 @public
23841 */
23842
23843 /**
23844 Custom state can be stored on a Transition's `data` object.
23845 This can be useful for decorating a Transition within an earlier
23846 hook and shared with a later hook. Properties set on `data` will
23847 be copied to new transitions generated by calling `retry` on this
23848 transition.
23849
23850 @property data
23851 @type {Object}
23852 @public
23853 */
23854
23855 /**
23856 A standard promise hook that resolves if the transition
23857 succeeds and rejects if it fails/redirects/aborts.
23858
23859 Forwards to the internal `promise` property which you can
23860 use in situations where you want to pass around a thennable,
23861 but not the Transition itself.
23862
23863 @method then
23864 @param {Function} onFulfilled
23865 @param {Function} onRejected
23866 @param {String} label optional string for labeling the promise.
23867 Useful for tooling.
23868 @return {Promise}
23869 @public
23870 */
23871
23872 /**
23873
23874 Forwards to the internal `promise` property which you can
23875 use in situations where you want to pass around a thennable,
23876 but not the Transition itself.
23877
23878 @method catch
23879 @param {Function} onRejection
23880 @param {String} label optional string for labeling the promise.
23881 Useful for tooling.
23882 @return {Promise}
23883 @public
23884 */
23885
23886 /**
23887
23888 Forwards to the internal `promise` property which you can
23889 use in situations where you want to pass around a thennable,
23890 but not the Transition itself.
23891
23892 @method finally
23893 @param {Function} callback
23894 @param {String} label optional string for labeling the promise.
23895 Useful for tooling.
23896 @return {Promise}
23897 @public
23898 */
23899
23900 /**
23901 Aborts the Transition. Note you can also implicitly abort a transition
23902 by initiating another transition while a previous one is underway.
23903
23904 @method abort
23905 @return {Transition} this transition
23906 @public
23907 */
23908
23909 /**
23910
23911 Retries a previously-aborted transition (making sure to abort the
23912 transition if it's still active). Returns a new transition that
23913 represents the new attempt to transition.
23914
23915 @method retry
23916 @return {Transition} new transition
23917 @public
23918 */
23919
23920 /**
23921
23922 Sets the URL-changing method to be employed at the end of a
23923 successful transition. By default, a new Transition will just
23924 use `updateURL`, but passing 'replace' to this method will
23925 cause the URL to update using 'replaceWith' instead. Omitting
23926 a parameter will disable the URL change, allowing for transitions
23927 that don't update the URL at completion (this is also used for
23928 handleURL, since the URL has already changed before the
23929 transition took place).
23930
23931 @method method
23932 @param {String} method the type of URL-changing method to use
23933 at the end of a transition. Accepted values are 'replace',
23934 falsy values, or any other non-falsy value (which is
23935 interpreted as an updateURL transition).
23936
23937 @return {Transition} this transition
23938 @public
23939 */
23940
23941 /**
23942
23943 Fires an event on the current list of resolved/resolving
23944 handlers within this transition. Useful for firing events
23945 on route hierarchies that haven't fully been entered yet.
23946
23947 Note: This method is also aliased as `send`
23948
23949 @method trigger
23950 @param {Boolean} [ignoreFailure=false] a boolean specifying whether unhandled events throw an error
23951 @param {String} name the name of the event to fire
23952 @public
23953 */
23954
23955 /**
23956 * This property is a `RouteInfo` object that represents
23957 * where the router is transitioning to. It's important
23958 * to note that a `RouteInfo` is a linked list and this
23959 * property represents the leafmost route.
23960 * @property {null|RouteInfo|RouteInfoWithAttributes} to
23961 * @public
23962 */
23963
23964 /**
23965 * This property is a `RouteInfo` object that represents
23966 * where transition originated from. It's important
23967 * to note that a `RouteInfo` is a linked list and this
23968 * property represents the head node of the list.
23969 * In the case of an initial render, `from` will be set to
23970 * `null`.
23971 * @property {null|RouteInfoWithAttributes} from
23972 * @public
23973 */
23974
23975 /**
23976 Transitions are aborted and their promises rejected
23977 when redirects occur; this method returns a promise
23978 that will follow any redirects that occur and fulfill
23979 with the value fulfilled by any redirecting transitions
23980 that occur.
23981
23982 @method followRedirects
23983 @return {Promise} a promise that fulfills with the same
23984 value that the final redirecting transition fulfills with
23985 @public
23986 */
23987});
23988define("@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) {
23989 "use strict";
23990
23991 Object.defineProperty(_exports, "__esModule", {
23992 value: true
23993 });
23994 _exports.extractRouteArgs = extractRouteArgs;
23995 _exports.getActiveTargetName = getActiveTargetName;
23996 _exports.stashParamNames = stashParamNames;
23997 _exports.calculateCacheKey = calculateCacheKey;
23998 _exports.normalizeControllerQueryParams = normalizeControllerQueryParams;
23999 _exports.resemblesURL = resemblesURL;
24000 _exports.prefixRouteNameArg = prefixRouteNameArg;
24001 _exports.shallowEqual = shallowEqual;
24002 var ALL_PERIODS_REGEX = /\./g;
24003
24004 function extractRouteArgs(args) {
24005 args = args.slice();
24006 var possibleQueryParams = args[args.length - 1];
24007 var queryParams;
24008
24009 if (possibleQueryParams && Object.prototype.hasOwnProperty.call(possibleQueryParams, 'queryParams')) {
24010 // SAFETY: this cast is safe because we have just checked whether
24011 // `possibleQueryParams` -- defined as the last item in args -- both exists
24012 // and has the property `queryParams`. If either of these invariants change,
24013 // ***this is unsafe and should be changed***.
24014 queryParams = args.pop().queryParams;
24015 } else {
24016 queryParams = {};
24017 } // UNSAFE: these are simply assumed as the existing behavior of the system.
24018 // However, this could break if upstream refactors change it, and the types
24019 // here would not be able to tell us; we would lie to everything downstream.
24020
24021
24022 var routeName = args.shift();
24023 var models = args;
24024 return {
24025 routeName,
24026 models,
24027 queryParams
24028 };
24029 }
24030
24031 function getActiveTargetName(router) {
24032 var routeInfos = router.activeTransition ? router.activeTransition[_router_js.STATE_SYMBOL].routeInfos : router.state.routeInfos;
24033 return routeInfos[routeInfos.length - 1].name;
24034 }
24035
24036 function stashParamNames(router, routeInfos) {
24037 if (routeInfos['_namesStashed']) {
24038 return;
24039 } // This helper exists because router.js/route-recognizer.js awkwardly
24040 // keeps separate a routeInfo's list of parameter names depending
24041 // on whether a URL transition or named transition is happening.
24042 // Hopefully we can remove this in the future.
24043
24044
24045 var targetRouteName = routeInfos[routeInfos.length - 1].name;
24046
24047 var recogHandlers = router._routerMicrolib.recognizer.handlersFor(targetRouteName);
24048
24049 var dynamicParent;
24050
24051 for (var i = 0; i < routeInfos.length; ++i) {
24052 var routeInfo = routeInfos[i];
24053 var names = recogHandlers[i].names;
24054
24055 if (names.length) {
24056 dynamicParent = routeInfo;
24057 }
24058
24059 routeInfo['_names'] = names;
24060 var route = routeInfo.route;
24061
24062 route._stashNames(routeInfo, dynamicParent);
24063 }
24064
24065 routeInfos['_namesStashed'] = true;
24066 }
24067
24068 function _calculateCacheValuePrefix(prefix, part) {
24069 // calculates the dot separated sections from prefix that are also
24070 // at the start of part - which gives us the route name
24071 // given : prefix = site.article.comments, part = site.article.id
24072 // - returns: site.article (use get(values[site.article], 'id') to get the dynamic part - used below)
24073 // given : prefix = site.article, part = site.article.id
24074 // - returns: site.article. (use get(values[site.article], 'id') to get the dynamic part - used below)
24075 var prefixParts = prefix.split('.');
24076 var currPrefix = '';
24077
24078 for (var i = 0; i < prefixParts.length; i++) {
24079 var currPart = prefixParts.slice(0, i + 1).join('.');
24080
24081 if (part.indexOf(currPart) !== 0) {
24082 break;
24083 }
24084
24085 currPrefix = currPart;
24086 }
24087
24088 return currPrefix;
24089 }
24090 /*
24091 Stolen from Controller
24092 */
24093
24094
24095 function calculateCacheKey(prefix, parts = [], values) {
24096 var suffixes = '';
24097
24098 for (var i = 0; i < parts.length; ++i) {
24099 var part = parts[i];
24100
24101 var cacheValuePrefix = _calculateCacheValuePrefix(prefix, part);
24102
24103 var value = void 0;
24104
24105 if (values) {
24106 if (cacheValuePrefix && cacheValuePrefix in values) {
24107 var partRemovedPrefix = part.indexOf(cacheValuePrefix) === 0 ? part.substr(cacheValuePrefix.length + 1) : part;
24108 value = (0, _metal.get)(values[cacheValuePrefix], partRemovedPrefix);
24109 } else {
24110 value = (0, _metal.get)(values, part);
24111 }
24112 }
24113
24114 suffixes += `::${part}:${value}`;
24115 }
24116
24117 return prefix + suffixes.replace(ALL_PERIODS_REGEX, '-');
24118 }
24119 /*
24120 Controller-defined query parameters can come in three shapes:
24121
24122 Array
24123 queryParams: ['foo', 'bar']
24124 Array of simple objects where value is an alias
24125 queryParams: [
24126 {
24127 'foo': 'rename_foo_to_this'
24128 },
24129 {
24130 'bar': 'call_bar_this_instead'
24131 }
24132 ]
24133 Array of fully defined objects
24134 queryParams: [
24135 {
24136 'foo': {
24137 as: 'rename_foo_to_this'
24138 },
24139 }
24140 {
24141 'bar': {
24142 as: 'call_bar_this_instead',
24143 scope: 'controller'
24144 }
24145 }
24146 ]
24147
24148 This helper normalizes all three possible styles into the
24149 'Array of fully defined objects' style.
24150 */
24151
24152
24153 function normalizeControllerQueryParams(queryParams) {
24154 var qpMap = {};
24155
24156 for (var i = 0; i < queryParams.length; ++i) {
24157 accumulateQueryParamDescriptors(queryParams[i], qpMap);
24158 }
24159
24160 return qpMap;
24161 }
24162
24163 function accumulateQueryParamDescriptors(_desc, accum) {
24164 var desc = _desc;
24165 var tmp;
24166
24167 if (typeof desc === 'string') {
24168 tmp = {};
24169 tmp[desc] = {
24170 as: null
24171 };
24172 desc = tmp;
24173 }
24174
24175 for (var key in desc) {
24176 if (!Object.prototype.hasOwnProperty.call(desc, key)) {
24177 return;
24178 }
24179
24180 var singleDesc = desc[key];
24181
24182 if (typeof singleDesc === 'string') {
24183 singleDesc = {
24184 as: singleDesc
24185 };
24186 }
24187
24188 tmp = accum[key] || {
24189 as: null,
24190 scope: 'model'
24191 };
24192 (0, _polyfills.assign)(tmp, singleDesc);
24193 accum[key] = tmp;
24194 }
24195 }
24196 /*
24197 Check if a routeName resembles a url instead
24198
24199 @private
24200 */
24201
24202
24203 function resemblesURL(str) {
24204 return typeof str === 'string' && (str === '' || str[0] === '/');
24205 }
24206 /*
24207 Returns an arguments array where the route name arg is prefixed based on the mount point
24208
24209 @private
24210 */
24211
24212
24213 function prefixRouteNameArg(route, args) {
24214 var routeName = args[0];
24215 var owner = (0, _owner.getOwner)(route);
24216 var prefix = owner.mountPoint; // only alter the routeName if it's actually referencing a route.
24217
24218 if (owner.routable && typeof routeName === 'string') {
24219 if (resemblesURL(routeName)) {
24220 throw new _error.default('Programmatic transitions by URL cannot be used within an Engine. Please use the route name instead.');
24221 } else {
24222 routeName = `${prefix}.${routeName}`;
24223 args[0] = routeName;
24224 }
24225 }
24226
24227 return args;
24228 }
24229
24230 function shallowEqual(a, b) {
24231 var k;
24232 var aCount = 0;
24233 var bCount = 0;
24234
24235 for (k in a) {
24236 if (Object.prototype.hasOwnProperty.call(a, k)) {
24237 if (a[k] !== b[k]) {
24238 return false;
24239 }
24240
24241 aCount++;
24242 }
24243 }
24244
24245 for (k in b) {
24246 if (Object.prototype.hasOwnProperty.call(b, k)) {
24247 bCount++;
24248 }
24249 }
24250
24251 return aCount === bCount;
24252 }
24253});
24254define("@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, _function) {
24255 "use strict";
24256
24257 Object.defineProperty(_exports, "__esModule", {
24258 value: true
24259 });
24260 Object.defineProperty(_exports, "Object", {
24261 enumerable: true,
24262 get: function () {
24263 return _object.default;
24264 }
24265 });
24266 Object.defineProperty(_exports, "FrameworkObject", {
24267 enumerable: true,
24268 get: function () {
24269 return _object.FrameworkObject;
24270 }
24271 });
24272 Object.defineProperty(_exports, "RegistryProxyMixin", {
24273 enumerable: true,
24274 get: function () {
24275 return _registry_proxy.default;
24276 }
24277 });
24278 Object.defineProperty(_exports, "ContainerProxyMixin", {
24279 enumerable: true,
24280 get: function () {
24281 return _container_proxy.default;
24282 }
24283 });
24284 Object.defineProperty(_exports, "copy", {
24285 enumerable: true,
24286 get: function () {
24287 return _copy.default;
24288 }
24289 });
24290 Object.defineProperty(_exports, "compare", {
24291 enumerable: true,
24292 get: function () {
24293 return _compare.default;
24294 }
24295 });
24296 Object.defineProperty(_exports, "isEqual", {
24297 enumerable: true,
24298 get: function () {
24299 return _isEqual.default;
24300 }
24301 });
24302 Object.defineProperty(_exports, "Array", {
24303 enumerable: true,
24304 get: function () {
24305 return _array.default;
24306 }
24307 });
24308 Object.defineProperty(_exports, "NativeArray", {
24309 enumerable: true,
24310 get: function () {
24311 return _array.NativeArray;
24312 }
24313 });
24314 Object.defineProperty(_exports, "A", {
24315 enumerable: true,
24316 get: function () {
24317 return _array.A;
24318 }
24319 });
24320 Object.defineProperty(_exports, "MutableArray", {
24321 enumerable: true,
24322 get: function () {
24323 return _array.MutableArray;
24324 }
24325 });
24326 Object.defineProperty(_exports, "removeAt", {
24327 enumerable: true,
24328 get: function () {
24329 return _array.removeAt;
24330 }
24331 });
24332 Object.defineProperty(_exports, "uniqBy", {
24333 enumerable: true,
24334 get: function () {
24335 return _array.uniqBy;
24336 }
24337 });
24338 Object.defineProperty(_exports, "isArray", {
24339 enumerable: true,
24340 get: function () {
24341 return _array.isArray;
24342 }
24343 });
24344 Object.defineProperty(_exports, "Comparable", {
24345 enumerable: true,
24346 get: function () {
24347 return _comparable.default;
24348 }
24349 });
24350 Object.defineProperty(_exports, "Namespace", {
24351 enumerable: true,
24352 get: function () {
24353 return _namespace.default;
24354 }
24355 });
24356 Object.defineProperty(_exports, "ArrayProxy", {
24357 enumerable: true,
24358 get: function () {
24359 return _array_proxy.default;
24360 }
24361 });
24362 Object.defineProperty(_exports, "ObjectProxy", {
24363 enumerable: true,
24364 get: function () {
24365 return _object_proxy.default;
24366 }
24367 });
24368 Object.defineProperty(_exports, "CoreObject", {
24369 enumerable: true,
24370 get: function () {
24371 return _core_object.default;
24372 }
24373 });
24374 Object.defineProperty(_exports, "ActionHandler", {
24375 enumerable: true,
24376 get: function () {
24377 return _action_handler.default;
24378 }
24379 });
24380 Object.defineProperty(_exports, "Copyable", {
24381 enumerable: true,
24382 get: function () {
24383 return _copyable.default;
24384 }
24385 });
24386 Object.defineProperty(_exports, "Enumerable", {
24387 enumerable: true,
24388 get: function () {
24389 return _enumerable.default;
24390 }
24391 });
24392 Object.defineProperty(_exports, "_ProxyMixin", {
24393 enumerable: true,
24394 get: function () {
24395 return _proxy.default;
24396 }
24397 });
24398 Object.defineProperty(_exports, "_contentFor", {
24399 enumerable: true,
24400 get: function () {
24401 return _proxy.contentFor;
24402 }
24403 });
24404 Object.defineProperty(_exports, "Observable", {
24405 enumerable: true,
24406 get: function () {
24407 return _observable.default;
24408 }
24409 });
24410 Object.defineProperty(_exports, "MutableEnumerable", {
24411 enumerable: true,
24412 get: function () {
24413 return _mutable_enumerable.default;
24414 }
24415 });
24416 Object.defineProperty(_exports, "TargetActionSupport", {
24417 enumerable: true,
24418 get: function () {
24419 return _target_action_support.default;
24420 }
24421 });
24422 Object.defineProperty(_exports, "Evented", {
24423 enumerable: true,
24424 get: function () {
24425 return _evented.default;
24426 }
24427 });
24428 Object.defineProperty(_exports, "PromiseProxyMixin", {
24429 enumerable: true,
24430 get: function () {
24431 return _promise_proxy.default;
24432 }
24433 });
24434 Object.defineProperty(_exports, "RSVP", {
24435 enumerable: true,
24436 get: function () {
24437 return _rsvp.default;
24438 }
24439 });
24440 Object.defineProperty(_exports, "onerrorDefault", {
24441 enumerable: true,
24442 get: function () {
24443 return _rsvp.onerrorDefault;
24444 }
24445 });
24446 Object.defineProperty(_exports, "typeOf", {
24447 enumerable: true,
24448 get: function () {
24449 return _typeOf.typeOf;
24450 }
24451 });
24452});
24453define("@ember/-internals/runtime/lib/compare", ["exports", "@ember/-internals/runtime/lib/type-of", "@ember/-internals/runtime/lib/mixins/comparable"], function (_exports, _typeOf, _comparable) {
24454 "use strict";
24455
24456 Object.defineProperty(_exports, "__esModule", {
24457 value: true
24458 });
24459 _exports.default = compare;
24460 var TYPE_ORDER = {
24461 undefined: 0,
24462 null: 1,
24463 boolean: 2,
24464 number: 3,
24465 string: 4,
24466 array: 5,
24467 object: 6,
24468 instance: 7,
24469 function: 8,
24470 class: 9,
24471 date: 10
24472 }; //
24473 // the spaceship operator
24474 //
24475 // `. ___
24476 // __,' __`. _..----....____
24477 // __...--.'``;. ,. ;``--..__ .' ,-._ _.-'
24478 // _..-''-------' `' `' `' O ``-''._ (,;') _,'
24479 // ,'________________ \`-._`-','
24480 // `._ ```````````------...___ '-.._'-:
24481 // ```--.._ ,. ````--...__\-.
24482 // `.--. `-` "INFINITY IS LESS ____ | |`
24483 // `. `. THAN BEYOND" ,'`````. ; ;`
24484 // `._`. __________ `. \'__/`
24485 // `-:._____/______/___/____`. \ `
24486 // | `._ `. \
24487 // `._________`-. `. `.___
24488 // SSt `------'`
24489
24490 function spaceship(a, b) {
24491 var diff = a - b;
24492 return (diff > 0) - (diff < 0);
24493 }
24494 /**
24495 @module @ember/utils
24496 */
24497
24498 /**
24499 Compares two javascript values and returns:
24500
24501 - -1 if the first is smaller than the second,
24502 - 0 if both are equal,
24503 - 1 if the first is greater than the second.
24504
24505 ```javascript
24506 import { compare } from '@ember/utils';
24507
24508 compare('hello', 'hello'); // 0
24509 compare('abc', 'dfg'); // -1
24510 compare(2, 1); // 1
24511 ```
24512
24513 If the types of the two objects are different precedence occurs in the
24514 following order, with types earlier in the list considered `<` types
24515 later in the list:
24516
24517 - undefined
24518 - null
24519 - boolean
24520 - number
24521 - string
24522 - array
24523 - object
24524 - instance
24525 - function
24526 - class
24527 - date
24528
24529 ```javascript
24530 import { compare } from '@ember/utils';
24531
24532 compare('hello', 50); // 1
24533 compare(50, 'hello'); // -1
24534 ```
24535
24536 @method compare
24537 @for @ember/utils
24538 @static
24539 @param {Object} v First value to compare
24540 @param {Object} w Second value to compare
24541 @return {Number} -1 if v < w, 0 if v = w and 1 if v > w.
24542 @public
24543 */
24544
24545
24546 function compare(v, w) {
24547 if (v === w) {
24548 return 0;
24549 }
24550
24551 var type1 = (0, _typeOf.typeOf)(v);
24552 var type2 = (0, _typeOf.typeOf)(w);
24553
24554 if (type1 === 'instance' && _comparable.default.detect(v) && v.constructor.compare) {
24555 return v.constructor.compare(v, w);
24556 }
24557
24558 if (type2 === 'instance' && _comparable.default.detect(w) && w.constructor.compare) {
24559 return w.constructor.compare(w, v) * -1;
24560 }
24561
24562 var res = spaceship(TYPE_ORDER[type1], TYPE_ORDER[type2]);
24563
24564 if (res !== 0) {
24565 return res;
24566 } // types are equal - so we have to check values now
24567
24568
24569 switch (type1) {
24570 case 'boolean':
24571 case 'number':
24572 return spaceship(v, w);
24573
24574 case 'string':
24575 return spaceship(v.localeCompare(w), 0);
24576
24577 case 'array':
24578 {
24579 var vLen = v.length;
24580 var wLen = w.length;
24581 var len = Math.min(vLen, wLen);
24582
24583 for (var i = 0; i < len; i++) {
24584 var r = compare(v[i], w[i]);
24585
24586 if (r !== 0) {
24587 return r;
24588 }
24589 } // all elements are equal now
24590 // shorter array should be ordered first
24591
24592
24593 return spaceship(vLen, wLen);
24594 }
24595
24596 case 'instance':
24597 if (_comparable.default.detect(v)) {
24598 return v.compare(v, w);
24599 }
24600
24601 return 0;
24602
24603 case 'date':
24604 return spaceship(v.getTime(), w.getTime());
24605
24606 default:
24607 return 0;
24608 }
24609 }
24610});
24611define("@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) {
24612 "use strict";
24613
24614 Object.defineProperty(_exports, "__esModule", {
24615 value: true
24616 });
24617 _exports.default = copy;
24618
24619 /**
24620 @module @ember/object
24621 */
24622 function _copy(obj, deep, seen, copies) {
24623 // primitive data types are immutable, just return them.
24624 if (typeof obj !== 'object' || obj === null) {
24625 return obj;
24626 }
24627
24628 var ret, loc; // avoid cyclical loops
24629
24630 if (deep && (loc = seen.indexOf(obj)) >= 0) {
24631 return copies[loc];
24632 }
24633
24634 if (deep) {
24635 seen.push(obj);
24636 } // IMPORTANT: this specific test will detect a native array only. Any other
24637 // object will need to implement Copyable.
24638
24639
24640 if (Array.isArray(obj)) {
24641 ret = obj.slice();
24642
24643 if (deep) {
24644 copies.push(ret);
24645 loc = ret.length;
24646
24647 while (--loc >= 0) {
24648 ret[loc] = _copy(ret[loc], deep, seen, copies);
24649 }
24650 }
24651 } else if (_copyable.default.detect(obj)) {
24652 ret = obj.copy(deep, seen, copies);
24653
24654 if (deep) {
24655 copies.push(ret);
24656 }
24657 } else if (obj instanceof Date) {
24658 ret = new Date(obj.getTime());
24659
24660 if (deep) {
24661 copies.push(ret);
24662 }
24663 } else {
24664 (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)));
24665 ret = {};
24666
24667 if (deep) {
24668 copies.push(ret);
24669 }
24670
24671 var key;
24672
24673 for (key in obj) {
24674 // support Null prototype
24675 if (!Object.prototype.hasOwnProperty.call(obj, key)) {
24676 continue;
24677 } // Prevents browsers that don't respect non-enumerability from
24678 // copying internal Ember properties
24679
24680
24681 if (key.substring(0, 2) === '__') {
24682 continue;
24683 }
24684
24685 ret[key] = deep ? _copy(obj[key], deep, seen, copies) : obj[key];
24686 }
24687 }
24688
24689 return ret;
24690 }
24691 /**
24692 Creates a shallow copy of the passed object. A deep copy of the object is
24693 returned if the optional `deep` argument is `true`.
24694
24695 If the passed object implements the `Copyable` interface, then this
24696 function will delegate to the object's `copy()` method and return the
24697 result. See `Copyable` for further details.
24698
24699 For primitive values (which are immutable in JavaScript), the passed object
24700 is simply returned.
24701
24702 @method copy
24703 @deprecated Use 'ember-copy' addon instead
24704 @static
24705 @for @ember/object/internals
24706 @param {Object} obj The object to clone
24707 @param {Boolean} [deep=false] If true, a deep copy of the object is made.
24708 @return {Object} The copied object
24709 @public
24710 */
24711
24712
24713 function copy(obj, deep) {
24714 (true && !(false) && (0, _debug.deprecate)('Use ember-copy addon instead of copy method and Copyable mixin.', false, {
24715 id: 'ember-runtime.deprecate-copy-copyable',
24716 until: '4.0.0',
24717 url: 'https://emberjs.com/deprecations/v3.x/#toc_ember-runtime-deprecate-copy-copyable'
24718 })); // fast paths
24719
24720 if ('object' !== typeof obj || obj === null) {
24721 return obj; // can't copy primitives
24722 }
24723
24724 if (!Array.isArray(obj) && _copyable.default.detect(obj)) {
24725 return obj.copy(deep);
24726 }
24727
24728 return _copy(obj, deep, deep ? [] : null, deep ? [] : null);
24729 }
24730});
24731define("@ember/-internals/runtime/lib/ext/function", ["@ember/-internals/environment", "@ember/-internals/metal", "@ember/debug", "@ember/deprecated-features"], function (_environment, _metal, _debug, _deprecatedFeatures) {
24732 "use strict";
24733
24734 /**
24735 @module ember
24736 */
24737 if (_deprecatedFeatures.FUNCTION_PROTOTYPE_EXTENSIONS && _environment.ENV.EXTEND_PROTOTYPES.Function) {
24738 Object.defineProperties(Function.prototype, {
24739 /**
24740 The `property` extension of Javascript's Function prototype is available
24741 when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is
24742 `true`, which is the default.
24743 Computed properties allow you to treat a function like a property:
24744 ```app/utils/president.js
24745 import EmberObject from '@ember/object';
24746 export default EmberObject.extend({
24747 firstName: '',
24748 lastName: '',
24749 fullName: function() {
24750 return this.get('firstName') + ' ' + this.get('lastName');
24751 }.property() // Call this flag to mark the function as a property
24752 });
24753 ```
24754 ```javascript
24755 let president = President.create({
24756 firstName: 'Barack',
24757 lastName: 'Obama'
24758 });
24759 president.get('fullName'); // 'Barack Obama'
24760 ```
24761 Treating a function like a property is useful because they can work with
24762 bindings, just like any other property.
24763 Many computed properties have dependencies on other properties. For
24764 example, in the above example, the `fullName` property depends on
24765 `firstName` and `lastName` to determine its value. You can tell Ember
24766 about these dependencies like this:
24767 ```app/utils/president.js
24768 import EmberObject from '@ember/object';
24769 export default EmberObject.extend({
24770 firstName: '',
24771 lastName: '',
24772 fullName: function() {
24773 return this.get('firstName') + ' ' + this.get('lastName');
24774 // Tell Ember.js that this computed property depends on firstName
24775 // and lastName
24776 }.property('firstName', 'lastName')
24777 });
24778 ```
24779 Make sure you list these dependencies so Ember knows when to update
24780 bindings that connect to a computed property. Changing a dependency
24781 will not immediately trigger an update of the computed property, but
24782 will instead clear the cache so that it is updated when the next `get`
24783 is called on the property.
24784 See [ComputedProperty](/ember/release/classes/ComputedProperty), [@ember/object/computed](/ember/release/classes/@ember%2Fobject%2Fcomputed).
24785 @method property
24786 @for Function
24787 @public
24788 */
24789 property: {
24790 configurable: true,
24791 enumerable: false,
24792 writable: true,
24793 value: function () {
24794 (true && !(false) && (0, _debug.deprecate)(`Function prototype extensions have been deprecated, please migrate from function(){}.property('bar') to computed('bar', function() {}).`, false, {
24795 id: 'function-prototype-extensions.property',
24796 until: '4.0.0',
24797 url: 'https://deprecations.emberjs.com/v3.x#toc_function-prototype-extensions-property'
24798 }));
24799 return (0, _metal.computed)(...arguments, this);
24800 }
24801 },
24802
24803 /**
24804 The `observes` extension of Javascript's Function prototype is available
24805 when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is
24806 true, which is the default.
24807 You can observe property changes simply by adding the `observes`
24808 call to the end of your method declarations in classes that you write.
24809 For example:
24810 ```javascript
24811 import EmberObject from '@ember/object';
24812 EmberObject.extend({
24813 valueObserver: function() {
24814 // Executes whenever the "value" property changes
24815 }.observes('value')
24816 });
24817 ```
24818 In the future this method may become asynchronous.
24819 See `observer`.
24820 @method observes
24821 @for Function
24822 @public
24823 */
24824 observes: {
24825 configurable: true,
24826 enumerable: false,
24827 writable: true,
24828 value: function () {
24829 (true && !(false) && (0, _debug.deprecate)(`Function prototype extensions have been deprecated, please migrate from function(){}.observes('foo') to observer('foo', function() {}).`, false, {
24830 id: 'function-prototype-extensions.observes',
24831 until: '4.0.0',
24832 url: 'https://deprecations.emberjs.com/v3.x#toc_function-prototype-extensions-observes'
24833 }));
24834 return (0, _metal.observer)(...arguments, this);
24835 }
24836 },
24837
24838 /**
24839 The `on` extension of Javascript's Function prototype is available
24840 when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is
24841 true, which is the default.
24842 You can listen for events simply by adding the `on` call to the end of
24843 your method declarations in classes or mixins that you write. For example:
24844 ```javascript
24845 import Mixin from '@ember/mixin';
24846 Mixin.create({
24847 doSomethingWithElement: function() {
24848 // Executes whenever the "didInsertElement" event fires
24849 }.on('didInsertElement')
24850 });
24851 ```
24852 See `@ember/object/evented/on`.
24853 @method on
24854 @for Function
24855 @public
24856 */
24857 on: {
24858 configurable: true,
24859 enumerable: false,
24860 writable: true,
24861 value: function () {
24862 (true && !(false) && (0, _debug.deprecate)(`Function prototype extensions have been deprecated, please migrate from function(){}.on('foo') to on('foo', function() {}).`, false, {
24863 id: 'function-prototype-extensions.on',
24864 until: '4.0.0',
24865 url: 'https://deprecations.emberjs.com/v3.x#toc_function-prototype-extensions-on'
24866 }));
24867 return (0, _metal.on)(...arguments, this);
24868 }
24869 }
24870 });
24871 }
24872});
24873define("@ember/-internals/runtime/lib/ext/rsvp", ["exports", "rsvp", "@ember/runloop", "@ember/-internals/error-handling", "@ember/debug"], function (_exports, RSVP, _runloop, _errorHandling, _debug) {
24874 "use strict";
24875
24876 Object.defineProperty(_exports, "__esModule", {
24877 value: true
24878 });
24879 _exports.onerrorDefault = onerrorDefault;
24880 _exports.default = void 0;
24881 RSVP.configure('async', (callback, promise) => {
24882 _runloop.backburner.schedule('actions', null, callback, promise);
24883 });
24884 RSVP.configure('after', cb => {
24885 _runloop.backburner.schedule(_runloop._rsvpErrorQueue, null, cb);
24886 });
24887 RSVP.on('error', onerrorDefault);
24888
24889 function onerrorDefault(reason) {
24890 var error = errorFor(reason);
24891
24892 if (error) {
24893 var overrideDispatch = (0, _errorHandling.getDispatchOverride)();
24894
24895 if (overrideDispatch) {
24896 overrideDispatch(error);
24897 } else {
24898 throw error;
24899 }
24900 }
24901 }
24902
24903 function errorFor(reason) {
24904 if (!reason) return;
24905
24906 if (reason.errorThrown) {
24907 return unwrapErrorThrown(reason);
24908 }
24909
24910 if (reason.name === 'UnrecognizedURLError') {
24911 (true && !(false) && (0, _debug.assert)(`The URL '${reason.message}' did not match any routes in your application`, false));
24912 return;
24913 }
24914
24915 if (reason.name === 'TransitionAborted') {
24916 return;
24917 }
24918
24919 return reason;
24920 }
24921
24922 function unwrapErrorThrown(reason) {
24923 var error = reason.errorThrown;
24924
24925 if (typeof error === 'string') {
24926 error = new Error(error);
24927 }
24928
24929 Object.defineProperty(error, '__reason_with_error_thrown__', {
24930 value: reason,
24931 enumerable: false
24932 });
24933 return error;
24934 }
24935
24936 var _default = RSVP;
24937 _exports.default = _default;
24938});
24939define("@ember/-internals/runtime/lib/is-equal", ["exports"], function (_exports) {
24940 "use strict";
24941
24942 Object.defineProperty(_exports, "__esModule", {
24943 value: true
24944 });
24945 _exports.default = isEqual;
24946
24947 /**
24948 @module @ember/utils
24949 */
24950
24951 /**
24952 Compares two objects, returning true if they are equal.
24953
24954 ```javascript
24955 import { isEqual } from '@ember/utils';
24956
24957 isEqual('hello', 'hello'); // true
24958 isEqual(1, 2); // false
24959 ```
24960
24961 `isEqual` is a more specific comparison than a triple equal comparison.
24962 It will call the `isEqual` instance method on the objects being
24963 compared, allowing finer control over when objects should be considered
24964 equal to each other.
24965
24966 ```javascript
24967 import { isEqual } from '@ember/utils';
24968 import EmberObject from '@ember/object';
24969
24970 let Person = EmberObject.extend({
24971 isEqual(other) { return this.ssn == other.ssn; }
24972 });
24973
24974 let personA = Person.create({name: 'Muhammad Ali', ssn: '123-45-6789'});
24975 let personB = Person.create({name: 'Cassius Clay', ssn: '123-45-6789'});
24976
24977 isEqual(personA, personB); // true
24978 ```
24979
24980 Due to the expense of array comparisons, collections will never be equal to
24981 each other even if each of their items are equal to each other.
24982
24983 ```javascript
24984 import { isEqual } from '@ember/utils';
24985
24986 isEqual([4, 2], [4, 2]); // false
24987 ```
24988
24989 @method isEqual
24990 @for @ember/utils
24991 @static
24992 @param {Object} a first object to compare
24993 @param {Object} b second object to compare
24994 @return {Boolean}
24995 @public
24996 */
24997 function isEqual(a, b) {
24998 if (a && typeof a.isEqual === 'function') {
24999 return a.isEqual(b);
25000 }
25001
25002 if (a instanceof Date && b instanceof Date) {
25003 return a.getTime() === b.getTime();
25004 }
25005
25006 return a === b;
25007 }
25008});
25009define("@ember/-internals/runtime/lib/mixins/-proxy", ["exports", "@ember/-internals/meta", "@ember/-internals/metal", "@ember/-internals/utils", "@ember/debug", "@glimmer/validator"], function (_exports, _meta, _metal, _utils, _debug, _validator) {
25010 "use strict";
25011
25012 Object.defineProperty(_exports, "__esModule", {
25013 value: true
25014 });
25015 _exports.contentFor = contentFor;
25016 _exports.default = void 0;
25017
25018 /**
25019 @module ember
25020 */
25021 function contentFor(proxy) {
25022 var content = (0, _metal.get)(proxy, 'content');
25023 (0, _validator.updateTag)((0, _metal.tagForObject)(proxy), (0, _metal.tagForObject)(content));
25024 return content;
25025 }
25026 /**
25027 `Ember.ProxyMixin` forwards all properties not defined by the proxy itself
25028 to a proxied `content` object. See ObjectProxy for more details.
25029
25030 @class ProxyMixin
25031 @namespace Ember
25032 @private
25033 */
25034
25035
25036 var _default = _metal.Mixin.create({
25037 /**
25038 The object whose properties will be forwarded.
25039 @property content
25040 @type {unknown}
25041 @default null
25042 @public
25043 */
25044 content: null,
25045
25046 init() {
25047 this._super(...arguments);
25048
25049 (0, _utils.setProxy)(this);
25050 (0, _metal.tagForObject)(this);
25051 },
25052
25053 willDestroy() {
25054 this.set('content', null);
25055
25056 this._super(...arguments);
25057 },
25058
25059 isTruthy: (0, _metal.computed)('content', function () {
25060 return Boolean((0, _metal.get)(this, 'content'));
25061 }),
25062
25063 [_metal.CUSTOM_TAG_FOR](key, addMandatorySetter) {
25064 var meta = (0, _validator.tagMetaFor)(this);
25065 var tag = (0, _validator.tagFor)(this, key, meta);
25066
25067 if (true
25068 /* DEBUG */
25069 ) {
25070 // TODO: Replace this with something more first class for tracking tags in DEBUG
25071 tag._propertyKey = key;
25072 }
25073
25074 if (key in this) {
25075 if (true
25076 /* DEBUG */
25077 && addMandatorySetter) {
25078 (0, _utils.setupMandatorySetter)(tag, this, key);
25079 }
25080
25081 return tag;
25082 } else {
25083 var tags = [tag, (0, _validator.tagFor)(this, 'content', meta)];
25084 var content = contentFor(this);
25085
25086 if ((0, _utils.isObject)(content)) {
25087 tags.push((0, _metal.tagForProperty)(content, key, addMandatorySetter));
25088 }
25089
25090 return (0, _validator.combine)(tags);
25091 }
25092 },
25093
25094 unknownProperty(key) {
25095 var content = contentFor(this);
25096
25097 if (content) {
25098 return (0, _metal.get)(content, key);
25099 }
25100 },
25101
25102 setUnknownProperty(key, value) {
25103 var m = (0, _meta.meta)(this);
25104
25105 if (m.isInitializing() || m.isPrototypeMeta(this)) {
25106 // if marked as prototype or object is initializing then just
25107 // defineProperty rather than delegate
25108 (0, _metal.defineProperty)(this, key, null, value);
25109 return value;
25110 }
25111
25112 var content = contentFor(this);
25113 (true && !(content) && (0, _debug.assert)(`Cannot delegate set('${key}', ${value}) to the 'content' property of object proxy ${this}: its 'content' is undefined.`, content));
25114 return (0, _metal.set)(content, key, value);
25115 }
25116
25117 });
25118
25119 _exports.default = _default;
25120});
25121define("@ember/-internals/runtime/lib/mixins/action_handler", ["exports", "@ember/-internals/metal", "@ember/debug"], function (_exports, _metal, _debug) {
25122 "use strict";
25123
25124 Object.defineProperty(_exports, "__esModule", {
25125 value: true
25126 });
25127 _exports.default = void 0;
25128
25129 /**
25130 @module ember
25131 */
25132
25133 /**
25134 `Ember.ActionHandler` is available on some familiar classes including
25135 `Route`, `Component`, and `Controller`.
25136 (Internally the mixin is used by `Ember.CoreView`, `Ember.ControllerMixin`,
25137 and `Route` and available to the above classes through
25138 inheritance.)
25139
25140 @class ActionHandler
25141 @namespace Ember
25142 @private
25143 */
25144 var ActionHandler = _metal.Mixin.create({
25145 mergedProperties: ['actions'],
25146
25147 /**
25148 The collection of functions, keyed by name, available on this
25149 `ActionHandler` as action targets.
25150 These functions will be invoked when a matching `{{action}}` is triggered
25151 from within a template and the application's current route is this route.
25152 Actions can also be invoked from other parts of your application
25153 via `ActionHandler#send`.
25154 The `actions` hash will inherit action handlers from
25155 the `actions` hash defined on extended parent classes
25156 or mixins rather than just replace the entire hash, e.g.:
25157 ```app/mixins/can-display-banner.js
25158 import Mixin from '@ember/mixin';
25159 export default Mixin.create({
25160 actions: {
25161 displayBanner(msg) {
25162 // ...
25163 }
25164 }
25165 });
25166 ```
25167 ```app/routes/welcome.js
25168 import Route from '@ember/routing/route';
25169 import CanDisplayBanner from '../mixins/can-display-banner';
25170 export default Route.extend(CanDisplayBanner, {
25171 actions: {
25172 playMusic() {
25173 // ...
25174 }
25175 }
25176 });
25177 // `WelcomeRoute`, when active, will be able to respond
25178 // to both actions, since the actions hash is merged rather
25179 // then replaced when extending mixins / parent classes.
25180 this.send('displayBanner');
25181 this.send('playMusic');
25182 ```
25183 Within a Controller, Route or Component's action handler,
25184 the value of the `this` context is the Controller, Route or
25185 Component object:
25186 ```app/routes/song.js
25187 import Route from '@ember/routing/route';
25188 export default Route.extend({
25189 actions: {
25190 myAction() {
25191 this.controllerFor("song");
25192 this.transitionTo("other.route");
25193 ...
25194 }
25195 }
25196 });
25197 ```
25198 It is also possible to call `this._super(...arguments)` from within an
25199 action handler if it overrides a handler defined on a parent
25200 class or mixin:
25201 Take for example the following routes:
25202 ```app/mixins/debug-route.js
25203 import Mixin from '@ember/mixin';
25204 export default Mixin.create({
25205 actions: {
25206 debugRouteInformation() {
25207 console.debug("It's a-me, console.debug!");
25208 }
25209 }
25210 });
25211 ```
25212 ```app/routes/annoying-debug.js
25213 import Route from '@ember/routing/route';
25214 import DebugRoute from '../mixins/debug-route';
25215 export default Route.extend(DebugRoute, {
25216 actions: {
25217 debugRouteInformation() {
25218 // also call the debugRouteInformation of mixed in DebugRoute
25219 this._super(...arguments);
25220 // show additional annoyance
25221 window.alert(...);
25222 }
25223 }
25224 });
25225 ```
25226 ## Bubbling
25227 By default, an action will stop bubbling once a handler defined
25228 on the `actions` hash handles it. To continue bubbling the action,
25229 you must return `true` from the handler:
25230 ```app/router.js
25231 Router.map(function() {
25232 this.route("album", function() {
25233 this.route("song");
25234 });
25235 });
25236 ```
25237 ```app/routes/album.js
25238 import Route from '@ember/routing/route';
25239 export default Route.extend({
25240 actions: {
25241 startPlaying: function() {
25242 }
25243 }
25244 });
25245 ```
25246 ```app/routes/album-song.js
25247 import Route from '@ember/routing/route';
25248 export default Route.extend({
25249 actions: {
25250 startPlaying() {
25251 // ...
25252 if (actionShouldAlsoBeTriggeredOnParentRoute) {
25253 return true;
25254 }
25255 }
25256 }
25257 });
25258 ```
25259 @property actions
25260 @type Object
25261 @default null
25262 @public
25263 */
25264
25265 /**
25266 Triggers a named action on the `ActionHandler`. Any parameters
25267 supplied after the `actionName` string will be passed as arguments
25268 to the action target function.
25269 If the `ActionHandler` has its `target` property set, actions may
25270 bubble to the `target`. Bubbling happens when an `actionName` can
25271 not be found in the `ActionHandler`'s `actions` hash or if the
25272 action target function returns `true`.
25273 Example
25274 ```app/routes/welcome.js
25275 import Route from '@ember/routing/route';
25276 export default Route.extend({
25277 actions: {
25278 playTheme() {
25279 this.send('playMusic', 'theme.mp3');
25280 },
25281 playMusic(track) {
25282 // ...
25283 }
25284 }
25285 });
25286 ```
25287 @method send
25288 @param {String} actionName The action to trigger
25289 @param {*} context a context to send with the action
25290 @public
25291 */
25292 send(actionName, ...args) {
25293 (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));
25294
25295 if (this.actions && this.actions[actionName]) {
25296 var shouldBubble = this.actions[actionName].apply(this, args) === true;
25297
25298 if (!shouldBubble) {
25299 return;
25300 }
25301 }
25302
25303 var target = (0, _metal.get)(this, 'target');
25304
25305 if (target) {
25306 (true && !(typeof target.send === 'function') && (0, _debug.assert)(`The \`target\` for ${this} (${target}) does not have a \`send\` method`, typeof target.send === 'function'));
25307 target.send(...arguments);
25308 }
25309 }
25310
25311 });
25312
25313 var _default = ActionHandler;
25314 _exports.default = _default;
25315});
25316define("@ember/-internals/runtime/lib/mixins/array", ["exports", "@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/mixins/mutable_enumerable", "@ember/-internals/runtime/lib/type-of"], function (_exports, _metal, _utils, _debug, _enumerable, _compare, _environment, _observable, _mutable_enumerable, _typeOf) {
25317 "use strict";
25318
25319 Object.defineProperty(_exports, "__esModule", {
25320 value: true
25321 });
25322 _exports.uniqBy = uniqBy;
25323 _exports.removeAt = removeAt;
25324 _exports.isArray = isArray;
25325 _exports.default = _exports.MutableArray = _exports.NativeArray = _exports.A = void 0;
25326
25327 /**
25328 @module @ember/array
25329 */
25330 var EMPTY_ARRAY = Object.freeze([]);
25331
25332 var identityFunction = item => item;
25333
25334 function uniqBy(array, key = identityFunction) {
25335 (true && !(isArray(array)) && (0, _debug.assert)(`first argument passed to \`uniqBy\` should be array`, isArray(array)));
25336 var ret = A();
25337 var seen = new Set();
25338 var getter = typeof key === 'function' ? key : item => (0, _metal.get)(item, key);
25339 array.forEach(item => {
25340 var val = getter(item);
25341
25342 if (!seen.has(val)) {
25343 seen.add(val);
25344 ret.push(item);
25345 }
25346 });
25347 return ret;
25348 }
25349
25350 function iter(key, value) {
25351 var valueProvided = arguments.length === 2;
25352 return valueProvided ? item => value === (0, _metal.get)(item, key) : item => Boolean((0, _metal.get)(item, key));
25353 }
25354
25355 function findIndex(array, predicate, startAt) {
25356 var len = array.length;
25357
25358 for (var index = startAt; index < len; index++) {
25359 var item = (0, _metal.objectAt)(array, index);
25360
25361 if (predicate(item, index, array)) {
25362 return index;
25363 }
25364 }
25365
25366 return -1;
25367 }
25368
25369 function find(array, callback, target) {
25370 var predicate = callback.bind(target);
25371 var index = findIndex(array, predicate, 0);
25372 return index === -1 ? undefined : (0, _metal.objectAt)(array, index);
25373 }
25374
25375 function any(array, callback, target) {
25376 var predicate = callback.bind(target);
25377 return findIndex(array, predicate, 0) !== -1;
25378 }
25379
25380 function every(array, callback, target) {
25381 var cb = callback.bind(target);
25382
25383 var predicate = (item, index, array) => !cb(item, index, array);
25384
25385 return findIndex(array, predicate, 0) === -1;
25386 }
25387
25388 function indexOf(array, val, startAt = 0, withNaNCheck) {
25389 var len = array.length;
25390
25391 if (startAt < 0) {
25392 startAt += len;
25393 } // SameValueZero comparison (NaN !== NaN)
25394
25395
25396 var predicate = withNaNCheck && val !== val ? item => item !== item : item => item === val;
25397 return findIndex(array, predicate, startAt);
25398 }
25399
25400 function removeAt(array, index, len = 1) {
25401 (true && !(index > -1 && index < array.length) && (0, _debug.assert)(`\`removeAt\` index provided is out of range`, index > -1 && index < array.length));
25402 (0, _metal.replace)(array, index, len, EMPTY_ARRAY);
25403 return array;
25404 }
25405
25406 function insertAt(array, index, item) {
25407 (true && !(index > -1 && index <= array.length) && (0, _debug.assert)(`\`insertAt\` index provided is out of range`, index > -1 && index <= array.length));
25408 (0, _metal.replace)(array, index, 0, [item]);
25409 return item;
25410 }
25411 /**
25412 Returns true if the passed object is an array or Array-like.
25413
25414 Objects are considered Array-like if any of the following are true:
25415
25416 - the object is a native Array
25417 - the object has an objectAt property
25418 - the object is an Object, and has a length property
25419
25420 Unlike `typeOf` this method returns true even if the passed object is
25421 not formally an array but appears to be array-like (i.e. implements `Array`)
25422
25423 ```javascript
25424 import { isArray } from '@ember/array';
25425 import ArrayProxy from '@ember/array/proxy';
25426
25427 isArray(); // false
25428 isArray([]); // true
25429 isArray(ArrayProxy.create({ content: [] })); // true
25430 ```
25431
25432 @method isArray
25433 @static
25434 @for @ember/array
25435 @param {Object} obj The object to test
25436 @return {Boolean} true if the passed object is an array or Array-like
25437 @public
25438 */
25439
25440
25441 function isArray(_obj) {
25442 var obj = _obj;
25443
25444 if (true
25445 /* DEBUG */
25446 && _utils.HAS_NATIVE_PROXY && typeof _obj === 'object' && _obj !== null) {
25447 var possibleProxyContent = _obj[_metal.PROXY_CONTENT];
25448
25449 if (possibleProxyContent !== undefined) {
25450 obj = possibleProxyContent;
25451 }
25452 }
25453
25454 if (!obj || obj.setInterval) {
25455 return false;
25456 }
25457
25458 if (Array.isArray(obj) || ArrayMixin.detect(obj)) {
25459 return true;
25460 }
25461
25462 var type = (0, _typeOf.typeOf)(obj);
25463
25464 if ('array' === type) {
25465 return true;
25466 }
25467
25468 var length = obj.length;
25469
25470 if (typeof length === 'number' && length === length && 'object' === type) {
25471 return true;
25472 }
25473
25474 return false;
25475 }
25476 /*
25477 This allows us to define computed properties that are not enumerable.
25478 The primary reason this is important is that when `NativeArray` is
25479 applied to `Array.prototype` we need to ensure that we do not add _any_
25480 new enumerable properties.
25481 */
25482
25483
25484 function nonEnumerableComputed() {
25485 var property = (0, _metal.computed)(...arguments);
25486 property.enumerable = false;
25487 return property;
25488 }
25489
25490 function mapBy(key) {
25491 return this.map(next => (0, _metal.get)(next, key));
25492 } // ..........................................................
25493 // ARRAY
25494 //
25495
25496 /**
25497 This mixin implements Observer-friendly Array-like behavior. It is not a
25498 concrete implementation, but it can be used up by other classes that want
25499 to appear like arrays.
25500
25501 For example, ArrayProxy is a concrete class that can be instantiated to
25502 implement array-like behavior. This class uses the Array Mixin by way of
25503 the MutableArray mixin, which allows observable changes to be made to the
25504 underlying array.
25505
25506 This mixin defines methods specifically for collections that provide
25507 index-ordered access to their contents. When you are designing code that
25508 needs to accept any kind of Array-like object, you should use these methods
25509 instead of Array primitives because these will properly notify observers of
25510 changes to the array.
25511
25512 Although these methods are efficient, they do add a layer of indirection to
25513 your application so it is a good idea to use them only when you need the
25514 flexibility of using both true JavaScript arrays and "virtual" arrays such
25515 as controllers and collections.
25516
25517 You can use the methods defined in this module to access and modify array
25518 contents in an observable-friendly way. You can also be notified whenever
25519 the membership of an array changes by using `.observes('myArray.[]')`.
25520
25521 To support `EmberArray` in your own class, you must override two
25522 primitives to use it: `length()` and `objectAt()`.
25523
25524 @class EmberArray
25525 @uses Enumerable
25526 @since Ember 0.9.0
25527 @public
25528 */
25529
25530
25531 var ArrayMixin = _metal.Mixin.create(_enumerable.default, {
25532 init() {
25533 this._super(...arguments);
25534
25535 (0, _utils.setEmberArray)(this);
25536 },
25537
25538 /**
25539 __Required.__ You must implement this method to apply this mixin.
25540 Your array must support the `length` property. Your replace methods should
25541 set this property whenever it changes.
25542 @property {Number} length
25543 @public
25544 */
25545
25546 /**
25547 Returns the object at the given `index`. If the given `index` is negative
25548 or is greater or equal than the array length, returns `undefined`.
25549 This is one of the primitives you must implement to support `EmberArray`.
25550 If your object supports retrieving the value of an array item using `get()`
25551 (i.e. `myArray.get(0)`), then you do not need to implement this method
25552 yourself.
25553 ```javascript
25554 let arr = ['a', 'b', 'c', 'd'];
25555 arr.objectAt(0); // 'a'
25556 arr.objectAt(3); // 'd'
25557 arr.objectAt(-1); // undefined
25558 arr.objectAt(4); // undefined
25559 arr.objectAt(5); // undefined
25560 ```
25561 @method objectAt
25562 @param {Number} idx The index of the item to return.
25563 @return {*} item at index or undefined
25564 @public
25565 */
25566
25567 /**
25568 This returns the objects at the specified indexes, using `objectAt`.
25569 ```javascript
25570 let arr = ['a', 'b', 'c', 'd'];
25571 arr.objectsAt([0, 1, 2]); // ['a', 'b', 'c']
25572 arr.objectsAt([2, 3, 4]); // ['c', 'd', undefined]
25573 ```
25574 @method objectsAt
25575 @param {Array} indexes An array of indexes of items to return.
25576 @return {Array}
25577 @public
25578 */
25579 objectsAt(indexes) {
25580 return indexes.map(idx => (0, _metal.objectAt)(this, idx));
25581 },
25582
25583 /**
25584 This is the handler for the special array content property. If you get
25585 this property, it will return this. If you set this property to a new
25586 array, it will replace the current content.
25587 ```javascript
25588 let peopleToMoon = ['Armstrong', 'Aldrin'];
25589 peopleToMoon.get('[]'); // ['Armstrong', 'Aldrin']
25590 peopleToMoon.set('[]', ['Collins']); // ['Collins']
25591 peopleToMoon.get('[]'); // ['Collins']
25592 ```
25593 @property []
25594 @return this
25595 @public
25596 */
25597 '[]': nonEnumerableComputed({
25598 get() {
25599 return this;
25600 },
25601
25602 set(key, value) {
25603 this.replace(0, this.length, value);
25604 return this;
25605 }
25606
25607 }),
25608
25609 /**
25610 The first object in the array, or `undefined` if the array is empty.
25611 ```javascript
25612 let vowels = ['a', 'e', 'i', 'o', 'u'];
25613 vowels.firstObject; // 'a'
25614 vowels.shiftObject();
25615 vowels.firstObject; // 'e'
25616 vowels.reverseObjects();
25617 vowels.firstObject; // 'u'
25618 vowels.clear();
25619 vowels.firstObject; // undefined
25620 ```
25621 @property firstObject
25622 @return {Object | undefined} The first object in the array
25623 @public
25624 */
25625 firstObject: nonEnumerableComputed(function () {
25626 return (0, _metal.objectAt)(this, 0);
25627 }).readOnly(),
25628
25629 /**
25630 The last object in the array, or `undefined` if the array is empty.
25631 @property lastObject
25632 @return {Object | undefined} The last object in the array
25633 @public
25634 */
25635 lastObject: nonEnumerableComputed(function () {
25636 return (0, _metal.objectAt)(this, this.length - 1);
25637 }).readOnly(),
25638
25639 // Add any extra methods to EmberArray that are native to the built-in Array.
25640
25641 /**
25642 Returns a new array that is a slice of the receiver. This implementation
25643 uses the observable array methods to retrieve the objects for the new
25644 slice.
25645 ```javascript
25646 let arr = ['red', 'green', 'blue'];
25647 arr.slice(0); // ['red', 'green', 'blue']
25648 arr.slice(0, 2); // ['red', 'green']
25649 arr.slice(1, 100); // ['green', 'blue']
25650 ```
25651 @method slice
25652 @param {Number} beginIndex (Optional) index to begin slicing from.
25653 @param {Number} endIndex (Optional) index to end the slice at (but not included).
25654 @return {Array} New array with specified slice
25655 @public
25656 */
25657 slice(beginIndex = 0, endIndex) {
25658 var ret = A();
25659 var length = this.length;
25660
25661 if (beginIndex < 0) {
25662 beginIndex = length + beginIndex;
25663 }
25664
25665 if (endIndex === undefined || endIndex > length) {
25666 endIndex = length;
25667 } else if (endIndex < 0) {
25668 endIndex = length + endIndex;
25669 }
25670
25671 while (beginIndex < endIndex) {
25672 ret[ret.length] = (0, _metal.objectAt)(this, beginIndex++);
25673 }
25674
25675 return ret;
25676 },
25677
25678 /**
25679 Used to determine the passed object's first occurrence in the array.
25680 Returns the index if found, -1 if no match is found.
25681 The optional `startAt` argument can be used to pass a starting
25682 index to search from, effectively slicing the searchable portion
25683 of the array. If it's negative it will add the array length to
25684 the startAt value passed in as the index to search from. If less
25685 than or equal to `-1 * array.length` the entire array is searched.
25686 ```javascript
25687 let arr = ['a', 'b', 'c', 'd', 'a'];
25688 arr.indexOf('a'); // 0
25689 arr.indexOf('z'); // -1
25690 arr.indexOf('a', 2); // 4
25691 arr.indexOf('a', -1); // 4, equivalent to indexOf('a', 4)
25692 arr.indexOf('a', -100); // 0, searches entire array
25693 arr.indexOf('b', 3); // -1
25694 arr.indexOf('a', 100); // -1
25695 let people = [{ name: 'Zoey' }, { name: 'Bob' }]
25696 let newPerson = { name: 'Tom' };
25697 people = [newPerson, ...people, newPerson];
25698 people.indexOf(newPerson); // 0
25699 people.indexOf(newPerson, 1); // 3
25700 people.indexOf(newPerson, -4); // 0
25701 people.indexOf(newPerson, 10); // -1
25702 ```
25703 @method indexOf
25704 @param {Object} object the item to search for
25705 @param {Number} startAt optional starting location to search, default 0
25706 @return {Number} index or -1 if not found
25707 @public
25708 */
25709 indexOf(object, startAt) {
25710 return indexOf(this, object, startAt, false);
25711 },
25712
25713 /**
25714 Returns the index of the given `object`'s last occurrence.
25715 - If no `startAt` argument is given, the search starts from
25716 the last position.
25717 - If it's greater than or equal to the length of the array,
25718 the search starts from the last position.
25719 - If it's negative, it is taken as the offset from the end
25720 of the array i.e. `startAt + array.length`.
25721 - If it's any other positive number, will search backwards
25722 from that index of the array.
25723 Returns -1 if no match is found.
25724 ```javascript
25725 let arr = ['a', 'b', 'c', 'd', 'a'];
25726 arr.lastIndexOf('a'); // 4
25727 arr.lastIndexOf('z'); // -1
25728 arr.lastIndexOf('a', 2); // 0
25729 arr.lastIndexOf('a', -1); // 4
25730 arr.lastIndexOf('a', -3); // 0
25731 arr.lastIndexOf('b', 3); // 1
25732 arr.lastIndexOf('a', 100); // 4
25733 ```
25734 @method lastIndexOf
25735 @param {Object} object the item to search for
25736 @param {Number} startAt optional starting location to search from
25737 backwards, defaults to `(array.length - 1)`
25738 @return {Number} The last index of the `object` in the array or -1
25739 if not found
25740 @public
25741 */
25742 lastIndexOf(object, startAt) {
25743 var len = this.length;
25744
25745 if (startAt === undefined || startAt >= len) {
25746 startAt = len - 1;
25747 }
25748
25749 if (startAt < 0) {
25750 startAt += len;
25751 }
25752
25753 for (var idx = startAt; idx >= 0; idx--) {
25754 if ((0, _metal.objectAt)(this, idx) === object) {
25755 return idx;
25756 }
25757 }
25758
25759 return -1;
25760 },
25761
25762 // ..........................................................
25763 // ARRAY OBSERVERS
25764 //
25765
25766 /**
25767 Adds an array observer to the receiving array. The array observer object
25768 normally must implement two methods:
25769 * `willChange(observedObj, start, removeCount, addCount)` - This method will be
25770 called just before the array is modified.
25771 * `didChange(observedObj, start, removeCount, addCount)` - This method will be
25772 called just after the array is modified.
25773 Both callbacks will be passed the observed object, starting index of the
25774 change as well as a count of the items to be removed and added. You can use
25775 these callbacks to optionally inspect the array during the change, clear
25776 caches, or do any other bookkeeping necessary.
25777 In addition to passing a target, you can also include an options hash
25778 which you can use to override the method names that will be invoked on the
25779 target.
25780 @method addArrayObserver
25781 @param {Object} target The observer object.
25782 @param {Object} opts Optional hash of configuration options including
25783 `willChange` and `didChange` option.
25784 @return {EmberArray} receiver
25785 @public
25786 @example
25787 import Service from '@ember/service';
25788 export default Service.extend({
25789 data: Ember.A(),
25790 init() {
25791 this._super(...arguments);
25792 this.data.addArrayObserver(this, {
25793 willChange: 'dataWillChange',
25794 didChange: 'dataDidChange'
25795 });
25796 },
25797 dataWillChange(array, start, removeCount, addCount) {
25798 console.log('array will change', array, start, removeCount, addCount);
25799 },
25800 dataDidChange(array, start, removeCount, addCount) {
25801 console.log('array did change', array, start, removeCount, addCount);
25802 }
25803 });
25804 */
25805 addArrayObserver(target, opts) {
25806 return (0, _metal.addArrayObserver)(this, target, opts);
25807 },
25808
25809 /**
25810 Removes an array observer from the object if the observer is current
25811 registered. Calling this method multiple times with the same object will
25812 have no effect.
25813 @method removeArrayObserver
25814 @param {Object} target The object observing the array.
25815 @param {Object} opts Optional hash of configuration options including
25816 `willChange` and `didChange` option.
25817 @return {EmberArray} receiver
25818 @public
25819 */
25820 removeArrayObserver(target, opts) {
25821 return (0, _metal.removeArrayObserver)(this, target, opts);
25822 },
25823
25824 /**
25825 Becomes true whenever the array currently has observers watching changes
25826 on the array.
25827 ```javascript
25828 let arr = [1, 2, 3, 4, 5];
25829 arr.hasArrayObservers; // false
25830 arr.addArrayObserver(this, {
25831 willChange() {
25832 console.log('willChange');
25833 }
25834 });
25835 arr.hasArrayObservers; // true
25836 ```
25837 @property {Boolean} hasArrayObservers
25838 @public
25839 */
25840 hasArrayObservers: (0, _metal.nativeDescDecorator)({
25841 configurable: true,
25842 enumerable: false,
25843
25844 get() {
25845 return (0, _metal.hasListeners)(this, '@array:change') || (0, _metal.hasListeners)(this, '@array:before');
25846 }
25847
25848 }),
25849
25850 /**
25851 If you are implementing an object that supports `EmberArray`, call this
25852 method just before the array content changes to notify any observers and
25853 invalidate any related properties. Pass the starting index of the change
25854 as well as a delta of the amounts to change.
25855 ```app/components/show-post.js
25856 import Component from '@ember/component';
25857 import EmberObject from '@ember/object';
25858 const Post = EmberObject.extend({
25859 body: '',
25860 save() {}
25861 })
25862 export default Component.extend({
25863 attemptsToModify: 0,
25864 successfulModifications: 0,
25865 posts: null,
25866 init() {
25867 this._super(...arguments);
25868 this.posts = [1, 2, 3].map(i => Post.create({ body: i }));
25869 this.posts.addArrayObserver(this, {
25870 willChange() {
25871 this.incrementProperty('attemptsToModify');
25872 },
25873 didChange() {
25874 this.incrementProperty('successfulModifications');
25875 }
25876 });
25877 },
25878 actions: {
25879 editPost(post, newContent) {
25880 let oldContent = post.body,
25881 postIndex = this.posts.indexOf(post);
25882 this.posts.arrayContentWillChange(postIndex, 0, 0); // attemptsToModify = 1
25883 post.set('body', newContent);
25884 post.save()
25885 .then(response => {
25886 this.posts.arrayContentDidChange(postIndex, 0, 0); // successfulModifications = 1
25887 })
25888 .catch(error => {
25889 post.set('body', oldContent);
25890 })
25891 }
25892 }
25893 });
25894 ```
25895 @method arrayContentWillChange
25896 @param {Number} startIdx The starting index in the array that will change.
25897 @param {Number} removeAmt The number of items that will be removed. If you
25898 pass `null` assumes 0
25899 @param {Number} addAmt The number of items that will be added. If you
25900 pass `null` assumes 0.
25901 @return {EmberArray} receiver
25902 @public
25903 */
25904 arrayContentWillChange(startIdx, removeAmt, addAmt) {
25905 return (0, _metal.arrayContentWillChange)(this, startIdx, removeAmt, addAmt);
25906 },
25907
25908 /**
25909 If you are implementing an object that supports `EmberArray`, call this
25910 method just after the array content changes to notify any observers and
25911 invalidate any related properties. Pass the starting index of the change
25912 as well as a delta of the amounts to change.
25913 ```javascript
25914 let arr = [1, 2, 3, 4, 5];
25915 arr.copyWithin(-2); // [1, 2, 3, 1, 2]
25916 // arr.lastObject = 5
25917 arr.arrayContentDidChange(3, 2, 2);
25918 // arr.lastObject = 2
25919 ```
25920 @method arrayContentDidChange
25921 @param {Number} startIdx The starting index in the array that did change.
25922 @param {Number} removeAmt The number of items that were removed. If you
25923 pass `null` assumes 0
25924 @param {Number} addAmt The number of items that were added. If you
25925 pass `null` assumes 0.
25926 @return {EmberArray} receiver
25927 @public
25928 */
25929 arrayContentDidChange(startIdx, removeAmt, addAmt) {
25930 return (0, _metal.arrayContentDidChange)(this, startIdx, removeAmt, addAmt);
25931 },
25932
25933 /**
25934 Iterates through the array, calling the passed function on each
25935 item. This method corresponds to the `forEach()` method defined in
25936 JavaScript 1.6.
25937 The callback method you provide should have the following signature (all
25938 parameters are optional):
25939 ```javascript
25940 function(item, index, array);
25941 ```
25942 - `item` is the current item in the iteration.
25943 - `index` is the current index in the iteration.
25944 - `array` is the array itself.
25945 Note that in addition to a callback, you can also pass an optional target
25946 object that will be set as `this` on the context. This is a good way
25947 to give your iterator function access to the current object.
25948 Example Usage:
25949 ```javascript
25950 let foods = [
25951 { name: 'apple', eaten: false },
25952 { name: 'banana', eaten: false },
25953 { name: 'carrot', eaten: false }
25954 ];
25955 foods.forEach((food) => food.eaten = true);
25956 let output = '';
25957 foods.forEach((item, index, array) =>
25958 output += `${index + 1}/${array.length} ${item.name}\n`;
25959 );
25960 console.log(output);
25961 // 1/3 apple
25962 // 2/3 banana
25963 // 3/3 carrot
25964 ```
25965 @method forEach
25966 @param {Function} callback The callback to execute
25967 @param {Object} [target] The target object to use
25968 @return {Object} receiver
25969 @public
25970 */
25971 forEach(callback, target = null) {
25972 (true && !(typeof callback === 'function') && (0, _debug.assert)('`forEach` expects a function as first argument.', typeof callback === 'function'));
25973 var length = this.length;
25974
25975 for (var index = 0; index < length; index++) {
25976 var item = this.objectAt(index);
25977 callback.call(target, item, index, this);
25978 }
25979
25980 return this;
25981 },
25982
25983 /**
25984 Alias for `mapBy`.
25985 Returns the value of the named
25986 property on all items in the enumeration.
25987 ```javascript
25988 let people = [{name: 'Joe'}, {name: 'Matt'}];
25989 people.getEach('name');
25990 // ['Joe', 'Matt'];
25991 people.getEach('nonexistentProperty');
25992 // [undefined, undefined];
25993 ```
25994 @method getEach
25995 @param {String} key name of the property
25996 @return {Array} The mapped array.
25997 @public
25998 */
25999 getEach: mapBy,
26000
26001 /**
26002 Sets the value on the named property for each member. This is more
26003 ergonomic than using other methods defined on this helper. If the object
26004 implements Observable, the value will be changed to `set(),` otherwise
26005 it will be set directly. `null` objects are skipped.
26006 ```javascript
26007 let people = [{name: 'Joe'}, {name: 'Matt'}];
26008 people.setEach('zipCode', '10011');
26009 // [{name: 'Joe', zipCode: '10011'}, {name: 'Matt', zipCode: '10011'}];
26010 ```
26011 @method setEach
26012 @param {String} key The key to set
26013 @param {Object} value The object to set
26014 @return {Object} receiver
26015 @public
26016 */
26017 setEach(key, value) {
26018 return this.forEach(item => (0, _metal.set)(item, key, value));
26019 },
26020
26021 /**
26022 Maps all of the items in the enumeration to another value, returning
26023 a new array. This method corresponds to `map()` defined in JavaScript 1.6.
26024 The callback method you provide should have the following signature (all
26025 parameters are optional):
26026 ```javascript
26027 function(item, index, array);
26028 let arr = [1, 2, 3, 4, 5, 6];
26029 arr.map(element => element * element);
26030 // [1, 4, 9, 16, 25, 36];
26031 arr.map((element, index) => element + index);
26032 // [1, 3, 5, 7, 9, 11];
26033 ```
26034 - `item` is the current item in the iteration.
26035 - `index` is the current index in the iteration.
26036 - `array` is the array itself.
26037 It should return the mapped value.
26038 Note that in addition to a callback, you can also pass an optional target
26039 object that will be set as `this` on the context. This is a good way
26040 to give your iterator function access to the current object.
26041 @method map
26042 @param {Function} callback The callback to execute
26043 @param {Object} [target] The target object to use
26044 @return {Array} The mapped array.
26045 @public
26046 */
26047 map(callback, target = null) {
26048 (true && !(typeof callback === 'function') && (0, _debug.assert)('`map` expects a function as first argument.', typeof callback === 'function'));
26049 var ret = A();
26050 this.forEach((x, idx, i) => ret[idx] = callback.call(target, x, idx, i));
26051 return ret;
26052 },
26053
26054 /**
26055 Similar to map, this specialized function returns the value of the named
26056 property on all items in the enumeration.
26057 ```javascript
26058 let people = [{name: 'Joe'}, {name: 'Matt'}];
26059 people.mapBy('name');
26060 // ['Joe', 'Matt'];
26061 people.mapBy('unknownProperty');
26062 // [undefined, undefined];
26063 ```
26064 @method mapBy
26065 @param {String} key name of the property
26066 @return {Array} The mapped array.
26067 @public
26068 */
26069 mapBy,
26070
26071 /**
26072 Returns a new array with all of the items in the enumeration that the provided
26073 callback function returns true for. This method corresponds to [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter).
26074 The callback method should have the following signature:
26075 ```javascript
26076 function(item, index, array);
26077 ```
26078 - `item` is the current item in the iteration.
26079 - `index` is the current index in the iteration.
26080 - `array` is the array itself.
26081 All parameters are optional. The function should return `true` to include the item
26082 in the results, and `false` otherwise.
26083 Example:
26084 ```javascript
26085 function isAdult(person) {
26086 return person.age > 18;
26087 };
26088 let people = Ember.A([{ name: 'John', age: 14 }, { name: 'Joan', age: 45 }]);
26089 people.filter(isAdult); // returns [{ name: 'Joan', age: 45 }];
26090 ```
26091 Note that in addition to a callback, you can pass an optional target object
26092 that will be set as `this` on the context. This is a good way to give your
26093 iterator function access to the current object. For example:
26094 ```javascript
26095 function isAdultAndEngineer(person) {
26096 return person.age > 18 && this.engineering;
26097 }
26098 class AdultsCollection {
26099 engineering = false;
26100 constructor(opts = {}) {
26101 super(...arguments);
26102 this.engineering = opts.engineering;
26103 this.people = Ember.A([{ name: 'John', age: 14 }, { name: 'Joan', age: 45 }]);
26104 }
26105 }
26106 let collection = new AdultsCollection({ engineering: true });
26107 collection.people.filter(isAdultAndEngineer, { target: collection });
26108 ```
26109 @method filter
26110 @param {Function} callback The callback to execute
26111 @param {Object} [target] The target object to use
26112 @return {Array} A filtered array.
26113 @public
26114 */
26115 filter(callback, target = null) {
26116 (true && !(typeof callback === 'function') && (0, _debug.assert)('`filter` expects a function as first argument.', typeof callback === 'function'));
26117 var ret = A();
26118 this.forEach((x, idx, i) => {
26119 if (callback.call(target, x, idx, i)) {
26120 ret.push(x);
26121 }
26122 });
26123 return ret;
26124 },
26125
26126 /**
26127 Returns an array with all of the items in the enumeration where the passed
26128 function returns false. This method is the inverse of filter().
26129 The callback method you provide should have the following signature (all
26130 parameters are optional):
26131 ```javascript
26132 function(item, index, array);
26133 ```
26134 - *item* is the current item in the iteration.
26135 - *index* is the current index in the iteration
26136 - *array* is the array itself.
26137 It should return a falsey value to include the item in the results.
26138 Note that in addition to a callback, you can also pass an optional target
26139 object that will be set as "this" on the context. This is a good way
26140 to give your iterator function access to the current object.
26141 Example Usage:
26142 ```javascript
26143 const food = [
26144 { food: 'apple', isFruit: true },
26145 { food: 'bread', isFruit: false },
26146 { food: 'banana', isFruit: true }
26147 ];
26148 const nonFruits = food.reject(function(thing) {
26149 return thing.isFruit;
26150 }); // [{food: 'bread', isFruit: false}]
26151 ```
26152 @method reject
26153 @param {Function} callback The callback to execute
26154 @param {Object} [target] The target object to use
26155 @return {Array} A rejected array.
26156 @public
26157 */
26158 reject(callback, target = null) {
26159 (true && !(typeof callback === 'function') && (0, _debug.assert)('`reject` expects a function as first argument.', typeof callback === 'function'));
26160 return this.filter(function () {
26161 return !callback.apply(target, arguments);
26162 });
26163 },
26164
26165 /**
26166 Filters the array by the property and an optional value. If a value is given, it returns
26167 the items that have said value for the property. If not, it returns all the items that
26168 have a truthy value for the property.
26169 Example Usage:
26170 ```javascript
26171 let things = Ember.A([{ food: 'apple', isFruit: true }, { food: 'beans', isFruit: false }]);
26172 things.filterBy('food', 'beans'); // [{ food: 'beans' }]
26173 things.filterBy('isFruit'); // [{ food: 'apple' }]
26174 ```
26175 @method filterBy
26176 @param {String} key the property to test
26177 @param {*} [value] optional value to test against.
26178 @return {Array} filtered array
26179 @public
26180 */
26181 filterBy() {
26182 return this.filter(iter(...arguments));
26183 },
26184
26185 /**
26186 Returns an array with the items that do not have truthy values for the provided key.
26187 You can pass an optional second argument with a target value to reject for the key.
26188 Otherwise this will reject objects where the provided property evaluates to false.
26189 Example Usage:
26190 ```javascript
26191 let food = [
26192 { name: "apple", isFruit: true },
26193 { name: "carrot", isFruit: false },
26194 { name: "bread", isFruit: false },
26195 ];
26196 food.rejectBy('isFruit'); // [{ name: "carrot", isFruit: false }, { name: "bread", isFruit: false }]
26197 food.rejectBy('name', 'carrot'); // [{ name: "apple", isFruit: true }}, { name: "bread", isFruit: false }]
26198 ```
26199 @method rejectBy
26200 @param {String} key the property to test
26201 @param {*} [value] optional value to test against.
26202 @return {Array} rejected array
26203 @public
26204 */
26205 rejectBy() {
26206 return this.reject(iter(...arguments));
26207 },
26208
26209 /**
26210 Returns the first item in the array for which the callback returns true.
26211 This method is similar to the `find()` method defined in ECMAScript 2015.
26212 The callback method you provide should have the following signature (all
26213 parameters are optional):
26214 ```javascript
26215 function(item, index, array);
26216 ```
26217 - `item` is the current item in the iteration.
26218 - `index` is the current index in the iteration.
26219 - `array` is the array itself.
26220 It should return the `true` to include the item in the results, `false`
26221 otherwise.
26222 Note that in addition to a callback, you can also pass an optional target
26223 object that will be set as `this` on the context. This is a good way
26224 to give your iterator function access to the current object.
26225 Example Usage:
26226 ```javascript
26227 let users = [
26228 { id: 1, name: 'Yehuda' },
26229 { id: 2, name: 'Tom' },
26230 { id: 3, name: 'Melanie' },
26231 { id: 4, name: 'Leah' }
26232 ];
26233 users.find((user) => user.name == 'Tom'); // [{ id: 2, name: 'Tom' }]
26234 users.find(({ id }) => id == 3); // [{ id: 3, name: 'Melanie' }]
26235 ```
26236 @method find
26237 @param {Function} callback The callback to execute
26238 @param {Object} [target] The target object to use
26239 @return {Object} Found item or `undefined`.
26240 @public
26241 */
26242 find(callback, target = null) {
26243 (true && !(typeof callback === 'function') && (0, _debug.assert)('`find` expects a function as first argument.', typeof callback === 'function'));
26244 return find(this, callback, target);
26245 },
26246
26247 /**
26248 Returns the first item with a property matching the passed value. You
26249 can pass an optional second argument with the target value. Otherwise
26250 this will match any property that evaluates to `true`.
26251 This method works much like the more generic `find()` method.
26252 Usage Example:
26253 ```javascript
26254 let users = [
26255 { id: 1, name: 'Yehuda', isTom: false },
26256 { id: 2, name: 'Tom', isTom: true },
26257 { id: 3, name: 'Melanie', isTom: false },
26258 { id: 4, name: 'Leah', isTom: false }
26259 ];
26260 users.findBy('id', 4); // { id: 4, name: 'Leah', isTom: false }
26261 users.findBy('name', 'Melanie'); // { id: 3, name: 'Melanie', isTom: false }
26262 users.findBy('isTom'); // { id: 2, name: 'Tom', isTom: true }
26263 ```
26264 @method findBy
26265 @param {String} key the property to test
26266 @param {String} [value] optional value to test against.
26267 @return {Object} found item or `undefined`
26268 @public
26269 */
26270 findBy() {
26271 return find(this, iter(...arguments));
26272 },
26273
26274 /**
26275 Returns `true` if the passed function returns true for every item in the
26276 enumeration. This corresponds with the `Array.prototype.every()` method defined in ES5.
26277 The callback method should have the following signature:
26278 ```javascript
26279 function(item, index, array);
26280 ```
26281 - `item` is the current item in the iteration.
26282 - `index` is the current index in the iteration.
26283 - `array` is the array itself.
26284 All params are optional. The method should return `true` or `false`.
26285 Note that in addition to a callback, you can also pass an optional target
26286 object that will be set as `this` on the context. This is a good way
26287 to give your iterator function access to the current object.
26288 Usage example:
26289 ```javascript
26290 function isAdult(person) {
26291 return person.age > 18;
26292 };
26293 const people = Ember.A([{ name: 'John', age: 24 }, { name: 'Joan', age: 45 }]);
26294 const areAllAdults = people.every(isAdult);
26295 ```
26296 @method every
26297 @param {Function} callback The callback to execute
26298 @param {Object} [target] The target object to use
26299 @return {Boolean}
26300 @public
26301 */
26302 every(callback, target = null) {
26303 (true && !(typeof callback === 'function') && (0, _debug.assert)('`every` expects a function as first argument.', typeof callback === 'function'));
26304 return every(this, callback, target);
26305 },
26306
26307 /**
26308 Returns `true` if the passed property resolves to the value of the second
26309 argument for all items in the array. This method is often simpler/faster
26310 than using a callback.
26311 Note that like the native `Array.every`, `isEvery` will return true when called
26312 on any empty array.
26313 ```javascript
26314 class Language {
26315 constructor(name, isProgrammingLanguage) {
26316 this.name = name;
26317 this.programmingLanguage = isProgrammingLanguage;
26318 }
26319 }
26320 const compiledLanguages = [
26321 new Language('Java', true),
26322 new Language('Go', true),
26323 new Language('Rust', true)
26324 ]
26325 const languagesKnownByMe = [
26326 new Language('Javascript', true),
26327 new Language('English', false),
26328 new Language('Ruby', true)
26329 ]
26330 compiledLanguages.isEvery('programmingLanguage'); // true
26331 languagesKnownByMe.isEvery('programmingLanguage'); // false
26332 ```
26333 @method isEvery
26334 @param {String} key the property to test
26335 @param {String} [value] optional value to test against. Defaults to `true`
26336 @return {Boolean}
26337 @since 1.3.0
26338 @public
26339 */
26340 isEvery() {
26341 return every(this, iter(...arguments));
26342 },
26343
26344 /**
26345 The any() method executes the callback function once for each element
26346 present in the array until it finds the one where callback returns a truthy
26347 value (i.e. `true`). If such an element is found, any() immediately returns
26348 true. Otherwise, any() returns false.
26349 ```javascript
26350 function(item, index, array);
26351 ```
26352 - `item` is the current item in the iteration.
26353 - `index` is the current index in the iteration.
26354 - `array` is the array object itself.
26355 Note that in addition to a callback, you can also pass an optional target
26356 object that will be set as `this` on the context. It can be a good way
26357 to give your iterator function access to an object in cases where an ES6
26358 arrow function would not be appropriate.
26359 Usage Example:
26360 ```javascript
26361 let includesManager = people.any(this.findPersonInManagersList, this);
26362 let includesStockHolder = people.any(person => {
26363 return this.findPersonInStockHoldersList(person)
26364 });
26365 if (includesManager || includesStockHolder) {
26366 Paychecks.addBiggerBonus();
26367 }
26368 ```
26369 @method any
26370 @param {Function} callback The callback to execute
26371 @param {Object} [target] The target object to use
26372 @return {Boolean} `true` if the passed function returns `true` for any item
26373 @public
26374 */
26375 any(callback, target = null) {
26376 (true && !(typeof callback === 'function') && (0, _debug.assert)('`any` expects a function as first argument.', typeof callback === 'function'));
26377 return any(this, callback, target);
26378 },
26379
26380 /**
26381 Returns `true` if the passed property resolves to the value of the second
26382 argument for any item in the array. This method is often simpler/faster
26383 than using a callback.
26384 Example usage:
26385 ```javascript
26386 const food = [
26387 { food: 'apple', isFruit: true },
26388 { food: 'bread', isFruit: false },
26389 { food: 'banana', isFruit: true }
26390 ];
26391 food.isAny('isFruit'); // true
26392 ```
26393 @method isAny
26394 @param {String} key the property to test
26395 @param {String} [value] optional value to test against. Defaults to `true`
26396 @return {Boolean}
26397 @since 1.3.0
26398 @public
26399 */
26400 isAny() {
26401 return any(this, iter(...arguments));
26402 },
26403
26404 /**
26405 This will combine the values of the array into a single value. It
26406 is a useful way to collect a summary value from an array. This
26407 corresponds to the `reduce()` method defined in JavaScript 1.8.
26408 The callback method you provide should have the following signature (all
26409 parameters are optional):
26410 ```javascript
26411 function(previousValue, item, index, array);
26412 ```
26413 - `previousValue` is the value returned by the last call to the iterator.
26414 - `item` is the current item in the iteration.
26415 - `index` is the current index in the iteration.
26416 - `array` is the array itself.
26417 Return the new cumulative value.
26418 In addition to the callback you can also pass an `initialValue`. An error
26419 will be raised if you do not pass an initial value and the enumerator is
26420 empty.
26421 Note that unlike the other methods, this method does not allow you to
26422 pass a target object to set as this for the callback. It's part of the
26423 spec. Sorry.
26424 Example Usage:
26425 ```javascript
26426 let numbers = [1, 2, 3, 4, 5];
26427 numbers.reduce(function(summation, current) {
26428 return summation + current;
26429 }); // 15 (1 + 2 + 3 + 4 + 5)
26430 numbers.reduce(function(summation, current) {
26431 return summation + current;
26432 }, -15); // 0 (-15 + 1 + 2 + 3 + 4 + 5)
26433 let binaryValues = [true, false, false];
26434 binaryValues.reduce(function(truthValue, current) {
26435 return truthValue && current;
26436 }); // false (true && false && false)
26437 ```
26438 @method reduce
26439 @param {Function} callback The callback to execute
26440 @param {Object} initialValue Initial value for the reduce
26441 @return {Object} The reduced value.
26442 @public
26443 */
26444 reduce(callback, initialValue) {
26445 (true && !(typeof callback === 'function') && (0, _debug.assert)('`reduce` expects a function as first argument.', typeof callback === 'function'));
26446 var ret = initialValue;
26447 this.forEach(function (item, i) {
26448 ret = callback(ret, item, i, this);
26449 }, this);
26450 return ret;
26451 },
26452
26453 /**
26454 Invokes the named method on every object in the receiver that
26455 implements it. This method corresponds to the implementation in
26456 Prototype 1.6.
26457 ```javascript
26458 class Person {
26459 name = null;
26460 constructor(name) {
26461 this.name = name;
26462 }
26463 greet(prefix='Hello') {
26464 return `${prefix} ${this.name}`;
26465 }
26466 }
26467 let people = [new Person('Joe'), new Person('Matt')];
26468 people.invoke('greet'); // ['Hello Joe', 'Hello Matt']
26469 people.invoke('greet', 'Bonjour'); // ['Bonjour Joe', 'Bonjour Matt']
26470 ```
26471 @method invoke
26472 @param {String} methodName the name of the method
26473 @param {Object...} args optional arguments to pass as well.
26474 @return {Array} return values from calling invoke.
26475 @public
26476 */
26477 invoke(methodName, ...args) {
26478 var ret = A();
26479 this.forEach(item => ret.push((0, _utils.tryInvoke)(item, methodName, args)));
26480 return ret;
26481 },
26482
26483 /**
26484 Simply converts the object into a genuine array. The order is not
26485 guaranteed. Corresponds to the method implemented by Prototype.
26486 @method toArray
26487 @return {Array} the object as an array.
26488 @public
26489 */
26490 toArray() {
26491 return this.map(item => item);
26492 },
26493
26494 /**
26495 Returns a copy of the array with all `null` and `undefined` elements removed.
26496 ```javascript
26497 let arr = ['a', null, 'c', undefined];
26498 arr.compact(); // ['a', 'c']
26499 ```
26500 @method compact
26501 @return {Array} the array without null and undefined elements.
26502 @public
26503 */
26504 compact() {
26505 return this.filter(value => value != null);
26506 },
26507
26508 /**
26509 Used to determine if the array contains the passed object.
26510 Returns `true` if found, `false` otherwise.
26511 The optional `startAt` argument can be used to pass a starting
26512 index to search from, effectively slicing the searchable portion
26513 of the array. If it's negative it will add the array length to
26514 the startAt value passed in as the index to search from. If less
26515 than or equal to `-1 * array.length` the entire array is searched.
26516 This method has the same behavior of JavaScript's [Array.includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes).
26517 ```javascript
26518 [1, 2, 3].includes(2); // true
26519 [1, 2, 3].includes(4); // false
26520 [1, 2, 3].includes(3, 2); // true
26521 [1, 2, 3].includes(3, 3); // false
26522 [1, 2, 3].includes(3, -1); // true
26523 [1, 2, 3].includes(1, -1); // false
26524 [1, 2, 3].includes(1, -4); // true
26525 [1, 2, NaN].includes(NaN); // true
26526 ```
26527 @method includes
26528 @param {Object} object The object to search for.
26529 @param {Number} startAt optional starting location to search, default 0
26530 @return {Boolean} `true` if object is found in the array.
26531 @public
26532 */
26533 includes(object, startAt) {
26534 return indexOf(this, object, startAt, true) !== -1;
26535 },
26536
26537 /**
26538 Sorts the array by the keys specified in the argument.
26539 You may provide multiple arguments to sort by multiple properties.
26540 ```javascript
26541 let colors = [
26542 { name: 'red', weight: 500 },
26543 { name: 'green', weight: 600 },
26544 { name: 'blue', weight: 500 }
26545 ];
26546 colors.sortBy('name');
26547 // [{name: 'blue', weight: 500}, {name: 'green', weight: 600}, {name: 'red', weight: 500}]
26548 colors.sortBy('weight', 'name');
26549 // [{name: 'blue', weight: 500}, {name: 'red', weight: 500}, {name: 'green', weight: 600}]
26550 ```
26551 @method sortBy
26552 @param {String} property name(s) to sort on
26553 @return {Array} The sorted array.
26554 @since 1.2.0
26555 @public
26556 */
26557 sortBy() {
26558 var sortKeys = arguments;
26559 return this.toArray().sort((a, b) => {
26560 for (var i = 0; i < sortKeys.length; i++) {
26561 var key = sortKeys[i];
26562 var propA = (0, _metal.get)(a, key);
26563 var propB = (0, _metal.get)(b, key); // return 1 or -1 else continue to the next sortKey
26564
26565 var compareValue = (0, _compare.default)(propA, propB);
26566
26567 if (compareValue) {
26568 return compareValue;
26569 }
26570 }
26571
26572 return 0;
26573 });
26574 },
26575
26576 /**
26577 Returns a new array that contains only unique values. The default
26578 implementation returns an array regardless of the receiver type.
26579 ```javascript
26580 let arr = ['a', 'a', 'b', 'b'];
26581 arr.uniq(); // ['a', 'b']
26582 ```
26583 This only works on primitive data types, e.g. Strings, Numbers, etc.
26584 @method uniq
26585 @return {EmberArray}
26586 @public
26587 */
26588 uniq() {
26589 return uniqBy(this);
26590 },
26591
26592 /**
26593 Returns a new array that contains only items containing a unique property value.
26594 The default implementation returns an array regardless of the receiver type.
26595 ```javascript
26596 let arr = [{ value: 'a' }, { value: 'a' }, { value: 'b' }, { value: 'b' }];
26597 arr.uniqBy('value'); // [{ value: 'a' }, { value: 'b' }]
26598 let arr = [2.2, 2.1, 3.2, 3.3];
26599 arr.uniqBy(Math.floor); // [2.2, 3.2];
26600 ```
26601 @method uniqBy
26602 @param {String,Function} key
26603 @return {EmberArray}
26604 @public
26605 */
26606 uniqBy(key) {
26607 return uniqBy(this, key);
26608 },
26609
26610 /**
26611 Returns a new array that excludes the passed value. The default
26612 implementation returns an array regardless of the receiver type.
26613 If the receiver does not contain the value it returns the original array.
26614 ```javascript
26615 let arr = ['a', 'b', 'a', 'c'];
26616 arr.without('a'); // ['b', 'c']
26617 ```
26618 @method without
26619 @param {Object} value
26620 @return {EmberArray}
26621 @public
26622 */
26623 without(value) {
26624 if (!this.includes(value)) {
26625 return this; // nothing to do
26626 } // SameValueZero comparison (NaN !== NaN)
26627
26628
26629 var predicate = value === value ? item => item !== value : item => item === item;
26630 return this.filter(predicate);
26631 }
26632
26633 });
26634 /**
26635 This mixin defines the API for modifying array-like objects. These methods
26636 can be applied only to a collection that keeps its items in an ordered set.
26637 It builds upon the Array mixin and adds methods to modify the array.
26638 One concrete implementations of this class include ArrayProxy.
26639
26640 It is important to use the methods in this class to modify arrays so that
26641 changes are observable. This allows the binding system in Ember to function
26642 correctly.
26643
26644
26645 Note that an Array can change even if it does not implement this mixin.
26646 For example, one might implement a SparseArray that cannot be directly
26647 modified, but if its underlying enumerable changes, it will change also.
26648
26649 @class MutableArray
26650 @uses EmberArray
26651 @uses MutableEnumerable
26652 @public
26653 */
26654
26655
26656 var MutableArray = _metal.Mixin.create(ArrayMixin, _mutable_enumerable.default, {
26657 /**
26658 __Required.__ You must implement this method to apply this mixin.
26659 This is one of the primitives you must implement to support `Array`.
26660 You should replace amt objects started at idx with the objects in the
26661 passed array. You should also call `this.arrayContentDidChange()`
26662 Note that this method is expected to validate the type(s) of objects that it expects.
26663 @method replace
26664 @param {Number} idx Starting index in the array to replace. If
26665 idx >= length, then append to the end of the array.
26666 @param {Number} amt Number of elements that should be removed from
26667 the array, starting at *idx*.
26668 @param {EmberArray} objects An array of zero or more objects that should be
26669 inserted into the array at *idx*
26670 @public
26671 */
26672
26673 /**
26674 Remove all elements from the array. This is useful if you
26675 want to reuse an existing array without having to recreate it.
26676 ```javascript
26677 let colors = ['red', 'green', 'blue'];
26678 colors.length; // 3
26679 colors.clear(); // []
26680 colors.length; // 0
26681 ```
26682 @method clear
26683 @return {Array} An empty Array.
26684 @public
26685 */
26686 clear() {
26687 var len = this.length;
26688
26689 if (len === 0) {
26690 return this;
26691 }
26692
26693 this.replace(0, len, EMPTY_ARRAY);
26694 return this;
26695 },
26696
26697 /**
26698 This will use the primitive `replace()` method to insert an object at the
26699 specified index.
26700 ```javascript
26701 let colors = ['red', 'green', 'blue'];
26702 colors.insertAt(2, 'yellow'); // ['red', 'green', 'yellow', 'blue']
26703 colors.insertAt(5, 'orange'); // Error: Index out of range
26704 ```
26705 @method insertAt
26706 @param {Number} idx index of insert the object at.
26707 @param {Object} object object to insert
26708 @return {EmberArray} receiver
26709 @public
26710 */
26711 insertAt(idx, object) {
26712 insertAt(this, idx, object);
26713 return this;
26714 },
26715
26716 /**
26717 Remove an object at the specified index using the `replace()` primitive
26718 method. You can pass either a single index, or a start and a length.
26719 If you pass a start and length that is beyond the
26720 length this method will throw an assertion.
26721 ```javascript
26722 let colors = ['red', 'green', 'blue', 'yellow', 'orange'];
26723 colors.removeAt(0); // ['green', 'blue', 'yellow', 'orange']
26724 colors.removeAt(2, 2); // ['green', 'blue']
26725 colors.removeAt(4, 2); // Error: Index out of range
26726 ```
26727 @method removeAt
26728 @param {Number} start index, start of range
26729 @param {Number} len length of passing range
26730 @return {EmberArray} receiver
26731 @public
26732 */
26733 removeAt(start, len) {
26734 return removeAt(this, start, len);
26735 },
26736
26737 /**
26738 Push the object onto the end of the array. Works just like `push()` but it
26739 is KVO-compliant.
26740 ```javascript
26741 let colors = ['red', 'green'];
26742 colors.pushObject('black'); // ['red', 'green', 'black']
26743 colors.pushObject(['yellow']); // ['red', 'green', ['yellow']]
26744 ```
26745 @method pushObject
26746 @param {*} obj object to push
26747 @return object same object passed as a param
26748 @public
26749 */
26750 pushObject(obj) {
26751 return insertAt(this, this.length, obj);
26752 },
26753
26754 /**
26755 Add the objects in the passed array to the end of the array. Defers
26756 notifying observers of the change until all objects are added.
26757 ```javascript
26758 let colors = ['red'];
26759 colors.pushObjects(['yellow', 'orange']); // ['red', 'yellow', 'orange']
26760 ```
26761 @method pushObjects
26762 @param {EmberArray} objects the objects to add
26763 @return {EmberArray} receiver
26764 @public
26765 */
26766 pushObjects(objects) {
26767 this.replace(this.length, 0, objects);
26768 return this;
26769 },
26770
26771 /**
26772 Pop object from array or nil if none are left. Works just like `pop()` but
26773 it is KVO-compliant.
26774 ```javascript
26775 let colors = ['red', 'green', 'blue'];
26776 colors.popObject(); // 'blue'
26777 console.log(colors); // ['red', 'green']
26778 ```
26779 @method popObject
26780 @return object
26781 @public
26782 */
26783 popObject() {
26784 var len = this.length;
26785
26786 if (len === 0) {
26787 return null;
26788 }
26789
26790 var ret = (0, _metal.objectAt)(this, len - 1);
26791 this.removeAt(len - 1, 1);
26792 return ret;
26793 },
26794
26795 /**
26796 Shift an object from start of array or nil if none are left. Works just
26797 like `shift()` but it is KVO-compliant.
26798 ```javascript
26799 let colors = ['red', 'green', 'blue'];
26800 colors.shiftObject(); // 'red'
26801 console.log(colors); // ['green', 'blue']
26802 ```
26803 @method shiftObject
26804 @return object
26805 @public
26806 */
26807 shiftObject() {
26808 if (this.length === 0) {
26809 return null;
26810 }
26811
26812 var ret = (0, _metal.objectAt)(this, 0);
26813 this.removeAt(0);
26814 return ret;
26815 },
26816
26817 /**
26818 Unshift an object to start of array. Works just like `unshift()` but it is
26819 KVO-compliant.
26820 ```javascript
26821 let colors = ['red'];
26822 colors.unshiftObject('yellow'); // ['yellow', 'red']
26823 colors.unshiftObject(['black']); // [['black'], 'yellow', 'red']
26824 ```
26825 @method unshiftObject
26826 @param {*} obj object to unshift
26827 @return object same object passed as a param
26828 @public
26829 */
26830 unshiftObject(obj) {
26831 return insertAt(this, 0, obj);
26832 },
26833
26834 /**
26835 Adds the named objects to the beginning of the array. Defers notifying
26836 observers until all objects have been added.
26837 ```javascript
26838 let colors = ['red'];
26839 colors.unshiftObjects(['black', 'white']); // ['black', 'white', 'red']
26840 colors.unshiftObjects('yellow'); // Type Error: 'undefined' is not a function
26841 ```
26842 @method unshiftObjects
26843 @param {Enumberable} objects the objects to add
26844 @return {EmberArray} receiver
26845 @public
26846 */
26847 unshiftObjects(objects) {
26848 this.replace(0, 0, objects);
26849 return this;
26850 },
26851
26852 /**
26853 Reverse objects in the array. Works just like `reverse()` but it is
26854 KVO-compliant.
26855 @method reverseObjects
26856 @return {EmberArray} receiver
26857 @public
26858 */
26859 reverseObjects() {
26860 var len = this.length;
26861
26862 if (len === 0) {
26863 return this;
26864 }
26865
26866 var objects = this.toArray().reverse();
26867 this.replace(0, len, objects);
26868 return this;
26869 },
26870
26871 /**
26872 Replace all the receiver's content with content of the argument.
26873 If argument is an empty array receiver will be cleared.
26874 ```javascript
26875 let colors = ['red', 'green', 'blue'];
26876 colors.setObjects(['black', 'white']); // ['black', 'white']
26877 colors.setObjects([]); // []
26878 ```
26879 @method setObjects
26880 @param {EmberArray} objects array whose content will be used for replacing
26881 the content of the receiver
26882 @return {EmberArray} receiver with the new content
26883 @public
26884 */
26885 setObjects(objects) {
26886 if (objects.length === 0) {
26887 return this.clear();
26888 }
26889
26890 var len = this.length;
26891 this.replace(0, len, objects);
26892 return this;
26893 },
26894
26895 /**
26896 Remove all occurrences of an object in the array.
26897 ```javascript
26898 let cities = ['Chicago', 'Berlin', 'Lima', 'Chicago'];
26899 cities.removeObject('Chicago'); // ['Berlin', 'Lima']
26900 cities.removeObject('Lima'); // ['Berlin']
26901 cities.removeObject('Tokyo') // ['Berlin']
26902 ```
26903 @method removeObject
26904 @param {*} obj object to remove
26905 @return {EmberArray} receiver
26906 @public
26907 */
26908 removeObject(obj) {
26909 var loc = this.length || 0;
26910
26911 while (--loc >= 0) {
26912 var curObject = (0, _metal.objectAt)(this, loc);
26913
26914 if (curObject === obj) {
26915 this.removeAt(loc);
26916 }
26917 }
26918
26919 return this;
26920 },
26921
26922 /**
26923 Removes each object in the passed array from the receiver.
26924 @method removeObjects
26925 @param {EmberArray} objects the objects to remove
26926 @return {EmberArray} receiver
26927 @public
26928 */
26929 removeObjects(objects) {
26930 (0, _metal.beginPropertyChanges)();
26931
26932 for (var i = objects.length - 1; i >= 0; i--) {
26933 this.removeObject(objects[i]);
26934 }
26935
26936 (0, _metal.endPropertyChanges)();
26937 return this;
26938 },
26939
26940 /**
26941 Push the object onto the end of the array if it is not already
26942 present in the array.
26943 ```javascript
26944 let cities = ['Chicago', 'Berlin'];
26945 cities.addObject('Lima'); // ['Chicago', 'Berlin', 'Lima']
26946 cities.addObject('Berlin'); // ['Chicago', 'Berlin', 'Lima']
26947 ```
26948 @method addObject
26949 @param {*} obj object to add, if not already present
26950 @return {EmberArray} receiver
26951 @public
26952 */
26953 addObject(obj) {
26954 var included = this.includes(obj);
26955
26956 if (!included) {
26957 this.pushObject(obj);
26958 }
26959
26960 return this;
26961 },
26962
26963 /**
26964 Adds each object in the passed array to the receiver.
26965 @method addObjects
26966 @param {EmberArray} objects the objects to add.
26967 @return {EmberArray} receiver
26968 @public
26969 */
26970 addObjects(objects) {
26971 (0, _metal.beginPropertyChanges)();
26972 objects.forEach(obj => this.addObject(obj));
26973 (0, _metal.endPropertyChanges)();
26974 return this;
26975 }
26976
26977 });
26978 /**
26979 Creates an `Ember.NativeArray` from an Array-like object.
26980 Does not modify the original object's contents. `A()` is not needed if
26981 `EmberENV.EXTEND_PROTOTYPES` is `true` (the default value). However,
26982 it is recommended that you use `A()` when creating addons for
26983 ember or when you can not guarantee that `EmberENV.EXTEND_PROTOTYPES`
26984 will be `true`.
26985
26986 Example
26987
26988 ```app/components/my-component.js
26989 import Component from '@ember/component';
26990 import { A } from '@ember/array';
26991
26992 export default Component.extend({
26993 tagName: 'ul',
26994 classNames: ['pagination'],
26995
26996 init() {
26997 this._super(...arguments);
26998
26999 if (!this.get('content')) {
27000 this.set('content', A());
27001 this.set('otherContent', A([1,2,3]));
27002 }
27003 }
27004 });
27005 ```
27006
27007 @method A
27008 @static
27009 @for @ember/array
27010 @return {Ember.NativeArray}
27011 @public
27012 */
27013 // Add Ember.Array to Array.prototype. Remove methods with native
27014 // implementations and supply some more optimized versions of generic methods
27015 // because they are so common.
27016
27017 /**
27018 @module ember
27019 */
27020
27021 /**
27022 The NativeArray mixin contains the properties needed to make the native
27023 Array support MutableArray and all of its dependent APIs. Unless you
27024 have `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Array` set to
27025 false, this will be applied automatically. Otherwise you can apply the mixin
27026 at anytime by calling `Ember.NativeArray.apply(Array.prototype)`.
27027
27028 @class Ember.NativeArray
27029 @uses MutableArray
27030 @uses Observable
27031 @public
27032 */
27033
27034
27035 _exports.MutableArray = MutableArray;
27036
27037 var NativeArray = _metal.Mixin.create(MutableArray, _observable.default, {
27038 objectAt(idx) {
27039 return this[idx];
27040 },
27041
27042 // primitive for array support.
27043 replace(start, deleteCount, items = EMPTY_ARRAY) {
27044 (true && !(Array.isArray(items)) && (0, _debug.assert)('The third argument to replace needs to be an array.', Array.isArray(items)));
27045 (0, _metal.replaceInNativeArray)(this, start, deleteCount, items);
27046 return this;
27047 }
27048
27049 }); // Remove any methods implemented natively so we don't override them
27050
27051
27052 _exports.NativeArray = NativeArray;
27053 var ignore = ['length'];
27054 NativeArray.keys().forEach(methodName => {
27055 if (Array.prototype[methodName]) {
27056 ignore.push(methodName);
27057 }
27058 });
27059 _exports.NativeArray = NativeArray = NativeArray.without(...ignore);
27060 var A;
27061 _exports.A = A;
27062
27063 if (_environment.ENV.EXTEND_PROTOTYPES.Array) {
27064 NativeArray.apply(Array.prototype, true);
27065
27066 _exports.A = A = function (arr) {
27067 (true && !(!(this instanceof A)) && (0, _debug.assert)('You cannot create an Ember Array with `new A()`, please update to calling A as a function: `A()`', !(this instanceof A)));
27068 return arr || [];
27069 };
27070 } else {
27071 _exports.A = A = function (arr) {
27072 (true && !(!(this instanceof A)) && (0, _debug.assert)('You cannot create an Ember Array with `new A()`, please update to calling A as a function: `A()`', !(this instanceof A)));
27073
27074 if (!arr) {
27075 arr = [];
27076 }
27077
27078 return ArrayMixin.detect(arr) ? arr : NativeArray.apply(arr);
27079 };
27080 }
27081
27082 var _default = ArrayMixin;
27083 _exports.default = _default;
27084});
27085define("@ember/-internals/runtime/lib/mixins/comparable", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
27086 "use strict";
27087
27088 Object.defineProperty(_exports, "__esModule", {
27089 value: true
27090 });
27091 _exports.default = void 0;
27092
27093 /**
27094 @module ember
27095 */
27096
27097 /**
27098 Implements some standard methods for comparing objects. Add this mixin to
27099 any class you create that can compare its instances.
27100
27101 You should implement the `compare()` method.
27102
27103 @class Comparable
27104 @namespace Ember
27105 @since Ember 0.9
27106 @private
27107 */
27108 var _default = _metal.Mixin.create({
27109 /**
27110 __Required.__ You must implement this method to apply this mixin.
27111 Override to return the result of the comparison of the two parameters. The
27112 compare method should return:
27113 - `-1` if `a < b`
27114 - `0` if `a == b`
27115 - `1` if `a > b`
27116 Default implementation raises an exception.
27117 @method compare
27118 @param a {Object} the first object to compare
27119 @param b {Object} the second object to compare
27120 @return {Number} the result of the comparison
27121 @private
27122 */
27123 compare: null
27124 });
27125
27126 _exports.default = _default;
27127});
27128define("@ember/-internals/runtime/lib/mixins/container_proxy", ["exports", "@ember/runloop", "@ember/-internals/metal"], function (_exports, _runloop, _metal) {
27129 "use strict";
27130
27131 Object.defineProperty(_exports, "__esModule", {
27132 value: true
27133 });
27134 _exports.default = void 0;
27135
27136 /**
27137 @module ember
27138 */
27139
27140 /**
27141 ContainerProxyMixin is used to provide public access to specific
27142 container functionality.
27143
27144 @class ContainerProxyMixin
27145 @private
27146 */
27147 var containerProxyMixin = {
27148 /**
27149 The container stores state.
27150 @private
27151 @property {Ember.Container} __container__
27152 */
27153 __container__: null,
27154
27155 /**
27156 Returns an object that can be used to provide an owner to a
27157 manually created instance.
27158 Example:
27159 ```
27160 import { getOwner } from '@ember/application';
27161 let owner = getOwner(this);
27162 User.create(
27163 owner.ownerInjection(),
27164 { username: 'rwjblue' }
27165 )
27166 ```
27167 @public
27168 @method ownerInjection
27169 @since 2.3.0
27170 @return {Object}
27171 */
27172 ownerInjection() {
27173 return this.__container__.ownerInjection();
27174 },
27175
27176 /**
27177 Given a fullName return a corresponding instance.
27178 The default behavior is for lookup to return a singleton instance.
27179 The singleton is scoped to the container, allowing multiple containers
27180 to all have their own locally scoped singletons.
27181 ```javascript
27182 let registry = new Registry();
27183 let container = registry.container();
27184 registry.register('api:twitter', Twitter);
27185 let twitter = container.lookup('api:twitter');
27186 twitter instanceof Twitter; // => true
27187 // by default the container will return singletons
27188 let twitter2 = container.lookup('api:twitter');
27189 twitter2 instanceof Twitter; // => true
27190 twitter === twitter2; //=> true
27191 ```
27192 If singletons are not wanted an optional flag can be provided at lookup.
27193 ```javascript
27194 let registry = new Registry();
27195 let container = registry.container();
27196 registry.register('api:twitter', Twitter);
27197 let twitter = container.lookup('api:twitter', { singleton: false });
27198 let twitter2 = container.lookup('api:twitter', { singleton: false });
27199 twitter === twitter2; //=> false
27200 ```
27201 @public
27202 @method lookup
27203 @param {String} fullName
27204 @param {Object} options
27205 @return {any}
27206 */
27207 lookup(fullName, options) {
27208 return this.__container__.lookup(fullName, options);
27209 },
27210
27211 destroy() {
27212 var container = this.__container__;
27213
27214 if (container) {
27215 (0, _runloop.join)(() => {
27216 container.destroy();
27217 (0, _runloop.schedule)('destroy', container, 'finalizeDestroy');
27218 });
27219 }
27220
27221 this._super();
27222 },
27223
27224 /**
27225 Given a fullName return a factory manager.
27226 This method returns a manager which can be used for introspection of the
27227 factory's class or for the creation of factory instances with initial
27228 properties. The manager is an object with the following properties:
27229 * `class` - The registered or resolved class.
27230 * `create` - A function that will create an instance of the class with
27231 any dependencies injected.
27232 For example:
27233 ```javascript
27234 import { getOwner } from '@ember/application';
27235 let owner = getOwner(otherInstance);
27236 // the owner is commonly the `applicationInstance`, and can be accessed via
27237 // an instance initializer.
27238 let factory = owner.factoryFor('service:bespoke');
27239 factory.class;
27240 // The registered or resolved class. For example when used with an Ember-CLI
27241 // app, this would be the default export from `app/services/bespoke.js`.
27242 let instance = factory.create({
27243 someProperty: 'an initial property value'
27244 });
27245 // Create an instance with any injections and the passed options as
27246 // initial properties.
27247 ```
27248 Any instances created via the factory's `.create()` method *must* be destroyed
27249 manually by the caller of `.create()`. Typically, this is done during the creating
27250 objects own `destroy` or `willDestroy` methods.
27251 @public
27252 @method factoryFor
27253 @param {String} fullName
27254 @param {Object} options
27255 @return {FactoryManager}
27256 */
27257 factoryFor(fullName, options = {}) {
27258 return this.__container__.factoryFor(fullName, options);
27259 }
27260
27261 };
27262
27263 var _default = _metal.Mixin.create(containerProxyMixin);
27264
27265 _exports.default = _default;
27266});
27267define("@ember/-internals/runtime/lib/mixins/copyable", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
27268 "use strict";
27269
27270 Object.defineProperty(_exports, "__esModule", {
27271 value: true
27272 });
27273 _exports.default = void 0;
27274
27275 /**
27276 @module ember
27277 */
27278
27279 /**
27280 Implements some standard methods for copying an object. Add this mixin to
27281 any object you create that can create a copy of itself. This mixin is
27282 added automatically to the built-in array.
27283
27284 You should generally implement the `copy()` method to return a copy of the
27285 receiver.
27286
27287 @class Copyable
27288 @namespace Ember
27289 @since Ember 0.9
27290 @deprecated Use 'ember-copy' addon instead
27291 @private
27292 */
27293 var _default = _metal.Mixin.create({
27294 /**
27295 __Required.__ You must implement this method to apply this mixin.
27296 Override to return a copy of the receiver. Default implementation raises
27297 an exception.
27298 @method copy
27299 @param {Boolean} deep if `true`, a deep copy of the object should be made
27300 @return {Object} copy of receiver
27301 @private
27302 */
27303 copy: null
27304 });
27305
27306 _exports.default = _default;
27307});
27308define("@ember/-internals/runtime/lib/mixins/enumerable", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
27309 "use strict";
27310
27311 Object.defineProperty(_exports, "__esModule", {
27312 value: true
27313 });
27314 _exports.default = void 0;
27315
27316 /**
27317 @module @ember/enumerable
27318 @private
27319 */
27320
27321 /**
27322 The methods in this mixin have been moved to [MutableArray](/ember/release/classes/MutableArray). This mixin has
27323 been intentionally preserved to avoid breaking Enumerable.detect checks
27324 until the community migrates away from them.
27325
27326 @class Enumerable
27327 @private
27328 */
27329 var _default = _metal.Mixin.create();
27330
27331 _exports.default = _default;
27332});
27333define("@ember/-internals/runtime/lib/mixins/evented", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
27334 "use strict";
27335
27336 Object.defineProperty(_exports, "__esModule", {
27337 value: true
27338 });
27339 _exports.default = void 0;
27340
27341 /**
27342 @module @ember/object
27343 */
27344
27345 /**
27346 This mixin allows for Ember objects to subscribe to and emit events.
27347
27348 ```app/utils/person.js
27349 import EmberObject from '@ember/object';
27350 import Evented from '@ember/object/evented';
27351
27352 export default EmberObject.extend(Evented, {
27353 greet() {
27354 // ...
27355 this.trigger('greet');
27356 }
27357 });
27358 ```
27359
27360 ```javascript
27361 var person = Person.create();
27362
27363 person.on('greet', function() {
27364 console.log('Our person has greeted');
27365 });
27366
27367 person.greet();
27368
27369 // outputs: 'Our person has greeted'
27370 ```
27371
27372 You can also chain multiple event subscriptions:
27373
27374 ```javascript
27375 person.on('greet', function() {
27376 console.log('Our person has greeted');
27377 }).one('greet', function() {
27378 console.log('Offer one-time special');
27379 }).off('event', this, forgetThis);
27380 ```
27381
27382 @class Evented
27383 @public
27384 */
27385 var _default = _metal.Mixin.create({
27386 /**
27387 Subscribes to a named event with given function.
27388 ```javascript
27389 person.on('didLoad', function() {
27390 // fired once the person has loaded
27391 });
27392 ```
27393 An optional target can be passed in as the 2nd argument that will
27394 be set as the "this" for the callback. This is a good way to give your
27395 function access to the object triggering the event. When the target
27396 parameter is used the callback method becomes the third argument.
27397 @method on
27398 @param {String} name The name of the event
27399 @param {Object} [target] The "this" binding for the callback
27400 @param {Function|String} method A function or the name of a function to be called on `target`
27401 @return this
27402 @public
27403 */
27404 on(name, target, method) {
27405 (0, _metal.addListener)(this, name, target, method);
27406 return this;
27407 },
27408
27409 /**
27410 Subscribes a function to a named event and then cancels the subscription
27411 after the first time the event is triggered. It is good to use ``one`` when
27412 you only care about the first time an event has taken place.
27413 This function takes an optional 2nd argument that will become the "this"
27414 value for the callback. When the target parameter is used the callback method
27415 becomes the third argument.
27416 @method one
27417 @param {String} name The name of the event
27418 @param {Object} [target] The "this" binding for the callback
27419 @param {Function|String} method A function or the name of a function to be called on `target`
27420 @return this
27421 @public
27422 */
27423 one(name, target, method) {
27424 (0, _metal.addListener)(this, name, target, method, true);
27425 return this;
27426 },
27427
27428 /**
27429 Triggers a named event for the object. Any additional arguments
27430 will be passed as parameters to the functions that are subscribed to the
27431 event.
27432 ```javascript
27433 person.on('didEat', function(food) {
27434 console.log('person ate some ' + food);
27435 });
27436 person.trigger('didEat', 'broccoli');
27437 // outputs: person ate some broccoli
27438 ```
27439 @method trigger
27440 @param {String} name The name of the event
27441 @param {Object...} args Optional arguments to pass on
27442 @public
27443 */
27444 trigger(name, ...args) {
27445 (0, _metal.sendEvent)(this, name, args);
27446 },
27447
27448 /**
27449 Cancels subscription for given name, target, and method.
27450 @method off
27451 @param {String} name The name of the event
27452 @param {Object} target The target of the subscription
27453 @param {Function|String} method The function or the name of a function of the subscription
27454 @return this
27455 @public
27456 */
27457 off(name, target, method) {
27458 (0, _metal.removeListener)(this, name, target, method);
27459 return this;
27460 },
27461
27462 /**
27463 Checks to see if object has any subscriptions for named event.
27464 @method has
27465 @param {String} name The name of the event
27466 @return {Boolean} does the object have a subscription for event
27467 @public
27468 */
27469 has(name) {
27470 return (0, _metal.hasListeners)(this, name);
27471 }
27472
27473 });
27474
27475 _exports.default = _default;
27476});
27477define("@ember/-internals/runtime/lib/mixins/mutable_enumerable", ["exports", "@ember/-internals/runtime/lib/mixins/enumerable", "@ember/-internals/metal"], function (_exports, _enumerable, _metal) {
27478 "use strict";
27479
27480 Object.defineProperty(_exports, "__esModule", {
27481 value: true
27482 });
27483 _exports.default = void 0;
27484
27485 /**
27486 @module ember
27487 */
27488
27489 /**
27490 The methods in this mixin have been moved to MutableArray. This mixin has
27491 been intentionally preserved to avoid breaking MutableEnumerable.detect
27492 checks until the community migrates away from them.
27493
27494 @class MutableEnumerable
27495 @namespace Ember
27496 @uses Enumerable
27497 @private
27498 */
27499 var _default = _metal.Mixin.create(_enumerable.default);
27500
27501 _exports.default = _default;
27502});
27503define("@ember/-internals/runtime/lib/mixins/observable", ["exports", "@ember/-internals/meta", "@ember/-internals/metal", "@ember/debug"], function (_exports, _meta, _metal, _debug) {
27504 "use strict";
27505
27506 Object.defineProperty(_exports, "__esModule", {
27507 value: true
27508 });
27509 _exports.default = void 0;
27510
27511 /**
27512 @module @ember/object
27513 */
27514
27515 /**
27516 ## Overview
27517
27518 This mixin provides properties and property observing functionality, core
27519 features of the Ember object model.
27520
27521 Properties and observers allow one object to observe changes to a
27522 property on another object. This is one of the fundamental ways that
27523 models, controllers and views communicate with each other in an Ember
27524 application.
27525
27526 Any object that has this mixin applied can be used in observer
27527 operations. That includes `EmberObject` and most objects you will
27528 interact with as you write your Ember application.
27529
27530 Note that you will not generally apply this mixin to classes yourself,
27531 but you will use the features provided by this module frequently, so it
27532 is important to understand how to use it.
27533
27534 ## Using `get()` and `set()`
27535
27536 Because of Ember's support for bindings and observers, you will always
27537 access properties using the get method, and set properties using the
27538 set method. This allows the observing objects to be notified and
27539 computed properties to be handled properly.
27540
27541 More documentation about `get` and `set` are below.
27542
27543 ## Observing Property Changes
27544
27545 You typically observe property changes simply by using the `observer`
27546 function in classes that you write.
27547
27548 For example:
27549
27550 ```javascript
27551 import { observer } from '@ember/object';
27552 import EmberObject from '@ember/object';
27553
27554 EmberObject.extend({
27555 valueObserver: observer('value', function(sender, key, value, rev) {
27556 // Executes whenever the "value" property changes
27557 // See the addObserver method for more information about the callback arguments
27558 })
27559 });
27560 ```
27561
27562 Although this is the most common way to add an observer, this capability
27563 is actually built into the `EmberObject` class on top of two methods
27564 defined in this mixin: `addObserver` and `removeObserver`. You can use
27565 these two methods to add and remove observers yourself if you need to
27566 do so at runtime.
27567
27568 To add an observer for a property, call:
27569
27570 ```javascript
27571 object.addObserver('propertyKey', targetObject, targetAction)
27572 ```
27573
27574 This will call the `targetAction` method on the `targetObject` whenever
27575 the value of the `propertyKey` changes.
27576
27577 Note that if `propertyKey` is a computed property, the observer will be
27578 called when any of the property dependencies are changed, even if the
27579 resulting value of the computed property is unchanged. This is necessary
27580 because computed properties are not computed until `get` is called.
27581
27582 @class Observable
27583 @public
27584 */
27585 var _default = _metal.Mixin.create({
27586 /**
27587 Retrieves the value of a property from the object.
27588 This method is usually similar to using `object[keyName]` or `object.keyName`,
27589 however it supports both computed properties and the unknownProperty
27590 handler.
27591 Because `get` unifies the syntax for accessing all these kinds
27592 of properties, it can make many refactorings easier, such as replacing a
27593 simple property with a computed property, or vice versa.
27594 ### Computed Properties
27595 Computed properties are methods defined with the `property` modifier
27596 declared at the end, such as:
27597 ```javascript
27598 import { computed } from '@ember/object';
27599 fullName: computed('firstName', 'lastName', function() {
27600 return this.get('firstName') + ' ' + this.get('lastName');
27601 })
27602 ```
27603 When you call `get` on a computed property, the function will be
27604 called and the return value will be returned instead of the function
27605 itself.
27606 ### Unknown Properties
27607 Likewise, if you try to call `get` on a property whose value is
27608 `undefined`, the `unknownProperty()` method will be called on the object.
27609 If this method returns any value other than `undefined`, it will be returned
27610 instead. This allows you to implement "virtual" properties that are
27611 not defined upfront.
27612 @method get
27613 @param {String} keyName The property to retrieve
27614 @return {Object} The property value or undefined.
27615 @public
27616 */
27617 get(keyName) {
27618 return (0, _metal.get)(this, keyName);
27619 },
27620
27621 /**
27622 To get the values of multiple properties at once, call `getProperties`
27623 with a list of strings or an array:
27624 ```javascript
27625 record.getProperties('firstName', 'lastName', 'zipCode');
27626 // { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
27627 ```
27628 is equivalent to:
27629 ```javascript
27630 record.getProperties(['firstName', 'lastName', 'zipCode']);
27631 // { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
27632 ```
27633 @method getProperties
27634 @param {String...|Array} list of keys to get
27635 @return {Object}
27636 @public
27637 */
27638 getProperties(...args) {
27639 return (0, _metal.getProperties)(...[this].concat(args));
27640 },
27641
27642 /**
27643 Sets the provided key or path to the value.
27644 ```javascript
27645 record.set("key", value);
27646 ```
27647 This method is generally very similar to calling `object["key"] = value` or
27648 `object.key = value`, except that it provides support for computed
27649 properties, the `setUnknownProperty()` method and property observers.
27650 ### Computed Properties
27651 If you try to set a value on a key that has a computed property handler
27652 defined (see the `get()` method for an example), then `set()` will call
27653 that method, passing both the value and key instead of simply changing
27654 the value itself. This is useful for those times when you need to
27655 implement a property that is composed of one or more member
27656 properties.
27657 ### Unknown Properties
27658 If you try to set a value on a key that is undefined in the target
27659 object, then the `setUnknownProperty()` handler will be called instead. This
27660 gives you an opportunity to implement complex "virtual" properties that
27661 are not predefined on the object. If `setUnknownProperty()` returns
27662 undefined, then `set()` will simply set the value on the object.
27663 ### Property Observers
27664 In addition to changing the property, `set()` will also register a property
27665 change with the object. Unless you have placed this call inside of a
27666 `beginPropertyChanges()` and `endPropertyChanges(),` any "local" observers
27667 (i.e. observer methods declared on the same object), will be called
27668 immediately. Any "remote" observers (i.e. observer methods declared on
27669 another object) will be placed in a queue and called at a later time in a
27670 coalesced manner.
27671 @method set
27672 @param {String} keyName The property to set
27673 @param {Object} value The value to set or `null`.
27674 @return {Object} The passed value
27675 @public
27676 */
27677 set(keyName, value) {
27678 return (0, _metal.set)(this, keyName, value);
27679 },
27680
27681 /**
27682 Sets a list of properties at once. These properties are set inside
27683 a single `beginPropertyChanges` and `endPropertyChanges` batch, so
27684 observers will be buffered.
27685 ```javascript
27686 record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
27687 ```
27688 @method setProperties
27689 @param {Object} hash the hash of keys and values to set
27690 @return {Object} The passed in hash
27691 @public
27692 */
27693 setProperties(hash) {
27694 return (0, _metal.setProperties)(this, hash);
27695 },
27696
27697 /**
27698 Begins a grouping of property changes.
27699 You can use this method to group property changes so that notifications
27700 will not be sent until the changes are finished. If you plan to make a
27701 large number of changes to an object at one time, you should call this
27702 method at the beginning of the changes to begin deferring change
27703 notifications. When you are done making changes, call
27704 `endPropertyChanges()` to deliver the deferred change notifications and end
27705 deferring.
27706 @method beginPropertyChanges
27707 @return {Observable}
27708 @private
27709 */
27710 beginPropertyChanges() {
27711 (0, _metal.beginPropertyChanges)();
27712 return this;
27713 },
27714
27715 /**
27716 Ends a grouping of property changes.
27717 You can use this method to group property changes so that notifications
27718 will not be sent until the changes are finished. If you plan to make a
27719 large number of changes to an object at one time, you should call
27720 `beginPropertyChanges()` at the beginning of the changes to defer change
27721 notifications. When you are done making changes, call this method to
27722 deliver the deferred change notifications and end deferring.
27723 @method endPropertyChanges
27724 @return {Observable}
27725 @private
27726 */
27727 endPropertyChanges() {
27728 (0, _metal.endPropertyChanges)();
27729 return this;
27730 },
27731
27732 /**
27733 Notify the observer system that a property has just changed.
27734 Sometimes you need to change a value directly or indirectly without
27735 actually calling `get()` or `set()` on it. In this case, you can use this
27736 method instead. Calling this method will notify all observers that the
27737 property has potentially changed value.
27738 @method notifyPropertyChange
27739 @param {String} keyName The property key to be notified about.
27740 @return {Observable}
27741 @public
27742 */
27743 notifyPropertyChange(keyName) {
27744 (0, _metal.notifyPropertyChange)(this, keyName);
27745 return this;
27746 },
27747
27748 /**
27749 Adds an observer on a property.
27750 This is the core method used to register an observer for a property.
27751 Once you call this method, any time the key's value is set, your observer
27752 will be notified. Note that the observers are triggered any time the
27753 value is set, regardless of whether it has actually changed. Your
27754 observer should be prepared to handle that.
27755 There are two common invocation patterns for `.addObserver()`:
27756 - Passing two arguments:
27757 - the name of the property to observe (as a string)
27758 - the function to invoke (an actual function)
27759 - Passing three arguments:
27760 - the name of the property to observe (as a string)
27761 - the target object (will be used to look up and invoke a
27762 function on)
27763 - the name of the function to invoke on the target object
27764 (as a string).
27765 ```app/components/my-component.js
27766 import Component from '@ember/component';
27767 export default Component.extend({
27768 init() {
27769 this._super(...arguments);
27770 // the following are equivalent:
27771 // using three arguments
27772 this.addObserver('foo', this, 'fooDidChange');
27773 // using two arguments
27774 this.addObserver('foo', (...args) => {
27775 this.fooDidChange(...args);
27776 });
27777 },
27778 fooDidChange() {
27779 // your custom logic code
27780 }
27781 });
27782 ```
27783 ### Observer Methods
27784 Observer methods have the following signature:
27785 ```app/components/my-component.js
27786 import Component from '@ember/component';
27787 export default Component.extend({
27788 init() {
27789 this._super(...arguments);
27790 this.addObserver('foo', this, 'fooDidChange');
27791 },
27792 fooDidChange(sender, key, value, rev) {
27793 // your code
27794 }
27795 });
27796 ```
27797 The `sender` is the object that changed. The `key` is the property that
27798 changes. The `value` property is currently reserved and unused. The `rev`
27799 is the last property revision of the object when it changed, which you can
27800 use to detect if the key value has really changed or not.
27801 Usually you will not need the value or revision parameters at
27802 the end. In this case, it is common to write observer methods that take
27803 only a sender and key value as parameters or, if you aren't interested in
27804 any of these values, to write an observer that has no parameters at all.
27805 @method addObserver
27806 @param {String} key The key to observe
27807 @param {Object} target The target object to invoke
27808 @param {String|Function} method The method to invoke
27809 @param {Boolean} sync Whether the observer is sync or not
27810 @return {Observable}
27811 @public
27812 */
27813 addObserver(key, target, method, sync) {
27814 (0, _metal.addObserver)(this, key, target, method, sync);
27815 return this;
27816 },
27817
27818 /**
27819 Remove an observer you have previously registered on this object. Pass
27820 the same key, target, and method you passed to `addObserver()` and your
27821 target will no longer receive notifications.
27822 @method removeObserver
27823 @param {String} key The key to observe
27824 @param {Object} target The target object to invoke
27825 @param {String|Function} method The method to invoke
27826 @param {Boolean} sync Whether the observer is async or not
27827 @return {Observable}
27828 @public
27829 */
27830 removeObserver(key, target, method, sync) {
27831 (0, _metal.removeObserver)(this, key, target, method, sync);
27832 return this;
27833 },
27834
27835 /**
27836 Returns `true` if the object currently has observers registered for a
27837 particular key. You can use this method to potentially defer performing
27838 an expensive action until someone begins observing a particular property
27839 on the object.
27840 @method hasObserverFor
27841 @param {String} key Key to check
27842 @return {Boolean}
27843 @private
27844 */
27845 hasObserverFor(key) {
27846 return (0, _metal.hasListeners)(this, `${key}:change`);
27847 },
27848
27849 /**
27850 Retrieves the value of a property, or a default value in the case that the
27851 property returns `undefined`.
27852 ```javascript
27853 person.getWithDefault('lastName', 'Doe');
27854 ```
27855 @method getWithDefault
27856 @param {String} keyName The name of the property to retrieve
27857 @param {Object} defaultValue The value to return if the property value is undefined
27858 @return {Object} The property value or the defaultValue.
27859 @public
27860 @deprecated
27861 */
27862 getWithDefault(keyName, defaultValue) {
27863 return (0, _metal.getWithDefault)(this, keyName, defaultValue);
27864 },
27865
27866 /**
27867 Set the value of a property to the current value plus some amount.
27868 ```javascript
27869 person.incrementProperty('age');
27870 team.incrementProperty('score', 2);
27871 ```
27872 @method incrementProperty
27873 @param {String} keyName The name of the property to increment
27874 @param {Number} increment The amount to increment by. Defaults to 1
27875 @return {Number} The new property value
27876 @public
27877 */
27878 incrementProperty(keyName, increment = 1) {
27879 (true && !(!isNaN(parseFloat(increment)) && isFinite(increment)) && (0, _debug.assert)('Must pass a numeric value to incrementProperty', !isNaN(parseFloat(increment)) && isFinite(increment)));
27880 return (0, _metal.set)(this, keyName, (parseFloat((0, _metal.get)(this, keyName)) || 0) + increment);
27881 },
27882
27883 /**
27884 Set the value of a property to the current value minus some amount.
27885 ```javascript
27886 player.decrementProperty('lives');
27887 orc.decrementProperty('health', 5);
27888 ```
27889 @method decrementProperty
27890 @param {String} keyName The name of the property to decrement
27891 @param {Number} decrement The amount to decrement by. Defaults to 1
27892 @return {Number} The new property value
27893 @public
27894 */
27895 decrementProperty(keyName, decrement = 1) {
27896 (true && !(!isNaN(parseFloat(decrement)) && isFinite(decrement)) && (0, _debug.assert)('Must pass a numeric value to decrementProperty', !isNaN(parseFloat(decrement)) && isFinite(decrement)));
27897 return (0, _metal.set)(this, keyName, ((0, _metal.get)(this, keyName) || 0) - decrement);
27898 },
27899
27900 /**
27901 Set the value of a boolean property to the opposite of its
27902 current value.
27903 ```javascript
27904 starship.toggleProperty('warpDriveEngaged');
27905 ```
27906 @method toggleProperty
27907 @param {String} keyName The name of the property to toggle
27908 @return {Boolean} The new property value
27909 @public
27910 */
27911 toggleProperty(keyName) {
27912 return (0, _metal.set)(this, keyName, !(0, _metal.get)(this, keyName));
27913 },
27914
27915 /**
27916 Returns the cached value of a computed property, if it exists.
27917 This allows you to inspect the value of a computed property
27918 without accidentally invoking it if it is intended to be
27919 generated lazily.
27920 @method cacheFor
27921 @param {String} keyName
27922 @return {Object} The cached value of the computed property, if any
27923 @public
27924 */
27925 cacheFor(keyName) {
27926 var meta = (0, _meta.peekMeta)(this);
27927
27928 if (meta !== null) {
27929 return meta.valueFor(keyName);
27930 }
27931 }
27932
27933 });
27934
27935 _exports.default = _default;
27936});
27937define("@ember/-internals/runtime/lib/mixins/promise_proxy", ["exports", "@ember/-internals/metal", "@ember/error"], function (_exports, _metal, _error) {
27938 "use strict";
27939
27940 Object.defineProperty(_exports, "__esModule", {
27941 value: true
27942 });
27943 _exports.default = void 0;
27944
27945 /**
27946 @module @ember/object
27947 */
27948 function tap(proxy, promise) {
27949 (0, _metal.setProperties)(proxy, {
27950 isFulfilled: false,
27951 isRejected: false
27952 });
27953 return promise.then(value => {
27954 if (!proxy.isDestroyed && !proxy.isDestroying) {
27955 (0, _metal.setProperties)(proxy, {
27956 content: value,
27957 isFulfilled: true
27958 });
27959 }
27960
27961 return value;
27962 }, reason => {
27963 if (!proxy.isDestroyed && !proxy.isDestroying) {
27964 (0, _metal.setProperties)(proxy, {
27965 reason,
27966 isRejected: true
27967 });
27968 }
27969
27970 throw reason;
27971 }, 'Ember: PromiseProxy');
27972 }
27973 /**
27974 A low level mixin making ObjectProxy promise-aware.
27975
27976 ```javascript
27977 import { resolve } from 'rsvp';
27978 import $ from 'jquery';
27979 import ObjectProxy from '@ember/object/proxy';
27980 import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
27981
27982 let ObjectPromiseProxy = ObjectProxy.extend(PromiseProxyMixin);
27983
27984 let proxy = ObjectPromiseProxy.create({
27985 promise: resolve($.getJSON('/some/remote/data.json'))
27986 });
27987
27988 proxy.then(function(json){
27989 // the json
27990 }, function(reason) {
27991 // the reason why you have no json
27992 });
27993 ```
27994
27995 the proxy has bindable attributes which
27996 track the promises life cycle
27997
27998 ```javascript
27999 proxy.get('isPending') //=> true
28000 proxy.get('isSettled') //=> false
28001 proxy.get('isRejected') //=> false
28002 proxy.get('isFulfilled') //=> false
28003 ```
28004
28005 When the $.getJSON completes, and the promise is fulfilled
28006 with json, the life cycle attributes will update accordingly.
28007 Note that $.getJSON doesn't return an ECMA specified promise,
28008 it is useful to wrap this with an `RSVP.resolve` so that it behaves
28009 as a spec compliant promise.
28010
28011 ```javascript
28012 proxy.get('isPending') //=> false
28013 proxy.get('isSettled') //=> true
28014 proxy.get('isRejected') //=> false
28015 proxy.get('isFulfilled') //=> true
28016 ```
28017
28018 As the proxy is an ObjectProxy, and the json now its content,
28019 all the json properties will be available directly from the proxy.
28020
28021 ```javascript
28022 // Assuming the following json:
28023 {
28024 firstName: 'Stefan',
28025 lastName: 'Penner'
28026 }
28027
28028 // both properties will accessible on the proxy
28029 proxy.get('firstName') //=> 'Stefan'
28030 proxy.get('lastName') //=> 'Penner'
28031 ```
28032
28033 @class PromiseProxyMixin
28034 @public
28035 */
28036
28037
28038 var _default = _metal.Mixin.create({
28039 /**
28040 If the proxied promise is rejected this will contain the reason
28041 provided.
28042 @property reason
28043 @default null
28044 @public
28045 */
28046 reason: null,
28047
28048 /**
28049 Once the proxied promise has settled this will become `false`.
28050 @property isPending
28051 @default true
28052 @public
28053 */
28054 isPending: (0, _metal.computed)('isSettled', function () {
28055 return !(0, _metal.get)(this, 'isSettled');
28056 }).readOnly(),
28057
28058 /**
28059 Once the proxied promise has settled this will become `true`.
28060 @property isSettled
28061 @default false
28062 @public
28063 */
28064 isSettled: (0, _metal.computed)('isRejected', 'isFulfilled', function () {
28065 return (0, _metal.get)(this, 'isRejected') || (0, _metal.get)(this, 'isFulfilled');
28066 }).readOnly(),
28067
28068 /**
28069 Will become `true` if the proxied promise is rejected.
28070 @property isRejected
28071 @default false
28072 @public
28073 */
28074 isRejected: false,
28075
28076 /**
28077 Will become `true` if the proxied promise is fulfilled.
28078 @property isFulfilled
28079 @default false
28080 @public
28081 */
28082 isFulfilled: false,
28083
28084 /**
28085 The promise whose fulfillment value is being proxied by this object.
28086 This property must be specified upon creation, and should not be
28087 changed once created.
28088 Example:
28089 ```javascript
28090 import ObjectProxy from '@ember/object/proxy';
28091 import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
28092 ObjectProxy.extend(PromiseProxyMixin).create({
28093 promise: <thenable>
28094 });
28095 ```
28096 @property promise
28097 @public
28098 */
28099 promise: (0, _metal.computed)({
28100 get() {
28101 throw new _error.default("PromiseProxy's promise must be set");
28102 },
28103
28104 set(key, promise) {
28105 return tap(this, promise);
28106 }
28107
28108 }),
28109
28110 /**
28111 An alias to the proxied promise's `then`.
28112 See RSVP.Promise.then.
28113 @method then
28114 @param {Function} callback
28115 @return {RSVP.Promise}
28116 @public
28117 */
28118 then: promiseAlias('then'),
28119
28120 /**
28121 An alias to the proxied promise's `catch`.
28122 See RSVP.Promise.catch.
28123 @method catch
28124 @param {Function} callback
28125 @return {RSVP.Promise}
28126 @since 1.3.0
28127 @public
28128 */
28129 catch: promiseAlias('catch'),
28130
28131 /**
28132 An alias to the proxied promise's `finally`.
28133 See RSVP.Promise.finally.
28134 @method finally
28135 @param {Function} callback
28136 @return {RSVP.Promise}
28137 @since 1.3.0
28138 @public
28139 */
28140 finally: promiseAlias('finally')
28141 });
28142
28143 _exports.default = _default;
28144
28145 function promiseAlias(name) {
28146 return function () {
28147 var promise = (0, _metal.get)(this, 'promise');
28148 return promise[name](...arguments);
28149 };
28150 }
28151});
28152define("@ember/-internals/runtime/lib/mixins/registry_proxy", ["exports", "@ember/debug", "@ember/-internals/metal"], function (_exports, _debug, _metal) {
28153 "use strict";
28154
28155 Object.defineProperty(_exports, "__esModule", {
28156 value: true
28157 });
28158 _exports.default = void 0;
28159
28160 /**
28161 @module ember
28162 */
28163
28164 /**
28165 RegistryProxyMixin is used to provide public access to specific
28166 registry functionality.
28167
28168 @class RegistryProxyMixin
28169 @private
28170 */
28171 var _default = _metal.Mixin.create({
28172 __registry__: null,
28173
28174 /**
28175 Given a fullName return the corresponding factory.
28176 @public
28177 @method resolveRegistration
28178 @param {String} fullName
28179 @return {Function} fullName's factory
28180 */
28181 resolveRegistration(fullName, options) {
28182 (true && !(this.__registry__.isValidFullName(fullName)) && (0, _debug.assert)('fullName must be a proper full name', this.__registry__.isValidFullName(fullName)));
28183 return this.__registry__.resolve(fullName, options);
28184 },
28185
28186 /**
28187 Registers a factory that can be used for dependency injection (with
28188 `inject`) or for service lookup. Each factory is registered with
28189 a full name including two parts: `type:name`.
28190 A simple example:
28191 ```javascript
28192 import Application from '@ember/application';
28193 import EmberObject from '@ember/object';
28194 let App = Application.create();
28195 App.Orange = EmberObject.extend();
28196 App.register('fruit:favorite', App.Orange);
28197 ```
28198 Ember will resolve factories from the `App` namespace automatically.
28199 For example `App.CarsController` will be discovered and returned if
28200 an application requests `controller:cars`.
28201 An example of registering a controller with a non-standard name:
28202 ```javascript
28203 import Application from '@ember/application';
28204 import Controller from '@ember/controller';
28205 let App = Application.create();
28206 let Session = Controller.extend();
28207 App.register('controller:session', Session);
28208 // The Session controller can now be treated like a normal controller,
28209 // despite its non-standard name.
28210 App.ApplicationController = Controller.extend({
28211 needs: ['session']
28212 });
28213 ```
28214 Registered factories are **instantiated** by having `create`
28215 called on them. Additionally they are **singletons**, each time
28216 they are looked up they return the same instance.
28217 Some examples modifying that default behavior:
28218 ```javascript
28219 import Application from '@ember/application';
28220 import EmberObject from '@ember/object';
28221 let App = Application.create();
28222 App.Person = EmberObject.extend();
28223 App.Orange = EmberObject.extend();
28224 App.Email = EmberObject.extend();
28225 App.session = EmberObject.create();
28226 App.register('model:user', App.Person, { singleton: false });
28227 App.register('fruit:favorite', App.Orange);
28228 App.register('communication:main', App.Email, { singleton: false });
28229 App.register('session', App.session, { instantiate: false });
28230 ```
28231 @method register
28232 @param fullName {String} type:name (e.g., 'model:user')
28233 @param factory {any} (e.g., App.Person)
28234 @param options {Object} (optional) disable instantiation or singleton usage
28235 @public
28236 */
28237 register: registryAlias('register'),
28238
28239 /**
28240 Unregister a factory.
28241 ```javascript
28242 import Application from '@ember/application';
28243 import EmberObject from '@ember/object';
28244 let App = Application.create();
28245 let User = EmberObject.extend();
28246 App.register('model:user', User);
28247 App.resolveRegistration('model:user').create() instanceof User //=> true
28248 App.unregister('model:user')
28249 App.resolveRegistration('model:user') === undefined //=> true
28250 ```
28251 @public
28252 @method unregister
28253 @param {String} fullName
28254 */
28255 unregister: registryAlias('unregister'),
28256
28257 /**
28258 Check if a factory is registered.
28259 @public
28260 @method hasRegistration
28261 @param {String} fullName
28262 @return {Boolean}
28263 */
28264 hasRegistration: registryAlias('has'),
28265
28266 /**
28267 Return a specific registered option for a particular factory.
28268 @public
28269 @method registeredOption
28270 @param {String} fullName
28271 @param {String} optionName
28272 @return {Object} options
28273 */
28274 registeredOption: registryAlias('getOption'),
28275
28276 /**
28277 Register options for a particular factory.
28278 @public
28279 @method registerOptions
28280 @param {String} fullName
28281 @param {Object} options
28282 */
28283 registerOptions: registryAlias('options'),
28284
28285 /**
28286 Return registered options for a particular factory.
28287 @public
28288 @method registeredOptions
28289 @param {String} fullName
28290 @return {Object} options
28291 */
28292 registeredOptions: registryAlias('getOptions'),
28293
28294 /**
28295 Allow registering options for all factories of a type.
28296 ```javascript
28297 import Application from '@ember/application';
28298 let App = Application.create();
28299 let appInstance = App.buildInstance();
28300 // if all of type `connection` must not be singletons
28301 appInstance.registerOptionsForType('connection', { singleton: false });
28302 appInstance.register('connection:twitter', TwitterConnection);
28303 appInstance.register('connection:facebook', FacebookConnection);
28304 let twitter = appInstance.lookup('connection:twitter');
28305 let twitter2 = appInstance.lookup('connection:twitter');
28306 twitter === twitter2; // => false
28307 let facebook = appInstance.lookup('connection:facebook');
28308 let facebook2 = appInstance.lookup('connection:facebook');
28309 facebook === facebook2; // => false
28310 ```
28311 @public
28312 @method registerOptionsForType
28313 @param {String} type
28314 @param {Object} options
28315 */
28316 registerOptionsForType: registryAlias('optionsForType'),
28317
28318 /**
28319 Return the registered options for all factories of a type.
28320 @public
28321 @method registeredOptionsForType
28322 @param {String} type
28323 @return {Object} options
28324 */
28325 registeredOptionsForType: registryAlias('getOptionsForType'),
28326
28327 /**
28328 Define a dependency injection onto a specific factory or all factories
28329 of a type.
28330 When Ember instantiates a controller, view, or other framework component
28331 it can attach a dependency to that component. This is often used to
28332 provide services to a set of framework components.
28333 An example of providing a session object to all controllers:
28334 ```javascript
28335 import { alias } from '@ember/object/computed';
28336 import Application from '@ember/application';
28337 import Controller from '@ember/controller';
28338 import EmberObject from '@ember/object';
28339 let App = Application.create();
28340 let Session = EmberObject.extend({ isAuthenticated: false });
28341 // A factory must be registered before it can be injected
28342 App.register('session:main', Session);
28343 // Inject 'session:main' onto all factories of the type 'controller'
28344 // with the name 'session'
28345 App.inject('controller', 'session', 'session:main');
28346 App.IndexController = Controller.extend({
28347 isLoggedIn: alias('session.isAuthenticated')
28348 });
28349 ```
28350 Injections can also be performed on specific factories.
28351 ```javascript
28352 App.inject(<full_name or type>, <property name>, <full_name>)
28353 App.inject('route', 'source', 'source:main')
28354 App.inject('route:application', 'email', 'model:email')
28355 ```
28356 It is important to note that injections can only be performed on
28357 classes that are instantiated by Ember itself. Instantiating a class
28358 directly (via `create` or `new`) bypasses the dependency injection
28359 system.
28360 @public
28361 @method inject
28362 @param factoryNameOrType {String}
28363 @param property {String}
28364 @param injectionName {String}
28365 **/
28366 inject: registryAlias('injection')
28367 });
28368
28369 _exports.default = _default;
28370
28371 function registryAlias(name) {
28372 return function () {
28373 return this.__registry__[name](...arguments);
28374 };
28375 }
28376});
28377define("@ember/-internals/runtime/lib/mixins/target_action_support", ["exports", "@ember/-internals/environment", "@ember/-internals/metal", "@ember/debug"], function (_exports, _environment, _metal, _debug) {
28378 "use strict";
28379
28380 Object.defineProperty(_exports, "__esModule", {
28381 value: true
28382 });
28383 _exports.default = void 0;
28384
28385 /**
28386 @module ember
28387 */
28388
28389 /**
28390 `Ember.TargetActionSupport` is a mixin that can be included in a class
28391 to add a `triggerAction` method with semantics similar to the Handlebars
28392 `{{action}}` helper. In normal Ember usage, the `{{action}}` helper is
28393 usually the best choice. This mixin is most often useful when you are
28394 doing more complex event handling in Components.
28395
28396 @class TargetActionSupport
28397 @namespace Ember
28398 @extends Mixin
28399 @private
28400 */
28401 var _default = _metal.Mixin.create({
28402 target: null,
28403 action: null,
28404 actionContext: null,
28405 actionContextObject: (0, _metal.computed)('actionContext', function () {
28406 var actionContext = (0, _metal.get)(this, 'actionContext');
28407
28408 if (typeof actionContext === 'string') {
28409 var value = (0, _metal.get)(this, actionContext);
28410
28411 if (value === undefined) {
28412 value = (0, _metal.get)(_environment.context.lookup, actionContext);
28413 }
28414
28415 return value;
28416 } else {
28417 return actionContext;
28418 }
28419 }),
28420
28421 /**
28422 Send an `action` with an `actionContext` to a `target`. The action, actionContext
28423 and target will be retrieved from properties of the object. For example:
28424 ```javascript
28425 import { alias } from '@ember/object/computed';
28426 App.SaveButtonView = Ember.View.extend(Ember.TargetActionSupport, {
28427 target: alias('controller'),
28428 action: 'save',
28429 actionContext: alias('context'),
28430 click() {
28431 this.triggerAction(); // Sends the `save` action, along with the current context
28432 // to the current controller
28433 }
28434 });
28435 ```
28436 The `target`, `action`, and `actionContext` can be provided as properties of
28437 an optional object argument to `triggerAction` as well.
28438 ```javascript
28439 App.SaveButtonView = Ember.View.extend(Ember.TargetActionSupport, {
28440 click() {
28441 this.triggerAction({
28442 action: 'save',
28443 target: this.get('controller'),
28444 actionContext: this.get('context')
28445 }); // Sends the `save` action, along with the current context
28446 // to the current controller
28447 }
28448 });
28449 ```
28450 The `actionContext` defaults to the object you are mixing `TargetActionSupport` into.
28451 But `target` and `action` must be specified either as properties or with the argument
28452 to `triggerAction`, or a combination:
28453 ```javascript
28454 import { alias } from '@ember/object/computed';
28455 App.SaveButtonView = Ember.View.extend(Ember.TargetActionSupport, {
28456 target: alias('controller'),
28457 click() {
28458 this.triggerAction({
28459 action: 'save'
28460 }); // Sends the `save` action, along with a reference to `this`,
28461 // to the current controller
28462 }
28463 });
28464 ```
28465 @method triggerAction
28466 @param opts {Object} (optional, with the optional keys action, target and/or actionContext)
28467 @return {Boolean} true if the action was sent successfully and did not return false
28468 @private
28469 */
28470 triggerAction(opts = {}) {
28471 var {
28472 action,
28473 target,
28474 actionContext
28475 } = opts;
28476 action = action || (0, _metal.get)(this, 'action');
28477 target = target || getTarget(this);
28478
28479 if (actionContext === undefined) {
28480 actionContext = (0, _metal.get)(this, 'actionContextObject') || this;
28481 }
28482
28483 if (target && action) {
28484 var ret;
28485
28486 if (target.send) {
28487 ret = target.send(...[action].concat(actionContext));
28488 } else {
28489 (true && !(typeof target[action] === 'function') && (0, _debug.assert)(`The action '${action}' did not exist on ${target}`, typeof target[action] === 'function'));
28490 ret = target[action](...[].concat(actionContext));
28491 }
28492
28493 if (ret !== false) {
28494 return true;
28495 }
28496 }
28497
28498 return false;
28499 }
28500
28501 });
28502
28503 _exports.default = _default;
28504
28505 function getTarget(instance) {
28506 var target = (0, _metal.get)(instance, 'target');
28507
28508 if (target) {
28509 if (typeof target === 'string') {
28510 var value = (0, _metal.get)(instance, target);
28511
28512 if (value === undefined) {
28513 value = (0, _metal.get)(_environment.context.lookup, target);
28514 }
28515
28516 return value;
28517 } else {
28518 return target;
28519 }
28520 }
28521
28522 if (instance._target) {
28523 return instance._target;
28524 }
28525
28526 return null;
28527 }
28528});
28529define("@ember/-internals/runtime/lib/system/array_proxy", ["exports", "@ember/-internals/metal", "@ember/-internals/utils", "@ember/-internals/runtime/lib/system/object", "@ember/-internals/runtime/lib/mixins/array", "@ember/debug", "@glimmer/validator"], function (_exports, _metal, _utils, _object, _array, _debug, _validator) {
28530 "use strict";
28531
28532 Object.defineProperty(_exports, "__esModule", {
28533 value: true
28534 });
28535 _exports.default = void 0;
28536
28537 /**
28538 @module @ember/array
28539 */
28540 var ARRAY_OBSERVER_MAPPING = {
28541 willChange: '_arrangedContentArrayWillChange',
28542 didChange: '_arrangedContentArrayDidChange'
28543 };
28544 /**
28545 An ArrayProxy wraps any other object that implements `Array` and/or
28546 `MutableArray,` forwarding all requests. This makes it very useful for
28547 a number of binding use cases or other cases where being able to swap
28548 out the underlying array is useful.
28549
28550 A simple example of usage:
28551
28552 ```javascript
28553 import { A } from '@ember/array';
28554 import ArrayProxy from '@ember/array/proxy';
28555
28556 let pets = ['dog', 'cat', 'fish'];
28557 let ap = ArrayProxy.create({ content: A(pets) });
28558
28559 ap.get('firstObject'); // 'dog'
28560 ap.set('content', ['amoeba', 'paramecium']);
28561 ap.get('firstObject'); // 'amoeba'
28562 ```
28563
28564 This class can also be useful as a layer to transform the contents of
28565 an array, as they are accessed. This can be done by overriding
28566 `objectAtContent`:
28567
28568 ```javascript
28569 import { A } from '@ember/array';
28570 import ArrayProxy from '@ember/array/proxy';
28571
28572 let pets = ['dog', 'cat', 'fish'];
28573 let ap = ArrayProxy.create({
28574 content: A(pets),
28575 objectAtContent: function(idx) {
28576 return this.get('content').objectAt(idx).toUpperCase();
28577 }
28578 });
28579
28580 ap.get('firstObject'); // . 'DOG'
28581 ```
28582
28583 When overriding this class, it is important to place the call to
28584 `_super` *after* setting `content` so the internal observers have
28585 a chance to fire properly:
28586
28587 ```javascript
28588 import { A } from '@ember/array';
28589 import ArrayProxy from '@ember/array/proxy';
28590
28591 export default ArrayProxy.extend({
28592 init() {
28593 this.set('content', A(['dog', 'cat', 'fish']));
28594 this._super(...arguments);
28595 }
28596 });
28597 ```
28598
28599 @class ArrayProxy
28600 @extends EmberObject
28601 @uses MutableArray
28602 @public
28603 */
28604
28605 class ArrayProxy extends _object.default {
28606 init() {
28607 super.init(...arguments);
28608 /*
28609 `this._objectsDirtyIndex` determines which indexes in the `this._objects`
28610 cache are dirty.
28611 If `this._objectsDirtyIndex === -1` then no indexes are dirty.
28612 Otherwise, an index `i` is dirty if `i >= this._objectsDirtyIndex`.
28613 Calling `objectAt` with a dirty index will cause the `this._objects`
28614 cache to be recomputed.
28615 */
28616
28617 this._objectsDirtyIndex = 0;
28618 this._objects = null;
28619 this._lengthDirty = true;
28620 this._length = 0;
28621 this._arrangedContent = null;
28622 this._arrangedContentIsUpdating = false;
28623 this._arrangedContentTag = null;
28624 this._arrangedContentRevision = null;
28625 this._lengthTag = null;
28626 this._arrTag = null;
28627 }
28628
28629 [_metal.PROPERTY_DID_CHANGE]() {
28630 this._revalidate();
28631 }
28632
28633 [_metal.CUSTOM_TAG_FOR](key) {
28634 if (key === '[]') {
28635 this._revalidate();
28636
28637 return this._arrTag;
28638 } else if (key === 'length') {
28639 this._revalidate();
28640
28641 return this._lengthTag;
28642 }
28643
28644 return (0, _validator.tagFor)(this, key);
28645 }
28646
28647 willDestroy() {
28648 this._removeArrangedContentArrayObserver();
28649 }
28650 /**
28651 The content array. Must be an object that implements `Array` and/or
28652 `MutableArray.`
28653 @property content
28654 @type EmberArray
28655 @public
28656 */
28657
28658 /**
28659 Should actually retrieve the object at the specified index from the
28660 content. You can override this method in subclasses to transform the
28661 content item to something new.
28662 This method will only be called if content is non-`null`.
28663 @method objectAtContent
28664 @param {Number} idx The index to retrieve.
28665 @return {Object} the value or undefined if none found
28666 @public
28667 */
28668
28669
28670 objectAtContent(idx) {
28671 return (0, _metal.objectAt)((0, _metal.get)(this, 'arrangedContent'), idx);
28672 } // See additional docs for `replace` from `MutableArray`:
28673 // https://api.emberjs.com/ember/release/classes/MutableArray/methods/replace?anchor=replace
28674
28675
28676 replace(idx, amt, objects) {
28677 (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')));
28678 this.replaceContent(idx, amt, objects);
28679 }
28680 /**
28681 Should actually replace the specified objects on the content array.
28682 You can override this method in subclasses to transform the content item
28683 into something new.
28684 This method will only be called if content is non-`null`.
28685 @method replaceContent
28686 @param {Number} idx The starting index
28687 @param {Number} amt The number of items to remove from the content.
28688 @param {EmberArray} objects Optional array of objects to insert or null if no
28689 objects.
28690 @return {void}
28691 @public
28692 */
28693
28694
28695 replaceContent(idx, amt, objects) {
28696 (0, _metal.get)(this, 'content').replace(idx, amt, objects);
28697 } // Overriding objectAt is not supported.
28698
28699
28700 objectAt(idx) {
28701 this._revalidate();
28702
28703 if (this._objects === null) {
28704 this._objects = [];
28705 }
28706
28707 if (this._objectsDirtyIndex !== -1 && idx >= this._objectsDirtyIndex) {
28708 var arrangedContent = (0, _metal.get)(this, 'arrangedContent');
28709
28710 if (arrangedContent) {
28711 var length = this._objects.length = (0, _metal.get)(arrangedContent, 'length');
28712
28713 for (var i = this._objectsDirtyIndex; i < length; i++) {
28714 this._objects[i] = this.objectAtContent(i);
28715 }
28716 } else {
28717 this._objects.length = 0;
28718 }
28719
28720 this._objectsDirtyIndex = -1;
28721 }
28722
28723 return this._objects[idx];
28724 } // Overriding length is not supported.
28725
28726
28727 get length() {
28728 this._revalidate();
28729
28730 if (this._lengthDirty) {
28731 var arrangedContent = (0, _metal.get)(this, 'arrangedContent');
28732 this._length = arrangedContent ? (0, _metal.get)(arrangedContent, 'length') : 0;
28733 this._lengthDirty = false;
28734 }
28735
28736 (0, _validator.consumeTag)(this._lengthTag);
28737 return this._length;
28738 }
28739
28740 set length(value) {
28741 var length = this.length;
28742 var removedCount = length - value;
28743 var added;
28744
28745 if (removedCount === 0) {
28746 return;
28747 } else if (removedCount < 0) {
28748 added = new Array(-removedCount);
28749 removedCount = 0;
28750 }
28751
28752 var content = (0, _metal.get)(this, 'content');
28753
28754 if (content) {
28755 (0, _metal.replace)(content, value, removedCount, added);
28756
28757 this._invalidate();
28758 }
28759 }
28760
28761 _updateArrangedContentArray(arrangedContent) {
28762 var oldLength = this._objects === null ? 0 : this._objects.length;
28763 var newLength = arrangedContent ? (0, _metal.get)(arrangedContent, 'length') : 0;
28764
28765 this._removeArrangedContentArrayObserver();
28766
28767 this.arrayContentWillChange(0, oldLength, newLength);
28768
28769 this._invalidate();
28770
28771 this.arrayContentDidChange(0, oldLength, newLength);
28772
28773 this._addArrangedContentArrayObserver(arrangedContent);
28774 }
28775
28776 _addArrangedContentArrayObserver(arrangedContent) {
28777 if (arrangedContent && !arrangedContent.isDestroyed) {
28778 (true && !(arrangedContent !== this) && (0, _debug.assert)("Can't set ArrayProxy's content to itself", arrangedContent !== this));
28779 (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));
28780 (0, _metal.addArrayObserver)(arrangedContent, this, ARRAY_OBSERVER_MAPPING);
28781 this._arrangedContent = arrangedContent;
28782 }
28783 }
28784
28785 _removeArrangedContentArrayObserver() {
28786 if (this._arrangedContent) {
28787 (0, _metal.removeArrayObserver)(this._arrangedContent, this, ARRAY_OBSERVER_MAPPING);
28788 }
28789 }
28790
28791 _arrangedContentArrayWillChange() {}
28792
28793 _arrangedContentArrayDidChange(proxy, idx, removedCnt, addedCnt) {
28794 this.arrayContentWillChange(idx, removedCnt, addedCnt);
28795 var dirtyIndex = idx;
28796
28797 if (dirtyIndex < 0) {
28798 var length = (0, _metal.get)(this._arrangedContent, 'length');
28799 dirtyIndex += length + removedCnt - addedCnt;
28800 }
28801
28802 if (this._objectsDirtyIndex === -1 || this._objectsDirtyIndex > dirtyIndex) {
28803 this._objectsDirtyIndex = dirtyIndex;
28804 }
28805
28806 this._lengthDirty = true;
28807 this.arrayContentDidChange(idx, removedCnt, addedCnt);
28808 }
28809
28810 _invalidate() {
28811 this._objectsDirtyIndex = 0;
28812 this._lengthDirty = true;
28813 }
28814
28815 _revalidate() {
28816 if (this._arrangedContentIsUpdating === true) return;
28817
28818 if (this._arrangedContentTag === null || !(0, _validator.validateTag)(this._arrangedContentTag, this._arrangedContentRevision)) {
28819 var arrangedContent = this.get('arrangedContent');
28820
28821 if (this._arrangedContentTag === null) {
28822 // This is the first time the proxy has been setup, only add the observer
28823 // don't trigger any events
28824 this._addArrangedContentArrayObserver(arrangedContent);
28825 } else {
28826 this._arrangedContentIsUpdating = true;
28827
28828 this._updateArrangedContentArray(arrangedContent);
28829
28830 this._arrangedContentIsUpdating = false;
28831 }
28832
28833 var arrangedContentTag = this._arrangedContentTag = (0, _validator.tagFor)(this, 'arrangedContent');
28834 this._arrangedContentRevision = (0, _validator.valueForTag)(this._arrangedContentTag);
28835
28836 if ((0, _utils.isObject)(arrangedContent)) {
28837 this._lengthTag = (0, _validator.combine)([arrangedContentTag, (0, _metal.tagForProperty)(arrangedContent, 'length')]);
28838 this._arrTag = (0, _validator.combine)([arrangedContentTag, (0, _metal.tagForProperty)(arrangedContent, '[]')]);
28839 } else {
28840 this._lengthTag = this._arrTag = arrangedContentTag;
28841 }
28842 }
28843 }
28844
28845 }
28846
28847 _exports.default = ArrayProxy;
28848 ArrayProxy.reopen(_array.MutableArray, {
28849 /**
28850 The array that the proxy pretends to be. In the default `ArrayProxy`
28851 implementation, this and `content` are the same. Subclasses of `ArrayProxy`
28852 can override this property to provide things like sorting and filtering.
28853 @property arrangedContent
28854 @public
28855 */
28856 arrangedContent: (0, _metal.alias)('content'),
28857
28858 // Array proxies don't need to notify when they change since their `[]` tag is
28859 // already dependent on the `[]` tag of `arrangedContent`
28860 arrayContentDidChange(startIdx, removeAmt, addAmt) {
28861 return (0, _metal.arrayContentDidChange)(this, startIdx, removeAmt, addAmt, false);
28862 }
28863
28864 });
28865});
28866define("@ember/-internals/runtime/lib/system/core_object", ["exports", "@ember/-internals/container", "@ember/-internals/owner", "@ember/polyfills", "@ember/-internals/utils", "@ember/-internals/meta", "@ember/-internals/metal", "@ember/-internals/runtime/lib/mixins/action_handler", "@ember/debug", "@glimmer/runtime"], function (_exports, _container, _owner, _polyfills, _utils, _meta2, _metal, _action_handler, _debug, _runtime) {
28867 "use strict";
28868
28869 Object.defineProperty(_exports, "__esModule", {
28870 value: true
28871 });
28872 _exports.default = void 0;
28873
28874 /**
28875 @module @ember/object
28876 */
28877 var reopen = _metal.Mixin.prototype.reopen;
28878 var wasApplied = new _polyfills._WeakSet();
28879 var prototypeMixinMap = new WeakMap();
28880 var initCalled = true
28881 /* DEBUG */
28882 ? new _polyfills._WeakSet() : undefined; // only used in debug builds to enable the proxy trap
28883
28884 var destroyCalled = new Set();
28885
28886 function ensureDestroyCalled(instance) {
28887 if (!destroyCalled.has(instance)) {
28888 instance.destroy();
28889 }
28890 }
28891
28892 function initialize(obj, properties) {
28893 var m = (0, _meta2.meta)(obj);
28894
28895 if (properties !== undefined) {
28896 (true && !(typeof properties === 'object' && properties !== null) && (0, _debug.assert)('EmberObject.create only accepts objects.', typeof properties === 'object' && properties !== null));
28897 (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)));
28898 var concatenatedProperties = obj.concatenatedProperties;
28899 var mergedProperties = obj.mergedProperties;
28900 var hasConcatenatedProps = concatenatedProperties !== undefined && concatenatedProperties.length > 0;
28901 var hasMergedProps = mergedProperties !== undefined && mergedProperties.length > 0;
28902 var keyNames = Object.keys(properties);
28903
28904 for (var i = 0; i < keyNames.length; i++) {
28905 var keyName = keyNames[i];
28906 var value = properties[keyName];
28907 (true && !(!(0, _metal.isClassicDecorator)(value)) && (0, _debug.assert)('EmberObject.create no longer supports defining computed ' + 'properties. Define computed properties using extend() or reopen() ' + 'before calling create().', !(0, _metal.isClassicDecorator)(value)));
28908 (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)));
28909 (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))));
28910 var possibleDesc = (0, _metal.descriptorForProperty)(obj, keyName, m);
28911 var isDescriptor = possibleDesc !== undefined;
28912
28913 if (!isDescriptor) {
28914 if (hasConcatenatedProps && concatenatedProperties.indexOf(keyName) > -1) {
28915 var baseValue = obj[keyName];
28916
28917 if (baseValue) {
28918 value = (0, _utils.makeArray)(baseValue).concat(value);
28919 } else {
28920 value = (0, _utils.makeArray)(value);
28921 }
28922 }
28923
28924 if (hasMergedProps && mergedProperties.indexOf(keyName) > -1) {
28925 var _baseValue = obj[keyName];
28926 value = (0, _polyfills.assign)({}, _baseValue, value);
28927 }
28928 }
28929
28930 if (isDescriptor) {
28931 possibleDesc.set(obj, keyName, value);
28932 } else if (typeof obj.setUnknownProperty === 'function' && !(keyName in obj)) {
28933 obj.setUnknownProperty(keyName, value);
28934 } else {
28935 if (true
28936 /* DEBUG */
28937 ) {
28938 (0, _metal.defineProperty)(obj, keyName, null, value, m); // setup mandatory setter
28939 } else {
28940 obj[keyName] = value;
28941 }
28942 }
28943 }
28944 } // using DEBUG here to avoid the extraneous variable when not needed
28945
28946
28947 if (true
28948 /* DEBUG */
28949 ) {
28950 initCalled.add(obj);
28951 }
28952
28953 obj.init(properties);
28954 m.unsetInitializing();
28955 var observerEvents = m.observerEvents();
28956
28957 if (observerEvents !== undefined) {
28958 for (var _i = 0; _i < observerEvents.length; _i++) {
28959 (0, _metal.activateObserver)(obj, observerEvents[_i].event, observerEvents[_i].sync);
28960 }
28961 }
28962
28963 (0, _metal.sendEvent)(obj, 'init', undefined, undefined, undefined, m);
28964 }
28965 /**
28966 `CoreObject` is the base class for all Ember constructs. It establishes a
28967 class system based on Ember's Mixin system, and provides the basis for the
28968 Ember Object Model. `CoreObject` should generally not be used directly,
28969 instead you should use `EmberObject`.
28970
28971 ## Usage
28972
28973 You can define a class by extending from `CoreObject` using the `extend`
28974 method:
28975
28976 ```js
28977 const Person = CoreObject.extend({
28978 name: 'Tomster',
28979 });
28980 ```
28981
28982 For detailed usage, see the [Object Model](https://guides.emberjs.com/release/object-model/)
28983 section of the guides.
28984
28985 ## Usage with Native Classes
28986
28987 Native JavaScript `class` syntax can be used to extend from any `CoreObject`
28988 based class:
28989
28990 ```js
28991 class Person extends CoreObject {
28992 init() {
28993 super.init(...arguments);
28994 this.name = 'Tomster';
28995 }
28996 }
28997 ```
28998
28999 Some notes about `class` usage:
29000
29001 * `new` syntax is not currently supported with classes that extend from
29002 `EmberObject` or `CoreObject`. You must continue to use the `create` method
29003 when making new instances of classes, even if they are defined using native
29004 class syntax. If you want to use `new` syntax, consider creating classes
29005 which do _not_ extend from `EmberObject` or `CoreObject`. Ember features,
29006 such as computed properties and decorators, will still work with base-less
29007 classes.
29008 * Instead of using `this._super()`, you must use standard `super` syntax in
29009 native classes. See the [MDN docs on classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Super_class_calls_with_super)
29010 for more details.
29011 * Native classes support using [constructors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Constructor)
29012 to set up newly-created instances. Ember uses these to, among other things,
29013 support features that need to retrieve other entities by name, like Service
29014 injection and `getOwner`. To ensure your custom instance setup logic takes
29015 place after this important work is done, avoid using the `constructor` in
29016 favor of `init`.
29017 * Properties passed to `create` will be available on the instance by the time
29018 `init` runs, so any code that requires these values should work at that
29019 time.
29020 * Using native classes, and switching back to the old Ember Object model is
29021 fully supported.
29022
29023 @class CoreObject
29024 @public
29025 */
29026
29027
29028 class CoreObject {
29029 constructor(owner) {
29030 // setOwner has to set both OWNER and LEGACY_OWNER for backwards compatibility, and
29031 // LEGACY_OWNER is enumerable, so setting it would add an enumerable property to the object,
29032 // so we just set `OWNER` directly here.
29033 this[_owner.OWNER] = owner; // prepare prototype...
29034
29035 this.constructor.proto();
29036 var self = this;
29037
29038 if (true
29039 /* DEBUG */
29040 && _utils.HAS_NATIVE_PROXY && typeof self.unknownProperty === 'function') {
29041 var messageFor = (obj, property) => {
29042 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.`;
29043 };
29044 /* globals Proxy Reflect */
29045
29046
29047 self = new Proxy(this, {
29048 get(target, property, receiver) {
29049 if (property === _metal.PROXY_CONTENT) {
29050 return target;
29051 } else if ( // init called will be set on the proxy, not the target, so get with the receiver
29052 !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) {
29053 return Reflect.get(target, property, receiver);
29054 }
29055
29056 var value = target.unknownProperty.call(receiver, property);
29057
29058 if (typeof value !== 'function') {
29059 (true && !(value === undefined || value === null) && (0, _debug.assert)(messageFor(receiver, property), value === undefined || value === null));
29060 }
29061 }
29062
29063 });
29064 }
29065
29066 (0, _runtime.registerDestructor)(self, ensureDestroyCalled, true);
29067 (0, _runtime.registerDestructor)(self, () => self.willDestroy()); // disable chains
29068
29069 var m = (0, _meta2.meta)(self);
29070 m.setInitializing(); // only return when in debug builds and `self` is the proxy created above
29071
29072 if (true
29073 /* DEBUG */
29074 && self !== this) {
29075 return self;
29076 }
29077 } // Empty setter for absorbing setting the LEGACY_OWNER, which should _not_
29078 // become an enumerable property, and should not be used in general.
29079
29080
29081 set [_owner.LEGACY_OWNER](value) {}
29082
29083 reopen(...args) {
29084 (0, _metal.applyMixin)(this, args);
29085 return this;
29086 }
29087 /**
29088 An overridable method called when objects are instantiated. By default,
29089 does nothing unless it is overridden during class definition.
29090 Example:
29091 ```javascript
29092 import EmberObject from '@ember/object';
29093 const Person = EmberObject.extend({
29094 init() {
29095 alert(`Name is ${this.get('name')}`);
29096 }
29097 });
29098 let steve = Person.create({
29099 name: 'Steve'
29100 });
29101 // alerts 'Name is Steve'.
29102 ```
29103 NOTE: If you do override `init` for a framework class like `Component`
29104 from `@ember/component`, be sure to call `this._super(...arguments)`
29105 in your `init` declaration!
29106 If you don't, Ember may not have an opportunity to
29107 do important setup work, and you'll see strange behavior in your
29108 application.
29109 @method init
29110 @public
29111 */
29112
29113
29114 init() {}
29115 /**
29116 Defines the properties that will be concatenated from the superclass
29117 (instead of overridden).
29118 By default, when you extend an Ember class a property defined in
29119 the subclass overrides a property with the same name that is defined
29120 in the superclass. However, there are some cases where it is preferable
29121 to build up a property's value by combining the superclass' property
29122 value with the subclass' value. An example of this in use within Ember
29123 is the `classNames` property of `Component` from `@ember/component`.
29124 Here is some sample code showing the difference between a concatenated
29125 property and a normal one:
29126 ```javascript
29127 import EmberObject from '@ember/object';
29128 const Bar = EmberObject.extend({
29129 // Configure which properties to concatenate
29130 concatenatedProperties: ['concatenatedProperty'],
29131 someNonConcatenatedProperty: ['bar'],
29132 concatenatedProperty: ['bar']
29133 });
29134 const FooBar = Bar.extend({
29135 someNonConcatenatedProperty: ['foo'],
29136 concatenatedProperty: ['foo']
29137 });
29138 let fooBar = FooBar.create();
29139 fooBar.get('someNonConcatenatedProperty'); // ['foo']
29140 fooBar.get('concatenatedProperty'); // ['bar', 'foo']
29141 ```
29142 This behavior extends to object creation as well. Continuing the
29143 above example:
29144 ```javascript
29145 let fooBar = FooBar.create({
29146 someNonConcatenatedProperty: ['baz'],
29147 concatenatedProperty: ['baz']
29148 })
29149 fooBar.get('someNonConcatenatedProperty'); // ['baz']
29150 fooBar.get('concatenatedProperty'); // ['bar', 'foo', 'baz']
29151 ```
29152 Adding a single property that is not an array will just add it in the array:
29153 ```javascript
29154 let fooBar = FooBar.create({
29155 concatenatedProperty: 'baz'
29156 })
29157 view.get('concatenatedProperty'); // ['bar', 'foo', 'baz']
29158 ```
29159 Using the `concatenatedProperties` property, we can tell Ember to mix the
29160 content of the properties.
29161 In `Component` the `classNames`, `classNameBindings` and
29162 `attributeBindings` properties are concatenated.
29163 This feature is available for you to use throughout the Ember object model,
29164 although typical app developers are likely to use it infrequently. Since
29165 it changes expectations about behavior of properties, you should properly
29166 document its usage in each individual concatenated property (to not
29167 mislead your users to think they can override the property in a subclass).
29168 @property concatenatedProperties
29169 @type Array
29170 @default null
29171 @public
29172 */
29173
29174 /**
29175 Defines the properties that will be merged from the superclass
29176 (instead of overridden).
29177 By default, when you extend an Ember class a property defined in
29178 the subclass overrides a property with the same name that is defined
29179 in the superclass. However, there are some cases where it is preferable
29180 to build up a property's value by merging the superclass property value
29181 with the subclass property's value. An example of this in use within Ember
29182 is the `queryParams` property of routes.
29183 Here is some sample code showing the difference between a merged
29184 property and a normal one:
29185 ```javascript
29186 import EmberObject from '@ember/object';
29187 const Bar = EmberObject.extend({
29188 // Configure which properties are to be merged
29189 mergedProperties: ['mergedProperty'],
29190 someNonMergedProperty: {
29191 nonMerged: 'superclass value of nonMerged'
29192 },
29193 mergedProperty: {
29194 page: { replace: false },
29195 limit: { replace: true }
29196 }
29197 });
29198 const FooBar = Bar.extend({
29199 someNonMergedProperty: {
29200 completelyNonMerged: 'subclass value of nonMerged'
29201 },
29202 mergedProperty: {
29203 limit: { replace: false }
29204 }
29205 });
29206 let fooBar = FooBar.create();
29207 fooBar.get('someNonMergedProperty');
29208 // => { completelyNonMerged: 'subclass value of nonMerged' }
29209 //
29210 // Note the entire object, including the nonMerged property of
29211 // the superclass object, has been replaced
29212 fooBar.get('mergedProperty');
29213 // => {
29214 // page: {replace: false},
29215 // limit: {replace: false}
29216 // }
29217 //
29218 // Note the page remains from the superclass, and the
29219 // `limit` property's value of `false` has been merged from
29220 // the subclass.
29221 ```
29222 This behavior is not available during object `create` calls. It is only
29223 available at `extend` time.
29224 In `Route` the `queryParams` property is merged.
29225 This feature is available for you to use throughout the Ember object model,
29226 although typical app developers are likely to use it infrequently. Since
29227 it changes expectations about behavior of properties, you should properly
29228 document its usage in each individual merged property (to not
29229 mislead your users to think they can override the property in a subclass).
29230 @property mergedProperties
29231 @type Array
29232 @default null
29233 @public
29234 */
29235
29236 /**
29237 Destroyed object property flag.
29238 if this property is `true` the observers and bindings were already
29239 removed by the effect of calling the `destroy()` method.
29240 @property isDestroyed
29241 @default false
29242 @public
29243 */
29244
29245
29246 get isDestroyed() {
29247 return (0, _runtime.isDestroyed)(this);
29248 }
29249
29250 set isDestroyed(value) {
29251 (true && !(false) && (0, _debug.assert)(`You cannot set \`${this}.isDestroyed\` directly, please use \`.destroy()\`.`, false));
29252 }
29253 /**
29254 Destruction scheduled flag. The `destroy()` method has been called.
29255 The object stays intact until the end of the run loop at which point
29256 the `isDestroyed` flag is set.
29257 @property isDestroying
29258 @default false
29259 @public
29260 */
29261
29262
29263 get isDestroying() {
29264 return (0, _runtime.isDestroying)(this);
29265 }
29266
29267 set isDestroying(value) {
29268 (true && !(false) && (0, _debug.assert)(`You cannot set \`${this}.isDestroying\` directly, please use \`.destroy()\`.`, false));
29269 }
29270 /**
29271 Destroys an object by setting the `isDestroyed` flag and removing its
29272 metadata, which effectively destroys observers and bindings.
29273 If you try to set a property on a destroyed object, an exception will be
29274 raised.
29275 Note that destruction is scheduled for the end of the run loop and does not
29276 happen immediately. It will set an isDestroying flag immediately.
29277 @method destroy
29278 @return {EmberObject} receiver
29279 @public
29280 */
29281
29282
29283 destroy() {
29284 // Used to ensure that manually calling `.destroy()` does not immediately call destroy again
29285 destroyCalled.add(this);
29286
29287 try {
29288 (0, _runtime.destroy)(this);
29289 } finally {
29290 destroyCalled.delete(this);
29291 }
29292
29293 return this;
29294 }
29295 /**
29296 Override to implement teardown.
29297 @method willDestroy
29298 @public
29299 */
29300
29301
29302 willDestroy() {}
29303 /**
29304 Returns a string representation which attempts to provide more information
29305 than Javascript's `toString` typically does, in a generic way for all Ember
29306 objects.
29307 ```javascript
29308 import EmberObject from '@ember/object';
29309 const Person = EmberObject.extend();
29310 person = Person.create();
29311 person.toString(); //=> "<Person:ember1024>"
29312 ```
29313 If the object's class is not defined on an Ember namespace, it will
29314 indicate it is a subclass of the registered superclass:
29315 ```javascript
29316 const Student = Person.extend();
29317 let student = Student.create();
29318 student.toString(); //=> "<(subclass of Person):ember1025>"
29319 ```
29320 If the method `toStringExtension` is defined, its return value will be
29321 included in the output.
29322 ```javascript
29323 const Teacher = Person.extend({
29324 toStringExtension() {
29325 return this.get('fullName');
29326 }
29327 });
29328 teacher = Teacher.create();
29329 teacher.toString(); //=> "<Teacher:ember1026:Tom Dale>"
29330 ```
29331 @method toString
29332 @return {String} string representation
29333 @public
29334 */
29335
29336
29337 toString() {
29338 var hasToStringExtension = typeof this.toStringExtension === 'function';
29339 var extension = hasToStringExtension ? `:${this.toStringExtension()}` : '';
29340 var ret = `<${(0, _utils.getName)(this) || (0, _container.getFactoryFor)(this) || this.constructor.toString()}:${(0, _utils.guidFor)(this)}${extension}>`;
29341 return ret;
29342 }
29343 /**
29344 Creates a new subclass.
29345 ```javascript
29346 import EmberObject from '@ember/object';
29347 const Person = EmberObject.extend({
29348 say(thing) {
29349 alert(thing);
29350 }
29351 });
29352 ```
29353 This defines a new subclass of EmberObject: `Person`. It contains one method: `say()`.
29354 You can also create a subclass from any existing class by calling its `extend()` method.
29355 For example, you might want to create a subclass of Ember's built-in `Component` class:
29356 ```javascript
29357 import Component from '@ember/component';
29358 const PersonComponent = Component.extend({
29359 tagName: 'li',
29360 classNameBindings: ['isAdministrator']
29361 });
29362 ```
29363 When defining a subclass, you can override methods but still access the
29364 implementation of your parent class by calling the special `_super()` method:
29365 ```javascript
29366 import EmberObject from '@ember/object';
29367 const Person = EmberObject.extend({
29368 say(thing) {
29369 let name = this.get('name');
29370 alert(`${name} says: ${thing}`);
29371 }
29372 });
29373 const Soldier = Person.extend({
29374 say(thing) {
29375 this._super(`${thing}, sir!`);
29376 },
29377 march(numberOfHours) {
29378 alert(`${this.get('name')} marches for ${numberOfHours} hours.`);
29379 }
29380 });
29381 let yehuda = Soldier.create({
29382 name: 'Yehuda Katz'
29383 });
29384 yehuda.say('Yes'); // alerts "Yehuda Katz says: Yes, sir!"
29385 ```
29386 The `create()` on line #17 creates an *instance* of the `Soldier` class.
29387 The `extend()` on line #8 creates a *subclass* of `Person`. Any instance
29388 of the `Person` class will *not* have the `march()` method.
29389 You can also pass `Mixin` classes to add additional properties to the subclass.
29390 ```javascript
29391 import EmberObject from '@ember/object';
29392 import Mixin from '@ember/object/mixin';
29393 const Person = EmberObject.extend({
29394 say(thing) {
29395 alert(`${this.get('name')} says: ${thing}`);
29396 }
29397 });
29398 const SingingMixin = Mixin.create({
29399 sing(thing) {
29400 alert(`${this.get('name')} sings: la la la ${thing}`);
29401 }
29402 });
29403 const BroadwayStar = Person.extend(SingingMixin, {
29404 dance() {
29405 alert(`${this.get('name')} dances: tap tap tap tap `);
29406 }
29407 });
29408 ```
29409 The `BroadwayStar` class contains three methods: `say()`, `sing()`, and `dance()`.
29410 @method extend
29411 @static
29412 @for @ember/object
29413 @param {Mixin} [mixins]* One or more Mixin classes
29414 @param {Object} [arguments]* Object containing values to use within the new class
29415 @public
29416 */
29417
29418
29419 static extend() {
29420 var Class = class extends this {};
29421 reopen.apply(Class.PrototypeMixin, arguments);
29422 return Class;
29423 }
29424 /**
29425 Creates an instance of a class. Accepts either no arguments, or an object
29426 containing values to initialize the newly instantiated object with.
29427 ```javascript
29428 import EmberObject from '@ember/object';
29429 const Person = EmberObject.extend({
29430 helloWorld() {
29431 alert(`Hi, my name is ${this.get('name')}`);
29432 }
29433 });
29434 let tom = Person.create({
29435 name: 'Tom Dale'
29436 });
29437 tom.helloWorld(); // alerts "Hi, my name is Tom Dale".
29438 ```
29439 `create` will call the `init` function if defined during
29440 `AnyObject.extend`
29441 If no arguments are passed to `create`, it will not set values to the new
29442 instance during initialization:
29443 ```javascript
29444 let noName = Person.create();
29445 noName.helloWorld(); // alerts undefined
29446 ```
29447 NOTE: For performance reasons, you cannot declare methods or computed
29448 properties during `create`. You should instead declare methods and computed
29449 properties when using `extend`.
29450 @method create
29451 @for @ember/object
29452 @static
29453 @param [arguments]*
29454 @public
29455 */
29456
29457
29458 static create(props, extra) {
29459 var instance;
29460
29461 if (props !== undefined) {
29462 instance = new this((0, _owner.getOwner)(props));
29463 (0, _container.setFactoryFor)(instance, (0, _container.getFactoryFor)(props));
29464 } else {
29465 instance = new this();
29466 }
29467
29468 if (extra === undefined) {
29469 initialize(instance, props);
29470 } else {
29471 initialize(instance, flattenProps.apply(this, arguments));
29472 }
29473
29474 return instance;
29475 }
29476 /**
29477 Augments a constructor's prototype with additional
29478 properties and functions:
29479 ```javascript
29480 import EmberObject from '@ember/object';
29481 const MyObject = EmberObject.extend({
29482 name: 'an object'
29483 });
29484 o = MyObject.create();
29485 o.get('name'); // 'an object'
29486 MyObject.reopen({
29487 say(msg) {
29488 console.log(msg);
29489 }
29490 });
29491 o2 = MyObject.create();
29492 o2.say('hello'); // logs "hello"
29493 o.say('goodbye'); // logs "goodbye"
29494 ```
29495 To add functions and properties to the constructor itself,
29496 see `reopenClass`
29497 @method reopen
29498 @for @ember/object
29499 @static
29500 @public
29501 */
29502
29503
29504 static reopen() {
29505 this.willReopen();
29506 reopen.apply(this.PrototypeMixin, arguments);
29507 return this;
29508 }
29509
29510 static willReopen() {
29511 var p = this.prototype;
29512
29513 if (wasApplied.has(p)) {
29514 wasApplied.delete(p); // If the base mixin already exists and was applied, create a new mixin to
29515 // make sure that it gets properly applied. Reusing the same mixin after
29516 // the first `proto` call will cause it to get skipped.
29517
29518 if (prototypeMixinMap.has(this)) {
29519 prototypeMixinMap.set(this, _metal.Mixin.create(this.PrototypeMixin));
29520 }
29521 }
29522 }
29523 /**
29524 Augments a constructor's own properties and functions:
29525 ```javascript
29526 import EmberObject from '@ember/object';
29527 const MyObject = EmberObject.extend({
29528 name: 'an object'
29529 });
29530 MyObject.reopenClass({
29531 canBuild: false
29532 });
29533 MyObject.canBuild; // false
29534 o = MyObject.create();
29535 ```
29536 In other words, this creates static properties and functions for the class.
29537 These are only available on the class and not on any instance of that class.
29538 ```javascript
29539 import EmberObject from '@ember/object';
29540 const Person = EmberObject.extend({
29541 name: '',
29542 sayHello() {
29543 alert(`Hello. My name is ${this.get('name')}`);
29544 }
29545 });
29546 Person.reopenClass({
29547 species: 'Homo sapiens',
29548 createPerson(name) {
29549 return Person.create({ name });
29550 }
29551 });
29552 let tom = Person.create({
29553 name: 'Tom Dale'
29554 });
29555 let yehuda = Person.createPerson('Yehuda Katz');
29556 tom.sayHello(); // "Hello. My name is Tom Dale"
29557 yehuda.sayHello(); // "Hello. My name is Yehuda Katz"
29558 alert(Person.species); // "Homo sapiens"
29559 ```
29560 Note that `species` and `createPerson` are *not* valid on the `tom` and `yehuda`
29561 variables. They are only valid on `Person`.
29562 To add functions and properties to instances of
29563 a constructor by extending the constructor's prototype
29564 see `reopen`
29565 @method reopenClass
29566 @for @ember/object
29567 @static
29568 @public
29569 */
29570
29571
29572 static reopenClass() {
29573 (0, _metal.applyMixin)(this, arguments);
29574 return this;
29575 }
29576
29577 static detect(obj) {
29578 if ('function' !== typeof obj) {
29579 return false;
29580 }
29581
29582 while (obj) {
29583 if (obj === this) {
29584 return true;
29585 }
29586
29587 obj = obj.superclass;
29588 }
29589
29590 return false;
29591 }
29592
29593 static detectInstance(obj) {
29594 return obj instanceof this;
29595 }
29596 /**
29597 In some cases, you may want to annotate computed properties with additional
29598 metadata about how they function or what values they operate on. For
29599 example, computed property functions may close over variables that are then
29600 no longer available for introspection.
29601 You can pass a hash of these values to a computed property like this:
29602 ```javascript
29603 import { computed } from '@ember/object';
29604 person: computed(function() {
29605 let personId = this.get('personId');
29606 return Person.create({ id: personId });
29607 }).meta({ type: Person })
29608 ```
29609 Once you've done this, you can retrieve the values saved to the computed
29610 property from your class like this:
29611 ```javascript
29612 MyClass.metaForProperty('person');
29613 ```
29614 This will return the original hash that was passed to `meta()`.
29615 @static
29616 @method metaForProperty
29617 @param key {String} property name
29618 @private
29619 */
29620
29621
29622 static metaForProperty(key) {
29623 var proto = this.proto(); // ensure prototype is initialized
29624
29625 var possibleDesc = (0, _metal.descriptorForProperty)(proto, key);
29626 (true && !(possibleDesc !== undefined) && (0, _debug.assert)(`metaForProperty() could not find a computed property with key '${key}'.`, possibleDesc !== undefined));
29627 return possibleDesc._meta || {};
29628 }
29629 /**
29630 Iterate over each computed property for the class, passing its name
29631 and any associated metadata (see `metaForProperty`) to the callback.
29632 @static
29633 @method eachComputedProperty
29634 @param {Function} callback
29635 @param {Object} binding
29636 @private
29637 */
29638
29639
29640 static eachComputedProperty(callback, binding = this) {
29641 this.proto(); // ensure prototype is initialized
29642
29643 var empty = {};
29644 (0, _meta2.meta)(this.prototype).forEachDescriptors((name, descriptor) => {
29645 if (descriptor.enumerable) {
29646 var _meta = descriptor._meta || empty;
29647
29648 callback.call(binding, name, _meta);
29649 }
29650 });
29651 }
29652
29653 static get PrototypeMixin() {
29654 var prototypeMixin = prototypeMixinMap.get(this);
29655
29656 if (prototypeMixin === undefined) {
29657 prototypeMixin = _metal.Mixin.create();
29658 prototypeMixin.ownerConstructor = this;
29659 prototypeMixinMap.set(this, prototypeMixin);
29660 }
29661
29662 return prototypeMixin;
29663 }
29664
29665 static get superclass() {
29666 var c = Object.getPrototypeOf(this);
29667 return c !== Function.prototype ? c : undefined;
29668 }
29669
29670 static proto() {
29671 var p = this.prototype;
29672
29673 if (!wasApplied.has(p)) {
29674 wasApplied.add(p);
29675 var parent = this.superclass;
29676
29677 if (parent) {
29678 parent.proto();
29679 } // If the prototype mixin exists, apply it. In the case of native classes,
29680 // it will not exist (unless the class has been reopened).
29681
29682
29683 if (prototypeMixinMap.has(this)) {
29684 this.PrototypeMixin.apply(p);
29685 }
29686 }
29687
29688 return p;
29689 }
29690
29691 }
29692
29693 CoreObject.toString = _metal.classToString;
29694 (0, _utils.setName)(CoreObject, 'Ember.CoreObject');
29695 CoreObject.isClass = true;
29696 CoreObject.isMethod = false;
29697
29698 function flattenProps(...props) {
29699 var {
29700 concatenatedProperties,
29701 mergedProperties
29702 } = this;
29703 var hasConcatenatedProps = concatenatedProperties !== undefined && concatenatedProperties.length > 0;
29704 var hasMergedProps = mergedProperties !== undefined && mergedProperties.length > 0;
29705 var initProperties = {};
29706
29707 for (var i = 0; i < props.length; i++) {
29708 var properties = props[i];
29709 (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)));
29710 var keyNames = Object.keys(properties);
29711
29712 for (var j = 0, k = keyNames.length; j < k; j++) {
29713 var keyName = keyNames[j];
29714 var value = properties[keyName];
29715
29716 if (hasConcatenatedProps && concatenatedProperties.indexOf(keyName) > -1) {
29717 var baseValue = initProperties[keyName];
29718
29719 if (baseValue) {
29720 value = (0, _utils.makeArray)(baseValue).concat(value);
29721 } else {
29722 value = (0, _utils.makeArray)(value);
29723 }
29724 }
29725
29726 if (hasMergedProps && mergedProperties.indexOf(keyName) > -1) {
29727 var _baseValue2 = initProperties[keyName];
29728 value = (0, _polyfills.assign)({}, _baseValue2, value);
29729 }
29730
29731 initProperties[keyName] = value;
29732 }
29733 }
29734
29735 return initProperties;
29736 }
29737
29738 if (true
29739 /* DEBUG */
29740 ) {
29741 /**
29742 Provides lookup-time type validation for injected properties.
29743 @private
29744 @method _onLookup
29745 */
29746 CoreObject._onLookup = function injectedPropertyAssertion(debugContainerKey) {
29747 var [type] = debugContainerKey.split(':');
29748 var proto = this.proto();
29749
29750 for (var key in proto) {
29751 var desc = (0, _metal.descriptorForProperty)(proto, key);
29752
29753 if (desc && _metal.DEBUG_INJECTION_FUNCTIONS.has(desc._getter)) {
29754 (true && !(type === 'controller' || _metal.DEBUG_INJECTION_FUNCTIONS.get(desc._getter).type !== 'controller') && (0, _debug.assert)(`Defining \`${key}\` as an injected controller property on a non-controller (\`${debugContainerKey}\`) is not allowed.`, type === 'controller' || _metal.DEBUG_INJECTION_FUNCTIONS.get(desc._getter).type !== 'controller'));
29755 }
29756 }
29757 };
29758 /**
29759 Returns a hash of property names and container names that injected
29760 properties will lookup on the container lazily.
29761 @method _lazyInjections
29762 @return {Object} Hash of all lazy injected property keys to container names
29763 @private
29764 */
29765
29766
29767 CoreObject._lazyInjections = function () {
29768 var injections = {};
29769 var proto = this.proto();
29770 var key;
29771 var desc;
29772
29773 for (key in proto) {
29774 desc = (0, _metal.descriptorForProperty)(proto, key);
29775
29776 if (desc && _metal.DEBUG_INJECTION_FUNCTIONS.has(desc._getter)) {
29777 var {
29778 namespace,
29779 source,
29780 type,
29781 name
29782 } = _metal.DEBUG_INJECTION_FUNCTIONS.get(desc._getter);
29783
29784 injections[key] = {
29785 namespace,
29786 source,
29787 specifier: `${type}:${name || key}`
29788 };
29789 }
29790 }
29791
29792 return injections;
29793 };
29794 }
29795
29796 if (!_utils.HAS_NATIVE_SYMBOL) {
29797 // Allows OWNER and INIT_FACTORY to be non-enumerable in IE11
29798 var instanceOwner = new WeakMap();
29799 var instanceFactory = new WeakMap();
29800 Object.defineProperty(CoreObject.prototype, _owner.OWNER, {
29801 get() {
29802 return instanceOwner.get(this);
29803 },
29804
29805 set(value) {
29806 instanceOwner.set(this, value);
29807 }
29808
29809 });
29810 Object.defineProperty(CoreObject.prototype, _container.INIT_FACTORY, {
29811 get() {
29812 return instanceFactory.get(this);
29813 },
29814
29815 set(value) {
29816 instanceFactory.set(this, value);
29817 }
29818
29819 });
29820 }
29821
29822 var _default = CoreObject;
29823 _exports.default = _default;
29824});
29825define("@ember/-internals/runtime/lib/system/namespace", ["exports", "@ember/-internals/metal", "@ember/-internals/utils", "@ember/-internals/runtime/lib/system/object"], function (_exports, _metal, _utils, _object) {
29826 "use strict";
29827
29828 Object.defineProperty(_exports, "__esModule", {
29829 value: true
29830 });
29831 _exports.default = void 0;
29832
29833 /**
29834 @module ember
29835 */
29836 // Preloaded into namespaces
29837
29838 /**
29839 A Namespace is an object usually used to contain other objects or methods
29840 such as an application or framework. Create a namespace anytime you want
29841 to define one of these new containers.
29842
29843 # Example Usage
29844
29845 ```javascript
29846 MyFramework = Ember.Namespace.create({
29847 VERSION: '1.0.0'
29848 });
29849 ```
29850
29851 @class Namespace
29852 @namespace Ember
29853 @extends EmberObject
29854 @public
29855 */
29856 class Namespace extends _object.default {
29857 init() {
29858 (0, _metal.addNamespace)(this);
29859 }
29860
29861 toString() {
29862 var name = (0, _metal.get)(this, 'name') || (0, _metal.get)(this, 'modulePrefix');
29863
29864 if (name) {
29865 return name;
29866 }
29867
29868 (0, _metal.findNamespaces)();
29869 name = (0, _utils.getName)(this);
29870
29871 if (name === undefined) {
29872 name = (0, _utils.guidFor)(this);
29873 (0, _utils.setName)(this, name);
29874 }
29875
29876 return name;
29877 }
29878
29879 nameClasses() {
29880 (0, _metal.processNamespace)(this);
29881 }
29882
29883 destroy() {
29884 (0, _metal.removeNamespace)(this);
29885 super.destroy();
29886 }
29887
29888 }
29889
29890 _exports.default = Namespace;
29891 Namespace.prototype.isNamespace = true;
29892 Namespace.NAMESPACES = _metal.NAMESPACES;
29893 Namespace.NAMESPACES_BY_ID = _metal.NAMESPACES_BY_ID;
29894 Namespace.processAll = _metal.processAllNamespaces;
29895 Namespace.byName = _metal.findNamespace;
29896});
29897define("@ember/-internals/runtime/lib/system/object", ["exports", "@ember/-internals/container", "@ember/-internals/utils", "@ember/-internals/metal", "@ember/-internals/runtime/lib/system/core_object", "@ember/-internals/runtime/lib/mixins/observable", "@ember/debug"], function (_exports, _container, _utils, _metal, _core_object, _observable, _debug) {
29898 "use strict";
29899
29900 Object.defineProperty(_exports, "__esModule", {
29901 value: true
29902 });
29903 _exports.FrameworkObject = _exports.default = void 0;
29904
29905 /**
29906 @module @ember/object
29907 */
29908
29909 /**
29910 `EmberObject` is the main base class for all Ember objects. It is a subclass
29911 of `CoreObject` with the `Observable` mixin applied. For details,
29912 see the documentation for each of these.
29913
29914 @class EmberObject
29915 @extends CoreObject
29916 @uses Observable
29917 @public
29918 */
29919 class EmberObject extends _core_object.default {
29920 get _debugContainerKey() {
29921 var factory = (0, _container.getFactoryFor)(this);
29922 return factory !== undefined && factory.fullName;
29923 }
29924
29925 }
29926
29927 _exports.default = EmberObject;
29928 (0, _utils.setName)(EmberObject, 'Ember.Object');
29929
29930 _observable.default.apply(EmberObject.prototype);
29931
29932 var FrameworkObject;
29933 _exports.FrameworkObject = FrameworkObject;
29934 _exports.FrameworkObject = FrameworkObject = class FrameworkObject extends _core_object.default {
29935 get _debugContainerKey() {
29936 var factory = (0, _container.getFactoryFor)(this);
29937 return factory !== undefined && factory.fullName;
29938 }
29939
29940 };
29941
29942 _observable.default.apply(FrameworkObject.prototype);
29943
29944 if (true
29945 /* DEBUG */
29946 ) {
29947 var INIT_WAS_CALLED = (0, _utils.symbol)('INIT_WAS_CALLED');
29948 var ASSERT_INIT_WAS_CALLED = (0, _utils.symbol)('ASSERT_INIT_WAS_CALLED');
29949 _exports.FrameworkObject = FrameworkObject = class DebugFrameworkObject extends EmberObject {
29950 init() {
29951 super.init(...arguments);
29952 this[INIT_WAS_CALLED] = true;
29953 }
29954
29955 [ASSERT_INIT_WAS_CALLED]() {
29956 (true && !(this[INIT_WAS_CALLED]) && (0, _debug.assert)(`You must call \`super.init(...arguments);\` or \`this._super(...arguments)\` when overriding \`init\` on a framework object. Please update ${this} to call \`super.init(...arguments);\` from \`init\` when using native classes or \`this._super(...arguments)\` when using \`EmberObject.extend()\`.`, this[INIT_WAS_CALLED]));
29957 }
29958
29959 };
29960 (0, _metal.addListener)(FrameworkObject.prototype, 'init', null, ASSERT_INIT_WAS_CALLED);
29961 }
29962});
29963define("@ember/-internals/runtime/lib/system/object_proxy", ["exports", "@ember/-internals/runtime/lib/system/object", "@ember/-internals/runtime/lib/mixins/-proxy"], function (_exports, _object, _proxy) {
29964 "use strict";
29965
29966 Object.defineProperty(_exports, "__esModule", {
29967 value: true
29968 });
29969 _exports.default = void 0;
29970
29971 /**
29972 `ObjectProxy` forwards all properties not defined by the proxy itself
29973 to a proxied `content` object.
29974
29975 ```javascript
29976 import EmberObject from '@ember/object';
29977 import ObjectProxy from '@ember/object/proxy';
29978
29979 let exampleObject = EmberObject.create({
29980 name: 'Foo'
29981 });
29982
29983 let exampleProxy = ObjectProxy.create({
29984 content: exampleObject
29985 });
29986
29987 // Access and change existing properties
29988 exampleProxy.get('name'); // 'Foo'
29989 exampleProxy.set('name', 'Bar');
29990 exampleObject.get('name'); // 'Bar'
29991
29992 // Create new 'description' property on `exampleObject`
29993 exampleProxy.set('description', 'Foo is a whizboo baz');
29994 exampleObject.get('description'); // 'Foo is a whizboo baz'
29995 ```
29996
29997 While `content` is unset, setting a property to be delegated will throw an
29998 Error.
29999
30000 ```javascript
30001 import ObjectProxy from '@ember/object/proxy';
30002
30003 let exampleProxy = ObjectProxy.create({
30004 content: null,
30005 flag: null
30006 });
30007 exampleProxy.set('flag', true);
30008 exampleProxy.get('flag'); // true
30009 exampleProxy.get('foo'); // undefined
30010 exampleProxy.set('foo', 'data'); // throws Error
30011 ```
30012
30013 Delegated properties can be bound to and will change when content is updated.
30014
30015 Computed properties on the proxy itself can depend on delegated properties.
30016
30017 ```javascript
30018 import { computed } from '@ember/object';
30019 import ObjectProxy from '@ember/object/proxy';
30020
30021 ProxyWithComputedProperty = ObjectProxy.extend({
30022 fullName: computed('firstName', 'lastName', function() {
30023 var firstName = this.get('firstName'),
30024 lastName = this.get('lastName');
30025 if (firstName && lastName) {
30026 return firstName + ' ' + lastName;
30027 }
30028 return firstName || lastName;
30029 })
30030 });
30031
30032 let exampleProxy = ProxyWithComputedProperty.create();
30033
30034 exampleProxy.get('fullName'); // undefined
30035 exampleProxy.set('content', {
30036 firstName: 'Tom', lastName: 'Dale'
30037 }); // triggers property change for fullName on proxy
30038
30039 exampleProxy.get('fullName'); // 'Tom Dale'
30040 ```
30041
30042 @class ObjectProxy
30043 @extends EmberObject
30044 @uses Ember.ProxyMixin
30045 @public
30046 */
30047 class ObjectProxy extends _object.default {}
30048
30049 _exports.default = ObjectProxy;
30050 ObjectProxy.PrototypeMixin.reopen(_proxy.default);
30051});
30052define("@ember/-internals/runtime/lib/type-of", ["exports", "@ember/-internals/runtime/lib/system/core_object"], function (_exports, _core_object) {
30053 "use strict";
30054
30055 Object.defineProperty(_exports, "__esModule", {
30056 value: true
30057 });
30058 _exports.typeOf = typeOf;
30059 // ........................................
30060 // TYPING & ARRAY MESSAGING
30061 //
30062 var TYPE_MAP = {
30063 '[object Boolean]': 'boolean',
30064 '[object Number]': 'number',
30065 '[object String]': 'string',
30066 '[object Function]': 'function',
30067 '[object AsyncFunction]': 'function',
30068 '[object Array]': 'array',
30069 '[object Date]': 'date',
30070 '[object RegExp]': 'regexp',
30071 '[object Object]': 'object',
30072 '[object FileList]': 'filelist'
30073 };
30074 var {
30075 toString
30076 } = Object.prototype;
30077 /**
30078 @module @ember/utils
30079 */
30080
30081 /**
30082 Returns a consistent type for the passed object.
30083
30084 Use this instead of the built-in `typeof` to get the type of an item.
30085 It will return the same result across all browsers and includes a bit
30086 more detail. Here is what will be returned:
30087
30088 | Return Value | Meaning |
30089 |---------------|------------------------------------------------------|
30090 | 'string' | String primitive or String object. |
30091 | 'number' | Number primitive or Number object. |
30092 | 'boolean' | Boolean primitive or Boolean object. |
30093 | 'null' | Null value |
30094 | 'undefined' | Undefined value |
30095 | 'function' | A function |
30096 | 'array' | An instance of Array |
30097 | 'regexp' | An instance of RegExp |
30098 | 'date' | An instance of Date |
30099 | 'filelist' | An instance of FileList |
30100 | 'class' | An Ember class (created using EmberObject.extend()) |
30101 | 'instance' | An Ember object instance |
30102 | 'error' | An instance of the Error object |
30103 | 'object' | A JavaScript object not inheriting from EmberObject |
30104
30105 Examples:
30106
30107 ```javascript
30108 import { A } from '@ember/array';
30109 import { typeOf } from '@ember/utils';
30110 import EmberObject from '@ember/object';
30111
30112 typeOf(); // 'undefined'
30113 typeOf(null); // 'null'
30114 typeOf(undefined); // 'undefined'
30115 typeOf('michael'); // 'string'
30116 typeOf(new String('michael')); // 'string'
30117 typeOf(101); // 'number'
30118 typeOf(new Number(101)); // 'number'
30119 typeOf(true); // 'boolean'
30120 typeOf(new Boolean(true)); // 'boolean'
30121 typeOf(A); // 'function'
30122 typeOf(A()); // 'array'
30123 typeOf([1, 2, 90]); // 'array'
30124 typeOf(/abc/); // 'regexp'
30125 typeOf(new Date()); // 'date'
30126 typeOf(event.target.files); // 'filelist'
30127 typeOf(EmberObject.extend()); // 'class'
30128 typeOf(EmberObject.create()); // 'instance'
30129 typeOf(new Error('teamocil')); // 'error'
30130
30131 // 'normal' JavaScript object
30132 typeOf({ a: 'b' }); // 'object'
30133 ```
30134
30135 @method typeOf
30136 @for @ember/utils
30137 @param {Object} item the item to check
30138 @return {String} the type
30139 @public
30140 @static
30141 */
30142
30143 function typeOf(item) {
30144 if (item === null) {
30145 return 'null';
30146 }
30147
30148 if (item === undefined) {
30149 return 'undefined';
30150 }
30151
30152 var ret = TYPE_MAP[toString.call(item)] || 'object';
30153
30154 if (ret === 'function') {
30155 if (_core_object.default.detect(item)) {
30156 ret = 'class';
30157 }
30158 } else if (ret === 'object') {
30159 if (item instanceof Error) {
30160 ret = 'error';
30161 } else if (item instanceof _core_object.default) {
30162 ret = 'instance';
30163 } else if (item instanceof Date) {
30164 ret = 'date';
30165 }
30166 }
30167
30168 return ret;
30169 }
30170});
30171define("@ember/-internals/utils/index", ["exports", "@ember/polyfills", "@ember/debug"], function (_exports, _polyfills, _debug) {
30172 "use strict";
30173
30174 Object.defineProperty(_exports, "__esModule", {
30175 value: true
30176 });
30177 _exports.enumerableSymbol = enumerableSymbol;
30178 _exports.isInternalSymbol = isInternalSymbol;
30179 _exports.dictionary = makeDictionary;
30180 _exports.uuid = uuid;
30181 _exports.generateGuid = generateGuid;
30182 _exports.guidFor = guidFor;
30183 _exports.intern = intern;
30184 _exports.wrap = wrap;
30185 _exports.observerListenerMetaFor = observerListenerMetaFor;
30186 _exports.setObservers = setObservers;
30187 _exports.setListeners = setListeners;
30188 _exports.inspect = inspect;
30189 _exports.lookupDescriptor = lookupDescriptor;
30190 _exports.canInvoke = canInvoke;
30191 _exports.tryInvoke = tryInvoke;
30192 _exports.makeArray = makeArray;
30193 _exports.getName = getName;
30194 _exports.setName = setName;
30195 _exports.toString = toString;
30196 _exports.isObject = isObject;
30197 _exports.isProxy = isProxy;
30198 _exports.setProxy = setProxy;
30199 _exports.setEmberArray = setEmberArray;
30200 _exports.isEmberArray = isEmberArray;
30201 _exports.setWithMandatorySetter = _exports.teardownMandatorySetter = _exports.setupMandatorySetter = _exports.Cache = _exports.HAS_NATIVE_PROXY = _exports.HAS_NATIVE_SYMBOL = _exports.ROOT = _exports.checkHasSuper = _exports.GUID_KEY = _exports.getDebugName = _exports.symbol = void 0;
30202
30203 /**
30204 Strongly hint runtimes to intern the provided string.
30205
30206 When do I need to use this function?
30207
30208 For the most part, never. Pre-mature optimization is bad, and often the
30209 runtime does exactly what you need it to, and more often the trade-off isn't
30210 worth it.
30211
30212 Why?
30213
30214 Runtimes store strings in at least 2 different representations:
30215 Ropes and Symbols (interned strings). The Rope provides a memory efficient
30216 data-structure for strings created from concatenation or some other string
30217 manipulation like splitting.
30218
30219 Unfortunately checking equality of different ropes can be quite costly as
30220 runtimes must resort to clever string comparison algorithms. These
30221 algorithms typically cost in proportion to the length of the string.
30222 Luckily, this is where the Symbols (interned strings) shine. As Symbols are
30223 unique by their string content, equality checks can be done by pointer
30224 comparison.
30225
30226 How do I know if my string is a rope or symbol?
30227
30228 Typically (warning general sweeping statement, but truthy in runtimes at
30229 present) static strings created as part of the JS source are interned.
30230 Strings often used for comparisons can be interned at runtime if some
30231 criteria are met. One of these criteria can be the size of the entire rope.
30232 For example, in chrome 38 a rope longer then 12 characters will not
30233 intern, nor will segments of that rope.
30234
30235 Some numbers: http://jsperf.com/eval-vs-keys/8
30236
30237 Known Trick™
30238
30239 @private
30240 @return {String} interned version of the provided string
30241 */
30242 function intern(str) {
30243 var obj = {};
30244 obj[str] = 1;
30245
30246 for (var key in obj) {
30247 if (key === str) {
30248 return key;
30249 }
30250 }
30251
30252 return str;
30253 }
30254 /**
30255 Returns whether Type(value) is Object.
30256
30257 Useful for checking whether a value is a valid WeakMap key.
30258
30259 Refs: https://tc39.github.io/ecma262/#sec-typeof-operator-runtime-semantics-evaluation
30260 https://tc39.github.io/ecma262/#sec-weakmap.prototype.set
30261
30262 @private
30263 @function isObject
30264 */
30265
30266
30267 function isObject(value) {
30268 return value !== null && (typeof value === 'object' || typeof value === 'function');
30269 }
30270 /**
30271 @module @ember/object
30272 */
30273
30274 /**
30275 Previously we used `Ember.$.uuid`, however `$.uuid` has been removed from
30276 jQuery master. We'll just bootstrap our own uuid now.
30277
30278 @private
30279 @return {Number} the uuid
30280 */
30281
30282
30283 var _uuid = 0;
30284 /**
30285 Generates a universally unique identifier. This method
30286 is used internally by Ember for assisting with
30287 the generation of GUID's and other unique identifiers.
30288
30289 @public
30290 @return {Number} [description]
30291 */
30292
30293 function uuid() {
30294 return ++_uuid;
30295 }
30296 /**
30297 Prefix used for guids through out Ember.
30298 @private
30299 @property GUID_PREFIX
30300 @for Ember
30301 @type String
30302 @final
30303 */
30304
30305
30306 var GUID_PREFIX = 'ember'; // Used for guid generation...
30307
30308 var OBJECT_GUIDS = new WeakMap();
30309 var NON_OBJECT_GUIDS = new Map();
30310 /**
30311 A unique key used to assign guids and other private metadata to objects.
30312 If you inspect an object in your browser debugger you will often see these.
30313 They can be safely ignored.
30314
30315 On browsers that support it, these properties are added with enumeration
30316 disabled so they won't show up when you iterate over your properties.
30317
30318 @private
30319 @property GUID_KEY
30320 @for Ember
30321 @type String
30322 @final
30323 */
30324
30325 var GUID_KEY = intern(`__ember${Date.now()}`);
30326 /**
30327 Generates a new guid, optionally saving the guid to the object that you
30328 pass in. You will rarely need to use this method. Instead you should
30329 call `guidFor(obj)`, which return an existing guid if available.
30330
30331 @private
30332 @method generateGuid
30333 @static
30334 @for @ember/object/internals
30335 @param {Object} [obj] Object the guid will be used for. If passed in, the guid will
30336 be saved on the object and reused whenever you pass the same object
30337 again.
30338
30339 If no object is passed, just generate a new guid.
30340 @param {String} [prefix] Prefix to place in front of the guid. Useful when you want to
30341 separate the guid into separate namespaces.
30342 @return {String} the guid
30343 */
30344
30345 _exports.GUID_KEY = GUID_KEY;
30346
30347 function generateGuid(obj, prefix = GUID_PREFIX) {
30348 var guid = prefix + uuid();
30349
30350 if (isObject(obj)) {
30351 OBJECT_GUIDS.set(obj, guid);
30352 }
30353
30354 return guid;
30355 }
30356 /**
30357 Returns a unique id for the object. If the object does not yet have a guid,
30358 one will be assigned to it. You can call this on any object,
30359 `EmberObject`-based or not.
30360
30361 You can also use this method on DOM Element objects.
30362
30363 @public
30364 @static
30365 @method guidFor
30366 @for @ember/object/internals
30367 @param {Object} obj any object, string, number, Element, or primitive
30368 @return {String} the unique guid for this instance.
30369 */
30370
30371
30372 function guidFor(value) {
30373 var guid;
30374
30375 if (isObject(value)) {
30376 guid = OBJECT_GUIDS.get(value);
30377
30378 if (guid === undefined) {
30379 guid = GUID_PREFIX + uuid();
30380 OBJECT_GUIDS.set(value, guid);
30381 }
30382 } else {
30383 guid = NON_OBJECT_GUIDS.get(value);
30384
30385 if (guid === undefined) {
30386 var type = typeof value;
30387
30388 if (type === 'string') {
30389 guid = 'st' + uuid();
30390 } else if (type === 'number') {
30391 guid = 'nu' + uuid();
30392 } else if (type === 'symbol') {
30393 guid = 'sy' + uuid();
30394 } else {
30395 guid = '(' + value + ')';
30396 }
30397
30398 NON_OBJECT_GUIDS.set(value, guid);
30399 }
30400 }
30401
30402 return guid;
30403 }
30404
30405 var HAS_NATIVE_SYMBOL = function () {
30406 if (typeof Symbol !== 'function') {
30407 return false;
30408 }
30409
30410 return typeof Symbol() === 'symbol';
30411 }();
30412
30413 _exports.HAS_NATIVE_SYMBOL = HAS_NATIVE_SYMBOL;
30414 var GENERATED_SYMBOLS = [];
30415
30416 function isInternalSymbol(possibleSymbol) {
30417 return GENERATED_SYMBOLS.indexOf(possibleSymbol) !== -1;
30418 } // Some legacy symbols still need to be enumerable for a variety of reasons.
30419 // This code exists for that, and as a fallback in IE11. In general, prefer
30420 // `symbol` below when creating a new symbol.
30421
30422
30423 function enumerableSymbol(debugName) {
30424 // TODO: Investigate using platform symbols, but we do not
30425 // want to require non-enumerability for this API, which
30426 // would introduce a large cost.
30427 var id = GUID_KEY + Math.floor(Math.random() * Date.now());
30428 var symbol = intern(`__${debugName}${id}__`);
30429
30430 if (true
30431 /* DEBUG */
30432 ) {
30433 GENERATED_SYMBOLS.push(symbol);
30434 }
30435
30436 return symbol;
30437 }
30438
30439 var symbol = HAS_NATIVE_SYMBOL ? Symbol : enumerableSymbol; // the delete is meant to hint at runtimes that this object should remain in
30440 // dictionary mode. This is clearly a runtime specific hack, but currently it
30441 // appears worthwhile in some usecases. Please note, these deletes do increase
30442 // the cost of creation dramatically over a plain Object.create. And as this
30443 // only makes sense for long-lived dictionaries that aren't instantiated often.
30444
30445 _exports.symbol = symbol;
30446
30447 function makeDictionary(parent) {
30448 var dict = Object.create(parent);
30449 dict['_dict'] = null;
30450 delete dict['_dict'];
30451 return dict;
30452 }
30453
30454 var getDebugName;
30455
30456 if (true
30457 /* DEBUG */
30458 ) {
30459 var getFunctionName = fn => {
30460 var functionName = fn.name;
30461
30462 if (functionName === undefined) {
30463 var match = Function.prototype.toString.call(fn).match(/function (\w+)\s*\(/);
30464 functionName = match && match[1] || '';
30465 }
30466
30467 return functionName.replace(/^bound /, '');
30468 };
30469
30470 var getObjectName = obj => {
30471 var name;
30472 var className;
30473
30474 if (obj.constructor && obj.constructor !== Object) {
30475 className = getFunctionName(obj.constructor);
30476 }
30477
30478 if ('toString' in obj && obj.toString !== Object.prototype.toString && obj.toString !== Function.prototype.toString) {
30479 name = obj.toString();
30480 } // If the class has a decent looking name, and the `toString` is one of the
30481 // default Ember toStrings, replace the constructor portion of the toString
30482 // with the class name. We check the length of the class name to prevent doing
30483 // this when the value is minified.
30484
30485
30486 if (name && name.match(/<.*:ember\d+>/) && className && className[0] !== '_' && className.length > 2 && className !== 'Class') {
30487 return name.replace(/<.*:/, `<${className}:`);
30488 }
30489
30490 return name || className;
30491 };
30492
30493 var getPrimitiveName = value => {
30494 return String(value);
30495 };
30496
30497 getDebugName = value => {
30498 if (typeof value === 'function') {
30499 return getFunctionName(value) || `(unknown function)`;
30500 } else if (typeof value === 'object' && value !== null) {
30501 return getObjectName(value) || `(unknown object)`;
30502 } else {
30503 return getPrimitiveName(value);
30504 }
30505 };
30506 }
30507
30508 var getDebugName$1 = getDebugName;
30509 _exports.getDebugName = getDebugName$1;
30510 var HAS_SUPER_PATTERN = /\.(_super|call\(this|apply\(this)/;
30511 var fnToString = Function.prototype.toString;
30512
30513 var checkHasSuper = (() => {
30514 var sourceAvailable = fnToString.call(function () {
30515 return this;
30516 }).indexOf('return this') > -1;
30517
30518 if (sourceAvailable) {
30519 return function checkHasSuper(func) {
30520 return HAS_SUPER_PATTERN.test(fnToString.call(func));
30521 };
30522 }
30523
30524 return function checkHasSuper() {
30525 return true;
30526 };
30527 })();
30528
30529 _exports.checkHasSuper = checkHasSuper;
30530 var HAS_SUPER_MAP = new WeakMap();
30531 var ROOT = Object.freeze(function () {});
30532 _exports.ROOT = ROOT;
30533 HAS_SUPER_MAP.set(ROOT, false);
30534
30535 function hasSuper(func) {
30536 var hasSuper = HAS_SUPER_MAP.get(func);
30537
30538 if (hasSuper === undefined) {
30539 hasSuper = checkHasSuper(func);
30540 HAS_SUPER_MAP.set(func, hasSuper);
30541 }
30542
30543 return hasSuper;
30544 }
30545
30546 class ObserverListenerMeta {
30547 constructor() {
30548 this.listeners = undefined;
30549 this.observers = undefined;
30550 }
30551
30552 }
30553
30554 var OBSERVERS_LISTENERS_MAP = new WeakMap();
30555
30556 function createObserverListenerMetaFor(fn) {
30557 var meta = OBSERVERS_LISTENERS_MAP.get(fn);
30558
30559 if (meta === undefined) {
30560 meta = new ObserverListenerMeta();
30561 OBSERVERS_LISTENERS_MAP.set(fn, meta);
30562 }
30563
30564 return meta;
30565 }
30566
30567 function observerListenerMetaFor(fn) {
30568 return OBSERVERS_LISTENERS_MAP.get(fn);
30569 }
30570
30571 function setObservers(func, observers) {
30572 var meta = createObserverListenerMetaFor(func);
30573 meta.observers = observers;
30574 }
30575
30576 function setListeners(func, listeners) {
30577 var meta = createObserverListenerMetaFor(func);
30578 meta.listeners = listeners;
30579 }
30580
30581 var IS_WRAPPED_FUNCTION_SET = new _polyfills._WeakSet();
30582 /**
30583 Wraps the passed function so that `this._super` will point to the superFunc
30584 when the function is invoked. This is the primitive we use to implement
30585 calls to super.
30586
30587 @private
30588 @method wrap
30589 @for Ember
30590 @param {Function} func The function to call
30591 @param {Function} superFunc The super function.
30592 @return {Function} wrapped function.
30593 */
30594
30595 function wrap(func, superFunc) {
30596 if (!hasSuper(func)) {
30597 return func;
30598 } // ensure an unwrapped super that calls _super is wrapped with a terminal _super
30599
30600
30601 if (!IS_WRAPPED_FUNCTION_SET.has(superFunc) && hasSuper(superFunc)) {
30602 return _wrap(func, _wrap(superFunc, ROOT));
30603 }
30604
30605 return _wrap(func, superFunc);
30606 }
30607
30608 function _wrap(func, superFunc) {
30609 function superWrapper() {
30610 var orig = this._super;
30611 this._super = superFunc;
30612 var ret = func.apply(this, arguments);
30613 this._super = orig;
30614 return ret;
30615 }
30616
30617 IS_WRAPPED_FUNCTION_SET.add(superWrapper);
30618 var meta = OBSERVERS_LISTENERS_MAP.get(func);
30619
30620 if (meta !== undefined) {
30621 OBSERVERS_LISTENERS_MAP.set(superWrapper, meta);
30622 }
30623
30624 return superWrapper;
30625 }
30626
30627 var {
30628 toString: objectToString
30629 } = Object.prototype;
30630 var {
30631 toString: functionToString
30632 } = Function.prototype;
30633 var {
30634 isArray
30635 } = Array;
30636 var {
30637 keys: objectKeys
30638 } = Object;
30639 var {
30640 stringify
30641 } = JSON;
30642 var LIST_LIMIT = 100;
30643 var DEPTH_LIMIT = 4;
30644 var SAFE_KEY = /^[\w$]+$/;
30645 /**
30646 @module @ember/debug
30647 */
30648
30649 /**
30650 Convenience method to inspect an object. This method will attempt to
30651 convert the object into a useful string description.
30652
30653 It is a pretty simple implementation. If you want something more robust,
30654 use something like JSDump: https://github.com/NV/jsDump
30655
30656 @method inspect
30657 @static
30658 @param {Object} obj The object you want to inspect.
30659 @return {String} A description of the object
30660 @since 1.4.0
30661 @private
30662 */
30663
30664 function inspect(obj) {
30665 // detect Node util.inspect call inspect(depth: number, opts: object)
30666 if (typeof obj === 'number' && arguments.length === 2) {
30667 return this;
30668 }
30669
30670 return inspectValue(obj, 0);
30671 }
30672
30673 function inspectValue(value, depth, seen) {
30674 var valueIsArray = false;
30675
30676 switch (typeof value) {
30677 case 'undefined':
30678 return 'undefined';
30679
30680 case 'object':
30681 if (value === null) return 'null';
30682
30683 if (isArray(value)) {
30684 valueIsArray = true;
30685 break;
30686 } // is toString Object.prototype.toString or undefined then traverse
30687
30688
30689 if (value.toString === objectToString || value.toString === undefined) {
30690 break;
30691 } // custom toString
30692
30693
30694 return value.toString();
30695
30696 case 'function':
30697 return value.toString === functionToString ? value.name ? `[Function:${value.name}]` : `[Function]` : value.toString();
30698
30699 case 'string':
30700 return stringify(value);
30701
30702 case 'symbol':
30703 case 'boolean':
30704 case 'number':
30705 default:
30706 return value.toString();
30707 }
30708
30709 if (seen === undefined) {
30710 seen = new _polyfills._WeakSet();
30711 } else {
30712 if (seen.has(value)) return `[Circular]`;
30713 }
30714
30715 seen.add(value);
30716 return valueIsArray ? inspectArray(value, depth + 1, seen) : inspectObject(value, depth + 1, seen);
30717 }
30718
30719 function inspectKey(key) {
30720 return SAFE_KEY.test(key) ? key : stringify(key);
30721 }
30722
30723 function inspectObject(obj, depth, seen) {
30724 if (depth > DEPTH_LIMIT) {
30725 return '[Object]';
30726 }
30727
30728 var s = '{';
30729 var keys = objectKeys(obj);
30730
30731 for (var i = 0; i < keys.length; i++) {
30732 s += i === 0 ? ' ' : ', ';
30733
30734 if (i >= LIST_LIMIT) {
30735 s += `... ${keys.length - LIST_LIMIT} more keys`;
30736 break;
30737 }
30738
30739 var key = keys[i];
30740 s += inspectKey(key) + ': ' + inspectValue(obj[key], depth, seen);
30741 }
30742
30743 s += ' }';
30744 return s;
30745 }
30746
30747 function inspectArray(arr, depth, seen) {
30748 if (depth > DEPTH_LIMIT) {
30749 return '[Array]';
30750 }
30751
30752 var s = '[';
30753
30754 for (var i = 0; i < arr.length; i++) {
30755 s += i === 0 ? ' ' : ', ';
30756
30757 if (i >= LIST_LIMIT) {
30758 s += `... ${arr.length - LIST_LIMIT} more items`;
30759 break;
30760 }
30761
30762 s += inspectValue(arr[i], depth, seen);
30763 }
30764
30765 s += ' ]';
30766 return s;
30767 }
30768
30769 function lookupDescriptor(obj, keyName) {
30770 var current = obj;
30771
30772 do {
30773 var descriptor = Object.getOwnPropertyDescriptor(current, keyName);
30774
30775 if (descriptor !== undefined) {
30776 return descriptor;
30777 }
30778
30779 current = Object.getPrototypeOf(current);
30780 } while (current !== null);
30781
30782 return null;
30783 }
30784 /**
30785 Checks to see if the `methodName` exists on the `obj`.
30786
30787 ```javascript
30788 let foo = { bar: function() { return 'bar'; }, baz: null };
30789
30790 Ember.canInvoke(foo, 'bar'); // true
30791 Ember.canInvoke(foo, 'baz'); // false
30792 Ember.canInvoke(foo, 'bat'); // false
30793 ```
30794
30795 @method canInvoke
30796 @for Ember
30797 @param {Object} obj The object to check for the method
30798 @param {String} methodName The method name to check for
30799 @return {Boolean}
30800 @private
30801 */
30802
30803
30804 function canInvoke(obj, methodName) {
30805 return obj !== null && obj !== undefined && typeof obj[methodName] === 'function';
30806 }
30807 /**
30808 @module @ember/utils
30809 */
30810
30811 /**
30812 Checks to see if the `methodName` exists on the `obj`,
30813 and if it does, invokes it with the arguments passed.
30814
30815 ```javascript
30816 import { tryInvoke } from '@ember/utils';
30817
30818 let d = new Date('03/15/2013');
30819
30820 tryInvoke(d, 'getTime'); // 1363320000000
30821 tryInvoke(d, 'setFullYear', [2014]); // 1394856000000
30822 tryInvoke(d, 'noSuchMethod', [2014]); // undefined
30823 ```
30824
30825 @method tryInvoke
30826 @for @ember/utils
30827 @static
30828 @param {Object} obj The object to check for the method
30829 @param {String} methodName The method name to check for
30830 @param {Array} [args] The arguments to pass to the method
30831 @return {*} the return value of the invoked method or undefined if it cannot be invoked
30832 @public
30833 */
30834
30835
30836 function tryInvoke(obj, methodName, args) {
30837 if (canInvoke(obj, methodName)) {
30838 var method = obj[methodName];
30839 return method.apply(obj, args);
30840 }
30841 }
30842
30843 var {
30844 isArray: isArray$1
30845 } = Array;
30846
30847 function makeArray(obj) {
30848 if (obj === null || obj === undefined) {
30849 return [];
30850 }
30851
30852 return isArray$1(obj) ? obj : [obj];
30853 }
30854
30855 var NAMES = new WeakMap();
30856
30857 function setName(obj, name) {
30858 if (isObject(obj)) NAMES.set(obj, name);
30859 }
30860
30861 function getName(obj) {
30862 return NAMES.get(obj);
30863 }
30864
30865 var objectToString$1 = Object.prototype.toString;
30866
30867 function isNone(obj) {
30868 return obj === null || obj === undefined;
30869 }
30870 /*
30871 A `toString` util function that supports objects without a `toString`
30872 method, e.g. an object created with `Object.create(null)`.
30873 */
30874
30875
30876 function toString(obj) {
30877 if (typeof obj === 'string') {
30878 return obj;
30879 }
30880
30881 if (null === obj) return 'null';
30882 if (undefined === obj) return 'undefined';
30883
30884 if (Array.isArray(obj)) {
30885 // Reimplement Array.prototype.join according to spec (22.1.3.13)
30886 // Changing ToString(element) with this safe version of ToString.
30887 var r = '';
30888
30889 for (var k = 0; k < obj.length; k++) {
30890 if (k > 0) {
30891 r += ',';
30892 }
30893
30894 if (!isNone(obj[k])) {
30895 r += toString(obj[k]);
30896 }
30897 }
30898
30899 return r;
30900 }
30901
30902 if (typeof obj.toString === 'function') {
30903 return obj.toString();
30904 }
30905
30906 return objectToString$1.call(obj);
30907 }
30908
30909 var HAS_NATIVE_PROXY = typeof Proxy === 'function';
30910 _exports.HAS_NATIVE_PROXY = HAS_NATIVE_PROXY;
30911 var PROXIES = new _polyfills._WeakSet();
30912
30913 function isProxy(value) {
30914 if (isObject(value)) {
30915 return PROXIES.has(value);
30916 }
30917
30918 return false;
30919 }
30920
30921 function setProxy(object) {
30922 if (isObject(object)) {
30923 PROXIES.add(object);
30924 }
30925 }
30926
30927 class Cache {
30928 constructor(limit, func, store) {
30929 this.limit = limit;
30930 this.func = func;
30931 this.store = store;
30932 this.size = 0;
30933 this.misses = 0;
30934 this.hits = 0;
30935 this.store = store || new Map();
30936 }
30937
30938 get(key) {
30939 if (this.store.has(key)) {
30940 this.hits++;
30941 return this.store.get(key);
30942 } else {
30943 this.misses++;
30944 return this.set(key, this.func(key));
30945 }
30946 }
30947
30948 set(key, value) {
30949 if (this.limit > this.size) {
30950 this.size++;
30951 this.store.set(key, value);
30952 }
30953
30954 return value;
30955 }
30956
30957 purge() {
30958 this.store.clear();
30959 this.size = 0;
30960 this.hits = 0;
30961 this.misses = 0;
30962 }
30963
30964 }
30965
30966 _exports.Cache = Cache;
30967 var EMBER_ARRAYS = new _polyfills._WeakSet();
30968
30969 function setEmberArray(obj) {
30970 EMBER_ARRAYS.add(obj);
30971 }
30972
30973 function isEmberArray(obj) {
30974 return EMBER_ARRAYS.has(obj);
30975 }
30976
30977 var setupMandatorySetter;
30978 _exports.setupMandatorySetter = setupMandatorySetter;
30979 var teardownMandatorySetter;
30980 _exports.teardownMandatorySetter = teardownMandatorySetter;
30981 var setWithMandatorySetter;
30982 _exports.setWithMandatorySetter = setWithMandatorySetter;
30983
30984 function isElementKey(key) {
30985 return typeof key === 'number' ? isPositiveInt(key) : isStringInt(key);
30986 }
30987
30988 function isStringInt(str) {
30989 var num = parseInt(str, 10);
30990 return isPositiveInt(num) && str === String(num);
30991 }
30992
30993 function isPositiveInt(num) {
30994 return num >= 0 && num % 1 === 0;
30995 }
30996
30997 if (true
30998 /* DEBUG */
30999 ) {
31000 var SEEN_TAGS = new _polyfills._WeakSet();
31001 var MANDATORY_SETTERS = new WeakMap();
31002
31003 var _propertyIsEnumerable = function (obj, key) {
31004 return Object.prototype.propertyIsEnumerable.call(obj, key);
31005 };
31006
31007 _exports.setupMandatorySetter = setupMandatorySetter = function (tag, obj, keyName) {
31008 if (SEEN_TAGS.has(tag)) {
31009 return;
31010 }
31011
31012 SEEN_TAGS.add(tag);
31013
31014 if (Array.isArray(obj) && isElementKey(keyName)) {
31015 return;
31016 }
31017
31018 var desc = lookupDescriptor(obj, keyName) || {};
31019
31020 if (desc.get || desc.set) {
31021 // if it has a getter or setter, we can't install the mandatory setter.
31022 // native setters are allowed, we have to assume that they will resolve
31023 // to tracked properties.
31024 return;
31025 }
31026
31027 if (desc && (!desc.configurable || !desc.writable)) {
31028 // if it isn't writable anyways, so we shouldn't provide the setter.
31029 // if it isn't configurable, we can't overwrite it anyways.
31030 return;
31031 }
31032
31033 var setters = MANDATORY_SETTERS.get(obj);
31034
31035 if (setters === undefined) {
31036 setters = {};
31037 MANDATORY_SETTERS.set(obj, setters);
31038 }
31039
31040 desc.hadOwnProperty = Object.hasOwnProperty.call(obj, keyName);
31041 setters[keyName] = desc;
31042 Object.defineProperty(obj, keyName, {
31043 configurable: true,
31044 enumerable: _propertyIsEnumerable(obj, keyName),
31045
31046 get() {
31047 if (desc.get) {
31048 return desc.get.call(this);
31049 } else {
31050 return desc.value;
31051 }
31052 },
31053
31054 set(value) {
31055 (true && !(false) && (0, _debug.assert)(`You attempted to update ${this}.${String(keyName)} to "${String(value)}", but it is being tracked by a tracking context, such as a template, computed property, or observer. In order to make sure the context updates properly, you must invalidate the property when updating it. You can mark the property as \`@tracked\`, or use \`@ember/object#set\` to do this.`));
31056 }
31057
31058 });
31059 };
31060
31061 _exports.teardownMandatorySetter = teardownMandatorySetter = function (obj, keyName) {
31062 var setters = MANDATORY_SETTERS.get(obj);
31063
31064 if (setters !== undefined && setters[keyName] !== undefined) {
31065 Object.defineProperty(obj, keyName, setters[keyName]);
31066 setters[keyName] = undefined;
31067 }
31068 };
31069
31070 _exports.setWithMandatorySetter = setWithMandatorySetter = function (obj, keyName, value) {
31071 var setters = MANDATORY_SETTERS.get(obj);
31072
31073 if (setters !== undefined && setters[keyName] !== undefined) {
31074 var setter = setters[keyName];
31075
31076 if (setter.set) {
31077 setter.set.call(obj, value);
31078 } else {
31079 setter.value = value; // If the object didn't have own property before, it would have changed
31080 // the enumerability after setting the value the first time.
31081
31082 if (!setter.hadOwnProperty) {
31083 var desc = lookupDescriptor(obj, keyName);
31084 desc.enumerable = true;
31085 Object.defineProperty(obj, keyName, desc);
31086 }
31087 }
31088 } else {
31089 obj[keyName] = value;
31090 }
31091 };
31092 }
31093 /*
31094 This package will be eagerly parsed and should have no dependencies on external
31095 packages.
31096
31097 It is intended to be used to share utility methods that will be needed
31098 by every Ember application (and is **not** a dumping ground of useful utilities).
31099
31100 Utility methods that are needed in < 80% of cases should be placed
31101 elsewhere (so they can be lazily evaluated / parsed).
31102 */
31103
31104});
31105define("@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/action_manager"], 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, _action_manager) {
31106 "use strict";
31107
31108 Object.defineProperty(_exports, "__esModule", {
31109 value: true
31110 });
31111 Object.defineProperty(_exports, "jQuery", {
31112 enumerable: true,
31113 get: function () {
31114 return _jquery.jQuery;
31115 }
31116 });
31117 Object.defineProperty(_exports, "jQueryDisabled", {
31118 enumerable: true,
31119 get: function () {
31120 return _jquery.jQueryDisabled;
31121 }
31122 });
31123 Object.defineProperty(_exports, "addChildView", {
31124 enumerable: true,
31125 get: function () {
31126 return _utils.addChildView;
31127 }
31128 });
31129 Object.defineProperty(_exports, "isSimpleClick", {
31130 enumerable: true,
31131 get: function () {
31132 return _utils.isSimpleClick;
31133 }
31134 });
31135 Object.defineProperty(_exports, "getViewBounds", {
31136 enumerable: true,
31137 get: function () {
31138 return _utils.getViewBounds;
31139 }
31140 });
31141 Object.defineProperty(_exports, "getViewClientRects", {
31142 enumerable: true,
31143 get: function () {
31144 return _utils.getViewClientRects;
31145 }
31146 });
31147 Object.defineProperty(_exports, "getViewBoundingClientRect", {
31148 enumerable: true,
31149 get: function () {
31150 return _utils.getViewBoundingClientRect;
31151 }
31152 });
31153 Object.defineProperty(_exports, "getRootViews", {
31154 enumerable: true,
31155 get: function () {
31156 return _utils.getRootViews;
31157 }
31158 });
31159 Object.defineProperty(_exports, "getChildViews", {
31160 enumerable: true,
31161 get: function () {
31162 return _utils.getChildViews;
31163 }
31164 });
31165 Object.defineProperty(_exports, "getViewId", {
31166 enumerable: true,
31167 get: function () {
31168 return _utils.getViewId;
31169 }
31170 });
31171 Object.defineProperty(_exports, "getElementView", {
31172 enumerable: true,
31173 get: function () {
31174 return _utils.getElementView;
31175 }
31176 });
31177 Object.defineProperty(_exports, "getViewElement", {
31178 enumerable: true,
31179 get: function () {
31180 return _utils.getViewElement;
31181 }
31182 });
31183 Object.defineProperty(_exports, "setElementView", {
31184 enumerable: true,
31185 get: function () {
31186 return _utils.setElementView;
31187 }
31188 });
31189 Object.defineProperty(_exports, "setViewElement", {
31190 enumerable: true,
31191 get: function () {
31192 return _utils.setViewElement;
31193 }
31194 });
31195 Object.defineProperty(_exports, "clearElementView", {
31196 enumerable: true,
31197 get: function () {
31198 return _utils.clearElementView;
31199 }
31200 });
31201 Object.defineProperty(_exports, "clearViewElement", {
31202 enumerable: true,
31203 get: function () {
31204 return _utils.clearViewElement;
31205 }
31206 });
31207 Object.defineProperty(_exports, "constructStyleDeprecationMessage", {
31208 enumerable: true,
31209 get: function () {
31210 return _utils.constructStyleDeprecationMessage;
31211 }
31212 });
31213 Object.defineProperty(_exports, "EventDispatcher", {
31214 enumerable: true,
31215 get: function () {
31216 return _event_dispatcher.default;
31217 }
31218 });
31219 Object.defineProperty(_exports, "ComponentLookup", {
31220 enumerable: true,
31221 get: function () {
31222 return _component_lookup.default;
31223 }
31224 });
31225 Object.defineProperty(_exports, "TextSupport", {
31226 enumerable: true,
31227 get: function () {
31228 return _text_support.default;
31229 }
31230 });
31231 Object.defineProperty(_exports, "CoreView", {
31232 enumerable: true,
31233 get: function () {
31234 return _core_view.default;
31235 }
31236 });
31237 Object.defineProperty(_exports, "ClassNamesSupport", {
31238 enumerable: true,
31239 get: function () {
31240 return _class_names_support.default;
31241 }
31242 });
31243 Object.defineProperty(_exports, "ChildViewsSupport", {
31244 enumerable: true,
31245 get: function () {
31246 return _child_views_support.default;
31247 }
31248 });
31249 Object.defineProperty(_exports, "ViewStateSupport", {
31250 enumerable: true,
31251 get: function () {
31252 return _view_state_support.default;
31253 }
31254 });
31255 Object.defineProperty(_exports, "ViewMixin", {
31256 enumerable: true,
31257 get: function () {
31258 return _view_support.default;
31259 }
31260 });
31261 Object.defineProperty(_exports, "ActionSupport", {
31262 enumerable: true,
31263 get: function () {
31264 return _action_support.default;
31265 }
31266 });
31267 Object.defineProperty(_exports, "MUTABLE_CELL", {
31268 enumerable: true,
31269 get: function () {
31270 return _attrs.MUTABLE_CELL;
31271 }
31272 });
31273 Object.defineProperty(_exports, "ActionManager", {
31274 enumerable: true,
31275 get: function () {
31276 return _action_manager.default;
31277 }
31278 });
31279});
31280define("@ember/-internals/views/lib/compat/attrs", ["exports", "@ember/-internals/utils"], function (_exports, _utils) {
31281 "use strict";
31282
31283 Object.defineProperty(_exports, "__esModule", {
31284 value: true
31285 });
31286 _exports.MUTABLE_CELL = void 0;
31287 var MUTABLE_CELL = (0, _utils.symbol)('MUTABLE_CELL');
31288 _exports.MUTABLE_CELL = MUTABLE_CELL;
31289});
31290define("@ember/-internals/views/lib/compat/fallback-view-registry", ["exports", "@ember/-internals/utils"], function (_exports, _utils) {
31291 "use strict";
31292
31293 Object.defineProperty(_exports, "__esModule", {
31294 value: true
31295 });
31296 _exports.default = void 0;
31297
31298 var _default = (0, _utils.dictionary)(null);
31299
31300 _exports.default = _default;
31301});
31302define("@ember/-internals/views/lib/component_lookup", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
31303 "use strict";
31304
31305 Object.defineProperty(_exports, "__esModule", {
31306 value: true
31307 });
31308 _exports.default = void 0;
31309
31310 var _default = _runtime.Object.extend({
31311 componentFor(name, owner, options) {
31312 var fullName = `component:${name}`;
31313 return owner.factoryFor(fullName, options);
31314 },
31315
31316 layoutFor(name, owner, options) {
31317 var templateFullName = `template:components/${name}`;
31318 return owner.lookup(templateFullName, options);
31319 }
31320
31321 });
31322
31323 _exports.default = _default;
31324});
31325define("@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) {
31326 "use strict";
31327
31328 Object.defineProperty(_exports, "__esModule", {
31329 value: true
31330 });
31331 _exports.default = void 0;
31332
31333 /**
31334 @module ember
31335 */
31336 var mixinObj = {
31337 send(actionName, ...args) {
31338 (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));
31339 var action = this.actions && this.actions[actionName];
31340
31341 if (action) {
31342 var shouldBubble = action.apply(this, args) === true;
31343
31344 if (!shouldBubble) {
31345 return;
31346 }
31347 }
31348
31349 var target = (0, _metal.get)(this, 'target');
31350
31351 if (target) {
31352 (true && !(typeof target.send === 'function') && (0, _debug.assert)(`The \`target\` for ${this} (${target}) does not have a \`send\` method`, typeof target.send === 'function'));
31353 target.send(...arguments);
31354 } else {
31355 (true && !(action) && (0, _debug.assert)(`${(0, _utils.inspect)(this)} had no action handler for: ${actionName}`, action));
31356 }
31357 }
31358
31359 };
31360
31361 if (_deprecatedFeatures.SEND_ACTION) {
31362 /**
31363 Calls an action passed to a component.
31364 For example a component for playing or pausing music may translate click events
31365 into action notifications of "play" or "stop" depending on some internal state
31366 of the component:
31367 ```app/components/play-button.js
31368 import Component from '@ember/component';
31369 export default Component.extend({
31370 click() {
31371 if (this.get('isPlaying')) {
31372 this.sendAction('play');
31373 } else {
31374 this.sendAction('stop');
31375 }
31376 }
31377 });
31378 ```
31379 The actions "play" and "stop" must be passed to this `play-button` component:
31380 ```handlebars
31381 {{! app/templates/application.hbs }}
31382 {{play-button play=(action "musicStarted") stop=(action "musicStopped")}}
31383 ```
31384 When the component receives a browser `click` event it translate this
31385 interaction into application-specific semantics ("play" or "stop") and
31386 calls the specified action.
31387 ```app/controller/application.js
31388 import Controller from '@ember/controller';
31389 export default Controller.extend({
31390 actions: {
31391 musicStarted() {
31392 // called when the play button is clicked
31393 // and the music started playing
31394 },
31395 musicStopped() {
31396 // called when the play button is clicked
31397 // and the music stopped playing
31398 }
31399 }
31400 });
31401 ```
31402 If no action is passed to `sendAction` a default name of "action"
31403 is assumed.
31404 ```app/components/next-button.js
31405 import Component from '@ember/component';
31406 export default Component.extend({
31407 click() {
31408 this.sendAction();
31409 }
31410 });
31411 ```
31412 ```handlebars
31413 {{! app/templates/application.hbs }}
31414 {{next-button action=(action "playNextSongInAlbum")}}
31415 ```
31416 ```app/controllers/application.js
31417 import Controller from '@ember/controller';
31418 export default Controller.extend({
31419 actions: {
31420 playNextSongInAlbum() {
31421 ...
31422 }
31423 }
31424 });
31425 ```
31426 @method sendAction
31427 @param [action] {String} the action to call
31428 @param [params] {*} arguments for the action
31429 @public
31430 @deprecated
31431 */
31432 var sendAction = function sendAction(action, ...contexts) {
31433 (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));
31434 (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, {
31435 id: 'ember-component.send-action',
31436 until: '4.0.0',
31437 url: 'https://emberjs.com/deprecations/v3.x#toc_ember-component-send-action'
31438 }));
31439 var actionName; // Send the default action
31440
31441 if (action === undefined) {
31442 action = 'action';
31443 }
31444
31445 actionName = (0, _metal.get)(this, `attrs.${action}`) || (0, _metal.get)(this, action);
31446 actionName = validateAction(this, actionName); // If no action name for that action could be found, just abort.
31447
31448 if (actionName === undefined) {
31449 return;
31450 }
31451
31452 if (typeof actionName === 'function') {
31453 actionName(...contexts);
31454 } else {
31455 this.triggerAction({
31456 action: actionName,
31457 actionContext: contexts
31458 });
31459 }
31460 };
31461
31462 var validateAction = function validateAction(component, actionName) {
31463 if (actionName && actionName[_attrs.MUTABLE_CELL]) {
31464 actionName = actionName.value;
31465 }
31466
31467 (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'));
31468 return actionName;
31469 };
31470
31471 mixinObj.sendAction = sendAction;
31472 }
31473 /**
31474 @class ActionSupport
31475 @namespace Ember
31476 @private
31477 */
31478
31479
31480 var _default = _metal.Mixin.create(mixinObj);
31481
31482 _exports.default = _default;
31483});
31484define("@ember/-internals/views/lib/mixins/child_views_support", ["exports", "@ember/-internals/metal", "@ember/-internals/views/lib/system/utils"], function (_exports, _metal, _utils) {
31485 "use strict";
31486
31487 Object.defineProperty(_exports, "__esModule", {
31488 value: true
31489 });
31490 _exports.default = void 0;
31491
31492 /**
31493 @module ember
31494 */
31495 var _default = _metal.Mixin.create({
31496 /**
31497 Array of child views. You should never edit this array directly.
31498 @property childViews
31499 @type Array
31500 @default []
31501 @private
31502 */
31503 childViews: (0, _metal.nativeDescDecorator)({
31504 configurable: false,
31505 enumerable: false,
31506
31507 get() {
31508 return (0, _utils.getChildViews)(this);
31509 }
31510
31511 }),
31512
31513 appendChild(view) {
31514 (0, _utils.addChildView)(this, view);
31515 }
31516
31517 });
31518
31519 _exports.default = _default;
31520});
31521define("@ember/-internals/views/lib/mixins/class_names_support", ["exports", "@ember/-internals/metal", "@ember/debug"], function (_exports, _metal, _debug) {
31522 "use strict";
31523
31524 Object.defineProperty(_exports, "__esModule", {
31525 value: true
31526 });
31527 _exports.default = void 0;
31528
31529 /**
31530 @module ember
31531 */
31532 var EMPTY_ARRAY = Object.freeze([]);
31533 /**
31534 @class ClassNamesSupport
31535 @namespace Ember
31536 @private
31537 */
31538
31539 var _default = _metal.Mixin.create({
31540 concatenatedProperties: ['classNames', 'classNameBindings'],
31541
31542 init() {
31543 this._super(...arguments);
31544
31545 (true && !((0, _metal.descriptorForProperty)(this, 'classNameBindings') === undefined && Array.isArray(this.classNameBindings)) && (0, _debug.assert)(`Only arrays are allowed for 'classNameBindings'`, (0, _metal.descriptorForProperty)(this, 'classNameBindings') === undefined && Array.isArray(this.classNameBindings)));
31546 (true && !((0, _metal.descriptorForProperty)(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, _metal.descriptorForProperty)(this, 'classNames') === undefined && Array.isArray(this.classNames)));
31547 },
31548
31549 /**
31550 Standard CSS class names to apply to the view's outer element. This
31551 property automatically inherits any class names defined by the view's
31552 superclasses as well.
31553 @property classNames
31554 @type Array
31555 @default ['ember-view']
31556 @public
31557 */
31558 classNames: EMPTY_ARRAY,
31559
31560 /**
31561 A list of properties of the view to apply as class names. If the property
31562 is a string value, the value of that string will be applied as a class
31563 name.
31564 ```javascript
31565 // Applies the 'high' class to the view element
31566 import Component from '@ember/component';
31567 Component.extend({
31568 classNameBindings: ['priority'],
31569 priority: 'high'
31570 });
31571 ```
31572 If the value of the property is a Boolean, the name of that property is
31573 added as a dasherized class name.
31574 ```javascript
31575 // Applies the 'is-urgent' class to the view element
31576 import Component from '@ember/component';
31577 Component.extend({
31578 classNameBindings: ['isUrgent'],
31579 isUrgent: true
31580 });
31581 ```
31582 If you would prefer to use a custom value instead of the dasherized
31583 property name, you can pass a binding like this:
31584 ```javascript
31585 // Applies the 'urgent' class to the view element
31586 import Component from '@ember/component';
31587 Component.extend({
31588 classNameBindings: ['isUrgent:urgent'],
31589 isUrgent: true
31590 });
31591 ```
31592 If you would like to specify a class that should only be added when the
31593 property is false, you can declare a binding like this:
31594 ```javascript
31595 // Applies the 'disabled' class to the view element
31596 import Component from '@ember/component';
31597 Component.extend({
31598 classNameBindings: ['isEnabled::disabled'],
31599 isEnabled: false
31600 });
31601 ```
31602 This list of properties is inherited from the component's superclasses as well.
31603 @property classNameBindings
31604 @type Array
31605 @default []
31606 @public
31607 */
31608 classNameBindings: EMPTY_ARRAY
31609 });
31610
31611 _exports.default = _default;
31612});
31613define("@ember/-internals/views/lib/mixins/text_support", ["exports", "@ember/-internals/metal", "@ember/-internals/runtime", "@ember/debug", "@ember/deprecated-features", "@ember/-internals/views"], function (_exports, _metal, _runtime, _debug, _deprecatedFeatures, _views) {
31614 "use strict";
31615
31616 Object.defineProperty(_exports, "__esModule", {
31617 value: true
31618 });
31619 _exports.default = void 0;
31620
31621 /**
31622 @module ember
31623 */
31624 var KEY_EVENTS = {
31625 13: 'insertNewline',
31626 27: 'cancel'
31627 };
31628 /**
31629 `TextSupport` is a shared mixin used by both `TextField` and
31630 `TextArea`. `TextSupport` adds a number of methods that allow you to
31631 specify a controller action to invoke when a certain event is fired on your
31632 text field or textarea. The specified controller action would get the current
31633 value of the field passed in as the only argument unless the value of
31634 the field is empty. In that case, the instance of the field itself is passed
31635 in as the only argument.
31636
31637 Let's use the pressing of the escape key as an example. If you wanted to
31638 invoke a controller action when a user presses the escape key while on your
31639 field, you would use the `escape-press` attribute on your field like so:
31640
31641 ```handlebars
31642 {{! application.hbs}}
31643
31644 {{input escape-press='alertUser'}}
31645 ```
31646
31647 ```javascript
31648 import Application from '@ember/application';
31649 import Controller from '@ember/controller';
31650 App = Application.create();
31651
31652 App.ApplicationController = Controller.extend({
31653 actions: {
31654 alertUser: function ( currentValue ) {
31655 alert( 'escape pressed, current value: ' + currentValue );
31656 }
31657 }
31658 });
31659 ```
31660
31661 The following chart is a visual representation of what takes place when the
31662 escape key is pressed in this scenario:
31663
31664 ```
31665 The Template
31666 +---------------------------+
31667 | |
31668 | escape-press='alertUser' |
31669 | | TextSupport Mixin
31670 +----+----------------------+ +-------------------------------+
31671 | | cancel method |
31672 | escape button pressed | |
31673 +-------------------------------> | checks for the `escape-press` |
31674 | attribute and pulls out the |
31675 +-------------------------------+ | `alertUser` value |
31676 | action name 'alertUser' +-------------------------------+
31677 | sent to controller
31678 v
31679 Controller
31680 +------------------------------------------ +
31681 | |
31682 | actions: { |
31683 | alertUser: function( currentValue ){ |
31684 | alert( 'the esc key was pressed!' ) |
31685 | } |
31686 | } |
31687 | |
31688 +-------------------------------------------+
31689 ```
31690
31691 Here are the events that we currently support along with the name of the
31692 attribute you would need to use on your field. To reiterate, you would use the
31693 attribute name like so:
31694
31695 ```handlebars
31696 {{input attribute-name='controllerAction'}}
31697 ```
31698
31699 ```
31700 +--------------------+----------------+
31701 | | |
31702 | event | attribute name |
31703 +--------------------+----------------+
31704 | new line inserted | insert-newline |
31705 | | |
31706 | enter key pressed | enter |
31707 | | |
31708 | cancel key pressed | escape-press |
31709 | | |
31710 | focusin | focus-in |
31711 | | |
31712 | focusout | focus-out |
31713 | | |
31714 | keypress | key-press |
31715 | | |
31716 | keyup | key-up |
31717 | | |
31718 | keydown | key-down |
31719 +--------------------+----------------+
31720 ```
31721
31722 @class TextSupport
31723 @namespace Ember
31724 @uses Ember.TargetActionSupport
31725 @extends Mixin
31726 @private
31727 */
31728
31729 var _default = _metal.Mixin.create(_runtime.TargetActionSupport, {
31730 value: '',
31731 attributeBindings: ['autocapitalize', 'autocorrect', 'autofocus', 'disabled', 'form', 'maxlength', 'minlength', 'placeholder', 'readonly', 'required', 'selectionDirection', 'spellcheck', 'tabindex', 'title'],
31732 placeholder: null,
31733 disabled: false,
31734 maxlength: null,
31735
31736 init() {
31737 this._super(...arguments);
31738
31739 this.on('paste', this, this._elementValueDidChange);
31740 this.on('cut', this, this._elementValueDidChange);
31741 this.on('input', this, this._elementValueDidChange);
31742 },
31743
31744 /**
31745 Whether the `keyUp` event that triggers an `action` to be sent continues
31746 propagating to other views.
31747 By default, when the user presses the return key on their keyboard and
31748 the text field has an `action` set, the action will be sent to the view's
31749 controller and the key event will stop propagating.
31750 If you would like parent views to receive the `keyUp` event even after an
31751 action has been dispatched, set `bubbles` to true.
31752 @property bubbles
31753 @type Boolean
31754 @default false
31755 @private
31756 */
31757 bubbles: false,
31758
31759 interpretKeyEvents(event) {
31760 var map = KEY_EVENTS;
31761 var method = map[event.keyCode];
31762
31763 this._elementValueDidChange();
31764
31765 if (method) {
31766 return this[method](event);
31767 }
31768 },
31769
31770 _elementValueDidChange() {
31771 (0, _metal.set)(this, 'value', this.element.value);
31772 },
31773
31774 change(event) {
31775 this._elementValueDidChange(event);
31776 },
31777
31778 /**
31779 Allows you to specify a controller action to invoke when either the `enter`
31780 key is pressed or, in the case of the field being a textarea, when a newline
31781 is inserted. To use this method, give your field an `insert-newline`
31782 attribute. The value of that attribute should be the name of the action
31783 in your controller that you wish to invoke.
31784 For an example on how to use the `insert-newline` attribute, please
31785 reference the example near the top of this file.
31786 @method insertNewline
31787 @param {Event} event
31788 @private
31789 */
31790 insertNewline(event) {
31791 sendAction('enter', this, event);
31792 sendAction('insert-newline', this, event);
31793 },
31794
31795 /**
31796 Allows you to specify a controller action to invoke when the escape button
31797 is pressed. To use this method, give your field an `escape-press`
31798 attribute. The value of that attribute should be the name of the action
31799 in your controller that you wish to invoke.
31800 For an example on how to use the `escape-press` attribute, please reference
31801 the example near the top of this file.
31802 @method cancel
31803 @param {Event} event
31804 @private
31805 */
31806 cancel(event) {
31807 sendAction('escape-press', this, event);
31808 },
31809
31810 /**
31811 Allows you to specify a controller action to invoke when a field receives
31812 focus. To use this method, give your field a `focus-in` attribute. The value
31813 of that attribute should be the name of the action in your controller
31814 that you wish to invoke.
31815 For an example on how to use the `focus-in` attribute, please reference the
31816 example near the top of this file.
31817 @method focusIn
31818 @param {Event} event
31819 @private
31820 */
31821 focusIn(event) {
31822 sendAction('focus-in', this, event);
31823 },
31824
31825 /**
31826 Allows you to specify a controller action to invoke when a field loses
31827 focus. To use this method, give your field a `focus-out` attribute. The value
31828 of that attribute should be the name of the action in your controller
31829 that you wish to invoke.
31830 For an example on how to use the `focus-out` attribute, please reference the
31831 example near the top of this file.
31832 @method focusOut
31833 @param {Event} event
31834 @private
31835 */
31836 focusOut(event) {
31837 this._elementValueDidChange(event);
31838
31839 sendAction('focus-out', this, event);
31840 },
31841
31842 /**
31843 Allows you to specify a controller action to invoke when a key is pressed.
31844 To use this method, give your field a `key-press` attribute. The value of
31845 that attribute should be the name of the action in your controller you
31846 that wish to invoke.
31847 For an example on how to use the `key-press` attribute, please reference the
31848 example near the top of this file.
31849 @method keyPress
31850 @param {Event} event
31851 @private
31852 */
31853 keyPress(event) {
31854 sendAction('key-press', this, event);
31855 },
31856
31857 /**
31858 Allows you to specify a controller action to invoke when a key-up event is
31859 fired. To use this method, give your field a `key-up` attribute. The value
31860 of that attribute should be the name of the action in your controller
31861 that you wish to invoke.
31862 For an example on how to use the `key-up` attribute, please reference the
31863 example near the top of this file.
31864 @method keyUp
31865 @param {Event} event
31866 @private
31867 */
31868 keyUp(event) {
31869 this.interpretKeyEvents(event);
31870 sendAction('key-up', this, event);
31871 },
31872
31873 /**
31874 Allows you to specify a controller action to invoke when a key-down event is
31875 fired. To use this method, give your field a `key-down` attribute. The value
31876 of that attribute should be the name of the action in your controller that
31877 you wish to invoke.
31878 For an example on how to use the `key-down` attribute, please reference the
31879 example near the top of this file.
31880 @method keyDown
31881 @param {Event} event
31882 @private
31883 */
31884 keyDown(event) {
31885 sendAction('key-down', this, event);
31886 }
31887
31888 }); // In principle, this shouldn't be necessary, but the legacy
31889 // sendAction semantics for TextField are different from
31890 // the component semantics so this method normalizes them.
31891
31892
31893 _exports.default = _default;
31894
31895 function sendAction(eventName, view, event) {
31896 var action = (0, _metal.get)(view, `attrs.${eventName}`);
31897
31898 if (action !== null && typeof action === 'object' && action[_views.MUTABLE_CELL] === true) {
31899 action = action.value;
31900 }
31901
31902 if (action === undefined) {
31903 action = (0, _metal.get)(view, eventName);
31904 }
31905
31906 var value = (0, _metal.get)(view, 'value');
31907
31908 if (_deprecatedFeatures.SEND_ACTION && typeof action === 'string') {
31909 var message = `Passing actions to components as strings (like \`<Input @${eventName}="${action}" />\`) is deprecated. Please use closure actions instead (\`<Input @${eventName}={{action "${action}"}} />\`).`;
31910 (true && !(false) && (0, _debug.deprecate)(message, false, {
31911 id: 'ember-component.send-action',
31912 until: '4.0.0',
31913 url: 'https://emberjs.com/deprecations/v3.x#toc_ember-component-send-action'
31914 }));
31915 view.triggerAction({
31916 action: action,
31917 actionContext: [value, event]
31918 });
31919 } else if (typeof action === 'function') {
31920 action(value, event);
31921 }
31922
31923 if (action && !(0, _metal.get)(view, 'bubbles')) {
31924 event.stopPropagation();
31925 }
31926 }
31927});
31928define("@ember/-internals/views/lib/mixins/view_state_support", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
31929 "use strict";
31930
31931 Object.defineProperty(_exports, "__esModule", {
31932 value: true
31933 });
31934 _exports.default = void 0;
31935
31936 /**
31937 @module ember
31938 */
31939 var _default = _metal.Mixin.create({
31940 _transitionTo(state) {
31941 var priorState = this._currentState;
31942 var currentState = this._currentState = this._states[state];
31943 this._state = state;
31944
31945 if (priorState && priorState.exit) {
31946 priorState.exit(this);
31947 }
31948
31949 if (currentState.enter) {
31950 currentState.enter(this);
31951 }
31952 }
31953
31954 });
31955
31956 _exports.default = _default;
31957});
31958define("@ember/-internals/views/lib/mixins/view_support", ["exports", "@ember/-internals/utils", "@ember/-internals/metal", "@ember/debug", "@ember/-internals/browser-environment", "@ember/-internals/views/lib/system/utils", "@ember/-internals/views/lib/system/jquery", "@ember/deprecated-features"], function (_exports, _utils, _metal, _debug, _browserEnvironment, _utils2, _jquery, _deprecatedFeatures) {
31959 "use strict";
31960
31961 Object.defineProperty(_exports, "__esModule", {
31962 value: true
31963 });
31964 _exports.default = void 0;
31965
31966 function K() {
31967 return this;
31968 }
31969
31970 var mixin = {
31971 /**
31972 A list of properties of the view to apply as attributes. If the property
31973 is a string value, the value of that string will be applied as the value
31974 for an attribute of the property's name.
31975 The following example creates a tag like `<div priority="high" />`.
31976 ```app/components/my-component.js
31977 import Component from '@ember/component';
31978 export default Component.extend({
31979 attributeBindings: ['priority'],
31980 priority: 'high'
31981 });
31982 ```
31983 If the value of the property is a Boolean, the attribute is treated as
31984 an HTML Boolean attribute. It will be present if the property is `true`
31985 and omitted if the property is `false`.
31986 The following example creates markup like `<div visible />`.
31987 ```app/components/my-component.js
31988 import Component from '@ember/component';
31989 export default Component.extend({
31990 attributeBindings: ['visible'],
31991 visible: true
31992 });
31993 ```
31994 If you would prefer to use a custom value instead of the property name,
31995 you can create the same markup as the last example with a binding like
31996 this:
31997 ```app/components/my-component.js
31998 import Component from '@ember/component';
31999 export default Component.extend({
32000 attributeBindings: ['isVisible:visible'],
32001 isVisible: true
32002 });
32003 ```
32004 This list of attributes is inherited from the component's superclasses,
32005 as well.
32006 @property attributeBindings
32007 @type Array
32008 @default []
32009 @public
32010 */
32011 concatenatedProperties: ['attributeBindings'],
32012
32013 // ..........................................................
32014 // TEMPLATE SUPPORT
32015 //
32016
32017 /**
32018 Return the nearest ancestor that is an instance of the provided
32019 class or mixin.
32020 @method nearestOfType
32021 @param {Class,Mixin} klass Subclass of Ember.View (or Ember.View itself),
32022 or an instance of Mixin.
32023 @return Ember.View
32024 @deprecated use `yield` and contextual components for composition instead.
32025 @private
32026 */
32027 nearestOfType(klass) {
32028 var view = this.parentView;
32029 var isOfType = klass instanceof _metal.Mixin ? view => klass.detect(view) : view => klass.detect(view.constructor);
32030
32031 while (view) {
32032 if (isOfType(view)) {
32033 return view;
32034 }
32035
32036 view = view.parentView;
32037 }
32038 },
32039
32040 /**
32041 Return the nearest ancestor that has a given property.
32042 @method nearestWithProperty
32043 @param {String} property A property name
32044 @return Ember.View
32045 @deprecated use `yield` and contextual components for composition instead.
32046 @private
32047 */
32048 nearestWithProperty(property) {
32049 var view = this.parentView;
32050
32051 while (view) {
32052 if (property in view) {
32053 return view;
32054 }
32055
32056 view = view.parentView;
32057 }
32058 },
32059
32060 /**
32061 Renders the view again. This will work regardless of whether the
32062 view is already in the DOM or not. If the view is in the DOM, the
32063 rendering process will be deferred to give bindings a chance
32064 to synchronize.
32065 If children were added during the rendering process using `appendChild`,
32066 `rerender` will remove them, because they will be added again
32067 if needed by the next `render`.
32068 In general, if the display of your view changes, you should modify
32069 the DOM element directly instead of manually calling `rerender`, which can
32070 be slow.
32071 @method rerender
32072 @public
32073 */
32074 rerender() {
32075 return this._currentState.rerender(this);
32076 },
32077
32078 // ..........................................................
32079 // ELEMENT SUPPORT
32080 //
32081
32082 /**
32083 Returns the current DOM element for the view.
32084 @property element
32085 @type DOMElement
32086 @public
32087 */
32088 element: (0, _metal.nativeDescDecorator)({
32089 configurable: false,
32090 enumerable: false,
32091
32092 get() {
32093 return this.renderer.getElement(this);
32094 }
32095
32096 }),
32097
32098 /**
32099 Appends the view's element to the specified parent element.
32100 Note that this method just schedules the view to be appended; the DOM
32101 element will not be appended to the given element until all bindings have
32102 finished synchronizing.
32103 This is not typically a function that you will need to call directly when
32104 building your application. If you do need to use `appendTo`, be sure that
32105 the target element you are providing is associated with an `Application`
32106 and does not have an ancestor element that is associated with an Ember view.
32107 @method appendTo
32108 @param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object
32109 @return {Ember.View} receiver
32110 @private
32111 */
32112 appendTo(selector) {
32113 var target;
32114
32115 if (_browserEnvironment.hasDOM) {
32116 target = typeof selector === 'string' ? document.querySelector(selector) : selector;
32117 (true && !(target) && (0, _debug.assert)(`You tried to append to (${selector}) but that isn't in the DOM`, target));
32118 (true && !(!(0, _utils2.matches)(target, '.ember-view')) && (0, _debug.assert)('You cannot append to an existing Ember.View.', !(0, _utils2.matches)(target, '.ember-view')));
32119 (true && !((() => {
32120 var node = target.parentNode;
32121
32122 while (node) {
32123 if (node.nodeType !== 9 && (0, _utils2.matches)(node, '.ember-view')) {
32124 return false;
32125 }
32126
32127 node = node.parentNode;
32128 }
32129
32130 return true;
32131 })()) && (0, _debug.assert)('You cannot append to an existing Ember.View.', (() => {
32132 var node = target.parentNode;
32133
32134 while (node) {
32135 if (node.nodeType !== 9 && (0, _utils2.matches)(node, '.ember-view')) {
32136 return false;
32137 }
32138
32139 node = node.parentNode;
32140 }
32141
32142 return true;
32143 })()));
32144 } else {
32145 target = selector;
32146 (true && !(typeof target !== 'string') && (0, _debug.assert)(`You tried to append to a selector string (${selector}) in an environment without jQuery`, typeof target !== 'string'));
32147 (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'));
32148 }
32149
32150 this.renderer.appendTo(this, target);
32151 return this;
32152 },
32153
32154 /**
32155 Appends the view's element to the document body. If the view does
32156 not have an HTML representation yet
32157 the element will be generated automatically.
32158 If your application uses the `rootElement` property, you must append
32159 the view within that element. Rendering views outside of the `rootElement`
32160 is not supported.
32161 Note that this method just schedules the view to be appended; the DOM
32162 element will not be appended to the document body until all bindings have
32163 finished synchronizing.
32164 @method append
32165 @return {Ember.View} receiver
32166 @private
32167 */
32168 append() {
32169 return this.appendTo(document.body);
32170 },
32171
32172 /**
32173 The HTML `id` of the view's element in the DOM. You can provide this
32174 value yourself but it must be unique (just as in HTML):
32175 ```handlebars
32176 {{my-component elementId="a-really-cool-id"}}
32177 ```
32178 If not manually set a default value will be provided by the framework.
32179 Once rendered an element's `elementId` is considered immutable and you
32180 should never change it. If you need to compute a dynamic value for the
32181 `elementId`, you should do this when the component or element is being
32182 instantiated:
32183 ```app/components/my-component.js
32184 import Component from '@ember/component';
32185 export default Component.extend({
32186 init() {
32187 this._super(...arguments);
32188 let index = this.get('index');
32189 this.set('elementId', 'component-id' + index);
32190 }
32191 });
32192 ```
32193 @property elementId
32194 @type String
32195 @public
32196 */
32197 elementId: null,
32198
32199 /**
32200 Called when a view is going to insert an element into the DOM.
32201 @event willInsertElement
32202 @public
32203 */
32204 willInsertElement: K,
32205
32206 /**
32207 Called when the element of the view has been inserted into the DOM.
32208 Override this function to do any set up that requires an element
32209 in the document body.
32210 When a view has children, didInsertElement will be called on the
32211 child view(s) first and on itself afterwards.
32212 @event didInsertElement
32213 @public
32214 */
32215 didInsertElement: K,
32216
32217 /**
32218 Called when the view is about to rerender, but before anything has
32219 been torn down. This is a good opportunity to tear down any manual
32220 observers you have installed based on the DOM state
32221 @event willClearRender
32222 @public
32223 */
32224 willClearRender: K,
32225
32226 /**
32227 You must call `destroy` on a view to destroy the view (and all of its
32228 child views). This will remove the view from any parent node, then make
32229 sure that the DOM element managed by the view can be released by the
32230 memory manager.
32231 @method destroy
32232 @private
32233 */
32234 destroy() {
32235 this._super(...arguments);
32236
32237 this._currentState.destroy(this);
32238 },
32239
32240 /**
32241 Called when the element of the view is going to be destroyed. Override
32242 this function to do any teardown that requires an element, like removing
32243 event listeners.
32244 Please note: any property changes made during this event will have no
32245 effect on object observers.
32246 @event willDestroyElement
32247 @public
32248 */
32249 willDestroyElement: K,
32250
32251 /**
32252 Called after the element of the view is destroyed.
32253 @event willDestroyElement
32254 @public
32255 */
32256 didDestroyElement: K,
32257
32258 /**
32259 Called when the parentView property has changed.
32260 @event parentViewDidChange
32261 @private
32262 */
32263 parentViewDidChange: K,
32264 // ..........................................................
32265 // STANDARD RENDER PROPERTIES
32266 //
32267
32268 /**
32269 Tag name for the view's outer element. The tag name is only used when an
32270 element is first created. If you change the `tagName` for an element, you
32271 must destroy and recreate the view element.
32272 By default, the render buffer will use a `<div>` tag for views.
32273 If the tagName is `''`, the view will be tagless, with no outer element.
32274 Component properties that depend on the presence of an outer element, such
32275 as `classNameBindings` and `attributeBindings`, do not work with tagless
32276 components. Tagless components cannot implement methods to handle events,
32277 and have no associated jQuery object to return with `$()`.
32278 @property tagName
32279 @type String
32280 @default null
32281 @public
32282 */
32283 // We leave this null by default so we can tell the difference between
32284 // the default case and a user-specified tag.
32285 tagName: null,
32286
32287 // .......................................................
32288 // CORE DISPLAY METHODS
32289 //
32290
32291 /**
32292 Setup a view, but do not finish waking it up.
32293 * configure `childViews`
32294 * register the view with the global views hash, which is used for event
32295 dispatch
32296 @method init
32297 @private
32298 */
32299 init() {
32300 this._super(...arguments); // tslint:disable-next-line:max-line-length
32301
32302
32303 (true && !((0, _metal.descriptorForProperty)(this, 'elementId') === undefined) && (0, _debug.assert)(`You cannot use a computed property for the component's \`elementId\` (${this}).`, (0, _metal.descriptorForProperty)(this, 'elementId') === undefined)); // tslint:disable-next-line:max-line-length
32304
32305 (true && !((0, _metal.descriptorForProperty)(this, 'tagName') === undefined) && (0, _debug.assert)(`You cannot use a computed property for the component's \`tagName\` (${this}).`, (0, _metal.descriptorForProperty)(this, 'tagName') === undefined));
32306
32307 if (!this.elementId && this.tagName !== '') {
32308 this.elementId = (0, _utils.guidFor)(this);
32309 }
32310
32311 (true && !(!this.render) && (0, _debug.assert)('Using a custom `.render` function is no longer supported.', !this.render));
32312 },
32313
32314 // .......................................................
32315 // EVENT HANDLING
32316 //
32317
32318 /**
32319 Handle events from `EventDispatcher`
32320 @method handleEvent
32321 @param eventName {String}
32322 @param evt {Event}
32323 @private
32324 */
32325 handleEvent(eventName, evt) {
32326 return this._currentState.handleEvent(this, eventName, evt);
32327 }
32328
32329 };
32330
32331 if (_deprecatedFeatures.JQUERY_INTEGRATION) {
32332 /**
32333 Returns a jQuery object for this view's element. If you pass in a selector
32334 string, this method will return a jQuery object, using the current element
32335 as its buffer.
32336 For example, calling `view.$('li')` will return a jQuery object containing
32337 all of the `li` elements inside the DOM element of this view.
32338 @method $
32339 @param {String} [selector] a jQuery-compatible selector string
32340 @return {jQuery} the jQuery object for the DOM node
32341 @public
32342 @deprecated
32343 */
32344 mixin.$ = function $(sel) {
32345 (true && !(this.tagName !== '') && (0, _debug.assert)("You cannot access this.$() on a component with `tagName: ''` specified.", this.tagName !== ''));
32346 (true && !(!_jquery.jQueryDisabled) && (0, _debug.assert)('You cannot access this.$() with `jQuery` disabled.', !_jquery.jQueryDisabled));
32347 (true && !(false) && (0, _debug.deprecate)('Using this.$() in a component has been deprecated, consider using this.element', false, {
32348 id: 'ember-views.curly-components.jquery-element',
32349 until: '4.0.0',
32350 url: 'https://emberjs.com/deprecations/v3.x#toc_jquery-apis'
32351 }));
32352
32353 if (this.element) {
32354 return sel ? (0, _jquery.jQuery)(sel, this.element) : (0, _jquery.jQuery)(this.element);
32355 }
32356 };
32357 }
32358 /**
32359 @class ViewMixin
32360 @namespace Ember
32361 @private
32362 */
32363
32364
32365 var _default = _metal.Mixin.create(mixin);
32366
32367 _exports.default = _default;
32368});
32369define("@ember/-internals/views/lib/system/action_manager", ["exports"], function (_exports) {
32370 "use strict";
32371
32372 Object.defineProperty(_exports, "__esModule", {
32373 value: true
32374 });
32375 _exports.default = ActionManager;
32376
32377 /**
32378 @module ember
32379 */
32380 function ActionManager() {}
32381 /**
32382 Global action id hash.
32383
32384 @private
32385 @property registeredActions
32386 @type Object
32387 */
32388
32389
32390 ActionManager.registeredActions = {};
32391});
32392define("@ember/-internals/views/lib/system/event_dispatcher", ["exports", "@ember/-internals/owner", "@ember/polyfills", "@ember/debug", "@ember/-internals/metal", "@ember/-internals/runtime", "@ember/-internals/views", "@ember/-internals/views/lib/system/jquery", "@ember/-internals/views/lib/system/action_manager", "@ember/-internals/views/lib/system/jquery_event_deprecation", "@ember/-internals/views/lib/system/utils", "@ember/deprecated-features"], function (_exports, _owner, _polyfills, _debug, _metal, _runtime, _views, _jquery, _action_manager, _jquery_event_deprecation, _utils, _deprecatedFeatures) {
32393 "use strict";
32394
32395 Object.defineProperty(_exports, "__esModule", {
32396 value: true
32397 });
32398 _exports.default = void 0;
32399
32400 /**
32401 @module ember
32402 */
32403 var ROOT_ELEMENT_CLASS = 'ember-application';
32404 var ROOT_ELEMENT_SELECTOR = `.${ROOT_ELEMENT_CLASS}`;
32405 var EVENT_MAP = {
32406 mouseenter: 'mouseover',
32407 mouseleave: 'mouseout'
32408 };
32409 /**
32410 `Ember.EventDispatcher` handles delegating browser events to their
32411 corresponding `Ember.Views.` For example, when you click on a view,
32412 `Ember.EventDispatcher` ensures that that view's `mouseDown` method gets
32413 called.
32414
32415 @class EventDispatcher
32416 @namespace Ember
32417 @private
32418 @extends Ember.Object
32419 */
32420
32421 var _default = _runtime.Object.extend({
32422 /**
32423 The set of events names (and associated handler function names) to be setup
32424 and dispatched by the `EventDispatcher`. Modifications to this list can be done
32425 at setup time, generally via the `Application.customEvents` hash.
32426 To add new events to be listened to:
32427 ```javascript
32428 import Application from '@ember/application';
32429 let App = Application.create({
32430 customEvents: {
32431 paste: 'paste'
32432 }
32433 });
32434 ```
32435 To prevent default events from being listened to:
32436 ```javascript
32437 import Application from '@ember/application';
32438 let App = Application.create({
32439 customEvents: {
32440 mouseenter: null,
32441 mouseleave: null
32442 }
32443 });
32444 ```
32445 @property events
32446 @type Object
32447 @private
32448 */
32449 events: (0, _polyfills.assign)({
32450 touchstart: 'touchStart',
32451 touchmove: 'touchMove',
32452 touchend: 'touchEnd',
32453 touchcancel: 'touchCancel',
32454 keydown: 'keyDown',
32455 keyup: 'keyUp',
32456 keypress: 'keyPress',
32457 mousedown: 'mouseDown',
32458 mouseup: 'mouseUp',
32459 contextmenu: 'contextMenu',
32460 click: 'click',
32461 dblclick: 'doubleClick',
32462 focusin: 'focusIn',
32463 focusout: 'focusOut',
32464 submit: 'submit',
32465 input: 'input',
32466 change: 'change',
32467 dragstart: 'dragStart',
32468 drag: 'drag',
32469 dragenter: 'dragEnter',
32470 dragleave: 'dragLeave',
32471 dragover: 'dragOver',
32472 drop: 'drop',
32473 dragend: 'dragEnd'
32474 }, _deprecatedFeatures.MOUSE_ENTER_LEAVE_MOVE_EVENTS ? {
32475 mouseenter: 'mouseEnter',
32476 mouseleave: 'mouseLeave',
32477 mousemove: 'mouseMove'
32478 } : {}),
32479
32480 /**
32481 The root DOM element to which event listeners should be attached. Event
32482 listeners will be attached to the document unless this is overridden.
32483 Can be specified as a DOMElement or a selector string.
32484 The default body is a string since this may be evaluated before document.body
32485 exists in the DOM.
32486 @private
32487 @property rootElement
32488 @type DOMElement
32489 @default 'body'
32490 */
32491 rootElement: 'body',
32492
32493 init() {
32494 this._super();
32495
32496 (true && !((() => {
32497 var owner = (0, _owner.getOwner)(this);
32498 var environment = owner.lookup('-environment:main');
32499 return environment.isInteractive;
32500 })()) && (0, _debug.assert)('EventDispatcher should never be instantiated in fastboot mode. Please report this as an Ember bug.', (() => {
32501 var owner = (0, _owner.getOwner)(this);
32502 var environment = owner.lookup('-environment:main');
32503 return environment.isInteractive;
32504 })()));
32505 this._eventHandlers = Object.create(null);
32506 },
32507
32508 /**
32509 Sets up event listeners for standard browser events.
32510 This will be called after the browser sends a `DOMContentReady` event. By
32511 default, it will set up all of the listeners on the document body. If you
32512 would like to register the listeners on a different element, set the event
32513 dispatcher's `root` property.
32514 @private
32515 @method setup
32516 @param addedEvents {Object}
32517 */
32518 setup(addedEvents, _rootElement) {
32519 var events = this._finalEvents = (0, _polyfills.assign)({}, (0, _metal.get)(this, 'events'), addedEvents);
32520
32521 if (_rootElement !== undefined && _rootElement !== null) {
32522 (0, _metal.set)(this, 'rootElement', _rootElement);
32523 }
32524
32525 var rootElementSelector = (0, _metal.get)(this, 'rootElement');
32526 var rootElement;
32527
32528 if (!_deprecatedFeatures.JQUERY_INTEGRATION || _jquery.jQueryDisabled) {
32529 if (typeof rootElementSelector !== 'string') {
32530 rootElement = rootElementSelector;
32531 } else {
32532 rootElement = document.querySelector(rootElementSelector);
32533 }
32534
32535 (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)));
32536 (true && !((() => {
32537 var target = rootElement.parentNode;
32538
32539 do {
32540 if (target.classList.contains(ROOT_ELEMENT_CLASS)) {
32541 return false;
32542 }
32543
32544 target = target.parentNode;
32545 } while (target && target.nodeType === 1);
32546
32547 return true;
32548 })()) && (0, _debug.assert)('You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application', (() => {
32549 var target = rootElement.parentNode;
32550
32551 do {
32552 if (target.classList.contains(ROOT_ELEMENT_CLASS)) {
32553 return false;
32554 }
32555
32556 target = target.parentNode;
32557 } while (target && target.nodeType === 1);
32558
32559 return true;
32560 })()));
32561 (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)));
32562 rootElement.classList.add(ROOT_ELEMENT_CLASS);
32563 (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)));
32564 } else {
32565 rootElement = (0, _jquery.jQuery)(rootElementSelector);
32566 (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)));
32567 (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));
32568 (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));
32569 rootElement.addClass(ROOT_ELEMENT_CLASS);
32570
32571 if (!rootElement.is(ROOT_ELEMENT_SELECTOR)) {
32572 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.`);
32573 }
32574 }
32575
32576 for (var event in events) {
32577 if (Object.prototype.hasOwnProperty.call(events, event)) {
32578 this.setupHandler(rootElement, event, events[event]);
32579 }
32580 }
32581 },
32582
32583 /**
32584 Registers an event listener on the rootElement. If the given event is
32585 triggered, the provided event handler will be triggered on the target view.
32586 If the target view does not implement the event handler, or if the handler
32587 returns `false`, the parent view will be called. The event will continue to
32588 bubble to each successive parent view until it reaches the top.
32589 @private
32590 @method setupHandler
32591 @param {Element} rootElement
32592 @param {String} event the browser-originated event to listen to
32593 @param {String} eventName the name of the method to call on the view
32594 */
32595 setupHandler(rootElement, event, eventName) {
32596 if (eventName === null) {
32597 return;
32598 }
32599
32600 if (!_deprecatedFeatures.JQUERY_INTEGRATION || _jquery.jQueryDisabled) {
32601 var viewHandler = (target, event) => {
32602 var view = (0, _views.getElementView)(target);
32603 var result = true;
32604
32605 if (view) {
32606 result = view.handleEvent(eventName, event);
32607 }
32608
32609 return result;
32610 };
32611
32612 var actionHandler = (target, event) => {
32613 var actionId = target.getAttribute('data-ember-action');
32614 var actions = _action_manager.default.registeredActions[actionId]; // In Glimmer2 this attribute is set to an empty string and an additional
32615 // attribute it set for each action on a given element. In this case, the
32616 // attributes need to be read so that a proper set of action handlers can
32617 // be coalesced.
32618
32619 if (actionId === '') {
32620 var attributes = target.attributes;
32621 var attributeCount = attributes.length;
32622 actions = [];
32623
32624 for (var i = 0; i < attributeCount; i++) {
32625 var attr = attributes.item(i);
32626 var attrName = attr.name;
32627
32628 if (attrName.indexOf('data-ember-action-') === 0) {
32629 actions = actions.concat(_action_manager.default.registeredActions[attr.value]);
32630 }
32631 }
32632 } // We have to check for actions here since in some cases, jQuery will trigger
32633 // an event on `removeChild` (i.e. focusout) after we've already torn down the
32634 // action handlers for the view.
32635
32636
32637 if (!actions) {
32638 return;
32639 }
32640
32641 var result = true;
32642
32643 for (var index = 0; index < actions.length; index++) {
32644 var action = actions[index];
32645
32646 if (action && action.eventName === eventName) {
32647 // return false if any of the action handlers returns false
32648 result = action.handler(event) && result;
32649 }
32650 }
32651
32652 return result;
32653 }; // Special handling of events that don't bubble (event delegation does not work).
32654 // Mimics the way this is handled in jQuery,
32655 // see https://github.com/jquery/jquery/blob/899c56f6ada26821e8af12d9f35fa039100e838e/src/event.js#L666-L700
32656
32657
32658 if (_deprecatedFeatures.MOUSE_ENTER_LEAVE_MOVE_EVENTS && EVENT_MAP[event] !== undefined) {
32659 var mappedEventType = EVENT_MAP[event];
32660 var origEventType = event;
32661
32662 var createFakeEvent = (eventType, event) => {
32663 var fakeEvent = document.createEvent('MouseEvent');
32664 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
32665
32666 Object.defineProperty(fakeEvent, 'target', {
32667 value: event.target,
32668 enumerable: true
32669 });
32670 return fakeEvent;
32671 };
32672
32673 var handleMappedEvent = this._eventHandlers[mappedEventType] = event => {
32674 var target = event.target;
32675 var related = event.relatedTarget;
32676
32677 while (target && target.nodeType === 1 && (related === null || related !== target && !(0, _utils.contains)(target, related))) {
32678 // mouseEnter/Leave don't bubble, so there is no logic to prevent it as with other events
32679 if ((0, _views.getElementView)(target)) {
32680 viewHandler(target, createFakeEvent(origEventType, event));
32681 } else if (target.hasAttribute('data-ember-action')) {
32682 actionHandler(target, createFakeEvent(origEventType, event));
32683 } // separate mouseEnter/Leave events are dispatched for each listening element
32684 // until the element (related) has been reached that the pointing device exited from/to
32685
32686
32687 target = target.parentNode;
32688 }
32689 };
32690
32691 rootElement.addEventListener(mappedEventType, handleMappedEvent);
32692 } else {
32693 var handleEvent = this._eventHandlers[event] = event => {
32694 var target = event.target;
32695
32696 do {
32697 if ((0, _views.getElementView)(target)) {
32698 if (viewHandler(target, event) === false) {
32699 event.preventDefault();
32700 event.stopPropagation();
32701 break;
32702 } else if (event.cancelBubble === true) {
32703 break;
32704 }
32705 } else if (typeof target.hasAttribute === 'function' && target.hasAttribute('data-ember-action')) {
32706 if (actionHandler(target, event) === false) {
32707 break;
32708 }
32709 }
32710
32711 target = target.parentNode;
32712 } while (target && target.nodeType === 1);
32713 };
32714
32715 rootElement.addEventListener(event, handleEvent);
32716 }
32717 } else {
32718 rootElement.on(`${event}.ember`, '.ember-view', function (evt) {
32719 var view = (0, _views.getElementView)(this);
32720 var result = true;
32721
32722 if (view) {
32723 result = view.handleEvent(eventName, (0, _jquery_event_deprecation.default)(evt));
32724 }
32725
32726 return result;
32727 });
32728 rootElement.on(`${event}.ember`, '[data-ember-action]', evt => {
32729 var attributes = evt.currentTarget.attributes;
32730 var handledActions = [];
32731 evt = (0, _jquery_event_deprecation.default)(evt);
32732
32733 for (var i = 0; i < attributes.length; i++) {
32734 var attr = attributes.item(i);
32735 var attrName = attr.name;
32736
32737 if (attrName.lastIndexOf('data-ember-action-', 0) !== -1) {
32738 var action = _action_manager.default.registeredActions[attr.value]; // We have to check for action here since in some cases, jQuery will trigger
32739 // an event on `removeChild` (i.e. focusout) after we've already torn down the
32740 // action handlers for the view.
32741
32742 if (action && action.eventName === eventName && handledActions.indexOf(action) === -1) {
32743 action.handler(evt); // Action handlers can mutate state which in turn creates new attributes on the element.
32744 // This effect could cause the `data-ember-action` attribute to shift down and be invoked twice.
32745 // To avoid this, we keep track of which actions have been handled.
32746
32747 handledActions.push(action);
32748 }
32749 }
32750 }
32751 });
32752 }
32753 },
32754
32755 destroy() {
32756 var rootElementSelector = (0, _metal.get)(this, 'rootElement');
32757 var rootElement;
32758
32759 if (rootElementSelector.nodeType) {
32760 rootElement = rootElementSelector;
32761 } else {
32762 rootElement = document.querySelector(rootElementSelector);
32763 }
32764
32765 if (!rootElement) {
32766 return;
32767 }
32768
32769 if (!_deprecatedFeatures.JQUERY_INTEGRATION || _jquery.jQueryDisabled) {
32770 for (var event in this._eventHandlers) {
32771 rootElement.removeEventListener(event, this._eventHandlers[event]);
32772 }
32773 } else {
32774 (0, _jquery.jQuery)(rootElementSelector).off('.ember', '**');
32775 }
32776
32777 rootElement.classList.remove(ROOT_ELEMENT_CLASS);
32778 return this._super(...arguments);
32779 },
32780
32781 toString() {
32782 return '(EventDispatcher)';
32783 }
32784
32785 });
32786
32787 _exports.default = _default;
32788});
32789define("@ember/-internals/views/lib/system/jquery", ["exports", "@ember/-internals/environment", "@ember/-internals/browser-environment", "@ember/deprecated-features"], function (_exports, _environment, _browserEnvironment, _deprecatedFeatures) {
32790 "use strict";
32791
32792 Object.defineProperty(_exports, "__esModule", {
32793 value: true
32794 });
32795 _exports.jQueryDisabled = _exports.jQuery = void 0;
32796 var jQuery;
32797 _exports.jQuery = jQuery;
32798 var jQueryDisabled = !_deprecatedFeatures.JQUERY_INTEGRATION || _environment.ENV._JQUERY_INTEGRATION === false;
32799 _exports.jQueryDisabled = jQueryDisabled;
32800
32801 if (_deprecatedFeatures.JQUERY_INTEGRATION && _browserEnvironment.hasDOM) {
32802 _exports.jQuery = jQuery = _environment.context.imports.jQuery;
32803
32804 if (!jQueryDisabled && jQuery) {
32805 if (jQuery.event.addProp) {
32806 jQuery.event.addProp('dataTransfer');
32807 } else {
32808 // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dndevents
32809 ['dragstart', 'drag', 'dragenter', 'dragleave', 'dragover', 'drop', 'dragend'].forEach(eventName => {
32810 jQuery.event.fixHooks[eventName] = {
32811 props: ['dataTransfer']
32812 };
32813 });
32814 }
32815 } else {
32816 _exports.jQuery = jQuery = undefined;
32817 _exports.jQueryDisabled = jQueryDisabled = true;
32818 }
32819 }
32820});
32821define("@ember/-internals/views/lib/system/jquery_event_deprecation", ["exports", "@ember/debug", "@ember/-internals/environment", "@ember/-internals/utils", "@ember/deprecated-features"], function (_exports, _debug, _environment, _utils, _deprecatedFeatures) {
32822 "use strict";
32823
32824 Object.defineProperty(_exports, "__esModule", {
32825 value: true
32826 });
32827 _exports.default = addJQueryEventDeprecation;
32828
32829 /* global Proxy */
32830 function addJQueryEventDeprecation(jqEvent) {
32831 if (true
32832 /* DEBUG */
32833 && _deprecatedFeatures.JQUERY_INTEGRATION && _utils.HAS_NATIVE_PROXY) {
32834 var boundFunctions = new Map(); // wrap the jQuery event in a Proxy to add the deprecation message for originalEvent, according to RFC#294
32835 // we need a native Proxy here, so we can make sure that the internal use of originalEvent in jQuery itself does
32836 // not trigger a deprecation
32837
32838 return new Proxy(jqEvent, {
32839 get(target, name) {
32840 switch (name) {
32841 case 'originalEvent':
32842 (true && !((EmberENV => {
32843 // this deprecation is intentionally checking `global.EmberENV` so
32844 // that we can ensure we _only_ deprecate in the case where jQuery
32845 // integration is enabled implicitly (e.g. "defaulted" to enabled)
32846 // as opposed to when the user explicitly opts in to using jQuery
32847 if (typeof EmberENV !== 'object' || EmberENV === null) return false;
32848 return EmberENV._JQUERY_INTEGRATION === true;
32849 })(_environment.global.EmberENV)) && (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 => {
32850 if (typeof EmberENV !== 'object' || EmberENV === null) return false;
32851 return EmberENV._JQUERY_INTEGRATION === true;
32852 })(_environment.global.EmberENV), {
32853 id: 'ember-views.event-dispatcher.jquery-event',
32854 until: '4.0.0',
32855 url: 'https://emberjs.com/deprecations/v3.x#toc_jquery-event'
32856 }));
32857 return target[name];
32858 // provide an escape hatch for ember-jquery-legacy to access originalEvent without a deprecation
32859
32860 case '__originalEvent':
32861 return target.originalEvent;
32862
32863 default:
32864 if (typeof target[name] === 'function') {
32865 // cache functions for reuse
32866 if (!boundFunctions.has(name)) {
32867 // for jQuery.Event methods call them with `target` as the `this` context, so they will access
32868 // `originalEvent` from the original jQuery event, not our proxy, thus not trigger the deprecation
32869 boundFunctions.set(name, target[name].bind(target));
32870 }
32871
32872 return boundFunctions.get(name);
32873 } // same for jQuery's getter functions for simple properties
32874
32875
32876 return target[name];
32877 }
32878 }
32879
32880 });
32881 }
32882
32883 return jqEvent;
32884 }
32885});
32886define("@ember/-internals/views/lib/system/utils", ["exports", "@ember/-internals/owner", "@ember/-internals/utils", "@ember/debug"], function (_exports, _owner, _utils, _debug) {
32887 "use strict";
32888
32889 Object.defineProperty(_exports, "__esModule", {
32890 value: true
32891 });
32892 _exports.isSimpleClick = isSimpleClick;
32893 _exports.constructStyleDeprecationMessage = constructStyleDeprecationMessage;
32894 _exports.getRootViews = getRootViews;
32895 _exports.getViewId = getViewId;
32896 _exports.getElementView = getElementView;
32897 _exports.getViewElement = getViewElement;
32898 _exports.setElementView = setElementView;
32899 _exports.setViewElement = setViewElement;
32900 _exports.clearElementView = clearElementView;
32901 _exports.clearViewElement = clearViewElement;
32902 _exports.getChildViews = getChildViews;
32903 _exports.initChildViews = initChildViews;
32904 _exports.addChildView = addChildView;
32905 _exports.collectChildViews = collectChildViews;
32906 _exports.getViewBounds = getViewBounds;
32907 _exports.getViewRange = getViewRange;
32908 _exports.getViewClientRects = getViewClientRects;
32909 _exports.getViewBoundingClientRect = getViewBoundingClientRect;
32910 _exports.matches = matches;
32911 _exports.contains = contains;
32912 _exports.elMatches = void 0;
32913
32914 /* globals Element */
32915
32916 /**
32917 @module ember
32918 */
32919 function isSimpleClick(event) {
32920 var modifier = event.shiftKey || event.metaKey || event.altKey || event.ctrlKey;
32921 var secondaryClick = event.which > 1; // IE9 may return undefined
32922
32923 return !modifier && !secondaryClick;
32924 }
32925
32926 function constructStyleDeprecationMessage(affectedStyle) {
32927 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 + '"';
32928 }
32929 /**
32930 @private
32931 @method getRootViews
32932 @param {Object} owner
32933 */
32934
32935
32936 function getRootViews(owner) {
32937 var registry = owner.lookup('-view-registry:main');
32938 var rootViews = [];
32939 Object.keys(registry).forEach(id => {
32940 var view = registry[id];
32941
32942 if (view.parentView === null) {
32943 rootViews.push(view);
32944 }
32945 });
32946 return rootViews;
32947 }
32948 /**
32949 @private
32950 @method getViewId
32951 @param {Ember.View} view
32952 */
32953
32954
32955 function getViewId(view) {
32956 if (view.tagName !== '' && view.elementId) {
32957 return view.elementId;
32958 } else {
32959 return (0, _utils.guidFor)(view);
32960 }
32961 }
32962
32963 var ELEMENT_VIEW = new WeakMap();
32964 var VIEW_ELEMENT = new WeakMap();
32965
32966 function getElementView(element) {
32967 return ELEMENT_VIEW.get(element) || null;
32968 }
32969 /**
32970 @private
32971 @method getViewElement
32972 @param {Ember.View} view
32973 */
32974
32975
32976 function getViewElement(view) {
32977 return VIEW_ELEMENT.get(view) || null;
32978 }
32979
32980 function setElementView(element, view) {
32981 ELEMENT_VIEW.set(element, view);
32982 }
32983
32984 function setViewElement(view, element) {
32985 VIEW_ELEMENT.set(view, element);
32986 } // These are not needed for GC, but for correctness. We want to be able to
32987 // null-out these links while the objects are still live. Specifically, in
32988 // this case, we want to prevent access to the element (and vice verse) during
32989 // destruction.
32990
32991
32992 function clearElementView(element) {
32993 ELEMENT_VIEW.delete(element);
32994 }
32995
32996 function clearViewElement(view) {
32997 VIEW_ELEMENT.delete(view);
32998 }
32999
33000 var CHILD_VIEW_IDS = new WeakMap();
33001 /**
33002 @private
33003 @method getChildViews
33004 @param {Ember.View} view
33005 */
33006
33007 function getChildViews(view) {
33008 var owner = (0, _owner.getOwner)(view);
33009 var registry = owner.lookup('-view-registry:main');
33010 return collectChildViews(view, registry);
33011 }
33012
33013 function initChildViews(view) {
33014 var childViews = new Set();
33015 CHILD_VIEW_IDS.set(view, childViews);
33016 return childViews;
33017 }
33018
33019 function addChildView(parent, child) {
33020 var childViews = CHILD_VIEW_IDS.get(parent);
33021
33022 if (childViews === undefined) {
33023 childViews = initChildViews(parent);
33024 }
33025
33026 childViews.add(getViewId(child));
33027 }
33028
33029 function collectChildViews(view, registry) {
33030 var views = [];
33031 var childViews = CHILD_VIEW_IDS.get(view);
33032
33033 if (childViews !== undefined) {
33034 childViews.forEach(id => {
33035 var view = registry[id];
33036
33037 if (view && !view.isDestroying && !view.isDestroyed) {
33038 views.push(view);
33039 }
33040 });
33041 }
33042
33043 return views;
33044 }
33045 /**
33046 @private
33047 @method getViewBounds
33048 @param {Ember.View} view
33049 */
33050
33051
33052 function getViewBounds(view) {
33053 return view.renderer.getBounds(view);
33054 }
33055 /**
33056 @private
33057 @method getViewRange
33058 @param {Ember.View} view
33059 */
33060
33061
33062 function getViewRange(view) {
33063 var bounds = getViewBounds(view);
33064 var range = document.createRange();
33065 range.setStartBefore(bounds.firstNode);
33066 range.setEndAfter(bounds.lastNode);
33067 return range;
33068 }
33069 /**
33070 `getViewClientRects` provides information about the position of the border
33071 box edges of a view relative to the viewport.
33072
33073 It is only intended to be used by development tools like the Ember Inspector
33074 and may not work on older browsers.
33075
33076 @private
33077 @method getViewClientRects
33078 @param {Ember.View} view
33079 */
33080
33081
33082 function getViewClientRects(view) {
33083 var range = getViewRange(view);
33084 return range.getClientRects();
33085 }
33086 /**
33087 `getViewBoundingClientRect` provides information about the position of the
33088 bounding border box edges of a view relative to the viewport.
33089
33090 It is only intended to be used by development tools like the Ember Inspector
33091 and may not work on older browsers.
33092
33093 @private
33094 @method getViewBoundingClientRect
33095 @param {Ember.View} view
33096 */
33097
33098
33099 function getViewBoundingClientRect(view) {
33100 var range = getViewRange(view);
33101 return range.getBoundingClientRect();
33102 }
33103 /**
33104 Determines if the element matches the specified selector.
33105
33106 @private
33107 @method matches
33108 @param {DOMElement} el
33109 @param {String} selector
33110 */
33111
33112
33113 var elMatches = typeof Element !== 'undefined' ? Element.prototype.matches || Element.prototype['matchesSelector'] || Element.prototype['mozMatchesSelector'] || Element.prototype['msMatchesSelector'] || Element.prototype['oMatchesSelector'] || Element.prototype['webkitMatchesSelector'] : undefined;
33114 _exports.elMatches = elMatches;
33115
33116 function matches(el, selector) {
33117 (true && !(elMatches !== undefined) && (0, _debug.assert)('cannot call `matches` in fastboot mode', elMatches !== undefined));
33118 return elMatches.call(el, selector);
33119 }
33120
33121 function contains(a, b) {
33122 if (a.contains !== undefined) {
33123 return a.contains(b);
33124 }
33125
33126 var current = b.parentNode;
33127
33128 while (current && (current = current.parentNode)) {
33129 if (current === a) {
33130 return true;
33131 }
33132 }
33133
33134 return false;
33135 }
33136});
33137define("@ember/-internals/views/lib/views/core_view", ["exports", "@ember/-internals/runtime", "@ember/-internals/views/lib/views/states"], function (_exports, _runtime, _states) {
33138 "use strict";
33139
33140 Object.defineProperty(_exports, "__esModule", {
33141 value: true
33142 });
33143 _exports.default = void 0;
33144
33145 /**
33146 `Ember.CoreView` is an abstract class that exists to give view-like behavior
33147 to both Ember's main view class `Component` and other classes that don't need
33148 the full functionality of `Component`.
33149
33150 Unless you have specific needs for `CoreView`, you will use `Component`
33151 in your applications.
33152
33153 @class CoreView
33154 @namespace Ember
33155 @extends EmberObject
33156 @deprecated Use `Component` instead.
33157 @uses Evented
33158 @uses Ember.ActionHandler
33159 @private
33160 */
33161 var CoreView = _runtime.FrameworkObject.extend(_runtime.Evented, _runtime.ActionHandler, {
33162 isView: true,
33163 _states: _states.default,
33164
33165 init() {
33166 this._super(...arguments);
33167
33168 this._state = 'preRender';
33169 this._currentState = this._states.preRender;
33170
33171 if (!this.renderer) {
33172 throw new Error(`Cannot instantiate a component without a renderer. Please ensure that you are creating ${this} with a proper container/registry.`);
33173 }
33174 },
33175
33176 /**
33177 If the view is currently inserted into the DOM of a parent view, this
33178 property will point to the parent of the view.
33179 @property parentView
33180 @type Ember.View
33181 @default null
33182 @private
33183 */
33184 parentView: null,
33185
33186 instrumentDetails(hash) {
33187 hash.object = this.toString();
33188 hash.containerKey = this._debugContainerKey;
33189 hash.view = this;
33190 return hash;
33191 },
33192
33193 /**
33194 Override the default event firing from `Evented` to
33195 also call methods with the given name.
33196 @method trigger
33197 @param name {String}
33198 @private
33199 */
33200 trigger(name, ...args) {
33201 this._super(...arguments);
33202
33203 var method = this[name];
33204
33205 if (typeof method === 'function') {
33206 return method.apply(this, args);
33207 }
33208 },
33209
33210 has(name) {
33211 return typeof this[name] === 'function' || this._super(name);
33212 }
33213
33214 });
33215
33216 CoreView.reopenClass({
33217 isViewFactory: true
33218 });
33219 var _default = CoreView;
33220 _exports.default = _default;
33221});
33222define("@ember/-internals/views/lib/views/states", ["exports", "@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, _pre_render, _has_element, _in_dom, _destroying) {
33223 "use strict";
33224
33225 Object.defineProperty(_exports, "__esModule", {
33226 value: true
33227 });
33228 _exports.default = void 0;
33229
33230 /*
33231 Describe how the specified actions should behave in the various
33232 states that a view can exist in. Possible states:
33233
33234 * preRender: when a view is first instantiated, and after its
33235 element was destroyed, it is in the preRender state
33236 * hasElement: the DOM representation of the view is created,
33237 and is ready to be inserted
33238 * inDOM: once a view has been inserted into the DOM it is in
33239 the inDOM state. A view spends the vast majority of its
33240 existence in this state.
33241 * destroyed: once a view has been destroyed (using the destroy
33242 method), it is in this state. No further actions can be invoked
33243 on a destroyed view.
33244 */
33245 var states = Object.freeze({
33246 preRender: _pre_render.default,
33247 inDOM: _in_dom.default,
33248 hasElement: _has_element.default,
33249 destroying: _destroying.default
33250 });
33251 var _default = states;
33252 _exports.default = _default;
33253});
33254define("@ember/-internals/views/lib/views/states/default", ["exports", "@ember/error"], function (_exports, _error) {
33255 "use strict";
33256
33257 Object.defineProperty(_exports, "__esModule", {
33258 value: true
33259 });
33260 _exports.default = void 0;
33261 var _default = {
33262 // appendChild is only legal while rendering the buffer.
33263 appendChild() {
33264 throw new _error.default("You can't use appendChild outside of the rendering process");
33265 },
33266
33267 // Handle events from `Ember.EventDispatcher`
33268 handleEvent() {
33269 return true; // continue event propagation
33270 },
33271
33272 rerender() {},
33273
33274 destroy() {}
33275
33276 };
33277
33278 var _default2 = Object.freeze(_default);
33279
33280 _exports.default = _default2;
33281});
33282define("@ember/-internals/views/lib/views/states/destroying", ["exports", "@ember/polyfills", "@ember/error", "@ember/-internals/views/lib/views/states/default"], function (_exports, _polyfills, _error, _default3) {
33283 "use strict";
33284
33285 Object.defineProperty(_exports, "__esModule", {
33286 value: true
33287 });
33288 _exports.default = void 0;
33289 var destroying = (0, _polyfills.assign)({}, _default3.default, {
33290 appendChild() {
33291 throw new _error.default("You can't call appendChild on a view being destroyed");
33292 },
33293
33294 rerender() {
33295 throw new _error.default("You can't call rerender on a view being destroyed");
33296 }
33297
33298 });
33299
33300 var _default2 = Object.freeze(destroying);
33301
33302 _exports.default = _default2;
33303});
33304define("@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, _default3, _runloop, _instrumentation) {
33305 "use strict";
33306
33307 Object.defineProperty(_exports, "__esModule", {
33308 value: true
33309 });
33310 _exports.default = void 0;
33311 var hasElement = (0, _polyfills.assign)({}, _default3.default, {
33312 rerender(view) {
33313 view.renderer.rerender(view);
33314 },
33315
33316 destroy(view) {
33317 view.renderer.remove(view);
33318 },
33319
33320 // Handle events from `Ember.EventDispatcher`
33321 handleEvent(view, eventName, event) {
33322 if (view.has(eventName)) {
33323 // Handler should be able to re-dispatch events, so we don't
33324 // preventDefault or stopPropagation.
33325 return (0, _instrumentation.flaggedInstrument)(`interaction.${eventName}`, {
33326 event,
33327 view
33328 }, () => {
33329 return (0, _runloop.join)(view, view.trigger, eventName, event);
33330 });
33331 } else {
33332 return true; // continue event propagation
33333 }
33334 }
33335
33336 });
33337
33338 var _default2 = Object.freeze(hasElement);
33339
33340 _exports.default = _default2;
33341});
33342define("@ember/-internals/views/lib/views/states/in_dom", ["exports", "@ember/-internals/utils", "@ember/polyfills", "@ember/error", "@ember/-internals/views/lib/views/states/has_element"], function (_exports, _utils, _polyfills, _error, _has_element) {
33343 "use strict";
33344
33345 Object.defineProperty(_exports, "__esModule", {
33346 value: true
33347 });
33348 _exports.default = void 0;
33349 var inDOM = (0, _polyfills.assign)({}, _has_element.default, {
33350 enter(view) {
33351 // Register the view for event handling. This hash is used by
33352 // Ember.EventDispatcher to dispatch incoming events.
33353 view.renderer.register(view);
33354
33355 if (true
33356 /* DEBUG */
33357 ) {
33358 var elementId = view.elementId;
33359 (0, _utils.teardownMandatorySetter)(view, 'elementId');
33360 Object.defineProperty(view, 'elementId', {
33361 configurable: true,
33362 enumerable: true,
33363
33364 get() {
33365 return elementId;
33366 },
33367
33368 set(value) {
33369 if (value !== elementId) {
33370 throw new _error.default("Changing a view's elementId after creation is not allowed");
33371 }
33372 }
33373
33374 });
33375 }
33376 }
33377
33378 });
33379
33380 var _default = Object.freeze(inDOM);
33381
33382 _exports.default = _default;
33383});
33384define("@ember/-internals/views/lib/views/states/pre_render", ["exports", "@ember/-internals/views/lib/views/states/default", "@ember/polyfills"], function (_exports, _default3, _polyfills) {
33385 "use strict";
33386
33387 Object.defineProperty(_exports, "__esModule", {
33388 value: true
33389 });
33390 _exports.default = void 0;
33391 var preRender = (0, _polyfills.assign)({}, _default3.default);
33392
33393 var _default2 = Object.freeze(preRender);
33394
33395 _exports.default = _default2;
33396});
33397define("@ember/application/globals-resolver", ["exports", "@ember/-internals/utils", "@ember/-internals/metal", "@ember/debug", "@ember/string", "@ember/-internals/runtime", "@ember/-internals/glimmer", "@ember/deprecated-features"], function (_exports, _utils, _metal, _debug, _string, _runtime, _glimmer, _deprecatedFeatures) {
33398 "use strict";
33399
33400 Object.defineProperty(_exports, "__esModule", {
33401 value: true
33402 });
33403 _exports.default = void 0;
33404
33405 /**
33406 @module @ember/application
33407 */
33408
33409 /**
33410 The DefaultResolver defines the default lookup rules to resolve
33411 container lookups before consulting the container for registered
33412 items:
33413
33414 * templates are looked up on `Ember.TEMPLATES`
33415 * other names are looked up on the application after converting
33416 the name. For example, `controller:post` looks up
33417 `App.PostController` by default.
33418 * there are some nuances (see examples below)
33419
33420 ### How Resolving Works
33421
33422 The container calls this object's `resolve` method with the
33423 `fullName` argument.
33424
33425 It first parses the fullName into an object using `parseName`.
33426
33427 Then it checks for the presence of a type-specific instance
33428 method of the form `resolve[Type]` and calls it if it exists.
33429 For example if it was resolving 'template:post', it would call
33430 the `resolveTemplate` method.
33431
33432 Its last resort is to call the `resolveOther` method.
33433
33434 The methods of this object are designed to be easy to override
33435 in a subclass. For example, you could enhance how a template
33436 is resolved like so:
33437
33438 ```app/app.js
33439 import Application from '@ember/application';
33440 import GlobalsResolver from '@ember/application/globals-resolver';
33441
33442 App = Application.create({
33443 Resolver: GlobalsResolver.extend({
33444 resolveTemplate(parsedName) {
33445 let resolvedTemplate = this._super(parsedName);
33446 if (resolvedTemplate) { return resolvedTemplate; }
33447
33448 return Ember.TEMPLATES['not_found'];
33449 }
33450 })
33451 });
33452 ```
33453
33454 Some examples of how names are resolved:
33455
33456 ```text
33457 'template:post' //=> Ember.TEMPLATES['post']
33458 'template:posts/byline' //=> Ember.TEMPLATES['posts/byline']
33459 'template:posts.byline' //=> Ember.TEMPLATES['posts/byline']
33460 'template:blogPost' //=> Ember.TEMPLATES['blog-post']
33461 'controller:post' //=> App.PostController
33462 'controller:posts.index' //=> App.PostsIndexController
33463 'controller:blog/post' //=> Blog.PostController
33464 'controller:basic' //=> Controller
33465 'route:post' //=> App.PostRoute
33466 'route:posts.index' //=> App.PostsIndexRoute
33467 'route:blog/post' //=> Blog.PostRoute
33468 'route:basic' //=> Route
33469 'foo:post' //=> App.PostFoo
33470 'model:post' //=> App.Post
33471 ```
33472
33473 @class GlobalsResolver
33474 @extends EmberObject
33475 @public
33476 @deprecated
33477 */
33478 var DefaultResolver;
33479
33480 if (_deprecatedFeatures.GLOBALS_RESOLVER) {
33481 DefaultResolver = class DefaultResolver extends _runtime.Object {
33482 static create(props) {
33483 // DO NOT REMOVE even though this doesn't do anything
33484 // This is required for a FireFox 60+ JIT bug with our tests.
33485 // without it, create(props) in our tests would lose props on a deopt.
33486 return super.create(props);
33487 }
33488 /**
33489 This will be set to the Application instance when it is
33490 created.
33491 @property namespace
33492 @public
33493 @deprecated
33494 */
33495
33496
33497 init() {
33498 (true && !(false) && (0, _debug.deprecate)('Using the globals resolver is deprecated. Use the ember-resolver package instead. See https://deprecations.emberjs.com/v3.x#toc_ember-deprecate-globals-resolver', false, {
33499 until: '4.0.0',
33500 id: 'globals-resolver',
33501 url: 'https://deprecations.emberjs.com/v3.x#toc_ember-deprecate-globals-resolver'
33502 }));
33503 this._parseNameCache = (0, _utils.dictionary)(null);
33504 }
33505
33506 normalize(fullName) {
33507 var [type, name] = fullName.split(':');
33508 (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));
33509
33510 if (type !== 'template') {
33511 var result = name.replace(/(\.|_|-)./g, m => m.charAt(1).toUpperCase());
33512 return `${type}:${result}`;
33513 } else {
33514 return fullName;
33515 }
33516 }
33517 /**
33518 This method is called via the container's resolver method.
33519 It parses the provided `fullName` and then looks up and
33520 returns the appropriate template or class.
33521 @method resolve
33522 @param {String} fullName the lookup string
33523 @return {Object} the resolved factory
33524 @public
33525 */
33526
33527
33528 resolve(fullName) {
33529 var parsedName = this.parseName(fullName);
33530 var resolveMethodName = parsedName.resolveMethodName;
33531 var resolved;
33532
33533 if (this[resolveMethodName]) {
33534 resolved = this[resolveMethodName](parsedName);
33535 }
33536
33537 resolved = resolved || this.resolveOther(parsedName);
33538
33539 if (true
33540 /* DEBUG */
33541 ) {
33542 if (parsedName.root && parsedName.root.LOG_RESOLVER) {
33543 this._logLookup(resolved, parsedName);
33544 }
33545
33546 if (resolved) {
33547 var VALIDATED_TYPES = {
33548 route: ['isRouteFactory', 'Ember.Route'],
33549 component: ['isComponentFactory', 'Ember.Component'],
33550 view: ['isViewFactory', 'Ember.View'],
33551 service: ['isServiceFactory', 'Ember.Service']
33552 };
33553 var validationAttributes = VALIDATED_TYPES[parsedName.type];
33554
33555 if (validationAttributes) {
33556 var [factoryFlag, expectedType] = validationAttributes;
33557 (true && !(Boolean(resolved[factoryFlag])) && (0, _debug.assert)(`Expected ${parsedName.fullName} to resolve to an ${expectedType} but ` + `instead it was ${resolved}.`, Boolean(resolved[factoryFlag])));
33558 }
33559 }
33560 }
33561
33562 return resolved;
33563 }
33564 /**
33565 Convert the string name of the form 'type:name' to
33566 a Javascript object with the parsed aspects of the name
33567 broken out.
33568 @param {String} fullName the lookup string
33569 @method parseName
33570 @protected
33571 */
33572
33573
33574 parseName(fullName) {
33575 return this._parseNameCache[fullName] || (this._parseNameCache[fullName] = this._parseName(fullName));
33576 }
33577
33578 _parseName(fullName) {
33579 var [type, fullNameWithoutType] = fullName.split(':');
33580 var name = fullNameWithoutType;
33581 var namespace = (0, _metal.get)(this, 'namespace');
33582 var root = namespace;
33583 var lastSlashIndex = name.lastIndexOf('/');
33584 var dirname = lastSlashIndex !== -1 ? name.slice(0, lastSlashIndex) : null;
33585
33586 if (type !== 'template' && lastSlashIndex !== -1) {
33587 var parts = name.split('/');
33588 name = parts[parts.length - 1];
33589 var namespaceName = (0, _string.capitalize)(parts.slice(0, -1).join('.'));
33590 root = (0, _metal.findNamespace)(namespaceName);
33591 (true && !(root) && (0, _debug.assert)(`You are looking for a ${name} ${type} in the ${namespaceName} namespace, but the namespace could not be found`, root));
33592 }
33593
33594 var resolveMethodName = fullNameWithoutType === 'main' ? 'Main' : (0, _string.classify)(type);
33595
33596 if (!(name && type)) {
33597 throw new TypeError(`Invalid fullName: \`${fullName}\`, must be of the form \`type:name\` `);
33598 }
33599
33600 return {
33601 fullName,
33602 type,
33603 fullNameWithoutType,
33604 dirname,
33605 name,
33606 root,
33607 resolveMethodName: `resolve${resolveMethodName}`
33608 };
33609 }
33610 /**
33611 Returns a human-readable description for a fullName. Used by the
33612 Application namespace in assertions to describe the
33613 precise name of the class that Ember is looking for, rather than
33614 container keys.
33615 @param {String} fullName the lookup string
33616 @method lookupDescription
33617 @protected
33618 */
33619
33620
33621 lookupDescription(fullName) {
33622 var parsedName = this.parseName(fullName);
33623 var description;
33624
33625 if (parsedName.type === 'template') {
33626 return `template at ${parsedName.fullNameWithoutType.replace(/\./g, '/')}`;
33627 }
33628
33629 description = `${parsedName.root}.${(0, _string.classify)(parsedName.name).replace(/\./g, '')}`;
33630
33631 if (parsedName.type !== 'model') {
33632 description += (0, _string.classify)(parsedName.type);
33633 }
33634
33635 return description;
33636 }
33637
33638 makeToString(factory) {
33639 return factory.toString();
33640 }
33641 /**
33642 Given a parseName object (output from `parseName`), apply
33643 the conventions expected by `Router`
33644 @param {Object} parsedName a parseName object with the parsed
33645 fullName lookup string
33646 @method useRouterNaming
33647 @protected
33648 */
33649
33650
33651 useRouterNaming(parsedName) {
33652 if (parsedName.name === 'basic') {
33653 parsedName.name = '';
33654 } else {
33655 parsedName.name = parsedName.name.replace(/\./g, '_');
33656 }
33657 }
33658 /**
33659 Look up the template in Ember.TEMPLATES
33660 @param {Object} parsedName a parseName object with the parsed
33661 fullName lookup string
33662 @method resolveTemplate
33663 @protected
33664 */
33665
33666
33667 resolveTemplate(parsedName) {
33668 var templateName = parsedName.fullNameWithoutType.replace(/\./g, '/');
33669 return (0, _glimmer.getTemplate)(templateName) || (0, _glimmer.getTemplate)((0, _string.decamelize)(templateName));
33670 }
33671 /**
33672 Lookup the view using `resolveOther`
33673 @param {Object} parsedName a parseName object with the parsed
33674 fullName lookup string
33675 @method resolveView
33676 @protected
33677 */
33678
33679
33680 resolveView(parsedName) {
33681 this.useRouterNaming(parsedName);
33682 return this.resolveOther(parsedName);
33683 }
33684 /**
33685 Lookup the controller using `resolveOther`
33686 @param {Object} parsedName a parseName object with the parsed
33687 fullName lookup string
33688 @method resolveController
33689 @protected
33690 */
33691
33692
33693 resolveController(parsedName) {
33694 this.useRouterNaming(parsedName);
33695 return this.resolveOther(parsedName);
33696 }
33697 /**
33698 Lookup the route using `resolveOther`
33699 @param {Object} parsedName a parseName object with the parsed
33700 fullName lookup string
33701 @method resolveRoute
33702 @protected
33703 */
33704
33705
33706 resolveRoute(parsedName) {
33707 this.useRouterNaming(parsedName);
33708 return this.resolveOther(parsedName);
33709 }
33710 /**
33711 Lookup the model on the Application namespace
33712 @param {Object} parsedName a parseName object with the parsed
33713 fullName lookup string
33714 @method resolveModel
33715 @protected
33716 */
33717
33718
33719 resolveModel(parsedName) {
33720 var className = (0, _string.classify)(parsedName.name);
33721 var factory = (0, _metal.get)(parsedName.root, className);
33722 return factory;
33723 }
33724 /**
33725 Look up the specified object (from parsedName) on the appropriate
33726 namespace (usually on the Application)
33727 @param {Object} parsedName a parseName object with the parsed
33728 fullName lookup string
33729 @method resolveHelper
33730 @protected
33731 */
33732
33733
33734 resolveHelper(parsedName) {
33735 return this.resolveOther(parsedName);
33736 }
33737 /**
33738 Look up the specified object (from parsedName) on the appropriate
33739 namespace (usually on the Application)
33740 @param {Object} parsedName a parseName object with the parsed
33741 fullName lookup string
33742 @method resolveOther
33743 @protected
33744 */
33745
33746
33747 resolveOther(parsedName) {
33748 var className = (0, _string.classify)(parsedName.name) + (0, _string.classify)(parsedName.type);
33749 var factory = (0, _metal.get)(parsedName.root, className);
33750 return factory;
33751 }
33752
33753 resolveMain(parsedName) {
33754 var className = (0, _string.classify)(parsedName.type);
33755 return (0, _metal.get)(parsedName.root, className);
33756 }
33757 /**
33758 Used to iterate all items of a given type.
33759 @method knownForType
33760 @param {String} type the type to search for
33761 @private
33762 */
33763
33764
33765 knownForType(type) {
33766 var namespace = (0, _metal.get)(this, 'namespace');
33767 var suffix = (0, _string.classify)(type);
33768 var typeRegexp = new RegExp(`${suffix}$`);
33769 var known = (0, _utils.dictionary)(null);
33770 var knownKeys = Object.keys(namespace);
33771
33772 for (var index = 0; index < knownKeys.length; index++) {
33773 var name = knownKeys[index];
33774
33775 if (typeRegexp.test(name)) {
33776 var containerName = this.translateToContainerFullname(type, name);
33777 known[containerName] = true;
33778 }
33779 }
33780
33781 return known;
33782 }
33783 /**
33784 Converts provided name from the backing namespace into a container lookup name.
33785 Examples:
33786 * App.FooBarHelper -> helper:foo-bar
33787 * App.THelper -> helper:t
33788 @method translateToContainerFullname
33789 @param {String} type
33790 @param {String} name
33791 @private
33792 */
33793
33794
33795 translateToContainerFullname(type, name) {
33796 var suffix = (0, _string.classify)(type);
33797 var namePrefix = name.slice(0, suffix.length * -1);
33798 var dasherizedName = (0, _string.dasherize)(namePrefix);
33799 return `${type}:${dasherizedName}`;
33800 }
33801
33802 };
33803
33804 if (true
33805 /* DEBUG */
33806 ) {
33807 /**
33808 @method _logLookup
33809 @param {Boolean} found
33810 @param {Object} parsedName
33811 @private
33812 */
33813 DefaultResolver.prototype._logLookup = function (found, parsedName) {
33814 var symbol = found ? '[✓]' : '[ ]';
33815 var padding;
33816
33817 if (parsedName.fullName.length > 60) {
33818 padding = '.';
33819 } else {
33820 padding = new Array(60 - parsedName.fullName.length).join('.');
33821 }
33822
33823 (0, _debug.info)(symbol, parsedName.fullName, padding, this.lookupDescription(parsedName.fullName));
33824 };
33825 }
33826 }
33827
33828 var _default = DefaultResolver;
33829 _exports.default = _default;
33830});
33831define("@ember/application/index", ["exports", "@ember/-internals/owner", "@ember/application/lib/lazy_load", "@ember/application/lib/application"], function (_exports, _owner, _lazy_load, _application) {
33832 "use strict";
33833
33834 Object.defineProperty(_exports, "__esModule", {
33835 value: true
33836 });
33837 Object.defineProperty(_exports, "getOwner", {
33838 enumerable: true,
33839 get: function () {
33840 return _owner.getOwner;
33841 }
33842 });
33843 Object.defineProperty(_exports, "setOwner", {
33844 enumerable: true,
33845 get: function () {
33846 return _owner.setOwner;
33847 }
33848 });
33849 Object.defineProperty(_exports, "onLoad", {
33850 enumerable: true,
33851 get: function () {
33852 return _lazy_load.onLoad;
33853 }
33854 });
33855 Object.defineProperty(_exports, "runLoadHooks", {
33856 enumerable: true,
33857 get: function () {
33858 return _lazy_load.runLoadHooks;
33859 }
33860 });
33861 Object.defineProperty(_exports, "_loaded", {
33862 enumerable: true,
33863 get: function () {
33864 return _lazy_load._loaded;
33865 }
33866 });
33867 Object.defineProperty(_exports, "default", {
33868 enumerable: true,
33869 get: function () {
33870 return _application.default;
33871 }
33872 });
33873});
33874define("@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, environment, _views, _instance, _glimmer) {
33875 "use strict";
33876
33877 Object.defineProperty(_exports, "__esModule", {
33878 value: true
33879 });
33880 _exports.default = void 0;
33881
33882 /**
33883 @module @ember/application
33884 */
33885
33886 /**
33887 The `ApplicationInstance` encapsulates all of the stateful aspects of a
33888 running `Application`.
33889
33890 At a high-level, we break application boot into two distinct phases:
33891
33892 * Definition time, where all of the classes, templates, and other
33893 dependencies are loaded (typically in the browser).
33894 * Run time, where we begin executing the application once everything
33895 has loaded.
33896
33897 Definition time can be expensive and only needs to happen once since it is
33898 an idempotent operation. For example, between test runs and FastBoot
33899 requests, the application stays the same. It is only the state that we want
33900 to reset.
33901
33902 That state is what the `ApplicationInstance` manages: it is responsible for
33903 creating the container that contains all application state, and disposing of
33904 it once the particular test run or FastBoot request has finished.
33905
33906 @public
33907 @class ApplicationInstance
33908 @extends EngineInstance
33909 */
33910 var ApplicationInstance = _instance.default.extend({
33911 /**
33912 The `Application` for which this is an instance.
33913 @property {Application} application
33914 @private
33915 */
33916 application: null,
33917
33918 /**
33919 The DOM events for which the event dispatcher should listen.
33920 By default, the application's `Ember.EventDispatcher` listens
33921 for a set of standard DOM events, such as `mousedown` and
33922 `keyup`, and delegates them to your application's `Ember.View`
33923 instances.
33924 @private
33925 @property {Object} customEvents
33926 */
33927 customEvents: null,
33928
33929 /**
33930 The root DOM element of the Application as an element or a
33931 [jQuery-compatible selector
33932 string](http://api.jquery.com/category/selectors/).
33933 @private
33934 @property {String|DOMElement} rootElement
33935 */
33936 rootElement: null,
33937
33938 init() {
33939 this._super(...arguments);
33940
33941 this.application._watchInstance(this); // Register this instance in the per-instance registry.
33942 //
33943 // Why do we need to register the instance in the first place?
33944 // Because we need a good way for the root route (a.k.a ApplicationRoute)
33945 // to notify us when it has created the root-most view. That view is then
33946 // appended to the rootElement, in the case of apps, to the fixture harness
33947 // in tests, or rendered to a string in the case of FastBoot.
33948
33949
33950 this.register('-application-instance:main', this, {
33951 instantiate: false
33952 });
33953 },
33954
33955 /**
33956 Overrides the base `EngineInstance._bootSync` method with concerns relevant
33957 to booting application (instead of engine) instances.
33958 This method should only contain synchronous boot concerns. Asynchronous
33959 boot concerns should eventually be moved to the `boot` method, which
33960 returns a promise.
33961 Until all boot code has been made asynchronous, we need to continue to
33962 expose this method for use *internally* in places where we need to boot an
33963 instance synchronously.
33964 @private
33965 */
33966 _bootSync(options) {
33967 if (this._booted) {
33968 return this;
33969 }
33970
33971 options = new BootOptions(options);
33972 this.setupRegistry(options);
33973
33974 if (options.rootElement) {
33975 this.rootElement = options.rootElement;
33976 } else {
33977 this.rootElement = this.application.rootElement;
33978 }
33979
33980 if (options.location) {
33981 (0, _metal.set)(this.router, 'location', options.location);
33982 }
33983
33984 this.application.runInstanceInitializers(this);
33985
33986 if (options.isInteractive) {
33987 this.setupEventDispatcher();
33988 }
33989
33990 this._booted = true;
33991 return this;
33992 },
33993
33994 setupRegistry(options) {
33995 this.constructor.setupRegistry(this.__registry__, options);
33996 },
33997
33998 router: (0, _metal.computed)(function () {
33999 return this.lookup('router:main');
34000 }).readOnly(),
34001
34002 /**
34003 This hook is called by the root-most Route (a.k.a. the ApplicationRoute)
34004 when it has finished creating the root View. By default, we simply take the
34005 view and append it to the `rootElement` specified on the Application.
34006 In cases like FastBoot and testing, we can override this hook and implement
34007 custom behavior, such as serializing to a string and sending over an HTTP
34008 socket rather than appending to DOM.
34009 @param view {Ember.View} the root-most view
34010 @deprecated
34011 @private
34012 */
34013 didCreateRootView(view) {
34014 view.appendTo(this.rootElement);
34015 },
34016
34017 /**
34018 Tells the router to start routing. The router will ask the location for the
34019 current URL of the page to determine the initial URL to start routing to.
34020 To start the app at a specific URL, call `handleURL` instead.
34021 @private
34022 */
34023 startRouting() {
34024 this.router.startRouting();
34025 this._didSetupRouter = true;
34026 },
34027
34028 /**
34029 Sets up the router, initializing the child router and configuring the
34030 location before routing begins.
34031 Because setup should only occur once, multiple calls to `setupRouter`
34032 beyond the first call have no effect.
34033
34034 This is commonly used in order to confirm things that rely on the router
34035 are functioning properly from tests that are primarily rendering related.
34036
34037 For example, from within [ember-qunit](https://github.com/emberjs/ember-qunit)'s
34038 `setupRenderingTest` calling `this.owner.setupRouter()` would allow that
34039 rendering test to confirm that any `<LinkTo></LinkTo>`'s that are rendered
34040 have the correct URL.
34041
34042 @public
34043 */
34044 setupRouter() {
34045 if (this._didSetupRouter) {
34046 return;
34047 }
34048
34049 this._didSetupRouter = true;
34050 this.router.setupRouter();
34051 },
34052
34053 /**
34054 Directs the router to route to a particular URL. This is useful in tests,
34055 for example, to tell the app to start at a particular URL.
34056 @param url {String} the URL the router should route to
34057 @private
34058 */
34059 handleURL(url) {
34060 this.setupRouter();
34061 return this.router.handleURL(url);
34062 },
34063
34064 /**
34065 @private
34066 */
34067 setupEventDispatcher() {
34068 var dispatcher = this.lookup('event_dispatcher:main');
34069 var applicationCustomEvents = (0, _metal.get)(this.application, 'customEvents');
34070 var instanceCustomEvents = (0, _metal.get)(this, 'customEvents');
34071 var customEvents = (0, _polyfills.assign)({}, applicationCustomEvents, instanceCustomEvents);
34072 dispatcher.setup(customEvents, this.rootElement);
34073 return dispatcher;
34074 },
34075
34076 /**
34077 Returns the current URL of the app instance. This is useful when your
34078 app does not update the browsers URL bar (i.e. it uses the `'none'`
34079 location adapter).
34080 @public
34081 @return {String} the current URL
34082 */
34083 getURL() {
34084 return this.router.url;
34085 },
34086
34087 // `instance.visit(url)` should eventually replace `instance.handleURL()`;
34088 // the test helpers can probably be switched to use this implementation too
34089
34090 /**
34091 Navigate the instance to a particular URL. This is useful in tests, for
34092 example, or to tell the app to start at a particular URL. This method
34093 returns a promise that resolves with the app instance when the transition
34094 is complete, or rejects if the transion was aborted due to an error.
34095 @public
34096 @param url {String} the destination URL
34097 @return {Promise<ApplicationInstance>}
34098 */
34099 visit(url) {
34100 this.setupRouter();
34101
34102 var bootOptions = this.__container__.lookup('-environment:main');
34103
34104 var router = this.router;
34105
34106 var handleTransitionResolve = () => {
34107 if (!bootOptions.options.shouldRender) {
34108 // No rendering is needed, and routing has completed, simply return.
34109 return this;
34110 } else {
34111 // Ensure that the visit promise resolves when all rendering has completed
34112 return (0, _glimmer.renderSettled)().then(() => this);
34113 }
34114 };
34115
34116 var handleTransitionReject = error => {
34117 if (error.error) {
34118 throw error.error;
34119 } else if (error.name === 'TransitionAborted' && router._routerMicrolib.activeTransition) {
34120 return router._routerMicrolib.activeTransition.then(handleTransitionResolve, handleTransitionReject);
34121 } else if (error.name === 'TransitionAborted') {
34122 throw new Error(error.message);
34123 } else {
34124 throw error;
34125 }
34126 };
34127
34128 var location = (0, _metal.get)(router, 'location'); // Keeps the location adapter's internal URL in-sync
34129
34130 location.setURL(url); // getURL returns the set url with the rootURL stripped off
34131
34132 return router.handleURL(location.getURL()).then(handleTransitionResolve, handleTransitionReject);
34133 },
34134
34135 willDestroy() {
34136 this._super(...arguments);
34137
34138 this.application._unwatchInstance(this);
34139 }
34140
34141 });
34142
34143 ApplicationInstance.reopenClass({
34144 /**
34145 @private
34146 @method setupRegistry
34147 @param {Registry} registry
34148 @param {BootOptions} options
34149 */
34150 setupRegistry(registry, options = {}) {
34151 if (!options.toEnvironment) {
34152 options = new BootOptions(options);
34153 }
34154
34155 registry.register('-environment:main', options.toEnvironment(), {
34156 instantiate: false
34157 });
34158 registry.register('service:-document', options.document, {
34159 instantiate: false
34160 });
34161
34162 this._super(registry, options);
34163 }
34164
34165 });
34166 /**
34167 A list of boot-time configuration options for customizing the behavior of
34168 an `ApplicationInstance`.
34169
34170 This is an interface class that exists purely to document the available
34171 options; you do not need to construct it manually. Simply pass a regular
34172 JavaScript object containing the desired options into methods that require
34173 one of these options object:
34174
34175 ```javascript
34176 MyApp.visit("/", { location: "none", rootElement: "#container" });
34177 ```
34178
34179 Not all combinations of the supported options are valid. See the documentation
34180 on `Application#visit` for the supported configurations.
34181
34182 Internal, experimental or otherwise unstable flags are marked as private.
34183
34184 @class BootOptions
34185 @namespace ApplicationInstance
34186 @public
34187 */
34188
34189 class BootOptions {
34190 constructor(options = {}) {
34191 /**
34192 Provide a specific instance of jQuery. This is useful in conjunction with
34193 the `document` option, as it allows you to use a copy of `jQuery` that is
34194 appropriately bound to the foreign `document` (e.g. a jsdom).
34195 This is highly experimental and support very incomplete at the moment.
34196 @property jQuery
34197 @type Object
34198 @default auto-detected
34199 @private
34200 */
34201 this.jQuery = _views.jQuery; // This default is overridable below
34202
34203 /**
34204 Interactive mode: whether we need to set up event delegation and invoke
34205 lifecycle callbacks on Components.
34206 @property isInteractive
34207 @type boolean
34208 @default auto-detected
34209 @private
34210 */
34211
34212 this.isInteractive = environment.hasDOM; // This default is overridable below
34213
34214 /**
34215 @property _renderMode
34216 @type string
34217 @default false
34218 @private
34219 */
34220
34221 this._renderMode = options._renderMode;
34222 /**
34223 Run in a full browser environment.
34224 When this flag is set to `false`, it will disable most browser-specific
34225 and interactive features. Specifically:
34226 * It does not use `jQuery` to append the root view; the `rootElement`
34227 (either specified as a subsequent option or on the application itself)
34228 must already be an `Element` in the given `document` (as opposed to a
34229 string selector).
34230 * It does not set up an `EventDispatcher`.
34231 * It does not run any `Component` lifecycle hooks (such as `didInsertElement`).
34232 * It sets the `location` option to `"none"`. (If you would like to use
34233 the location adapter specified in the app's router instead, you can also
34234 specify `{ location: null }` to specifically opt-out.)
34235 @property isBrowser
34236 @type boolean
34237 @default auto-detected
34238 @public
34239 */
34240
34241 if (options.isBrowser !== undefined) {
34242 this.isBrowser = Boolean(options.isBrowser);
34243 } else {
34244 this.isBrowser = environment.hasDOM;
34245 }
34246
34247 if (!this.isBrowser) {
34248 this.jQuery = null;
34249 this.isInteractive = false;
34250 this.location = 'none';
34251 }
34252 /**
34253 Disable rendering completely.
34254 When this flag is set to `false`, it will disable the entire rendering
34255 pipeline. Essentially, this puts the app into "routing-only" mode. No
34256 templates will be rendered, and no Components will be created.
34257 @property shouldRender
34258 @type boolean
34259 @default true
34260 @public
34261 */
34262
34263
34264 if (options.shouldRender !== undefined) {
34265 this.shouldRender = Boolean(options.shouldRender);
34266 } else {
34267 this.shouldRender = true;
34268 }
34269
34270 if (!this.shouldRender) {
34271 this.jQuery = null;
34272 this.isInteractive = false;
34273 }
34274 /**
34275 If present, render into the given `Document` object instead of the
34276 global `window.document` object.
34277 In practice, this is only useful in non-browser environment or in
34278 non-interactive mode, because Ember's `jQuery` dependency is
34279 implicitly bound to the current document, causing event delegation
34280 to not work properly when the app is rendered into a foreign
34281 document object (such as an iframe's `contentDocument`).
34282 In non-browser mode, this could be a "`Document`-like" object as
34283 Ember only interact with a small subset of the DOM API in non-
34284 interactive mode. While the exact requirements have not yet been
34285 formalized, the `SimpleDOM` library's implementation is known to
34286 work.
34287 @property document
34288 @type Document
34289 @default the global `document` object
34290 @public
34291 */
34292
34293
34294 if (options.document) {
34295 this.document = options.document;
34296 } else {
34297 this.document = typeof document !== 'undefined' ? document : null;
34298 }
34299 /**
34300 If present, overrides the application's `rootElement` property on
34301 the instance. This is useful for testing environment, where you
34302 might want to append the root view to a fixture area.
34303 In non-browser mode, because Ember does not have access to jQuery,
34304 this options must be specified as a DOM `Element` object instead of
34305 a selector string.
34306 See the documentation on `Application`'s `rootElement` for
34307 details.
34308 @property rootElement
34309 @type String|Element
34310 @default null
34311 @public
34312 */
34313
34314
34315 if (options.rootElement) {
34316 this.rootElement = options.rootElement;
34317 } // Set these options last to give the user a chance to override the
34318 // defaults from the "combo" options like `isBrowser` (although in
34319 // practice, the resulting combination is probably invalid)
34320
34321 /**
34322 If present, overrides the router's `location` property with this
34323 value. This is useful for environments where trying to modify the
34324 URL would be inappropriate.
34325 @property location
34326 @type string
34327 @default null
34328 @public
34329 */
34330
34331
34332 if (options.location !== undefined) {
34333 this.location = options.location;
34334 }
34335
34336 if (options.jQuery !== undefined) {
34337 this.jQuery = options.jQuery;
34338 }
34339
34340 if (options.isInteractive !== undefined) {
34341 this.isInteractive = Boolean(options.isInteractive);
34342 }
34343 }
34344
34345 toEnvironment() {
34346 // Do we really want to assign all of this!?
34347 var env = (0, _polyfills.assign)({}, environment); // For compatibility with existing code
34348
34349 env.hasDOM = this.isBrowser;
34350 env.isInteractive = this.isInteractive;
34351 env._renderMode = this._renderMode;
34352 env.options = this;
34353 return env;
34354 }
34355
34356 }
34357
34358 var _default = ApplicationInstance;
34359 _exports.default = _default;
34360});
34361define("@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", "@ember/deprecated-features"], function (_exports, _utils, _environment, _browserEnvironment, _debug, _runloop, _metal, _lazy_load, _runtime, _views, _routing, _instance, _engine, _container, _glimmer, _deprecatedFeatures) {
34362 "use strict";
34363
34364 Object.defineProperty(_exports, "__esModule", {
34365 value: true
34366 });
34367 _exports.default = void 0;
34368
34369 /**
34370 @module @ember/application
34371 */
34372 var librariesRegistered = false;
34373 /**
34374 An instance of `Application` is the starting point for every Ember
34375 application. It instantiates, initializes and coordinates the
34376 objects that make up your app.
34377
34378 Each Ember app has one and only one `Application` object. Although
34379 Ember CLI creates this object implicitly, the `Application` class
34380 is defined in the `app/app.js`. You can define a `ready` method on the
34381 `Application` class, which will be run by Ember when the application is
34382 initialized.
34383
34384 ```app/app.js
34385 const App = Application.extend({
34386 ready() {
34387 // your code here
34388 }
34389 })
34390 ```
34391
34392 Because `Application` ultimately inherits from `Ember.Namespace`, any classes
34393 you create will have useful string representations when calling `toString()`.
34394 See the `Ember.Namespace` documentation for more information.
34395
34396 While you can think of your `Application` as a container that holds the
34397 other classes in your application, there are several other responsibilities
34398 going on under-the-hood that you may want to understand. It is also important
34399 to understand that an `Application` is different from an `ApplicationInstance`.
34400 Refer to the Guides to understand the difference between these.
34401
34402 ### Event Delegation
34403
34404 Ember uses a technique called _event delegation_. This allows the framework
34405 to set up a global, shared event listener instead of requiring each view to
34406 do it manually. For example, instead of each view registering its own
34407 `mousedown` listener on its associated element, Ember sets up a `mousedown`
34408 listener on the `body`.
34409
34410 If a `mousedown` event occurs, Ember will look at the target of the event and
34411 start walking up the DOM node tree, finding corresponding views and invoking
34412 their `mouseDown` method as it goes.
34413
34414 `Application` has a number of default events that it listens for, as
34415 well as a mapping from lowercase events to camel-cased view method names. For
34416 example, the `keypress` event causes the `keyPress` method on the view to be
34417 called, the `dblclick` event causes `doubleClick` to be called, and so on.
34418
34419 If there is a bubbling browser event that Ember does not listen for by
34420 default, you can specify custom events and their corresponding view method
34421 names by setting the application's `customEvents` property:
34422
34423 ```app/app.js
34424 import Application from '@ember/application';
34425
34426 let App = Application.extend({
34427 customEvents: {
34428 // add support for the paste event
34429 paste: 'paste'
34430 }
34431 });
34432 ```
34433
34434 To prevent Ember from setting up a listener for a default event,
34435 specify the event name with a `null` value in the `customEvents`
34436 property:
34437
34438 ```app/app.js
34439 import Application from '@ember/application';
34440
34441 let App = Application.extend({
34442 customEvents: {
34443 // prevent listeners for mouseenter/mouseleave events
34444 mouseenter: null,
34445 mouseleave: null
34446 }
34447 });
34448 ```
34449
34450 By default, the application sets up these event listeners on the document
34451 body. However, in cases where you are embedding an Ember application inside
34452 an existing page, you may want it to set up the listeners on an element
34453 inside the body.
34454
34455 For example, if only events inside a DOM element with the ID of `ember-app`
34456 should be delegated, set your application's `rootElement` property:
34457
34458 ```app/app.js
34459 import Application from '@ember/application';
34460
34461 let App = Application.extend({
34462 rootElement: '#ember-app'
34463 });
34464 ```
34465
34466 The `rootElement` can be either a DOM element or a jQuery-compatible selector
34467 string. Note that *views appended to the DOM outside the root element will
34468 not receive events.* If you specify a custom root element, make sure you only
34469 append views inside it!
34470
34471 To learn more about the events Ember components use, see
34472
34473 [components/handling-events](https://guides.emberjs.com/release/components/handling-events/#toc_event-names).
34474
34475 ### Initializers
34476
34477 To add behavior to the Application's boot process, you can define initializers in
34478 the `app/initializers` directory, or with `ember generate initializer` using Ember CLI.
34479 These files should export a named `initialize` function which will receive the created `application`
34480 object as its first argument.
34481
34482 ```javascript
34483 export function initialize(application) {
34484 // application.inject('route', 'foo', 'service:foo');
34485 }
34486 ```
34487
34488 Application initializers can be used for a variety of reasons including:
34489
34490 - setting up external libraries
34491 - injecting dependencies
34492 - setting up event listeners in embedded apps
34493 - deferring the boot process using the `deferReadiness` and `advanceReadiness` APIs.
34494
34495 ### Routing
34496
34497 In addition to creating your application's router, `Application` is
34498 also responsible for telling the router when to start routing. Transitions
34499 between routes can be logged with the `LOG_TRANSITIONS` flag, and more
34500 detailed intra-transition logging can be logged with
34501 the `LOG_TRANSITIONS_INTERNAL` flag:
34502
34503 ```javascript
34504 import Application from '@ember/application';
34505
34506 let App = Application.create({
34507 LOG_TRANSITIONS: true, // basic logging of successful transitions
34508 LOG_TRANSITIONS_INTERNAL: true // detailed logging of all routing steps
34509 });
34510 ```
34511
34512 By default, the router will begin trying to translate the current URL into
34513 application state once the browser emits the `DOMContentReady` event. If you
34514 need to defer routing, you can call the application's `deferReadiness()`
34515 method. Once routing can begin, call the `advanceReadiness()` method.
34516
34517 If there is any setup required before routing begins, you can implement a
34518 `ready()` method on your app that will be invoked immediately before routing
34519 begins.
34520
34521 @class Application
34522 @extends Engine
34523 @uses RegistryProxyMixin
34524 @public
34525 */
34526
34527 var Application = _engine.default.extend({
34528 /**
34529 The root DOM element of the Application. This can be specified as an
34530 element or a
34531 [jQuery-compatible selector string](http://api.jquery.com/category/selectors/).
34532 This is the element that will be passed to the Application's,
34533 `eventDispatcher`, which sets up the listeners for event delegation. Every
34534 view in your application should be a child of the element you specify here.
34535 @property rootElement
34536 @type DOMElement
34537 @default 'body'
34538 @public
34539 */
34540 rootElement: 'body',
34541
34542 /**
34543 The `Ember.EventDispatcher` responsible for delegating events to this
34544 application's views.
34545 The event dispatcher is created by the application at initialization time
34546 and sets up event listeners on the DOM element described by the
34547 application's `rootElement` property.
34548 See the documentation for `Ember.EventDispatcher` for more information.
34549 @property eventDispatcher
34550 @type Ember.EventDispatcher
34551 @default null
34552 @public
34553 */
34554 eventDispatcher: null,
34555
34556 /**
34557 The DOM events for which the event dispatcher should listen.
34558 By default, the application's `Ember.EventDispatcher` listens
34559 for a set of standard DOM events, such as `mousedown` and
34560 `keyup`, and delegates them to your application's `Ember.View`
34561 instances.
34562 If you would like additional bubbling events to be delegated to your
34563 views, set your `Application`'s `customEvents` property
34564 to a hash containing the DOM event name as the key and the
34565 corresponding view method name as the value. Setting an event to
34566 a value of `null` will prevent a default event listener from being
34567 added for that event.
34568 To add new events to be listened to:
34569 ```app/app.js
34570 import Application from '@ember/application';
34571 let App = Application.extend({
34572 customEvents: {
34573 // add support for the paste event
34574 paste: 'paste'
34575 }
34576 });
34577 ```
34578 To prevent default events from being listened to:
34579 ```app/app.js
34580 import Application from '@ember/application';
34581 let App = Application.extend({
34582 customEvents: {
34583 // remove support for mouseenter / mouseleave events
34584 mouseenter: null,
34585 mouseleave: null
34586 }
34587 });
34588 ```
34589 @property customEvents
34590 @type Object
34591 @default null
34592 @public
34593 */
34594 customEvents: null,
34595
34596 /**
34597 Whether the application should automatically start routing and render
34598 templates to the `rootElement` on DOM ready. While default by true,
34599 other environments such as FastBoot or a testing harness can set this
34600 property to `false` and control the precise timing and behavior of the boot
34601 process.
34602 @property autoboot
34603 @type Boolean
34604 @default true
34605 @private
34606 */
34607 autoboot: true,
34608
34609 /**
34610 Whether the application should be configured for the legacy "globals mode".
34611 Under this mode, the Application object serves as a global namespace for all
34612 classes.
34613 ```javascript
34614 import Application from '@ember/application';
34615 import Component from '@ember/component';
34616 let App = Application.create({
34617 ...
34618 });
34619 App.Router.reopen({
34620 location: 'none'
34621 });
34622 App.Router.map({
34623 ...
34624 });
34625 App.MyComponent = Component.extend({
34626 ...
34627 });
34628 ```
34629 This flag also exposes other internal APIs that assumes the existence of
34630 a special "default instance", like `App.__container__.lookup(...)`.
34631 This option is currently not configurable, its value is derived from
34632 the `autoboot` flag – disabling `autoboot` also implies opting-out of
34633 globals mode support, although they are ultimately orthogonal concerns.
34634 Some of the global modes features are already deprecated in 1.x. The
34635 existence of this flag is to untangle the globals mode code paths from
34636 the autoboot code paths, so that these legacy features can be reviewed
34637 for deprecation/removal separately.
34638 Forcing the (autoboot=true, _globalsMode=false) here and running the tests
34639 would reveal all the places where we are still relying on these legacy
34640 behavior internally (mostly just tests).
34641 @property _globalsMode
34642 @type Boolean
34643 @default true
34644 @private
34645 */
34646 _globalsMode: true,
34647
34648 /**
34649 An array of application instances created by `buildInstance()`. Used
34650 internally to ensure that all instances get destroyed.
34651 @property _applicationInstances
34652 @type Array
34653 @default null
34654 @private
34655 */
34656 _applicationInstances: null,
34657
34658 init() {
34659 // eslint-disable-line no-unused-vars
34660 this._super(...arguments);
34661
34662 if (!this.$) {
34663 this.$ = _views.jQuery;
34664 }
34665
34666 registerLibraries();
34667
34668 if (true
34669 /* DEBUG */
34670 ) {
34671 if (_environment.ENV.LOG_VERSION) {
34672 // we only need to see this once per Application#init
34673 _environment.ENV.LOG_VERSION = false;
34674
34675 _metal.libraries.logVersions();
34676 }
34677 } // Start off the number of deferrals at 1. This will be decremented by
34678 // the Application's own `boot` method.
34679
34680
34681 this._readinessDeferrals = 1;
34682 this._booted = false;
34683 this._applicationInstances = new Set();
34684 this.autoboot = this._globalsMode = Boolean(this.autoboot);
34685
34686 if (this._globalsMode) {
34687 this._prepareForGlobalsMode();
34688 }
34689
34690 if (this.autoboot) {
34691 this.waitForDOMReady();
34692 }
34693 },
34694
34695 /**
34696 Create an ApplicationInstance for this application.
34697 @public
34698 @method buildInstance
34699 @return {ApplicationInstance} the application instance
34700 */
34701 buildInstance(options = {}) {
34702 (true && !(!this.isDestroyed) && (0, _debug.assert)('You cannot build new instances of this application since it has already been destroyed', !this.isDestroyed));
34703 (true && !(!this.isDestroying) && (0, _debug.assert)('You cannot build new instances of this application since it is being destroyed', !this.isDestroying));
34704 options.base = this;
34705 options.application = this;
34706 return _instance.default.create(options);
34707 },
34708
34709 /**
34710 Start tracking an ApplicationInstance for this application.
34711 Used when the ApplicationInstance is created.
34712 @private
34713 @method _watchInstance
34714 */
34715 _watchInstance(instance) {
34716 this._applicationInstances.add(instance);
34717 },
34718
34719 /**
34720 Stop tracking an ApplicationInstance for this application.
34721 Used when the ApplicationInstance is about to be destroyed.
34722 @private
34723 @method _unwatchInstance
34724 */
34725 _unwatchInstance(instance) {
34726 return this._applicationInstances.delete(instance);
34727 },
34728
34729 /**
34730 Enable the legacy globals mode by allowing this application to act
34731 as a global namespace. See the docs on the `_globalsMode` property
34732 for details.
34733 Most of these features are already deprecated in 1.x, so we can
34734 stop using them internally and try to remove them.
34735 @private
34736 @method _prepareForGlobalsMode
34737 */
34738 _prepareForGlobalsMode() {
34739 // Create subclass of Router for this Application instance.
34740 // This is to ensure that someone reopening `App.Router` does not
34741 // tamper with the default `Router`.
34742 this.Router = (this.Router || _routing.Router).extend();
34743
34744 this._buildDeprecatedInstance();
34745 },
34746
34747 /*
34748 Build the deprecated instance for legacy globals mode support.
34749 Called when creating and resetting the application.
34750 This is orthogonal to autoboot: the deprecated instance needs to
34751 be created at Application construction (not boot) time to expose
34752 App.__container__. If autoboot sees that this instance exists,
34753 it will continue booting it to avoid doing unncessary work (as
34754 opposed to building a new instance at boot time), but they are
34755 otherwise unrelated.
34756 @private
34757 @method _buildDeprecatedInstance
34758 */
34759 _buildDeprecatedInstance() {
34760 // Build a default instance
34761 var instance = this.buildInstance(); // Legacy support for App.__container__ and other global methods
34762 // on App that rely on a single, default instance.
34763
34764 this.__deprecatedInstance__ = instance;
34765 this.__container__ = instance.__container__;
34766 },
34767
34768 /**
34769 Automatically kick-off the boot process for the application once the
34770 DOM has become ready.
34771 The initialization itself is scheduled on the actions queue which
34772 ensures that code-loading finishes before booting.
34773 If you are asynchronously loading code, you should call `deferReadiness()`
34774 to defer booting, and then call `advanceReadiness()` once all of your code
34775 has finished loading.
34776 @private
34777 @method waitForDOMReady
34778 */
34779 waitForDOMReady() {
34780 if (!this.$ || this.$.isReady) {
34781 (0, _runloop.schedule)('actions', this, 'domReady');
34782 } else {
34783 this.$().ready((0, _runloop.bind)(this, 'domReady'));
34784 }
34785 },
34786
34787 /**
34788 This is the autoboot flow:
34789 1. Boot the app by calling `this.boot()`
34790 2. Create an instance (or use the `__deprecatedInstance__` in globals mode)
34791 3. Boot the instance by calling `instance.boot()`
34792 4. Invoke the `App.ready()` callback
34793 5. Kick-off routing on the instance
34794 Ideally, this is all we would need to do:
34795 ```javascript
34796 _autoBoot() {
34797 this.boot().then(() => {
34798 let instance = (this._globalsMode) ? this.__deprecatedInstance__ : this.buildInstance();
34799 return instance.boot();
34800 }).then((instance) => {
34801 App.ready();
34802 instance.startRouting();
34803 });
34804 }
34805 ```
34806 Unfortunately, we cannot actually write this because we need to participate
34807 in the "synchronous" boot process. While the code above would work fine on
34808 the initial boot (i.e. DOM ready), when `App.reset()` is called, we need to
34809 boot a new instance synchronously (see the documentation on `_bootSync()`
34810 for details).
34811 Because of this restriction, the actual logic of this method is located
34812 inside `didBecomeReady()`.
34813 @private
34814 @method domReady
34815 */
34816 domReady() {
34817 if (this.isDestroying || this.isDestroyed) {
34818 return;
34819 }
34820
34821 this._bootSync(); // Continues to `didBecomeReady`
34822
34823 },
34824
34825 /**
34826 Use this to defer readiness until some condition is true.
34827 Example:
34828 ```javascript
34829 import Application from '@ember/application';
34830 let App = Application.create();
34831 App.deferReadiness();
34832 // $ is a reference to the jQuery object/function
34833 import $ from 'jquery;
34834 $.getJSON('/auth-token', function(token) {
34835 App.token = token;
34836 App.advanceReadiness();
34837 });
34838 ```
34839 This allows you to perform asynchronous setup logic and defer
34840 booting your application until the setup has finished.
34841 However, if the setup requires a loading UI, it might be better
34842 to use the router for this purpose.
34843 @method deferReadiness
34844 @public
34845 */
34846 deferReadiness() {
34847 (true && !(this instanceof Application) && (0, _debug.assert)('You must call deferReadiness on an instance of Application', this instanceof Application));
34848 (true && !(!this.isDestroyed) && (0, _debug.assert)('You cannot defer readiness since application has already destroyed', !this.isDestroyed));
34849 (true && !(!this.isDestroying) && (0, _debug.assert)('You cannot defer readiness since the application is being destroyed', !this.isDestroying));
34850 (true && !(this._readinessDeferrals > 0) && (0, _debug.assert)('You cannot defer readiness since the `ready()` hook has already been called', this._readinessDeferrals > 0));
34851 this._readinessDeferrals++;
34852 },
34853
34854 /**
34855 Call `advanceReadiness` after any asynchronous setup logic has completed.
34856 Each call to `deferReadiness` must be matched by a call to `advanceReadiness`
34857 or the application will never become ready and routing will not begin.
34858 @method advanceReadiness
34859 @see {Application#deferReadiness}
34860 @public
34861 */
34862 advanceReadiness() {
34863 (true && !(this instanceof Application) && (0, _debug.assert)('You must call advanceReadiness on an instance of Application', this instanceof Application));
34864 (true && !(!this.isDestroyed) && (0, _debug.assert)('You cannot advance readiness since application has already destroyed', !this.isDestroyed));
34865 (true && !(!this.isDestroying) && (0, _debug.assert)('You cannot advance readiness since the application is being destroyed', !this.isDestroying));
34866 (true && !(this._readinessDeferrals > 0) && (0, _debug.assert)('You cannot advance readiness since the `ready()` hook has already been called', this._readinessDeferrals > 0));
34867 this._readinessDeferrals--;
34868
34869 if (this._readinessDeferrals === 0) {
34870 (0, _runloop.once)(this, this.didBecomeReady);
34871 }
34872 },
34873
34874 /**
34875 Initialize the application and return a promise that resolves with the `Application`
34876 object when the boot process is complete.
34877 Run any application initializers and run the application load hook. These hooks may
34878 choose to defer readiness. For example, an authentication hook might want to defer
34879 readiness until the auth token has been retrieved.
34880 By default, this method is called automatically on "DOM ready"; however, if autoboot
34881 is disabled, this is automatically called when the first application instance is
34882 created via `visit`.
34883 @public
34884 @method boot
34885 @return {Promise<Application,Error>}
34886 */
34887 boot() {
34888 (true && !(!this.isDestroyed) && (0, _debug.assert)('You cannot boot this application since it has already been destroyed', !this.isDestroyed));
34889 (true && !(!this.isDestroying) && (0, _debug.assert)('You cannot boot this application since it is being destroyed', !this.isDestroying));
34890
34891 if (this._bootPromise) {
34892 return this._bootPromise;
34893 }
34894
34895 try {
34896 this._bootSync();
34897 } catch (_) {// Ignore the error: in the asynchronous boot path, the error is already reflected
34898 // in the promise rejection
34899 }
34900
34901 return this._bootPromise;
34902 },
34903
34904 /**
34905 Unfortunately, a lot of existing code assumes the booting process is
34906 "synchronous". Specifically, a lot of tests assumes the last call to
34907 `app.advanceReadiness()` or `app.reset()` will result in the app being
34908 fully-booted when the current runloop completes.
34909 We would like new code (like the `visit` API) to stop making this assumption,
34910 so we created the asynchronous version above that returns a promise. But until
34911 we have migrated all the code, we would have to expose this method for use
34912 *internally* in places where we need to boot an app "synchronously".
34913 @private
34914 */
34915 _bootSync() {
34916 if (this._booted || this.isDestroying || this.isDestroyed) {
34917 return;
34918 } // Even though this returns synchronously, we still need to make sure the
34919 // boot promise exists for book-keeping purposes: if anything went wrong in
34920 // the boot process, we need to store the error as a rejection on the boot
34921 // promise so that a future caller of `boot()` can tell what failed.
34922
34923
34924 var defer = this._bootResolver = _runtime.RSVP.defer();
34925
34926 this._bootPromise = defer.promise;
34927
34928 try {
34929 this.runInitializers();
34930 (0, _lazy_load.runLoadHooks)('application', this);
34931 this.advanceReadiness(); // Continues to `didBecomeReady`
34932 } catch (error) {
34933 // For the asynchronous boot path
34934 defer.reject(error); // For the synchronous boot path
34935
34936 throw error;
34937 }
34938 },
34939
34940 /**
34941 Reset the application. This is typically used only in tests. It cleans up
34942 the application in the following order:
34943 1. Deactivate existing routes
34944 2. Destroy all objects in the container
34945 3. Create a new application container
34946 4. Re-route to the existing url
34947 Typical Example:
34948 ```javascript
34949 import Application from '@ember/application';
34950 let App;
34951 run(function() {
34952 App = Application.create();
34953 });
34954 module('acceptance test', {
34955 setup: function() {
34956 App.reset();
34957 }
34958 });
34959 test('first test', function() {
34960 // App is freshly reset
34961 });
34962 test('second test', function() {
34963 // App is again freshly reset
34964 });
34965 ```
34966 Advanced Example:
34967 Occasionally you may want to prevent the app from initializing during
34968 setup. This could enable extra configuration, or enable asserting prior
34969 to the app becoming ready.
34970 ```javascript
34971 import Application from '@ember/application';
34972 let App;
34973 run(function() {
34974 App = Application.create();
34975 });
34976 module('acceptance test', {
34977 setup: function() {
34978 run(function() {
34979 App.reset();
34980 App.deferReadiness();
34981 });
34982 }
34983 });
34984 test('first test', function() {
34985 ok(true, 'something before app is initialized');
34986 run(function() {
34987 App.advanceReadiness();
34988 });
34989 ok(true, 'something after app is initialized');
34990 });
34991 ```
34992 @method reset
34993 @public
34994 */
34995 reset() {
34996 (true && !(!this.isDestroyed) && (0, _debug.assert)('You cannot reset this application since it has already been destroyed', !this.isDestroyed));
34997 (true && !(!this.isDestroying) && (0, _debug.assert)('You cannot reset this application since it is being destroyed', !this.isDestroying));
34998 (true && !(this._globalsMode && this.autoboot) && (0, _debug.assert)(`Calling reset() on instances of \`Application\` is not
34999 supported when globals mode is disabled; call \`visit()\` to
35000 create new \`ApplicationInstance\`s and dispose them
35001 via their \`destroy()\` method instead.`, this._globalsMode && this.autoboot));
35002 var instance = this.__deprecatedInstance__;
35003 this._readinessDeferrals = 1;
35004 this._bootPromise = null;
35005 this._bootResolver = null;
35006 this._booted = false;
35007
35008 function handleReset() {
35009 (0, _runloop.run)(instance, 'destroy');
35010
35011 this._buildDeprecatedInstance();
35012
35013 (0, _runloop.schedule)('actions', this, '_bootSync');
35014 }
35015
35016 (0, _runloop.join)(this, handleReset);
35017 },
35018
35019 /**
35020 @private
35021 @method didBecomeReady
35022 */
35023 didBecomeReady() {
35024 if (this.isDestroying || this.isDestroyed) {
35025 return;
35026 }
35027
35028 try {
35029 // TODO: Is this still needed for _globalsMode = false?
35030 if (!(0, _debug.isTesting)()) {
35031 // Eagerly name all classes that are already loaded
35032 (0, _metal.processAllNamespaces)();
35033 (0, _metal.setNamespaceSearchDisabled)(true);
35034 } // See documentation on `_autoboot()` for details
35035
35036
35037 if (this.autoboot) {
35038 var instance;
35039
35040 if (this._globalsMode) {
35041 // If we already have the __deprecatedInstance__ lying around, boot it to
35042 // avoid unnecessary work
35043 instance = this.__deprecatedInstance__;
35044 } else {
35045 // Otherwise, build an instance and boot it. This is currently unreachable,
35046 // because we forced _globalsMode to === autoboot; but having this branch
35047 // allows us to locally toggle that flag for weeding out legacy globals mode
35048 // dependencies independently
35049 instance = this.buildInstance();
35050 }
35051
35052 instance._bootSync(); // TODO: App.ready() is not called when autoboot is disabled, is this correct?
35053
35054
35055 this.ready();
35056 instance.startRouting();
35057 } // For the asynchronous boot path
35058
35059
35060 this._bootResolver.resolve(this); // For the synchronous boot path
35061
35062
35063 this._booted = true;
35064 } catch (error) {
35065 // For the asynchronous boot path
35066 this._bootResolver.reject(error); // For the synchronous boot path
35067
35068
35069 throw error;
35070 }
35071 },
35072
35073 /**
35074 Called when the Application has become ready, immediately before routing
35075 begins. The call will be delayed until the DOM has become ready.
35076 @event ready
35077 @public
35078 */
35079 ready() {
35080 return this;
35081 },
35082
35083 // This method must be moved to the application instance object
35084 willDestroy() {
35085 this._super(...arguments);
35086
35087 (0, _metal.setNamespaceSearchDisabled)(false);
35088
35089 if (_lazy_load._loaded.application === this) {
35090 _lazy_load._loaded.application = undefined;
35091 }
35092
35093 if (this._applicationInstances.size) {
35094 this._applicationInstances.forEach(i => i.destroy());
35095
35096 this._applicationInstances.clear();
35097 }
35098 },
35099
35100 /**
35101 Boot a new instance of `ApplicationInstance` for the current
35102 application and navigate it to the given `url`. Returns a `Promise` that
35103 resolves with the instance when the initial routing and rendering is
35104 complete, or rejects with any error that occurred during the boot process.
35105 When `autoboot` is disabled, calling `visit` would first cause the
35106 application to boot, which runs the application initializers.
35107 This method also takes a hash of boot-time configuration options for
35108 customizing the instance's behavior. See the documentation on
35109 `ApplicationInstance.BootOptions` for details.
35110 `ApplicationInstance.BootOptions` is an interface class that exists
35111 purely to document the available options; you do not need to construct it
35112 manually. Simply pass a regular JavaScript object containing of the
35113 desired options:
35114 ```javascript
35115 MyApp.visit("/", { location: "none", rootElement: "#container" });
35116 ```
35117 ### Supported Scenarios
35118 While the `BootOptions` class exposes a large number of knobs, not all
35119 combinations of them are valid; certain incompatible combinations might
35120 result in unexpected behavior.
35121 For example, booting the instance in the full browser environment
35122 while specifying a foreign `document` object (e.g. `{ isBrowser: true,
35123 document: iframe.contentDocument }`) does not work correctly today,
35124 largely due to Ember's jQuery dependency.
35125 Currently, there are three officially supported scenarios/configurations.
35126 Usages outside of these scenarios are not guaranteed to work, but please
35127 feel free to file bug reports documenting your experience and any issues
35128 you encountered to help expand support.
35129 #### Browser Applications (Manual Boot)
35130 The setup is largely similar to how Ember works out-of-the-box. Normally,
35131 Ember will boot a default instance for your Application on "DOM ready".
35132 However, you can customize this behavior by disabling `autoboot`.
35133 For example, this allows you to render a miniture demo of your application
35134 into a specific area on your marketing website:
35135 ```javascript
35136 import MyApp from 'my-app';
35137 $(function() {
35138 let App = MyApp.create({ autoboot: false });
35139 let options = {
35140 // Override the router's location adapter to prevent it from updating
35141 // the URL in the address bar
35142 location: 'none',
35143 // Override the default `rootElement` on the app to render into a
35144 // specific `div` on the page
35145 rootElement: '#demo'
35146 };
35147 // Start the app at the special demo URL
35148 App.visit('/demo', options);
35149 });
35150 ```
35151 Or perhaps you might want to boot two instances of your app on the same
35152 page for a split-screen multiplayer experience:
35153 ```javascript
35154 import MyApp from 'my-app';
35155 $(function() {
35156 let App = MyApp.create({ autoboot: false });
35157 let sessionId = MyApp.generateSessionID();
35158 let player1 = App.visit(`/matches/join?name=Player+1&session=${sessionId}`, { rootElement: '#left', location: 'none' });
35159 let player2 = App.visit(`/matches/join?name=Player+2&session=${sessionId}`, { rootElement: '#right', location: 'none' });
35160 Promise.all([player1, player2]).then(() => {
35161 // Both apps have completed the initial render
35162 $('#loading').fadeOut();
35163 });
35164 });
35165 ```
35166 Do note that each app instance maintains their own registry/container, so
35167 they will run in complete isolation by default.
35168 #### Server-Side Rendering (also known as FastBoot)
35169 This setup allows you to run your Ember app in a server environment using
35170 Node.js and render its content into static HTML for SEO purposes.
35171 ```javascript
35172 const HTMLSerializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap);
35173 function renderURL(url) {
35174 let dom = new SimpleDOM.Document();
35175 let rootElement = dom.body;
35176 let options = { isBrowser: false, document: dom, rootElement: rootElement };
35177 return MyApp.visit(options).then(instance => {
35178 try {
35179 return HTMLSerializer.serialize(rootElement.firstChild);
35180 } finally {
35181 instance.destroy();
35182 }
35183 });
35184 }
35185 ```
35186 In this scenario, because Ember does not have access to a global `document`
35187 object in the Node.js environment, you must provide one explicitly. In practice,
35188 in the non-browser environment, the stand-in `document` object only needs to
35189 implement a limited subset of the full DOM API. The `SimpleDOM` library is known
35190 to work.
35191 Since there is no access to jQuery in the non-browser environment, you must also
35192 specify a DOM `Element` object in the same `document` for the `rootElement` option
35193 (as opposed to a selector string like `"body"`).
35194 See the documentation on the `isBrowser`, `document` and `rootElement` properties
35195 on `ApplicationInstance.BootOptions` for details.
35196 #### Server-Side Resource Discovery
35197 This setup allows you to run the routing layer of your Ember app in a server
35198 environment using Node.js and completely disable rendering. This allows you
35199 to simulate and discover the resources (i.e. AJAX requests) needed to fulfill
35200 a given request and eagerly "push" these resources to the client.
35201 ```app/initializers/network-service.js
35202 import BrowserNetworkService from 'app/services/network/browser';
35203 import NodeNetworkService from 'app/services/network/node';
35204 // Inject a (hypothetical) service for abstracting all AJAX calls and use
35205 // the appropriate implementation on the client/server. This also allows the
35206 // server to log all the AJAX calls made during a particular request and use
35207 // that for resource-discovery purpose.
35208 export function initialize(application) {
35209 if (window) { // browser
35210 application.register('service:network', BrowserNetworkService);
35211 } else { // node
35212 application.register('service:network', NodeNetworkService);
35213 }
35214 application.inject('route', 'network', 'service:network');
35215 };
35216 export default {
35217 name: 'network-service',
35218 initialize: initialize
35219 };
35220 ```
35221 ```app/routes/post.js
35222 import Route from '@ember/routing/route';
35223 // An example of how the (hypothetical) service is used in routes.
35224 export default Route.extend({
35225 model(params) {
35226 return this.network.fetch(`/api/posts/${params.post_id}.json`);
35227 },
35228 afterModel(post) {
35229 if (post.isExternalContent) {
35230 return this.network.fetch(`/api/external/?url=${post.externalURL}`);
35231 } else {
35232 return post;
35233 }
35234 }
35235 });
35236 ```
35237 ```javascript
35238 // Finally, put all the pieces together
35239 function discoverResourcesFor(url) {
35240 return MyApp.visit(url, { isBrowser: false, shouldRender: false }).then(instance => {
35241 let networkService = instance.lookup('service:network');
35242 return networkService.requests; // => { "/api/posts/123.json": "..." }
35243 });
35244 }
35245 ```
35246 @public
35247 @method visit
35248 @param url {String} The initial URL to navigate to
35249 @param options {ApplicationInstance.BootOptions}
35250 @return {Promise<ApplicationInstance, Error>}
35251 */
35252 visit(url, options) {
35253 (true && !(!this.isDestroyed) && (0, _debug.assert)('You cannot visit this application since it has already been destroyed', !this.isDestroyed));
35254 (true && !(!this.isDestroying) && (0, _debug.assert)('You cannot visit this application since it is being destroyed', !this.isDestroying));
35255 return this.boot().then(() => {
35256 var instance = this.buildInstance();
35257 return instance.boot(options).then(() => instance.visit(url)).catch(error => {
35258 (0, _runloop.run)(instance, 'destroy');
35259 throw error;
35260 });
35261 });
35262 }
35263
35264 });
35265
35266 Application.reopenClass({
35267 /**
35268 This creates a registry with the default Ember naming conventions.
35269 It also configures the registry:
35270 * registered views are created every time they are looked up (they are
35271 not singletons)
35272 * registered templates are not factories; the registered value is
35273 returned directly.
35274 * the router receives the application as its `namespace` property
35275 * all controllers receive the router as their `target` and `controllers`
35276 properties
35277 * all controllers receive the application as their `namespace` property
35278 * the application view receives the application controller as its
35279 `controller` property
35280 * the application view receives the application template as its
35281 `defaultTemplate` property
35282 @method buildRegistry
35283 @static
35284 @param {Application} namespace the application for which to
35285 build the registry
35286 @return {Ember.Registry} the built registry
35287 @private
35288 */
35289 buildRegistry() {
35290 // eslint-disable-line no-unused-vars
35291 var registry = this._super(...arguments);
35292
35293 commonSetupRegistry(registry);
35294 (0, _glimmer.setupApplicationRegistry)(registry);
35295 return registry;
35296 }
35297
35298 });
35299
35300 function commonSetupRegistry(registry) {
35301 registry.register('router:main', _routing.Router.extend());
35302 registry.register('-view-registry:main', {
35303 create() {
35304 return (0, _utils.dictionary)(null);
35305 }
35306
35307 });
35308 registry.register('route:basic', _routing.Route);
35309 registry.register('event_dispatcher:main', _views.EventDispatcher);
35310 registry.injection('router:main', 'namespace', 'application:main');
35311 registry.register('location:auto', _routing.AutoLocation);
35312 registry.register('location:hash', _routing.HashLocation);
35313 registry.register('location:history', _routing.HistoryLocation);
35314 registry.register('location:none', _routing.NoneLocation);
35315 registry.register((0, _container.privatize)`-bucket-cache:main`, {
35316 create() {
35317 return new _routing.BucketCache();
35318 }
35319
35320 });
35321 registry.register('service:router', _routing.RouterService);
35322 registry.injection('service:router', '_router', 'router:main');
35323 }
35324
35325 function registerLibraries() {
35326 if (!librariesRegistered) {
35327 librariesRegistered = true;
35328
35329 if (_deprecatedFeatures.JQUERY_INTEGRATION && _browserEnvironment.hasDOM && !_views.jQueryDisabled) {
35330 _metal.libraries.registerCoreLibrary('jQuery', (0, _views.jQuery)().jquery);
35331 }
35332 }
35333 }
35334
35335 var _default = Application;
35336 _exports.default = _default;
35337});
35338define("@ember/application/lib/lazy_load", ["exports", "@ember/-internals/environment", "@ember/-internals/browser-environment"], function (_exports, _environment, _browserEnvironment) {
35339 "use strict";
35340
35341 Object.defineProperty(_exports, "__esModule", {
35342 value: true
35343 });
35344 _exports.onLoad = onLoad;
35345 _exports.runLoadHooks = runLoadHooks;
35346 _exports._loaded = void 0;
35347
35348 /*globals CustomEvent */
35349
35350 /**
35351 @module @ember/application
35352 */
35353 var loadHooks = _environment.ENV.EMBER_LOAD_HOOKS || {};
35354 var loaded = {};
35355 var _loaded = loaded;
35356 /**
35357 Detects when a specific package of Ember (e.g. 'Application')
35358 has fully loaded and is available for extension.
35359
35360 The provided `callback` will be called with the `name` passed
35361 resolved from a string into the object:
35362
35363 ``` javascript
35364 import { onLoad } from '@ember/application';
35365
35366 onLoad('Ember.Application' function(hbars) {
35367 hbars.registerHelper(...);
35368 });
35369 ```
35370
35371 @method onLoad
35372 @static
35373 @for @ember/application
35374 @param name {String} name of hook
35375 @param callback {Function} callback to be called
35376 @private
35377 */
35378
35379 _exports._loaded = _loaded;
35380
35381 function onLoad(name, callback) {
35382 var object = loaded[name];
35383 loadHooks[name] = loadHooks[name] || [];
35384 loadHooks[name].push(callback);
35385
35386 if (object) {
35387 callback(object);
35388 }
35389 }
35390 /**
35391 Called when an Ember.js package (e.g Application) has finished
35392 loading. Triggers any callbacks registered for this event.
35393
35394 @method runLoadHooks
35395 @static
35396 @for @ember/application
35397 @param name {String} name of hook
35398 @param object {Object} object to pass to callbacks
35399 @private
35400 */
35401
35402
35403 function runLoadHooks(name, object) {
35404 loaded[name] = object;
35405
35406 if (_browserEnvironment.window && typeof CustomEvent === 'function') {
35407 var event = new CustomEvent(name, {
35408 detail: object,
35409 name
35410 });
35411
35412 _browserEnvironment.window.dispatchEvent(event);
35413 }
35414
35415 if (loadHooks[name]) {
35416 loadHooks[name].forEach(callback => callback(object));
35417 }
35418 }
35419});
35420define("@ember/canary-features/index", ["exports", "@ember/-internals/environment", "@ember/polyfills"], function (_exports, _environment, _polyfills) {
35421 "use strict";
35422
35423 Object.defineProperty(_exports, "__esModule", {
35424 value: true
35425 });
35426 _exports.isEnabled = isEnabled;
35427 _exports.EMBER_CACHE_API = _exports.EMBER_GLIMMER_IN_ELEMENT = _exports.EMBER_ROUTING_MODEL_ARG = _exports.EMBER_GLIMMER_SET_COMPONENT_TEMPLATE = _exports.EMBER_CUSTOM_COMPONENT_ARG_PROXY = _exports.EMBER_MODULE_UNIFICATION = _exports.EMBER_NAMED_BLOCKS = _exports.EMBER_IMPROVED_INSTRUMENTATION = _exports.EMBER_LIBRARIES_ISREGISTERED = _exports.FEATURES = _exports.DEFAULT_FEATURES = void 0;
35428
35429 /**
35430 Set `EmberENV.FEATURES` in your application's `config/environment.js` file
35431 to enable canary features in your application.
35432
35433 See the [feature flag guide](https://guides.emberjs.com/release/configuring-ember/feature-flags/)
35434 for more details.
35435
35436 @module @ember/canary-features
35437 @public
35438 */
35439 var DEFAULT_FEATURES = {
35440 EMBER_LIBRARIES_ISREGISTERED: false,
35441 EMBER_IMPROVED_INSTRUMENTATION: false,
35442 EMBER_NAMED_BLOCKS: false,
35443 EMBER_MODULE_UNIFICATION: false,
35444 EMBER_CUSTOM_COMPONENT_ARG_PROXY: true,
35445 EMBER_GLIMMER_SET_COMPONENT_TEMPLATE: true,
35446 EMBER_ROUTING_MODEL_ARG: true,
35447 EMBER_GLIMMER_IN_ELEMENT: true,
35448 EMBER_CACHE_API: false
35449 };
35450 /**
35451 The hash of enabled Canary features. Add to this, any canary features
35452 before creating your application.
35453
35454 @class FEATURES
35455 @static
35456 @since 1.1.0
35457 @public
35458 */
35459
35460 _exports.DEFAULT_FEATURES = DEFAULT_FEATURES;
35461 var FEATURES = (0, _polyfills.assign)(DEFAULT_FEATURES, _environment.ENV.FEATURES);
35462 /**
35463 Determine whether the specified `feature` is enabled. Used by Ember's
35464 build tools to exclude experimental features from beta/stable builds.
35465
35466 You can define the following configuration options:
35467
35468 * `EmberENV.ENABLE_OPTIONAL_FEATURES` - enable any features that have not been explicitly
35469 enabled/disabled.
35470
35471 @method isEnabled
35472 @param {String} feature The feature to check
35473 @return {Boolean}
35474 @since 1.1.0
35475 @public
35476 */
35477
35478 _exports.FEATURES = FEATURES;
35479
35480 function isEnabled(feature) {
35481 var featureValue = FEATURES[feature];
35482
35483 if (featureValue === true || featureValue === false) {
35484 return featureValue;
35485 } else if (_environment.ENV.ENABLE_OPTIONAL_FEATURES) {
35486 return true;
35487 } else {
35488 return false;
35489 }
35490 }
35491
35492 function featureValue(value) {
35493 if (_environment.ENV.ENABLE_OPTIONAL_FEATURES && value === null) {
35494 return true;
35495 }
35496
35497 return value;
35498 }
35499
35500 var EMBER_LIBRARIES_ISREGISTERED = featureValue(FEATURES.EMBER_LIBRARIES_ISREGISTERED);
35501 _exports.EMBER_LIBRARIES_ISREGISTERED = EMBER_LIBRARIES_ISREGISTERED;
35502 var EMBER_IMPROVED_INSTRUMENTATION = featureValue(FEATURES.EMBER_IMPROVED_INSTRUMENTATION);
35503 _exports.EMBER_IMPROVED_INSTRUMENTATION = EMBER_IMPROVED_INSTRUMENTATION;
35504 var EMBER_NAMED_BLOCKS = featureValue(FEATURES.EMBER_NAMED_BLOCKS);
35505 _exports.EMBER_NAMED_BLOCKS = EMBER_NAMED_BLOCKS;
35506 var EMBER_MODULE_UNIFICATION = featureValue(FEATURES.EMBER_MODULE_UNIFICATION);
35507 _exports.EMBER_MODULE_UNIFICATION = EMBER_MODULE_UNIFICATION;
35508 var EMBER_CUSTOM_COMPONENT_ARG_PROXY = featureValue(FEATURES.EMBER_CUSTOM_COMPONENT_ARG_PROXY);
35509 _exports.EMBER_CUSTOM_COMPONENT_ARG_PROXY = EMBER_CUSTOM_COMPONENT_ARG_PROXY;
35510 var EMBER_GLIMMER_SET_COMPONENT_TEMPLATE = featureValue(FEATURES.EMBER_GLIMMER_SET_COMPONENT_TEMPLATE);
35511 _exports.EMBER_GLIMMER_SET_COMPONENT_TEMPLATE = EMBER_GLIMMER_SET_COMPONENT_TEMPLATE;
35512 var EMBER_ROUTING_MODEL_ARG = featureValue(FEATURES.EMBER_ROUTING_MODEL_ARG);
35513 _exports.EMBER_ROUTING_MODEL_ARG = EMBER_ROUTING_MODEL_ARG;
35514 var EMBER_GLIMMER_IN_ELEMENT = featureValue(FEATURES.EMBER_GLIMMER_IN_ELEMENT);
35515 _exports.EMBER_GLIMMER_IN_ELEMENT = EMBER_GLIMMER_IN_ELEMENT;
35516 var EMBER_CACHE_API = featureValue(FEATURES.EMBER_CACHE_API);
35517 _exports.EMBER_CACHE_API = EMBER_CACHE_API;
35518});
35519define("@ember/component/index", ["exports", "@ember/-internals/glimmer"], function (_exports, _glimmer) {
35520 "use strict";
35521
35522 Object.defineProperty(_exports, "__esModule", {
35523 value: true
35524 });
35525 Object.defineProperty(_exports, "Component", {
35526 enumerable: true,
35527 get: function () {
35528 return _glimmer.Component;
35529 }
35530 });
35531});
35532define("@ember/component/template-only", ["exports"], function (_exports) {
35533 "use strict";
35534
35535 Object.defineProperty(_exports, "__esModule", {
35536 value: true
35537 });
35538 _exports.default = templateOnlyComponent;
35539 _exports.isTemplateOnlyComponent = isTemplateOnlyComponent;
35540 _exports.TemplateOnlyComponent = void 0;
35541
35542 // This is only exported for types, don't use this class directly
35543 class TemplateOnlyComponent {
35544 constructor(moduleName = '@ember/component/template-only') {
35545 this.moduleName = moduleName;
35546 }
35547
35548 toString() {
35549 return this.moduleName;
35550 }
35551
35552 }
35553 /**
35554 @module @ember/component/template-only
35555 @public
35556 */
35557
35558 /**
35559 This utility function is used to declare a given component has no backing class. When the rendering engine detects this it
35560 is able to perform a number of optimizations. Templates that are associated with `templateOnly()` will be rendered _as is_
35561 without adding a wrapping `<div>` (or any of the other element customization behaviors of [@ember/component](/ember/release/classes/Component)).
35562 Specifically, this means that the template will be rendered as "outer HTML".
35563
35564 In general, this method will be used by build time tooling and would not be directly written in an application. However,
35565 at times it may be useful to use directly to leverage the "outer HTML" semantics mentioned above. For example, if an addon would like
35566 to use these semantics for its templates but cannot be certain it will only be consumed by applications that have enabled the
35567 `template-only-glimmer-components` optional feature.
35568
35569 @example
35570
35571 ```js
35572 import templateOnly from '@ember/component/template-only';
35573
35574 export default templateOnly();
35575 ```
35576
35577 @public
35578 @method templateOnly
35579 @param {String} moduleName the module name that the template only component represents, this will be used for debugging purposes
35580 @category EMBER_GLIMMER_SET_COMPONENT_TEMPLATE
35581 */
35582
35583
35584 _exports.TemplateOnlyComponent = TemplateOnlyComponent;
35585
35586 function templateOnlyComponent(moduleName) {
35587 return new TemplateOnlyComponent(moduleName);
35588 }
35589
35590 function isTemplateOnlyComponent(component) {
35591 return component instanceof TemplateOnlyComponent;
35592 }
35593});
35594define("@ember/controller/index", ["exports", "@ember/-internals/runtime", "@ember/-internals/metal", "@ember/controller/lib/controller_mixin"], function (_exports, _runtime, _metal, _controller_mixin) {
35595 "use strict";
35596
35597 Object.defineProperty(_exports, "__esModule", {
35598 value: true
35599 });
35600 _exports.inject = inject;
35601 _exports.default = void 0;
35602
35603 /**
35604 @module @ember/controller
35605 */
35606
35607 /**
35608 @class Controller
35609 @extends EmberObject
35610 @uses Ember.ControllerMixin
35611 @public
35612 */
35613 var Controller = _runtime.FrameworkObject.extend(_controller_mixin.default);
35614 /**
35615 Creates a property that lazily looks up another controller in the container.
35616 Can only be used when defining another controller.
35617
35618 Example:
35619
35620 ```app/controllers/post.js
35621 import Controller, {
35622 inject as controller
35623 } from '@ember/controller';
35624
35625 export default class PostController extends Controller {
35626 @controller posts;
35627 }
35628 ```
35629
35630 Classic Class Example:
35631
35632 ```app/controllers/post.js
35633 import Controller, {
35634 inject as controller
35635 } from '@ember/controller';
35636
35637 export default Controller.extend({
35638 posts: controller()
35639 });
35640 ```
35641
35642 This example will create a `posts` property on the `post` controller that
35643 looks up the `posts` controller in the container, making it easy to reference
35644 other controllers.
35645
35646 @method inject
35647 @static
35648 @for @ember/controller
35649 @since 1.10.0
35650 @param {String} name (optional) name of the controller to inject, defaults to
35651 the property's name
35652 @return {ComputedDecorator} injection decorator instance
35653 @public
35654 */
35655
35656
35657 function inject() {
35658 return (0, _metal.inject)('controller', ...arguments);
35659 }
35660
35661 var _default = Controller;
35662 _exports.default = _default;
35663});
35664define("@ember/controller/lib/controller_mixin", ["exports", "@ember/-internals/metal", "@ember/-internals/runtime", "@ember/-internals/utils"], function (_exports, _metal, _runtime, _utils) {
35665 "use strict";
35666
35667 Object.defineProperty(_exports, "__esModule", {
35668 value: true
35669 });
35670 _exports.default = void 0;
35671 var MODEL = (0, _utils.symbol)('MODEL');
35672 /**
35673 @module ember
35674 */
35675
35676 /**
35677 @class ControllerMixin
35678 @namespace Ember
35679 @uses Ember.ActionHandler
35680 @private
35681 */
35682
35683 var _default = _metal.Mixin.create(_runtime.ActionHandler, {
35684 /* ducktype as a controller */
35685 isController: true,
35686
35687 /**
35688 The object to which actions from the view should be sent.
35689 For example, when a Handlebars template uses the `{{action}}` helper,
35690 it will attempt to send the action to the view's controller's `target`.
35691 By default, the value of the target property is set to the router, and
35692 is injected when a controller is instantiated. This injection is applied
35693 as part of the application's initialization process. In most cases the
35694 `target` property will automatically be set to the logical consumer of
35695 actions for the controller.
35696 @property target
35697 @default null
35698 @public
35699 */
35700 target: null,
35701 store: null,
35702
35703 /**
35704 The controller's current model. When retrieving or modifying a controller's
35705 model, this property should be used instead of the `content` property.
35706 @property model
35707 @public
35708 */
35709 model: (0, _metal.computed)({
35710 get() {
35711 return this[MODEL];
35712 },
35713
35714 set(key, value) {
35715 return this[MODEL] = value;
35716 }
35717
35718 })
35719 });
35720
35721 _exports.default = _default;
35722});
35723define("@ember/debug/index", ["exports", "@ember/-internals/browser-environment", "@ember/error", "@ember/debug/lib/deprecate", "@ember/debug/lib/testing", "@ember/debug/lib/warn", "@ember/debug/lib/capture-render-tree"], function (_exports, _browserEnvironment, _error, _deprecate2, _testing, _warn2, _captureRenderTree) {
35724 "use strict";
35725
35726 Object.defineProperty(_exports, "__esModule", {
35727 value: true
35728 });
35729 Object.defineProperty(_exports, "registerDeprecationHandler", {
35730 enumerable: true,
35731 get: function () {
35732 return _deprecate2.registerHandler;
35733 }
35734 });
35735 Object.defineProperty(_exports, "isTesting", {
35736 enumerable: true,
35737 get: function () {
35738 return _testing.isTesting;
35739 }
35740 });
35741 Object.defineProperty(_exports, "setTesting", {
35742 enumerable: true,
35743 get: function () {
35744 return _testing.setTesting;
35745 }
35746 });
35747 Object.defineProperty(_exports, "registerWarnHandler", {
35748 enumerable: true,
35749 get: function () {
35750 return _warn2.registerHandler;
35751 }
35752 });
35753 Object.defineProperty(_exports, "captureRenderTree", {
35754 enumerable: true,
35755 get: function () {
35756 return _captureRenderTree.default;
35757 }
35758 });
35759 _exports._warnIfUsingStrippedFeatureFlags = _exports.getDebugFunction = _exports.setDebugFunction = _exports.deprecateFunc = _exports.runInDebug = _exports.debugFreeze = _exports.debugSeal = _exports.deprecate = _exports.debug = _exports.warn = _exports.info = _exports.assert = void 0;
35760
35761 // These are the default production build versions:
35762 var noop = () => {};
35763
35764 var assert = noop;
35765 _exports.assert = assert;
35766 var info = noop;
35767 _exports.info = info;
35768 var warn = noop;
35769 _exports.warn = warn;
35770 var debug = noop;
35771 _exports.debug = debug;
35772 var deprecate = noop;
35773 _exports.deprecate = deprecate;
35774 var debugSeal = noop;
35775 _exports.debugSeal = debugSeal;
35776 var debugFreeze = noop;
35777 _exports.debugFreeze = debugFreeze;
35778 var runInDebug = noop;
35779 _exports.runInDebug = runInDebug;
35780 var setDebugFunction = noop;
35781 _exports.setDebugFunction = setDebugFunction;
35782 var getDebugFunction = noop;
35783 _exports.getDebugFunction = getDebugFunction;
35784
35785 var deprecateFunc = function () {
35786 return arguments[arguments.length - 1];
35787 };
35788
35789 _exports.deprecateFunc = deprecateFunc;
35790
35791 if (true
35792 /* DEBUG */
35793 ) {
35794 _exports.setDebugFunction = setDebugFunction = function (type, callback) {
35795 switch (type) {
35796 case 'assert':
35797 return _exports.assert = assert = callback;
35798
35799 case 'info':
35800 return _exports.info = info = callback;
35801
35802 case 'warn':
35803 return _exports.warn = warn = callback;
35804
35805 case 'debug':
35806 return _exports.debug = debug = callback;
35807
35808 case 'deprecate':
35809 return _exports.deprecate = deprecate = callback;
35810
35811 case 'debugSeal':
35812 return _exports.debugSeal = debugSeal = callback;
35813
35814 case 'debugFreeze':
35815 return _exports.debugFreeze = debugFreeze = callback;
35816
35817 case 'runInDebug':
35818 return _exports.runInDebug = runInDebug = callback;
35819
35820 case 'deprecateFunc':
35821 return _exports.deprecateFunc = deprecateFunc = callback;
35822 }
35823 };
35824
35825 _exports.getDebugFunction = getDebugFunction = function (type) {
35826 switch (type) {
35827 case 'assert':
35828 return assert;
35829
35830 case 'info':
35831 return info;
35832
35833 case 'warn':
35834 return warn;
35835
35836 case 'debug':
35837 return debug;
35838
35839 case 'deprecate':
35840 return deprecate;
35841
35842 case 'debugSeal':
35843 return debugSeal;
35844
35845 case 'debugFreeze':
35846 return debugFreeze;
35847
35848 case 'runInDebug':
35849 return runInDebug;
35850
35851 case 'deprecateFunc':
35852 return deprecateFunc;
35853 }
35854 };
35855 }
35856 /**
35857 @module @ember/debug
35858 */
35859
35860
35861 if (true
35862 /* DEBUG */
35863 ) {
35864 /**
35865 Verify that a certain expectation is met, or throw a exception otherwise.
35866 This is useful for communicating assumptions in the code to other human
35867 readers as well as catching bugs that accidentally violates these
35868 expectations.
35869 Assertions are removed from production builds, so they can be freely added
35870 for documentation and debugging purposes without worries of incuring any
35871 performance penalty. However, because of that, they should not be used for
35872 checks that could reasonably fail during normal usage. Furthermore, care
35873 should be taken to avoid accidentally relying on side-effects produced from
35874 evaluating the condition itself, since the code will not run in production.
35875 ```javascript
35876 import { assert } from '@ember/debug';
35877 // Test for truthiness
35878 assert('Must pass a string', typeof str === 'string');
35879 // Fail unconditionally
35880 assert('This code path should never be run');
35881 ```
35882 @method assert
35883 @static
35884 @for @ember/debug
35885 @param {String} description Describes the expectation. This will become the
35886 text of the Error thrown if the assertion fails.
35887 @param {any} condition Must be truthy for the assertion to pass. If
35888 falsy, an exception will be thrown.
35889 @public
35890 @since 1.0.0
35891 */
35892 setDebugFunction('assert', function assert(desc, test) {
35893 if (!test) {
35894 throw new _error.default(`Assertion Failed: ${desc}`);
35895 }
35896 });
35897 /**
35898 Display a debug notice.
35899 Calls to this function are removed from production builds, so they can be
35900 freely added for documentation and debugging purposes without worries of
35901 incuring any performance penalty.
35902 ```javascript
35903 import { debug } from '@ember/debug';
35904 debug('I\'m a debug notice!');
35905 ```
35906 @method debug
35907 @for @ember/debug
35908 @static
35909 @param {String} message A debug message to display.
35910 @public
35911 */
35912
35913 setDebugFunction('debug', function debug(message) {
35914 /* eslint-disable no-console */
35915 if (console.debug) {
35916 console.debug(`DEBUG: ${message}`);
35917 } else {
35918 console.log(`DEBUG: ${message}`);
35919 }
35920 /* eslint-ensable no-console */
35921
35922 });
35923 /**
35924 Display an info notice.
35925 Calls to this function are removed from production builds, so they can be
35926 freely added for documentation and debugging purposes without worries of
35927 incuring any performance penalty.
35928 @method info
35929 @private
35930 */
35931
35932 setDebugFunction('info', function info() {
35933 console.info(...arguments);
35934 /* eslint-disable-line no-console */
35935 });
35936 /**
35937 @module @ember/debug
35938 @public
35939 */
35940
35941 /**
35942 Alias an old, deprecated method with its new counterpart.
35943 Display a deprecation warning with the provided message and a stack trace
35944 (Chrome and Firefox only) when the assigned method is called.
35945 Calls to this function are removed from production builds, so they can be
35946 freely added for documentation and debugging purposes without worries of
35947 incuring any performance penalty.
35948 ```javascript
35949 import { deprecateFunc } from '@ember/debug';
35950 Ember.oldMethod = deprecateFunc('Please use the new, updated method', options, Ember.newMethod);
35951 ```
35952 @method deprecateFunc
35953 @static
35954 @for @ember/debug
35955 @param {String} message A description of the deprecation.
35956 @param {Object} [options] The options object for `deprecate`.
35957 @param {Function} func The new function called to replace its deprecated counterpart.
35958 @return {Function} A new function that wraps the original function with a deprecation warning
35959 @private
35960 */
35961
35962 setDebugFunction('deprecateFunc', function deprecateFunc(...args) {
35963 if (args.length === 3) {
35964 var [message, options, func] = args;
35965 return function (...args) {
35966 deprecate(message, false, options);
35967 return func.apply(this, args);
35968 };
35969 } else {
35970 var [_message, _func] = args;
35971 return function () {
35972 deprecate(_message);
35973 return _func.apply(this, arguments);
35974 };
35975 }
35976 });
35977 /**
35978 @module @ember/debug
35979 @public
35980 */
35981
35982 /**
35983 Run a function meant for debugging.
35984 Calls to this function are removed from production builds, so they can be
35985 freely added for documentation and debugging purposes without worries of
35986 incuring any performance penalty.
35987 ```javascript
35988 import Component from '@ember/component';
35989 import { runInDebug } from '@ember/debug';
35990 runInDebug(() => {
35991 Component.reopen({
35992 didInsertElement() {
35993 console.log("I'm happy");
35994 }
35995 });
35996 });
35997 ```
35998 @method runInDebug
35999 @for @ember/debug
36000 @static
36001 @param {Function} func The function to be executed.
36002 @since 1.5.0
36003 @public
36004 */
36005
36006 setDebugFunction('runInDebug', function runInDebug(func) {
36007 func();
36008 });
36009 setDebugFunction('debugSeal', function debugSeal(obj) {
36010 Object.seal(obj);
36011 });
36012 setDebugFunction('debugFreeze', function debugFreeze(obj) {
36013 // re-freezing an already frozen object introduces a significant
36014 // performance penalty on Chrome (tested through 59).
36015 //
36016 // See: https://bugs.chromium.org/p/v8/issues/detail?id=6450
36017 if (!Object.isFrozen(obj)) {
36018 Object.freeze(obj);
36019 }
36020 });
36021 setDebugFunction('deprecate', _deprecate2.default);
36022 setDebugFunction('warn', _warn2.default);
36023 }
36024
36025 var _warnIfUsingStrippedFeatureFlags;
36026
36027 _exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags;
36028
36029 if (true
36030 /* DEBUG */
36031 && !(0, _testing.isTesting)()) {
36032 if (typeof window !== 'undefined' && (_browserEnvironment.isFirefox || _browserEnvironment.isChrome) && window.addEventListener) {
36033 window.addEventListener('load', () => {
36034 if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset.emberExtension) {
36035 var downloadURL;
36036
36037 if (_browserEnvironment.isChrome) {
36038 downloadURL = 'https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi';
36039 } else if (_browserEnvironment.isFirefox) {
36040 downloadURL = 'https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/';
36041 }
36042
36043 debug(`For more advanced debugging, install the Ember Inspector from ${downloadURL}`);
36044 }
36045 }, false);
36046 }
36047 }
36048});
36049define("@ember/debug/lib/capture-render-tree", ["exports", "@glimmer/util"], function (_exports, _util) {
36050 "use strict";
36051
36052 Object.defineProperty(_exports, "__esModule", {
36053 value: true
36054 });
36055 _exports.default = captureRenderTree;
36056
36057 /**
36058 @module @ember/debug
36059 */
36060
36061 /**
36062 Ember Inspector calls this function to capture the current render tree.
36063
36064 In production mode, this requires turning on `ENV._DEBUG_RENDER_TREE`
36065 before loading Ember.
36066
36067 @private
36068 @static
36069 @method captureRenderTree
36070 @for @ember/debug
36071 @param app {ApplicationInstance} An `ApplicationInstance`.
36072 @since 3.14.0
36073 */
36074 function captureRenderTree(app) {
36075 var env = (0, _util.expect)(app.lookup('-environment:main'), 'BUG: owner is missing -environment:main');
36076 var rendererType = env.isInteractive ? 'renderer:-dom' : 'renderer:-inert';
36077 var renderer = (0, _util.expect)(app.lookup(rendererType), `BUG: owner is missing ${rendererType}`);
36078 return renderer.debugRenderTree.capture();
36079 }
36080});
36081define("@ember/debug/lib/deprecate", ["exports", "@ember/-internals/environment", "@ember/debug/index", "@ember/debug/lib/handlers"], function (_exports, _environment, _index, _handlers) {
36082 "use strict";
36083
36084 Object.defineProperty(_exports, "__esModule", {
36085 value: true
36086 });
36087 _exports.missingOptionsUntilDeprecation = _exports.missingOptionsIdDeprecation = _exports.missingOptionsDeprecation = _exports.registerHandler = _exports.default = void 0;
36088
36089 /**
36090 @module @ember/debug
36091 @public
36092 */
36093
36094 /**
36095 Allows for runtime registration of handler functions that override the default deprecation behavior.
36096 Deprecations are invoked by calls to [@ember/debug/deprecate](/ember/release/classes/@ember%2Fdebug/methods/deprecate?anchor=deprecate).
36097 The following example demonstrates its usage by registering a handler that throws an error if the
36098 message contains the word "should", otherwise defers to the default handler.
36099
36100 ```javascript
36101 import { registerDeprecationHandler } from '@ember/debug';
36102
36103 registerDeprecationHandler((message, options, next) => {
36104 if (message.indexOf('should') !== -1) {
36105 throw new Error(`Deprecation message with should: ${message}`);
36106 } else {
36107 // defer to whatever handler was registered before this one
36108 next(message, options);
36109 }
36110 });
36111 ```
36112
36113 The handler function takes the following arguments:
36114
36115 <ul>
36116 <li> <code>message</code> - The message received from the deprecation call.</li>
36117 <li> <code>options</code> - An object passed in with the deprecation call containing additional information including:</li>
36118 <ul>
36119 <li> <code>id</code> - An id of the deprecation in the form of <code>package-name.specific-deprecation</code>.</li>
36120 <li> <code>until</code> - The Ember version number the feature and deprecation will be removed in.</li>
36121 </ul>
36122 <li> <code>next</code> - A function that calls into the previously registered handler.</li>
36123 </ul>
36124
36125 @public
36126 @static
36127 @method registerDeprecationHandler
36128 @for @ember/debug
36129 @param handler {Function} A function to handle deprecation calls.
36130 @since 2.1.0
36131 */
36132 var registerHandler = () => {};
36133
36134 _exports.registerHandler = registerHandler;
36135 var missingOptionsDeprecation;
36136 _exports.missingOptionsDeprecation = missingOptionsDeprecation;
36137 var missingOptionsIdDeprecation;
36138 _exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation;
36139 var missingOptionsUntilDeprecation;
36140 _exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation;
36141
36142 var deprecate = () => {};
36143
36144 if (true
36145 /* DEBUG */
36146 ) {
36147 _exports.registerHandler = registerHandler = function registerHandler(handler) {
36148 (0, _handlers.registerHandler)('deprecate', handler);
36149 };
36150
36151 var formatMessage = function formatMessage(_message, options) {
36152 var message = _message;
36153
36154 if (options && options.id) {
36155 message = message + ` [deprecation id: ${options.id}]`;
36156 }
36157
36158 if (options && options.url) {
36159 message += ` See ${options.url} for more details.`;
36160 }
36161
36162 return message;
36163 };
36164
36165 registerHandler(function logDeprecationToConsole(message, options) {
36166 var updatedMessage = formatMessage(message, options);
36167 console.warn(`DEPRECATION: ${updatedMessage}`); // eslint-disable-line no-console
36168 });
36169 var captureErrorForStack;
36170
36171 if (new Error().stack) {
36172 captureErrorForStack = () => new Error();
36173 } else {
36174 captureErrorForStack = () => {
36175 try {
36176 __fail__.fail();
36177 } catch (e) {
36178 return e;
36179 }
36180 };
36181 }
36182
36183 registerHandler(function logDeprecationStackTrace(message, options, next) {
36184 if (_environment.ENV.LOG_STACKTRACE_ON_DEPRECATION) {
36185 var stackStr = '';
36186 var error = captureErrorForStack();
36187 var stack;
36188
36189 if (error.stack) {
36190 if (error['arguments']) {
36191 // Chrome
36192 stack = error.stack.replace(/^\s+at\s+/gm, '').replace(/^([^(]+?)([\n$])/gm, '{anonymous}($1)$2').replace(/^Object.<anonymous>\s*\(([^)]+)\)/gm, '{anonymous}($1)').split('\n');
36193 stack.shift();
36194 } else {
36195 // Firefox
36196 stack = error.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^\(/gm, '{anonymous}(').split('\n');
36197 }
36198
36199 stackStr = `\n ${stack.slice(2).join('\n ')}`;
36200 }
36201
36202 var updatedMessage = formatMessage(message, options);
36203 console.warn(`DEPRECATION: ${updatedMessage}${stackStr}`); // eslint-disable-line no-console
36204 } else {
36205 next(message, options);
36206 }
36207 });
36208 registerHandler(function raiseOnDeprecation(message, options, next) {
36209 if (_environment.ENV.RAISE_ON_DEPRECATION) {
36210 var updatedMessage = formatMessage(message);
36211 throw new Error(updatedMessage);
36212 } else {
36213 next(message, options);
36214 }
36215 });
36216 _exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `deprecate` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include `id` and `until` properties.';
36217 _exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `deprecate` you must provide `id` in options.';
36218 _exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation = 'When calling `deprecate` you must provide `until` in options.';
36219 /**
36220 @module @ember/debug
36221 @public
36222 */
36223
36224 /**
36225 Display a deprecation warning with the provided message and a stack trace
36226 (Chrome and Firefox only).
36227 * In a production build, this method is defined as an empty function (NOP).
36228 Uses of this method in Ember itself are stripped from the ember.prod.js build.
36229 @method deprecate
36230 @for @ember/debug
36231 @param {String} message A description of the deprecation.
36232 @param {Boolean} test A boolean. If falsy, the deprecation will be displayed.
36233 @param {Object} options
36234 @param {String} options.id A unique id for this deprecation. The id can be
36235 used by Ember debugging tools to change the behavior (raise, log or silence)
36236 for that specific deprecation. The id should be namespaced by dots, e.g.
36237 "view.helper.select".
36238 @param {string} options.until The version of Ember when this deprecation
36239 warning will be removed.
36240 @param {String} [options.url] An optional url to the transition guide on the
36241 emberjs.com website.
36242 @static
36243 @public
36244 @since 1.0.0
36245 */
36246
36247 deprecate = function deprecate(message, test, options) {
36248 (0, _index.assert)(missingOptionsDeprecation, Boolean(options && (options.id || options.until)));
36249 (0, _index.assert)(missingOptionsIdDeprecation, Boolean(options.id));
36250 (0, _index.assert)(missingOptionsUntilDeprecation, Boolean(options.until));
36251 (0, _handlers.invoke)('deprecate', message, test, options);
36252 };
36253 }
36254
36255 var _default = deprecate;
36256 _exports.default = _default;
36257});
36258define("@ember/debug/lib/handlers", ["exports"], function (_exports) {
36259 "use strict";
36260
36261 Object.defineProperty(_exports, "__esModule", {
36262 value: true
36263 });
36264 _exports.invoke = _exports.registerHandler = _exports.HANDLERS = void 0;
36265 var HANDLERS = {};
36266 _exports.HANDLERS = HANDLERS;
36267
36268 var registerHandler = () => {};
36269
36270 _exports.registerHandler = registerHandler;
36271
36272 var invoke = () => {};
36273
36274 _exports.invoke = invoke;
36275
36276 if (true
36277 /* DEBUG */
36278 ) {
36279 _exports.registerHandler = registerHandler = function registerHandler(type, callback) {
36280 var nextHandler = HANDLERS[type] || (() => {});
36281
36282 HANDLERS[type] = (message, options) => {
36283 callback(message, options, nextHandler);
36284 };
36285 };
36286
36287 _exports.invoke = invoke = function invoke(type, message, test, options) {
36288 if (test) {
36289 return;
36290 }
36291
36292 var handlerForType = HANDLERS[type];
36293
36294 if (handlerForType) {
36295 handlerForType(message, options);
36296 }
36297 };
36298 }
36299});
36300define("@ember/debug/lib/testing", ["exports"], function (_exports) {
36301 "use strict";
36302
36303 Object.defineProperty(_exports, "__esModule", {
36304 value: true
36305 });
36306 _exports.isTesting = isTesting;
36307 _exports.setTesting = setTesting;
36308 var testing = false;
36309
36310 function isTesting() {
36311 return testing;
36312 }
36313
36314 function setTesting(value) {
36315 testing = Boolean(value);
36316 }
36317});
36318define("@ember/debug/lib/warn", ["exports", "@ember/debug/index", "@ember/debug/lib/handlers"], function (_exports, _index, _handlers) {
36319 "use strict";
36320
36321 Object.defineProperty(_exports, "__esModule", {
36322 value: true
36323 });
36324 _exports.missingOptionsDeprecation = _exports.missingOptionsIdDeprecation = _exports.registerHandler = _exports.default = void 0;
36325
36326 var registerHandler = () => {};
36327
36328 _exports.registerHandler = registerHandler;
36329
36330 var warn = () => {};
36331
36332 var missingOptionsDeprecation;
36333 _exports.missingOptionsDeprecation = missingOptionsDeprecation;
36334 var missingOptionsIdDeprecation;
36335 /**
36336 @module @ember/debug
36337 */
36338
36339 _exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation;
36340
36341 if (true
36342 /* DEBUG */
36343 ) {
36344 /**
36345 Allows for runtime registration of handler functions that override the default warning behavior.
36346 Warnings are invoked by calls made to [@ember/debug/warn](/ember/release/classes/@ember%2Fdebug/methods/warn?anchor=warn).
36347 The following example demonstrates its usage by registering a handler that does nothing overriding Ember's
36348 default warning behavior.
36349 ```javascript
36350 import { registerWarnHandler } from '@ember/debug';
36351 // next is not called, so no warnings get the default behavior
36352 registerWarnHandler(() => {});
36353 ```
36354 The handler function takes the following arguments:
36355 <ul>
36356 <li> <code>message</code> - The message received from the warn call. </li>
36357 <li> <code>options</code> - An object passed in with the warn call containing additional information including:</li>
36358 <ul>
36359 <li> <code>id</code> - An id of the warning in the form of <code>package-name.specific-warning</code>.</li>
36360 </ul>
36361 <li> <code>next</code> - A function that calls into the previously registered handler.</li>
36362 </ul>
36363 @public
36364 @static
36365 @method registerWarnHandler
36366 @for @ember/debug
36367 @param handler {Function} A function to handle warnings.
36368 @since 2.1.0
36369 */
36370 _exports.registerHandler = registerHandler = function registerHandler(handler) {
36371 (0, _handlers.registerHandler)('warn', handler);
36372 };
36373
36374 registerHandler(function logWarning(message) {
36375 /* eslint-disable no-console */
36376 console.warn(`WARNING: ${message}`);
36377 /* eslint-enable no-console */
36378 });
36379 _exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `warn` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include an `id` property.';
36380 _exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `warn` you must provide `id` in options.';
36381 /**
36382 Display a warning with the provided message.
36383 * In a production build, this method is defined as an empty function (NOP).
36384 Uses of this method in Ember itself are stripped from the ember.prod.js build.
36385 ```javascript
36386 import { warn } from '@ember/debug';
36387 import tomsterCount from './tomster-counter'; // a module in my project
36388 // Log a warning if we have more than 3 tomsters
36389 warn('Too many tomsters!', tomsterCount <= 3, {
36390 id: 'ember-debug.too-many-tomsters'
36391 });
36392 ```
36393 @method warn
36394 @for @ember/debug
36395 @static
36396 @param {String} message A warning to display.
36397 @param {Boolean} test An optional boolean. If falsy, the warning
36398 will be displayed.
36399 @param {Object} options An object that can be used to pass a unique
36400 `id` for this warning. The `id` can be used by Ember debugging tools
36401 to change the behavior (raise, log, or silence) for that specific warning.
36402 The `id` should be namespaced by dots, e.g. "ember-debug.feature-flag-with-features-stripped"
36403 @public
36404 @since 1.0.0
36405 */
36406
36407 warn = function warn(message, test, options) {
36408 if (arguments.length === 2 && typeof test === 'object') {
36409 options = test;
36410 test = false;
36411 }
36412
36413 (0, _index.assert)(missingOptionsDeprecation, Boolean(options));
36414 (0, _index.assert)(missingOptionsIdDeprecation, Boolean(options && options.id));
36415 (0, _handlers.invoke)('warn', message, test, options);
36416 };
36417 }
36418
36419 var _default = warn;
36420 _exports.default = _default;
36421});
36422define("@ember/deprecated-features/index", ["exports"], function (_exports) {
36423 "use strict";
36424
36425 Object.defineProperty(_exports, "__esModule", {
36426 value: true
36427 });
36428 _exports.GLOBALS_RESOLVER = _exports.PARTIALS = _exports.EMBER_COMPONENT_IS_VISIBLE = _exports.MOUSE_ENTER_LEAVE_MOVE_EVENTS = _exports.FUNCTION_PROTOTYPE_EXTENSIONS = _exports.APP_CTRL_ROUTER_PROPS = _exports.ALIAS_METHOD = _exports.JQUERY_INTEGRATION = _exports.COMPONENT_MANAGER_STRING_LOOKUP = _exports.ROUTER_EVENTS = _exports.MERGE = _exports.LOGGER = _exports.EMBER_EXTEND_PROTOTYPES = _exports.SEND_ACTION = void 0;
36429
36430 /* eslint-disable no-implicit-coercion */
36431 // These versions should be the version that the deprecation was _introduced_,
36432 // not the version that the feature will be removed.
36433 var SEND_ACTION = !!'3.4.0';
36434 _exports.SEND_ACTION = SEND_ACTION;
36435 var EMBER_EXTEND_PROTOTYPES = !!'3.2.0-beta.5';
36436 _exports.EMBER_EXTEND_PROTOTYPES = EMBER_EXTEND_PROTOTYPES;
36437 var LOGGER = !!'3.2.0-beta.1';
36438 _exports.LOGGER = LOGGER;
36439 var MERGE = !!'3.6.0-beta.1';
36440 _exports.MERGE = MERGE;
36441 var ROUTER_EVENTS = !!'4.0.0';
36442 _exports.ROUTER_EVENTS = ROUTER_EVENTS;
36443 var COMPONENT_MANAGER_STRING_LOOKUP = !!'3.8.0';
36444 _exports.COMPONENT_MANAGER_STRING_LOOKUP = COMPONENT_MANAGER_STRING_LOOKUP;
36445 var JQUERY_INTEGRATION = !!'3.9.0';
36446 _exports.JQUERY_INTEGRATION = JQUERY_INTEGRATION;
36447 var ALIAS_METHOD = !!'3.9.0';
36448 _exports.ALIAS_METHOD = ALIAS_METHOD;
36449 var APP_CTRL_ROUTER_PROPS = !!'3.10.0-beta.1';
36450 _exports.APP_CTRL_ROUTER_PROPS = APP_CTRL_ROUTER_PROPS;
36451 var FUNCTION_PROTOTYPE_EXTENSIONS = !!'3.11.0-beta.1';
36452 _exports.FUNCTION_PROTOTYPE_EXTENSIONS = FUNCTION_PROTOTYPE_EXTENSIONS;
36453 var MOUSE_ENTER_LEAVE_MOVE_EVENTS = !!'3.13.0-beta.1';
36454 _exports.MOUSE_ENTER_LEAVE_MOVE_EVENTS = MOUSE_ENTER_LEAVE_MOVE_EVENTS;
36455 var EMBER_COMPONENT_IS_VISIBLE = !!'3.15.0-beta.1';
36456 _exports.EMBER_COMPONENT_IS_VISIBLE = EMBER_COMPONENT_IS_VISIBLE;
36457 var PARTIALS = !!'3.15.0-beta.1';
36458 _exports.PARTIALS = PARTIALS;
36459 var GLOBALS_RESOLVER = !!'3.16.0-beta.1';
36460 _exports.GLOBALS_RESOLVER = GLOBALS_RESOLVER;
36461});
36462define("@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) {
36463 "use strict";
36464
36465 Object.defineProperty(_exports, "__esModule", {
36466 value: true
36467 });
36468 Object.defineProperty(_exports, "getEngineParent", {
36469 enumerable: true,
36470 get: function () {
36471 return _engineParent.getEngineParent;
36472 }
36473 });
36474 Object.defineProperty(_exports, "setEngineParent", {
36475 enumerable: true,
36476 get: function () {
36477 return _engineParent.setEngineParent;
36478 }
36479 });
36480 _exports.default = void 0;
36481
36482 function props(obj) {
36483 var properties = [];
36484
36485 for (var key in obj) {
36486 properties.push(key);
36487 }
36488
36489 return properties;
36490 }
36491 /**
36492 @module @ember/engine
36493 */
36494
36495 /**
36496 The `Engine` class contains core functionality for both applications and
36497 engines.
36498
36499 Each engine manages a registry that's used for dependency injection and
36500 exposed through `RegistryProxy`.
36501
36502 Engines also manage initializers and instance initializers.
36503
36504 Engines can spawn `EngineInstance` instances via `buildInstance()`.
36505
36506 @class Engine
36507 @extends Ember.Namespace
36508 @uses RegistryProxy
36509 @public
36510 */
36511
36512
36513 var Engine = _runtime.Namespace.extend(_runtime.RegistryProxyMixin, {
36514 init() {
36515 this._super(...arguments);
36516
36517 this.buildRegistry();
36518 },
36519
36520 /**
36521 A private flag indicating whether an engine's initializers have run yet.
36522 @private
36523 @property _initializersRan
36524 */
36525 _initializersRan: false,
36526
36527 /**
36528 Ensure that initializers are run once, and only once, per engine.
36529 @private
36530 @method ensureInitializers
36531 */
36532 ensureInitializers() {
36533 if (!this._initializersRan) {
36534 this.runInitializers();
36535 this._initializersRan = true;
36536 }
36537 },
36538
36539 /**
36540 Create an EngineInstance for this engine.
36541 @public
36542 @method buildInstance
36543 @return {EngineInstance} the engine instance
36544 */
36545 buildInstance(options = {}) {
36546 this.ensureInitializers();
36547 options.base = this;
36548 return _instance.default.create(options);
36549 },
36550
36551 /**
36552 Build and configure the registry for the current engine.
36553 @private
36554 @method buildRegistry
36555 @return {Ember.Registry} the configured registry
36556 */
36557 buildRegistry() {
36558 var registry = this.__registry__ = this.constructor.buildRegistry(this);
36559 return registry;
36560 },
36561
36562 /**
36563 @private
36564 @method initializer
36565 */
36566 initializer(options) {
36567 this.constructor.initializer(options);
36568 },
36569
36570 /**
36571 @private
36572 @method instanceInitializer
36573 */
36574 instanceInitializer(options) {
36575 this.constructor.instanceInitializer(options);
36576 },
36577
36578 /**
36579 @private
36580 @method runInitializers
36581 */
36582 runInitializers() {
36583 this._runInitializer('initializers', (name, initializer) => {
36584 (true && !(Boolean(initializer)) && (0, _debug.assert)(`No application initializer named '${name}'`, Boolean(initializer)));
36585 initializer.initialize(this);
36586 });
36587 },
36588
36589 /**
36590 @private
36591 @since 1.12.0
36592 @method runInstanceInitializers
36593 */
36594 runInstanceInitializers(instance) {
36595 this._runInitializer('instanceInitializers', (name, initializer) => {
36596 (true && !(Boolean(initializer)) && (0, _debug.assert)(`No instance initializer named '${name}'`, Boolean(initializer)));
36597 initializer.initialize(instance);
36598 });
36599 },
36600
36601 _runInitializer(bucketName, cb) {
36602 var initializersByName = (0, _metal.get)(this.constructor, bucketName);
36603 var initializers = props(initializersByName);
36604 var graph = new _dagMap.default();
36605 var initializer;
36606
36607 for (var i = 0; i < initializers.length; i++) {
36608 initializer = initializersByName[initializers[i]];
36609 graph.add(initializer.name, initializer, initializer.before, initializer.after);
36610 }
36611
36612 graph.topsort(cb);
36613 }
36614
36615 });
36616
36617 Engine.reopenClass({
36618 initializers: Object.create(null),
36619 instanceInitializers: Object.create(null),
36620
36621 /**
36622 The goal of initializers should be to register dependencies and injections.
36623 This phase runs once. Because these initializers may load code, they are
36624 allowed to defer application readiness and advance it. If you need to access
36625 the container or store you should use an InstanceInitializer that will be run
36626 after all initializers and therefore after all code is loaded and the app is
36627 ready.
36628 Initializer receives an object which has the following attributes:
36629 `name`, `before`, `after`, `initialize`. The only required attribute is
36630 `initialize`, all others are optional.
36631 * `name` allows you to specify under which name the initializer is registered.
36632 This must be a unique name, as trying to register two initializers with the
36633 same name will result in an error.
36634 ```app/initializer/named-initializer.js
36635 import { debug } from '@ember/debug';
36636 export function initialize() {
36637 debug('Running namedInitializer!');
36638 }
36639 export default {
36640 name: 'named-initializer',
36641 initialize
36642 };
36643 ```
36644 * `before` and `after` are used to ensure that this initializer is ran prior
36645 or after the one identified by the value. This value can be a single string
36646 or an array of strings, referencing the `name` of other initializers.
36647 An example of ordering initializers, we create an initializer named `first`:
36648 ```app/initializer/first.js
36649 import { debug } from '@ember/debug';
36650 export function initialize() {
36651 debug('First initializer!');
36652 }
36653 export default {
36654 name: 'first',
36655 initialize
36656 };
36657 ```
36658 ```bash
36659 // DEBUG: First initializer!
36660 ```
36661 We add another initializer named `second`, specifying that it should run
36662 after the initializer named `first`:
36663 ```app/initializer/second.js
36664 import { debug } from '@ember/debug';
36665 export function initialize() {
36666 debug('Second initializer!');
36667 }
36668 export default {
36669 name: 'second',
36670 after: 'first',
36671 initialize
36672 };
36673 ```
36674 ```
36675 // DEBUG: First initializer!
36676 // DEBUG: Second initializer!
36677 ```
36678 Afterwards we add a further initializer named `pre`, this time specifying
36679 that it should run before the initializer named `first`:
36680 ```app/initializer/pre.js
36681 import { debug } from '@ember/debug';
36682 export function initialize() {
36683 debug('Pre initializer!');
36684 }
36685 export default {
36686 name: 'pre',
36687 before: 'first',
36688 initialize
36689 };
36690 ```
36691 ```bash
36692 // DEBUG: Pre initializer!
36693 // DEBUG: First initializer!
36694 // DEBUG: Second initializer!
36695 ```
36696 Finally we add an initializer named `post`, specifying it should run after
36697 both the `first` and the `second` initializers:
36698 ```app/initializer/post.js
36699 import { debug } from '@ember/debug';
36700 export function initialize() {
36701 debug('Post initializer!');
36702 }
36703 export default {
36704 name: 'post',
36705 after: ['first', 'second'],
36706 initialize
36707 };
36708 ```
36709 ```bash
36710 // DEBUG: Pre initializer!
36711 // DEBUG: First initializer!
36712 // DEBUG: Second initializer!
36713 // DEBUG: Post initializer!
36714 ```
36715 * `initialize` is a callback function that receives one argument,
36716 `application`, on which you can operate.
36717 Example of using `application` to register an adapter:
36718 ```app/initializer/api-adapter.js
36719 import ApiAdapter from '../utils/api-adapter';
36720 export function initialize(application) {
36721 application.register('api-adapter:main', ApiAdapter);
36722 }
36723 export default {
36724 name: 'post',
36725 after: ['first', 'second'],
36726 initialize
36727 };
36728 ```
36729 @method initializer
36730 @param initializer {Object}
36731 @public
36732 */
36733 initializer: buildInitializerMethod('initializers', 'initializer'),
36734
36735 /**
36736 Instance initializers run after all initializers have run. Because
36737 instance initializers run after the app is fully set up. We have access
36738 to the store, container, and other items. However, these initializers run
36739 after code has loaded and are not allowed to defer readiness.
36740 Instance initializer receives an object which has the following attributes:
36741 `name`, `before`, `after`, `initialize`. The only required attribute is
36742 `initialize`, all others are optional.
36743 * `name` allows you to specify under which name the instanceInitializer is
36744 registered. This must be a unique name, as trying to register two
36745 instanceInitializer with the same name will result in an error.
36746 ```app/initializer/named-instance-initializer.js
36747 import { debug } from '@ember/debug';
36748 export function initialize() {
36749 debug('Running named-instance-initializer!');
36750 }
36751 export default {
36752 name: 'named-instance-initializer',
36753 initialize
36754 };
36755 ```
36756 * `before` and `after` are used to ensure that this initializer is ran prior
36757 or after the one identified by the value. This value can be a single string
36758 or an array of strings, referencing the `name` of other initializers.
36759 * See Application.initializer for discussion on the usage of before
36760 and after.
36761 Example instanceInitializer to preload data into the store.
36762 ```app/initializer/preload-data.js
36763 import $ from 'jquery';
36764 export function initialize(application) {
36765 var userConfig, userConfigEncoded, store;
36766 // We have a HTML escaped JSON representation of the user's basic
36767 // configuration generated server side and stored in the DOM of the main
36768 // index.html file. This allows the app to have access to a set of data
36769 // without making any additional remote calls. Good for basic data that is
36770 // needed for immediate rendering of the page. Keep in mind, this data,
36771 // like all local models and data can be manipulated by the user, so it
36772 // should not be relied upon for security or authorization.
36773 // Grab the encoded data from the meta tag
36774 userConfigEncoded = $('head meta[name=app-user-config]').attr('content');
36775 // Unescape the text, then parse the resulting JSON into a real object
36776 userConfig = JSON.parse(unescape(userConfigEncoded));
36777 // Lookup the store
36778 store = application.lookup('service:store');
36779 // Push the encoded JSON into the store
36780 store.pushPayload(userConfig);
36781 }
36782 export default {
36783 name: 'named-instance-initializer',
36784 initialize
36785 };
36786 ```
36787 @method instanceInitializer
36788 @param instanceInitializer
36789 @public
36790 */
36791 instanceInitializer: buildInitializerMethod('instanceInitializers', 'instance initializer'),
36792
36793 /**
36794 This creates a registry with the default Ember naming conventions.
36795 It also configures the registry:
36796 * registered views are created every time they are looked up (they are
36797 not singletons)
36798 * registered templates are not factories; the registered value is
36799 returned directly.
36800 * the router receives the application as its `namespace` property
36801 * all controllers receive the router as their `target` and `controllers`
36802 properties
36803 * all controllers receive the application as their `namespace` property
36804 * the application view receives the application controller as its
36805 `controller` property
36806 * the application view receives the application template as its
36807 `defaultTemplate` property
36808 @method buildRegistry
36809 @static
36810 @param {Application} namespace the application for which to
36811 build the registry
36812 @return {Ember.Registry} the built registry
36813 @private
36814 */
36815 buildRegistry(namespace) {
36816 var registry = new _container.Registry({
36817 resolver: resolverFor(namespace)
36818 });
36819 registry.set = _metal.set;
36820 registry.register('application:main', namespace, {
36821 instantiate: false
36822 });
36823 commonSetupRegistry(registry);
36824 (0, _glimmer.setupEngineRegistry)(registry);
36825 return registry;
36826 },
36827
36828 /**
36829 Set this to provide an alternate class to `DefaultResolver`
36830 @deprecated Use 'Resolver' instead
36831 @property resolver
36832 @public
36833 */
36834 resolver: null,
36835
36836 /**
36837 Set this to provide an alternate class to `DefaultResolver`
36838 @property resolver
36839 @public
36840 */
36841 Resolver: null
36842 });
36843 /**
36844 This function defines the default lookup rules for container lookups:
36845
36846 * templates are looked up on `Ember.TEMPLATES`
36847 * other names are looked up on the application after classifying the name.
36848 For example, `controller:post` looks up `App.PostController` by default.
36849 * if the default lookup fails, look for registered classes on the container
36850
36851 This allows the application to register default injections in the container
36852 that could be overridden by the normal naming convention.
36853
36854 @private
36855 @method resolverFor
36856 @param {Ember.Namespace} namespace the namespace to look for classes
36857 @return {*} the resolved value for a given lookup
36858 */
36859
36860 function resolverFor(namespace) {
36861 var ResolverClass = (0, _metal.get)(namespace, 'Resolver') || _globalsResolver.default;
36862
36863 var props = {
36864 namespace
36865 };
36866 return ResolverClass.create(props);
36867 }
36868
36869 function buildInitializerMethod(bucketName, humanName) {
36870 return function (initializer) {
36871 // If this is the first initializer being added to a subclass, we are going to reopen the class
36872 // to make sure we have a new `initializers` object, which extends from the parent class' using
36873 // prototypal inheritance. Without this, attempting to add initializers to the subclass would
36874 // pollute the parent class as well as other subclasses.
36875 if (this.superclass[bucketName] !== undefined && this.superclass[bucketName] === this[bucketName]) {
36876 var attrs = {};
36877 attrs[bucketName] = Object.create(this[bucketName]);
36878 this.reopenClass(attrs);
36879 }
36880
36881 (true && !(!this[bucketName][initializer.name]) && (0, _debug.assert)(`The ${humanName} '${initializer.name}' has already been registered`, !this[bucketName][initializer.name]));
36882 (true && !((0, _utils.canInvoke)(initializer, 'initialize')) && (0, _debug.assert)(`An ${humanName} cannot be registered without an initialize function`, (0, _utils.canInvoke)(initializer, 'initialize')));
36883 (true && !(initializer.name !== undefined) && (0, _debug.assert)(`An ${humanName} cannot be registered without a name property`, initializer.name !== undefined));
36884 this[bucketName][initializer.name] = initializer;
36885 };
36886 }
36887
36888 function commonSetupRegistry(registry) {
36889 registry.optionsForType('component', {
36890 singleton: false
36891 });
36892 registry.optionsForType('view', {
36893 singleton: false
36894 });
36895 registry.register('controller:basic', _controller.default, {
36896 instantiate: false
36897 });
36898 registry.injection('view', '_viewRegistry', '-view-registry:main');
36899 registry.injection('renderer', '_viewRegistry', '-view-registry:main');
36900 registry.injection('route', '_topLevelViewTemplate', 'template:-outlet');
36901 registry.injection('view:-outlet', 'namespace', 'application:main');
36902 registry.injection('controller', 'target', 'router:main');
36903 registry.injection('controller', 'namespace', 'application:main');
36904 registry.injection('router', '_bucketCache', (0, _container.privatize)`-bucket-cache:main`);
36905 registry.injection('route', '_bucketCache', (0, _container.privatize)`-bucket-cache:main`);
36906 registry.injection('route', '_router', 'router:main'); // Register the routing service...
36907
36908 registry.register('service:-routing', _routing.RoutingService); // Then inject the app router into it
36909
36910 registry.injection('service:-routing', 'router', 'router:main'); // DEBUGGING
36911
36912 registry.register('resolver-for-debugging:main', registry.resolver, {
36913 instantiate: false
36914 });
36915 registry.injection('container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main');
36916 registry.injection('data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main'); // Custom resolver authors may want to register their own ContainerDebugAdapter with this key
36917
36918 registry.register('container-debug-adapter:main', _extensionSupport.ContainerDebugAdapter);
36919 registry.register('component-lookup:main', _views.ComponentLookup);
36920 }
36921
36922 var _default = Engine;
36923 _exports.default = _default;
36924});
36925define("@ember/engine/instance", ["exports", "@ember/-internals/runtime", "@ember/debug", "@ember/error", "@ember/-internals/container", "@ember/-internals/utils", "@ember/engine/lib/engine-parent"], function (_exports, _runtime, _debug, _error, _container, _utils, _engineParent) {
36926 "use strict";
36927
36928 Object.defineProperty(_exports, "__esModule", {
36929 value: true
36930 });
36931 _exports.default = void 0;
36932
36933 /**
36934 @module @ember/engine
36935 */
36936
36937 /**
36938 The `EngineInstance` encapsulates all of the stateful aspects of a
36939 running `Engine`.
36940
36941 @public
36942 @class EngineInstance
36943 @extends EmberObject
36944 @uses RegistryProxyMixin
36945 @uses ContainerProxyMixin
36946 */
36947 var EngineInstance = _runtime.Object.extend(_runtime.RegistryProxyMixin, _runtime.ContainerProxyMixin, {
36948 /**
36949 The base `Engine` for which this is an instance.
36950 @property {Engine} engine
36951 @private
36952 */
36953 base: null,
36954
36955 init() {
36956 this._super(...arguments); // Ensure the guid gets setup for this instance
36957
36958
36959 (0, _utils.guidFor)(this);
36960 var base = this.base;
36961
36962 if (!base) {
36963 base = this.application;
36964 this.base = base;
36965 } // Create a per-instance registry that will use the application's registry
36966 // as a fallback for resolving registrations.
36967
36968
36969 var registry = this.__registry__ = new _container.Registry({
36970 fallback: base.__registry__
36971 }); // Create a per-instance container from the instance's registry
36972
36973 this.__container__ = registry.container({
36974 owner: this
36975 });
36976 this._booted = false;
36977 },
36978
36979 /**
36980 Initialize the `EngineInstance` and return a promise that resolves
36981 with the instance itself when the boot process is complete.
36982 The primary task here is to run any registered instance initializers.
36983 See the documentation on `BootOptions` for the options it takes.
36984 @public
36985 @method boot
36986 @param options {Object}
36987 @return {Promise<EngineInstance,Error>}
36988 */
36989 boot(options) {
36990 if (this._bootPromise) {
36991 return this._bootPromise;
36992 }
36993
36994 this._bootPromise = new _runtime.RSVP.Promise(resolve => resolve(this._bootSync(options)));
36995 return this._bootPromise;
36996 },
36997
36998 /**
36999 Unfortunately, a lot of existing code assumes booting an instance is
37000 synchronous – specifically, a lot of tests assume the last call to
37001 `app.advanceReadiness()` or `app.reset()` will result in a new instance
37002 being fully-booted when the current runloop completes.
37003 We would like new code (like the `visit` API) to stop making this
37004 assumption, so we created the asynchronous version above that returns a
37005 promise. But until we have migrated all the code, we would have to expose
37006 this method for use *internally* in places where we need to boot an instance
37007 synchronously.
37008 @private
37009 */
37010 _bootSync(options) {
37011 if (this._booted) {
37012 return this;
37013 }
37014
37015 (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)));
37016 this.cloneParentDependencies();
37017 this.setupRegistry(options);
37018 this.base.runInstanceInitializers(this);
37019 this._booted = true;
37020 return this;
37021 },
37022
37023 setupRegistry(options = this.__container__.lookup('-environment:main')) {
37024 this.constructor.setupRegistry(this.__registry__, options);
37025 },
37026
37027 /**
37028 Unregister a factory.
37029 Overrides `RegistryProxy#unregister` in order to clear any cached instances
37030 of the unregistered factory.
37031 @public
37032 @method unregister
37033 @param {String} fullName
37034 */
37035 unregister(fullName) {
37036 this.__container__.reset(fullName);
37037
37038 this._super(...arguments);
37039 },
37040
37041 /**
37042 Build a new `EngineInstance` that's a child of this instance.
37043 Engines must be registered by name with their parent engine
37044 (or application).
37045 @private
37046 @method buildChildEngineInstance
37047 @param name {String} the registered name of the engine.
37048 @param options {Object} options provided to the engine instance.
37049 @return {EngineInstance,Error}
37050 */
37051 buildChildEngineInstance(name, options = {}) {
37052 var Engine = this.lookup(`engine:${name}`);
37053
37054 if (!Engine) {
37055 throw new _error.default(`You attempted to mount the engine '${name}', but it is not registered with its parent.`);
37056 }
37057
37058 var engineInstance = Engine.buildInstance(options);
37059 (0, _engineParent.setEngineParent)(engineInstance, this);
37060 return engineInstance;
37061 },
37062
37063 /**
37064 Clone dependencies shared between an engine instance and its parent.
37065 @private
37066 @method cloneParentDependencies
37067 */
37068 cloneParentDependencies() {
37069 var parent = (0, _engineParent.getEngineParent)(this);
37070 var registrations = ['route:basic', 'service:-routing'];
37071 registrations.forEach(key => this.register(key, parent.resolveRegistration(key)));
37072 var env = parent.lookup('-environment:main');
37073 this.register('-environment:main', env, {
37074 instantiate: false
37075 });
37076 var singletons = ['router:main', (0, _container.privatize)`-bucket-cache:main`, '-view-registry:main', `renderer:-${env.isInteractive ? 'dom' : 'inert'}`, 'service:-document'];
37077
37078 if (env.isInteractive) {
37079 singletons.push('event_dispatcher:main');
37080 }
37081
37082 singletons.forEach(key => this.register(key, parent.lookup(key), {
37083 instantiate: false
37084 }));
37085 this.inject('view', '_environment', '-environment:main');
37086 this.inject('route', '_environment', '-environment:main');
37087 }
37088
37089 });
37090
37091 EngineInstance.reopenClass({
37092 /**
37093 @private
37094 @method setupRegistry
37095 @param {Registry} registry
37096 @param {BootOptions} options
37097 */
37098 setupRegistry(registry, options) {
37099 // when no options/environment is present, do nothing
37100 if (!options) {
37101 return;
37102 }
37103
37104 registry.injection('view', '_environment', '-environment:main');
37105 registry.injection('route', '_environment', '-environment:main');
37106
37107 if (options.isInteractive) {
37108 registry.injection('view', 'renderer', 'renderer:-dom');
37109 registry.injection('component', 'renderer', 'renderer:-dom');
37110 } else {
37111 registry.injection('view', 'renderer', 'renderer:-inert');
37112 registry.injection('component', 'renderer', 'renderer:-inert');
37113 }
37114 }
37115
37116 });
37117 var _default = EngineInstance;
37118 _exports.default = _default;
37119});
37120define("@ember/engine/lib/engine-parent", ["exports", "@ember/-internals/utils"], function (_exports, _utils) {
37121 "use strict";
37122
37123 Object.defineProperty(_exports, "__esModule", {
37124 value: true
37125 });
37126 _exports.getEngineParent = getEngineParent;
37127 _exports.setEngineParent = setEngineParent;
37128
37129 /**
37130 @module @ember/engine
37131 */
37132 var ENGINE_PARENT = (0, _utils.symbol)('ENGINE_PARENT');
37133 /**
37134 `getEngineParent` retrieves an engine instance's parent instance.
37135
37136 @method getEngineParent
37137 @param {EngineInstance} engine An engine instance.
37138 @return {EngineInstance} The parent engine instance.
37139 @for @ember/engine
37140 @static
37141 @private
37142 */
37143
37144 function getEngineParent(engine) {
37145 return engine[ENGINE_PARENT];
37146 }
37147 /**
37148 `setEngineParent` sets an engine instance's parent instance.
37149
37150 @method setEngineParent
37151 @param {EngineInstance} engine An engine instance.
37152 @param {EngineInstance} parent The parent engine instance.
37153 @private
37154 */
37155
37156
37157 function setEngineParent(engine, parent) {
37158 engine[ENGINE_PARENT] = parent;
37159 }
37160});
37161define("@ember/error/index", ["exports"], function (_exports) {
37162 "use strict";
37163
37164 Object.defineProperty(_exports, "__esModule", {
37165 value: true
37166 });
37167 _exports.default = void 0;
37168
37169 /**
37170 @module @ember/error
37171 */
37172
37173 /**
37174 The JavaScript Error object used by Ember.assert.
37175
37176 @class Error
37177 @namespace Ember
37178 @extends Error
37179 @constructor
37180 @public
37181 */
37182 var _default = Error;
37183 _exports.default = _default;
37184});
37185define("@ember/instrumentation/index", ["exports", "@ember/-internals/environment"], function (_exports, _environment) {
37186 "use strict";
37187
37188 Object.defineProperty(_exports, "__esModule", {
37189 value: true
37190 });
37191 _exports.instrument = instrument;
37192 _exports._instrumentStart = _instrumentStart;
37193 _exports.subscribe = subscribe;
37194 _exports.unsubscribe = unsubscribe;
37195 _exports.reset = reset;
37196 _exports.flaggedInstrument = _exports.subscribers = void 0;
37197
37198 /* eslint no-console:off */
37199
37200 /* global console */
37201
37202 /**
37203 @module @ember/instrumentation
37204 @private
37205 */
37206
37207 /**
37208 The purpose of the Ember Instrumentation module is
37209 to provide efficient, general-purpose instrumentation
37210 for Ember.
37211
37212 Subscribe to a listener by using `subscribe`:
37213
37214 ```javascript
37215 import { subscribe } from '@ember/instrumentation';
37216
37217 subscribe("render", {
37218 before(name, timestamp, payload) {
37219
37220 },
37221
37222 after(name, timestamp, payload) {
37223
37224 }
37225 });
37226 ```
37227
37228 If you return a value from the `before` callback, that same
37229 value will be passed as a fourth parameter to the `after`
37230 callback.
37231
37232 Instrument a block of code by using `instrument`:
37233
37234 ```javascript
37235 import { instrument } from '@ember/instrumentation';
37236
37237 instrument("render.handlebars", payload, function() {
37238 // rendering logic
37239 }, binding);
37240 ```
37241
37242 Event names passed to `instrument` are namespaced
37243 by periods, from more general to more specific. Subscribers
37244 can listen for events by whatever level of granularity they
37245 are interested in.
37246
37247 In the above example, the event is `render.handlebars`,
37248 and the subscriber listened for all events beginning with
37249 `render`. It would receive callbacks for events named
37250 `render`, `render.handlebars`, `render.container`, or
37251 even `render.handlebars.layout`.
37252
37253 @class Instrumentation
37254 @static
37255 @private
37256 */
37257 var subscribers = [];
37258 _exports.subscribers = subscribers;
37259 var cache = {};
37260
37261 function populateListeners(name) {
37262 var listeners = [];
37263 var subscriber;
37264
37265 for (var i = 0; i < subscribers.length; i++) {
37266 subscriber = subscribers[i];
37267
37268 if (subscriber.regex.test(name)) {
37269 listeners.push(subscriber.object);
37270 }
37271 }
37272
37273 cache[name] = listeners;
37274 return listeners;
37275 }
37276
37277 var time = (() => {
37278 var perf = 'undefined' !== typeof window ? window.performance || {} : {};
37279 var fn = perf.now || perf.mozNow || perf.webkitNow || perf.msNow || perf.oNow;
37280 return fn ? fn.bind(perf) : Date.now;
37281 })();
37282
37283 function isCallback(value) {
37284 return typeof value === 'function';
37285 }
37286
37287 function instrument(name, p1, p2, p3) {
37288 var _payload;
37289
37290 var callback;
37291 var binding;
37292
37293 if (arguments.length <= 3 && isCallback(p1)) {
37294 callback = p1;
37295 binding = p2;
37296 } else {
37297 _payload = p1;
37298 callback = p2;
37299 binding = p3;
37300 } // fast path
37301
37302
37303 if (subscribers.length === 0) {
37304 return callback.call(binding);
37305 } // avoid allocating the payload in fast path
37306
37307
37308 var payload = _payload || {};
37309
37310 var finalizer = _instrumentStart(name, () => payload);
37311
37312 if (finalizer === NOOP) {
37313 return callback.call(binding);
37314 } else {
37315 return withFinalizer(callback, finalizer, payload, binding);
37316 }
37317 }
37318
37319 var flaggedInstrument;
37320 _exports.flaggedInstrument = flaggedInstrument;
37321
37322 if (false
37323 /* EMBER_IMPROVED_INSTRUMENTATION */
37324 ) {
37325 _exports.flaggedInstrument = flaggedInstrument = instrument;
37326 } else {
37327 _exports.flaggedInstrument = flaggedInstrument = function instrument(_name, _payload, callback) {
37328 return callback();
37329 };
37330 }
37331
37332 function withFinalizer(callback, finalizer, payload, binding) {
37333 try {
37334 return callback.call(binding);
37335 } catch (e) {
37336 payload.exception = e;
37337 throw e;
37338 } finally {
37339 finalizer();
37340 }
37341 }
37342
37343 function NOOP() {}
37344
37345 function _instrumentStart(name, payloadFunc, payloadArg) {
37346 if (subscribers.length === 0) {
37347 return NOOP;
37348 }
37349
37350 var listeners = cache[name];
37351
37352 if (!listeners) {
37353 listeners = populateListeners(name);
37354 }
37355
37356 if (listeners.length === 0) {
37357 return NOOP;
37358 }
37359
37360 var payload = payloadFunc(payloadArg);
37361 var STRUCTURED_PROFILE = _environment.ENV.STRUCTURED_PROFILE;
37362 var timeName;
37363
37364 if (STRUCTURED_PROFILE) {
37365 timeName = `${name}: ${payload.object}`;
37366 console.time(timeName);
37367 }
37368
37369 var beforeValues = [];
37370 var timestamp = time();
37371
37372 for (var i = 0; i < listeners.length; i++) {
37373 var listener = listeners[i];
37374 beforeValues.push(listener.before(name, timestamp, payload));
37375 }
37376
37377 return function _instrumentEnd() {
37378 var timestamp = time();
37379
37380 for (var _i = 0; _i < listeners.length; _i++) {
37381 var _listener = listeners[_i];
37382
37383 if (typeof _listener.after === 'function') {
37384 _listener.after(name, timestamp, payload, beforeValues[_i]);
37385 }
37386 }
37387
37388 if (STRUCTURED_PROFILE) {
37389 console.timeEnd(timeName);
37390 }
37391 };
37392 }
37393 /**
37394 Subscribes to a particular event or instrumented block of code.
37395
37396 @method subscribe
37397 @for @ember/instrumentation
37398 @static
37399
37400 @param {String} [pattern] Namespaced event name.
37401 @param {Object} [object] Before and After hooks.
37402
37403 @return {Subscriber}
37404 @private
37405 */
37406
37407
37408 function subscribe(pattern, object) {
37409 var paths = pattern.split('.');
37410 var path;
37411 var regexes = [];
37412
37413 for (var i = 0; i < paths.length; i++) {
37414 path = paths[i];
37415
37416 if (path === '*') {
37417 regexes.push('[^\\.]*');
37418 } else {
37419 regexes.push(path);
37420 }
37421 }
37422
37423 var regex = regexes.join('\\.');
37424 regex = `${regex}(\\..*)?`;
37425 var subscriber = {
37426 pattern,
37427 regex: new RegExp(`^${regex}$`),
37428 object
37429 };
37430 subscribers.push(subscriber);
37431 cache = {};
37432 return subscriber;
37433 }
37434 /**
37435 Unsubscribes from a particular event or instrumented block of code.
37436
37437 @method unsubscribe
37438 @for @ember/instrumentation
37439 @static
37440
37441 @param {Object} [subscriber]
37442 @private
37443 */
37444
37445
37446 function unsubscribe(subscriber) {
37447 var index = 0;
37448
37449 for (var i = 0; i < subscribers.length; i++) {
37450 if (subscribers[i] === subscriber) {
37451 index = i;
37452 }
37453 }
37454
37455 subscribers.splice(index, 1);
37456 cache = {};
37457 }
37458 /**
37459 Resets `Instrumentation` by flushing list of subscribers.
37460
37461 @method reset
37462 @for @ember/instrumentation
37463 @static
37464 @private
37465 */
37466
37467
37468 function reset() {
37469 subscribers.length = 0;
37470 cache = {};
37471 }
37472});
37473define("@ember/modifier/index", ["exports", "@ember/-internals/glimmer"], function (_exports, _glimmer) {
37474 "use strict";
37475
37476 Object.defineProperty(_exports, "__esModule", {
37477 value: true
37478 });
37479 Object.defineProperty(_exports, "setModifierManager", {
37480 enumerable: true,
37481 get: function () {
37482 return _glimmer.setModifierManager;
37483 }
37484 });
37485 Object.defineProperty(_exports, "capabilties", {
37486 enumerable: true,
37487 get: function () {
37488 return _glimmer.modifierCapabilities;
37489 }
37490 });
37491});
37492define("@ember/object/compat", ["exports", "@ember/-internals/metal", "@ember/debug", "@glimmer/validator"], function (_exports, _metal, _debug, _validator) {
37493 "use strict";
37494
37495 Object.defineProperty(_exports, "__esModule", {
37496 value: true
37497 });
37498 _exports.dependentKeyCompat = dependentKeyCompat;
37499
37500 var wrapGetterSetter = function (target, key, desc) {
37501 var {
37502 get: originalGet
37503 } = desc;
37504 (true && !((0, _metal.descriptorForProperty)(target, key) === undefined) && (0, _debug.assert)('You attempted to use @dependentKeyCompat on a property that already has been decorated with either @computed or @tracked. @dependentKeyCompat is only necessary for native getters that are not decorated with @computed.', (0, _metal.descriptorForProperty)(target, key) === undefined));
37505
37506 if (originalGet !== undefined) {
37507 desc.get = function () {
37508 var propertyTag = (0, _validator.tagFor)(this, key);
37509 var ret;
37510 var tag = (0, _validator.track)(() => {
37511 ret = originalGet.call(this);
37512 });
37513 (0, _validator.updateTag)(propertyTag, tag);
37514 (0, _validator.consumeTag)(tag);
37515 return ret;
37516 };
37517 }
37518
37519 return desc;
37520 };
37521
37522 function dependentKeyCompat(target, key, desc) {
37523 if (!(0, _metal.isElementDescriptor)([target, key, desc])) {
37524 desc = target;
37525
37526 var decorator = function (target, key, _desc, _meta, isClassicDecorator) {
37527 (true && !(isClassicDecorator) && (0, _debug.assert)('The @dependentKeyCompat decorator may only be passed a method when used in classic classes. You should decorate getters/setters directly in native classes', isClassicDecorator));
37528 (true && !(desc !== null && typeof desc === 'object' && (typeof desc.get === 'function' || typeof desc.set === 'function')) && (0, _debug.assert)('The dependentKeyCompat() decorator must be passed a getter or setter when used in classic classes', desc !== null && typeof desc === 'object' && (typeof desc.get === 'function' || typeof desc.set === 'function')));
37529 return wrapGetterSetter(target, key, desc);
37530 };
37531
37532 (0, _metal.setClassicDecorator)(decorator);
37533 return decorator;
37534 }
37535
37536 (true && !(desc !== null && typeof desc.get === 'function' || typeof desc.set === 'function') && (0, _debug.assert)('The @dependentKeyCompat decorator must be applied to getters/setters when used in native classes', desc !== null && typeof desc.get === 'function' || typeof desc.set === 'function'));
37537 return wrapGetterSetter(target, key, desc);
37538 }
37539
37540 (0, _metal.setClassicDecorator)(dependentKeyCompat);
37541});
37542define("@ember/object/computed", ["exports", "@ember/object/lib/computed/computed_macros", "@ember/object/lib/computed/reduce_computed_macros"], function (_exports, _computed_macros, _reduce_computed_macros) {
37543 "use strict";
37544
37545 Object.defineProperty(_exports, "__esModule", {
37546 value: true
37547 });
37548 Object.defineProperty(_exports, "empty", {
37549 enumerable: true,
37550 get: function () {
37551 return _computed_macros.empty;
37552 }
37553 });
37554 Object.defineProperty(_exports, "notEmpty", {
37555 enumerable: true,
37556 get: function () {
37557 return _computed_macros.notEmpty;
37558 }
37559 });
37560 Object.defineProperty(_exports, "none", {
37561 enumerable: true,
37562 get: function () {
37563 return _computed_macros.none;
37564 }
37565 });
37566 Object.defineProperty(_exports, "not", {
37567 enumerable: true,
37568 get: function () {
37569 return _computed_macros.not;
37570 }
37571 });
37572 Object.defineProperty(_exports, "bool", {
37573 enumerable: true,
37574 get: function () {
37575 return _computed_macros.bool;
37576 }
37577 });
37578 Object.defineProperty(_exports, "match", {
37579 enumerable: true,
37580 get: function () {
37581 return _computed_macros.match;
37582 }
37583 });
37584 Object.defineProperty(_exports, "equal", {
37585 enumerable: true,
37586 get: function () {
37587 return _computed_macros.equal;
37588 }
37589 });
37590 Object.defineProperty(_exports, "gt", {
37591 enumerable: true,
37592 get: function () {
37593 return _computed_macros.gt;
37594 }
37595 });
37596 Object.defineProperty(_exports, "gte", {
37597 enumerable: true,
37598 get: function () {
37599 return _computed_macros.gte;
37600 }
37601 });
37602 Object.defineProperty(_exports, "lt", {
37603 enumerable: true,
37604 get: function () {
37605 return _computed_macros.lt;
37606 }
37607 });
37608 Object.defineProperty(_exports, "lte", {
37609 enumerable: true,
37610 get: function () {
37611 return _computed_macros.lte;
37612 }
37613 });
37614 Object.defineProperty(_exports, "oneWay", {
37615 enumerable: true,
37616 get: function () {
37617 return _computed_macros.oneWay;
37618 }
37619 });
37620 Object.defineProperty(_exports, "readOnly", {
37621 enumerable: true,
37622 get: function () {
37623 return _computed_macros.readOnly;
37624 }
37625 });
37626 Object.defineProperty(_exports, "deprecatingAlias", {
37627 enumerable: true,
37628 get: function () {
37629 return _computed_macros.deprecatingAlias;
37630 }
37631 });
37632 Object.defineProperty(_exports, "and", {
37633 enumerable: true,
37634 get: function () {
37635 return _computed_macros.and;
37636 }
37637 });
37638 Object.defineProperty(_exports, "or", {
37639 enumerable: true,
37640 get: function () {
37641 return _computed_macros.or;
37642 }
37643 });
37644 Object.defineProperty(_exports, "sum", {
37645 enumerable: true,
37646 get: function () {
37647 return _reduce_computed_macros.sum;
37648 }
37649 });
37650 Object.defineProperty(_exports, "min", {
37651 enumerable: true,
37652 get: function () {
37653 return _reduce_computed_macros.min;
37654 }
37655 });
37656 Object.defineProperty(_exports, "max", {
37657 enumerable: true,
37658 get: function () {
37659 return _reduce_computed_macros.max;
37660 }
37661 });
37662 Object.defineProperty(_exports, "map", {
37663 enumerable: true,
37664 get: function () {
37665 return _reduce_computed_macros.map;
37666 }
37667 });
37668 Object.defineProperty(_exports, "sort", {
37669 enumerable: true,
37670 get: function () {
37671 return _reduce_computed_macros.sort;
37672 }
37673 });
37674 Object.defineProperty(_exports, "setDiff", {
37675 enumerable: true,
37676 get: function () {
37677 return _reduce_computed_macros.setDiff;
37678 }
37679 });
37680 Object.defineProperty(_exports, "mapBy", {
37681 enumerable: true,
37682 get: function () {
37683 return _reduce_computed_macros.mapBy;
37684 }
37685 });
37686 Object.defineProperty(_exports, "filter", {
37687 enumerable: true,
37688 get: function () {
37689 return _reduce_computed_macros.filter;
37690 }
37691 });
37692 Object.defineProperty(_exports, "filterBy", {
37693 enumerable: true,
37694 get: function () {
37695 return _reduce_computed_macros.filterBy;
37696 }
37697 });
37698 Object.defineProperty(_exports, "uniq", {
37699 enumerable: true,
37700 get: function () {
37701 return _reduce_computed_macros.uniq;
37702 }
37703 });
37704 Object.defineProperty(_exports, "uniqBy", {
37705 enumerable: true,
37706 get: function () {
37707 return _reduce_computed_macros.uniqBy;
37708 }
37709 });
37710 Object.defineProperty(_exports, "union", {
37711 enumerable: true,
37712 get: function () {
37713 return _reduce_computed_macros.union;
37714 }
37715 });
37716 Object.defineProperty(_exports, "intersect", {
37717 enumerable: true,
37718 get: function () {
37719 return _reduce_computed_macros.intersect;
37720 }
37721 });
37722 Object.defineProperty(_exports, "collect", {
37723 enumerable: true,
37724 get: function () {
37725 return _reduce_computed_macros.collect;
37726 }
37727 });
37728});
37729define("@ember/object/index", ["exports", "@ember/debug", "@ember/polyfills", "@ember/-internals/metal"], function (_exports, _debug, _polyfills, _metal) {
37730 "use strict";
37731
37732 Object.defineProperty(_exports, "__esModule", {
37733 value: true
37734 });
37735 _exports.action = action;
37736
37737 /**
37738 Decorator that turns the target function into an Action which can be accessed
37739 directly by reference.
37740
37741 ```js
37742 import Component from '@ember/component';
37743 import { action, set } from '@ember/object';
37744
37745 export default class Tooltip extends Component {
37746 @action
37747 toggleShowing() {
37748 set(this, 'isShowing', !this.isShowing);
37749 }
37750 }
37751 ```
37752 ```hbs
37753 <!-- template.hbs -->
37754 <button {{action this.toggleShowing}}>Show tooltip</button>
37755
37756 {{#if isShowing}}
37757 <div class="tooltip">
37758 I'm a tooltip!
37759 </div>
37760 {{/if}}
37761 ```
37762
37763 Decorated actions also interop with the string style template actions:
37764
37765 ```hbs
37766 <!-- template.hbs -->
37767 <button {{action "toggleShowing"}}>Show tooltip</button>
37768
37769 {{#if isShowing}}
37770 <div class="tooltip">
37771 I'm a tooltip!
37772 </div>
37773 {{/if}}
37774 ```
37775
37776 It also binds the function directly to the instance, so it can be used in any
37777 context and will correctly refer to the class it came from:
37778
37779 ```hbs
37780 <!-- template.hbs -->
37781 <button
37782 {{did-insert this.toggleShowing}}
37783 {{on "click" this.toggleShowing}}
37784 >
37785 Show tooltip
37786 </button>
37787
37788 {{#if isShowing}}
37789 <div class="tooltip">
37790 I'm a tooltip!
37791 </div>
37792 {{/if}}
37793 ```
37794
37795 This can also be used in JavaScript code directly:
37796
37797 ```js
37798 import Component from '@ember/component';
37799 import { action, set } from '@ember/object';
37800
37801 export default class Tooltip extends Component {
37802 constructor() {
37803 super(...arguments);
37804
37805 // this.toggleShowing is still bound correctly when added to
37806 // the event listener
37807 document.addEventListener('click', this.toggleShowing);
37808 }
37809
37810 @action
37811 toggleShowing() {
37812 set(this, 'isShowing', !this.isShowing);
37813 }
37814 }
37815 ```
37816
37817 This is considered best practice, since it means that methods will be bound
37818 correctly no matter where they are used. By contrast, the `{{action}}` helper
37819 and modifier can also be used to bind context, but it will be required for
37820 every usage of the method:
37821
37822 ```hbs
37823 <!-- template.hbs -->
37824 <button
37825 {{did-insert (action this.toggleShowing)}}
37826 {{on "click" (action this.toggleShowing)}}
37827 >
37828 Show tooltip
37829 </button>
37830
37831 {{#if isShowing}}
37832 <div class="tooltip">
37833 I'm a tooltip!
37834 </div>
37835 {{/if}}
37836 ```
37837
37838 They also do not have equivalents in JavaScript directly, so they cannot be
37839 used for other situations where binding would be useful.
37840
37841 @public
37842 @method action
37843 @for @ember/object
37844 @static
37845 @param {Function|undefined} callback The function to turn into an action,
37846 when used in classic classes
37847 @return {PropertyDecorator} property decorator instance
37848 */
37849 var BINDINGS_MAP = new WeakMap();
37850
37851 function setupAction(target, key, actionFn) {
37852 if (target.constructor !== undefined && typeof target.constructor.proto === 'function') {
37853 target.constructor.proto();
37854 }
37855
37856 if (!Object.prototype.hasOwnProperty.call(target, 'actions')) {
37857 var parentActions = target.actions; // we need to assign because of the way mixins copy actions down when inheriting
37858
37859 target.actions = parentActions ? (0, _polyfills.assign)({}, parentActions) : {};
37860 }
37861
37862 target.actions[key] = actionFn;
37863 return {
37864 get() {
37865 var bindings = BINDINGS_MAP.get(this);
37866
37867 if (bindings === undefined) {
37868 bindings = new Map();
37869 BINDINGS_MAP.set(this, bindings);
37870 }
37871
37872 var fn = bindings.get(actionFn);
37873
37874 if (fn === undefined) {
37875 fn = actionFn.bind(this);
37876 bindings.set(actionFn, fn);
37877 }
37878
37879 return fn;
37880 }
37881
37882 };
37883 }
37884
37885 function action(target, key, desc) {
37886 var actionFn;
37887
37888 if (!(0, _metal.isElementDescriptor)([target, key, desc])) {
37889 actionFn = target;
37890
37891 var decorator = function (target, key, desc, meta, isClassicDecorator) {
37892 (true && !(isClassicDecorator) && (0, _debug.assert)('The @action decorator may only be passed a method when used in classic classes. You should decorate methods directly in native classes', isClassicDecorator));
37893 (true && !(typeof actionFn === 'function') && (0, _debug.assert)('The action() decorator must be passed a method when used in classic classes', typeof actionFn === 'function'));
37894 return setupAction(target, key, actionFn);
37895 };
37896
37897 (0, _metal.setClassicDecorator)(decorator);
37898 return decorator;
37899 }
37900
37901 actionFn = desc.value;
37902 (true && !(typeof actionFn === 'function') && (0, _debug.assert)('The @action decorator must be applied to methods when used in native classes', typeof actionFn === 'function'));
37903 return setupAction(target, key, actionFn);
37904 }
37905
37906 (0, _metal.setClassicDecorator)(action);
37907});
37908define("@ember/object/lib/computed/computed_macros", ["exports", "@ember/-internals/metal", "@ember/debug"], function (_exports, _metal, _debug) {
37909 "use strict";
37910
37911 Object.defineProperty(_exports, "__esModule", {
37912 value: true
37913 });
37914 _exports.empty = empty;
37915 _exports.notEmpty = notEmpty;
37916 _exports.none = none;
37917 _exports.not = not;
37918 _exports.bool = bool;
37919 _exports.match = match;
37920 _exports.equal = equal;
37921 _exports.gt = gt;
37922 _exports.gte = gte;
37923 _exports.lt = lt;
37924 _exports.lte = lte;
37925 _exports.oneWay = oneWay;
37926 _exports.readOnly = readOnly;
37927 _exports.deprecatingAlias = deprecatingAlias;
37928 _exports.or = _exports.and = void 0;
37929
37930 /**
37931 @module @ember/object
37932 */
37933 function expandPropertiesToArray(predicateName, properties) {
37934 var expandedProperties = [];
37935
37936 function extractProperty(entry) {
37937 expandedProperties.push(entry);
37938 }
37939
37940 for (var i = 0; i < properties.length; i++) {
37941 var property = properties[i];
37942 (true && !(property.indexOf(' ') < 0) && (0, _debug.assert)(`Dependent keys passed to computed.${predicateName}() can't have spaces.`, property.indexOf(' ') < 0));
37943 (0, _metal.expandProperties)(property, extractProperty);
37944 }
37945
37946 return expandedProperties;
37947 }
37948
37949 function generateComputedWithPredicate(name, predicate) {
37950 return (...properties) => {
37951 (true && !(!(0, _metal.isElementDescriptor)(properties)) && (0, _debug.assert)(`You attempted to use @${name} as a decorator directly, but it requires at least one dependent key parameter`, !(0, _metal.isElementDescriptor)(properties)));
37952 var dependentKeys = expandPropertiesToArray(name, properties);
37953 var computedFunc = (0, _metal.computed)(...dependentKeys, function () {
37954 var lastIdx = dependentKeys.length - 1;
37955
37956 for (var i = 0; i < lastIdx; i++) {
37957 var value = (0, _metal.get)(this, dependentKeys[i]);
37958
37959 if (!predicate(value)) {
37960 return value;
37961 }
37962 }
37963
37964 return (0, _metal.get)(this, dependentKeys[lastIdx]);
37965 });
37966 return computedFunc;
37967 };
37968 }
37969 /**
37970 A computed property macro that returns true if the value of the dependent
37971 property is null, an empty string, empty array, or empty function.
37972
37973 Example:
37974
37975 ```javascript
37976 import { set } from '@ember/object';
37977 import { empty } from '@ember/object/computed';
37978
37979 class ToDoList {
37980 constructor(todos) {
37981 set(this, 'todos', todos);
37982 }
37983
37984 @empty('todos') isDone;
37985 }
37986
37987 let todoList = new ToDoList(
37988 ['Unit Test', 'Documentation', 'Release']
37989 );
37990
37991 todoList.isDone; // false
37992 set(todoList, 'todos', []);
37993 todoList.isDone; // true
37994 ```
37995
37996 Classic Class Example:
37997
37998 ```javascript
37999 import EmberObject, { set } from '@ember/object';
38000 import { empty } from '@ember/object/computed';
38001
38002 let ToDoList = EmberObject.extend({
38003 isDone: empty('todos')
38004 });
38005
38006 let todoList = ToDoList.create({
38007 todos: ['Unit Test', 'Documentation', 'Release']
38008 });
38009
38010 todoList.isDone; // false
38011 set(todoList, 'todos', []);
38012 todoList.isDone; // true
38013 ```
38014
38015 @since 1.6.0
38016 @method empty
38017 @static
38018 @for @ember/object/computed
38019 @param {String} dependentKey
38020 @return {ComputedProperty} computed property which returns true if the value
38021 of the dependent property is null, an empty string, empty array, or empty
38022 function and false if the underlying value is not empty.
38023
38024 @public
38025 */
38026
38027
38028 function empty(dependentKey) {
38029 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @empty as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
38030 return (0, _metal.computed)(`${dependentKey}.length`, function () {
38031 return (0, _metal.isEmpty)((0, _metal.get)(this, dependentKey));
38032 });
38033 }
38034 /**
38035 A computed property that returns true if the value of the dependent property
38036 is NOT null, an empty string, empty array, or empty function.
38037
38038 Example:
38039
38040 ```javascript
38041 import { set } from '@ember/object';
38042 import { notEmpty } from '@ember/object/computed';
38043
38044 class Hamster {
38045 constructor(backpack) {
38046 set(this, 'backpack', backpack);
38047 }
38048
38049 @notEmpty('backpack') hasStuff
38050 }
38051
38052 let hamster = new Hamster(
38053 ['Food', 'Sleeping Bag', 'Tent']
38054 );
38055
38056 hamster.hasStuff; // true
38057 set(hamster, 'backpack', []);
38058 hamster.hasStuff; // false
38059 ```
38060
38061 Classic Class Example:
38062
38063 ```javascript
38064 import EmberObject, { set } from '@ember/object';
38065 import { notEmpty } from '@ember/object/computed';
38066
38067 let Hamster = EmberObject.extend({
38068 hasStuff: notEmpty('backpack')
38069 });
38070
38071 let hamster = Hamster.create({
38072 backpack: ['Food', 'Sleeping Bag', 'Tent']
38073 });
38074
38075 hamster.hasStuff; // true
38076 set(hamster, 'backpack', []);
38077 hamster.hasStuff; // false
38078 ```
38079
38080 @method notEmpty
38081 @static
38082 @for @ember/object/computed
38083 @param {String} dependentKey
38084 @return {ComputedProperty} computed property which returns true if original
38085 value for property is not empty.
38086 @public
38087 */
38088
38089
38090 function notEmpty(dependentKey) {
38091 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @notEmpty as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
38092 return (0, _metal.computed)(`${dependentKey}.length`, function () {
38093 return !(0, _metal.isEmpty)((0, _metal.get)(this, dependentKey));
38094 });
38095 }
38096 /**
38097 A computed property that returns true if the value of the dependent property
38098 is null or undefined. This avoids errors from JSLint complaining about use of
38099 ==, which can be technically confusing.
38100
38101 ```javascript
38102 import { set } from '@ember/object';
38103 import { none } from '@ember/object/computed';
38104
38105 class Hamster {
38106 @none('food') isHungry;
38107 }
38108
38109 let hamster = new Hamster();
38110
38111 hamster.isHungry; // true
38112
38113 set(hamster, 'food', 'Banana');
38114 hamster.isHungry; // false
38115
38116 set(hamster, 'food', null);
38117 hamster.isHungry; // true
38118 ```
38119
38120 Classic Class Example:
38121
38122 ```javascript
38123 import EmberObject, { set } from '@ember/object';
38124 import { none } from '@ember/object/computed';
38125
38126 let Hamster = EmberObject.extend({
38127 isHungry: none('food')
38128 });
38129
38130 let hamster = Hamster.create();
38131
38132 hamster.isHungry; // true
38133
38134 set(hamster, 'food', 'Banana');
38135 hamster.isHungry; // false
38136
38137 set(hamster, 'food', null);
38138 hamster.isHungry; // true
38139 ```
38140
38141 @method none
38142 @static
38143 @for @ember/object/computed
38144 @param {String} dependentKey
38145 @return {ComputedProperty} computed property which returns true if original
38146 value for property is null or undefined.
38147 @public
38148 */
38149
38150
38151 function none(dependentKey) {
38152 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @none as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
38153 return (0, _metal.computed)(dependentKey, function () {
38154 return (0, _metal.isNone)((0, _metal.get)(this, dependentKey));
38155 });
38156 }
38157 /**
38158 A computed property that returns the inverse boolean value of the original
38159 value for the dependent property.
38160
38161 Example:
38162
38163 ```javascript
38164 import { set } from '@ember/object';
38165 import { not } from '@ember/object/computed';
38166
38167 class User {
38168 loggedIn = false;
38169
38170 @not('loggedIn') isAnonymous;
38171 }
38172
38173 let user = new User();
38174
38175 user.isAnonymous; // true
38176 set(user, 'loggedIn', true);
38177 user.isAnonymous; // false
38178 ```
38179
38180 Classic Class Example:
38181
38182 ```javascript
38183 import EmberObject, { set } from '@ember/object';
38184 import { not } from '@ember/object/computed';
38185
38186 let User = EmberObject.extend({
38187 loggedIn: false,
38188
38189 isAnonymous: not('loggedIn')
38190 });
38191
38192 let user = User.create();
38193
38194 user.isAnonymous; // true
38195 set(user, 'loggedIn', true);
38196 user.isAnonymous; // false
38197 ```
38198
38199 @method not
38200 @static
38201 @for @ember/object/computed
38202 @param {String} dependentKey
38203 @return {ComputedProperty} computed property which returns inverse of the
38204 original value for property
38205 @public
38206 */
38207
38208
38209 function not(dependentKey) {
38210 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @not as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
38211 return (0, _metal.computed)(dependentKey, function () {
38212 return !(0, _metal.get)(this, dependentKey);
38213 });
38214 }
38215 /**
38216 A computed property that converts the provided dependent property into a
38217 boolean value.
38218
38219 Example:
38220
38221 ```javascript
38222 import { set } from '@ember/object';
38223 import { bool } from '@ember/object/computed';
38224
38225
38226 class Hamster {
38227 @bool('numBananas') hasBananas
38228 }
38229
38230 let hamster = new Hamster();
38231
38232 hamster.hasBananas; // false
38233
38234 set(hamster, 'numBananas', 0);
38235 hamster.hasBananas; // false
38236
38237 set(hamster, 'numBananas', 1);
38238 hamster.hasBananas; // true
38239
38240 set(hamster, 'numBananas', null);
38241 hamster.hasBananas; // false
38242 ```
38243
38244 Classic Class Example:
38245
38246 ```javascript
38247 import EmberObject, { set } from '@ember/object';
38248 import { bool } from '@ember/object/computed';
38249
38250
38251 let Hamster = EmberObject.extend({
38252 hasBananas: bool('numBananas')
38253 });
38254
38255 let hamster = Hamster.create();
38256
38257 hamster.hasBananas; // false
38258
38259 set(hamster, 'numBananas', 0);
38260 hamster.hasBananas; // false
38261
38262 set(hamster, 'numBananas', 1);
38263 hamster.hasBananas; // true
38264
38265 set(hamster, 'numBananas', null);
38266 hamster.hasBananas; // false
38267 ```
38268
38269 @method bool
38270 @static
38271 @for @ember/object/computed
38272 @param {String} dependentKey
38273 @return {ComputedProperty} computed property which converts to boolean the
38274 original value for property
38275 @public
38276 */
38277
38278
38279 function bool(dependentKey) {
38280 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @bool as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
38281 return (0, _metal.computed)(dependentKey, function () {
38282 return Boolean((0, _metal.get)(this, dependentKey));
38283 });
38284 }
38285 /**
38286 A computed property which matches the original value for the dependent
38287 property against a given RegExp, returning `true` if the value matches the
38288 RegExp and `false` if it does not.
38289
38290 Example:
38291
38292 ```javascript
38293 import { set } from '@ember/object';
38294 import { match } from '@ember/object/computed';
38295
38296 class User {
38297 @match('email', /^.+@.+\..+$/) hasValidEmail;
38298 }
38299
38300 let user = new User();
38301
38302 user.hasValidEmail; // false
38303
38304 set(user, 'email', '');
38305 user.hasValidEmail; // false
38306
38307 set(user, 'email', 'ember_hamster@example.com');
38308 user.hasValidEmail; // true
38309 ```
38310
38311 Classic Class Example:
38312
38313 ```javascript
38314 import EmberObject, { set } from '@ember/object';
38315 import { match } from '@ember/object/computed';
38316
38317 let User = EmberObject.extend({
38318 hasValidEmail: match('email', /^.+@.+\..+$/)
38319 });
38320
38321 let user = User.create();
38322
38323 user.hasValidEmail; // false
38324
38325 set(user, 'email', '');
38326 user.hasValidEmail; // false
38327
38328 set(user, 'email', 'ember_hamster@example.com');
38329 user.hasValidEmail; // true
38330 ```
38331
38332 @method match
38333 @static
38334 @for @ember/object/computed
38335 @param {String} dependentKey
38336 @param {RegExp} regexp
38337 @return {ComputedProperty} computed property which match the original value
38338 for property against a given RegExp
38339 @public
38340 */
38341
38342
38343 function match(dependentKey, regexp) {
38344 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @match as a decorator directly, but it requires `dependentKey` and `regexp` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
38345 return (0, _metal.computed)(dependentKey, function () {
38346 var value = (0, _metal.get)(this, dependentKey);
38347 return regexp.test(value);
38348 });
38349 }
38350 /**
38351 A computed property that returns true if the provided dependent property is
38352 equal to the given value.
38353
38354 Example:
38355
38356 ```javascript
38357 import { set } from '@ember/object';
38358 import { equal } from '@ember/object/computed';
38359
38360 class Hamster {
38361 @equal('percentCarrotsEaten', 100) satisfied;
38362 }
38363
38364 let hamster = new Hamster();
38365
38366 hamster.satisfied; // false
38367
38368 set(hamster, 'percentCarrotsEaten', 100);
38369 hamster.satisfied; // true
38370
38371 set(hamster, 'percentCarrotsEaten', 50);
38372 hamster.satisfied; // false
38373 ```
38374
38375 Classic Class Example:
38376
38377 ```javascript
38378 import EmberObject, { set } from '@ember/object';
38379 import { equal } from '@ember/object/computed';
38380
38381 let Hamster = EmberObject.extend({
38382 satisfied: equal('percentCarrotsEaten', 100)
38383 });
38384
38385 let hamster = Hamster.create();
38386
38387 hamster.satisfied; // false
38388
38389 set(hamster, 'percentCarrotsEaten', 100);
38390 hamster.satisfied; // true
38391
38392 set(hamster, 'percentCarrotsEaten', 50);
38393 hamster.satisfied; // false
38394 ```
38395
38396 @method equal
38397 @static
38398 @for @ember/object/computed
38399 @param {String} dependentKey
38400 @param {String|Number|Object} value
38401 @return {ComputedProperty} computed property which returns true if the
38402 original value for property is equal to the given value.
38403 @public
38404 */
38405
38406
38407 function equal(dependentKey, value) {
38408 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @equal as a decorator directly, but it requires `dependentKey` and `value` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
38409 return (0, _metal.computed)(dependentKey, function () {
38410 return (0, _metal.get)(this, dependentKey) === value;
38411 });
38412 }
38413 /**
38414 A computed property that returns true if the provided dependent property is
38415 greater than the provided value.
38416
38417 Example:
38418
38419 ```javascript
38420 import { set } from '@ember/object';
38421 import { gt } from '@ember/object/computed';
38422
38423 class Hamster {
38424 @gt('numBananas', 10) hasTooManyBananas;
38425 }
38426
38427 let hamster = new Hamster();
38428
38429 hamster.hasTooManyBananas; // false
38430
38431 set(hamster, 'numBananas', 3);
38432 hamster.hasTooManyBananas; // false
38433
38434 set(hamster, 'numBananas', 11);
38435 hamster.hasTooManyBananas; // true
38436 ```
38437
38438 Classic Class Example:
38439
38440 ```javascript
38441 import EmberObject, { set } from '@ember/object';
38442 import { gt } from '@ember/object/computed';
38443
38444 let Hamster = EmberObject.extend({
38445 hasTooManyBananas: gt('numBananas', 10)
38446 });
38447
38448 let hamster = Hamster.create();
38449
38450 hamster.hasTooManyBananas; // false
38451
38452 set(hamster, 'numBananas', 3);
38453 hamster.hasTooManyBananas; // false
38454
38455 set(hamster, 'numBananas', 11);
38456 hamster.hasTooManyBananas; // true
38457 ```
38458
38459 @method gt
38460 @static
38461 @for @ember/object/computed
38462 @param {String} dependentKey
38463 @param {Number} value
38464 @return {ComputedProperty} computed property which returns true if the
38465 original value for property is greater than given value.
38466 @public
38467 */
38468
38469
38470 function gt(dependentKey, value) {
38471 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @gt as a decorator directly, but it requires `dependentKey` and `value` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
38472 return (0, _metal.computed)(dependentKey, function () {
38473 return (0, _metal.get)(this, dependentKey) > value;
38474 });
38475 }
38476 /**
38477 A computed property that returns true if the provided dependent property is
38478 greater than or equal to the provided value.
38479
38480 Example:
38481
38482 ```javascript
38483 import { set } from '@ember/object';
38484 import { gte } from '@ember/object/computed';
38485
38486 class Hamster {
38487 @gte('numBananas', 10) hasTooManyBananas;
38488 }
38489
38490 let hamster = new Hamster();
38491
38492 hamster.hasTooManyBananas; // false
38493
38494 set(hamster, 'numBananas', 3);
38495 hamster.hasTooManyBananas; // false
38496
38497 set(hamster, 'numBananas', 10);
38498 hamster.hasTooManyBananas; // true
38499 ```
38500
38501 Classic Class Example:
38502
38503 ```javascript
38504 import EmberObject, { set } from '@ember/object';
38505 import { gte } from '@ember/object/computed';
38506
38507 let Hamster = EmberObject.extend({
38508 hasTooManyBananas: gte('numBananas', 10)
38509 });
38510
38511 let hamster = Hamster.create();
38512
38513 hamster.hasTooManyBananas; // false
38514
38515 set(hamster, 'numBananas', 3);
38516 hamster.hasTooManyBananas; // false
38517
38518 set(hamster, 'numBananas', 10);
38519 hamster.hasTooManyBananas; // true
38520 ```
38521
38522 @method gte
38523 @static
38524 @for @ember/object/computed
38525 @param {String} dependentKey
38526 @param {Number} value
38527 @return {ComputedProperty} computed property which returns true if the
38528 original value for property is greater or equal then given value.
38529 @public
38530 */
38531
38532
38533 function gte(dependentKey, value) {
38534 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @gte as a decorator directly, but it requires `dependentKey` and `value` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
38535 return (0, _metal.computed)(dependentKey, function () {
38536 return (0, _metal.get)(this, dependentKey) >= value;
38537 });
38538 }
38539 /**
38540 A computed property that returns true if the provided dependent property is
38541 less than the provided value.
38542
38543 Example:
38544
38545 ```javascript
38546 import { set } from '@ember/object';
38547 import { lt } from '@ember/object/computed';
38548
38549 class Hamster {
38550 @lt('numBananas', 3) needsMoreBananas;
38551 }
38552
38553 let hamster = new Hamster();
38554
38555 hamster.needsMoreBananas; // true
38556
38557 set(hamster, 'numBananas', 3);
38558 hamster.needsMoreBananas; // false
38559
38560 set(hamster, 'numBananas', 2);
38561 hamster.needsMoreBananas; // true
38562 ```
38563
38564 Classic Class Example:
38565
38566 ```javascript
38567 import EmberObject, { set } from '@ember/object';
38568 import { lt } from '@ember/object/computed';
38569
38570 let Hamster = EmberObject.extend({
38571 needsMoreBananas: lt('numBananas', 3)
38572 });
38573
38574 let hamster = Hamster.create();
38575
38576 hamster.needsMoreBananas; // true
38577
38578 set(hamster, 'numBananas', 3);
38579 hamster.needsMoreBananas; // false
38580
38581 set(hamster, 'numBananas', 2);
38582 hamster.needsMoreBananas; // true
38583 ```
38584
38585 @method lt
38586 @static
38587 @for @ember/object/computed
38588 @param {String} dependentKey
38589 @param {Number} value
38590 @return {ComputedProperty} computed property which returns true if the
38591 original value for property is less then given value.
38592 @public
38593 */
38594
38595
38596 function lt(dependentKey, value) {
38597 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @lt as a decorator directly, but it requires `dependentKey` and `value` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
38598 return (0, _metal.computed)(dependentKey, function () {
38599 return (0, _metal.get)(this, dependentKey) < value;
38600 });
38601 }
38602 /**
38603 A computed property that returns true if the provided dependent property is
38604 less than or equal to the provided value.
38605
38606 Example:
38607
38608 ```javascript
38609 import { set } from '@ember/object';
38610 import { lte } from '@ember/object/computed';
38611
38612 class Hamster {
38613 @lte('numBananas', 3) needsMoreBananas;
38614 }
38615
38616 let hamster = new Hamster();
38617
38618 hamster.needsMoreBananas; // true
38619
38620 set(hamster, 'numBananas', 5);
38621 hamster.needsMoreBananas; // false
38622
38623 set(hamster, 'numBananas', 3);
38624 hamster.needsMoreBananas; // true
38625 ```
38626
38627 Classic Class Example:
38628
38629 ```javascript
38630 import EmberObject, { set } from '@ember/object';
38631 import { lte } from '@ember/object/computed';
38632
38633 let Hamster = EmberObject.extend({
38634 needsMoreBananas: lte('numBananas', 3)
38635 });
38636
38637 let hamster = Hamster.create();
38638
38639 hamster.needsMoreBananas; // true
38640
38641 set(hamster, 'numBananas', 5);
38642 hamster.needsMoreBananas; // false
38643
38644 set(hamster, 'numBananas', 3);
38645 hamster.needsMoreBananas; // true
38646 ```
38647
38648 @method lte
38649 @static
38650 @for @ember/object/computed
38651 @param {String} dependentKey
38652 @param {Number} value
38653 @return {ComputedProperty} computed property which returns true if the
38654 original value for property is less or equal than given value.
38655 @public
38656 */
38657
38658
38659 function lte(dependentKey, value) {
38660 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @lte as a decorator directly, but it requires `dependentKey` and `value` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
38661 return (0, _metal.computed)(dependentKey, function () {
38662 return (0, _metal.get)(this, dependentKey) <= value;
38663 });
38664 }
38665 /**
38666 A computed property that performs a logical `and` on the original values for
38667 the provided dependent properties.
38668
38669 You may pass in more than two properties and even use property brace
38670 expansion. The computed property will return the first falsy value or last
38671 truthy value just like JavaScript's `&&` operator.
38672
38673 Example:
38674
38675 ```javascript
38676 import { set } from '@ember/object';
38677 import { and } from '@ember/object/computed';
38678
38679 class Hamster {
38680 @and('hasTent', 'hasBackpack') readyForCamp;
38681 @and('hasWalkingStick', 'hasBackpack') readyForHike;
38682 }
38683
38684 let tomster = new Hamster();
38685
38686 tomster.readyForCamp; // false
38687
38688 set(tomster, 'hasTent', true);
38689 tomster.readyForCamp; // false
38690
38691 set(tomster, 'hasBackpack', true);
38692 tomster.readyForCamp; // true
38693
38694 set(tomster, 'hasBackpack', 'Yes');
38695 tomster.readyForCamp; // 'Yes'
38696
38697 set(tomster, 'hasWalkingStick', null);
38698 tomster.readyForHike; // null
38699 ```
38700
38701 Classic Class Example:
38702
38703 ```javascript
38704 import EmberObject, { set } from '@ember/object';
38705 import { and } from '@ember/object/computed';
38706
38707 let Hamster = EmberObject.extend({
38708 readyForCamp: and('hasTent', 'hasBackpack'),
38709 readyForHike: and('hasWalkingStick', 'hasBackpack')
38710 });
38711
38712 let tomster = Hamster.create();
38713
38714 tomster.readyForCamp; // false
38715
38716 set(tomster, 'hasTent', true);
38717 tomster.readyForCamp; // false
38718
38719 set(tomster, 'hasBackpack', true);
38720 tomster.readyForCamp; // true
38721
38722 set(tomster, 'hasBackpack', 'Yes');
38723 tomster.readyForCamp; // 'Yes'
38724
38725 set(tomster, 'hasWalkingStick', null);
38726 tomster.readyForHike; // null
38727 ```
38728
38729 @method and
38730 @static
38731 @for @ember/object/computed
38732 @param {String} dependentKey*
38733 @return {ComputedProperty} computed property which performs a logical `and` on
38734 the values of all the original values for properties.
38735 @public
38736 */
38737
38738
38739 var and = generateComputedWithPredicate('and', value => value);
38740 /**
38741 A computed property which performs a logical `or` on the original values for
38742 the provided dependent properties.
38743
38744 You may pass in more than two properties and even use property brace
38745 expansion. The computed property will return the first truthy value or last
38746 falsy value just like JavaScript's `||` operator.
38747
38748 Example:
38749
38750 ```javascript
38751 import { set } from '@ember/object';
38752 import { or } from '@ember/object/computed';
38753
38754 class Hamster {
38755 @or('hasJacket', 'hasUmbrella') readyForRain;
38756 @or('hasSunscreen', 'hasUmbrella') readyForBeach;
38757 }
38758
38759 let tomster = new Hamster();
38760
38761 tomster.readyForRain; // undefined
38762
38763 set(tomster, 'hasUmbrella', true);
38764 tomster.readyForRain; // true
38765
38766 set(tomster, 'hasJacket', 'Yes');
38767 tomster.readyForRain; // 'Yes'
38768
38769 set(tomster, 'hasSunscreen', 'Check');
38770 tomster.readyForBeach; // 'Check'
38771 ```
38772
38773 Classic Class Example:
38774
38775 ```javascript
38776 import EmberObject, { set } from '@ember/object';
38777 import { or } from '@ember/object/computed';
38778
38779 let Hamster = EmberObject.extend({
38780 readyForRain: or('hasJacket', 'hasUmbrella'),
38781 readyForBeach: or('hasSunscreen', 'hasUmbrella')
38782 });
38783
38784 let tomster = Hamster.create();
38785
38786 tomster.readyForRain; // undefined
38787
38788 set(tomster, 'hasUmbrella', true);
38789 tomster.readyForRain; // true
38790
38791 set(tomster, 'hasJacket', 'Yes');
38792 tomster.readyForRain; // 'Yes'
38793
38794 set(tomster, 'hasSunscreen', 'Check');
38795 tomster.readyForBeach; // 'Check'
38796 ```
38797
38798 @method or
38799 @static
38800 @for @ember/object/computed
38801 @param {String} dependentKey*
38802 @return {ComputedProperty} computed property which performs a logical `or` on
38803 the values of all the original values for properties.
38804 @public
38805 */
38806
38807 _exports.and = and;
38808 var or = generateComputedWithPredicate('or', value => !value);
38809 /**
38810 Creates a new property that is an alias for another property on an object.
38811 Calls to `get` or `set` this property behave as though they were called on the
38812 original property.
38813
38814 Example:
38815
38816 ```javascript
38817 import { set } from '@ember/object';
38818 import { alias } from '@ember/object/computed';
38819
38820 class Person {
38821 name = 'Alex Matchneer';
38822
38823 @alias('name') nomen;
38824 }
38825
38826 let alex = new Person();
38827
38828 alex.nomen; // 'Alex Matchneer'
38829 alex.name; // 'Alex Matchneer'
38830
38831 set(alex, 'nomen', '@machty');
38832 alex.name; // '@machty'
38833 ```
38834
38835 Classic Class Example:
38836
38837 ```javascript
38838 import EmberObject, { set } from '@ember/object';
38839 import { alias } from '@ember/object/computed';
38840
38841 let Person = EmberObject.extend({
38842 name: 'Alex Matchneer',
38843
38844 nomen: alias('name')
38845 });
38846
38847 let alex = Person.create();
38848
38849 alex.nomen; // 'Alex Matchneer'
38850 alex.name; // 'Alex Matchneer'
38851
38852 set(alex, 'nomen', '@machty');
38853 alex.name; // '@machty'
38854 ```
38855
38856 @method alias
38857 @static
38858 @for @ember/object/computed
38859 @param {String} dependentKey
38860 @return {ComputedProperty} computed property which creates an alias to the
38861 original value for property.
38862 @public
38863 */
38864
38865 /**
38866 Where `computed.alias` aliases `get` and `set`, and allows for bidirectional
38867 data flow, `computed.oneWay` only provides an aliased `get`. The `set` will
38868 not mutate the upstream property, rather causes the current property to become
38869 the value set. This causes the downstream property to permanently diverge from
38870 the upstream property.
38871
38872 Example:
38873
38874 ```javascript
38875 import { set } from '@ember/object';
38876 import { oneWay }from '@ember/object/computed';
38877
38878 class User {
38879 constructor(firstName, lastName) {
38880 set(this, 'firstName', firstName);
38881 set(this, 'lastName', lastName);
38882 }
38883
38884 @oneWay('firstName') nickName;
38885 }
38886
38887 let teddy = new User('Teddy', 'Zeenny');
38888
38889 teddy.nickName; // 'Teddy'
38890
38891 set(teddy, 'nickName', 'TeddyBear');
38892 teddy.firstName; // 'Teddy'
38893 teddy.nickName; // 'TeddyBear'
38894 ```
38895
38896 Classic Class Example:
38897
38898 ```javascript
38899 import EmberObject, { set } from '@ember/object';
38900 import { oneWay } from '@ember/object/computed';
38901
38902 let User = EmberObject.extend({
38903 firstName: null,
38904 lastName: null,
38905
38906 nickName: oneWay('firstName')
38907 });
38908
38909 let teddy = User.create({
38910 firstName: 'Teddy',
38911 lastName: 'Zeenny'
38912 });
38913
38914 teddy.nickName; // 'Teddy'
38915
38916 set(teddy, 'nickName', 'TeddyBear'); // 'TeddyBear'
38917 teddy.firstName; // 'Teddy'
38918 teddy.nickName; // 'TeddyBear'
38919 ```
38920
38921 @method oneWay
38922 @static
38923 @for @ember/object/computed
38924 @param {String} dependentKey
38925 @return {ComputedProperty} computed property which creates a one way computed
38926 property to the original value for property.
38927 @public
38928 */
38929
38930 _exports.or = or;
38931
38932 function oneWay(dependentKey) {
38933 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @oneWay as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
38934 return (0, _metal.alias)(dependentKey).oneWay();
38935 }
38936 /**
38937 This is a more semantically meaningful alias of `computed.oneWay`, whose name
38938 is somewhat ambiguous as to which direction the data flows.
38939
38940 @method reads
38941 @static
38942 @for @ember/object/computed
38943 @param {String} dependentKey
38944 @return {ComputedProperty} computed property which creates a one way computed
38945 property to the original value for property.
38946 @public
38947 */
38948
38949 /**
38950 Where `computed.oneWay` provides oneWay bindings, `computed.readOnly` provides
38951 a readOnly one way binding. Very often when using `computed.oneWay` one does
38952 not also want changes to propagate back up, as they will replace the value.
38953
38954 This prevents the reverse flow, and also throws an exception when it occurs.
38955
38956 Example:
38957
38958 ```javascript
38959 import { set } from '@ember/object';
38960 import { readOnly } from '@ember/object/computed';
38961
38962 class User {
38963 constructor(firstName, lastName) {
38964 set(this, 'firstName', firstName);
38965 set(this, 'lastName', lastName);
38966 }
38967
38968 @readOnly('firstName') nickName;
38969 });
38970
38971 let teddy = new User('Teddy', 'Zeenny');
38972
38973 teddy.nickName; // 'Teddy'
38974
38975 set(teddy, 'nickName', 'TeddyBear'); // throws Exception
38976 // throw new EmberError('Cannot Set: nickName on: <User:ember27288>' );`
38977
38978 teddy.firstName; // 'Teddy'
38979 ```
38980
38981 Classic Class Example:
38982
38983 ```javascript
38984 import EmberObject, { set } from '@ember/object';
38985 import { readOnly } from '@ember/object/computed';
38986
38987 let User = EmberObject.extend({
38988 firstName: null,
38989 lastName: null,
38990
38991 nickName: readOnly('firstName')
38992 });
38993
38994 let teddy = User.create({
38995 firstName: 'Teddy',
38996 lastName: 'Zeenny'
38997 });
38998
38999 teddy.nickName; // 'Teddy'
39000
39001 set(teddy, 'nickName', 'TeddyBear'); // throws Exception
39002 // throw new EmberError('Cannot Set: nickName on: <User:ember27288>' );`
39003
39004 teddy.firstName; // 'Teddy'
39005 ```
39006
39007 @method readOnly
39008 @static
39009 @for @ember/object/computed
39010 @param {String} dependentKey
39011 @return {ComputedProperty} computed property which creates a one way computed
39012 property to the original value for property.
39013 @since 1.5.0
39014 @public
39015 */
39016
39017
39018 function readOnly(dependentKey) {
39019 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @readOnly as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
39020 return (0, _metal.alias)(dependentKey).readOnly();
39021 }
39022 /**
39023 Creates a new property that is an alias for another property on an object.
39024 Calls to `get` or `set` this property behave as though they were called on the
39025 original property, but also print a deprecation warning.
39026
39027 Example:
39028
39029 ```javascript
39030 import { set } from '@ember/object';
39031 import { deprecatingAlias } from '@ember/object/computed';
39032
39033 class Hamster {
39034 @deprecatingAlias('cavendishCount', {
39035 id: 'hamster.deprecate-banana',
39036 until: '3.0.0'
39037 })
39038 bananaCount;
39039 }
39040
39041 let hamster = new Hamster();
39042
39043 set(hamster, 'bananaCount', 5); // Prints a deprecation warning.
39044 hamster.cavendishCount; // 5
39045 ```
39046
39047 Classic Class Example:
39048
39049 ```javascript
39050 import EmberObject, { set } from '@ember/object';
39051 import { deprecatingAlias } from '@ember/object/computed';
39052
39053 let Hamster = EmberObject.extend({
39054 bananaCount: deprecatingAlias('cavendishCount', {
39055 id: 'hamster.deprecate-banana',
39056 until: '3.0.0'
39057 })
39058 });
39059
39060 let hamster = Hamster.create();
39061
39062 set(hamster, 'bananaCount', 5); // Prints a deprecation warning.
39063 hamster.cavendishCount; // 5
39064 ```
39065
39066 @method deprecatingAlias
39067 @static
39068 @for @ember/object/computed
39069 @param {String} dependentKey
39070 @param {Object} options Options for `deprecate`.
39071 @return {ComputedProperty} computed property which creates an alias with a
39072 deprecation to the original value for property.
39073 @since 1.7.0
39074 @public
39075 */
39076
39077
39078 function deprecatingAlias(dependentKey, options) {
39079 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @deprecatingAlias as a decorator directly, but it requires `dependentKey` and `options` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
39080 return (0, _metal.computed)(dependentKey, {
39081 get(key) {
39082 (true && !(false) && (0, _debug.deprecate)(`Usage of \`${key}\` is deprecated, use \`${dependentKey}\` instead.`, false, options));
39083 return (0, _metal.get)(this, dependentKey);
39084 },
39085
39086 set(key, value) {
39087 (true && !(false) && (0, _debug.deprecate)(`Usage of \`${key}\` is deprecated, use \`${dependentKey}\` instead.`, false, options));
39088 (0, _metal.set)(this, dependentKey, value);
39089 return value;
39090 }
39091
39092 });
39093 }
39094});
39095define("@ember/object/lib/computed/reduce_computed_macros", ["exports", "@ember/debug", "@ember/-internals/metal", "@ember/-internals/runtime"], function (_exports, _debug, _metal, _runtime) {
39096 "use strict";
39097
39098 Object.defineProperty(_exports, "__esModule", {
39099 value: true
39100 });
39101 _exports.sum = sum;
39102 _exports.max = max;
39103 _exports.min = min;
39104 _exports.map = map;
39105 _exports.mapBy = mapBy;
39106 _exports.filter = filter;
39107 _exports.filterBy = filterBy;
39108 _exports.uniq = uniq;
39109 _exports.uniqBy = uniqBy;
39110 _exports.intersect = intersect;
39111 _exports.setDiff = setDiff;
39112 _exports.collect = collect;
39113 _exports.sort = sort;
39114 _exports.union = void 0;
39115
39116 /**
39117 @module @ember/object
39118 */
39119 function reduceMacro(dependentKey, callback, initialValue, name) {
39120 (true && !(!/[[\]{}]/g.test(dependentKey)) && (0, _debug.assert)(`Dependent key passed to \`computed.${name}\` shouldn't contain brace expanding pattern.`, !/[[\]{}]/g.test(dependentKey)));
39121 return (0, _metal.computed)(`${dependentKey}.[]`, function () {
39122 var arr = (0, _metal.get)(this, dependentKey);
39123
39124 if (arr === null || typeof arr !== 'object') {
39125 return initialValue;
39126 }
39127
39128 return arr.reduce(callback, initialValue, this);
39129 }).readOnly();
39130 }
39131
39132 function arrayMacro(dependentKey, additionalDependentKeys, callback) {
39133 // This is a bit ugly
39134 var propertyName;
39135
39136 if (/@each/.test(dependentKey)) {
39137 propertyName = dependentKey.replace(/\.@each.*$/, '');
39138 } else {
39139 propertyName = dependentKey;
39140 dependentKey += '.[]';
39141 }
39142
39143 return (0, _metal.computed)(dependentKey, ...additionalDependentKeys, function () {
39144 var value = (0, _metal.get)(this, propertyName);
39145
39146 if ((0, _runtime.isArray)(value)) {
39147 return (0, _runtime.A)(callback.call(this, value));
39148 } else {
39149 return (0, _runtime.A)();
39150 }
39151 }).readOnly();
39152 }
39153
39154 function multiArrayMacro(_dependentKeys, callback, name) {
39155 (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))));
39156
39157 var dependentKeys = _dependentKeys.map(key => `${key}.[]`);
39158
39159 return (0, _metal.computed)(...dependentKeys, function () {
39160 return (0, _runtime.A)(callback.call(this, _dependentKeys));
39161 }).readOnly();
39162 }
39163 /**
39164 A computed property that returns the sum of the values in the dependent array.
39165
39166 Example:
39167
39168 ```javascript
39169 import { sum } from '@ember/object/computed';
39170
39171 class Invoice {
39172 lineItems = [1.00, 2.50, 9.99];
39173
39174 @sum('lineItems') total;
39175 }
39176
39177 let invoice = new Invoice();
39178
39179 invoice.total; // 13.49
39180 ```
39181
39182 Classic Class Example:
39183
39184 ```javascript
39185 import EmberObject from '@ember/object';
39186 import { sum } from '@ember/object/computed';
39187
39188 let Invoice = EmberObject.extend({
39189 lineItems: [1.00, 2.50, 9.99],
39190
39191 total: sum('lineItems')
39192 })
39193
39194 let invoice = Invoice.create();
39195
39196 invoice.total; // 13.49
39197 ```
39198
39199 @method sum
39200 @for @ember/object/computed
39201 @static
39202 @param {String} dependentKey
39203 @return {ComputedProperty} computes the sum of all values in the
39204 dependentKey's array
39205 @since 1.4.0
39206 @public
39207 */
39208
39209
39210 function sum(dependentKey) {
39211 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @sum as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
39212 return reduceMacro(dependentKey, (sum, item) => sum + item, 0, 'sum');
39213 }
39214 /**
39215 A computed property that calculates the maximum value in the dependent array.
39216 This will return `-Infinity` when the dependent array is empty.
39217
39218 Example:
39219
39220 ```javascript
39221 import { set } from '@ember/object';
39222 import { mapBy, max } from '@ember/object/computed';
39223
39224 class Person {
39225 children = [];
39226
39227 @mapBy('children', 'age') childAges;
39228 @max('childAges') maxChildAge;
39229 }
39230
39231 let lordByron = new Person();
39232
39233 lordByron.maxChildAge; // -Infinity
39234
39235 set(lordByron, 'children', [
39236 {
39237 name: 'Augusta Ada Byron',
39238 age: 7
39239 }
39240 ]);
39241 lordByron.maxChildAge; // 7
39242
39243 set(lordByron, 'children', [
39244 ...lordByron.children,
39245 {
39246 name: 'Allegra Byron',
39247 age: 5
39248 }, {
39249 name: 'Elizabeth Medora Leigh',
39250 age: 8
39251 }
39252 ]);
39253 lordByron.maxChildAge; // 8
39254 ```
39255
39256 Classic Class Example:
39257
39258 ```javascript
39259 import EmberObject, { set } from '@ember/object';
39260 import { mapBy, max } from '@ember/object/computed';
39261
39262 let Person = EmberObject.extend({
39263 childAges: mapBy('children', 'age'),
39264 maxChildAge: max('childAges')
39265 });
39266
39267 let lordByron = Person.create({ children: [] });
39268
39269 lordByron.maxChildAge; // -Infinity
39270
39271 set(lordByron, 'children', [
39272 {
39273 name: 'Augusta Ada Byron',
39274 age: 7
39275 }
39276 ]);
39277 lordByron.maxChildAge; // 7
39278
39279 set(lordByron, 'children', [
39280 ...lordByron.children,
39281 {
39282 name: 'Allegra Byron',
39283 age: 5
39284 }, {
39285 name: 'Elizabeth Medora Leigh',
39286 age: 8
39287 }
39288 ]);
39289 lordByron.maxChildAge; // 8
39290 ```
39291
39292 If the types of the arguments are not numbers, they will be converted to
39293 numbers and the type of the return value will always be `Number`. For example,
39294 the max of a list of Date objects will be the highest timestamp as a `Number`.
39295 This behavior is consistent with `Math.max`.
39296
39297 @method max
39298 @for @ember/object/computed
39299 @static
39300 @param {String} dependentKey
39301 @return {ComputedProperty} computes the largest value in the dependentKey's
39302 array
39303 @public
39304 */
39305
39306
39307 function max(dependentKey) {
39308 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @max as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
39309 return reduceMacro(dependentKey, (max, item) => Math.max(max, item), -Infinity, 'max');
39310 }
39311 /**
39312 A computed property that calculates the minimum value in the dependent array.
39313 This will return `Infinity` when the dependent array is empty.
39314
39315 Example:
39316
39317 ```javascript
39318 import { set } from '@ember/object';
39319 import { mapBy, min } from '@ember/object/computed';
39320
39321 class Person {
39322 children = [];
39323
39324 @mapBy('children', 'age') childAges;
39325 @min('childAges') minChildAge;
39326 }
39327
39328 let lordByron = Person.create({ children: [] });
39329
39330 lordByron.minChildAge; // Infinity
39331
39332 set(lordByron, 'children', [
39333 {
39334 name: 'Augusta Ada Byron',
39335 age: 7
39336 }
39337 ]);
39338 lordByron.minChildAge; // 7
39339
39340 set(lordByron, 'children', [
39341 ...lordByron.children,
39342 {
39343 name: 'Allegra Byron',
39344 age: 5
39345 }, {
39346 name: 'Elizabeth Medora Leigh',
39347 age: 8
39348 }
39349 ]);
39350 lordByron.minChildAge; // 5
39351 ```
39352
39353 Classic Class Example:
39354
39355 ```javascript
39356 import EmberObject, { set } from '@ember/object';
39357 import { mapBy, min } from '@ember/object/computed';
39358
39359 let Person = EmberObject.extend({
39360 childAges: mapBy('children', 'age'),
39361 minChildAge: min('childAges')
39362 });
39363
39364 let lordByron = Person.create({ children: [] });
39365
39366 lordByron.minChildAge; // Infinity
39367
39368 set(lordByron, 'children', [
39369 {
39370 name: 'Augusta Ada Byron',
39371 age: 7
39372 }
39373 ]);
39374 lordByron.minChildAge; // 7
39375
39376 set(lordByron, 'children', [
39377 ...lordByron.children,
39378 {
39379 name: 'Allegra Byron',
39380 age: 5
39381 }, {
39382 name: 'Elizabeth Medora Leigh',
39383 age: 8
39384 }
39385 ]);
39386 lordByron.minChildAge; // 5
39387 ```
39388
39389 If the types of the arguments are not numbers, they will be converted to
39390 numbers and the type of the return value will always be `Number`. For example,
39391 the min of a list of Date objects will be the lowest timestamp as a `Number`.
39392 This behavior is consistent with `Math.min`.
39393
39394 @method min
39395 @for @ember/object/computed
39396 @static
39397 @param {String} dependentKey
39398 @return {ComputedProperty} computes the smallest value in the dependentKey's array
39399 @public
39400 */
39401
39402
39403 function min(dependentKey) {
39404 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @min as a decorator directly, but it requires a `dependentKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
39405 return reduceMacro(dependentKey, (min, item) => Math.min(min, item), Infinity, 'min');
39406 }
39407 /**
39408 Returns an array mapped via the callback
39409
39410 The callback method you provide should have the following signature:
39411 - `item` is the current item in the iteration.
39412 - `index` is the integer index of the current item in the iteration.
39413
39414 ```javascript
39415 function mapCallback(item, index);
39416 ```
39417
39418 Example:
39419
39420 ```javascript
39421 import { set } from '@ember/object';
39422 import { map } from '@ember/object/computed';
39423
39424 class Hamster {
39425 constructor(chores) {
39426 set(this, 'chores', chores);
39427 }
39428
39429 @map('chores', function(chore, index) {
39430 return `${chore.toUpperCase()}!`;
39431 })
39432 excitingChores;
39433 });
39434
39435 let hamster = new Hamster(['clean', 'write more unit tests']);
39436
39437 hamster.excitingChores; // ['CLEAN!', 'WRITE MORE UNIT TESTS!']
39438 ```
39439
39440 Classic Class Example:
39441
39442 ```javascript
39443 import EmberObject from '@ember/object';
39444 import { map } from '@ember/object/computed';
39445
39446 let Hamster = EmberObject.extend({
39447 excitingChores: map('chores', function(chore, index) {
39448 return `${chore.toUpperCase()}!`;
39449 })
39450 });
39451
39452 let hamster = Hamster.create({
39453 chores: ['clean', 'write more unit tests']
39454 });
39455
39456 hamster.excitingChores; // ['CLEAN!', 'WRITE MORE UNIT TESTS!']
39457 ```
39458
39459 You can optionally pass an array of additional dependent keys as the second
39460 parameter to the macro, if your map function relies on any external values:
39461
39462 ```javascript
39463 import { set } from '@ember/object';
39464 import { map } from '@ember/object/computed';
39465
39466 class Hamster {
39467 shouldUpperCase = false;
39468
39469 constructor(chores) {
39470 set(this, 'chores', chores);
39471 }
39472
39473 @map('chores', ['shouldUpperCase'], function(chore, index) {
39474 if (this.shouldUpperCase) {
39475 return `${chore.toUpperCase()}!`;
39476 } else {
39477 return `${chore}!`;
39478 }
39479 })
39480 excitingChores;
39481 }
39482
39483 let hamster = new Hamster(['clean', 'write more unit tests']);
39484
39485 hamster.excitingChores; // ['clean!', 'write more unit tests!']
39486
39487 set(hamster, 'shouldUpperCase', true);
39488 hamster.excitingChores; // ['CLEAN!', 'WRITE MORE UNIT TESTS!']
39489 ```
39490
39491 @method map
39492 @for @ember/object/computed
39493 @static
39494 @param {String} dependentKey
39495 @param {Array} [additionalDependentKeys] optional array of additional
39496 dependent keys
39497 @param {Function} callback
39498 @return {ComputedProperty} an array mapped via the callback
39499 @public
39500 */
39501
39502
39503 function map(dependentKey, additionalDependentKeys, callback) {
39504 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @map as a decorator directly, but it requires atleast `dependentKey` and `callback` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
39505
39506 if (callback === undefined && typeof additionalDependentKeys === 'function') {
39507 callback = additionalDependentKeys;
39508 additionalDependentKeys = [];
39509 }
39510
39511 (true && !(typeof callback === 'function') && (0, _debug.assert)('The final parameter provided to map must be a callback function', typeof callback === 'function'));
39512 (true && !(Array.isArray(additionalDependentKeys)) && (0, _debug.assert)('The second parameter provided to map must either be the callback or an array of additional dependent keys', Array.isArray(additionalDependentKeys)));
39513 return arrayMacro(dependentKey, additionalDependentKeys, function (value) {
39514 return value.map(callback, this);
39515 });
39516 }
39517 /**
39518 Returns an array mapped to the specified key.
39519
39520 Example:
39521
39522 ```javascript
39523 import { set } from '@ember/object';
39524 import { mapBy } from '@ember/object/computed';
39525
39526 class Person {
39527 children = [];
39528
39529 @mapBy('children', 'age') childAges;
39530 }
39531
39532 let lordByron = new Person();
39533
39534 lordByron.childAges; // []
39535
39536 set(lordByron, 'children', [
39537 {
39538 name: 'Augusta Ada Byron',
39539 age: 7
39540 }
39541 ]);
39542 lordByron.childAges; // [7]
39543
39544 set(lordByron, 'children', [
39545 ...lordByron.children,
39546 {
39547 name: 'Allegra Byron',
39548 age: 5
39549 }, {
39550 name: 'Elizabeth Medora Leigh',
39551 age: 8
39552 }
39553 ]);
39554 lordByron.childAges; // [7, 5, 8]
39555 ```
39556
39557 Classic Class Example:
39558
39559 ```javascript
39560 import EmberObject, { set } from '@ember/object';
39561 import { mapBy } from '@ember/object/computed';
39562
39563 let Person = EmberObject.extend({
39564 childAges: mapBy('children', 'age')
39565 });
39566
39567 let lordByron = Person.create({ children: [] });
39568
39569 lordByron.childAges; // []
39570
39571 set(lordByron, 'children', [
39572 {
39573 name: 'Augusta Ada Byron',
39574 age: 7
39575 }
39576 ]);
39577 lordByron.childAges; // [7]
39578
39579 set(lordByron, 'children', [
39580 ...lordByron.children,
39581 {
39582 name: 'Allegra Byron',
39583 age: 5
39584 }, {
39585 name: 'Elizabeth Medora Leigh',
39586 age: 8
39587 }
39588 ]);
39589 lordByron.childAges; // [7, 5, 8]
39590 ```
39591
39592 @method mapBy
39593 @for @ember/object/computed
39594 @static
39595 @param {String} dependentKey
39596 @param {String} propertyKey
39597 @return {ComputedProperty} an array mapped to the specified key
39598 @public
39599 */
39600
39601
39602 function mapBy(dependentKey, propertyKey) {
39603 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @mapBy as a decorator directly, but it requires `dependentKey` and `propertyKey` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
39604 (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'));
39605 (true && !(!/[[\]{}]/g.test(dependentKey)) && (0, _debug.assert)(`Dependent key passed to \`computed.mapBy\` shouldn't contain brace expanding pattern.`, !/[[\]{}]/g.test(dependentKey)));
39606 return map(`${dependentKey}.@each.${propertyKey}`, item => (0, _metal.get)(item, propertyKey));
39607 }
39608 /**
39609 Filters the array by the callback.
39610
39611 The callback method you provide should have the following signature:
39612 - `item` is the current item in the iteration.
39613 - `index` is the integer index of the current item in the iteration.
39614 - `array` is the dependant array itself.
39615
39616 ```javascript
39617 function filterCallback(item, index, array);
39618 ```
39619
39620 Example:
39621
39622 ```javascript
39623 import { set } from '@ember/object';
39624 import { filter } from '@ember/object/computed';
39625
39626 class Hamster {
39627 constructor(chores) {
39628 set(this, 'chores', chores);
39629 }
39630
39631 @filter('chores', function(chore, index, array) {
39632 return !chore.done;
39633 })
39634 remainingChores;
39635 }
39636
39637 let hamster = Hamster.create([
39638 { name: 'cook', done: true },
39639 { name: 'clean', done: true },
39640 { name: 'write more unit tests', done: false }
39641 ]);
39642
39643 hamster.remainingChores; // [{name: 'write more unit tests', done: false}]
39644 ```
39645
39646 Classic Class Example:
39647
39648 ```javascript
39649 import EmberObject from '@ember/object';
39650 import { filter } from '@ember/object/computed';
39651
39652 let Hamster = EmberObject.extend({
39653 remainingChores: filter('chores', function(chore, index, array) {
39654 return !chore.done;
39655 })
39656 });
39657
39658 let hamster = Hamster.create({
39659 chores: [
39660 { name: 'cook', done: true },
39661 { name: 'clean', done: true },
39662 { name: 'write more unit tests', done: false }
39663 ]
39664 });
39665
39666 hamster.remainingChores; // [{name: 'write more unit tests', done: false}]
39667 ```
39668
39669 You can also use `@each.property` in your dependent key, the callback will
39670 still use the underlying array:
39671
39672 ```javascript
39673 import { set } from '@ember/object';
39674 import { filter } from '@ember/object/computed';
39675
39676 class Hamster {
39677 constructor(chores) {
39678 set(this, 'chores', chores);
39679 }
39680
39681 @filter('chores.@each.done', function(chore, index, array) {
39682 return !chore.done;
39683 })
39684 remainingChores;
39685 }
39686
39687 let hamster = new Hamster([
39688 { name: 'cook', done: true },
39689 { name: 'clean', done: true },
39690 { name: 'write more unit tests', done: false }
39691 ]);
39692 hamster.remainingChores; // [{name: 'write more unit tests', done: false}]
39693
39694 set(hamster.chores[2], 'done', true);
39695 hamster.remainingChores; // []
39696 ```
39697
39698 Finally, you can optionally pass an array of additional dependent keys as the
39699 second parameter to the macro, if your filter function relies on any external
39700 values:
39701
39702 ```javascript
39703 import { filter } from '@ember/object/computed';
39704
39705 class Hamster {
39706 constructor(chores) {
39707 set(this, 'chores', chores);
39708 }
39709
39710 doneKey = 'finished';
39711
39712 @filter('chores', ['doneKey'], function(chore, index, array) {
39713 return !chore[this.doneKey];
39714 })
39715 remainingChores;
39716 }
39717
39718 let hamster = new Hamster([
39719 { name: 'cook', finished: true },
39720 { name: 'clean', finished: true },
39721 { name: 'write more unit tests', finished: false }
39722 ]);
39723
39724 hamster.remainingChores; // [{name: 'write more unit tests', finished: false}]
39725 ```
39726
39727 @method filter
39728 @for @ember/object/computed
39729 @static
39730 @param {String} dependentKey
39731 @param {Array} [additionalDependentKeys] optional array of additional dependent keys
39732 @param {Function} callback
39733 @return {ComputedProperty} the filtered array
39734 @public
39735 */
39736
39737
39738 function filter(dependentKey, additionalDependentKeys, callback) {
39739 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @filter as a decorator directly, but it requires atleast `dependentKey` and `callback` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
39740
39741 if (callback === undefined && typeof additionalDependentKeys === 'function') {
39742 callback = additionalDependentKeys;
39743 additionalDependentKeys = [];
39744 }
39745
39746 (true && !(typeof callback === 'function') && (0, _debug.assert)('The final parameter provided to filter must be a callback function', typeof callback === 'function'));
39747 (true && !(Array.isArray(additionalDependentKeys)) && (0, _debug.assert)('The second parameter provided to filter must either be the callback or an array of additional dependent keys', Array.isArray(additionalDependentKeys)));
39748 return arrayMacro(dependentKey, additionalDependentKeys, function (value) {
39749 return value.filter(callback, this);
39750 });
39751 }
39752 /**
39753 Filters the array by the property and value.
39754
39755 Example:
39756
39757 ```javascript
39758 import { set } from '@ember/object';
39759 import { filterBy } from '@ember/object/computed';
39760
39761 class Hamster {
39762 constructor(chores) {
39763 set(this, 'chores', chores);
39764 }
39765
39766 @filterBy('chores', 'done', false) remainingChores;
39767 }
39768
39769 let hamster = new Hamster([
39770 { name: 'cook', done: true },
39771 { name: 'clean', done: true },
39772 { name: 'write more unit tests', done: false }
39773 ]);
39774
39775 hamster.remainingChores; // [{ name: 'write more unit tests', done: false }]
39776 ```
39777
39778 Classic Class Example:
39779
39780 ```javascript
39781 import EmberObject from '@ember/object';
39782 import { filterBy } from '@ember/object/computed';
39783
39784 let Hamster = EmberObject.extend({
39785 remainingChores: filterBy('chores', 'done', false)
39786 });
39787
39788 let hamster = Hamster.create({
39789 chores: [
39790 { name: 'cook', done: true },
39791 { name: 'clean', done: true },
39792 { name: 'write more unit tests', done: false }
39793 ]
39794 });
39795
39796 hamster.remainingChores; // [{ name: 'write more unit tests', done: false }]
39797 ```
39798
39799 @method filterBy
39800 @for @ember/object/computed
39801 @static
39802 @param {String} dependentKey
39803 @param {String} propertyKey
39804 @param {*} value
39805 @return {ComputedProperty} the filtered array
39806 @public
39807 */
39808
39809
39810 function filterBy(dependentKey, propertyKey, value) {
39811 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @filterBy as a decorator directly, but it requires atleast `dependentKey` and `propertyKey` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
39812 (true && !(!/[[\]{}]/g.test(dependentKey)) && (0, _debug.assert)(`Dependent key passed to \`computed.filterBy\` shouldn't contain brace expanding pattern.`, !/[[\]{}]/g.test(dependentKey)));
39813 var callback;
39814
39815 if (arguments.length === 2) {
39816 callback = item => (0, _metal.get)(item, propertyKey);
39817 } else {
39818 callback = item => (0, _metal.get)(item, propertyKey) === value;
39819 }
39820
39821 return filter(`${dependentKey}.@each.${propertyKey}`, callback);
39822 }
39823 /**
39824 A computed property which returns a new array with all the unique elements
39825 from one or more dependent arrays.
39826
39827 Example:
39828
39829 ```javascript
39830 import { set } from '@ember/object';
39831 import { uniq } from '@ember/object/computed';
39832
39833 class Hamster {
39834 constructor(fruits) {
39835 set(this, 'fruits', fruits);
39836 }
39837
39838 @uniq('fruits') uniqueFruits;
39839 }
39840
39841 let hamster = new Hamster([
39842 'banana',
39843 'grape',
39844 'kale',
39845 'banana'
39846 ]);
39847
39848 hamster.uniqueFruits; // ['banana', 'grape', 'kale']
39849 ```
39850
39851 Classic Class Example:
39852
39853 ```javascript
39854 import EmberObject from '@ember/object';
39855 import { uniq } from '@ember/object/computed';
39856
39857 let Hamster = EmberObject.extend({
39858 uniqueFruits: uniq('fruits')
39859 });
39860
39861 let hamster = Hamster.create({
39862 fruits: [
39863 'banana',
39864 'grape',
39865 'kale',
39866 'banana'
39867 ]
39868 });
39869
39870 hamster.uniqueFruits; // ['banana', 'grape', 'kale']
39871 ```
39872
39873 @method uniq
39874 @for @ember/object/computed
39875 @static
39876 @param {String} propertyKey*
39877 @return {ComputedProperty} computes a new array with all the
39878 unique elements from the dependent array
39879 @public
39880 */
39881
39882
39883 function uniq(...args) {
39884 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @uniq/@union as a decorator directly, but it requires atleast one dependent key parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
39885 return multiArrayMacro(args, function (dependentKeys) {
39886 var uniq = (0, _runtime.A)();
39887 var seen = new Set();
39888 dependentKeys.forEach(dependentKey => {
39889 var value = (0, _metal.get)(this, dependentKey);
39890
39891 if ((0, _runtime.isArray)(value)) {
39892 value.forEach(item => {
39893 if (!seen.has(item)) {
39894 seen.add(item);
39895 uniq.push(item);
39896 }
39897 });
39898 }
39899 });
39900 return uniq;
39901 }, 'uniq');
39902 }
39903 /**
39904 A computed property which returns a new array with all the unique elements
39905 from an array, with uniqueness determined by specific key.
39906
39907 Example:
39908
39909 ```javascript
39910 import { set } from '@ember/object';
39911 import { uniqBy } from '@ember/object/computed';
39912
39913 class Hamster {
39914 constructor(fruits) {
39915 set(this, 'fruits', fruits);
39916 }
39917
39918 @uniqBy('fruits', 'id') uniqueFruits;
39919 }
39920
39921 let hamster = new Hamster([
39922 { id: 1, 'banana' },
39923 { id: 2, 'grape' },
39924 { id: 3, 'peach' },
39925 { id: 1, 'banana' }
39926 ]);
39927
39928 hamster.uniqueFruits; // [ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }]
39929 ```
39930
39931 Classic Class Example:
39932
39933 ```javascript
39934 import EmberObject from '@ember/object';
39935 import { uniqBy } from '@ember/object/computed';
39936
39937 let Hamster = EmberObject.extend({
39938 uniqueFruits: uniqBy('fruits', 'id')
39939 });
39940
39941 let hamster = Hamster.create({
39942 fruits: [
39943 { id: 1, 'banana' },
39944 { id: 2, 'grape' },
39945 { id: 3, 'peach' },
39946 { id: 1, 'banana' }
39947 ]
39948 });
39949
39950 hamster.uniqueFruits; // [ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }]
39951 ```
39952
39953 @method uniqBy
39954 @for @ember/object/computed
39955 @static
39956 @param {String} dependentKey
39957 @param {String} propertyKey
39958 @return {ComputedProperty} computes a new array with all the
39959 unique elements from the dependent array
39960 @public
39961 */
39962
39963
39964 function uniqBy(dependentKey, propertyKey) {
39965 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @uniqBy as a decorator directly, but it requires `dependentKey` and `propertyKey` parameters', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
39966 (true && !(!/[[\]{}]/g.test(dependentKey)) && (0, _debug.assert)(`Dependent key passed to \`computed.uniqBy\` shouldn't contain brace expanding pattern.`, !/[[\]{}]/g.test(dependentKey)));
39967 return (0, _metal.computed)(`${dependentKey}.[]`, function () {
39968 var list = (0, _metal.get)(this, dependentKey);
39969 return (0, _runtime.isArray)(list) ? (0, _runtime.uniqBy)(list, propertyKey) : (0, _runtime.A)();
39970 }).readOnly();
39971 }
39972 /**
39973 A computed property which returns a new array with all the unique elements
39974 from one or more dependent arrays.
39975
39976 Example:
39977
39978 ```javascript
39979 import { set } from '@ember/object';
39980 import { union } from '@ember/object/computed';
39981
39982 class Hamster {
39983 constructor(fruits, vegetables) {
39984 set(this, 'fruits', fruits);
39985 set(this, 'vegetables', vegetables);
39986 }
39987
39988 @union('fruits', 'vegetables') uniqueFruits;
39989 });
39990
39991 let hamster = new, Hamster(
39992 [
39993 'banana',
39994 'grape',
39995 'kale',
39996 'banana',
39997 'tomato'
39998 ],
39999 [
40000 'tomato',
40001 'carrot',
40002 'lettuce'
40003 ]
40004 );
40005
40006 hamster.uniqueFruits; // ['banana', 'grape', 'kale', 'tomato', 'carrot', 'lettuce']
40007 ```
40008
40009 Classic Class Example:
40010
40011 ```javascript
40012 import EmberObject from '@ember/object';
40013 import { union } from '@ember/object/computed';
40014
40015 let Hamster = EmberObject.extend({
40016 uniqueFruits: union('fruits', 'vegetables')
40017 });
40018
40019 let hamster = Hamster.create({
40020 fruits: [
40021 'banana',
40022 'grape',
40023 'kale',
40024 'banana',
40025 'tomato'
40026 ],
40027 vegetables: [
40028 'tomato',
40029 'carrot',
40030 'lettuce'
40031 ]
40032 });
40033
40034 hamster.uniqueFruits; // ['banana', 'grape', 'kale', 'tomato', 'carrot', 'lettuce']
40035 ```
40036
40037 @method union
40038 @for @ember/object/computed
40039 @static
40040 @param {String} propertyKey*
40041 @return {ComputedProperty} computes a new array with all the unique elements
40042 from one or more dependent arrays.
40043 @public
40044 */
40045
40046
40047 var union = uniq;
40048 /**
40049 A computed property which returns a new array with all the elements
40050 two or more dependent arrays have in common.
40051
40052 Example:
40053
40054 ```javascript
40055 import { set } from '@ember/object';
40056 import { intersect } from '@ember/object/computed';
40057
40058 class FriendGroups {
40059 constructor(adaFriends, charlesFriends) {
40060 set(this, 'adaFriends', adaFriends);
40061 set(this, 'charlesFriends', charlesFriends);
40062 }
40063
40064 @intersect('adaFriends', 'charlesFriends') friendsInCommon;
40065 }
40066
40067 let groups = new FriendGroups(
40068 ['Charles Babbage', 'John Hobhouse', 'William King', 'Mary Somerville'],
40069 ['William King', 'Mary Somerville', 'Ada Lovelace', 'George Peacock']
40070 );
40071
40072 groups.friendsInCommon; // ['William King', 'Mary Somerville']
40073 ```
40074
40075 Classic Class Example:
40076
40077 ```javascript
40078 import EmberObject from '@ember/object';
40079 import { intersect } from '@ember/object/computed';
40080
40081 let FriendGroups = EmberObject.extend({
40082 friendsInCommon: intersect('adaFriends', 'charlesFriends')
40083 });
40084
40085 let groups = FriendGroups.create({
40086 adaFriends: ['Charles Babbage', 'John Hobhouse', 'William King', 'Mary Somerville'],
40087 charlesFriends: ['William King', 'Mary Somerville', 'Ada Lovelace', 'George Peacock']
40088 });
40089
40090 groups.friendsInCommon; // ['William King', 'Mary Somerville']
40091 ```
40092
40093 @method intersect
40094 @for @ember/object/computed
40095 @static
40096 @param {String} propertyKey*
40097 @return {ComputedProperty} computes a new array with all the duplicated
40098 elements from the dependent arrays
40099 @public
40100 */
40101
40102 _exports.union = union;
40103
40104 function intersect(...args) {
40105 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @intersect as a decorator directly, but it requires atleast one dependent key parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
40106 return multiArrayMacro(args, function (dependentKeys) {
40107 var arrays = dependentKeys.map(dependentKey => {
40108 var array = (0, _metal.get)(this, dependentKey);
40109 return (0, _runtime.isArray)(array) ? array : [];
40110 });
40111 var results = arrays.pop().filter(candidate => {
40112 for (var i = 0; i < arrays.length; i++) {
40113 var found = false;
40114 var array = arrays[i];
40115
40116 for (var j = 0; j < array.length; j++) {
40117 if (array[j] === candidate) {
40118 found = true;
40119 break;
40120 }
40121 }
40122
40123 if (found === false) {
40124 return false;
40125 }
40126 }
40127
40128 return true;
40129 });
40130 return (0, _runtime.A)(results);
40131 }, 'intersect');
40132 }
40133 /**
40134 A computed property which returns a new array with all the properties from the
40135 first dependent array that are not in the second dependent array.
40136
40137 Example:
40138
40139 ```javascript
40140 import { set } from '@ember/object';
40141 import { setDiff } from '@ember/object/computed';
40142
40143 class Hamster {
40144 constructor(likes, fruits) {
40145 set(this, 'likes', likes);
40146 set(this, 'fruits', fruits);
40147 }
40148
40149 @setDiff('likes', 'fruits') wants;
40150 }
40151
40152 let hamster = new Hamster(
40153 [
40154 'banana',
40155 'grape',
40156 'kale'
40157 ],
40158 [
40159 'grape',
40160 'kale',
40161 ]
40162 );
40163
40164 hamster.wants; // ['banana']
40165 ```
40166
40167 Classic Class Example:
40168
40169 ```javascript
40170 import EmberObject from '@ember/object';
40171 import { setDiff } from '@ember/object/computed';
40172
40173 let Hamster = EmberObject.extend({
40174 wants: setDiff('likes', 'fruits')
40175 });
40176
40177 let hamster = Hamster.create({
40178 likes: [
40179 'banana',
40180 'grape',
40181 'kale'
40182 ],
40183 fruits: [
40184 'grape',
40185 'kale',
40186 ]
40187 });
40188
40189 hamster.wants; // ['banana']
40190 ```
40191
40192 @method setDiff
40193 @for @ember/object/computed
40194 @static
40195 @param {String} setAProperty
40196 @param {String} setBProperty
40197 @return {ComputedProperty} computes a new array with all the items from the
40198 first dependent array that are not in the second dependent array
40199 @public
40200 */
40201
40202
40203 function setDiff(setAProperty, setBProperty) {
40204 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @setDiff as a decorator directly, but it requires atleast one dependent key parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
40205 (true && !(arguments.length === 2) && (0, _debug.assert)('`computed.setDiff` requires exactly two dependent arrays.', arguments.length === 2));
40206 (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)));
40207 return (0, _metal.computed)(`${setAProperty}.[]`, `${setBProperty}.[]`, function () {
40208 var setA = (0, _metal.get)(this, setAProperty);
40209 var setB = (0, _metal.get)(this, setBProperty);
40210
40211 if (!(0, _runtime.isArray)(setA)) {
40212 return (0, _runtime.A)();
40213 }
40214
40215 if (!(0, _runtime.isArray)(setB)) {
40216 return (0, _runtime.A)(setA);
40217 }
40218
40219 return setA.filter(x => setB.indexOf(x) === -1);
40220 }).readOnly();
40221 }
40222 /**
40223 A computed property that returns the array of values for the provided
40224 dependent properties.
40225
40226 Example:
40227
40228 ```javascript
40229 import { set } from '@ember/object';
40230 import { collect } from '@ember/object/computed';
40231
40232 class Hamster {
40233 @collect('hat', 'shirt') clothes;
40234 }
40235
40236 let hamster = new Hamster();
40237
40238 hamster.clothes; // [null, null]
40239
40240 set(hamster, 'hat', 'Camp Hat');
40241 set(hamster, 'shirt', 'Camp Shirt');
40242 hamster.clothes; // ['Camp Hat', 'Camp Shirt']
40243 ```
40244
40245 Classic Class Example:
40246
40247 ```javascript
40248 import EmberObject, { set } from '@ember/object';
40249 import { collect } from '@ember/object/computed';
40250
40251 let Hamster = EmberObject.extend({
40252 clothes: collect('hat', 'shirt')
40253 });
40254
40255 let hamster = Hamster.create();
40256
40257 hamster.clothes; // [null, null]
40258
40259 set(hamster, 'hat', 'Camp Hat');
40260 set(hamster, 'shirt', 'Camp Shirt');
40261 hamster.clothes; // ['Camp Hat', 'Camp Shirt']
40262 ```
40263
40264 @method collect
40265 @for @ember/object/computed
40266 @static
40267 @param {String} dependentKey*
40268 @return {ComputedProperty} computed property which maps values of all passed
40269 in properties to an array.
40270 @public
40271 */
40272
40273
40274 function collect(...dependentKeys) {
40275 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @collect as a decorator directly, but it requires atleast one dependent key parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
40276 return multiArrayMacro(dependentKeys, function () {
40277 var res = dependentKeys.map(key => {
40278 var val = (0, _metal.get)(this, key);
40279 return val === undefined ? null : val;
40280 });
40281 return (0, _runtime.A)(res);
40282 }, 'collect');
40283 }
40284 /**
40285 A computed property which returns a new array with all the properties from the
40286 first dependent array sorted based on a property or sort function. The sort
40287 macro can be used in two different ways:
40288
40289 1. By providing a sort callback function
40290 2. By providing an array of keys to sort the array
40291
40292 In the first form, the callback method you provide should have the following
40293 signature:
40294
40295 ```javascript
40296 function sortCallback(itemA, itemB);
40297 ```
40298
40299 - `itemA` the first item to compare.
40300 - `itemB` the second item to compare.
40301
40302 This function should return negative number (e.g. `-1`) when `itemA` should
40303 come before `itemB`. It should return positive number (e.g. `1`) when `itemA`
40304 should come after `itemB`. If the `itemA` and `itemB` are equal this function
40305 should return `0`.
40306
40307 Therefore, if this function is comparing some numeric values, simple `itemA -
40308 itemB` or `itemA.get( 'foo' ) - itemB.get( 'foo' )` can be used instead of
40309 series of `if`.
40310
40311 Example:
40312
40313 ```javascript
40314 import { set } from '@ember/object';
40315 import { sort } from '@ember/object/computed';
40316
40317 class ToDoList {
40318 constructor(todos) {
40319 set(this, 'todos', todos);
40320 }
40321
40322 // using a custom sort function
40323 @sort('todos', function(a, b){
40324 if (a.priority > b.priority) {
40325 return 1;
40326 } else if (a.priority < b.priority) {
40327 return -1;
40328 }
40329
40330 return 0;
40331 })
40332 priorityTodos;
40333 }
40334
40335 let todoList = new ToDoList([
40336 { name: 'Unit Test', priority: 2 },
40337 { name: 'Documentation', priority: 3 },
40338 { name: 'Release', priority: 1 }
40339 ]);
40340
40341 todoList.priorityTodos; // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }]
40342 ```
40343
40344 Classic Class Example:
40345
40346 ```javascript
40347 import EmberObject from '@ember/object';
40348 import { sort } from '@ember/object/computed';
40349
40350 let ToDoList = EmberObject.extend({
40351 // using a custom sort function
40352 priorityTodos: sort('todos', function(a, b){
40353 if (a.priority > b.priority) {
40354 return 1;
40355 } else if (a.priority < b.priority) {
40356 return -1;
40357 }
40358
40359 return 0;
40360 })
40361 });
40362
40363 let todoList = ToDoList.create({
40364 todos: [
40365 { name: 'Unit Test', priority: 2 },
40366 { name: 'Documentation', priority: 3 },
40367 { name: 'Release', priority: 1 }
40368 ]
40369 });
40370
40371 todoList.priorityTodos; // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }]
40372 ```
40373
40374 You can also optionally pass an array of additional dependent keys as the
40375 second parameter, if your sort function is dependent on additional values that
40376 could changes:
40377
40378 ```js
40379 import EmberObject, { set } from '@ember/object';
40380 import { sort } from '@ember/object/computed';
40381
40382 class ToDoList {
40383 sortKey = 'priority';
40384
40385 constructor(todos) {
40386 set(this, 'todos', todos);
40387 }
40388
40389 // using a custom sort function
40390 @sort('todos', ['sortKey'], function(a, b){
40391 if (a[this.sortKey] > b[this.sortKey]) {
40392 return 1;
40393 } else if (a[this.sortKey] < b[this.sortKey]) {
40394 return -1;
40395 }
40396
40397 return 0;
40398 })
40399 sortedTodos;
40400 });
40401
40402 let todoList = new ToDoList([
40403 { name: 'Unit Test', priority: 2 },
40404 { name: 'Documentation', priority: 3 },
40405 { name: 'Release', priority: 1 }
40406 ]);
40407
40408 todoList.priorityTodos; // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }]
40409 ```
40410
40411 In the second form, you should provide the key of the array of sort values as
40412 the second parameter:
40413
40414 ```javascript
40415 import { set } from '@ember/object';
40416 import { sort } from '@ember/object/computed';
40417
40418 class ToDoList {
40419 constructor(todos) {
40420 set(this, 'todos', todos);
40421 }
40422
40423 // using standard ascending sort
40424 todosSorting = ['name'];
40425 @sort('todos', 'todosSorting') sortedTodos;
40426
40427 // using descending sort
40428 todosSortingDesc = ['name:desc'];
40429 @sort('todos', 'todosSortingDesc') sortedTodosDesc;
40430 }
40431
40432 let todoList = new ToDoList([
40433 { name: 'Unit Test', priority: 2 },
40434 { name: 'Documentation', priority: 3 },
40435 { name: 'Release', priority: 1 }
40436 ]);
40437
40438 todoList.sortedTodos; // [{ name:'Documentation', priority:3 }, { name:'Release', priority:1 }, { name:'Unit Test', priority:2 }]
40439 todoList.sortedTodosDesc; // [{ name:'Unit Test', priority:2 }, { name:'Release', priority:1 }, { name:'Documentation', priority:3 }]
40440 ```
40441
40442 @method sort
40443 @for @ember/object/computed
40444 @static
40445 @param {String} itemsKey
40446 @param {String|Function|Array} sortDefinitionOrDependentKeys The key of the sort definition (an array of sort properties),
40447 the sort function, or an array of additional dependent keys
40448 @param {Function?} sortDefinition the sort function (when used with additional dependent keys)
40449 @return {ComputedProperty} computes a new sorted array based on the sort
40450 property array or callback function
40451 @public
40452 */
40453
40454
40455 function sort(itemsKey, additionalDependentKeys, sortDefinition) {
40456 (true && !(!(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))) && (0, _debug.assert)('You attempted to use @sort as a decorator directly, but it requires atleast an `itemsKey` parameter', !(0, _metal.isElementDescriptor)(Array.prototype.slice.call(arguments))));
40457
40458 if (true
40459 /* DEBUG */
40460 ) {
40461 var argumentsValid = false;
40462
40463 if (arguments.length === 2) {
40464 argumentsValid = typeof itemsKey === 'string' && (typeof additionalDependentKeys === 'string' || typeof additionalDependentKeys === 'function');
40465 }
40466
40467 if (arguments.length === 3) {
40468 argumentsValid = typeof itemsKey === 'string' && Array.isArray(additionalDependentKeys) && typeof sortDefinition === 'function';
40469 }
40470
40471 (true && !(argumentsValid) && (0, _debug.assert)('`computed.sort` can either be used with an array of sort properties or with a sort function. If used with an array of sort properties, it must receive exactly two arguments: the key of the array to sort, and the key of the array of sort properties. If used with a sort function, it may receive up to three arguments: the key of the array to sort, an optional additional array of dependent keys for the computed property, and the sort function.', argumentsValid));
40472 }
40473
40474 if (sortDefinition === undefined && !Array.isArray(additionalDependentKeys)) {
40475 sortDefinition = additionalDependentKeys;
40476 additionalDependentKeys = [];
40477 }
40478
40479 if (typeof sortDefinition === 'function') {
40480 return customSort(itemsKey, additionalDependentKeys, sortDefinition);
40481 } else {
40482 return propertySort(itemsKey, sortDefinition);
40483 }
40484 }
40485
40486 function customSort(itemsKey, additionalDependentKeys, comparator) {
40487 return arrayMacro(itemsKey, additionalDependentKeys, function (value) {
40488 return value.slice().sort((x, y) => comparator.call(this, x, y));
40489 });
40490 } // This one needs to dynamically set up and tear down observers on the itemsKey
40491 // depending on the sortProperties
40492
40493
40494 function propertySort(itemsKey, sortPropertiesKey) {
40495 var cp = (0, _metal.autoComputed)(function (key) {
40496 var sortProperties = (0, _metal.get)(this, sortPropertiesKey);
40497 (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')));
40498 var itemsKeyIsAtThis = itemsKey === '@this';
40499 var normalizedSortProperties = normalizeSortProperties(sortProperties);
40500 var items = itemsKeyIsAtThis ? this : (0, _metal.get)(this, itemsKey);
40501
40502 if (!(0, _runtime.isArray)(items)) {
40503 return (0, _runtime.A)();
40504 }
40505
40506 if (normalizedSortProperties.length === 0) {
40507 return (0, _runtime.A)(items.slice());
40508 } else {
40509 return sortByNormalizedSortProperties(items, normalizedSortProperties);
40510 }
40511 }).readOnly();
40512 return cp;
40513 }
40514
40515 function normalizeSortProperties(sortProperties) {
40516 return sortProperties.map(p => {
40517 var [prop, direction] = p.split(':');
40518 direction = direction || 'asc';
40519 return [prop, direction];
40520 });
40521 }
40522
40523 function sortByNormalizedSortProperties(items, normalizedSortProperties) {
40524 return (0, _runtime.A)(items.slice().sort((itemA, itemB) => {
40525 for (var i = 0; i < normalizedSortProperties.length; i++) {
40526 var [prop, direction] = normalizedSortProperties[i];
40527 var result = (0, _runtime.compare)((0, _metal.get)(itemA, prop), (0, _metal.get)(itemB, prop));
40528
40529 if (result !== 0) {
40530 return direction === 'desc' ? -1 * result : result;
40531 }
40532 }
40533
40534 return 0;
40535 }));
40536 }
40537});
40538define("@ember/polyfills/index", ["exports", "@ember/deprecated-features", "@ember/polyfills/lib/merge", "@ember/polyfills/lib/assign", "@ember/polyfills/lib/weak_set"], function (_exports, _deprecatedFeatures, _merge, _assign, _weak_set) {
40539 "use strict";
40540
40541 Object.defineProperty(_exports, "__esModule", {
40542 value: true
40543 });
40544 Object.defineProperty(_exports, "assign", {
40545 enumerable: true,
40546 get: function () {
40547 return _assign.default;
40548 }
40549 });
40550 Object.defineProperty(_exports, "assignPolyfill", {
40551 enumerable: true,
40552 get: function () {
40553 return _assign.assign;
40554 }
40555 });
40556 Object.defineProperty(_exports, "_WeakSet", {
40557 enumerable: true,
40558 get: function () {
40559 return _weak_set.default;
40560 }
40561 });
40562 _exports.merge = void 0;
40563 var merge = _deprecatedFeatures.MERGE ? _merge.default : undefined; // Export `assignPolyfill` for testing
40564
40565 _exports.merge = merge;
40566});
40567define("@ember/polyfills/lib/assign", ["exports"], function (_exports) {
40568 "use strict";
40569
40570 Object.defineProperty(_exports, "__esModule", {
40571 value: true
40572 });
40573 _exports.assign = assign;
40574 _exports.default = void 0;
40575
40576 /**
40577 @module @ember/polyfills
40578 */
40579
40580 /**
40581 Copy properties from a source object to a target object. Source arguments remain unchanged.
40582
40583 ```javascript
40584 import { assign } from '@ember/polyfills';
40585
40586 var a = { first: 'Yehuda' };
40587 var b = { last: 'Katz' };
40588 var c = { company: 'Other Company' };
40589 var d = { company: 'Tilde Inc.' };
40590 assign(a, b, c, d); // a === { first: 'Yehuda', last: 'Katz', company: 'Tilde Inc.' };
40591 ```
40592
40593 @method assign
40594 @for @ember/polyfills
40595 @param {Object} target The object to assign into
40596 @param {Object} ...args The objects to copy properties from
40597 @return {Object}
40598 @public
40599 @static
40600 */
40601 function assign(target) {
40602 for (var i = 1; i < arguments.length; i++) {
40603 var arg = arguments[i];
40604
40605 if (!arg) {
40606 continue;
40607 }
40608
40609 var updates = Object.keys(arg);
40610
40611 for (var _i = 0; _i < updates.length; _i++) {
40612 var prop = updates[_i];
40613 target[prop] = arg[prop];
40614 }
40615 }
40616
40617 return target;
40618 } // Note: We use the bracket notation so
40619 // that the babel plugin does not
40620 // transform it.
40621 // https://www.npmjs.com/package/babel-plugin-transform-object-assign
40622
40623
40624 var {
40625 assign: _assign
40626 } = Object;
40627
40628 var _default = _assign || assign;
40629
40630 _exports.default = _default;
40631});
40632define("@ember/polyfills/lib/merge", ["exports", "@ember/debug"], function (_exports, _debug) {
40633 "use strict";
40634
40635 Object.defineProperty(_exports, "__esModule", {
40636 value: true
40637 });
40638 _exports.default = merge;
40639
40640 /**
40641 Merge the contents of two objects together into the first object.
40642
40643 ```javascript
40644 import { merge } from '@ember/polyfills';
40645
40646 merge({ first: 'Tom' }, { last: 'Dale' }); // { first: 'Tom', last: 'Dale' }
40647 var a = { first: 'Yehuda' };
40648 var b = { last: 'Katz' };
40649 merge(a, b); // a == { first: 'Yehuda', last: 'Katz' }, b == { last: 'Katz' }
40650 ```
40651
40652 @method merge
40653 @static
40654 @for @ember/polyfills
40655 @param {Object} original The object to merge into
40656 @param {Object} updates The object to copy properties from
40657 @return {Object}
40658 @deprecated
40659 @public
40660 */
40661 function merge(original, updates) {
40662 (true && !(false) && (0, _debug.deprecate)('Use of `merge` has been deprecated. Please use `assign` instead.', false, {
40663 id: 'ember-polyfills.deprecate-merge',
40664 until: '4.0.0',
40665 url: 'https://emberjs.com/deprecations/v3.x/#toc_ember-polyfills-deprecate-merge'
40666 }));
40667
40668 if (updates === null || typeof updates !== 'object') {
40669 return original;
40670 }
40671
40672 var props = Object.keys(updates);
40673 var prop;
40674
40675 for (var i = 0; i < props.length; i++) {
40676 prop = props[i];
40677 original[prop] = updates[prop];
40678 }
40679
40680 return original;
40681 }
40682});
40683define("@ember/polyfills/lib/weak_set", ["exports"], function (_exports) {
40684 "use strict";
40685
40686 Object.defineProperty(_exports, "__esModule", {
40687 value: true
40688 });
40689 _exports.default = void 0;
40690
40691 /* globals WeakSet */
40692 var _default = typeof WeakSet === 'function' ? WeakSet : class WeakSetPolyFill {
40693 constructor() {
40694 this._map = new WeakMap();
40695 }
40696
40697 add(val) {
40698 this._map.set(val, true);
40699
40700 return this;
40701 }
40702
40703 delete(val) {
40704 return this._map.delete(val);
40705 }
40706
40707 has(val) {
40708 return this._map.has(val);
40709 }
40710
40711 };
40712
40713 _exports.default = _default;
40714});
40715define("@ember/runloop/index", ["exports", "@ember/debug", "@ember/-internals/error-handling", "@ember/-internals/metal", "backburner"], function (_exports, _debug, _errorHandling, _metal, _backburner) {
40716 "use strict";
40717
40718 Object.defineProperty(_exports, "__esModule", {
40719 value: true
40720 });
40721 _exports.getCurrentRunLoop = getCurrentRunLoop;
40722 _exports.run = run;
40723 _exports.join = join;
40724 _exports.begin = begin;
40725 _exports.end = end;
40726 _exports.schedule = schedule;
40727 _exports.hasScheduledTimers = hasScheduledTimers;
40728 _exports.cancelTimers = cancelTimers;
40729 _exports.later = later;
40730 _exports.once = once;
40731 _exports.scheduleOnce = scheduleOnce;
40732 _exports.next = next;
40733 _exports.cancel = cancel;
40734 _exports.debounce = debounce;
40735 _exports.throttle = throttle;
40736 _exports.bind = _exports._globalsRun = _exports.backburner = _exports.queues = _exports._rsvpErrorQueue = void 0;
40737 var currentRunLoop = null;
40738
40739 function getCurrentRunLoop() {
40740 return currentRunLoop;
40741 }
40742
40743 function onBegin(current) {
40744 currentRunLoop = current;
40745 }
40746
40747 function onEnd(current, next) {
40748 currentRunLoop = next;
40749 (0, _metal.flushAsyncObservers)();
40750 }
40751
40752 function flush(queueName, next) {
40753 if (queueName === 'render' || queueName === _rsvpErrorQueue) {
40754 (0, _metal.flushAsyncObservers)();
40755 }
40756
40757 next();
40758 }
40759
40760 var _rsvpErrorQueue = `${Math.random()}${Date.now()}`.replace('.', '');
40761 /**
40762 Array of named queues. This array determines the order in which queues
40763 are flushed at the end of the RunLoop. You can define your own queues by
40764 simply adding the queue name to this array. Normally you should not need
40765 to inspect or modify this property.
40766
40767 @property queues
40768 @type Array
40769 @default ['actions', 'destroy']
40770 @private
40771 */
40772
40773
40774 _exports._rsvpErrorQueue = _rsvpErrorQueue;
40775 var queues = ['actions', // used in router transitions to prevent unnecessary loading state entry
40776 // if all context promises resolve on the 'actions' queue first
40777 'routerTransitions', 'render', 'afterRender', 'destroy', // used to re-throw unhandled RSVP rejection errors specifically in this
40778 // position to avoid breaking anything rendered in the other sections
40779 _rsvpErrorQueue];
40780 _exports.queues = queues;
40781 var backburner = new _backburner.default(queues, {
40782 defaultQueue: 'actions',
40783 onBegin,
40784 onEnd,
40785 onErrorTarget: _errorHandling.onErrorTarget,
40786 onErrorMethod: 'onerror',
40787 flush
40788 });
40789 /**
40790 @module @ember/runloop
40791 */
40792 // ..........................................................
40793 // run - this is ideally the only public API the dev sees
40794 //
40795
40796 /**
40797 Runs the passed target and method inside of a RunLoop, ensuring any
40798 deferred actions including bindings and views updates are flushed at the
40799 end.
40800
40801 Normally you should not need to invoke this method yourself. However if
40802 you are implementing raw event handlers when interfacing with other
40803 libraries or plugins, you should probably wrap all of your code inside this
40804 call.
40805
40806 ```javascript
40807 import { run } from '@ember/runloop';
40808
40809 run(function() {
40810 // code to be executed within a RunLoop
40811 });
40812 ```
40813 @method run
40814 @for @ember/runloop
40815 @static
40816 @param {Object} [target] target of method to call
40817 @param {Function|String} method Method to invoke.
40818 May be a function or a string. If you pass a string
40819 then it will be looked up on the passed target.
40820 @param {Object} [args*] Any additional arguments you wish to pass to the method.
40821 @return {Object} return value from invoking the passed function.
40822 @public
40823 */
40824
40825 _exports.backburner = backburner;
40826
40827 function run() {
40828 return backburner.run(...arguments);
40829 } // used for the Ember.run global only
40830
40831
40832 var _globalsRun = run.bind(null);
40833 /**
40834 If no run-loop is present, it creates a new one. If a run loop is
40835 present it will queue itself to run on the existing run-loops action
40836 queue.
40837
40838 Please note: This is not for normal usage, and should be used sparingly.
40839
40840 If invoked when not within a run loop:
40841
40842 ```javascript
40843 import { join } from '@ember/runloop';
40844
40845 join(function() {
40846 // creates a new run-loop
40847 });
40848 ```
40849
40850 Alternatively, if called within an existing run loop:
40851
40852 ```javascript
40853 import { run, join } from '@ember/runloop';
40854
40855 run(function() {
40856 // creates a new run-loop
40857
40858 join(function() {
40859 // joins with the existing run-loop, and queues for invocation on
40860 // the existing run-loops action queue.
40861 });
40862 });
40863 ```
40864
40865 @method join
40866 @static
40867 @for @ember/runloop
40868 @param {Object} [target] target of method to call
40869 @param {Function|String} method Method to invoke.
40870 May be a function or a string. If you pass a string
40871 then it will be looked up on the passed target.
40872 @param {Object} [args*] Any additional arguments you wish to pass to the method.
40873 @return {Object} Return value from invoking the passed function. Please note,
40874 when called within an existing loop, no return value is possible.
40875 @public
40876 */
40877
40878
40879 _exports._globalsRun = _globalsRun;
40880
40881 function join() {
40882 return backburner.join(...arguments);
40883 }
40884 /**
40885 Allows you to specify which context to call the specified function in while
40886 adding the execution of that function to the Ember run loop. This ability
40887 makes this method a great way to asynchronously integrate third-party libraries
40888 into your Ember application.
40889
40890 `bind` takes two main arguments, the desired context and the function to
40891 invoke in that context. Any additional arguments will be supplied as arguments
40892 to the function that is passed in.
40893
40894 Let's use the creation of a TinyMCE component as an example. Currently,
40895 TinyMCE provides a setup configuration option we can use to do some processing
40896 after the TinyMCE instance is initialized but before it is actually rendered.
40897 We can use that setup option to do some additional setup for our component.
40898 The component itself could look something like the following:
40899
40900 ```app/components/rich-text-editor.js
40901 import Component from '@ember/component';
40902 import { on } from '@ember/object/evented';
40903 import { bind } from '@ember/runloop';
40904
40905 export default Component.extend({
40906 initializeTinyMCE: on('didInsertElement', function() {
40907 tinymce.init({
40908 selector: '#' + this.$().prop('id'),
40909 setup: bind(this, this.setupEditor)
40910 });
40911 }),
40912
40913 didInsertElement() {
40914 tinymce.init({
40915 selector: '#' + this.$().prop('id'),
40916 setup: bind(this, this.setupEditor)
40917 });
40918 }
40919
40920 setupEditor(editor) {
40921 this.set('editor', editor);
40922
40923 editor.on('change', function() {
40924 console.log('content changed!');
40925 });
40926 }
40927 });
40928 ```
40929
40930 In this example, we use `bind` to bind the setupEditor method to the
40931 context of the RichTextEditor component and to have the invocation of that
40932 method be safely handled and executed by the Ember run loop.
40933
40934 @method bind
40935 @static
40936 @for @ember/runloop
40937 @param {Object} [target] target of method to call
40938 @param {Function|String} method Method to invoke.
40939 May be a function or a string. If you pass a string
40940 then it will be looked up on the passed target.
40941 @param {Object} [args*] Any additional arguments you wish to pass to the method.
40942 @return {Function} returns a new function that will always have a particular context
40943 @since 1.4.0
40944 @public
40945 */
40946
40947
40948 var bind = (...curried) => {
40949 (true && !(function (methodOrTarget, methodOrArg) {
40950 // Applies the same logic as backburner parseArgs for detecting if a method
40951 // is actually being passed.
40952 var length = arguments.length;
40953
40954 if (length === 0) {
40955 return false;
40956 } else if (length === 1) {
40957 return typeof methodOrTarget === 'function';
40958 } else {
40959 var type = typeof methodOrArg;
40960 return type === 'function' || // second argument is a function
40961 methodOrTarget !== null && type === 'string' && methodOrArg in methodOrTarget || // second argument is the name of a method in first argument
40962 typeof methodOrTarget === 'function' //first argument is a function
40963 ;
40964 }
40965 }(...curried)) && (0, _debug.assert)('could not find a suitable method to bind', function (methodOrTarget, methodOrArg) {
40966 var length = arguments.length;
40967
40968 if (length === 0) {
40969 return false;
40970 } else if (length === 1) {
40971 return typeof methodOrTarget === 'function';
40972 } else {
40973 var type = typeof methodOrArg;
40974 return type === 'function' || methodOrTarget !== null && type === 'string' && methodOrArg in methodOrTarget || typeof methodOrTarget === 'function';
40975 }
40976 }(...curried)));
40977 return (...args) => join(...curried.concat(args));
40978 };
40979 /**
40980 Begins a new RunLoop. Any deferred actions invoked after the begin will
40981 be buffered until you invoke a matching call to `end()`. This is
40982 a lower-level way to use a RunLoop instead of using `run()`.
40983
40984 ```javascript
40985 import { begin, end } from '@ember/runloop';
40986
40987 begin();
40988 // code to be executed within a RunLoop
40989 end();
40990 ```
40991
40992 @method begin
40993 @static
40994 @for @ember/runloop
40995 @return {void}
40996 @public
40997 */
40998
40999
41000 _exports.bind = bind;
41001
41002 function begin() {
41003 backburner.begin();
41004 }
41005 /**
41006 Ends a RunLoop. This must be called sometime after you call
41007 `begin()` to flush any deferred actions. This is a lower-level way
41008 to use a RunLoop instead of using `run()`.
41009
41010 ```javascript
41011 import { begin, end } from '@ember/runloop';
41012
41013 begin();
41014 // code to be executed within a RunLoop
41015 end();
41016 ```
41017
41018 @method end
41019 @static
41020 @for @ember/runloop
41021 @return {void}
41022 @public
41023 */
41024
41025
41026 function end() {
41027 backburner.end();
41028 }
41029 /**
41030 Adds the passed target/method and any optional arguments to the named
41031 queue to be executed at the end of the RunLoop. If you have not already
41032 started a RunLoop when calling this method one will be started for you
41033 automatically.
41034
41035 At the end of a RunLoop, any methods scheduled in this way will be invoked.
41036 Methods will be invoked in an order matching the named queues defined in
41037 the `queues` property.
41038
41039 ```javascript
41040 import { schedule } from '@ember/runloop';
41041
41042 schedule('afterRender', this, function() {
41043 // this will be executed in the 'afterRender' queue
41044 console.log('scheduled on afterRender queue');
41045 });
41046
41047 schedule('actions', this, function() {
41048 // this will be executed in the 'actions' queue
41049 console.log('scheduled on actions queue');
41050 });
41051
41052 // Note the functions will be run in order based on the run queues order.
41053 // Output would be:
41054 // scheduled on actions queue
41055 // scheduled on afterRender queue
41056 ```
41057
41058 @method schedule
41059 @static
41060 @for @ember/runloop
41061 @param {String} queue The name of the queue to schedule against. Default queues is 'actions'
41062 @param {Object} [target] target object to use as the context when invoking a method.
41063 @param {String|Function} method The method to invoke. If you pass a string it
41064 will be resolved on the target object at the time the scheduled item is
41065 invoked allowing you to change the target function.
41066 @param {Object} [arguments*] Optional arguments to be passed to the queued method.
41067 @return {*} Timer information for use in canceling, see `cancel`.
41068 @public
41069 */
41070
41071
41072 function schedule()
41073 /* queue, target, method */
41074 {
41075 return backburner.schedule(...arguments);
41076 } // Used by global test teardown
41077
41078
41079 function hasScheduledTimers() {
41080 return backburner.hasTimers();
41081 } // Used by global test teardown
41082
41083
41084 function cancelTimers() {
41085 backburner.cancelTimers();
41086 }
41087 /**
41088 Invokes the passed target/method and optional arguments after a specified
41089 period of time. The last parameter of this method must always be a number
41090 of milliseconds.
41091
41092 You should use this method whenever you need to run some action after a
41093 period of time instead of using `setTimeout()`. This method will ensure that
41094 items that expire during the same script execution cycle all execute
41095 together, which is often more efficient than using a real setTimeout.
41096
41097 ```javascript
41098 import { later } from '@ember/runloop';
41099
41100 later(myContext, function() {
41101 // code here will execute within a RunLoop in about 500ms with this == myContext
41102 }, 500);
41103 ```
41104
41105 @method later
41106 @static
41107 @for @ember/runloop
41108 @param {Object} [target] target of method to invoke
41109 @param {Function|String} method The method to invoke.
41110 If you pass a string it will be resolved on the
41111 target at the time the method is invoked.
41112 @param {Object} [args*] Optional arguments to pass to the timeout.
41113 @param {Number} wait Number of milliseconds to wait.
41114 @return {*} Timer information for use in canceling, see `cancel`.
41115 @public
41116 */
41117
41118
41119 function later()
41120 /*target, method*/
41121 {
41122 return backburner.later(...arguments);
41123 }
41124 /**
41125 Schedule a function to run one time during the current RunLoop. This is equivalent
41126 to calling `scheduleOnce` with the "actions" queue.
41127
41128 @method once
41129 @static
41130 @for @ember/runloop
41131 @param {Object} [target] The target of the method to invoke.
41132 @param {Function|String} method The method to invoke.
41133 If you pass a string it will be resolved on the
41134 target at the time the method is invoked.
41135 @param {Object} [args*] Optional arguments to pass to the timeout.
41136 @return {Object} Timer information for use in canceling, see `cancel`.
41137 @public
41138 */
41139
41140
41141 function once(...args) {
41142 args.unshift('actions');
41143 return backburner.scheduleOnce(...args);
41144 }
41145 /**
41146 Schedules a function to run one time in a given queue of the current RunLoop.
41147 Calling this method with the same queue/target/method combination will have
41148 no effect (past the initial call).
41149
41150 Note that although you can pass optional arguments these will not be
41151 considered when looking for duplicates. New arguments will replace previous
41152 calls.
41153
41154 ```javascript
41155 import { run, scheduleOnce } from '@ember/runloop';
41156
41157 function sayHi() {
41158 console.log('hi');
41159 }
41160
41161 run(function() {
41162 scheduleOnce('afterRender', myContext, sayHi);
41163 scheduleOnce('afterRender', myContext, sayHi);
41164 // sayHi will only be executed once, in the afterRender queue of the RunLoop
41165 });
41166 ```
41167
41168 Also note that for `scheduleOnce` to prevent additional calls, you need to
41169 pass the same function instance. The following case works as expected:
41170
41171 ```javascript
41172 function log() {
41173 console.log('Logging only once');
41174 }
41175
41176 function scheduleIt() {
41177 scheduleOnce('actions', myContext, log);
41178 }
41179
41180 scheduleIt();
41181 scheduleIt();
41182 ```
41183
41184 But this other case will schedule the function multiple times:
41185
41186 ```javascript
41187 import { scheduleOnce } from '@ember/runloop';
41188
41189 function scheduleIt() {
41190 scheduleOnce('actions', myContext, function() {
41191 console.log('Closure');
41192 });
41193 }
41194
41195 scheduleIt();
41196 scheduleIt();
41197
41198 // "Closure" will print twice, even though we're using `scheduleOnce`,
41199 // because the function we pass to it won't match the
41200 // previously scheduled operation.
41201 ```
41202
41203 Available queues, and their order, can be found at `queues`
41204
41205 @method scheduleOnce
41206 @static
41207 @for @ember/runloop
41208 @param {String} [queue] The name of the queue to schedule against. Default queues is 'actions'.
41209 @param {Object} [target] The target of the method to invoke.
41210 @param {Function|String} method The method to invoke.
41211 If you pass a string it will be resolved on the
41212 target at the time the method is invoked.
41213 @param {Object} [args*] Optional arguments to pass to the timeout.
41214 @return {Object} Timer information for use in canceling, see `cancel`.
41215 @public
41216 */
41217
41218
41219 function scheduleOnce()
41220 /* queue, target, method*/
41221 {
41222 return backburner.scheduleOnce(...arguments);
41223 }
41224 /**
41225 Schedules an item to run from within a separate run loop, after
41226 control has been returned to the system. This is equivalent to calling
41227 `later` with a wait time of 1ms.
41228
41229 ```javascript
41230 import { next } from '@ember/runloop';
41231
41232 next(myContext, function() {
41233 // code to be executed in the next run loop,
41234 // which will be scheduled after the current one
41235 });
41236 ```
41237
41238 Multiple operations scheduled with `next` will coalesce
41239 into the same later run loop, along with any other operations
41240 scheduled by `later` that expire right around the same
41241 time that `next` operations will fire.
41242
41243 Note that there are often alternatives to using `next`.
41244 For instance, if you'd like to schedule an operation to happen
41245 after all DOM element operations have completed within the current
41246 run loop, you can make use of the `afterRender` run loop queue (added
41247 by the `ember-views` package, along with the preceding `render` queue
41248 where all the DOM element operations happen).
41249
41250 Example:
41251
41252 ```app/components/my-component.js
41253 import Component from '@ember/component';
41254 import { scheduleOnce } from '@ember/runloop';
41255
41256 export Component.extend({
41257 didInsertElement() {
41258 this._super(...arguments);
41259 scheduleOnce('afterRender', this, 'processChildElements');
41260 },
41261
41262 processChildElements() {
41263 // ... do something with component's child component
41264 // elements after they've finished rendering, which
41265 // can't be done within this component's
41266 // `didInsertElement` hook because that gets run
41267 // before the child elements have been added to the DOM.
41268 }
41269 });
41270 ```
41271
41272 One benefit of the above approach compared to using `next` is
41273 that you will be able to perform DOM/CSS operations before unprocessed
41274 elements are rendered to the screen, which may prevent flickering or
41275 other artifacts caused by delaying processing until after rendering.
41276
41277 The other major benefit to the above approach is that `next`
41278 introduces an element of non-determinism, which can make things much
41279 harder to test, due to its reliance on `setTimeout`; it's much harder
41280 to guarantee the order of scheduled operations when they are scheduled
41281 outside of the current run loop, i.e. with `next`.
41282
41283 @method next
41284 @static
41285 @for @ember/runloop
41286 @param {Object} [target] target of method to invoke
41287 @param {Function|String} method The method to invoke.
41288 If you pass a string it will be resolved on the
41289 target at the time the method is invoked.
41290 @param {Object} [args*] Optional arguments to pass to the timeout.
41291 @return {Object} Timer information for use in canceling, see `cancel`.
41292 @public
41293 */
41294
41295
41296 function next(...args) {
41297 args.push(1);
41298 return backburner.later(...args);
41299 }
41300 /**
41301 Cancels a scheduled item. Must be a value returned by `later()`,
41302 `once()`, `scheduleOnce()`, `next()`, `debounce()`, or
41303 `throttle()`.
41304
41305 ```javascript
41306 import {
41307 next,
41308 cancel,
41309 later,
41310 scheduleOnce,
41311 once,
41312 throttle,
41313 debounce
41314 } from '@ember/runloop';
41315
41316 let runNext = next(myContext, function() {
41317 // will not be executed
41318 });
41319
41320 cancel(runNext);
41321
41322 let runLater = later(myContext, function() {
41323 // will not be executed
41324 }, 500);
41325
41326 cancel(runLater);
41327
41328 let runScheduleOnce = scheduleOnce('afterRender', myContext, function() {
41329 // will not be executed
41330 });
41331
41332 cancel(runScheduleOnce);
41333
41334 let runOnce = once(myContext, function() {
41335 // will not be executed
41336 });
41337
41338 cancel(runOnce);
41339
41340 let throttle = throttle(myContext, function() {
41341 // will not be executed
41342 }, 1, false);
41343
41344 cancel(throttle);
41345
41346 let debounce = debounce(myContext, function() {
41347 // will not be executed
41348 }, 1);
41349
41350 cancel(debounce);
41351
41352 let debounceImmediate = debounce(myContext, function() {
41353 // will be executed since we passed in true (immediate)
41354 }, 100, true);
41355
41356 // the 100ms delay until this method can be called again will be canceled
41357 cancel(debounceImmediate);
41358 ```
41359
41360 @method cancel
41361 @static
41362 @for @ember/runloop
41363 @param {Object} timer Timer object to cancel
41364 @return {Boolean} true if canceled or false/undefined if it wasn't found
41365 @public
41366 */
41367
41368
41369 function cancel(timer) {
41370 return backburner.cancel(timer);
41371 }
41372 /**
41373 Delay calling the target method until the debounce period has elapsed
41374 with no additional debounce calls. If `debounce` is called again before
41375 the specified time has elapsed, the timer is reset and the entire period
41376 must pass again before the target method is called.
41377
41378 This method should be used when an event may be called multiple times
41379 but the action should only be called once when the event is done firing.
41380 A common example is for scroll events where you only want updates to
41381 happen once scrolling has ceased.
41382
41383 ```javascript
41384 import { debounce } from '@ember/runloop';
41385
41386 function whoRan() {
41387 console.log(this.name + ' ran.');
41388 }
41389
41390 let myContext = { name: 'debounce' };
41391
41392 debounce(myContext, whoRan, 150);
41393
41394 // less than 150ms passes
41395 debounce(myContext, whoRan, 150);
41396
41397 // 150ms passes
41398 // whoRan is invoked with context myContext
41399 // console logs 'debounce ran.' one time.
41400 ```
41401
41402 Immediate allows you to run the function immediately, but debounce
41403 other calls for this function until the wait time has elapsed. If
41404 `debounce` is called again before the specified time has elapsed,
41405 the timer is reset and the entire period must pass again before
41406 the method can be called again.
41407
41408 ```javascript
41409 import { debounce } from '@ember/runloop';
41410
41411 function whoRan() {
41412 console.log(this.name + ' ran.');
41413 }
41414
41415 let myContext = { name: 'debounce' };
41416
41417 debounce(myContext, whoRan, 150, true);
41418
41419 // console logs 'debounce ran.' one time immediately.
41420 // 100ms passes
41421 debounce(myContext, whoRan, 150, true);
41422
41423 // 150ms passes and nothing else is logged to the console and
41424 // the debouncee is no longer being watched
41425 debounce(myContext, whoRan, 150, true);
41426
41427 // console logs 'debounce ran.' one time immediately.
41428 // 150ms passes and nothing else is logged to the console and
41429 // the debouncee is no longer being watched
41430 ```
41431
41432 @method debounce
41433 @static
41434 @for @ember/runloop
41435 @param {Object} [target] target of method to invoke
41436 @param {Function|String} method The method to invoke.
41437 May be a function or a string. If you pass a string
41438 then it will be looked up on the passed target.
41439 @param {Object} [args*] Optional arguments to pass to the timeout.
41440 @param {Number} wait Number of milliseconds to wait.
41441 @param {Boolean} immediate Trigger the function on the leading instead
41442 of the trailing edge of the wait interval. Defaults to false.
41443 @return {Array} Timer information for use in canceling, see `cancel`.
41444 @public
41445 */
41446
41447
41448 function debounce() {
41449 return backburner.debounce(...arguments);
41450 }
41451 /**
41452 Ensure that the target method is never called more frequently than
41453 the specified spacing period. The target method is called immediately.
41454
41455 ```javascript
41456 import { throttle } from '@ember/runloop';
41457
41458 function whoRan() {
41459 console.log(this.name + ' ran.');
41460 }
41461
41462 let myContext = { name: 'throttle' };
41463
41464 throttle(myContext, whoRan, 150);
41465 // whoRan is invoked with context myContext
41466 // console logs 'throttle ran.'
41467
41468 // 50ms passes
41469 throttle(myContext, whoRan, 150);
41470
41471 // 50ms passes
41472 throttle(myContext, whoRan, 150);
41473
41474 // 150ms passes
41475 throttle(myContext, whoRan, 150);
41476 // whoRan is invoked with context myContext
41477 // console logs 'throttle ran.'
41478 ```
41479
41480 @method throttle
41481 @static
41482 @for @ember/runloop
41483 @param {Object} [target] target of method to invoke
41484 @param {Function|String} method The method to invoke.
41485 May be a function or a string. If you pass a string
41486 then it will be looked up on the passed target.
41487 @param {Object} [args*] Optional arguments to pass to the timeout.
41488 @param {Number} spacing Number of milliseconds to space out requests.
41489 @param {Boolean} immediate Trigger the function on the leading instead
41490 of the trailing edge of the wait interval. Defaults to true.
41491 @return {Array} Timer information for use in canceling, see `cancel`.
41492 @public
41493 */
41494
41495
41496 function throttle() {
41497 return backburner.throttle(...arguments);
41498 }
41499});
41500define("@ember/service/index", ["exports", "@ember/-internals/runtime", "@ember/-internals/metal"], function (_exports, _runtime, _metal) {
41501 "use strict";
41502
41503 Object.defineProperty(_exports, "__esModule", {
41504 value: true
41505 });
41506 _exports.inject = inject;
41507 _exports.default = void 0;
41508
41509 /**
41510 @module @ember/service
41511 @public
41512 */
41513
41514 /**
41515 Creates a property that lazily looks up a service in the container. There are
41516 no restrictions as to what objects a service can be injected into.
41517
41518 Example:
41519
41520 ```app/routes/application.js
41521 import Route from '@ember/routing/route';
41522 import { inject as service } from '@ember/service';
41523
41524 export default class ApplicationRoute extends Route {
41525 @service('auth') authManager;
41526
41527 model() {
41528 return this.authManager.findCurrentUser();
41529 }
41530 }
41531 ```
41532
41533 Classic Class Example:
41534
41535 ```app/routes/application.js
41536 import Route from '@ember/routing/route';
41537 import { inject as service } from '@ember/service';
41538
41539 export default Route.extend({
41540 authManager: service('auth'),
41541
41542 model() {
41543 return this.get('authManager').findCurrentUser();
41544 }
41545 });
41546 ```
41547
41548 This example will create an `authManager` property on the application route
41549 that looks up the `auth` service in the container, making it easily accessible
41550 in the `model` hook.
41551
41552 @method inject
41553 @static
41554 @since 1.10.0
41555 @for @ember/service
41556 @param {String} name (optional) name of the service to inject, defaults to
41557 the property's name
41558 @return {ComputedDecorator} injection decorator instance
41559 @public
41560 */
41561 function inject() {
41562 return (0, _metal.inject)('service', ...arguments);
41563 }
41564 /**
41565 @class Service
41566 @extends EmberObject
41567 @since 1.10.0
41568 @public
41569 */
41570
41571
41572 var Service = _runtime.FrameworkObject.extend();
41573
41574 Service.reopenClass({
41575 isServiceFactory: true
41576 });
41577 var _default = Service;
41578 _exports.default = _default;
41579});
41580define("@ember/string/index", ["exports", "@ember/string/lib/string_registry", "@ember/-internals/environment", "@ember/-internals/utils"], function (_exports, _string_registry, _environment, _utils) {
41581 "use strict";
41582
41583 Object.defineProperty(_exports, "__esModule", {
41584 value: true
41585 });
41586 _exports.loc = loc;
41587 _exports.w = w;
41588 _exports.decamelize = decamelize;
41589 _exports.dasherize = dasherize;
41590 _exports.camelize = camelize;
41591 _exports.classify = classify;
41592 _exports.underscore = underscore;
41593 _exports.capitalize = capitalize;
41594 Object.defineProperty(_exports, "_getStrings", {
41595 enumerable: true,
41596 get: function () {
41597 return _string_registry.getStrings;
41598 }
41599 });
41600 Object.defineProperty(_exports, "_setStrings", {
41601 enumerable: true,
41602 get: function () {
41603 return _string_registry.setStrings;
41604 }
41605 });
41606
41607 /**
41608 @module @ember/string
41609 */
41610 var STRING_DASHERIZE_REGEXP = /[ _]/g;
41611 var STRING_DASHERIZE_CACHE = new _utils.Cache(1000, key => decamelize(key).replace(STRING_DASHERIZE_REGEXP, '-'));
41612 var STRING_CAMELIZE_REGEXP_1 = /(-|_|\.|\s)+(.)?/g;
41613 var STRING_CAMELIZE_REGEXP_2 = /(^|\/)([A-Z])/g;
41614 var 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
41615 /*, separator, chr */
41616 ) => match.toLowerCase()));
41617 var STRING_CLASSIFY_REGEXP_1 = /^(-|_)+(.)?/;
41618 var STRING_CLASSIFY_REGEXP_2 = /(.)(-|_|\.|\s)+(.)?/g;
41619 var STRING_CLASSIFY_REGEXP_3 = /(^|\/|\.)([a-z])/g;
41620 var CLASSIFY_CACHE = new _utils.Cache(1000, str => {
41621 var replace1 = (_match, _separator, chr) => chr ? `_${chr.toUpperCase()}` : '';
41622
41623 var replace2 = (_match, initialChar, _separator, chr) => initialChar + (chr ? chr.toUpperCase() : '');
41624
41625 var parts = str.split('/');
41626
41627 for (var i = 0; i < parts.length; i++) {
41628 parts[i] = parts[i].replace(STRING_CLASSIFY_REGEXP_1, replace1).replace(STRING_CLASSIFY_REGEXP_2, replace2);
41629 }
41630
41631 return parts.join('/').replace(STRING_CLASSIFY_REGEXP_3, (match
41632 /*, separator, chr */
41633 ) => match.toUpperCase());
41634 });
41635 var STRING_UNDERSCORE_REGEXP_1 = /([a-z\d])([A-Z]+)/g;
41636 var STRING_UNDERSCORE_REGEXP_2 = /-|\s+/g;
41637 var UNDERSCORE_CACHE = new _utils.Cache(1000, str => str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2').replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase());
41638 var STRING_CAPITALIZE_REGEXP = /(^|\/)([a-z\u00C0-\u024F])/g;
41639 var CAPITALIZE_CACHE = new _utils.Cache(1000, str => str.replace(STRING_CAPITALIZE_REGEXP, (match
41640 /*, separator, chr */
41641 ) => match.toUpperCase()));
41642 var STRING_DECAMELIZE_REGEXP = /([a-z\d])([A-Z])/g;
41643 var DECAMELIZE_CACHE = new _utils.Cache(1000, str => str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase());
41644 /**
41645 Defines string helper methods including string formatting and localization.
41646 Unless `EmberENV.EXTEND_PROTOTYPES.String` is `false` these methods will also be
41647 added to the `String.prototype` as well.
41648
41649 @class String
41650 @public
41651 */
41652
41653 function _fmt(str, formats) {
41654 // first, replace any ORDERED replacements.
41655 var idx = 0; // the current index for non-numerical replacements
41656
41657 return str.replace(/%@([0-9]+)?/g, (_s, argIndex) => {
41658 var i = argIndex ? parseInt(argIndex, 10) - 1 : idx++;
41659 var r = i < formats.length ? formats[i] : undefined;
41660 return typeof r === 'string' ? r : r === null ? '(null)' : r === undefined ? '' : String(r);
41661 });
41662 }
41663 /**
41664 Formats the passed string, but first looks up the string in the localized
41665 strings hash. This is a convenient way to localize text.
41666
41667 Note that it is traditional but not required to prefix localized string
41668 keys with an underscore or other character so you can easily identify
41669 localized strings.
41670
41671 ```javascript
41672 import { loc } from '@ember/string';
41673
41674 Ember.STRINGS = {
41675 '_Hello World': 'Bonjour le monde',
41676 '_Hello %@ %@': 'Bonjour %@ %@'
41677 };
41678
41679 loc("_Hello World"); // 'Bonjour le monde';
41680 loc("_Hello %@ %@", ["John", "Smith"]); // "Bonjour John Smith";
41681 ```
41682
41683 @method loc
41684 @param {String} str The string to format
41685 @param {Array} formats Optional array of parameters to interpolate into string.
41686 @return {String} formatted string
41687 @public
41688 */
41689
41690
41691 function loc(str, formats) {
41692 if (!Array.isArray(formats) || arguments.length > 2) {
41693 formats = Array.prototype.slice.call(arguments, 1);
41694 }
41695
41696 str = (0, _string_registry.getString)(str) || str;
41697 return _fmt(str, formats);
41698 }
41699 /**
41700 Splits a string into separate units separated by spaces, eliminating any
41701 empty strings in the process. This is a convenience method for split that
41702 is mostly useful when applied to the `String.prototype`.
41703
41704 ```javascript
41705 import { w } from '@ember/string';
41706
41707 w("alpha beta gamma").forEach(function(key) {
41708 console.log(key);
41709 });
41710
41711 // > alpha
41712 // > beta
41713 // > gamma
41714 ```
41715
41716 @method w
41717 @param {String} str The string to split
41718 @return {Array} array containing the split strings
41719 @public
41720 */
41721
41722
41723 function w(str) {
41724 return str.split(/\s+/);
41725 }
41726 /**
41727 Converts a camelized string into all lower case separated by underscores.
41728
41729 ```javascript
41730 import { decamelize } from '@ember/string';
41731
41732 decamelize('innerHTML'); // 'inner_html'
41733 decamelize('action_name'); // 'action_name'
41734 decamelize('css-class-name'); // 'css-class-name'
41735 decamelize('my favorite items'); // 'my favorite items'
41736 ```
41737
41738 @method decamelize
41739 @param {String} str The string to decamelize.
41740 @return {String} the decamelized string.
41741 @public
41742 */
41743
41744
41745 function decamelize(str) {
41746 return DECAMELIZE_CACHE.get(str);
41747 }
41748 /**
41749 Replaces underscores, spaces, or camelCase with dashes.
41750
41751 ```javascript
41752 import { dasherize } from '@ember/string';
41753
41754 dasherize('innerHTML'); // 'inner-html'
41755 dasherize('action_name'); // 'action-name'
41756 dasherize('css-class-name'); // 'css-class-name'
41757 dasherize('my favorite items'); // 'my-favorite-items'
41758 dasherize('privateDocs/ownerInvoice'; // 'private-docs/owner-invoice'
41759 ```
41760
41761 @method dasherize
41762 @param {String} str The string to dasherize.
41763 @return {String} the dasherized string.
41764 @public
41765 */
41766
41767
41768 function dasherize(str) {
41769 return STRING_DASHERIZE_CACHE.get(str);
41770 }
41771 /**
41772 Returns the lowerCamelCase form of a string.
41773
41774 ```javascript
41775 import { camelize } from '@ember/string';
41776
41777 camelize('innerHTML'); // 'innerHTML'
41778 camelize('action_name'); // 'actionName'
41779 camelize('css-class-name'); // 'cssClassName'
41780 camelize('my favorite items'); // 'myFavoriteItems'
41781 camelize('My Favorite Items'); // 'myFavoriteItems'
41782 camelize('private-docs/owner-invoice'); // 'privateDocs/ownerInvoice'
41783 ```
41784
41785 @method camelize
41786 @param {String} str The string to camelize.
41787 @return {String} the camelized string.
41788 @public
41789 */
41790
41791
41792 function camelize(str) {
41793 return CAMELIZE_CACHE.get(str);
41794 }
41795 /**
41796 Returns the UpperCamelCase form of a string.
41797
41798 ```javascript
41799 import { classify } from '@ember/string';
41800
41801 classify('innerHTML'); // 'InnerHTML'
41802 classify('action_name'); // 'ActionName'
41803 classify('css-class-name'); // 'CssClassName'
41804 classify('my favorite items'); // 'MyFavoriteItems'
41805 classify('private-docs/owner-invoice'); // 'PrivateDocs/OwnerInvoice'
41806 ```
41807
41808 @method classify
41809 @param {String} str the string to classify
41810 @return {String} the classified string
41811 @public
41812 */
41813
41814
41815 function classify(str) {
41816 return CLASSIFY_CACHE.get(str);
41817 }
41818 /**
41819 More general than decamelize. Returns the lower\_case\_and\_underscored
41820 form of a string.
41821
41822 ```javascript
41823 import { underscore } from '@ember/string';
41824
41825 underscore('innerHTML'); // 'inner_html'
41826 underscore('action_name'); // 'action_name'
41827 underscore('css-class-name'); // 'css_class_name'
41828 underscore('my favorite items'); // 'my_favorite_items'
41829 underscore('privateDocs/ownerInvoice'); // 'private_docs/owner_invoice'
41830 ```
41831
41832 @method underscore
41833 @param {String} str The string to underscore.
41834 @return {String} the underscored string.
41835 @public
41836 */
41837
41838
41839 function underscore(str) {
41840 return UNDERSCORE_CACHE.get(str);
41841 }
41842 /**
41843 Returns the Capitalized form of a string
41844
41845 ```javascript
41846 import { capitalize } from '@ember/string';
41847
41848 capitalize('innerHTML') // 'InnerHTML'
41849 capitalize('action_name') // 'Action_name'
41850 capitalize('css-class-name') // 'Css-class-name'
41851 capitalize('my favorite items') // 'My favorite items'
41852 capitalize('privateDocs/ownerInvoice'); // 'PrivateDocs/ownerInvoice'
41853 ```
41854
41855 @method capitalize
41856 @param {String} str The string to capitalize.
41857 @return {String} The capitalized string.
41858 @public
41859 */
41860
41861
41862 function capitalize(str) {
41863 return CAPITALIZE_CACHE.get(str);
41864 }
41865
41866 if (_environment.ENV.EXTEND_PROTOTYPES.String) {
41867 Object.defineProperties(String.prototype, {
41868 /**
41869 See [String.w](/ember/release/classes/String/methods/w?anchor=w).
41870 @method w
41871 @for @ember/string
41872 @static
41873 @private
41874 */
41875 w: {
41876 configurable: true,
41877 enumerable: false,
41878 writeable: true,
41879
41880 value() {
41881 return w(this);
41882 }
41883
41884 },
41885
41886 /**
41887 See [String.loc](/ember/release/classes/String/methods/loc?anchor=loc).
41888 @method loc
41889 @for @ember/string
41890 @static
41891 @private
41892 */
41893 loc: {
41894 configurable: true,
41895 enumerable: false,
41896 writeable: true,
41897
41898 value(...args) {
41899 return loc(this, args);
41900 }
41901
41902 },
41903
41904 /**
41905 See [String.camelize](/ember/release/classes/String/methods/camelize?anchor=camelize).
41906 @method camelize
41907 @for @ember/string
41908 @static
41909 @private
41910 */
41911 camelize: {
41912 configurable: true,
41913 enumerable: false,
41914 writeable: true,
41915
41916 value() {
41917 return camelize(this);
41918 }
41919
41920 },
41921
41922 /**
41923 See [String.decamelize](/ember/release/classes/String/methods/decamelize?anchor=decamelize).
41924 @method decamelize
41925 @for @ember/string
41926 @static
41927 @private
41928 */
41929 decamelize: {
41930 configurable: true,
41931 enumerable: false,
41932 writeable: true,
41933
41934 value() {
41935 return decamelize(this);
41936 }
41937
41938 },
41939
41940 /**
41941 See [String.dasherize](/ember/release/classes/String/methods/dasherize?anchor=dasherize).
41942 @method dasherize
41943 @for @ember/string
41944 @static
41945 @private
41946 */
41947 dasherize: {
41948 configurable: true,
41949 enumerable: false,
41950 writeable: true,
41951
41952 value() {
41953 return dasherize(this);
41954 }
41955
41956 },
41957
41958 /**
41959 See [String.underscore](/ember/release/classes/String/methods/underscore?anchor=underscore).
41960 @method underscore
41961 @for @ember/string
41962 @static
41963 @private
41964 */
41965 underscore: {
41966 configurable: true,
41967 enumerable: false,
41968 writeable: true,
41969
41970 value() {
41971 return underscore(this);
41972 }
41973
41974 },
41975
41976 /**
41977 See [String.classify](/ember/release/classes/String/methods/classify?anchor=classify).
41978 @method classify
41979 @for @ember/string
41980 @static
41981 @private
41982 */
41983 classify: {
41984 configurable: true,
41985 enumerable: false,
41986 writeable: true,
41987
41988 value() {
41989 return classify(this);
41990 }
41991
41992 },
41993
41994 /**
41995 See [String.capitalize](/ember/release/classes/String/methods/capitalize?anchor=capitalize).
41996 @method capitalize
41997 @for @ember/string
41998 @static
41999 @private
42000 */
42001 capitalize: {
42002 configurable: true,
42003 enumerable: false,
42004 writeable: true,
42005
42006 value() {
42007 return capitalize(this);
42008 }
42009
42010 }
42011 });
42012 }
42013});
42014define("@ember/string/lib/string_registry", ["exports"], function (_exports) {
42015 "use strict";
42016
42017 Object.defineProperty(_exports, "__esModule", {
42018 value: true
42019 });
42020 _exports.setStrings = setStrings;
42021 _exports.getStrings = getStrings;
42022 _exports.getString = getString;
42023 // STATE within a module is frowned upon, this exists
42024 // to support Ember.STRINGS but shield ember internals from this legacy global
42025 // API.
42026 var STRINGS = {};
42027
42028 function setStrings(strings) {
42029 STRINGS = strings;
42030 }
42031
42032 function getStrings() {
42033 return STRINGS;
42034 }
42035
42036 function getString(name) {
42037 return STRINGS[name];
42038 }
42039});
42040define("@glimmer/encoder", ["exports"], function (_exports) {
42041 "use strict";
42042
42043 Object.defineProperty(_exports, "__esModule", {
42044 value: true
42045 });
42046 _exports.InstructionEncoderImpl = void 0;
42047
42048 class InstructionEncoderImpl {
42049 constructor(buffer) {
42050 this.buffer = buffer;
42051 this.size = 0;
42052 }
42053
42054 encode(type, machine) {
42055 if (type > 255
42056 /* TYPE_SIZE */
42057 ) {
42058 throw new Error(`Opcode type over 8-bits. Got ${type}.`);
42059 }
42060
42061 var first = type | machine | arguments.length - 2 << 8
42062 /* ARG_SHIFT */
42063 ;
42064 this.buffer.push(first);
42065
42066 for (var i = 2; i < arguments.length; i++) {
42067 var op = arguments[i];
42068
42069 if (typeof op === 'number' && op > 2147483647
42070 /* MAX_SIZE */
42071 ) {
42072 throw new Error(`Operand over 32-bits. Got ${op}.`);
42073 }
42074
42075 this.buffer.push(op);
42076 }
42077
42078 this.size = this.buffer.length;
42079 }
42080
42081 patch(position, target) {
42082 if (this.buffer[position + 1] === -1) {
42083 this.buffer[position + 1] = target;
42084 } else {
42085 throw new Error('Trying to patch operand in populated slot instead of a reserved slot.');
42086 }
42087 }
42088
42089 }
42090
42091 _exports.InstructionEncoderImpl = InstructionEncoderImpl;
42092});
42093define("@glimmer/env", ["exports"], function (_exports) {
42094 "use strict";
42095
42096 Object.defineProperty(_exports, "__esModule", {
42097 value: true
42098 });
42099 _exports.CI = _exports.DEBUG = void 0;
42100 var DEBUG = false;
42101 _exports.DEBUG = DEBUG;
42102 var CI = false;
42103 _exports.CI = CI;
42104});
42105define("@glimmer/low-level", ["exports"], function (_exports) {
42106 "use strict";
42107
42108 Object.defineProperty(_exports, "__esModule", {
42109 value: true
42110 });
42111 _exports.Stack = _exports.Storage = void 0;
42112
42113 class Storage {
42114 constructor() {
42115 this.array = [];
42116 this.next = 0;
42117 }
42118
42119 add(element) {
42120 var {
42121 next: slot,
42122 array
42123 } = this;
42124
42125 if (slot === array.length) {
42126 this.next++;
42127 } else {
42128 var prev = array[slot];
42129 this.next = prev;
42130 }
42131
42132 this.array[slot] = element;
42133 return slot;
42134 }
42135
42136 deref(pointer) {
42137 return this.array[pointer];
42138 }
42139
42140 drop(pointer) {
42141 this.array[pointer] = this.next;
42142 this.next = pointer;
42143 }
42144
42145 }
42146
42147 _exports.Storage = Storage;
42148
42149 class Stack {
42150 constructor(vec = []) {
42151 this.vec = vec;
42152 }
42153
42154 clone() {
42155 return new Stack(this.vec.slice());
42156 }
42157
42158 sliceFrom(start) {
42159 return new Stack(this.vec.slice(start));
42160 }
42161
42162 slice(start, end) {
42163 return new Stack(this.vec.slice(start, end));
42164 }
42165
42166 copy(from, to) {
42167 this.vec[to] = this.vec[from];
42168 } // TODO: how to model u64 argument?
42169
42170
42171 writeRaw(pos, value) {
42172 // TODO: Grow?
42173 this.vec[pos] = value;
42174 } // TODO: partially decoded enum?
42175
42176
42177 getRaw(pos) {
42178 return this.vec[pos];
42179 }
42180
42181 reset() {
42182 this.vec.length = 0;
42183 }
42184
42185 len() {
42186 return this.vec.length;
42187 }
42188
42189 }
42190
42191 _exports.Stack = Stack;
42192});
42193define("@glimmer/node", ["exports", "@glimmer/runtime", "@simple-dom/document"], function (_exports, _runtime, _document) {
42194 "use strict";
42195
42196 Object.defineProperty(_exports, "__esModule", {
42197 value: true
42198 });
42199 _exports.serializeBuilder = serializeBuilder;
42200 _exports.NodeDOMTreeConstruction = void 0;
42201
42202 class NodeDOMTreeConstruction extends _runtime.DOMTreeConstruction {
42203 constructor(doc) {
42204 super(doc || (0, _document.default)());
42205 } // override to prevent usage of `this.document` until after the constructor
42206
42207
42208 setupUselessElement() {}
42209
42210 insertHTMLBefore(parent, reference, html) {
42211 var raw = this.document.createRawHTMLSection(html);
42212 parent.insertBefore(raw, reference);
42213 return new _runtime.ConcreteBounds(parent, raw, raw);
42214 } // override to avoid SVG detection/work when in node (this is not needed in SSR)
42215
42216
42217 createElement(tag) {
42218 return this.document.createElement(tag);
42219 } // override to avoid namespace shenanigans when in node (this is not needed in SSR)
42220
42221
42222 setAttribute(element, name, value) {
42223 element.setAttribute(name, value);
42224 }
42225
42226 }
42227
42228 _exports.NodeDOMTreeConstruction = NodeDOMTreeConstruction;
42229 var TEXT_NODE = 3;
42230 var NEEDS_EXTRA_CLOSE = new WeakMap();
42231
42232 function currentNode(cursor) {
42233 var {
42234 element,
42235 nextSibling
42236 } = cursor;
42237
42238 if (nextSibling === null) {
42239 return element.lastChild;
42240 } else {
42241 return nextSibling.previousSibling;
42242 }
42243 }
42244
42245 class SerializeBuilder extends _runtime.NewElementBuilder {
42246 constructor() {
42247 super(...arguments);
42248 this.serializeBlockDepth = 0;
42249 }
42250
42251 __openBlock() {
42252 var {
42253 tagName
42254 } = this.element;
42255
42256 if (tagName !== 'TITLE' && tagName !== 'SCRIPT' && tagName !== 'STYLE') {
42257 var depth = this.serializeBlockDepth++;
42258
42259 this.__appendComment(`%+b:${depth}%`);
42260 }
42261
42262 super.__openBlock();
42263 }
42264
42265 __closeBlock() {
42266 var {
42267 tagName
42268 } = this.element;
42269
42270 super.__closeBlock();
42271
42272 if (tagName !== 'TITLE' && tagName !== 'SCRIPT' && tagName !== 'STYLE') {
42273 var depth = --this.serializeBlockDepth;
42274
42275 this.__appendComment(`%-b:${depth}%`);
42276 }
42277 }
42278
42279 __appendHTML(html) {
42280 var {
42281 tagName
42282 } = this.element;
42283
42284 if (tagName === 'TITLE' || tagName === 'SCRIPT' || tagName === 'STYLE') {
42285 return super.__appendHTML(html);
42286 } // Do we need to run the html tokenizer here?
42287
42288
42289 var first = this.__appendComment('%glmr%');
42290
42291 if (tagName === 'TABLE') {
42292 var openIndex = html.indexOf('<');
42293
42294 if (openIndex > -1) {
42295 var tr = html.slice(openIndex + 1, openIndex + 3);
42296
42297 if (tr === 'tr') {
42298 html = `<tbody>${html}</tbody>`;
42299 }
42300 }
42301 }
42302
42303 if (html === '') {
42304 this.__appendComment('% %');
42305 } else {
42306 super.__appendHTML(html);
42307 }
42308
42309 var last = this.__appendComment('%glmr%');
42310
42311 return new _runtime.ConcreteBounds(this.element, first, last);
42312 }
42313
42314 __appendText(string) {
42315 var {
42316 tagName
42317 } = this.element;
42318 var current = currentNode(this);
42319
42320 if (tagName === 'TITLE' || tagName === 'SCRIPT' || tagName === 'STYLE') {
42321 return super.__appendText(string);
42322 } else if (string === '') {
42323 return this.__appendComment('% %');
42324 } else if (current && current.nodeType === TEXT_NODE) {
42325 this.__appendComment('%|%');
42326 }
42327
42328 return super.__appendText(string);
42329 }
42330
42331 closeElement() {
42332 if (NEEDS_EXTRA_CLOSE.has(this.element)) {
42333 NEEDS_EXTRA_CLOSE.delete(this.element);
42334 super.closeElement();
42335 }
42336
42337 return super.closeElement();
42338 }
42339
42340 openElement(tag) {
42341 if (tag === 'tr') {
42342 if (this.element.tagName !== 'TBODY' && this.element.tagName !== 'THEAD' && this.element.tagName !== 'TFOOT') {
42343 this.openElement('tbody'); // This prevents the closeBlock comment from being re-parented
42344 // under the auto inserted tbody. Rehydration builder needs to
42345 // account for the insertion since it is injected here and not
42346 // really in the template.
42347
42348 NEEDS_EXTRA_CLOSE.set(this.constructing, true);
42349 this.flushElement(null);
42350 }
42351 }
42352
42353 return super.openElement(tag);
42354 }
42355
42356 pushRemoteElement(element, cursorId, insertBefore = null) {
42357 var {
42358 dom
42359 } = this;
42360 var script = dom.createElement('script');
42361 script.setAttribute('glmr', cursorId);
42362 dom.insertBefore(element, script, insertBefore);
42363 return super.pushRemoteElement(element, cursorId, insertBefore);
42364 }
42365
42366 }
42367
42368 function serializeBuilder(env, cursor) {
42369 return SerializeBuilder.forInitialRender(env, cursor);
42370 }
42371});
42372define("@glimmer/opcode-compiler", ["exports", "@glimmer/vm", "@glimmer/util", "@glimmer/program", "@glimmer/encoder"], function (_exports, _vm, _util, _program, _encoder) {
42373 "use strict";
42374
42375 Object.defineProperty(_exports, "__esModule", {
42376 value: true
42377 });
42378 _exports.compileStatements = compileStatements;
42379 _exports.compilable = compilable;
42380 _exports.staticComponent = StaticComponent;
42381 _exports.invokeStaticBlockWithStack = InvokeStaticBlockWithStack;
42382 _exports.invokeStaticBlock = InvokeStaticBlock;
42383 _exports.compileStd = compileStd;
42384 _exports.meta = meta;
42385 _exports.templateFactory = templateFactory;
42386 _exports.Component = Component;
42387 _exports.resolveLayoutForTag = resolveLayoutForTag;
42388 _exports.syntaxCompilationContext = syntaxCompilationContext;
42389 _exports.Context = Context;
42390 _exports.JitContext = JitContext;
42391 _exports.AotContext = AotContext;
42392 _exports.templateCompilationContext = templateCompilationContext;
42393 _exports.DefaultCompileTimeResolverDelegate = _exports.MINIMAL_CAPABILITIES = _exports.DEFAULT_CAPABILITIES = _exports.JitProgramCompilationContext = _exports.ProgramCompilationContext = _exports.EMPTY_BLOCKS = _exports.WrappedBuilder = _exports.PartialDefinitionImpl = _exports.StdLib = _exports.debugCompiler = _exports.NONE = _exports.UNHANDLED = _exports.MacrosImpl = void 0;
42394
42395 function arr(value) {
42396 return {
42397 type: 'array',
42398 value
42399 };
42400 }
42401
42402 function strArray(value) {
42403 return {
42404 type: 'string-array',
42405 value
42406 };
42407 }
42408
42409 function serializable(value) {
42410 return {
42411 type: 'serializable',
42412 value
42413 };
42414 }
42415
42416 function templateMeta(value) {
42417 return {
42418 type: 'template-meta',
42419 value
42420 };
42421 }
42422
42423 function other(value) {
42424 return {
42425 type: 'other',
42426 value
42427 };
42428 }
42429
42430 function label(value) {
42431 return {
42432 type: 'label',
42433 value
42434 };
42435 }
42436
42437 function immediate(value) {
42438 return {
42439 type: 'immediate',
42440 value
42441 };
42442 }
42443
42444 function prim(value) {
42445 return {
42446 type: 'primitive',
42447 value
42448 };
42449 }
42450
42451 var DEFAULT_CAPABILITIES = {
42452 dynamicLayout: true,
42453 dynamicTag: true,
42454 prepareArgs: true,
42455 createArgs: true,
42456 attributeHook: false,
42457 elementHook: false,
42458 dynamicScope: true,
42459 createCaller: false,
42460 updateHook: true,
42461 createInstance: true,
42462 wrapped: false,
42463 willDestroy: false
42464 };
42465 _exports.DEFAULT_CAPABILITIES = DEFAULT_CAPABILITIES;
42466 var MINIMAL_CAPABILITIES = {
42467 dynamicLayout: false,
42468 dynamicTag: false,
42469 prepareArgs: false,
42470 createArgs: false,
42471 attributeHook: false,
42472 elementHook: false,
42473 dynamicScope: false,
42474 createCaller: false,
42475 updateHook: false,
42476 createInstance: false,
42477 wrapped: false,
42478 willDestroy: false
42479 };
42480 _exports.MINIMAL_CAPABILITIES = MINIMAL_CAPABILITIES;
42481
42482 class DefaultCompileTimeResolverDelegate {
42483 constructor(inner) {
42484 this.inner = inner;
42485 }
42486
42487 lookupHelper(name, referrer) {
42488 if (this.inner.lookupHelper) {
42489 var helper = this.inner.lookupHelper(name, referrer);
42490
42491 if (helper === undefined) {
42492 throw new Error(`Unexpected helper (${name} from ${JSON.stringify(referrer)}) (lookupHelper returned undefined)`);
42493 }
42494
42495 return helper;
42496 } else {
42497 throw new Error(`Can't compile global helper invocations without an implementation of lookupHelper`);
42498 }
42499 }
42500
42501 lookupModifier(name, referrer) {
42502 if (this.inner.lookupModifier) {
42503 var modifier = this.inner.lookupModifier(name, referrer);
42504
42505 if (modifier === undefined) {
42506 throw new Error(`Unexpected modifier (${name} from ${JSON.stringify(referrer)}) (lookupModifier returned undefined)`);
42507 }
42508
42509 return modifier;
42510 } else {
42511 throw new Error(`Can't compile global modifier invocations without an implementation of lookupModifier`);
42512 }
42513 }
42514
42515 lookupComponent(name, referrer) {
42516 if (this.inner.lookupComponent) {
42517 var component = this.inner.lookupComponent(name, referrer);
42518
42519 if (component === undefined) {
42520 throw new Error(`Unexpected component (${name} from ${JSON.stringify(referrer)}) (lookupComponent returned undefined)`);
42521 }
42522
42523 return component;
42524 } else {
42525 throw new Error(`Can't compile global component invocations without an implementation of lookupComponent`);
42526 }
42527 }
42528
42529 lookupPartial(name, referrer) {
42530 if (this.inner.lookupPartial) {
42531 var partial = this.inner.lookupPartial(name, referrer);
42532
42533 if (partial === undefined) {
42534 throw new Error(`Unexpected partial (${name} from ${JSON.stringify(referrer)}) (lookupPartial returned undefined)`);
42535 }
42536
42537 return partial;
42538 } else {
42539 throw new Error(`Can't compile global partial invocations without an implementation of lookupPartial`);
42540 }
42541 } // For debugging
42542
42543
42544 resolve(handle) {
42545 if (this.inner.resolve) {
42546 return this.inner.resolve(handle);
42547 } else {
42548 throw new Error(`Compile-time debugging requires an implementation of resolve`);
42549 }
42550 }
42551
42552 }
42553
42554 _exports.DefaultCompileTimeResolverDelegate = DefaultCompileTimeResolverDelegate;
42555
42556 function resolveLayoutForTag(tag, {
42557 resolver,
42558 meta: {
42559 referrer
42560 }
42561 }) {
42562 var component = resolver.lookupComponent(tag, referrer);
42563 if (component === null) return component;
42564 var {
42565 handle,
42566 compilable,
42567 capabilities
42568 } = component;
42569 return {
42570 handle,
42571 compilable,
42572 capabilities: capabilities || MINIMAL_CAPABILITIES
42573 };
42574 }
42575 /**
42576 * Push a reference onto the stack corresponding to a statically known primitive
42577 * @param value A JavaScript primitive (undefined, null, boolean, number or string)
42578 */
42579
42580
42581 function PushPrimitiveReference(value) {
42582 return [PushPrimitive(value), op(31
42583 /* PrimitiveReference */
42584 )];
42585 }
42586 /**
42587 * Push an encoded representation of a JavaScript primitive on the stack
42588 *
42589 * @param value A JavaScript primitive (undefined, null, boolean, number or string)
42590 */
42591
42592
42593 function PushPrimitive(primitive) {
42594 var p = typeof primitive === 'number' && (0, _util.isSmallInt)(primitive) ? immediate(primitive) : prim(primitive);
42595 return op(30
42596 /* Primitive */
42597 , p);
42598 }
42599 /**
42600 * Invoke a foreign function (a "helper") based on a statically known handle
42601 *
42602 * @param compile.handle A handle
42603 * @param compile.params An optional list of expressions to compile
42604 * @param compile.hash An optional list of named arguments (name + expression) to compile
42605 */
42606
42607
42608 function Call({
42609 handle,
42610 params,
42611 hash
42612 }) {
42613 return [op(0
42614 /* PushFrame */
42615 ), op('SimpleArgs', {
42616 params,
42617 hash,
42618 atNames: false
42619 }), op(16
42620 /* Helper */
42621 , handle), op(1
42622 /* PopFrame */
42623 ), op(36
42624 /* Fetch */
42625 , _vm.$v0)];
42626 }
42627 /**
42628 * Evaluate statements in the context of new dynamic scope entries. Move entries from the
42629 * stack into named entries in the dynamic scope, then evaluate the statements, then pop
42630 * the dynamic scope
42631 *
42632 * @param names a list of dynamic scope names
42633 * @param block a function that returns a list of statements to evaluate
42634 */
42635
42636
42637 function DynamicScope(names, block) {
42638 return [op(59
42639 /* PushDynamicScope */
42640 ), op(58
42641 /* BindDynamicScope */
42642 , strArray(names)), block(), op(60
42643 /* PopDynamicScope */
42644 )];
42645 }
42646 /**
42647 * Yield to a block located at a particular symbol location.
42648 *
42649 * @param to the symbol containing the block to yield to
42650 * @param params optional block parameters to yield to the block
42651 */
42652
42653
42654 function YieldBlock(to, params) {
42655 return [op('SimpleArgs', {
42656 params,
42657 hash: null,
42658 atNames: true
42659 }), op(24
42660 /* GetBlock */
42661 , to), op(25
42662 /* JitSpreadBlock */
42663 ), op('Option', op('JitCompileBlock')), op(64
42664 /* InvokeYield */
42665 ), op(40
42666 /* PopScope */
42667 ), op(1
42668 /* PopFrame */
42669 )];
42670 }
42671 /**
42672 * Push an (optional) yieldable block onto the stack. The yieldable block must be known
42673 * statically at compile time.
42674 *
42675 * @param block An optional Compilable block
42676 */
42677
42678
42679 function PushYieldableBlock(block) {
42680 return [PushSymbolTable(block && block.symbolTable), op(62
42681 /* PushBlockScope */
42682 ), op('PushCompilable', block)];
42683 }
42684 /**
42685 * Invoke a block that is known statically at compile time.
42686 *
42687 * @param block a Compilable block
42688 */
42689
42690
42691 function InvokeStaticBlock(block) {
42692 return [op(0
42693 /* PushFrame */
42694 ), op('PushCompilable', block), op('JitCompileBlock'), op(2
42695 /* InvokeVirtual */
42696 ), op(1
42697 /* PopFrame */
42698 )];
42699 }
42700 /**
42701 * Invoke a static block, preserving some number of stack entries for use in
42702 * updating.
42703 *
42704 * @param block A compilable block
42705 * @param callerCount A number of stack entries to preserve
42706 */
42707
42708
42709 function InvokeStaticBlockWithStack(block, callerCount) {
42710 var {
42711 parameters
42712 } = block.symbolTable;
42713 var calleeCount = parameters.length;
42714 var count = Math.min(callerCount, calleeCount);
42715
42716 if (count === 0) {
42717 return InvokeStaticBlock(block);
42718 }
42719
42720 var out = [];
42721 out.push(op(0
42722 /* PushFrame */
42723 ));
42724
42725 if (count) {
42726 out.push(op(39
42727 /* ChildScope */
42728 ));
42729
42730 for (var i = 0; i < count; i++) {
42731 out.push(op(33
42732 /* Dup */
42733 , _vm.$fp, callerCount - i));
42734 out.push(op(19
42735 /* SetVariable */
42736 , parameters[i]));
42737 }
42738 }
42739
42740 out.push(op('PushCompilable', block));
42741 out.push(op('JitCompileBlock'));
42742 out.push(op(2
42743 /* InvokeVirtual */
42744 ));
42745
42746 if (count) {
42747 out.push(op(40
42748 /* PopScope */
42749 ));
42750 }
42751
42752 out.push(op(1
42753 /* PopFrame */
42754 ));
42755 return out;
42756 }
42757
42758 function PushSymbolTable(table) {
42759 if (table) {
42760 return op(63
42761 /* PushSymbolTable */
42762 , serializable(table));
42763 } else {
42764 return PushPrimitive(null);
42765 }
42766 }
42767
42768 function SwitchCases(callback) {
42769 // Setup the switch DSL
42770 var clauses = [];
42771 var count = 0;
42772
42773 function when(match, callback) {
42774 clauses.push({
42775 match,
42776 callback,
42777 label: `CLAUSE${count++}`
42778 });
42779 } // Call the callback
42780
42781
42782 callback(when); // Emit the opcodes for the switch
42783
42784 var out = [op(69
42785 /* Enter */
42786 , 2), op(68
42787 /* AssertSame */
42788 ), op(32
42789 /* ReifyU32 */
42790 ), op('StartLabels')]; // First, emit the jump opcodes. We don't need a jump for the last
42791 // opcode, since it bleeds directly into its clause.
42792
42793 for (var clause of clauses.slice(0, -1)) {
42794 out.push(op(67
42795 /* JumpEq */
42796 , label(clause.label), clause.match));
42797 } // Enumerate the clauses in reverse order. Earlier matches will
42798 // require fewer checks.
42799
42800
42801 for (var i = clauses.length - 1; i >= 0; i--) {
42802 var _clause = clauses[i];
42803 out.push(op('Label', _clause.label), op(34
42804 /* Pop */
42805 , 2), _clause.callback()); // The first match is special: it is placed directly before the END
42806 // label, so no additional jump is needed at the end of it.
42807
42808 if (i !== 0) {
42809 out.push(op(4
42810 /* Jump */
42811 , label('END')));
42812 }
42813 }
42814
42815 out.push(op('Label', 'END'), op('StopLabels'), op(70
42816 /* Exit */
42817 ));
42818 return out;
42819 }
42820 /**
42821 * A convenience for pushing some arguments on the stack and
42822 * running some code if the code needs to be re-executed during
42823 * updating execution if some of the arguments have changed.
42824 *
42825 * # Initial Execution
42826 *
42827 * The `args` function should push zero or more arguments onto
42828 * the stack and return the number of arguments pushed.
42829 *
42830 * The `body` function provides the instructions to execute both
42831 * during initial execution and during updating execution.
42832 *
42833 * Internally, this function starts by pushing a new frame, so
42834 * that the body can return and sets the return point ($ra) to
42835 * the ENDINITIAL label.
42836 *
42837 * It then executes the `args` function, which adds instructions
42838 * responsible for pushing the arguments for the block to the
42839 * stack. These arguments will be restored to the stack before
42840 * updating execution.
42841 *
42842 * Next, it adds the Enter opcode, which marks the current position
42843 * in the DOM, and remembers the current $pc (the next instruction)
42844 * as the first instruction to execute during updating execution.
42845 *
42846 * Next, it runs `body`, which adds the opcodes that should
42847 * execute both during initial execution and during updating execution.
42848 * If the `body` wishes to finish early, it should Jump to the
42849 * `FINALLY` label.
42850 *
42851 * Next, it adds the FINALLY label, followed by:
42852 *
42853 * - the Exit opcode, which finalizes the marked DOM started by the
42854 * Enter opcode.
42855 * - the Return opcode, which returns to the current return point
42856 * ($ra).
42857 *
42858 * Finally, it adds the ENDINITIAL label followed by the PopFrame
42859 * instruction, which restores $fp, $sp and $ra.
42860 *
42861 * # Updating Execution
42862 *
42863 * Updating execution for this `replayable` occurs if the `body` added an
42864 * assertion, via one of the `JumpIf`, `JumpUnless` or `AssertSame` opcodes.
42865 *
42866 * If, during updating executon, the assertion fails, the initial VM is
42867 * restored, and the stored arguments are pushed onto the stack. The DOM
42868 * between the starting and ending markers is cleared, and the VM's cursor
42869 * is set to the area just cleared.
42870 *
42871 * The return point ($ra) is set to -1, the exit instruction.
42872 *
42873 * Finally, the $pc is set to to the instruction saved off by the
42874 * Enter opcode during initial execution, and execution proceeds as
42875 * usual.
42876 *
42877 * The only difference is that when a `Return` instruction is
42878 * encountered, the program jumps to -1 rather than the END label,
42879 * and the PopFrame opcode is not needed.
42880 */
42881
42882
42883 function Replayable({
42884 args: args$$1,
42885 body
42886 }) {
42887 // Push the arguments onto the stack. The args() function
42888 // tells us how many stack elements to retain for re-execution
42889 // when updating.
42890 var {
42891 count,
42892 actions
42893 } = args$$1(); // Start a new label frame, to give END and RETURN
42894 // a unique meaning.
42895
42896 return [op('StartLabels'), op(0
42897 /* PushFrame */
42898 ), // If the body invokes a block, its return will return to
42899 // END. Otherwise, the return in RETURN will return to END.
42900 op(6
42901 /* ReturnTo */
42902 , label('ENDINITIAL')), actions, // Start a new updating closure, remembering `count` elements
42903 // from the stack. Everything after this point, and before END,
42904 // will execute both initially and to update the block.
42905 //
42906 // The enter and exit opcodes also track the area of the DOM
42907 // associated with this block. If an assertion inside the block
42908 // fails (for example, the test value changes from true to false
42909 // in an #if), the DOM is cleared and the program is re-executed,
42910 // restoring `count` elements to the stack and executing the
42911 // instructions between the enter and exit.
42912 op(69
42913 /* Enter */
42914 , count), // Evaluate the body of the block. The body of the block may
42915 // return, which will jump execution to END during initial
42916 // execution, and exit the updating routine.
42917 body(), // All execution paths in the body should run the FINALLY once
42918 // they are done. It is executed both during initial execution
42919 // and during updating execution.
42920 op('Label', 'FINALLY'), // Finalize the DOM.
42921 op(70
42922 /* Exit */
42923 ), // In initial execution, this is a noop: it returns to the
42924 // immediately following opcode. In updating execution, this
42925 // exits the updating routine.
42926 op(5
42927 /* Return */
42928 ), // Cleanup code for the block. Runs on initial execution
42929 // but not on updating.
42930 op('Label', 'ENDINITIAL'), op(1
42931 /* PopFrame */
42932 ), op('StopLabels')];
42933 }
42934 /**
42935 * A specialized version of the `replayable` convenience that allows the
42936 * caller to provide different code based upon whether the item at
42937 * the top of the stack is true or false.
42938 *
42939 * As in `replayable`, the `ifTrue` and `ifFalse` code can invoke `return`.
42940 *
42941 * During the initial execution, a `return` will continue execution
42942 * in the cleanup code, which finalizes the current DOM block and pops
42943 * the current frame.
42944 *
42945 * During the updating execution, a `return` will exit the updating
42946 * routine, as it can reuse the DOM block and is always only a single
42947 * frame deep.
42948 */
42949
42950
42951 function ReplayableIf({
42952 args: args$$1,
42953 ifTrue,
42954 ifFalse
42955 }) {
42956 return Replayable({
42957 args: args$$1,
42958 body: () => {
42959 var out = [// If the conditional is false, jump to the ELSE label.
42960 op(66
42961 /* JumpUnless */
42962 , label('ELSE')), // Otherwise, execute the code associated with the true branch.
42963 ifTrue(), // We're done, so return. In the initial execution, this runs
42964 // the cleanup code. In the updating VM, it exits the updating
42965 // routine.
42966 op(4
42967 /* Jump */
42968 , label('FINALLY')), op('Label', 'ELSE')]; // If the conditional is false, and code associatied ith the
42969 // false branch was provided, execute it. If there was no code
42970 // associated with the false branch, jumping to the else statement
42971 // has no other behavior.
42972
42973 if (ifFalse) {
42974 out.push(ifFalse());
42975 }
42976
42977 return out;
42978 }
42979 });
42980 }
42981
42982 function pushBuilderOp(context, op$$1) {
42983 var {
42984 encoder,
42985 syntax: {
42986 program: {
42987 mode,
42988 constants
42989 }
42990 }
42991 } = context;
42992
42993 switch (op$$1.op) {
42994 case "Option"
42995 /* Option */
42996 :
42997 return concat(context, option$1(op$$1));
42998
42999 case "Label"
43000 /* Label */
43001 :
43002 return encoder.label(op$$1.op1);
43003
43004 case "StartLabels"
43005 /* StartLabels */
43006 :
43007 return encoder.startLabels();
43008
43009 case "StopLabels"
43010 /* StopLabels */
43011 :
43012 return encoder.stopLabels();
43013
43014 case "JitCompileBlock"
43015 /* JitCompileBlock */
43016 :
43017 return concat(context, jitCompileBlock(mode));
43018
43019 case "GetComponentLayout"
43020 /* GetComponentLayout */
43021 :
43022 return encoder.push(constants, compileLayoutOpcode(mode), op$$1.op1);
43023
43024 case "SetBlock"
43025 /* SetBlock */
43026 :
43027 return encoder.push(constants, setBlock(mode), op$$1.op1);
43028
43029 default:
43030 return (0, _util.exhausted)(op$$1);
43031 }
43032 }
43033
43034 function option$1(op$$1) {
43035 var value = op$$1.op1;
43036 return value === null ? NONE : value;
43037 }
43038
43039 function compileLayoutOpcode(mode) {
43040 return mode === "aot"
43041 /* aot */
43042 ? 94
43043 /* GetAotComponentLayout */
43044 : 95
43045 /* GetJitComponentLayout */
43046 ;
43047 }
43048
43049 function jitCompileBlock(mode) {
43050 return mode === "jit"
43051 /* jit */
43052 ? op(61
43053 /* CompileBlock */
43054 ) : NONE;
43055 }
43056
43057 function setBlock(mode) {
43058 return mode === "aot"
43059 /* aot */
43060 ? 20
43061 /* SetAotBlock */
43062 : 21
43063 /* SetJitBlock */
43064 ;
43065 }
43066
43067 function pushCompileOp(context, action) {
43068 concatStatements(context, compileOp(context, action));
43069 }
43070
43071 function compileOp(context, action) {
43072 switch (action.op) {
43073 case "CompileBlock"
43074 /* CompileBlock */
43075 :
43076 return CompileBlockOp(context, action);
43077
43078 case "CompileInline"
43079 /* CompileInline */
43080 :
43081 return CompileInlineOp(context, action);
43082
43083 case "InvokeStatic"
43084 /* InvokeStatic */
43085 :
43086 return InvokeStatic(context.syntax, action);
43087
43088 case "Args"
43089 /* Args */
43090 :
43091 return CompileArgs(action.op1);
43092
43093 case "PushCompilable"
43094 /* PushCompilable */
43095 :
43096 return PushCompilable(action.op1, context.syntax);
43097
43098 case "DynamicComponent"
43099 /* DynamicComponent */
43100 :
43101 return DynamicComponent(context, action);
43102
43103 case "IfResolvedComponent"
43104 /* IfResolvedComponent */
43105 :
43106 return IfResolvedComponent(context, action);
43107
43108 default:
43109 return (0, _util.exhausted)(action);
43110 }
43111 }
43112
43113 function CompileBlockOp(context, op$$1) {
43114 return compileBlock(op$$1.op1, context);
43115 }
43116
43117 function CompileInlineOp(context, op$$1) {
43118 var {
43119 inline,
43120 ifUnhandled
43121 } = op$$1.op1;
43122 var returned = compileInline(inline, context);
43123
43124 if (isHandled(returned)) {
43125 return returned;
43126 } else {
43127 return ifUnhandled(inline);
43128 }
43129 }
43130
43131 function InvokeStatic(context, action) {
43132 var compilable$$1 = action.op1;
43133
43134 if (context.program.mode === "aot"
43135 /* aot */
43136 ) {
43137 var handle = compilable$$1.compile(context);
43138
43139 if (typeof handle !== 'number') {
43140 return op('Error', {
43141 problem: 'Invalid block',
43142 start: 0,
43143 end: 0
43144 });
43145 } // If the handle for the invoked component is not yet known (for example,
43146 // because this is a recursive invocation and we're still compiling), push a
43147 // function that will produce the correct handle when the heap is
43148 // serialized.
43149
43150
43151 if (handle === PLACEHOLDER_HANDLE) {
43152 return op(3
43153 /* InvokeStatic */
43154 , () => compilable$$1.compile(context));
43155 } else {
43156 return op(3
43157 /* InvokeStatic */
43158 , handle);
43159 }
43160 } else {
43161 return [op(29
43162 /* Constant */
43163 , other(action.op1)), op(61
43164 /* CompileBlock */
43165 ), op(2
43166 /* InvokeVirtual */
43167 )];
43168 }
43169 }
43170
43171 function DynamicComponent(context, action) {
43172 var {
43173 definition,
43174 attrs,
43175 params,
43176 args: args$$1,
43177 blocks,
43178 atNames
43179 } = action.op1;
43180 var attrsBlock = attrs && attrs.length > 0 ? compilableBlock(attrs, context.meta) : null;
43181 var compiled = Array.isArray(blocks) || blocks === null ? namedBlocks(blocks, context.meta) : blocks;
43182 return InvokeDynamicComponent(context.meta, {
43183 definition,
43184 attrs: attrsBlock,
43185 params,
43186 hash: args$$1,
43187 atNames,
43188 blocks: compiled
43189 });
43190 }
43191
43192 function IfResolvedComponent(context, action) {
43193 var {
43194 name,
43195 attrs,
43196 blocks,
43197 staticTemplate,
43198 dynamicTemplate,
43199 orElse
43200 } = action.op1;
43201 var component = resolveLayoutForTag(name, {
43202 resolver: context.syntax.program.resolverDelegate,
43203 meta: context.meta
43204 });
43205 var {
43206 meta: meta$$1
43207 } = context;
43208
43209 if (component !== null) {
43210 var {
43211 handle,
43212 capabilities,
43213 compilable: compilable$$1
43214 } = component;
43215 var attrsBlock = compilableBlock(attrs, meta$$1);
43216 var compilableBlocks = namedBlocks(blocks, meta$$1);
43217
43218 if (compilable$$1 !== null) {
43219 return staticTemplate(handle, capabilities, compilable$$1, {
43220 attrs: attrsBlock,
43221 blocks: compilableBlocks
43222 });
43223 } else {
43224 return dynamicTemplate(handle, capabilities, {
43225 attrs: attrsBlock,
43226 blocks: compilableBlocks
43227 });
43228 }
43229 } else if (orElse) {
43230 return orElse();
43231 } else {
43232 throw new Error(`Compile Error: Cannot find component ${name}`);
43233 }
43234 }
43235
43236 function PushCompilable(block, context) {
43237 if (block === null) {
43238 return PushPrimitive(null);
43239 } else if (context.program.mode === "aot"
43240 /* aot */
43241 ) {
43242 var compiled = block.compile(context);
43243
43244 if (typeof compiled !== 'number') {
43245 return op('Error', {
43246 problem: 'Compile Error (TODO: thread better)',
43247 start: 0,
43248 end: 0
43249 });
43250 }
43251
43252 return PushPrimitive(compiled);
43253 } else {
43254 return op(29
43255 /* Constant */
43256 , other(block));
43257 }
43258 }
43259
43260 function pushOp(encoder, constants, op) {
43261 if (op.op3 !== undefined) {
43262 encoder.push(constants, op.op, op.op1, op.op2, op.op3);
43263 } else if (op.op2 !== undefined) {
43264 encoder.push(constants, op.op, op.op1, op.op2);
43265 } else if (op.op1 !== undefined) {
43266 encoder.push(constants, op.op, op.op1);
43267 } else {
43268 encoder.push(constants, op.op);
43269 }
43270 }
43271
43272 class Compilers {
43273 constructor() {
43274 this.names = {};
43275 this.funcs = [];
43276 }
43277
43278 add(name, func) {
43279 this.names[name] = this.funcs.push(func) - 1;
43280 }
43281
43282 compile(sexp, meta) {
43283 var name = sexp[0];
43284 var index = this.names[name];
43285 var func = this.funcs[index];
43286 return func(sexp, meta);
43287 }
43288
43289 }
43290
43291 var EXPRESSIONS = new Compilers();
43292 EXPRESSIONS.add(31
43293 /* Concat */
43294 , ([, parts]) => {
43295 var out = [];
43296
43297 for (var part of parts) {
43298 out.push(op('Expr', part));
43299 }
43300
43301 out.push(op(28
43302 /* Concat */
43303 , parts.length));
43304 return out;
43305 });
43306 EXPRESSIONS.add(30
43307 /* Call */
43308 , ([, name, params, hash], meta) => {
43309 // TODO: triage this in the WF compiler
43310 var start = 0;
43311 var offset = 0;
43312
43313 if (isComponent(name, meta)) {
43314 if (!params || params.length === 0) {
43315 return op('Error', {
43316 problem: 'component helper requires at least one argument',
43317 start: start,
43318 end: start + offset
43319 });
43320 }
43321
43322 var [definition, ...restArgs] = params;
43323 return curryComponent({
43324 definition,
43325 params: restArgs,
43326 hash,
43327 atNames: false
43328 }, meta.referrer);
43329 }
43330
43331 var nameOrError = expectString(name, meta, 'Expected call head to be a string');
43332
43333 if (typeof nameOrError !== 'string') {
43334 return nameOrError;
43335 }
43336
43337 return op('IfResolved', {
43338 kind: "Helper"
43339 /* Helper */
43340 ,
43341 name: nameOrError,
43342 andThen: handle => Call({
43343 handle,
43344 params,
43345 hash
43346 }),
43347 span: {
43348 start,
43349 end: start + offset
43350 }
43351 });
43352 });
43353
43354 function isGetContextualFree(opcode) {
43355 return opcode[0] >= 34
43356 /* GetContextualFreeStart */
43357 ;
43358 }
43359
43360 function isComponent(expr, meta) {
43361 if (!Array.isArray(expr)) {
43362 return false;
43363 }
43364
43365 if (isGetContextualFree(expr)) {
43366 var head = expr[1];
43367
43368 if (meta.upvars && meta.upvars[head] === 'component') {
43369 return true;
43370 } else {
43371 return false;
43372 }
43373 }
43374
43375 return false;
43376 }
43377
43378 EXPRESSIONS.add(32
43379 /* GetSymbol */
43380 , ([, sym, path]) => withPath(op(22
43381 /* GetVariable */
43382 , sym), path));
43383 EXPRESSIONS.add(33
43384 /* GetFree */
43385 , ([, sym, path]) => withPath(op('ResolveFree', sym), path));
43386 EXPRESSIONS.add(34
43387 /* GetFreeInAppendSingleId */
43388 , ([, sym, path]) => withPath(op('ResolveContextualFree', {
43389 freeVar: sym,
43390 context: 0
43391 /* AppendSingleId */
43392
43393 }), path));
43394 EXPRESSIONS.add(35
43395 /* GetFreeInExpression */
43396 , ([, sym, path]) => withPath(op('ResolveContextualFree', {
43397 freeVar: sym,
43398 context: 1
43399 /* Expression */
43400
43401 }), path));
43402 EXPRESSIONS.add(36
43403 /* GetFreeInCallHead */
43404 , ([, sym, path]) => withPath(op('ResolveContextualFree', {
43405 freeVar: sym,
43406 context: 2
43407 /* CallHead */
43408
43409 }), path));
43410 EXPRESSIONS.add(37
43411 /* GetFreeInBlockHead */
43412 , ([, sym, path]) => withPath(op('ResolveContextualFree', {
43413 freeVar: sym,
43414 context: 3
43415 /* BlockHead */
43416
43417 }), path));
43418 EXPRESSIONS.add(38
43419 /* GetFreeInModifierHead */
43420 , ([, sym, path]) => withPath(op('ResolveContextualFree', {
43421 freeVar: sym,
43422 context: 4
43423 /* ModifierHead */
43424
43425 }), path));
43426 EXPRESSIONS.add(39
43427 /* GetFreeInComponentHead */
43428 , ([, sym, path]) => withPath(op('ResolveContextualFree', {
43429 freeVar: sym,
43430 context: 5
43431 /* ComponentHead */
43432
43433 }), path));
43434
43435 function withPath(expr, path) {
43436 if (path === undefined || path.length === 0) return expr;
43437 if (!Array.isArray(expr)) expr = [expr];
43438
43439 for (var i = 0; i < path.length; i++) {
43440 expr.push(op(23
43441 /* GetProperty */
43442 , path[i]));
43443 }
43444
43445 return expr;
43446 }
43447
43448 EXPRESSIONS.add(29
43449 /* Undefined */
43450 , () => PushPrimitiveReference(undefined));
43451 EXPRESSIONS.add(27
43452 /* HasBlock */
43453 , ([, block]) => {
43454 return [op('Expr', block), op(26
43455 /* HasBlock */
43456 )];
43457 });
43458 EXPRESSIONS.add(28
43459 /* HasBlockParams */
43460 , ([, block]) => [op('Expr', block), op(25
43461 /* JitSpreadBlock */
43462 ), op('JitCompileBlock'), op(27
43463 /* HasBlockParams */
43464 )]);
43465
43466 function pushResolutionOp(encoder, context, operation, constants) {
43467 switch (operation.op) {
43468 case "SimpleArgs"
43469 /* SimpleArgs */
43470 :
43471 concatExpressions(encoder, context, compileSimpleArgs(operation.op1.params, operation.op1.hash, operation.op1.atNames), constants);
43472 break;
43473
43474 case "Expr"
43475 /* Expr */
43476 :
43477 concatExpressions(encoder, context, expr(operation.op1, context.meta), constants);
43478 break;
43479
43480 case "IfResolved"
43481 /* IfResolved */
43482 :
43483 {
43484 concatExpressions(encoder, context, ifResolved(context, operation), constants);
43485 break;
43486 }
43487
43488 case "ResolveFree"
43489 /* ResolveFree */
43490 :
43491 {
43492 throw new Error('Unimplemented HighLevelResolutionOpcode.ResolveFree');
43493 }
43494
43495 case "ResolveContextualFree"
43496 /* ResolveContextualFree */
43497 :
43498 {
43499 var {
43500 freeVar,
43501 context: expressionContext
43502 } = operation.op1;
43503
43504 if (context.meta.asPartial) {
43505 var name = context.meta.upvars[freeVar];
43506 concatExpressions(encoder, context, [op(105
43507 /* ResolveMaybeLocal */
43508 , name)], constants);
43509 break;
43510 }
43511
43512 switch (expressionContext) {
43513 case 1
43514 /* Expression */
43515 :
43516 {
43517 // in classic mode, this is always a this-fallback
43518 var _name2 = context.meta.upvars[freeVar];
43519 concatExpressions(encoder, context, [op(22
43520 /* GetVariable */
43521 , 0), op(23
43522 /* GetProperty */
43523 , _name2)], constants);
43524 break;
43525 }
43526
43527 case 0
43528 /* AppendSingleId */
43529 :
43530 {
43531 var resolver = context.syntax.program.resolverDelegate;
43532 var _name3 = context.meta.upvars[freeVar];
43533 var resolvedHelper = resolver.lookupHelper(_name3, context.meta.referrer);
43534 var expressions;
43535
43536 if (resolvedHelper) {
43537 expressions = Call({
43538 handle: resolvedHelper,
43539 params: null,
43540 hash: null
43541 });
43542 } else {
43543 // in classic mode, this is always a this-fallback
43544 expressions = [op(22
43545 /* GetVariable */
43546 , 0), op(23
43547 /* GetProperty */
43548 , _name3)];
43549 }
43550
43551 concatExpressions(encoder, context, expressions, constants);
43552 break;
43553 }
43554
43555 default:
43556 throw new Error(`unimplemented: Can't evaluate expression in context ${expressionContext}`);
43557 }
43558
43559 break;
43560 }
43561
43562 default:
43563 return (0, _util.exhausted)(operation);
43564 }
43565 }
43566
43567 function expr(expression$$1, meta$$1) {
43568 if (Array.isArray(expression$$1)) {
43569 return EXPRESSIONS.compile(expression$$1, meta$$1);
43570 } else {
43571 return [PushPrimitive(expression$$1), op(31
43572 /* PrimitiveReference */
43573 )];
43574 }
43575 }
43576
43577 function compileSimpleArgs(params, hash, atNames) {
43578 var out = [];
43579 var {
43580 count,
43581 actions
43582 } = CompilePositional(params);
43583 out.push(actions);
43584 var flags = count << 4;
43585 if (atNames) flags |= 0b1000;
43586 var names = _util.EMPTY_ARRAY;
43587
43588 if (hash) {
43589 names = hash[0];
43590 var val = hash[1];
43591
43592 for (var i = 0; i < val.length; i++) {
43593 out.push(op('Expr', val[i]));
43594 }
43595 }
43596
43597 out.push(op(84
43598 /* PushArgs */
43599 , strArray(names), strArray(_util.EMPTY_ARRAY), flags));
43600 return out;
43601 }
43602
43603 function ifResolved(context, {
43604 op1
43605 }) {
43606 var {
43607 kind,
43608 name,
43609 andThen,
43610 orElse,
43611 span
43612 } = op1;
43613 var resolved = resolve(context.syntax.program.resolverDelegate, kind, name, context.meta.referrer);
43614
43615 if (resolved !== null) {
43616 return andThen(resolved);
43617 } else if (orElse) {
43618 return orElse();
43619 } else {
43620 return error(`Unexpected ${kind} ${name}`, span.start, span.end);
43621 }
43622 }
43623
43624 function resolve(resolver, kind, name, referrer) {
43625 switch (kind) {
43626 case "Modifier"
43627 /* Modifier */
43628 :
43629 return resolver.lookupModifier(name, referrer);
43630
43631 case "Helper"
43632 /* Helper */
43633 :
43634 return resolver.lookupHelper(name, referrer);
43635
43636 case "ComponentDefinition"
43637 /* ComponentDefinition */
43638 :
43639 {
43640 var component = resolver.lookupComponent(name, referrer);
43641 return component && component.handle;
43642 }
43643 }
43644 }
43645
43646 var NONE = {
43647 'no-action': true
43648 };
43649 _exports.NONE = NONE;
43650 var UNHANDLED = {
43651 'not-handled': true
43652 };
43653 _exports.UNHANDLED = UNHANDLED;
43654
43655 function isNoAction(actions) {
43656 return actions && !!actions['no-action'];
43657 }
43658
43659 function isHandled(actions) {
43660 return !actions || !actions['not-handled'];
43661 }
43662
43663 function concat(context, action) {
43664 if (isNoAction(action)) {
43665 return;
43666 } else if (Array.isArray(action)) {
43667 for (var item of action) {
43668 concat(context, item);
43669 }
43670 } else if (action.type === 'Simple') {
43671 pushBuilderOp(context, action);
43672 } else {
43673 pushOp(context.encoder, context.syntax.program.constants, action);
43674 }
43675 }
43676
43677 function concatExpressions(encoder, context, action, constants) {
43678 if (isNoAction(action)) {
43679 return;
43680 } else if (Array.isArray(action)) {
43681 for (var item of action) {
43682 concatExpressions(encoder, context, item, constants);
43683 }
43684 } else if (action.type === 'Number') {
43685 pushOp(encoder, constants, action);
43686 } else if (action.type === 'Resolution') {
43687 pushResolutionOp(encoder, context, action, constants);
43688 } else if (action.type === 'Simple') {
43689 pushBuilderOp(context, action);
43690 } else if (action.type === 'Error') {
43691 encoder.error({
43692 problem: action.op1.problem,
43693 span: {
43694 start: action.op1.start,
43695 end: action.op1.end
43696 }
43697 });
43698 } else {
43699 throw (0, _util.assertNever)(action, 'unexpected action kind');
43700 }
43701 }
43702
43703 function concatStatements(context, action) {
43704 if (isNoAction(action)) {
43705 return;
43706 } else if (Array.isArray(action)) {
43707 for (var item of action) {
43708 concatStatements(context, item);
43709 }
43710 } else if (action.type === 'Number') {
43711 pushOp(context.encoder, context.syntax.program.constants, action);
43712 } else {
43713 if (action.type === 'Compile') {
43714 pushCompileOp(context, action);
43715 } else if (action.type === 'Resolution') {
43716 pushResolutionOp(context.encoder, context, action, context.syntax.program.constants);
43717 } else if (action.type === 'Simple') {
43718 pushBuilderOp(context, action);
43719 } else if (action.type === 'Error') {} else {
43720 throw (0, _util.assertNever)(action, `unexpected action type`);
43721 }
43722 }
43723 }
43724
43725 function populateBuiltins(blocks, inlines) {
43726 blocks.add('if', (params, _hash, blocks) => {
43727 if (!params || params.length !== 1) {
43728 throw new Error(`SYNTAX ERROR: #if requires a single argument`);
43729 }
43730
43731 return ReplayableIf({
43732 args() {
43733 return {
43734 count: 1,
43735 actions: [op('Expr', params[0]), op(71
43736 /* ToBoolean */
43737 )]
43738 };
43739 },
43740
43741 ifTrue() {
43742 return InvokeStaticBlock(blocks.get('default'));
43743 },
43744
43745 ifFalse() {
43746 if (blocks.has('else')) {
43747 return InvokeStaticBlock(blocks.get('else'));
43748 } else {
43749 return NONE;
43750 }
43751 }
43752
43753 });
43754 });
43755 blocks.add('unless', (params, _hash, blocks) => {
43756 if (!params || params.length !== 1) {
43757 throw new Error(`SYNTAX ERROR: #unless requires a single argument`);
43758 }
43759
43760 return ReplayableIf({
43761 args() {
43762 return {
43763 count: 1,
43764 actions: [op('Expr', params[0]), op(71
43765 /* ToBoolean */
43766 )]
43767 };
43768 },
43769
43770 ifTrue() {
43771 if (blocks.has('else')) {
43772 return InvokeStaticBlock(blocks.get('else'));
43773 } else {
43774 return NONE;
43775 }
43776 },
43777
43778 ifFalse() {
43779 return InvokeStaticBlock(blocks.get('default'));
43780 }
43781
43782 });
43783 });
43784 blocks.add('with', (params, _hash, blocks) => {
43785 if (!params || params.length !== 1) {
43786 throw new Error(`SYNTAX ERROR: #with requires a single argument`);
43787 }
43788
43789 return ReplayableIf({
43790 args() {
43791 return {
43792 count: 2,
43793 actions: [op('Expr', params[0]), op(33
43794 /* Dup */
43795 , _vm.$sp, 0), op(71
43796 /* ToBoolean */
43797 )]
43798 };
43799 },
43800
43801 ifTrue() {
43802 return InvokeStaticBlockWithStack(blocks.get('default'), 1);
43803 },
43804
43805 ifFalse() {
43806 if (blocks.has('else')) {
43807 return InvokeStaticBlock(blocks.get('else'));
43808 } else {
43809 return NONE;
43810 }
43811 }
43812
43813 });
43814 });
43815 blocks.add('let', (params, _hash, blocks) => {
43816 if (!params) {
43817 return error('let requires arguments', 0, 0);
43818 }
43819
43820 var {
43821 count,
43822 actions
43823 } = CompilePositional(params);
43824 return [actions, InvokeStaticBlockWithStack(blocks.get('default'), count)];
43825 });
43826 blocks.add('each', (params, hash, blocks) => {
43827 return Replayable({
43828 args() {
43829 var actions;
43830
43831 if (hash && hash[0][0] === 'key') {
43832 actions = [op('Expr', hash[1][0])];
43833 } else {
43834 actions = [PushPrimitiveReference(null)];
43835 }
43836
43837 actions.push(op('Expr', params[0]));
43838 return {
43839 count: 2,
43840 actions
43841 };
43842 },
43843
43844 body() {
43845 var out = [op(74
43846 /* PutIterator */
43847 ), op(66
43848 /* JumpUnless */
43849 , label('ELSE')), op(0
43850 /* PushFrame */
43851 ), op(33
43852 /* Dup */
43853 , _vm.$fp, 1), op(6
43854 /* ReturnTo */
43855 , label('ITER')), op(72
43856 /* EnterList */
43857 , label('BODY')), op('Label', 'ITER'), op(75
43858 /* Iterate */
43859 , label('BREAK')), op('Label', 'BODY'), InvokeStaticBlockWithStack(blocks.get('default'), 2), op(34
43860 /* Pop */
43861 , 2), op(4
43862 /* Jump */
43863 , label('FINALLY')), op('Label', 'BREAK'), op(73
43864 /* ExitList */
43865 ), op(1
43866 /* PopFrame */
43867 ), op(4
43868 /* Jump */
43869 , label('FINALLY')), op('Label', 'ELSE')];
43870
43871 if (blocks.has('else')) {
43872 out.push(InvokeStaticBlock(blocks.get('else')));
43873 }
43874
43875 return out;
43876 }
43877
43878 });
43879 });
43880 blocks.add('in-element', (params, hash, blocks) => {
43881 if (!params || params.length !== 1) {
43882 throw new Error(`SYNTAX ERROR: #in-element requires a single argument`);
43883 }
43884
43885 return ReplayableIf({
43886 args() {
43887 var [keys, values] = hash;
43888 var actions = [];
43889
43890 for (var i = 0; i < keys.length; i++) {
43891 var key = keys[i];
43892
43893 if (key === 'guid' || key === 'insertBefore') {
43894 actions.push(op('Expr', values[i]));
43895 } else {
43896 throw new Error(`SYNTAX ERROR: #in-element does not take a \`${keys[0]}\` option`);
43897 }
43898 }
43899
43900 actions.push(op('Expr', params[0]), op(33
43901 /* Dup */
43902 , _vm.$sp, 0));
43903 return {
43904 count: 4,
43905 actions
43906 };
43907 },
43908
43909 ifTrue() {
43910 return [op(50
43911 /* PushRemoteElement */
43912 ), InvokeStaticBlock(blocks.get('default')), op(56
43913 /* PopRemoteElement */
43914 )];
43915 }
43916
43917 });
43918 });
43919 blocks.add('-with-dynamic-vars', (_params, hash, blocks) => {
43920 if (hash) {
43921 var [names, expressions] = hash;
43922 var {
43923 actions
43924 } = CompilePositional(expressions);
43925 return [actions, DynamicScope(names, () => {
43926 return InvokeStaticBlock(blocks.get('default'));
43927 })];
43928 } else {
43929 return InvokeStaticBlock(blocks.get('default'));
43930 }
43931 });
43932 blocks.add('component', (_params, hash, blocks, context) => {
43933 var tag = _params[0];
43934
43935 if (typeof tag === 'string') {
43936 var returned = StaticComponentHelper(context, _params[0], hash, blocks.get('default'));
43937 if (isHandled(returned)) return returned;
43938 }
43939
43940 var [definition, ...params] = _params;
43941 return op('DynamicComponent', {
43942 definition,
43943 attrs: null,
43944 params,
43945 args: hash,
43946 atNames: false,
43947 blocks
43948 });
43949 });
43950 inlines.add('component', (_name, _params, hash, context) => {
43951 var tag = _params && _params[0];
43952
43953 if (typeof tag === 'string') {
43954 var returned = StaticComponentHelper(context, tag, hash, null);
43955 if (returned !== UNHANDLED) return returned;
43956 }
43957
43958 var [definition, ...params] = _params;
43959 return InvokeDynamicComponent(context.meta, {
43960 definition,
43961 attrs: null,
43962 params,
43963 hash,
43964 atNames: false,
43965 blocks: EMPTY_BLOCKS
43966 });
43967 });
43968 return {
43969 blocks,
43970 inlines
43971 };
43972 }
43973
43974 class MacrosImpl {
43975 constructor() {
43976 var {
43977 blocks,
43978 inlines
43979 } = populateBuiltins(new Blocks(), new Inlines());
43980 this.blocks = blocks;
43981 this.inlines = inlines;
43982 }
43983
43984 }
43985
43986 _exports.MacrosImpl = MacrosImpl;
43987
43988 class Blocks {
43989 constructor() {
43990 this.names = (0, _util.dict)();
43991 this.funcs = [];
43992 }
43993
43994 add(name, func) {
43995 this.funcs.push(func);
43996 this.names[name] = this.funcs.length - 1;
43997 }
43998
43999 addMissing(func) {
44000 this.missing = func;
44001 }
44002
44003 compile(name, params, hash, blocks, context) {
44004 var index = this.names[name];
44005 var macroContext = {
44006 resolver: context.syntax.program.resolverDelegate,
44007 meta: context.meta
44008 };
44009
44010 if (index === undefined) {
44011 var func = this.missing;
44012 var handled = func(name, params, hash, blocks, macroContext);
44013 return handled;
44014 } else {
44015 var _func = this.funcs[index];
44016 return _func(params, hash, blocks, macroContext);
44017 }
44018 }
44019
44020 }
44021
44022 class Inlines {
44023 constructor() {
44024 this.names = (0, _util.dict)();
44025 this.funcs = [];
44026 }
44027
44028 add(name, func) {
44029 this.funcs.push(func);
44030 this.names[name] = this.funcs.length - 1;
44031 }
44032
44033 addMissing(func) {
44034 this.missing = func;
44035 }
44036
44037 compile(sexp, context) {
44038 var [, value] = sexp; // TODO: Fix this so that expression macros can return
44039 // things like components, so that {{component foo}}
44040 // is the same as {{(component foo)}}
44041
44042 if (!Array.isArray(value)) return UNHANDLED;
44043 var name;
44044 var params;
44045 var hash;
44046
44047 if (value[0] === 30
44048 /* Call */
44049 ) {
44050 var nameOrError = expectString(value[1], context.meta, 'Expected head of call to be a string');
44051
44052 if (typeof nameOrError !== 'string') {
44053 return nameOrError;
44054 }
44055
44056 name = nameOrError;
44057 params = value[2];
44058 hash = value[3];
44059 } else if (isGet(value)) {
44060 var pathName = simplePathName(value, context.meta);
44061
44062 if (pathName === null) {
44063 return UNHANDLED;
44064 }
44065
44066 name = pathName;
44067 params = null;
44068 hash = null;
44069 } else {
44070 return UNHANDLED;
44071 }
44072
44073 var index = this.names[name];
44074 var macroContext = {
44075 resolver: context.syntax.program.resolverDelegate,
44076 meta: context.meta
44077 };
44078
44079 if (index === undefined && this.missing) {
44080 var func = this.missing;
44081 return func(name, params, hash, macroContext);
44082 } else if (index !== undefined) {
44083 var _func2 = this.funcs[index];
44084 return _func2(name, params, hash, macroContext);
44085 } else {
44086 return UNHANDLED;
44087 }
44088 }
44089
44090 }
44091
44092 function syntaxCompilationContext(program, macros) {
44093 return {
44094 program,
44095 macros
44096 };
44097 }
44098
44099 function Context(resolver = {}, mode = "aot"
44100 /* aot */
44101 , macros = new MacrosImpl()) {
44102 return {
44103 program: new ProgramCompilationContext(new DefaultCompileTimeResolverDelegate(resolver), mode),
44104 macros
44105 };
44106 }
44107
44108 function JitContext(resolver = {}, macros = new MacrosImpl()) {
44109 return {
44110 program: new JitProgramCompilationContext(new DefaultCompileTimeResolverDelegate(resolver)),
44111 macros
44112 };
44113 }
44114
44115 function AotContext(resolver = {}, macros = new MacrosImpl()) {
44116 return {
44117 program: new ProgramCompilationContext(new DefaultCompileTimeResolverDelegate(resolver), "aot"
44118 /* aot */
44119 ),
44120 macros
44121 };
44122 }
44123
44124 function templateCompilationContext(syntax, meta) {
44125 var encoder = new EncoderImpl();
44126 return {
44127 syntax,
44128 encoder,
44129 meta
44130 };
44131 }
44132
44133 var STATEMENTS = new Compilers();
44134 var INFLATE_ATTR_TABLE = ['class', 'id', 'value', 'name', 'type', 'style', 'href'];
44135 var INFLATE_TAG_TABLE = ['div', 'span', 'p', 'a'];
44136
44137 function inflateTagName(tagName) {
44138 return typeof tagName === 'string' ? tagName : INFLATE_TAG_TABLE[tagName];
44139 }
44140
44141 function inflateAttrName(attrName) {
44142 return typeof attrName === 'string' ? attrName : INFLATE_ATTR_TABLE[attrName];
44143 }
44144
44145 STATEMENTS.add(3
44146 /* Comment */
44147 , sexp => op(42
44148 /* Comment */
44149 , sexp[1]));
44150 STATEMENTS.add(13
44151 /* CloseElement */
44152 , () => op(55
44153 /* CloseElement */
44154 ));
44155 STATEMENTS.add(12
44156 /* FlushElement */
44157 , () => op(54
44158 /* FlushElement */
44159 ));
44160 STATEMENTS.add(4
44161 /* Modifier */
44162 , (sexp, meta) => {
44163 var [, name, params, hash] = sexp;
44164 var stringName = expectString(name, meta, 'Expected modifier head to be a string');
44165
44166 if (typeof stringName !== 'string') {
44167 return stringName;
44168 }
44169
44170 return op('IfResolved', {
44171 kind: "Modifier"
44172 /* Modifier */
44173 ,
44174 name: stringName,
44175 andThen: handle => [op(0
44176 /* PushFrame */
44177 ), op('SimpleArgs', {
44178 params,
44179 hash,
44180 atNames: false
44181 }), op(57
44182 /* Modifier */
44183 , handle), op(1
44184 /* PopFrame */
44185 )],
44186 span: {
44187 start: 0,
44188 end: 0
44189 }
44190 });
44191 });
44192 STATEMENTS.add(14
44193 /* StaticAttr */
44194 , ([, name, value, namespace]) => op(51
44195 /* StaticAttr */
44196 , inflateAttrName(name), value, namespace !== null && namespace !== void 0 ? namespace : null));
44197 STATEMENTS.add(24
44198 /* StaticComponentAttr */
44199 , ([, name, value, namespace]) => op(108
44200 /* StaticComponentAttr */
44201 , inflateAttrName(name), value, namespace !== null && namespace !== void 0 ? namespace : null));
44202 STATEMENTS.add(15
44203 /* DynamicAttr */
44204 , ([, name, value, namespace]) => [op('Expr', value), op(52
44205 /* DynamicAttr */
44206 , inflateAttrName(name), false, namespace !== null && namespace !== void 0 ? namespace : null)]);
44207 STATEMENTS.add(22
44208 /* TrustingDynamicAttr */
44209 , ([, name, value, namespace]) => [op('Expr', value), op(52
44210 /* DynamicAttr */
44211 , inflateAttrName(name), true, namespace !== null && namespace !== void 0 ? namespace : null)]);
44212 STATEMENTS.add(16
44213 /* ComponentAttr */
44214 , ([, name, value, namespace]) => [op('Expr', value), op(53
44215 /* ComponentAttr */
44216 , inflateAttrName(name), false, namespace !== null && namespace !== void 0 ? namespace : null)]);
44217 STATEMENTS.add(23
44218 /* TrustingComponentAttr */
44219 , ([, name, value, namespace]) => [op('Expr', value), op(53
44220 /* ComponentAttr */
44221 , inflateAttrName(name), true, namespace !== null && namespace !== void 0 ? namespace : null)]);
44222 STATEMENTS.add(10
44223 /* OpenElement */
44224 , ([, tag]) => {
44225 return op(48
44226 /* OpenElement */
44227 , inflateTagName(tag));
44228 });
44229 STATEMENTS.add(11
44230 /* OpenElementWithSplat */
44231 , ([, tag]) => {
44232 return [op(91
44233 /* PutComponentOperations */
44234 ), op(48
44235 /* OpenElement */
44236 , inflateTagName(tag))];
44237 });
44238 STATEMENTS.add(8
44239 /* Component */
44240 , ([, tag, attrs, args$$1, blocks]) => {
44241 if (typeof tag === 'string') {
44242 return op('IfResolvedComponent', {
44243 name: tag,
44244 attrs,
44245 blocks,
44246 staticTemplate: (layoutHandle, capabilities, template, {
44247 blocks,
44248 attrs
44249 }) => {
44250 return [op(80
44251 /* PushComponentDefinition */
44252 , layoutHandle), InvokeStaticComponent({
44253 capabilities,
44254 layout: template,
44255 attrs,
44256 params: null,
44257 hash: args$$1,
44258 blocks
44259 })];
44260 },
44261 dynamicTemplate: (layoutHandle, capabilities, {
44262 attrs,
44263 blocks
44264 }) => {
44265 return [op(80
44266 /* PushComponentDefinition */
44267 , layoutHandle), InvokeComponent({
44268 capabilities,
44269 attrs,
44270 params: null,
44271 hash: args$$1,
44272 atNames: true,
44273 blocks
44274 })];
44275 }
44276 });
44277 } else {
44278 return op('DynamicComponent', {
44279 definition: tag,
44280 attrs,
44281 params: null,
44282 args: args$$1,
44283 blocks,
44284 atNames: true
44285 });
44286 }
44287 });
44288 STATEMENTS.add(19
44289 /* Partial */
44290 , ([, name, evalInfo], meta) => ReplayableIf({
44291 args() {
44292 return {
44293 count: 2,
44294 actions: [op('Expr', name), op(33
44295 /* Dup */
44296 , _vm.$sp, 0)]
44297 };
44298 },
44299
44300 ifTrue() {
44301 return [op(104
44302 /* InvokePartial */
44303 , templateMeta(meta.referrer), strArray(meta.evalSymbols), arr(evalInfo)), op(40
44304 /* PopScope */
44305 ), op(1
44306 /* PopFrame */
44307 )];
44308 }
44309
44310 }));
44311 STATEMENTS.add(18
44312 /* Yield */
44313 , ([, to, params]) => YieldBlock(to, params));
44314 STATEMENTS.add(17
44315 /* AttrSplat */
44316 , ([, to]) => YieldBlock(to, _util.EMPTY_ARRAY));
44317 STATEMENTS.add(26
44318 /* Debugger */
44319 , ([, evalInfo], meta) => op(106
44320 /* Debugger */
44321 , strArray(meta.evalSymbols), arr(evalInfo)));
44322 STATEMENTS.add(1
44323 /* Append */
44324 , sexp => {
44325 var [, value] = sexp;
44326 return op('CompileInline', {
44327 inline: sexp,
44328 ifUnhandled: () => [op(0
44329 /* PushFrame */
44330 ), op("Expr"
44331 /* Expr */
44332 , value), op(3
44333 /* InvokeStatic */
44334 , {
44335 type: 'stdlib',
44336 value: 'cautious-append'
44337 }), op(1
44338 /* PopFrame */
44339 )]
44340 });
44341 });
44342 STATEMENTS.add(2
44343 /* TrustingAppend */
44344 , sexp => {
44345 var [, value] = sexp;
44346
44347 if (typeof value === 'string') {
44348 return op(41
44349 /* Text */
44350 , value);
44351 } // macro was ignoring trusting flag doesn't seem like {{{}}} should
44352 // even be passed to macros, there is no {{{component}}}
44353
44354
44355 return [op(0
44356 /* PushFrame */
44357 ), op("Expr"
44358 /* Expr */
44359 , value), op(3
44360 /* InvokeStatic */
44361 , {
44362 type: 'stdlib',
44363 value: 'trusting-append'
44364 }), op(1
44365 /* PopFrame */
44366 )];
44367 });
44368 STATEMENTS.add(6
44369 /* Block */
44370 , sexp => {
44371 return op('CompileBlock', sexp);
44372 });
44373 var PLACEHOLDER_HANDLE = -1;
44374
44375 class CompilableTemplateImpl {
44376 constructor(statements, meta$$1, // Part of CompilableTemplate
44377 symbolTable) {
44378 this.statements = statements;
44379 this.meta = meta$$1;
44380 this.symbolTable = symbolTable;
44381 this.compiled = null;
44382 } // Part of CompilableTemplate
44383
44384
44385 compile(context) {
44386 return maybeCompile(this, context);
44387 }
44388
44389 }
44390
44391 function compilable(layout) {
44392 var block = layout.block;
44393 return new CompilableTemplateImpl(block.statements, meta(layout), {
44394 symbols: block.symbols,
44395 hasEval: block.hasEval
44396 });
44397 }
44398
44399 function maybeCompile(compilable, context) {
44400 if (compilable.compiled !== null) return compilable.compiled;
44401 compilable.compiled = PLACEHOLDER_HANDLE;
44402 var {
44403 statements,
44404 meta: meta$$1
44405 } = compilable;
44406 var result = compileStatements(statements, meta$$1, context);
44407 (0, _program.patchStdlibs)(context.program);
44408 compilable.compiled = result;
44409 return result;
44410 }
44411
44412 function compileStatements(statements, meta$$1, syntaxContext) {
44413 var sCompiler = STATEMENTS;
44414 var context = templateCompilationContext(syntaxContext, meta$$1);
44415
44416 for (var i = 0; i < statements.length; i++) {
44417 concatStatements(context, sCompiler.compile(statements[i], context.meta));
44418 }
44419
44420 var handle = context.encoder.commit(syntaxContext.program.heap, meta$$1.size);
44421 return handle;
44422 }
44423
44424 function compilableBlock(overloadBlock, containing) {
44425 var block = Array.isArray(overloadBlock) ? {
44426 statements: overloadBlock,
44427 parameters: _util.EMPTY_ARRAY
44428 } : overloadBlock;
44429 return new CompilableTemplateImpl(block.statements, containing, {
44430 parameters: block.parameters
44431 });
44432 }
44433
44434 class NamedBlocksImpl {
44435 constructor(blocks) {
44436 this.blocks = blocks;
44437 this.names = blocks ? Object.keys(blocks) : [];
44438 }
44439
44440 get(name) {
44441 if (!this.blocks) return null;
44442 return this.blocks[name] || null;
44443 }
44444
44445 has(name) {
44446 var {
44447 blocks
44448 } = this;
44449 return blocks !== null && name in blocks;
44450 }
44451
44452 with(name, block) {
44453 var {
44454 blocks
44455 } = this;
44456
44457 if (blocks) {
44458 return new NamedBlocksImpl((0, _util.assign)({}, blocks, {
44459 [name]: block
44460 }));
44461 } else {
44462 return new NamedBlocksImpl({
44463 [name]: block
44464 });
44465 }
44466 }
44467
44468 get hasAny() {
44469 return this.blocks !== null;
44470 }
44471
44472 }
44473
44474 var EMPTY_BLOCKS = new NamedBlocksImpl(null);
44475 _exports.EMPTY_BLOCKS = EMPTY_BLOCKS;
44476
44477 function namedBlocks(blocks, meta) {
44478 if (blocks === null) {
44479 return EMPTY_BLOCKS;
44480 }
44481
44482 var out = (0, _util.dict)();
44483 var [keys, values] = blocks;
44484
44485 for (var i = 0; i < keys.length; i++) {
44486 out[keys[i]] = compilableBlock(values[i], meta);
44487 }
44488
44489 return new NamedBlocksImpl(out);
44490 }
44491
44492 function expectString(expr, meta, desc) {
44493 if (!meta.upvars) {
44494 return error(`${desc}, but there were no free variables in the template`, 0, 0);
44495 }
44496
44497 if (!Array.isArray(expr)) {
44498 throw new Error(`${desc}, got ${JSON.stringify(expr)}`);
44499 }
44500
44501 if (isGet(expr)) {
44502 var name = simplePathName(expr, meta);
44503 if (name !== null) return name;
44504 }
44505
44506 throw new Error(`${desc}, got ${JSON.stringify(expr)}`);
44507 }
44508
44509 function simplePathName(opcode, meta) {
44510 if (opcode.length === 3 && opcode[2].length > 0) {
44511 return null;
44512 }
44513
44514 if (isGetFree(opcode)) {
44515 return meta.upvars[opcode[1]];
44516 }
44517
44518 return null;
44519 }
44520
44521 function isGet(opcode) {
44522 return opcode.length >= 2 && opcode[0] >= 32
44523 /* GetSymbol */
44524 ;
44525 }
44526
44527 function isGetFree(opcode) {
44528 return opcode[0] >= 33
44529 /* GetFree */
44530 ;
44531 }
44532
44533 function compileInline(sexp, context) {
44534 return context.syntax.macros.inlines.compile(sexp, context);
44535 }
44536
44537 function compileBlock(block, context) {
44538 var [, name, params, hash, named] = block;
44539 var blocks = namedBlocks(named, context.meta);
44540 var nameOrError = expectString(name, context.meta, 'Expected block head to be a string');
44541
44542 if (typeof nameOrError !== 'string') {
44543 return nameOrError;
44544 }
44545
44546 return context.syntax.macros.blocks.compile(nameOrError, params || [], hash, blocks, context);
44547 }
44548
44549 function commit(heap, scopeSize, buffer) {
44550 var handle = heap.malloc();
44551
44552 for (var i = 0; i < buffer.length; i++) {
44553 var value = buffer[i];
44554
44555 if (typeof value === 'function') {
44556 heap.pushPlaceholder(value);
44557 } else if (typeof value === 'object') {
44558 heap.pushStdlib(value);
44559 } else {
44560 heap.push(value);
44561 }
44562 }
44563
44564 heap.finishMalloc(handle, scopeSize);
44565 return handle;
44566 }
44567
44568 var debugCompiler;
44569 _exports.debugCompiler = debugCompiler;
44570
44571 class LabelsImpl {
44572 constructor() {
44573 this.labels = (0, _util.dict)();
44574 this.targets = [];
44575 }
44576
44577 label(name, index) {
44578 this.labels[name] = index;
44579 }
44580
44581 target(at, target) {
44582 this.targets.push({
44583 at,
44584 target
44585 });
44586 }
44587
44588 patch(encoder) {
44589 var {
44590 targets,
44591 labels
44592 } = this;
44593
44594 for (var i = 0; i < targets.length; i++) {
44595 var {
44596 at,
44597 target
44598 } = targets[i];
44599 var address = labels[target] - at;
44600 encoder.patch(at, address);
44601 }
44602 }
44603
44604 }
44605
44606 function error(problem, start, end) {
44607 return op('Error', {
44608 problem,
44609 start,
44610 end
44611 });
44612 }
44613
44614 function op(name, op1, op2, op3) {
44615 if (typeof name === 'number') {
44616 if (op3 !== undefined) {
44617 return {
44618 type: 'Number',
44619 op: name,
44620 op1,
44621 op2,
44622 op3
44623 };
44624 } else if (op2 !== undefined) {
44625 return {
44626 type: 'Number',
44627 op: name,
44628 op1,
44629 op2
44630 };
44631 } else if (op1 !== undefined) {
44632 return {
44633 type: 'Number',
44634 op: name,
44635 op1: op1
44636 };
44637 } else {
44638 return {
44639 type: 'Number',
44640 op: name
44641 };
44642 }
44643 } else {
44644 var type;
44645
44646 if (isCompileOpcode(name)) {
44647 type = 'Compile';
44648 } else if (isResolutionOpcode(name)) {
44649 type = 'Resolution';
44650 } else if (isSimpleOpcode(name)) {
44651 type = 'Simple';
44652 } else if (isErrorOpcode(name)) {
44653 type = 'Error';
44654 } else {
44655 throw new Error(`Exhausted ${name}`);
44656 }
44657
44658 if (op1 === undefined) {
44659 return {
44660 type,
44661 op: name,
44662 op1: undefined
44663 };
44664 } else {
44665 return {
44666 type,
44667 op: name,
44668 op1
44669 };
44670 }
44671 }
44672 }
44673
44674 class EncoderImpl {
44675 constructor() {
44676 this.labelsStack = new _util.Stack();
44677 this.encoder = new _encoder.InstructionEncoderImpl([]);
44678 this.errors = [];
44679 }
44680
44681 error(error) {
44682 this.encoder.encode(30
44683 /* Primitive */
44684 , 0);
44685 this.errors.push(error);
44686 }
44687
44688 commit(heap, size) {
44689 this.encoder.encode(5
44690 /* Return */
44691 , 1024
44692 /* MACHINE_MASK */
44693 );
44694 var handle = commit(heap, size, this.encoder.buffer);
44695
44696 if (this.errors.length) {
44697 return {
44698 errors: this.errors,
44699 handle
44700 };
44701 } else {
44702 return handle;
44703 }
44704 }
44705
44706 push(constants, name, ...args) {
44707 if ((0, _vm.isMachineOp)(name)) {
44708 var operands = args.map((operand, i) => this.operand(constants, operand, i));
44709 return this.encoder.encode(name, 1024
44710 /* MACHINE_MASK */
44711 , ...operands);
44712 } else {
44713 var _operands = args.map((operand, i) => this.operand(constants, operand, i));
44714
44715 return this.encoder.encode(name, 0, ..._operands);
44716 }
44717 }
44718
44719 operand(constants, operand, index) {
44720 if (operand && typeof operand === 'object' && operand.type === 'label') {
44721 this.currentLabels.target(this.encoder.size + index, operand.value);
44722 return -1;
44723 }
44724
44725 return constant(constants, operand);
44726 }
44727
44728 get currentLabels() {
44729 return this.labelsStack.current;
44730 }
44731
44732 label(name) {
44733 this.currentLabels.label(name, this.encoder.size);
44734 }
44735
44736 startLabels() {
44737 this.labelsStack.push(new LabelsImpl());
44738 }
44739
44740 stopLabels() {
44741 var label = this.labelsStack.pop();
44742 label.patch(this.encoder);
44743 }
44744
44745 }
44746
44747 function constant(constants, operand) {
44748 if (typeof operand === 'number' || typeof operand === 'function') {
44749 return operand;
44750 }
44751
44752 if (typeof operand === 'boolean') {
44753 return operand === true ? 1 : 0;
44754 }
44755
44756 if (typeof operand === 'string') {
44757 return constants.value(operand);
44758 }
44759
44760 if (operand === null) {
44761 return 0;
44762 }
44763
44764 switch (operand.type) {
44765 case 'string-array':
44766 return constants.array(operand.value);
44767
44768 case 'serializable':
44769 return constants.serializable(operand.value);
44770
44771 case 'stdlib':
44772 return operand;
44773
44774 case 'immediate':
44775 return (0, _util.encodeImmediate)(operand.value);
44776
44777 case 'primitive':
44778 case 'template-meta':
44779 case 'array':
44780 case 'other':
44781 return (0, _util.encodeHandle)(constants.value(operand.value));
44782
44783 case 'lookup':
44784 throw (0, _util.unreachable)('lookup not reachable');
44785
44786 default:
44787 return (0, _util.exhausted)(operand);
44788 }
44789 }
44790
44791 function isSimpleOpcode(op) {
44792 return op === 'Label' || op === 'Option' || op === 'GetComponentLayout' || op === 'StartLabels' || op === 'StopLabels' || op === 'SimpleArgs' || op === 'JitCompileBlock' || op === 'SetBlock';
44793 }
44794
44795 function isCompileOpcode(op) {
44796 return op === 'CompileInline' || op === 'CompileBlock' || op === 'InvokeStatic' || op === 'PushCompilable' || op === 'Args' || op === 'IfResolvedComponent' || op === 'DynamicComponent';
44797 }
44798
44799 function isResolutionOpcode(op) {
44800 return op === 'IfResolved' || op === 'Expr' || op === 'SimpleArgs' || op === 'ResolveFree' || op === 'ResolveContextualFree';
44801 }
44802
44803 function isErrorOpcode(op) {
44804 return op === 'Error';
44805 }
44806 /**
44807 * Compile arguments, pushing an Arguments object onto the stack.
44808 *
44809 * @param args.params
44810 * @param args.hash
44811 * @param args.blocks
44812 * @param args.atNames
44813 */
44814
44815
44816 function CompileArgs({
44817 params,
44818 hash,
44819 blocks,
44820 atNames
44821 }) {
44822 var out = [];
44823 var blockNames = blocks.names;
44824
44825 for (var i = 0; i < blockNames.length; i++) {
44826 out.push(PushYieldableBlock(blocks.get(blockNames[i])));
44827 }
44828
44829 var {
44830 count,
44831 actions
44832 } = CompilePositional(params);
44833 out.push(actions);
44834 var flags = count << 4;
44835 if (atNames) flags |= 0b1000;
44836
44837 if (blocks) {
44838 flags |= 0b111;
44839 }
44840
44841 var names = _util.EMPTY_ARRAY;
44842
44843 if (hash) {
44844 names = hash[0];
44845 var val = hash[1];
44846
44847 for (var _i = 0; _i < val.length; _i++) {
44848 out.push(op('Expr', val[_i]));
44849 }
44850 }
44851
44852 out.push(op(84
44853 /* PushArgs */
44854 , strArray(names), strArray(blockNames), flags));
44855 return out;
44856 }
44857 /**
44858 * Compile an optional list of positional arguments, which pushes each argument
44859 * onto the stack and returns the number of parameters compiled
44860 *
44861 * @param params an optional list of positional arguments
44862 */
44863
44864
44865 function CompilePositional(params) {
44866 if (!params) return {
44867 count: 0,
44868 actions: NONE
44869 };
44870 var actions = [];
44871
44872 for (var i = 0; i < params.length; i++) {
44873 actions.push(op('Expr', params[i]));
44874 }
44875
44876 return {
44877 count: params.length,
44878 actions
44879 };
44880 }
44881
44882 function meta(layout) {
44883 return {
44884 asPartial: layout.asPartial || false,
44885 evalSymbols: evalSymbols(layout),
44886 upvars: layout.block.upvars,
44887 referrer: layout.referrer,
44888 size: layout.block.symbols.length
44889 };
44890 }
44891
44892 function evalSymbols(layout) {
44893 var {
44894 block
44895 } = layout;
44896 return block.hasEval ? block.symbols : null;
44897 }
44898
44899 var ATTRS_BLOCK = '&attrs';
44900
44901 function StaticComponentHelper(context, tag, hash, template) {
44902 var component = resolveLayoutForTag(tag, context);
44903
44904 if (component !== null) {
44905 var {
44906 compilable: compilable$$1,
44907 handle,
44908 capabilities
44909 } = component;
44910
44911 if (compilable$$1) {
44912 if (hash) {
44913 for (var i = 0; i < hash.length; i = i + 2) {
44914 hash[i][0] = `@${hash[i][0]}`;
44915 }
44916 }
44917
44918 var out = [op(80
44919 /* PushComponentDefinition */
44920 , handle)];
44921 out.push(InvokeStaticComponent({
44922 capabilities,
44923 layout: compilable$$1,
44924 attrs: null,
44925 params: null,
44926 hash,
44927 blocks: new NamedBlocksImpl({
44928 default: template
44929 })
44930 }));
44931 return out;
44932 }
44933 }
44934
44935 return UNHANDLED;
44936 }
44937
44938 function InvokeStaticComponent({
44939 capabilities,
44940 layout,
44941 attrs,
44942 params,
44943 hash,
44944 blocks
44945 }) {
44946 var {
44947 symbolTable
44948 } = layout;
44949 var bailOut = symbolTable.hasEval || capabilities.prepareArgs;
44950
44951 if (bailOut) {
44952 return InvokeComponent({
44953 capabilities,
44954 attrs,
44955 params,
44956 hash,
44957 atNames: true,
44958 blocks,
44959 layout
44960 });
44961 }
44962
44963 var out = [op(36
44964 /* Fetch */
44965 , _vm.$s0), op(33
44966 /* Dup */
44967 , _vm.$sp, 1), op(35
44968 /* Load */
44969 , _vm.$s0)];
44970 var {
44971 symbols
44972 } = symbolTable;
44973
44974 if (capabilities.createArgs) {
44975 out.push(op(0
44976 /* PushFrame */
44977 ), op('SimpleArgs', {
44978 params,
44979 hash,
44980 atNames: true
44981 }));
44982 }
44983
44984 out.push(op(100
44985 /* BeginComponentTransaction */
44986 ));
44987
44988 if (capabilities.dynamicScope) {
44989 out.push(op(59
44990 /* PushDynamicScope */
44991 ));
44992 }
44993
44994 if (capabilities.createInstance) {
44995 out.push(op(89
44996 /* CreateComponent */
44997 , blocks.has('default') | 0, _vm.$s0));
44998 }
44999
45000 if (capabilities.createArgs) {
45001 out.push(op(1
45002 /* PopFrame */
45003 ));
45004 }
45005
45006 out.push(op(0
45007 /* PushFrame */
45008 ), op(90
45009 /* RegisterComponentDestructor */
45010 , _vm.$s0));
45011 var bindings = [];
45012 out.push(op(92
45013 /* GetComponentSelf */
45014 , _vm.$s0));
45015 bindings.push({
45016 symbol: 0,
45017 isBlock: false
45018 });
45019
45020 for (var i = 0; i < symbols.length; i++) {
45021 var symbol = symbols[i];
45022
45023 switch (symbol.charAt(0)) {
45024 case '&':
45025 var callerBlock = void 0;
45026
45027 if (symbol === ATTRS_BLOCK) {
45028 callerBlock = attrs;
45029 } else {
45030 callerBlock = blocks.get(symbol.slice(1));
45031 }
45032
45033 if (callerBlock) {
45034 out.push(PushYieldableBlock(callerBlock));
45035 bindings.push({
45036 symbol: i + 1,
45037 isBlock: true
45038 });
45039 } else {
45040 out.push(PushYieldableBlock(null));
45041 bindings.push({
45042 symbol: i + 1,
45043 isBlock: true
45044 });
45045 }
45046
45047 break;
45048
45049 case '@':
45050 if (!hash) {
45051 break;
45052 }
45053
45054 var [keys, values] = hash;
45055 var lookupName = symbol;
45056 var index = keys.indexOf(lookupName);
45057
45058 if (index !== -1) {
45059 out.push(op('Expr', values[index]));
45060 bindings.push({
45061 symbol: i + 1,
45062 isBlock: false
45063 });
45064 }
45065
45066 break;
45067 }
45068 }
45069
45070 out.push(op(37
45071 /* RootScope */
45072 , symbols.length + 1, Object.keys(blocks).length > 0 ? 1 : 0));
45073
45074 for (var _i2 = bindings.length - 1; _i2 >= 0; _i2--) {
45075 var {
45076 symbol: _symbol,
45077 isBlock
45078 } = bindings[_i2];
45079
45080 if (isBlock) {
45081 out.push(op('SetBlock', _symbol));
45082 } else {
45083 out.push(op(19
45084 /* SetVariable */
45085 , _symbol));
45086 }
45087 }
45088
45089 out.push(op('InvokeStatic', layout));
45090
45091 if (capabilities.createInstance) {
45092 out.push(op(103
45093 /* DidRenderLayout */
45094 , _vm.$s0));
45095 }
45096
45097 out.push(op(1
45098 /* PopFrame */
45099 ), op(40
45100 /* PopScope */
45101 ));
45102
45103 if (capabilities.dynamicScope) {
45104 out.push(op(60
45105 /* PopDynamicScope */
45106 ));
45107 }
45108
45109 out.push(op(101
45110 /* CommitComponentTransaction */
45111 ), op(35
45112 /* Load */
45113 , _vm.$s0));
45114 return out;
45115 }
45116
45117 function InvokeDynamicComponent(meta$$1, {
45118 definition,
45119 attrs,
45120 params,
45121 hash,
45122 atNames,
45123 blocks
45124 }) {
45125 return Replayable({
45126 args: () => {
45127 return {
45128 count: 2,
45129 actions: [op('Expr', definition), op(33
45130 /* Dup */
45131 , _vm.$sp, 0)]
45132 };
45133 },
45134 body: () => {
45135 return [op(66
45136 /* JumpUnless */
45137 , label('ELSE')), op(83
45138 /* ResolveDynamicComponent */
45139 , templateMeta(meta$$1.referrer)), op(81
45140 /* PushDynamicComponentInstance */
45141 ), InvokeComponent({
45142 capabilities: true,
45143 attrs,
45144 params,
45145 hash,
45146 atNames,
45147 blocks
45148 }), op('Label', 'ELSE')];
45149 }
45150 });
45151 }
45152
45153 function WrappedComponent(layout, attrsBlockNumber) {
45154 return [op('StartLabels'), WithSavedRegister(_vm.$s1, () => [op(93
45155 /* GetComponentTagName */
45156 , _vm.$s0), op(31
45157 /* PrimitiveReference */
45158 ), op(33
45159 /* Dup */
45160 , _vm.$sp, 0)]), op(66
45161 /* JumpUnless */
45162 , label('BODY')), op(36
45163 /* Fetch */
45164 , _vm.$s1), op(91
45165 /* PutComponentOperations */
45166 ), op(49
45167 /* OpenDynamicElement */
45168 ), op(102
45169 /* DidCreateElement */
45170 , _vm.$s0), YieldBlock(attrsBlockNumber, _util.EMPTY_ARRAY), op(54
45171 /* FlushElement */
45172 ), op('Label', 'BODY'), InvokeStaticBlock(blockForLayout(layout)), op(36
45173 /* Fetch */
45174 , _vm.$s1), op(66
45175 /* JumpUnless */
45176 , label('END')), op(55
45177 /* CloseElement */
45178 ), op('Label', 'END'), op(35
45179 /* Load */
45180 , _vm.$s1), op('StopLabels')];
45181 }
45182
45183 function StaticComponent(component, args$$1) {
45184 var [params, hash, blocks] = args$$1;
45185 if (component === null) return NONE;
45186 var {
45187 compilable: compilable$$1,
45188 capabilities,
45189 handle
45190 } = component;
45191
45192 if (compilable$$1) {
45193 return [op(80
45194 /* PushComponentDefinition */
45195 , handle), InvokeStaticComponent({
45196 capabilities: capabilities || MINIMAL_CAPABILITIES,
45197 layout: compilable$$1,
45198 attrs: null,
45199 params,
45200 hash,
45201 blocks
45202 })];
45203 } else {
45204 return [op(80
45205 /* PushComponentDefinition */
45206 , handle), InvokeComponent({
45207 capabilities: capabilities || MINIMAL_CAPABILITIES,
45208 attrs: null,
45209 params,
45210 hash,
45211 atNames: true,
45212 blocks
45213 })];
45214 }
45215 }
45216
45217 function InvokeComponent({
45218 capabilities,
45219 attrs,
45220 params,
45221 hash,
45222 atNames,
45223 blocks: namedBlocks$$1,
45224 layout
45225 }) {
45226 var bindableBlocks = !!namedBlocks$$1;
45227 var bindableAtNames = capabilities === true || capabilities.prepareArgs || !!(hash && hash[0].length !== 0);
45228 var blocks = namedBlocks$$1.with('attrs', attrs);
45229 return [op(36
45230 /* Fetch */
45231 , _vm.$s0), op(33
45232 /* Dup */
45233 , _vm.$sp, 1), op(35
45234 /* Load */
45235 , _vm.$s0), op(0
45236 /* PushFrame */
45237 ), op('Args', {
45238 params,
45239 hash,
45240 blocks,
45241 atNames
45242 }), op(87
45243 /* PrepareArgs */
45244 , _vm.$s0), invokePreparedComponent(blocks.has('default'), bindableBlocks, bindableAtNames, () => {
45245 var out;
45246
45247 if (layout) {
45248 out = [PushSymbolTable(layout.symbolTable), op('PushCompilable', layout), op('JitCompileBlock')];
45249 } else {
45250 out = [op('GetComponentLayout', _vm.$s0)];
45251 }
45252
45253 out.push(op(98
45254 /* PopulateLayout */
45255 , _vm.$s0));
45256 return out;
45257 }), op(35
45258 /* Load */
45259 , _vm.$s0)];
45260 }
45261
45262 function invokePreparedComponent(hasBlock, bindableBlocks, bindableAtNames, populateLayout = null) {
45263 var out = [op(100
45264 /* BeginComponentTransaction */
45265 ), op(59
45266 /* PushDynamicScope */
45267 ), op(89
45268 /* CreateComponent */
45269 , hasBlock | 0, _vm.$s0)]; // this has to run after createComponent to allow
45270 // for late-bound layouts, but a caller is free
45271 // to populate the layout earlier if it wants to
45272 // and do nothing here.
45273
45274 if (populateLayout) {
45275 out.push(populateLayout());
45276 }
45277
45278 out.push(op(90
45279 /* RegisterComponentDestructor */
45280 , _vm.$s0), op(92
45281 /* GetComponentSelf */
45282 , _vm.$s0), op(38
45283 /* VirtualRootScope */
45284 , _vm.$s0), op(19
45285 /* SetVariable */
45286 , 0), op(97
45287 /* SetupForEval */
45288 , _vm.$s0), bindableAtNames ? op(17
45289 /* SetNamedVariables */
45290 , _vm.$s0) : NONE, bindableBlocks ? op(18
45291 /* SetBlocks */
45292 , _vm.$s0) : NONE, op(34
45293 /* Pop */
45294 , 1), op(99
45295 /* InvokeComponentLayout */
45296 , _vm.$s0), op(103
45297 /* DidRenderLayout */
45298 , _vm.$s0), op(1
45299 /* PopFrame */
45300 ), op(40
45301 /* PopScope */
45302 ), op(60
45303 /* PopDynamicScope */
45304 ), op(101
45305 /* CommitComponentTransaction */
45306 ));
45307 return out;
45308 }
45309
45310 function InvokeBareComponent() {
45311 return [op(36
45312 /* Fetch */
45313 , _vm.$s0), op(33
45314 /* Dup */
45315 , _vm.$sp, 1), op(35
45316 /* Load */
45317 , _vm.$s0), op(0
45318 /* PushFrame */
45319 ), op(85
45320 /* PushEmptyArgs */
45321 ), op(87
45322 /* PrepareArgs */
45323 , _vm.$s0), invokePreparedComponent(false, false, true, () => [op('GetComponentLayout', _vm.$s0), op(98
45324 /* PopulateLayout */
45325 , _vm.$s0)]), op(35
45326 /* Load */
45327 , _vm.$s0)];
45328 }
45329
45330 function curryComponent({
45331 definition,
45332 params,
45333 hash,
45334 atNames
45335 }, referrer) {
45336 return [op(0
45337 /* PushFrame */
45338 ), op('SimpleArgs', {
45339 params,
45340 hash,
45341 atNames
45342 }), op(88
45343 /* CaptureArgs */
45344 ), op('Expr', definition), op(79
45345 /* CurryComponent */
45346 , templateMeta(referrer)), op(1
45347 /* PopFrame */
45348 ), op(36
45349 /* Fetch */
45350 , _vm.$v0)];
45351 }
45352
45353 function blockForLayout(layout) {
45354 return compilableBlock(layout.block.statements, meta(layout));
45355 }
45356
45357 function WithSavedRegister(register, block) {
45358 return [op(36
45359 /* Fetch */
45360 , register), block(), op(35
45361 /* Load */
45362 , register)];
45363 }
45364
45365 class StdLib {
45366 constructor(main, trustingGuardedAppend, cautiousGuardedAppend) {
45367 this.main = main;
45368 this.trustingGuardedAppend = trustingGuardedAppend;
45369 this.cautiousGuardedAppend = cautiousGuardedAppend;
45370 }
45371
45372 get 'trusting-append'() {
45373 return this.trustingGuardedAppend;
45374 }
45375
45376 get 'cautious-append'() {
45377 return this.cautiousGuardedAppend;
45378 }
45379
45380 getAppend(trusting) {
45381 return trusting ? this.trustingGuardedAppend : this.cautiousGuardedAppend;
45382 }
45383
45384 }
45385
45386 _exports.StdLib = StdLib;
45387
45388 function main() {
45389 return [op(76
45390 /* Main */
45391 , _vm.$s0), invokePreparedComponent(false, false, true)];
45392 }
45393 /**
45394 * Append content to the DOM. This standard function triages content and does the
45395 * right thing based upon whether it's a string, safe string, component, fragment
45396 * or node.
45397 *
45398 * @param trusting whether to interpolate a string as raw HTML (corresponds to
45399 * triple curlies)
45400 */
45401
45402
45403 function StdAppend(trusting) {
45404 return [op(78
45405 /* ContentType */
45406 ), SwitchCases(when => {
45407 when(1
45408 /* String */
45409 , () => {
45410 if (trusting) {
45411 return [op(68
45412 /* AssertSame */
45413 ), op(43
45414 /* AppendHTML */
45415 )];
45416 } else {
45417 return op(47
45418 /* AppendText */
45419 );
45420 }
45421 });
45422 when(0
45423 /* Component */
45424 , () => [op(82
45425 /* PushCurriedComponent */
45426 ), op(81
45427 /* PushDynamicComponentInstance */
45428 ), InvokeBareComponent()]);
45429 when(3
45430 /* SafeString */
45431 , () => [op(68
45432 /* AssertSame */
45433 ), op(44
45434 /* AppendSafeHTML */
45435 )]);
45436 when(4
45437 /* Fragment */
45438 , () => [op(68
45439 /* AssertSame */
45440 ), op(45
45441 /* AppendDocumentFragment */
45442 )]);
45443 when(5
45444 /* Node */
45445 , () => [op(68
45446 /* AssertSame */
45447 ), op(46
45448 /* AppendNode */
45449 )]);
45450 })];
45451 }
45452
45453 function compileStd(context) {
45454 var mainHandle = build(context, main);
45455 var trustingGuardedAppend = build(context, () => StdAppend(true));
45456 var cautiousGuardedAppend = build(context, () => StdAppend(false));
45457 return new StdLib(mainHandle, trustingGuardedAppend, cautiousGuardedAppend);
45458 }
45459
45460 var STDLIB_META = {
45461 asPartial: false,
45462 evalSymbols: null,
45463 upvars: null,
45464 // TODO: ??
45465 referrer: {},
45466 size: 0
45467 };
45468
45469 function build(program, callback) {
45470 var encoder = new EncoderImpl();
45471 var macros = new MacrosImpl();
45472 var stdContext = {
45473 encoder,
45474 meta: STDLIB_META,
45475 syntax: {
45476 macros,
45477 program
45478 }
45479 };
45480 concat(stdContext, callback());
45481 var result = encoder.commit(program.heap, 0);
45482
45483 if (typeof result !== 'number') {
45484 // This shouldn't be possible
45485 throw new Error(`Unexpected errors compiling std`);
45486 } else {
45487 return result;
45488 }
45489 }
45490
45491 class ProgramCompilationContext {
45492 constructor(delegate, mode) {
45493 this.mode = mode;
45494 this.constants = new _program.WriteOnlyConstants();
45495 this.heap = new _program.HeapImpl();
45496 this.resolverDelegate = delegate;
45497 this.stdlib = compileStd(this);
45498 }
45499
45500 }
45501
45502 _exports.ProgramCompilationContext = ProgramCompilationContext;
45503
45504 class JitProgramCompilationContext {
45505 constructor(delegate) {
45506 this.constants = new _program.JitConstants();
45507 this.heap = new _program.HeapImpl();
45508 this.mode = "jit"
45509 /* jit */
45510 ;
45511 this.resolverDelegate = delegate;
45512 this.stdlib = compileStd(this);
45513 }
45514
45515 }
45516
45517 _exports.JitProgramCompilationContext = JitProgramCompilationContext;
45518
45519 class PartialDefinitionImpl {
45520 constructor(name, // for debugging
45521 template) {
45522 this.name = name;
45523 this.template = template;
45524 }
45525
45526 getPartial(context) {
45527 var partial = (0, _util.unwrapTemplate)(this.template).asPartial();
45528 var handle = partial.compile(context);
45529 return {
45530 symbolTable: partial.symbolTable,
45531 handle
45532 };
45533 }
45534
45535 }
45536
45537 _exports.PartialDefinitionImpl = PartialDefinitionImpl;
45538
45539 class WrappedBuilder {
45540 constructor(layout) {
45541 this.layout = layout;
45542 this.compiled = null;
45543 var {
45544 block
45545 } = layout;
45546 var symbols = block.symbols.slice(); // ensure ATTRS_BLOCK is always included (only once) in the list of symbols
45547
45548 var attrsBlockIndex = symbols.indexOf(ATTRS_BLOCK);
45549
45550 if (attrsBlockIndex === -1) {
45551 this.attrsBlockNumber = symbols.push(ATTRS_BLOCK);
45552 } else {
45553 this.attrsBlockNumber = attrsBlockIndex + 1;
45554 }
45555
45556 this.symbolTable = {
45557 hasEval: block.hasEval,
45558 symbols
45559 };
45560 }
45561
45562 compile(syntax) {
45563 if (this.compiled !== null) return this.compiled;
45564 var m = meta(this.layout);
45565 var context = templateCompilationContext(syntax, m);
45566 var actions = WrappedComponent(this.layout, this.attrsBlockNumber);
45567 concatStatements(context, actions);
45568 var handle = context.encoder.commit(context.syntax.program.heap, m.size);
45569
45570 if (typeof handle !== 'number') {
45571 return handle;
45572 }
45573
45574 this.compiled = handle;
45575 (0, _program.patchStdlibs)(context.syntax.program);
45576 return handle;
45577 }
45578
45579 }
45580
45581 _exports.WrappedBuilder = WrappedBuilder;
45582 var clientId = 0;
45583
45584 function templateFactory({
45585 id: templateId,
45586 meta,
45587 block
45588 }) {
45589 var parsedBlock;
45590 var id = templateId || `client-${clientId++}`;
45591
45592 var create = envMeta => {
45593 var newMeta = envMeta ? (0, _util.assign)({}, envMeta, meta) : meta;
45594
45595 if (!parsedBlock) {
45596 parsedBlock = JSON.parse(block);
45597 }
45598
45599 return new TemplateImpl({
45600 id,
45601 block: parsedBlock,
45602 referrer: newMeta
45603 });
45604 };
45605
45606 return {
45607 id,
45608 meta,
45609 create
45610 };
45611 }
45612
45613 class TemplateImpl {
45614 constructor(parsedLayout) {
45615 this.parsedLayout = parsedLayout;
45616 this.result = 'ok';
45617 this.layout = null;
45618 this.partial = null;
45619 this.wrappedLayout = null;
45620 var {
45621 block
45622 } = parsedLayout;
45623 this.symbols = block.symbols;
45624 this.hasEval = block.hasEval;
45625 this.referrer = parsedLayout.referrer;
45626 this.id = parsedLayout.id || `client-${clientId++}`;
45627 }
45628
45629 asLayout() {
45630 if (this.layout) return this.layout;
45631 return this.layout = compilable((0, _util.assign)({}, this.parsedLayout, {
45632 asPartial: false
45633 }));
45634 }
45635
45636 asPartial() {
45637 if (this.partial) return this.partial;
45638 return this.layout = compilable((0, _util.assign)({}, this.parsedLayout, {
45639 asPartial: true
45640 }));
45641 }
45642
45643 asWrappedLayout() {
45644 if (this.wrappedLayout) return this.wrappedLayout;
45645 return this.wrappedLayout = new WrappedBuilder((0, _util.assign)({}, this.parsedLayout, {
45646 asPartial: false
45647 }));
45648 }
45649
45650 }
45651
45652 function Component(serialized, envMeta) {
45653 var parsed = JSON.parse(serialized);
45654 var factory = templateFactory(parsed);
45655 var template = (0, _util.unwrapTemplate)(factory.create(envMeta));
45656 return template.asLayout();
45657 }
45658});
45659define("@glimmer/program", ["exports", "@glimmer/util"], function (_exports, _util) {
45660 "use strict";
45661
45662 Object.defineProperty(_exports, "__esModule", {
45663 value: true
45664 });
45665 _exports.hydrateHeap = hydrateHeap;
45666 _exports.hydrateProgram = hydrateProgram;
45667 _exports.patchStdlibs = patchStdlibs;
45668 _exports.programArtifacts = programArtifacts;
45669 _exports.artifacts = artifacts;
45670 _exports.RuntimeOpImpl = _exports.RuntimeProgramImpl = _exports.HeapImpl = _exports.RuntimeHeapImpl = _exports.JitConstants = _exports.RuntimeConstantsImpl = _exports.WriteOnlyConstants = void 0;
45671 var WELL_KNOWN_EMPTY_ARRAY = Object.freeze([]);
45672 var STARTER_CONSTANTS = (0, _util.constants)(WELL_KNOWN_EMPTY_ARRAY);
45673 var WELL_KNOWN_EMPTY_ARRAY_POSITION = STARTER_CONSTANTS.indexOf(WELL_KNOWN_EMPTY_ARRAY);
45674
45675 class WriteOnlyConstants {
45676 constructor() {
45677 // `0` means NULL
45678 this.values = STARTER_CONSTANTS.slice();
45679 this.indexMap = new Map(this.values.map((value, index) => [value, index]));
45680 }
45681
45682 value(value) {
45683 var indexMap = this.indexMap;
45684 var index = indexMap.get(value);
45685
45686 if (index === undefined) {
45687 index = this.values.push(value) - 1;
45688 indexMap.set(value, index);
45689 }
45690
45691 return index;
45692 }
45693
45694 array(values) {
45695 if (values.length === 0) {
45696 return WELL_KNOWN_EMPTY_ARRAY_POSITION;
45697 }
45698
45699 var handles = new Array(values.length);
45700
45701 for (var i = 0; i < values.length; i++) {
45702 handles[i] = this.value(values[i]);
45703 }
45704
45705 return this.value(handles);
45706 }
45707
45708 serializable(value) {
45709 var str = JSON.stringify(value);
45710 return this.value(str);
45711 }
45712
45713 toPool() {
45714 return this.values;
45715 }
45716
45717 }
45718
45719 _exports.WriteOnlyConstants = WriteOnlyConstants;
45720
45721 class RuntimeConstantsImpl {
45722 constructor(pool) {
45723 this.values = pool;
45724 }
45725
45726 getValue(handle) {
45727 return this.values[handle];
45728 }
45729
45730 getArray(value) {
45731 var handles = this.getValue(value);
45732 var reified = new Array(handles.length);
45733
45734 for (var i = 0; i < handles.length; i++) {
45735 var n = handles[i];
45736 reified[i] = this.getValue(n);
45737 }
45738
45739 return reified;
45740 }
45741
45742 getSerializable(s) {
45743 return JSON.parse(this.values[s]);
45744 }
45745
45746 }
45747
45748 _exports.RuntimeConstantsImpl = RuntimeConstantsImpl;
45749
45750 class JitConstants extends WriteOnlyConstants {
45751 constructor() {
45752 super(...arguments);
45753 this.reifiedArrs = {
45754 [WELL_KNOWN_EMPTY_ARRAY_POSITION]: WELL_KNOWN_EMPTY_ARRAY
45755 };
45756 }
45757
45758 templateMeta(meta) {
45759 return this.value(meta);
45760 }
45761
45762 getValue(index) {
45763 return this.values[index];
45764 }
45765
45766 getArray(index) {
45767 var reifiedArrs = this.reifiedArrs;
45768 var reified = reifiedArrs[index];
45769
45770 if (reified === undefined) {
45771 var names = this.getValue(index);
45772 reified = new Array(names.length);
45773
45774 for (var i = 0; i < names.length; i++) {
45775 reified[i] = this.getValue(names[i]);
45776 }
45777
45778 reifiedArrs[index] = reified;
45779 }
45780
45781 return reified;
45782 }
45783
45784 getSerializable(s) {
45785 return JSON.parse(this.getValue(s));
45786 }
45787
45788 }
45789
45790 _exports.JitConstants = JitConstants;
45791
45792 class RuntimeOpImpl {
45793 constructor(heap) {
45794 this.heap = heap;
45795 this.offset = 0;
45796 }
45797
45798 get size() {
45799 var rawType = this.heap.getbyaddr(this.offset);
45800 return ((rawType & 768
45801 /* OPERAND_LEN_MASK */
45802 ) >> 8
45803 /* ARG_SHIFT */
45804 ) + 1;
45805 }
45806
45807 get isMachine() {
45808 var rawType = this.heap.getbyaddr(this.offset);
45809 return rawType & 1024
45810 /* MACHINE_MASK */
45811 ? 1 : 0;
45812 }
45813
45814 get type() {
45815 return this.heap.getbyaddr(this.offset) & 255
45816 /* TYPE_MASK */
45817 ;
45818 }
45819
45820 get op1() {
45821 return this.heap.getbyaddr(this.offset + 1);
45822 }
45823
45824 get op2() {
45825 return this.heap.getbyaddr(this.offset + 2);
45826 }
45827
45828 get op3() {
45829 return this.heap.getbyaddr(this.offset + 3);
45830 }
45831
45832 }
45833
45834 _exports.RuntimeOpImpl = RuntimeOpImpl;
45835
45836 function encodeTableInfo(scopeSize, state) {
45837 return state | scopeSize << 2;
45838 }
45839
45840 function changeState(info, newState) {
45841 return info | newState << 30;
45842 }
45843
45844 var PAGE_SIZE = 0x100000;
45845
45846 class RuntimeHeapImpl {
45847 constructor(serializedHeap) {
45848 var {
45849 buffer,
45850 table
45851 } = serializedHeap;
45852 this.heap = new Int32Array(buffer);
45853 this.table = table;
45854 } // It is illegal to close over this address, as compaction
45855 // may move it. However, it is legal to use this address
45856 // multiple times between compactions.
45857
45858
45859 getaddr(handle) {
45860 return this.table[handle];
45861 }
45862
45863 getbyaddr(address) {
45864 return this.heap[address];
45865 }
45866
45867 sizeof(handle) {
45868 return sizeof(this.table, handle);
45869 }
45870
45871 scopesizeof(handle) {
45872 return scopesizeof(this.table, handle);
45873 }
45874
45875 }
45876
45877 _exports.RuntimeHeapImpl = RuntimeHeapImpl;
45878
45879 function hydrateHeap(serializedHeap) {
45880 return new RuntimeHeapImpl(serializedHeap);
45881 }
45882 /**
45883 * The Heap is responsible for dynamically allocating
45884 * memory in which we read/write the VM's instructions
45885 * from/to. When we malloc we pass out a VMHandle, which
45886 * is used as an indirect way of accessing the memory during
45887 * execution of the VM. Internally we track the different
45888 * regions of the memory in an int array known as the table.
45889 *
45890 * The table 32-bit aligned and has the following layout:
45891 *
45892 * | ... | hp (u32) | info (u32) | size (u32) |
45893 * | ... | Handle | Scope Size | State | Size |
45894 * | ... | 32bits | 30bits | 2bits | 32bit |
45895 *
45896 * With this information we effectively have the ability to
45897 * control when we want to free memory. That being said you
45898 * can not free during execution as raw address are only
45899 * valid during the execution. This means you cannot close
45900 * over them as you will have a bad memory access exception.
45901 */
45902
45903
45904 class HeapImpl {
45905 constructor() {
45906 this.placeholders = [];
45907 this.stdlibs = [];
45908 this.offset = 0;
45909 this.handle = 0;
45910 this.capacity = PAGE_SIZE;
45911 this.heap = new Int32Array(PAGE_SIZE);
45912 this.table = [];
45913 }
45914
45915 push(item) {
45916 this.sizeCheck();
45917 this.heap[this.offset++] = item;
45918 }
45919
45920 sizeCheck() {
45921 if (this.capacity === 0) {
45922 var heap = slice(this.heap, 0, this.offset);
45923 this.heap = new Int32Array(heap.length + PAGE_SIZE);
45924 this.heap.set(heap, 0);
45925 this.capacity = PAGE_SIZE;
45926 }
45927
45928 this.capacity--;
45929 }
45930
45931 getbyaddr(address) {
45932 return this.heap[address];
45933 }
45934
45935 setbyaddr(address, value) {
45936 this.heap[address] = value;
45937 }
45938
45939 malloc() {
45940 // push offset, info, size
45941 this.table.push(this.offset, 0, 0);
45942 var handle = this.handle;
45943 this.handle += 3
45944 /* ENTRY_SIZE */
45945 ;
45946 return handle;
45947 }
45948
45949 finishMalloc(handle, scopeSize) {
45950 this.table[handle + 1
45951 /* INFO_OFFSET */
45952 ] = encodeTableInfo(scopeSize, 0
45953 /* Allocated */
45954 );
45955 }
45956
45957 size() {
45958 return this.offset;
45959 } // It is illegal to close over this address, as compaction
45960 // may move it. However, it is legal to use this address
45961 // multiple times between compactions.
45962
45963
45964 getaddr(handle) {
45965 return this.table[handle];
45966 }
45967
45968 gethandle(address) {
45969 this.table.push(address, encodeTableInfo(0, 3
45970 /* Pointer */
45971 ), 0);
45972 var handle = this.handle;
45973 this.handle += 3
45974 /* ENTRY_SIZE */
45975 ;
45976 return handle;
45977 }
45978
45979 sizeof(handle) {
45980 return sizeof(this.table, handle);
45981 }
45982
45983 scopesizeof(handle) {
45984 return scopesizeof(this.table, handle);
45985 }
45986
45987 free(handle) {
45988 var info = this.table[handle + 1
45989 /* INFO_OFFSET */
45990 ];
45991 this.table[handle + 1
45992 /* INFO_OFFSET */
45993 ] = changeState(info, 1
45994 /* Freed */
45995 );
45996 }
45997 /**
45998 * The heap uses the [Mark-Compact Algorithm](https://en.wikipedia.org/wiki/Mark-compact_algorithm) to shift
45999 * reachable memory to the bottom of the heap and freeable
46000 * memory to the top of the heap. When we have shifted all
46001 * the reachable memory to the top of the heap, we move the
46002 * offset to the next free position.
46003 */
46004
46005
46006 compact() {
46007 var compactedSize = 0;
46008 var {
46009 table,
46010 table: {
46011 length
46012 },
46013 heap
46014 } = this;
46015
46016 for (var i = 0; i < length; i += 3
46017 /* ENTRY_SIZE */
46018 ) {
46019 var offset = table[i];
46020 var info = table[i + 1
46021 /* INFO_OFFSET */
46022 ]; // @ts-ignore (this whole function is currently unused)
46023
46024 var size = info & Size.SIZE_MASK;
46025 var state = info & 3
46026 /* STATE_MASK */
46027 >> 30;
46028
46029 if (state === 2
46030 /* Purged */
46031 ) {
46032 continue;
46033 } else if (state === 1
46034 /* Freed */
46035 ) {
46036 // transition to "already freed" aka "purged"
46037 // a good improvement would be to reuse
46038 // these slots
46039 table[i + 1
46040 /* INFO_OFFSET */
46041 ] = changeState(info, 2
46042 /* Purged */
46043 );
46044 compactedSize += size;
46045 } else if (state === 0
46046 /* Allocated */
46047 ) {
46048 for (var j = offset; j <= i + size; j++) {
46049 heap[j - compactedSize] = heap[j];
46050 }
46051
46052 table[i] = offset - compactedSize;
46053 } else if (state === 3
46054 /* Pointer */
46055 ) {
46056 table[i] = offset - compactedSize;
46057 }
46058 }
46059
46060 this.offset = this.offset - compactedSize;
46061 }
46062
46063 pushPlaceholder(valueFunc) {
46064 this.sizeCheck();
46065 var address = this.offset++;
46066 this.heap[address] = 2147483647
46067 /* MAX_SIZE */
46068 ;
46069 this.placeholders.push([address, valueFunc]);
46070 }
46071
46072 pushStdlib(operand) {
46073 this.sizeCheck();
46074 var address = this.offset++;
46075 this.heap[address] = 2147483647
46076 /* MAX_SIZE */
46077 ;
46078 this.stdlibs.push([address, operand]);
46079 }
46080
46081 patchPlaceholders() {
46082 var {
46083 placeholders
46084 } = this;
46085
46086 for (var i = 0; i < placeholders.length; i++) {
46087 var [address, getValue] = placeholders[i];
46088 this.setbyaddr(address, getValue());
46089 }
46090 }
46091
46092 patchStdlibs(stdlib) {
46093 var {
46094 stdlibs
46095 } = this;
46096
46097 for (var i = 0; i < stdlibs.length; i++) {
46098 var [address, {
46099 value
46100 }] = stdlibs[i];
46101 this.setbyaddr(address, stdlib[value]);
46102 }
46103
46104 this.stdlibs = [];
46105 }
46106
46107 capture(stdlib, offset = this.offset) {
46108 this.patchPlaceholders();
46109 this.patchStdlibs(stdlib); // Only called in eager mode
46110
46111 var buffer = slice(this.heap, 0, offset).buffer;
46112 return {
46113 handle: this.handle,
46114 table: this.table,
46115 buffer: buffer
46116 };
46117 }
46118
46119 }
46120
46121 _exports.HeapImpl = HeapImpl;
46122
46123 class RuntimeProgramImpl {
46124 constructor(constants$$1, heap) {
46125 this.constants = constants$$1;
46126 this.heap = heap;
46127 this._opcode = new RuntimeOpImpl(this.heap);
46128 }
46129
46130 static hydrate(artifacts) {
46131 var heap = new RuntimeHeapImpl(artifacts.heap);
46132 var constants$$1 = new RuntimeConstantsImpl(artifacts.constants);
46133 return new RuntimeProgramImpl(constants$$1, heap);
46134 }
46135
46136 opcode(offset) {
46137 this._opcode.offset = offset;
46138 return this._opcode;
46139 }
46140
46141 }
46142
46143 _exports.RuntimeProgramImpl = RuntimeProgramImpl;
46144
46145 function hydrateProgram(artifacts) {
46146 var heap = new RuntimeHeapImpl(artifacts.heap);
46147 var constants$$1 = new RuntimeConstantsImpl(artifacts.constants);
46148 return new RuntimeProgramImpl(constants$$1, heap);
46149 }
46150
46151 function slice(arr, start, end) {
46152 if (arr.slice !== undefined) {
46153 return arr.slice(start, end);
46154 }
46155
46156 var ret = new Int32Array(end);
46157
46158 for (; start < end; start++) {
46159 ret[start] = arr[start];
46160 }
46161
46162 return ret;
46163 }
46164
46165 function sizeof(table, handle) {
46166 {
46167 return -1;
46168 }
46169 }
46170
46171 function scopesizeof(table, handle) {
46172 var info = table[handle + 1
46173 /* INFO_OFFSET */
46174 ];
46175 return info >> 2;
46176 }
46177
46178 function patchStdlibs(program) {
46179 program.heap.patchStdlibs(program.stdlib);
46180 }
46181
46182 function programArtifacts(program) {
46183 var heap = program.heap.capture(program.stdlib);
46184 var constants$$1 = program.constants.toPool();
46185 return {
46186 heap,
46187 constants: constants$$1
46188 };
46189 }
46190
46191 function artifacts(syntax) {
46192 return programArtifacts(syntax.program);
46193 }
46194});
46195define("@glimmer/reference", ["exports", "@glimmer/util", "@glimmer/validator"], function (_exports, _util, _validator) {
46196 "use strict";
46197
46198 Object.defineProperty(_exports, "__esModule", {
46199 value: true
46200 });
46201 _exports.isModified = isModified;
46202 _exports.IterationItemReference = _exports.PropertyReference = _exports.HelperRootReference = _exports.ComponentRootReference = _exports.RootReference = _exports.UPDATE_REFERENCED_VALUE = _exports.IterableReference = _exports.ConstReference = _exports.ReferenceCache = _exports.CachedReference = void 0;
46203
46204 class CachedReference {
46205 constructor() {
46206 this.lastRevision = null;
46207 this.lastValue = null;
46208 }
46209
46210 value() {
46211 var {
46212 tag,
46213 lastRevision,
46214 lastValue
46215 } = this;
46216
46217 if (lastRevision === null || !(0, _validator.validateTag)(tag, lastRevision)) {
46218 lastValue = this.lastValue = this.compute();
46219 this.lastRevision = (0, _validator.valueForTag)(tag);
46220 }
46221
46222 return lastValue;
46223 }
46224
46225 invalidate() {
46226 this.lastRevision = null;
46227 }
46228
46229 } //////////
46230
46231
46232 _exports.CachedReference = CachedReference;
46233
46234 class ReferenceCache {
46235 constructor(reference) {
46236 this.lastValue = null;
46237 this.lastRevision = null;
46238 this.initialized = false;
46239 this.tag = reference.tag;
46240 this.reference = reference;
46241 }
46242
46243 peek() {
46244 if (!this.initialized) {
46245 return this.initialize();
46246 }
46247
46248 return this.lastValue;
46249 }
46250
46251 revalidate() {
46252 if (!this.initialized) {
46253 return this.initialize();
46254 }
46255
46256 var {
46257 reference,
46258 lastRevision
46259 } = this;
46260 var tag = reference.tag;
46261 if ((0, _validator.validateTag)(tag, lastRevision)) return NOT_MODIFIED;
46262 var {
46263 lastValue
46264 } = this;
46265 var currentValue = reference.value();
46266 this.lastRevision = (0, _validator.valueForTag)(tag);
46267 if (currentValue === lastValue) return NOT_MODIFIED;
46268 this.lastValue = currentValue;
46269 return currentValue;
46270 }
46271
46272 initialize() {
46273 var {
46274 reference
46275 } = this;
46276 var currentValue = this.lastValue = reference.value();
46277 this.lastRevision = (0, _validator.valueForTag)(reference.tag);
46278 this.initialized = true;
46279 return currentValue;
46280 }
46281
46282 }
46283
46284 _exports.ReferenceCache = ReferenceCache;
46285 var NOT_MODIFIED = (0, _util.symbol)('NOT_MODIFIED');
46286
46287 function isModified(value) {
46288 return value !== NOT_MODIFIED;
46289 }
46290
46291 class PrimitiveReference {
46292 constructor(inner) {
46293 this.inner = inner;
46294 this.tag = _validator.CONSTANT_TAG;
46295 }
46296
46297 value() {
46298 return this.inner;
46299 }
46300
46301 get(_key) {
46302 return UNDEFINED_REFERENCE;
46303 }
46304
46305 }
46306
46307 var UNDEFINED_REFERENCE = new PrimitiveReference(undefined);
46308
46309 class ConstReference {
46310 constructor(inner) {
46311 this.inner = inner;
46312 this.tag = _validator.CONSTANT_TAG;
46313 }
46314
46315 value() {
46316 return this.inner;
46317 }
46318
46319 get(_key) {
46320 return UNDEFINED_REFERENCE;
46321 }
46322
46323 }
46324
46325 _exports.ConstReference = ConstReference;
46326 var UPDATE_REFERENCED_VALUE = (0, _util.symbol)('UPDATE_REFERENCED_VALUE');
46327 /**
46328 * RootReferences refer to a constant root value within a template. For
46329 * instance, the `this` in `{{this.some.prop}}`. This is typically a:
46330 *
46331 * - Component
46332 * - Controller
46333 * - Helper
46334 *
46335 * Or another "top level" template construct, if you will. PropertyReferences
46336 * chain off a root reference in the template, and can then be passed around and
46337 * used at will.
46338 */
46339
46340 _exports.UPDATE_REFERENCED_VALUE = UPDATE_REFERENCED_VALUE;
46341
46342 class RootReference {
46343 constructor(env) {
46344 this.env = env;
46345 this.children = (0, _util.dict)();
46346 this.tag = _validator.CONSTANT_TAG;
46347 }
46348
46349 get(key) {
46350 // References should in general be identical to one another, so we can usually
46351 // deduplicate them in production. However, in DEBUG we need unique references
46352 // so we can properly key off them for the logging context.
46353 if (true
46354 /* DEBUG */
46355 ) {
46356 // We register the template debug context now since the reference is
46357 // created before the component itself. It shouldn't be possible to cause
46358 // errors when accessing the root, only subproperties of the root, so this
46359 // should be fine for the time being. The exception is helpers, but they
46360 // set their context earlier.
46361 //
46362 // TODO: This points to a need for more first class support for arguments in
46363 // the debugRenderTree. The fact that we can't accurately relate an argument
46364 // reference to its component is problematic for debug tooling.
46365 if (!this.didSetupDebugContext) {
46366 this.didSetupDebugContext = true;
46367 this.env.setTemplatePathDebugContext(this, this.debugLogName || 'this', null);
46368 }
46369
46370 return new PropertyReference(this, key, this.env);
46371 } else {
46372 var ref = this.children[key];
46373
46374 if (ref === undefined) {
46375 ref = this.children[key] = new PropertyReference(this, key, this.env);
46376 }
46377
46378 return ref;
46379 }
46380 }
46381
46382 }
46383
46384 _exports.RootReference = RootReference;
46385
46386 class ComponentRootReference extends RootReference {
46387 constructor(inner, env) {
46388 super(env);
46389 this.inner = inner;
46390 }
46391
46392 value() {
46393 return this.inner;
46394 }
46395
46396 }
46397
46398 _exports.ComponentRootReference = ComponentRootReference;
46399
46400 class HelperRootReference extends RootReference {
46401 constructor(fn, args, env, debugName) {
46402 super(env);
46403 this.fn = fn;
46404 this.args = args;
46405 this.computeRevision = null;
46406 this.computeTag = null;
46407
46408 if (true
46409 /* DEBUG */
46410 ) {
46411 var name = debugName || fn.name;
46412 env.setTemplatePathDebugContext(this, `(result of a \`${name}\` helper)`, null);
46413 this.didSetupDebugContext = true;
46414 }
46415
46416 if ((0, _validator.isConstTagged)(args)) {
46417 this.compute();
46418 }
46419
46420 var {
46421 tag,
46422 computeTag
46423 } = this;
46424
46425 if (computeTag !== null && (0, _validator.isConstTag)(computeTag)) {
46426 // If the args are constant, and the first computation is constant, then
46427 // the helper itself is constant and will never update.
46428 tag = this.tag = _validator.CONSTANT_TAG;
46429 this.computeRevision = (0, _validator.valueForTag)(tag);
46430 } else {
46431 var valueTag = this.valueTag = (0, _validator.createUpdatableTag)();
46432 tag = this.tag = (0, _validator.combine)([args.tag, valueTag]);
46433
46434 if (computeTag !== null) {
46435 // We computed once, so setup the cache state correctly
46436 (0, _validator.updateTag)(valueTag, computeTag);
46437 this.computeRevision = (0, _validator.valueForTag)(tag);
46438 }
46439 }
46440 }
46441
46442 compute() {
46443 this.computeTag = (0, _validator.track)(() => {
46444 this.computeValue = this.fn(this.args);
46445 }, true
46446 /* DEBUG */
46447 && this.env.getTemplatePathDebugContext(this));
46448 }
46449
46450 value() {
46451 var {
46452 tag,
46453 computeRevision
46454 } = this;
46455
46456 if (computeRevision === null || !(0, _validator.validateTag)(tag, computeRevision)) {
46457 this.compute();
46458 (0, _validator.updateTag)(this.valueTag, this.computeTag);
46459 this.computeRevision = (0, _validator.valueForTag)(tag);
46460 }
46461
46462 return this.computeValue;
46463 }
46464
46465 }
46466 /**
46467 * PropertyReferences represent a property that has been accessed on a root, or
46468 * another property (or iterable, see below). `some` and `prop` in
46469 * `{{this.some.prop}}` are each property references, `some` being a property of
46470 * `this`, and `prop` being a property of `some`. They are constructed by
46471 * recursively calling `get` on the previous reference as a template chain is
46472 * followed.
46473 */
46474
46475
46476 _exports.HelperRootReference = HelperRootReference;
46477
46478 class PropertyReference {
46479 constructor(parentReference, propertyKey, env) {
46480 this.parentReference = parentReference;
46481 this.propertyKey = propertyKey;
46482 this.env = env;
46483 this.children = (0, _util.dict)();
46484 this.lastRevision = null;
46485
46486 if (true
46487 /* DEBUG */
46488 ) {
46489 env.setTemplatePathDebugContext(this, propertyKey, parentReference);
46490 }
46491
46492 var valueTag = this.valueTag = (0, _validator.createUpdatableTag)();
46493 var parentReferenceTag = parentReference.tag;
46494 this.tag = (0, _validator.combine)([parentReferenceTag, valueTag]);
46495 }
46496
46497 value() {
46498 var {
46499 tag,
46500 lastRevision,
46501 lastValue,
46502 parentReference,
46503 valueTag,
46504 propertyKey
46505 } = this;
46506
46507 if (lastRevision === null || !(0, _validator.validateTag)(tag, lastRevision)) {
46508 var parentValue = parentReference.value();
46509
46510 if ((0, _util.isDict)(parentValue)) {
46511 var combined = (0, _validator.track)(() => {
46512 lastValue = this.env.getPath(parentValue, propertyKey);
46513 }, true
46514 /* DEBUG */
46515 && this.env.getTemplatePathDebugContext(this));
46516 (0, _validator.updateTag)(valueTag, combined);
46517 } else {
46518 lastValue = undefined;
46519 }
46520
46521 this.lastValue = lastValue;
46522 this.lastRevision = (0, _validator.valueForTag)(tag);
46523 }
46524
46525 return lastValue;
46526 }
46527
46528 get(key) {
46529 // References should in general be identical to one another, so we can usually
46530 // deduplicate them in production. However, in DEBUG we need unique references
46531 // so we can properly key off them for the logging context.
46532 if (true
46533 /* DEBUG */
46534 ) {
46535 return new PropertyReference(this, key, this.env);
46536 } else {
46537 var ref = this.children[key];
46538
46539 if (ref === undefined) {
46540 ref = this.children[key] = new PropertyReference(this, key, this.env);
46541 }
46542
46543 return ref;
46544 }
46545 }
46546
46547 [UPDATE_REFERENCED_VALUE](value) {
46548 var {
46549 parentReference,
46550 propertyKey
46551 } = this;
46552 var parentValue = parentReference.value();
46553 this.env.setPath(parentValue, propertyKey, value);
46554 }
46555
46556 } //////////
46557
46558 /**
46559 * IterationItemReferences represent an individual item in an iterable `each`.
46560 * They are similar to PropertyReferences, but since iteration items need to be
46561 * updated they have slightly different behavior. Concretely, they are the
46562 * `item` in:
46563 *
46564 * ```hbs
46565 * {{#each this.items as |item|}}
46566 * {{item.foo}}
46567 * {{/each}}
46568 * ```
46569 *
46570 * Properties can chain off an iteration item, just like with the other template
46571 * reference types.
46572 */
46573
46574
46575 _exports.PropertyReference = PropertyReference;
46576
46577 class IterationItemReference {
46578 constructor(parentReference, itemValue, itemKey, env) {
46579 this.parentReference = parentReference;
46580 this.itemValue = itemValue;
46581 this.env = env;
46582 this.tag = (0, _validator.createUpdatableTag)();
46583 this.children = (0, _util.dict)();
46584
46585 if (true
46586 /* DEBUG */
46587 ) {
46588 env.setTemplatePathDebugContext(this, (0, _util.debugToString)(itemKey), parentReference);
46589 }
46590 }
46591
46592 value() {
46593 return this.itemValue;
46594 }
46595
46596 update(value) {
46597 var {
46598 itemValue
46599 } = this; // TODO: refactor this https://github.com/glimmerjs/glimmer-vm/issues/1101
46600
46601 if (value !== itemValue) {
46602 (0, _validator.dirtyTag)(this.tag);
46603 this.itemValue = value;
46604 }
46605 }
46606
46607 get(key) {
46608 // References should in general be identical to one another, so we can usually
46609 // deduplicate them in production. However, in DEBUG we need unique references
46610 // so we can properly key off them for the logging context.
46611 if (true
46612 /* DEBUG */
46613 ) {
46614 return new PropertyReference(this, key, this.env);
46615 } else {
46616 var ref = this.children[key];
46617
46618 if (ref === undefined) {
46619 ref = this.children[key] = new PropertyReference(this, key, this.env);
46620 }
46621
46622 return ref;
46623 }
46624 }
46625
46626 }
46627
46628 _exports.IterationItemReference = IterationItemReference;
46629 var NULL_IDENTITY = {};
46630
46631 var KEY = (_, index) => index;
46632
46633 var INDEX = (_, index) => String(index);
46634
46635 var IDENTITY = item => {
46636 if (item === null) {
46637 // Returning null as an identity will cause failures since the iterator
46638 // can't tell that it's actually supposed to be null
46639 return NULL_IDENTITY;
46640 }
46641
46642 return item;
46643 };
46644
46645 function keyForPath(path, getPath) {
46646 if (true
46647 /* DEBUG */
46648 && path[0] === '@') {
46649 throw new Error(`invalid keypath: '${path}', valid keys: @index, @identity, or a path`);
46650 }
46651
46652 return uniqueKeyFor(item => getPath(item, path));
46653 }
46654
46655 function makeKeyFor(key, getPath) {
46656 switch (key) {
46657 case '@key':
46658 return uniqueKeyFor(KEY);
46659
46660 case '@index':
46661 return uniqueKeyFor(INDEX);
46662
46663 case '@identity':
46664 return uniqueKeyFor(IDENTITY);
46665
46666 default:
46667 return keyForPath(key, getPath);
46668 }
46669 }
46670
46671 class WeakMapWithPrimitives {
46672 get weakMap() {
46673 if (this._weakMap === undefined) {
46674 this._weakMap = new WeakMap();
46675 }
46676
46677 return this._weakMap;
46678 }
46679
46680 get primitiveMap() {
46681 if (this._primitiveMap === undefined) {
46682 this._primitiveMap = new Map();
46683 }
46684
46685 return this._primitiveMap;
46686 }
46687
46688 set(key, value) {
46689 if ((0, _util.isObject)(key) || typeof key === 'function') {
46690 this.weakMap.set(key, value);
46691 } else {
46692 this.primitiveMap.set(key, value);
46693 }
46694 }
46695
46696 get(key) {
46697 if ((0, _util.isObject)(key) || typeof key === 'function') {
46698 return this.weakMap.get(key);
46699 } else {
46700 return this.primitiveMap.get(key);
46701 }
46702 }
46703
46704 }
46705
46706 var IDENTITIES = new WeakMapWithPrimitives();
46707
46708 function identityForNthOccurence(value, count) {
46709 var identities = IDENTITIES.get(value);
46710
46711 if (identities === undefined) {
46712 identities = [];
46713 IDENTITIES.set(value, identities);
46714 }
46715
46716 var identity = identities[count];
46717
46718 if (identity === undefined) {
46719 identity = {
46720 value,
46721 count
46722 };
46723 identities[count] = identity;
46724 }
46725
46726 return identity;
46727 }
46728 /**
46729 * When iterating over a list, it's possible that an item with the same unique
46730 * key could be encountered twice:
46731 *
46732 * ```js
46733 * let arr = ['same', 'different', 'same', 'same'];
46734 * ```
46735 *
46736 * In general, we want to treat these items as _unique within the list_. To do
46737 * this, we track the occurences of every item as we iterate the list, and when
46738 * an item occurs more than once, we generate a new unique key just for that
46739 * item, and that occurence within the list. The next time we iterate the list,
46740 * and encounter an item for the nth time, we can get the _same_ key, and let
46741 * Glimmer know that it should reuse the DOM for the previous nth occurence.
46742 */
46743
46744
46745 function uniqueKeyFor(keyFor) {
46746 var seen = new WeakMapWithPrimitives();
46747 return (value, memo) => {
46748 var key = keyFor(value, memo);
46749 var count = seen.get(key) || 0;
46750 seen.set(key, count + 1);
46751
46752 if (count === 0) {
46753 return key;
46754 }
46755
46756 return identityForNthOccurence(key, count);
46757 };
46758 }
46759
46760 class IterableReference {
46761 constructor(parentRef, key, env) {
46762 this.parentRef = parentRef;
46763 this.key = key;
46764 this.env = env;
46765 this.iterator = null;
46766 this.tag = parentRef.tag;
46767 }
46768
46769 value() {
46770 return !this.isEmpty();
46771 }
46772
46773 isEmpty() {
46774 var iterator = this.iterator = this.createIterator();
46775 return iterator.isEmpty();
46776 }
46777
46778 next() {
46779 var iterator = this.iterator;
46780 var item = iterator.next();
46781
46782 if (item === null) {
46783 this.iterator = null;
46784 }
46785
46786 return item;
46787 }
46788
46789 createIterator() {
46790 var {
46791 parentRef,
46792 key,
46793 env
46794 } = this;
46795 var iterable = parentRef.value();
46796 var keyFor = makeKeyFor(key, env.getPath);
46797
46798 if (Array.isArray(iterable)) {
46799 return new ArrayIterator(iterable, keyFor);
46800 }
46801
46802 var maybeIterator = env.toIterator(iterable);
46803
46804 if (maybeIterator === null) {
46805 return new ArrayIterator(_util.EMPTY_ARRAY, () => null);
46806 }
46807
46808 return new IteratorWrapper(maybeIterator, keyFor);
46809 }
46810
46811 childRefFor(key, value) {
46812 var {
46813 parentRef,
46814 env
46815 } = this;
46816 return new IterationItemReference(parentRef, value, true
46817 /* DEBUG */
46818 ? `(key: ${(0, _util.debugToString)(key)}` : '', env);
46819 }
46820
46821 }
46822
46823 _exports.IterableReference = IterableReference;
46824
46825 class IteratorWrapper {
46826 constructor(inner, keyFor) {
46827 this.inner = inner;
46828 this.keyFor = keyFor;
46829 }
46830
46831 isEmpty() {
46832 return this.inner.isEmpty();
46833 }
46834
46835 next() {
46836 var nextValue = this.inner.next();
46837
46838 if (nextValue !== null) {
46839 nextValue.key = this.keyFor(nextValue.value, nextValue.memo);
46840 }
46841
46842 return nextValue;
46843 }
46844
46845 }
46846
46847 class ArrayIterator {
46848 constructor(iterator, keyFor) {
46849 this.iterator = iterator;
46850 this.keyFor = keyFor;
46851 this.pos = 0;
46852
46853 if (iterator.length === 0) {
46854 this.current = {
46855 kind: 'empty'
46856 };
46857 } else {
46858 this.current = {
46859 kind: 'first',
46860 value: iterator[this.pos]
46861 };
46862 }
46863 }
46864
46865 isEmpty() {
46866 return this.current.kind === 'empty';
46867 }
46868
46869 next() {
46870 var value;
46871 var current = this.current;
46872
46873 if (current.kind === 'first') {
46874 this.current = {
46875 kind: 'progress'
46876 };
46877 value = current.value;
46878 } else if (this.pos >= this.iterator.length - 1) {
46879 return null;
46880 } else {
46881 value = this.iterator[++this.pos];
46882 }
46883
46884 var {
46885 keyFor
46886 } = this;
46887 var key = keyFor(value, this.pos);
46888 var memo = this.pos;
46889 return {
46890 key,
46891 value,
46892 memo
46893 };
46894 }
46895
46896 }
46897});
46898define("@glimmer/runtime", ["exports", "@glimmer/util", "@glimmer/reference", "@glimmer/validator", "@glimmer/program", "@glimmer/vm", "@glimmer/low-level"], function (_exports, _util, _reference, _validator, _program, _vm2, _lowLevel) {
46899 "use strict";
46900
46901 Object.defineProperty(_exports, "__esModule", {
46902 value: true
46903 });
46904 _exports.clear = clear;
46905 _exports.capabilityFlagsFrom = capabilityFlagsFrom;
46906 _exports.hasCapability = hasCapability;
46907 _exports.resetDebuggerCallback = resetDebuggerCallback;
46908 _exports.setDebuggerCallback = setDebuggerCallback;
46909 _exports.curry = curry;
46910 _exports.isCurriedComponentDefinition = isCurriedComponentDefinition;
46911 _exports.isWhitespace = isWhitespace;
46912 _exports.normalizeProperty = normalizeProperty;
46913 _exports.AotRuntime = AotRuntime;
46914 _exports.JitRuntime = JitRuntime;
46915 _exports.inTransaction = inTransaction;
46916 _exports.getDynamicVar = getDynamicVar;
46917 _exports.renderAot = renderAot;
46918 _exports.renderAotComponent = renderAotComponent;
46919 _exports.renderAotMain = renderAotMain;
46920 _exports.renderJitComponent = renderJitComponent;
46921 _exports.renderJitMain = renderJitMain;
46922 _exports.renderSync = renderSync;
46923 _exports.dynamicAttribute = dynamicAttribute;
46924 _exports.clientBuilder = clientBuilder;
46925 _exports.isSerializationFirstNode = isSerializationFirstNode;
46926 _exports.rehydrationBuilder = rehydrationBuilder;
46927 _exports.destroy = destroy;
46928 _exports.registerDestructor = registerDestructor;
46929 _exports.unregisterDestructor = unregisterDestructor;
46930 _exports.associateDestroyableChild = associateDestroyableChild;
46931 _exports.isDestroying = isDestroying;
46932 _exports.isDestroyed = isDestroyed;
46933 _exports.setScheduleDestroy = setScheduleDestroy;
46934 _exports.setScheduleDestroyed = setScheduleDestroyed;
46935 _exports._destroyChildren = destroyChildren;
46936 _exports.TEMPLATE_ONLY_COMPONENT = _exports.SimpleComponentManager = _exports._scheduleDestroyed = _exports._scheduleDestroy = _exports.assertDestroyablesDestroyed = _exports.enableDestroyableTracking = _exports.SERIALIZATION_FIRST_NODE_STRING = _exports.RehydrateBuilder = _exports.RemoteLiveBlock = _exports.UpdatableBlockImpl = _exports.NewElementBuilder = _exports.SimpleDynamicAttribute = _exports.DynamicAttribute = _exports.CapturedPositionalArgumentsImpl = _exports.CapturedNamedArgumentsImpl = _exports.CapturedArgumentsImpl = _exports.EMPTY_ARGS = _exports.LowLevelVM = _exports.UpdatingVM = _exports.UNDEFINED_REFERENCE = _exports.PrimitiveReference = _exports.NULL_REFERENCE = _exports.ConditionalReference = _exports.ScopeImpl = _exports.EnvironmentImpl = _exports.DefaultDynamicScope = _exports.DOMTreeConstruction = _exports.IDOMChanges = _exports.DOMChanges = _exports.MINIMAL_CAPABILITIES = _exports.DEFAULT_CAPABILITIES = _exports.CurriedComponentDefinition = _exports.CursorImpl = _exports.ConcreteBounds = void 0;
46937 // the VM in other classes, but are not intended to be a part of
46938 // Glimmer's API.
46939 var INNER_VM = (0, _util.symbol)('INNER_VM');
46940 var DESTROYABLE_STACK = (0, _util.symbol)('DESTROYABLE_STACK');
46941 var STACKS = (0, _util.symbol)('STACKS');
46942 var REGISTERS = (0, _util.symbol)('REGISTERS');
46943 var HEAP = (0, _util.symbol)('HEAP');
46944 var CONSTANTS = (0, _util.symbol)('CONSTANTS');
46945 var ARGS = (0, _util.symbol)('ARGS');
46946 var PC = (0, _util.symbol)('PC');
46947
46948 class CursorImpl {
46949 constructor(element, nextSibling) {
46950 this.element = element;
46951 this.nextSibling = nextSibling;
46952 }
46953
46954 }
46955
46956 _exports.CursorImpl = CursorImpl;
46957
46958 class ConcreteBounds {
46959 constructor(parentNode, first, last) {
46960 this.parentNode = parentNode;
46961 this.first = first;
46962 this.last = last;
46963 }
46964
46965 parentElement() {
46966 return this.parentNode;
46967 }
46968
46969 firstNode() {
46970 return this.first;
46971 }
46972
46973 lastNode() {
46974 return this.last;
46975 }
46976
46977 }
46978
46979 _exports.ConcreteBounds = ConcreteBounds;
46980
46981 class SingleNodeBounds {
46982 constructor(parentNode, node) {
46983 this.parentNode = parentNode;
46984 this.node = node;
46985 }
46986
46987 parentElement() {
46988 return this.parentNode;
46989 }
46990
46991 firstNode() {
46992 return this.node;
46993 }
46994
46995 lastNode() {
46996 return this.node;
46997 }
46998
46999 }
47000
47001 function move(bounds, reference) {
47002 var parent = bounds.parentElement();
47003 var first = bounds.firstNode();
47004 var last = bounds.lastNode();
47005 var current = first;
47006
47007 while (true) {
47008 var next = current.nextSibling;
47009 parent.insertBefore(current, reference);
47010
47011 if (current === last) {
47012 return next;
47013 }
47014
47015 current = next;
47016 }
47017 }
47018
47019 function clear(bounds) {
47020 var parent = bounds.parentElement();
47021 var first = bounds.firstNode();
47022 var last = bounds.lastNode();
47023 var current = first;
47024
47025 while (true) {
47026 var next = current.nextSibling;
47027 parent.removeChild(current);
47028
47029 if (current === last) {
47030 return next;
47031 }
47032
47033 current = next;
47034 }
47035 }
47036
47037 var DESTROYABLE_META = new WeakMap();
47038
47039 function push(collection, newItem) {
47040 if (collection === null) {
47041 return newItem;
47042 } else if (Array.isArray(collection)) {
47043 collection.push(newItem);
47044 return collection;
47045 } else {
47046 return [collection, newItem];
47047 }
47048 }
47049
47050 function iterate(collection, fn) {
47051 if (Array.isArray(collection)) {
47052 for (var i = 0; i < collection.length; i++) {
47053 fn(collection[i]);
47054 }
47055 } else if (collection !== null) {
47056 fn(collection);
47057 }
47058 }
47059
47060 function remove(collection, item, message) {
47061 if (true
47062 /* DEBUG */
47063 ) {
47064 var collectionIsItem = collection === item;
47065 var collectionContainsItem = Array.isArray(collection) && collection.indexOf(item) !== -1;
47066
47067 if (!collectionIsItem && !collectionContainsItem) {
47068 throw new Error(String(message));
47069 }
47070 }
47071
47072 if (Array.isArray(collection) && collection.length > 1) {
47073 var index = collection.indexOf(item);
47074 collection.splice(index, 1);
47075 return collection;
47076 } else {
47077 return null;
47078 }
47079 }
47080
47081 function getDestroyableMeta(destroyable) {
47082 var meta = DESTROYABLE_META.get(destroyable);
47083
47084 if (meta === undefined) {
47085 meta = {
47086 parents: null,
47087 children: null,
47088 eagerDestructors: null,
47089 destructors: null,
47090 state: 0
47091 /* Live */
47092
47093 };
47094
47095 if (true
47096 /* DEBUG */
47097 ) {
47098 meta.source = destroyable;
47099 }
47100
47101 DESTROYABLE_META.set(destroyable, meta);
47102 }
47103
47104 return meta;
47105 }
47106
47107 function associateDestroyableChild(parent, child) {
47108 if (true
47109 /* DEBUG */
47110 && isDestroying(parent)) {
47111 throw new Error('Attempted to associate a destroyable child with an object that is already destroying or destroyed');
47112 }
47113
47114 var parentMeta = getDestroyableMeta(parent);
47115 var childMeta = getDestroyableMeta(child);
47116 parentMeta.children = push(parentMeta.children, child);
47117 childMeta.parents = push(childMeta.parents, parent);
47118 return child;
47119 }
47120
47121 function registerDestructor(destroyable, destructor, eager = false) {
47122 if (true
47123 /* DEBUG */
47124 && isDestroying(destroyable)) {
47125 throw new Error('Attempted to register a destructor with an object that is already destroying or destroyed');
47126 }
47127
47128 var meta = getDestroyableMeta(destroyable);
47129 var destructorsKey = eager === true ? 'eagerDestructors' : 'destructors';
47130 meta[destructorsKey] = push(meta[destructorsKey], destructor);
47131 return destructor;
47132 }
47133
47134 function unregisterDestructor(destroyable, destructor, eager = false) {
47135 if (true
47136 /* DEBUG */
47137 && isDestroying(destroyable)) {
47138 throw new Error('Attempted to unregister a destructor with an object that is already destroying or destroyed');
47139 }
47140
47141 var meta = getDestroyableMeta(destroyable);
47142 var destructorsKey = eager === true ? 'eagerDestructors' : 'destructors';
47143 meta[destructorsKey] = remove(meta[destructorsKey], destructor, true
47144 /* DEBUG */
47145 && 'attempted to remove a destructor that was not registered with the destroyable');
47146 } ////////////
47147
47148
47149 var scheduleDestroy = true
47150 /* DEBUG */
47151 ? () => {
47152 throw new Error('Must provide a scheduleDestroy method');
47153 } : () => {};
47154 _exports._scheduleDestroy = scheduleDestroy;
47155 var scheduleDestroyed = true
47156 /* DEBUG */
47157 ? () => {
47158 throw new Error('Must provide a scheduleDestroyed method');
47159 } : () => {};
47160 _exports._scheduleDestroyed = scheduleDestroyed;
47161
47162 function destroy(destroyable) {
47163 var meta = getDestroyableMeta(destroyable);
47164 if (meta.state >= 1
47165 /* Destroying */
47166 ) return;
47167 var {
47168 parents,
47169 children,
47170 eagerDestructors,
47171 destructors
47172 } = meta;
47173 meta.state = 1
47174 /* Destroying */
47175 ;
47176 iterate(children, destroy);
47177 iterate(eagerDestructors, destructor => destructor(destroyable));
47178 iterate(destructors, destructor => scheduleDestroy(destroyable, destructor));
47179 scheduleDestroyed(() => {
47180 iterate(parents, parent => removeChildFromParent(destroyable, parent));
47181 meta.state = 2
47182 /* Destroyed */
47183 ;
47184 });
47185 }
47186
47187 function removeChildFromParent(child, parent) {
47188 var parentMeta = getDestroyableMeta(parent);
47189
47190 if (parentMeta.state === 0
47191 /* Live */
47192 ) {
47193 parentMeta.children = remove(parentMeta.children, child, true
47194 /* DEBUG */
47195 && "attempted to remove child from parent, but the parent's children did not contain the child. This is likely a bug with destructors.");
47196 }
47197 }
47198
47199 function destroyChildren(destroyable) {
47200 var {
47201 children
47202 } = getDestroyableMeta(destroyable);
47203 iterate(children, destroy);
47204 }
47205
47206 function setScheduleDestroy(fn) {
47207 _exports._scheduleDestroy = scheduleDestroy = fn;
47208 }
47209
47210 function setScheduleDestroyed(fn) {
47211 _exports._scheduleDestroyed = scheduleDestroyed = fn;
47212 }
47213
47214 function isDestroying(destroyable) {
47215 var meta = DESTROYABLE_META.get(destroyable);
47216 return meta === undefined ? false : meta.state >= 1
47217 /* Destroying */
47218 ;
47219 }
47220
47221 function isDestroyed(destroyable) {
47222 var meta = DESTROYABLE_META.get(destroyable);
47223 return meta === undefined ? false : meta.state >= 2
47224 /* Destroyed */
47225 ;
47226 } ////////////
47227
47228
47229 var enableDestroyableTracking;
47230 _exports.enableDestroyableTracking = enableDestroyableTracking;
47231 var assertDestroyablesDestroyed;
47232 _exports.assertDestroyablesDestroyed = assertDestroyablesDestroyed;
47233
47234 if (true
47235 /* DEBUG */
47236 ) {
47237 var isTesting = false;
47238
47239 _exports.enableDestroyableTracking = enableDestroyableTracking = () => {
47240 if (isTesting) {
47241 throw new Error('Attempted to start destroyable testing, but you did not end the previous destroyable test. Did you forget to call `assertDestroyablesDestroyed()`');
47242 }
47243
47244 isTesting = true;
47245 DESTROYABLE_META = new Map();
47246 };
47247
47248 _exports.assertDestroyablesDestroyed = assertDestroyablesDestroyed = () => {
47249 if (!isTesting) {
47250 throw new Error('Attempted to assert destroyables destroyed, but you did not start a destroyable test. Did you forget to call `enableDestroyableTracking()`');
47251 }
47252
47253 isTesting = false;
47254 var map = DESTROYABLE_META;
47255 DESTROYABLE_META = new WeakMap();
47256 var undestroyed = [];
47257 map.forEach(meta => {
47258 if (meta.state !== 2
47259 /* Destroyed */
47260 ) {
47261 undestroyed.push(meta.source);
47262 }
47263 });
47264
47265 if (undestroyed.length > 0) {
47266 var objectsToString = undestroyed.map(_util.debugToString).join('\n ');
47267 var error = new Error(`Some destroyables were not destroyed during this test:\n ${objectsToString}`);
47268 error.destroyables = undestroyed;
47269 throw error;
47270 }
47271 };
47272 }
47273
47274 var _a;
47275
47276 class First {
47277 constructor(node) {
47278 this.node = node;
47279 }
47280
47281 firstNode() {
47282 return this.node;
47283 }
47284
47285 }
47286
47287 class Last {
47288 constructor(node) {
47289 this.node = node;
47290 }
47291
47292 lastNode() {
47293 return this.node;
47294 }
47295
47296 }
47297
47298 var CURSOR_STACK = (0, _util.symbol)('CURSOR_STACK');
47299
47300 class NewElementBuilder {
47301 constructor(env, parentNode, nextSibling) {
47302 this.constructing = null;
47303 this.operations = null;
47304 this[_a] = new _util.Stack();
47305 this.modifierStack = new _util.Stack();
47306 this.blockStack = new _util.Stack();
47307 this.pushElement(parentNode, nextSibling);
47308 this.env = env;
47309 this.dom = env.getAppendOperations();
47310 this.updateOperations = env.getDOM();
47311 }
47312
47313 static forInitialRender(env, cursor) {
47314 return new this(env, cursor.element, cursor.nextSibling).initialize();
47315 }
47316
47317 static resume(env, block) {
47318 var parentNode = block.parentElement();
47319 var nextSibling = block.reset(env);
47320 var stack = new this(env, parentNode, nextSibling).initialize();
47321 stack.pushLiveBlock(block);
47322 return stack;
47323 }
47324
47325 initialize() {
47326 this.pushSimpleBlock();
47327 return this;
47328 }
47329
47330 debugBlocks() {
47331 return this.blockStack.toArray();
47332 }
47333
47334 get element() {
47335 return this[CURSOR_STACK].current.element;
47336 }
47337
47338 get nextSibling() {
47339 return this[CURSOR_STACK].current.nextSibling;
47340 }
47341
47342 get hasBlocks() {
47343 return this.blockStack.size > 0;
47344 }
47345
47346 block() {
47347 return this.blockStack.current;
47348 }
47349
47350 popElement() {
47351 this[CURSOR_STACK].pop();
47352 this[CURSOR_STACK].current;
47353 }
47354
47355 pushSimpleBlock() {
47356 return this.pushLiveBlock(new SimpleLiveBlock(this.element));
47357 }
47358
47359 pushUpdatableBlock() {
47360 return this.pushLiveBlock(new UpdatableBlockImpl(this.element));
47361 }
47362
47363 pushBlockList(list) {
47364 return this.pushLiveBlock(new LiveBlockList(this.element, list));
47365 }
47366
47367 pushLiveBlock(block, isRemote = false) {
47368 var current = this.blockStack.current;
47369
47370 if (current !== null) {
47371 if (!isRemote) {
47372 current.didAppendBounds(block);
47373 }
47374 }
47375
47376 this.__openBlock();
47377
47378 this.blockStack.push(block);
47379 return block;
47380 }
47381
47382 popBlock() {
47383 this.block().finalize(this);
47384
47385 this.__closeBlock();
47386
47387 return this.blockStack.pop();
47388 }
47389
47390 __openBlock() {}
47391
47392 __closeBlock() {} // todo return seems unused
47393
47394
47395 openElement(tag) {
47396 var element = this.__openElement(tag);
47397
47398 this.constructing = element;
47399 return element;
47400 }
47401
47402 __openElement(tag) {
47403 return this.dom.createElement(tag, this.element);
47404 }
47405
47406 flushElement(modifiers) {
47407 var parent = this.element;
47408 var element = this.constructing;
47409
47410 this.__flushElement(parent, element);
47411
47412 this.constructing = null;
47413 this.operations = null;
47414 this.pushModifiers(modifiers);
47415 this.pushElement(element, null);
47416 this.didOpenElement(element);
47417 }
47418
47419 __flushElement(parent, constructing) {
47420 this.dom.insertBefore(parent, constructing, this.nextSibling);
47421 }
47422
47423 closeElement() {
47424 this.willCloseElement();
47425 this.popElement();
47426 return this.popModifiers();
47427 }
47428
47429 pushRemoteElement(element, guid, insertBefore) {
47430 return this.__pushRemoteElement(element, guid, insertBefore);
47431 }
47432
47433 __pushRemoteElement(element, _guid, insertBefore) {
47434 this.pushElement(element, insertBefore);
47435
47436 if (insertBefore === undefined) {
47437 while (element.lastChild) {
47438 element.removeChild(element.lastChild);
47439 }
47440 }
47441
47442 var block = new RemoteLiveBlock(element);
47443 return this.pushLiveBlock(block, true);
47444 }
47445
47446 popRemoteElement() {
47447 this.popBlock();
47448 this.popElement();
47449 }
47450
47451 pushElement(element, nextSibling = null) {
47452 this[CURSOR_STACK].push(new CursorImpl(element, nextSibling));
47453 }
47454
47455 pushModifiers(modifiers) {
47456 this.modifierStack.push(modifiers);
47457 }
47458
47459 popModifiers() {
47460 return this.modifierStack.pop();
47461 }
47462
47463 didAppendBounds(bounds) {
47464 this.block().didAppendBounds(bounds);
47465 return bounds;
47466 }
47467
47468 didAppendNode(node) {
47469 this.block().didAppendNode(node);
47470 return node;
47471 }
47472
47473 didOpenElement(element) {
47474 this.block().openElement(element);
47475 return element;
47476 }
47477
47478 willCloseElement() {
47479 this.block().closeElement();
47480 }
47481
47482 appendText(string) {
47483 return this.didAppendNode(this.__appendText(string));
47484 }
47485
47486 __appendText(text) {
47487 var {
47488 dom,
47489 element,
47490 nextSibling
47491 } = this;
47492 var node = dom.createTextNode(text);
47493 dom.insertBefore(element, node, nextSibling);
47494 return node;
47495 }
47496
47497 __appendNode(node) {
47498 this.dom.insertBefore(this.element, node, this.nextSibling);
47499 return node;
47500 }
47501
47502 __appendFragment(fragment) {
47503 var first = fragment.firstChild;
47504
47505 if (first) {
47506 var ret = new ConcreteBounds(this.element, first, fragment.lastChild);
47507 this.dom.insertBefore(this.element, fragment, this.nextSibling);
47508 return ret;
47509 } else {
47510 return new SingleNodeBounds(this.element, this.__appendComment(''));
47511 }
47512 }
47513
47514 __appendHTML(html) {
47515 return this.dom.insertHTMLBefore(this.element, this.nextSibling, html);
47516 }
47517
47518 appendDynamicHTML(value) {
47519 var bounds = this.trustedContent(value);
47520 this.didAppendBounds(bounds);
47521 }
47522
47523 appendDynamicText(value) {
47524 var node = this.untrustedContent(value);
47525 this.didAppendNode(node);
47526 return node;
47527 }
47528
47529 appendDynamicFragment(value) {
47530 var bounds = this.__appendFragment(value);
47531
47532 this.didAppendBounds(bounds);
47533 }
47534
47535 appendDynamicNode(value) {
47536 var node = this.__appendNode(value);
47537
47538 var bounds = new SingleNodeBounds(this.element, node);
47539 this.didAppendBounds(bounds);
47540 }
47541
47542 trustedContent(value) {
47543 return this.__appendHTML(value);
47544 }
47545
47546 untrustedContent(value) {
47547 return this.__appendText(value);
47548 }
47549
47550 appendComment(string) {
47551 return this.didAppendNode(this.__appendComment(string));
47552 }
47553
47554 __appendComment(string) {
47555 var {
47556 dom,
47557 element,
47558 nextSibling
47559 } = this;
47560 var node = dom.createComment(string);
47561 dom.insertBefore(element, node, nextSibling);
47562 return node;
47563 }
47564
47565 __setAttribute(name, value, namespace) {
47566 this.dom.setAttribute(this.constructing, name, value, namespace);
47567 }
47568
47569 __setProperty(name, value) {
47570 this.constructing[name] = value;
47571 }
47572
47573 setStaticAttribute(name, value, namespace) {
47574 this.__setAttribute(name, value, namespace);
47575 }
47576
47577 setDynamicAttribute(name, value, trusting, namespace) {
47578 var element = this.constructing;
47579 var attribute = this.env.attributeFor(element, name, trusting, namespace);
47580 attribute.set(this, value, this.env);
47581 return attribute;
47582 }
47583
47584 }
47585
47586 _exports.NewElementBuilder = NewElementBuilder;
47587 _a = CURSOR_STACK;
47588
47589 class SimpleLiveBlock {
47590 constructor(parent) {
47591 this.parent = parent;
47592 this.first = null;
47593 this.last = null;
47594 this.nesting = 0;
47595 }
47596
47597 parentElement() {
47598 return this.parent;
47599 }
47600
47601 firstNode() {
47602 var first = this.first;
47603 return first.firstNode();
47604 }
47605
47606 lastNode() {
47607 var last = this.last;
47608 return last.lastNode();
47609 }
47610
47611 openElement(element) {
47612 this.didAppendNode(element);
47613 this.nesting++;
47614 }
47615
47616 closeElement() {
47617 this.nesting--;
47618 }
47619
47620 didAppendNode(node) {
47621 if (this.nesting !== 0) return;
47622
47623 if (!this.first) {
47624 this.first = new First(node);
47625 }
47626
47627 this.last = new Last(node);
47628 }
47629
47630 didAppendBounds(bounds) {
47631 if (this.nesting !== 0) return;
47632
47633 if (!this.first) {
47634 this.first = bounds;
47635 }
47636
47637 this.last = bounds;
47638 }
47639
47640 finalize(stack) {
47641 if (this.first === null) {
47642 stack.appendComment('');
47643 }
47644 }
47645
47646 }
47647
47648 class RemoteLiveBlock extends SimpleLiveBlock {
47649 constructor(parent) {
47650 super(parent);
47651 registerDestructor(this, () => {
47652 // In general, you only need to clear the root of a hierarchy, and should never
47653 // need to clear any child nodes. This is an important constraint that gives us
47654 // a strong guarantee that clearing a subtree is a single DOM operation.
47655 //
47656 // Because remote blocks are not normally physically nested inside of the tree
47657 // that they are logically nested inside, we manually clear remote blocks when
47658 // a logical parent is cleared.
47659 //
47660 // HOWEVER, it is currently possible for a remote block to be physically nested
47661 // inside of the block it is logically contained inside of. This happens when
47662 // the remote block is appended to the end of the application's entire element.
47663 //
47664 // The problem with that scenario is that Glimmer believes that it owns more of
47665 // the DOM than it actually does. The code is attempting to write past the end
47666 // of the Glimmer-managed root, but Glimmer isn't aware of that.
47667 //
47668 // The correct solution to that problem is for Glimmer to be aware of the end
47669 // of the bounds that it owns, and once we make that change, this check could
47670 // be removed.
47671 //
47672 // For now, a more targeted fix is to check whether the node was already removed
47673 // and avoid clearing the node if it was. In most cases this shouldn't happen,
47674 // so this might hide bugs where the code clears nested nodes unnecessarily,
47675 // so we should eventually try to do the correct fix.
47676 if (this.parentElement() === this.firstNode().parentNode) {
47677 clear(this);
47678 }
47679 });
47680 }
47681
47682 }
47683
47684 _exports.RemoteLiveBlock = RemoteLiveBlock;
47685
47686 class UpdatableBlockImpl extends SimpleLiveBlock {
47687 reset() {
47688 destroy(this);
47689 var nextSibling = clear(this);
47690 this.first = null;
47691 this.last = null;
47692 this.nesting = 0;
47693 return nextSibling;
47694 }
47695
47696 } // FIXME: All the noops in here indicate a modelling problem
47697
47698
47699 _exports.UpdatableBlockImpl = UpdatableBlockImpl;
47700
47701 class LiveBlockList {
47702 constructor(parent, boundList) {
47703 this.parent = parent;
47704 this.boundList = boundList;
47705 this.parent = parent;
47706 this.boundList = boundList;
47707 }
47708
47709 parentElement() {
47710 return this.parent;
47711 }
47712
47713 firstNode() {
47714 var head = this.boundList[0];
47715 return head.firstNode();
47716 }
47717
47718 lastNode() {
47719 var boundList = this.boundList;
47720 var tail = boundList[boundList.length - 1];
47721 return tail.lastNode();
47722 }
47723
47724 openElement(_element) {}
47725
47726 closeElement() {}
47727
47728 didAppendNode(_node) {}
47729
47730 didAppendBounds(_bounds) {}
47731
47732 finalize(_stack) {}
47733
47734 }
47735
47736 function clientBuilder(env, cursor) {
47737 return NewElementBuilder.forInitialRender(env, cursor);
47738 } // http://www.w3.org/TR/html/syntax.html#html-integration-point
47739
47740
47741 var SVG_INTEGRATION_POINTS = {
47742 foreignObject: 1,
47743 desc: 1,
47744 title: 1
47745 }; // http://www.w3.org/TR/html/syntax.html#adjust-svg-attributes
47746 // TODO: Adjust SVG attributes
47747 // http://www.w3.org/TR/html/syntax.html#parsing-main-inforeign
47748 // TODO: Adjust SVG elements
47749 // http://www.w3.org/TR/html/syntax.html#parsing-main-inforeign
47750
47751 var BLACKLIST_TABLE = Object.create(null);
47752
47753 class DOMOperations {
47754 constructor(document) {
47755 this.document = document;
47756 this.setupUselessElement();
47757 } // split into seperate method so that NodeDOMTreeConstruction
47758 // can override it.
47759
47760
47761 setupUselessElement() {
47762 this.uselessElement = this.document.createElement('div');
47763 }
47764
47765 createElement(tag, context) {
47766 var isElementInSVGNamespace, isHTMLIntegrationPoint;
47767
47768 if (context) {
47769 isElementInSVGNamespace = context.namespaceURI === "http://www.w3.org/2000/svg"
47770 /* SVG */
47771 || tag === 'svg';
47772 isHTMLIntegrationPoint = !!SVG_INTEGRATION_POINTS[context.tagName];
47773 } else {
47774 isElementInSVGNamespace = tag === 'svg';
47775 isHTMLIntegrationPoint = false;
47776 }
47777
47778 if (isElementInSVGNamespace && !isHTMLIntegrationPoint) {
47779 // FIXME: This does not properly handle <font> with color, face, or
47780 // size attributes, which is also disallowed by the spec. We should fix
47781 // this.
47782 if (BLACKLIST_TABLE[tag]) {
47783 throw new Error(`Cannot create a ${tag} inside an SVG context`);
47784 }
47785
47786 return this.document.createElementNS("http://www.w3.org/2000/svg"
47787 /* SVG */
47788 , tag);
47789 } else {
47790 return this.document.createElement(tag);
47791 }
47792 }
47793
47794 insertBefore(parent, node, reference) {
47795 parent.insertBefore(node, reference);
47796 }
47797
47798 insertHTMLBefore(parent, nextSibling, html) {
47799 if (html === '') {
47800 var comment = this.createComment('');
47801 parent.insertBefore(comment, nextSibling);
47802 return new ConcreteBounds(parent, comment, comment);
47803 }
47804
47805 var prev = nextSibling ? nextSibling.previousSibling : parent.lastChild;
47806 var last;
47807
47808 if (nextSibling === null) {
47809 parent.insertAdjacentHTML("beforeend"
47810 /* beforeend */
47811 , html);
47812 last = parent.lastChild;
47813 } else if (nextSibling instanceof HTMLElement) {
47814 nextSibling.insertAdjacentHTML('beforebegin', html);
47815 last = nextSibling.previousSibling;
47816 } else {
47817 // Non-element nodes do not support insertAdjacentHTML, so add an
47818 // element and call it on that element. Then remove the element.
47819 //
47820 // This also protects Edge, IE and Firefox w/o the inspector open
47821 // from merging adjacent text nodes. See ./compat/text-node-merging-fix.ts
47822 var {
47823 uselessElement
47824 } = this;
47825 parent.insertBefore(uselessElement, nextSibling);
47826 uselessElement.insertAdjacentHTML("beforebegin"
47827 /* beforebegin */
47828 , html);
47829 last = uselessElement.previousSibling;
47830 parent.removeChild(uselessElement);
47831 }
47832
47833 var first = prev ? prev.nextSibling : parent.firstChild;
47834 return new ConcreteBounds(parent, first, last);
47835 }
47836
47837 createTextNode(text) {
47838 return this.document.createTextNode(text);
47839 }
47840
47841 createComment(data) {
47842 return this.document.createComment(data);
47843 }
47844
47845 }
47846
47847 function moveNodesBefore(source, target, nextSibling) {
47848 var first = source.firstChild;
47849 var last = first;
47850 var current = first;
47851
47852 while (current) {
47853 var next = current.nextSibling;
47854 target.insertBefore(current, nextSibling);
47855 last = current;
47856 current = next;
47857 }
47858
47859 return new ConcreteBounds(target, first, last);
47860 }
47861
47862 var SVG_NAMESPACE = "http://www.w3.org/2000/svg"
47863 /* SVG */
47864 ; // Patch: insertAdjacentHTML on SVG Fix
47865 // Browsers: Safari, IE, Edge, Firefox ~33-34
47866 // Reason: insertAdjacentHTML does not exist on SVG elements in Safari. It is
47867 // present but throws an exception on IE and Edge. Old versions of
47868 // Firefox create nodes in the incorrect namespace.
47869 // Fix: Since IE and Edge silently fail to create SVG nodes using
47870 // innerHTML, and because Firefox may create nodes in the incorrect
47871 // namespace using innerHTML on SVG elements, an HTML-string wrapping
47872 // approach is used. A pre/post SVG tag is added to the string, then
47873 // that whole string is added to a div. The created nodes are plucked
47874 // out and applied to the target location on DOM.
47875
47876 function applySVGInnerHTMLFix(document, DOMClass, svgNamespace) {
47877 if (!document) return DOMClass;
47878
47879 if (!shouldApplyFix(document, svgNamespace)) {
47880 return DOMClass;
47881 }
47882
47883 var div = document.createElement('div');
47884 return class DOMChangesWithSVGInnerHTMLFix extends DOMClass {
47885 insertHTMLBefore(parent, nextSibling, html) {
47886 if (html === '') {
47887 return super.insertHTMLBefore(parent, nextSibling, html);
47888 }
47889
47890 if (parent.namespaceURI !== svgNamespace) {
47891 return super.insertHTMLBefore(parent, nextSibling, html);
47892 }
47893
47894 return fixSVG(parent, div, html, nextSibling);
47895 }
47896
47897 };
47898 }
47899
47900 function fixSVG(parent, div, html, reference) {
47901 var source; // This is important, because decendants of the <foreignObject> integration
47902 // point are parsed in the HTML namespace
47903
47904 if (parent.tagName.toUpperCase() === 'FOREIGNOBJECT') {
47905 // IE, Edge: also do not correctly support using `innerHTML` on SVG
47906 // namespaced elements. So here a wrapper is used.
47907 var wrappedHtml = '<svg><foreignObject>' + html + '</foreignObject></svg>';
47908 (0, _util.clearElement)(div);
47909 div.insertAdjacentHTML("afterbegin"
47910 /* afterbegin */
47911 , wrappedHtml);
47912 source = div.firstChild.firstChild;
47913 } else {
47914 // IE, Edge: also do not correctly support using `innerHTML` on SVG
47915 // namespaced elements. So here a wrapper is used.
47916 var _wrappedHtml = '<svg>' + html + '</svg>';
47917
47918 (0, _util.clearElement)(div);
47919 div.insertAdjacentHTML("afterbegin"
47920 /* afterbegin */
47921 , _wrappedHtml);
47922 source = div.firstChild;
47923 }
47924
47925 return moveNodesBefore(source, parent, reference);
47926 }
47927
47928 function shouldApplyFix(document, svgNamespace) {
47929 var svg = document.createElementNS(svgNamespace, 'svg');
47930
47931 try {
47932 svg.insertAdjacentHTML("beforeend"
47933 /* beforeend */
47934 , '<circle></circle>');
47935 } catch (e) {// IE, Edge: Will throw, insertAdjacentHTML is unsupported on SVG
47936 // Safari: Will throw, insertAdjacentHTML is not present on SVG
47937 } finally {
47938 // FF: Old versions will create a node in the wrong namespace
47939 if (svg.childNodes.length === 1 && svg.firstChild.namespaceURI === SVG_NAMESPACE) {
47940 // The test worked as expected, no fix required
47941 return false;
47942 }
47943
47944 return true;
47945 }
47946 } // Patch: Adjacent text node merging fix
47947 // Browsers: IE, Edge, Firefox w/o inspector open
47948 // Reason: These browsers will merge adjacent text nodes. For exmaple given
47949 // <div>Hello</div> with div.insertAdjacentHTML(' world') browsers
47950 // with proper behavior will populate div.childNodes with two items.
47951 // These browsers will populate it with one merged node instead.
47952 // Fix: Add these nodes to a wrapper element, then iterate the childNodes
47953 // of that wrapper and move the nodes to their target location. Note
47954 // that potential SVG bugs will have been handled before this fix.
47955 // Note that this fix must only apply to the previous text node, as
47956 // the base implementation of `insertHTMLBefore` already handles
47957 // following text nodes correctly.
47958
47959
47960 function applyTextNodeMergingFix(document, DOMClass) {
47961 if (!document) return DOMClass;
47962
47963 if (!shouldApplyFix$1(document)) {
47964 return DOMClass;
47965 }
47966
47967 return class DOMChangesWithTextNodeMergingFix extends DOMClass {
47968 constructor(document) {
47969 super(document);
47970 this.uselessComment = document.createComment('');
47971 }
47972
47973 insertHTMLBefore(parent, nextSibling, html) {
47974 if (html === '') {
47975 return super.insertHTMLBefore(parent, nextSibling, html);
47976 }
47977
47978 var didSetUselessComment = false;
47979 var nextPrevious = nextSibling ? nextSibling.previousSibling : parent.lastChild;
47980
47981 if (nextPrevious && nextPrevious instanceof Text) {
47982 didSetUselessComment = true;
47983 parent.insertBefore(this.uselessComment, nextSibling);
47984 }
47985
47986 var bounds = super.insertHTMLBefore(parent, nextSibling, html);
47987
47988 if (didSetUselessComment) {
47989 parent.removeChild(this.uselessComment);
47990 }
47991
47992 return bounds;
47993 }
47994
47995 };
47996 }
47997
47998 function shouldApplyFix$1(document) {
47999 var mergingTextDiv = document.createElement('div');
48000 mergingTextDiv.appendChild(document.createTextNode('first'));
48001 mergingTextDiv.insertAdjacentHTML("beforeend"
48002 /* beforeend */
48003 , 'second');
48004
48005 if (mergingTextDiv.childNodes.length === 2) {
48006 // It worked as expected, no fix required
48007 return false;
48008 }
48009
48010 return true;
48011 }
48012
48013 ['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);
48014 var WHITESPACE = /[\t-\r \xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]/;
48015 var doc = typeof document === 'undefined' ? null : document;
48016
48017 function isWhitespace(string) {
48018 return WHITESPACE.test(string);
48019 }
48020
48021 var DOM;
48022
48023 (function (DOM) {
48024 class TreeConstruction extends DOMOperations {
48025 createElementNS(namespace, tag) {
48026 return this.document.createElementNS(namespace, tag);
48027 }
48028
48029 setAttribute(element, name, value, namespace = null) {
48030 if (namespace) {
48031 element.setAttributeNS(namespace, name, value);
48032 } else {
48033 element.setAttribute(name, value);
48034 }
48035 }
48036
48037 }
48038
48039 DOM.TreeConstruction = TreeConstruction;
48040 var appliedTreeContruction = TreeConstruction;
48041 appliedTreeContruction = applyTextNodeMergingFix(doc, appliedTreeContruction);
48042 appliedTreeContruction = applySVGInnerHTMLFix(doc, appliedTreeContruction, "http://www.w3.org/2000/svg"
48043 /* SVG */
48044 );
48045 DOM.DOMTreeConstruction = appliedTreeContruction;
48046 })(DOM || (DOM = {}));
48047
48048 class DOMChangesImpl extends DOMOperations {
48049 constructor(document) {
48050 super(document);
48051 this.document = document;
48052 this.namespace = null;
48053 }
48054
48055 setAttribute(element, name, value) {
48056 element.setAttribute(name, value);
48057 }
48058
48059 removeAttribute(element, name) {
48060 element.removeAttribute(name);
48061 }
48062
48063 insertAfter(element, node, reference) {
48064 this.insertBefore(element, node, reference.nextSibling);
48065 }
48066
48067 }
48068
48069 _exports.IDOMChanges = DOMChangesImpl;
48070 var helper = DOMChangesImpl;
48071 helper = applyTextNodeMergingFix(doc, helper);
48072 helper = applySVGInnerHTMLFix(doc, helper, "http://www.w3.org/2000/svg"
48073 /* SVG */
48074 );
48075 var helper$1 = helper;
48076 _exports.DOMChanges = helper$1;
48077 var DOMTreeConstruction = DOM.DOMTreeConstruction;
48078 _exports.DOMTreeConstruction = DOMTreeConstruction;
48079
48080 class PrimitiveReference extends _reference.ConstReference {
48081 static create(value) {
48082 if (value === undefined) {
48083 return UNDEFINED_REFERENCE;
48084 } else if (value === null) {
48085 return NULL_REFERENCE;
48086 } else if (value === true) {
48087 return TRUE_REFERENCE;
48088 } else if (value === false) {
48089 return FALSE_REFERENCE;
48090 } else if (typeof value === 'number') {
48091 return new ValueReference(value);
48092 } else {
48093 return new StringReference(value);
48094 }
48095 }
48096
48097 constructor(value) {
48098 super(value);
48099 }
48100
48101 get(_key) {
48102 return UNDEFINED_REFERENCE;
48103 }
48104
48105 }
48106
48107 _exports.PrimitiveReference = PrimitiveReference;
48108
48109 class StringReference extends PrimitiveReference {
48110 constructor() {
48111 super(...arguments);
48112 this.lengthReference = null;
48113 }
48114
48115 get(key) {
48116 if (key === 'length') {
48117 var {
48118 lengthReference
48119 } = this;
48120
48121 if (lengthReference === null) {
48122 lengthReference = this.lengthReference = new ValueReference(this.inner.length);
48123 }
48124
48125 return lengthReference;
48126 } else {
48127 return super.get(key);
48128 }
48129 }
48130
48131 }
48132
48133 class ValueReference extends PrimitiveReference {
48134 constructor(value) {
48135 super(value);
48136 }
48137
48138 }
48139
48140 var UNDEFINED_REFERENCE = new ValueReference(undefined);
48141 _exports.UNDEFINED_REFERENCE = UNDEFINED_REFERENCE;
48142 var NULL_REFERENCE = new ValueReference(null);
48143 _exports.NULL_REFERENCE = NULL_REFERENCE;
48144 var TRUE_REFERENCE = new ValueReference(true);
48145 var FALSE_REFERENCE = new ValueReference(false);
48146
48147 class ConditionalReference {
48148 constructor(inner, toBool = defaultToBool) {
48149 this.inner = inner;
48150 this.toBool = toBool;
48151 this._tag = (0, _validator.createUpdatableTag)();
48152 this.tag = (0, _validator.combine)([inner.tag, this._tag]);
48153 }
48154
48155 value() {
48156 var ret;
48157 var {
48158 toBool,
48159 inner
48160 } = this;
48161 var tag = (0, _validator.track)(() => ret = toBool(inner.value()));
48162 (0, _validator.updateTag)(this._tag, tag);
48163 return ret;
48164 }
48165
48166 }
48167
48168 _exports.ConditionalReference = ConditionalReference;
48169
48170 function defaultToBool(value) {
48171 return !!value;
48172 }
48173
48174 function normalizeStringValue(value) {
48175 if (isEmpty(value)) {
48176 return '';
48177 }
48178
48179 return String(value);
48180 }
48181
48182 function shouldCoerce(value) {
48183 return isString(value) || isEmpty(value) || typeof value === 'boolean' || typeof value === 'number';
48184 }
48185
48186 function isEmpty(value) {
48187 return value === null || value === undefined || typeof value.toString !== 'function';
48188 }
48189
48190 function isSafeString(value) {
48191 return typeof value === 'object' && value !== null && typeof value.toHTML === 'function';
48192 }
48193
48194 function isNode(value) {
48195 return typeof value === 'object' && value !== null && typeof value.nodeType === 'number';
48196 }
48197
48198 function isFragment(value) {
48199 return isNode(value) && value.nodeType === 11;
48200 }
48201
48202 function isString(value) {
48203 return typeof value === 'string';
48204 }
48205 /*
48206 * @method normalizeProperty
48207 * @param element {HTMLElement}
48208 * @param slotName {String}
48209 * @returns {Object} { name, type }
48210 */
48211
48212
48213 function normalizeProperty(element, slotName) {
48214 var type, normalized;
48215
48216 if (slotName in element) {
48217 normalized = slotName;
48218 type = 'prop';
48219 } else {
48220 var lower = slotName.toLowerCase();
48221
48222 if (lower in element) {
48223 type = 'prop';
48224 normalized = lower;
48225 } else {
48226 type = 'attr';
48227 normalized = slotName;
48228 }
48229 }
48230
48231 if (type === 'prop' && (normalized.toLowerCase() === 'style' || preferAttr(element.tagName, normalized))) {
48232 type = 'attr';
48233 }
48234
48235 return {
48236 normalized,
48237 type
48238 };
48239 } // * browser bug
48240 // * strange spec outlier
48241
48242
48243 var ATTR_OVERRIDES = {
48244 INPUT: {
48245 form: true,
48246 // Chrome 46.0.2464.0: 'autocorrect' in document.createElement('input') === false
48247 // Safari 8.0.7: 'autocorrect' in document.createElement('input') === false
48248 // Mobile Safari (iOS 8.4 simulator): 'autocorrect' in document.createElement('input') === true
48249 autocorrect: true,
48250 // Chrome 54.0.2840.98: 'list' in document.createElement('input') === true
48251 // Safari 9.1.3: 'list' in document.createElement('input') === false
48252 list: true
48253 },
48254 // element.form is actually a legitimate readOnly property, that is to be
48255 // mutated, but must be mutated by setAttribute...
48256 SELECT: {
48257 form: true
48258 },
48259 OPTION: {
48260 form: true
48261 },
48262 TEXTAREA: {
48263 form: true
48264 },
48265 LABEL: {
48266 form: true
48267 },
48268 FIELDSET: {
48269 form: true
48270 },
48271 LEGEND: {
48272 form: true
48273 },
48274 OBJECT: {
48275 form: true
48276 },
48277 BUTTON: {
48278 form: true
48279 }
48280 };
48281
48282 function preferAttr(tagName, propName) {
48283 var tag = ATTR_OVERRIDES[tagName.toUpperCase()];
48284 return tag && tag[propName.toLowerCase()] || false;
48285 }
48286
48287 var badProtocols = ['javascript:', 'vbscript:'];
48288 var badTags = ['A', 'BODY', 'LINK', 'IMG', 'IFRAME', 'BASE', 'FORM'];
48289 var badTagsForDataURI = ['EMBED'];
48290 var badAttributes = ['href', 'src', 'background', 'action'];
48291 var badAttributesForDataURI = ['src'];
48292
48293 function has(array, item) {
48294 return array.indexOf(item) !== -1;
48295 }
48296
48297 function checkURI(tagName, attribute) {
48298 return (tagName === null || has(badTags, tagName)) && has(badAttributes, attribute);
48299 }
48300
48301 function checkDataURI(tagName, attribute) {
48302 if (tagName === null) return false;
48303 return has(badTagsForDataURI, tagName) && has(badAttributesForDataURI, attribute);
48304 }
48305
48306 function requiresSanitization(tagName, attribute) {
48307 return checkURI(tagName, attribute) || checkDataURI(tagName, attribute);
48308 }
48309
48310 function sanitizeAttributeValue(env, element, attribute, value) {
48311 var tagName = null;
48312
48313 if (value === null || value === undefined) {
48314 return value;
48315 }
48316
48317 if (isSafeString(value)) {
48318 return value.toHTML();
48319 }
48320
48321 if (!element) {
48322 tagName = null;
48323 } else {
48324 tagName = element.tagName.toUpperCase();
48325 }
48326
48327 var str = normalizeStringValue(value);
48328
48329 if (checkURI(tagName, attribute)) {
48330 var protocol = env.protocolForURL(str);
48331
48332 if (has(badProtocols, protocol)) {
48333 return `unsafe:${str}`;
48334 }
48335 }
48336
48337 if (checkDataURI(tagName, attribute)) {
48338 return `unsafe:${str}`;
48339 }
48340
48341 return str;
48342 }
48343
48344 function dynamicAttribute(element, attr, namespace) {
48345 var {
48346 tagName,
48347 namespaceURI
48348 } = element;
48349 var attribute = {
48350 element,
48351 name: attr,
48352 namespace
48353 };
48354
48355 if (namespaceURI === "http://www.w3.org/2000/svg"
48356 /* SVG */
48357 ) {
48358 return buildDynamicAttribute(tagName, attr, attribute);
48359 }
48360
48361 var {
48362 type,
48363 normalized
48364 } = normalizeProperty(element, attr);
48365
48366 if (type === 'attr') {
48367 return buildDynamicAttribute(tagName, normalized, attribute);
48368 } else {
48369 return buildDynamicProperty(tagName, normalized, attribute);
48370 }
48371 }
48372
48373 function buildDynamicAttribute(tagName, name, attribute) {
48374 if (requiresSanitization(tagName, name)) {
48375 return new SafeDynamicAttribute(attribute);
48376 } else {
48377 return new SimpleDynamicAttribute(attribute);
48378 }
48379 }
48380
48381 function buildDynamicProperty(tagName, name, attribute) {
48382 if (requiresSanitization(tagName, name)) {
48383 return new SafeDynamicProperty(name, attribute);
48384 }
48385
48386 if (isUserInputValue(tagName, name)) {
48387 return new InputValueDynamicAttribute(name, attribute);
48388 }
48389
48390 if (isOptionSelected(tagName, name)) {
48391 return new OptionSelectedDynamicAttribute(name, attribute);
48392 }
48393
48394 return new DefaultDynamicProperty(name, attribute);
48395 }
48396
48397 class DynamicAttribute {
48398 constructor(attribute) {
48399 this.attribute = attribute;
48400 }
48401
48402 }
48403
48404 _exports.DynamicAttribute = DynamicAttribute;
48405
48406 class SimpleDynamicAttribute extends DynamicAttribute {
48407 set(dom, value, _env) {
48408 var normalizedValue = normalizeValue(value);
48409
48410 if (normalizedValue !== null) {
48411 var {
48412 name: _name2,
48413 namespace
48414 } = this.attribute;
48415
48416 dom.__setAttribute(_name2, normalizedValue, namespace);
48417 }
48418 }
48419
48420 update(value, _env) {
48421 var normalizedValue = normalizeValue(value);
48422 var {
48423 element,
48424 name
48425 } = this.attribute;
48426
48427 if (normalizedValue === null) {
48428 element.removeAttribute(name);
48429 } else {
48430 element.setAttribute(name, normalizedValue);
48431 }
48432 }
48433
48434 }
48435
48436 _exports.SimpleDynamicAttribute = SimpleDynamicAttribute;
48437
48438 class DefaultDynamicProperty extends DynamicAttribute {
48439 constructor(normalizedName, attribute) {
48440 super(attribute);
48441 this.normalizedName = normalizedName;
48442 }
48443
48444 set(dom, value, _env) {
48445 if (value !== null && value !== undefined) {
48446 this.value = value;
48447
48448 dom.__setProperty(this.normalizedName, value);
48449 }
48450 }
48451
48452 update(value, _env) {
48453 var {
48454 element
48455 } = this.attribute;
48456
48457 if (this.value !== value) {
48458 element[this.normalizedName] = this.value = value;
48459
48460 if (value === null || value === undefined) {
48461 this.removeAttribute();
48462 }
48463 }
48464 }
48465
48466 removeAttribute() {
48467 // TODO this sucks but to preserve properties first and to meet current
48468 // semantics we must do this.
48469 var {
48470 element,
48471 namespace
48472 } = this.attribute;
48473
48474 if (namespace) {
48475 element.removeAttributeNS(namespace, this.normalizedName);
48476 } else {
48477 element.removeAttribute(this.normalizedName);
48478 }
48479 }
48480
48481 }
48482
48483 class SafeDynamicProperty extends DefaultDynamicProperty {
48484 set(dom, value, env) {
48485 var {
48486 element,
48487 name
48488 } = this.attribute;
48489 var sanitized = sanitizeAttributeValue(env, element, name, value);
48490 super.set(dom, sanitized, env);
48491 }
48492
48493 update(value, env) {
48494 var {
48495 element,
48496 name
48497 } = this.attribute;
48498 var sanitized = sanitizeAttributeValue(env, element, name, value);
48499 super.update(sanitized, env);
48500 }
48501
48502 }
48503
48504 class SafeDynamicAttribute extends SimpleDynamicAttribute {
48505 set(dom, value, env) {
48506 var {
48507 element,
48508 name
48509 } = this.attribute;
48510 var sanitized = sanitizeAttributeValue(env, element, name, value);
48511 super.set(dom, sanitized, env);
48512 }
48513
48514 update(value, env) {
48515 var {
48516 element,
48517 name
48518 } = this.attribute;
48519 var sanitized = sanitizeAttributeValue(env, element, name, value);
48520 super.update(sanitized, env);
48521 }
48522
48523 }
48524
48525 class InputValueDynamicAttribute extends DefaultDynamicProperty {
48526 set(dom, value) {
48527 dom.__setProperty('value', normalizeStringValue(value));
48528 }
48529
48530 update(value) {
48531 var input = this.attribute.element;
48532 var currentValue = input.value;
48533 var normalizedValue = normalizeStringValue(value);
48534
48535 if (currentValue !== normalizedValue) {
48536 input.value = normalizedValue;
48537 }
48538 }
48539
48540 }
48541
48542 class OptionSelectedDynamicAttribute extends DefaultDynamicProperty {
48543 set(dom, value) {
48544 if (value !== null && value !== undefined && value !== false) {
48545 dom.__setProperty('selected', true);
48546 }
48547 }
48548
48549 update(value) {
48550 var option = this.attribute.element;
48551
48552 if (value) {
48553 option.selected = true;
48554 } else {
48555 option.selected = false;
48556 }
48557 }
48558
48559 }
48560
48561 function isOptionSelected(tagName, attribute) {
48562 return tagName === 'OPTION' && attribute === 'selected';
48563 }
48564
48565 function isUserInputValue(tagName, attribute) {
48566 return (tagName === 'INPUT' || tagName === 'TEXTAREA') && attribute === 'value';
48567 }
48568
48569 function normalizeValue(value) {
48570 if (value === false || value === undefined || value === null || typeof value.toString === 'undefined') {
48571 return null;
48572 }
48573
48574 if (value === true) {
48575 return '';
48576 } // onclick function etc in SSR
48577
48578
48579 if (typeof value === 'function') {
48580 return null;
48581 }
48582
48583 return String(value);
48584 }
48585
48586 var _a$1;
48587
48588 class ScopeImpl {
48589 constructor( // the 0th slot is `self`
48590 slots, callerScope, // named arguments and blocks passed to a layout that uses eval
48591 evalScope, // locals in scope when the partial was invoked
48592 partialMap) {
48593 this.slots = slots;
48594 this.callerScope = callerScope;
48595 this.evalScope = evalScope;
48596 this.partialMap = partialMap;
48597 }
48598
48599 static root(self, size = 0) {
48600 var refs = new Array(size + 1);
48601
48602 for (var i = 0; i <= size; i++) {
48603 refs[i] = UNDEFINED_REFERENCE;
48604 }
48605
48606 return new ScopeImpl(refs, null, null, null).init({
48607 self
48608 });
48609 }
48610
48611 static sized(size = 0) {
48612 var refs = new Array(size + 1);
48613
48614 for (var i = 0; i <= size; i++) {
48615 refs[i] = UNDEFINED_REFERENCE;
48616 }
48617
48618 return new ScopeImpl(refs, null, null, null);
48619 }
48620
48621 init({
48622 self
48623 }) {
48624 this.slots[0] = self;
48625 return this;
48626 }
48627
48628 getSelf() {
48629 return this.get(0);
48630 }
48631
48632 getSymbol(symbol$$1) {
48633 return this.get(symbol$$1);
48634 }
48635
48636 getBlock(symbol$$1) {
48637 var block = this.get(symbol$$1);
48638 return block === UNDEFINED_REFERENCE ? null : block;
48639 }
48640
48641 getEvalScope() {
48642 return this.evalScope;
48643 }
48644
48645 getPartialMap() {
48646 return this.partialMap;
48647 }
48648
48649 bind(symbol$$1, value) {
48650 this.set(symbol$$1, value);
48651 }
48652
48653 bindSelf(self) {
48654 this.set(0, self);
48655 }
48656
48657 bindSymbol(symbol$$1, value) {
48658 this.set(symbol$$1, value);
48659 }
48660
48661 bindBlock(symbol$$1, value) {
48662 this.set(symbol$$1, value);
48663 }
48664
48665 bindEvalScope(map) {
48666 this.evalScope = map;
48667 }
48668
48669 bindPartialMap(map) {
48670 this.partialMap = map;
48671 }
48672
48673 bindCallerScope(scope) {
48674 this.callerScope = scope;
48675 }
48676
48677 getCallerScope() {
48678 return this.callerScope;
48679 }
48680
48681 child() {
48682 return new ScopeImpl(this.slots.slice(), this.callerScope, this.evalScope, this.partialMap);
48683 }
48684
48685 get(index) {
48686 if (index >= this.slots.length) {
48687 throw new RangeError(`BUG: cannot get $${index} from scope; length=${this.slots.length}`);
48688 }
48689
48690 return this.slots[index];
48691 }
48692
48693 set(index, value) {
48694 if (index >= this.slots.length) {
48695 throw new RangeError(`BUG: cannot get $${index} from scope; length=${this.slots.length}`);
48696 }
48697
48698 this.slots[index] = value;
48699 }
48700
48701 }
48702
48703 _exports.ScopeImpl = ScopeImpl;
48704 var TRANSACTION = (0, _util.symbol)('TRANSACTION');
48705
48706 class TransactionImpl {
48707 constructor() {
48708 this.scheduledInstallManagers = [];
48709 this.scheduledInstallModifiers = [];
48710 this.scheduledUpdateModifierManagers = [];
48711 this.scheduledUpdateModifiers = [];
48712 this.createdComponents = [];
48713 this.createdManagers = [];
48714 this.updatedComponents = [];
48715 this.updatedManagers = [];
48716 }
48717
48718 didCreate(component, manager) {
48719 this.createdComponents.push(component);
48720 this.createdManagers.push(manager);
48721 }
48722
48723 didUpdate(component, manager) {
48724 this.updatedComponents.push(component);
48725 this.updatedManagers.push(manager);
48726 }
48727
48728 scheduleInstallModifier(modifier, manager) {
48729 this.scheduledInstallModifiers.push(modifier);
48730 this.scheduledInstallManagers.push(manager);
48731 }
48732
48733 scheduleUpdateModifier(modifier, manager) {
48734 this.scheduledUpdateModifiers.push(modifier);
48735 this.scheduledUpdateModifierManagers.push(manager);
48736 }
48737
48738 commit() {
48739 var {
48740 createdComponents,
48741 createdManagers
48742 } = this;
48743
48744 for (var i = 0; i < createdComponents.length; i++) {
48745 var component = createdComponents[i];
48746 var manager = createdManagers[i];
48747 manager.didCreate(component);
48748 }
48749
48750 var {
48751 updatedComponents,
48752 updatedManagers
48753 } = this;
48754
48755 for (var _i = 0; _i < updatedComponents.length; _i++) {
48756 var _component = updatedComponents[_i];
48757 var _manager2 = updatedManagers[_i];
48758
48759 _manager2.didUpdate(_component);
48760 }
48761
48762 var {
48763 scheduledInstallManagers,
48764 scheduledInstallModifiers
48765 } = this;
48766
48767 for (var _i2 = 0; _i2 < scheduledInstallManagers.length; _i2++) {
48768 var modifier = scheduledInstallModifiers[_i2];
48769 var _manager3 = scheduledInstallManagers[_i2];
48770
48771 _manager3.install(modifier);
48772 }
48773
48774 var {
48775 scheduledUpdateModifierManagers,
48776 scheduledUpdateModifiers
48777 } = this;
48778
48779 for (var _i3 = 0; _i3 < scheduledUpdateModifierManagers.length; _i3++) {
48780 var _modifier = scheduledUpdateModifiers[_i3];
48781 var _manager4 = scheduledUpdateModifierManagers[_i3];
48782
48783 _manager4.update(_modifier);
48784 }
48785 }
48786
48787 }
48788
48789 function defaultDelegateFn(delegateFn, delegateDefault) {
48790 var defaultFn = delegateFn !== undefined ? delegateFn : delegateDefault;
48791
48792 if (true
48793 /* DEBUG */
48794 ) {
48795 // Bind to `null` in DEBUG since these methods are assumed to be pure
48796 // functions, so we can reassign them.
48797 return defaultFn.bind(null);
48798 }
48799
48800 return defaultFn;
48801 }
48802
48803 class EnvironmentImpl {
48804 constructor(options, delegate) {
48805 this.delegate = delegate;
48806 this[_a$1] = null; // Delegate methods and values
48807
48808 this.extra = this.delegate.extra;
48809 this.isInteractive = typeof this.delegate.isInteractive === 'boolean' ? this.delegate.isInteractive : true;
48810 this.protocolForURL = defaultDelegateFn(this.delegate.protocolForURL, defaultGetProtocolForURL);
48811 this.attributeFor = defaultDelegateFn(this.delegate.attributeFor, defaultAttributeFor);
48812 this.getProp = defaultDelegateFn(this.delegate.getProp, defaultGetProp);
48813 this.getPath = defaultDelegateFn(this.delegate.getPath, defaultGetProp);
48814 this.setPath = defaultDelegateFn(this.delegate.setPath, defaultSetPath);
48815 this.toBool = defaultDelegateFn(this.delegate.toBool, defaultToBool$1);
48816 this.toIterator = defaultDelegateFn(this.delegate.toIterator, defaultToIterator);
48817
48818 if (options.appendOperations) {
48819 this.appendOperations = options.appendOperations;
48820 this.updateOperations = options.updateOperations;
48821 } else if (options.document) {
48822 this.appendOperations = new DOMTreeConstruction(options.document);
48823 this.updateOperations = new DOMChangesImpl(options.document);
48824 } else if (true
48825 /* DEBUG */
48826 ) {
48827 throw new Error('you must pass document or appendOperations to a new runtime');
48828 }
48829 }
48830
48831 getTemplatePathDebugContext(ref) {
48832 if (this.delegate.getTemplatePathDebugContext !== undefined) {
48833 return this.delegate.getTemplatePathDebugContext(ref);
48834 }
48835
48836 return '';
48837 }
48838
48839 setTemplatePathDebugContext(ref, desc, parentRef) {
48840 if (this.delegate.setTemplatePathDebugContext !== undefined) {
48841 this.delegate.setTemplatePathDebugContext(ref, desc, parentRef);
48842 }
48843 }
48844
48845 toConditionalReference(input) {
48846 return new ConditionalReference(input, this.delegate.toBool);
48847 }
48848
48849 getAppendOperations() {
48850 return this.appendOperations;
48851 }
48852
48853 getDOM() {
48854 return this.updateOperations;
48855 }
48856
48857 begin() {
48858 if (this.delegate.onTransactionBegin !== undefined) {
48859 this.delegate.onTransactionBegin();
48860 }
48861
48862 this[TRANSACTION] = new TransactionImpl();
48863 }
48864
48865 get transaction() {
48866 return this[TRANSACTION];
48867 }
48868
48869 didCreate(component, manager) {
48870 this.transaction.didCreate(component, manager);
48871 }
48872
48873 didUpdate(component, manager) {
48874 this.transaction.didUpdate(component, manager);
48875 }
48876
48877 scheduleInstallModifier(modifier, manager) {
48878 if (this.isInteractive) {
48879 this.transaction.scheduleInstallModifier(modifier, manager);
48880 }
48881 }
48882
48883 scheduleUpdateModifier(modifier, manager) {
48884 if (this.isInteractive) {
48885 this.transaction.scheduleUpdateModifier(modifier, manager);
48886 }
48887 }
48888
48889 commit() {
48890 var transaction = this.transaction;
48891 this[TRANSACTION] = null;
48892 transaction.commit();
48893
48894 if (this.delegate.onTransactionCommit !== undefined) {
48895 this.delegate.onTransactionCommit();
48896 }
48897 }
48898
48899 }
48900
48901 _exports.EnvironmentImpl = EnvironmentImpl;
48902 _a$1 = TRANSACTION;
48903
48904 function defaultGetProtocolForURL(url) {
48905 if (typeof URL === 'object' || typeof URL === 'undefined') {
48906 return legacyProtocolForURL(url);
48907 } else if (typeof document !== 'undefined') {
48908 return new URL(url, document.baseURI).protocol;
48909 } else {
48910 return new URL(url, 'https://www.example.com').protocol;
48911 }
48912 }
48913
48914 function defaultAttributeFor(element, attr, _isTrusting, namespace) {
48915 return dynamicAttribute(element, attr, namespace);
48916 }
48917
48918 function defaultGetProp(obj, key) {
48919 return obj[key];
48920 }
48921
48922 function defaultSetPath(obj, key, value) {
48923 return obj[key] = value;
48924 }
48925
48926 function defaultToBool$1(value) {
48927 return Boolean(value);
48928 }
48929
48930 function defaultToIterator(value) {
48931 if (value && value[Symbol.iterator]) {
48932 return value[Symbol.iterator]();
48933 }
48934
48935 return null;
48936 }
48937
48938 function legacyProtocolForURL(url) {
48939 if (typeof window === 'undefined') {
48940 var match = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i.exec(url);
48941 return match && match[1] ? match[1].toLowerCase() : '';
48942 }
48943
48944 var anchor = window.document.createElement('a');
48945 anchor.href = url;
48946 return anchor.protocol;
48947 }
48948
48949 class DefaultRuntimeResolver {
48950 constructor(inner) {
48951 this.inner = inner;
48952 }
48953
48954 lookupComponent(name, referrer) {
48955 if (this.inner.lookupComponent) {
48956 var component = this.inner.lookupComponent(name, referrer);
48957
48958 if (component === undefined) {
48959 throw new Error(`Unexpected component ${name} (from ${referrer}) (lookupComponent returned undefined)`);
48960 }
48961
48962 return component;
48963 } else {
48964 throw new Error('lookupComponent not implemented on RuntimeResolver.');
48965 }
48966 }
48967
48968 lookupPartial(name, referrer) {
48969 if (this.inner.lookupPartial) {
48970 var partial = this.inner.lookupPartial(name, referrer);
48971
48972 if (partial === undefined) {
48973 throw new Error(`Unexpected partial ${name} (from ${referrer}) (lookupPartial returned undefined)`);
48974 }
48975
48976 return partial;
48977 } else {
48978 throw new Error('lookupPartial not implemented on RuntimeResolver.');
48979 }
48980 }
48981
48982 resolve(handle) {
48983 if (this.inner.resolve) {
48984 var resolved = this.inner.resolve(handle);
48985
48986 if (resolved === undefined) {
48987 throw new Error(`Unexpected handle ${handle} (resolve returned undefined)`);
48988 }
48989
48990 return resolved;
48991 } else {
48992 throw new Error('resolve not implemented on RuntimeResolver.');
48993 }
48994 }
48995
48996 compilable(locator) {
48997 if (this.inner.compilable) {
48998 var resolved = this.inner.compilable(locator);
48999
49000 if (resolved === undefined) {
49001 throw new Error(`Unable to compile ${name} (compilable returned undefined)`);
49002 }
49003
49004 return resolved;
49005 } else {
49006 throw new Error('compilable not implemented on RuntimeResolver.');
49007 }
49008 }
49009
49010 getInvocation(locator) {
49011 if (this.inner.getInvocation) {
49012 var invocation = this.inner.getInvocation(locator);
49013
49014 if (invocation === undefined) {
49015 throw new Error(`Unable to get invocation for ${JSON.stringify(locator)} (getInvocation returned undefined)`);
49016 }
49017
49018 return invocation;
49019 } else {
49020 throw new Error('getInvocation not implemented on RuntimeResolver.');
49021 }
49022 }
49023
49024 }
49025
49026 function AotRuntime(options, program, resolver = {}, delegate = {}) {
49027 var env = new EnvironmentImpl(options, delegate);
49028 return {
49029 env,
49030 resolver: new DefaultRuntimeResolver(resolver),
49031 program: _program.RuntimeProgramImpl.hydrate(program)
49032 };
49033 }
49034
49035 function JitRuntime(options, delegate = {}, context, resolver = {}) {
49036 return {
49037 env: new EnvironmentImpl(options, delegate),
49038 program: new _program.RuntimeProgramImpl(context.program.constants, context.program.heap),
49039 resolver: new DefaultRuntimeResolver(resolver)
49040 };
49041 }
49042
49043 function inTransaction(env, cb) {
49044 if (!env[TRANSACTION]) {
49045 env.begin();
49046
49047 try {
49048 cb();
49049 } finally {
49050 env.commit();
49051 }
49052 } else {
49053 cb();
49054 }
49055 }
49056
49057 class AppendOpcodes {
49058 constructor() {
49059 this.evaluateOpcode = (0, _util.fillNulls)(107
49060 /* Size */
49061 ).slice();
49062 }
49063
49064 add(name, evaluate, kind = 'syscall') {
49065 this.evaluateOpcode[name] = {
49066 syscall: kind !== 'machine',
49067 evaluate
49068 };
49069 }
49070
49071 debugBefore(vm, opcode) {
49072 var params = undefined;
49073 var opName = undefined;
49074 var sp;
49075 return {
49076 sp: sp,
49077 pc: vm.fetchValue(_vm2.$pc),
49078 name: opName,
49079 params,
49080 type: opcode.type,
49081 isMachine: opcode.isMachine,
49082 size: opcode.size,
49083 state: undefined
49084 };
49085 }
49086
49087 debugAfter(vm, pre) {}
49088
49089 evaluate(vm, opcode, type) {
49090 var operation = this.evaluateOpcode[type];
49091
49092 if (operation.syscall) {
49093 operation.evaluate(vm, opcode);
49094 } else {
49095 operation.evaluate(vm[INNER_VM], opcode);
49096 }
49097 }
49098
49099 }
49100
49101 var APPEND_OPCODES = new AppendOpcodes();
49102
49103 class AbstractOpcode {
49104 constructor() {
49105 (0, _util.initializeGuid)(this);
49106 }
49107
49108 }
49109
49110 class UpdatingOpcode extends AbstractOpcode {}
49111 /**
49112 * These utility functions are related to @glimmer/validator, but they aren't
49113 * meant to be consumed publicly. They exist as an optimization, and pull in
49114 * types that are otherwise unrelated to the validation system. Keeping them
49115 * here keeps the validation system isolated, and allows it to avoid pulling in
49116 * extra type information (which can lead to issues in public types).
49117 */
49118
49119
49120 function combineTagged(tagged) {
49121 var optimized = [];
49122
49123 for (var i = 0; i < tagged.length; i++) {
49124 var tag = tagged[i].tag;
49125 if (tag === _validator.CONSTANT_TAG) continue;
49126 optimized.push(tag);
49127 }
49128
49129 return (0, _validator.createCombinatorTag)(optimized);
49130 }
49131
49132 function combineFromIndex(tagged, startIndex) {
49133 var optimized = [];
49134
49135 for (var i = startIndex; i < tagged.length; i++) {
49136 var tag = tagged[i].tag;
49137 if (tag === _validator.CONSTANT_TAG) continue;
49138 optimized.push(tag);
49139 }
49140
49141 return (0, _validator.createCombinatorTag)(optimized);
49142 }
49143
49144 class ConcatReference extends _reference.CachedReference {
49145 constructor(parts) {
49146 super();
49147 this.parts = parts;
49148 this.tag = combineTagged(parts);
49149 }
49150
49151 compute() {
49152 var parts = new Array();
49153
49154 for (var i = 0; i < this.parts.length; i++) {
49155 var value = this.parts[i].value();
49156
49157 if (value !== null && value !== undefined) {
49158 parts[i] = castToString(value);
49159 }
49160 }
49161
49162 if (parts.length > 0) {
49163 return parts.join('');
49164 }
49165
49166 return null;
49167 }
49168
49169 }
49170
49171 function castToString(value) {
49172 if (typeof value.toString !== 'function') {
49173 return '';
49174 }
49175
49176 return String(value);
49177 }
49178
49179 APPEND_OPCODES.add(16
49180 /* Helper */
49181 , (vm, {
49182 op1: handle
49183 }) => {
49184 var stack = vm.stack;
49185 var helper = vm.runtime.resolver.resolve(handle);
49186 var args = stack.popJs();
49187 var value = helper(args, vm);
49188 vm.loadValue(_vm2.$v0, value);
49189 });
49190 APPEND_OPCODES.add(22
49191 /* GetVariable */
49192 , (vm, {
49193 op1: symbol$$1
49194 }) => {
49195 var expr = vm.referenceForSymbol(symbol$$1);
49196 vm.stack.pushJs(expr);
49197 });
49198 APPEND_OPCODES.add(19
49199 /* SetVariable */
49200 , (vm, {
49201 op1: symbol$$1
49202 }) => {
49203 var expr = vm.stack.pop();
49204 vm.scope().bindSymbol(symbol$$1, expr);
49205 });
49206 APPEND_OPCODES.add(21
49207 /* SetJitBlock */
49208 , (vm, {
49209 op1: symbol$$1
49210 }) => {
49211 var handle = vm.stack.popJs();
49212 var scope = vm.stack.popJs();
49213 var table = vm.stack.popJs();
49214 var block = table ? [handle, scope, table] : null;
49215 vm.scope().bindBlock(symbol$$1, block);
49216 }, 'jit');
49217 APPEND_OPCODES.add(20
49218 /* SetAotBlock */
49219 , (vm, {
49220 op1: symbol$$1
49221 }) => {
49222 // In DEBUG handles could be ErrHandle objects
49223 var handle = true
49224 /* DEBUG */
49225 ? vm.stack.pop() : vm.stack.popSmallInt();
49226 var scope = vm.stack.popJs();
49227 var table = vm.stack.popJs();
49228 var block = table ? [handle, scope, table] : null;
49229 vm.scope().bindBlock(symbol$$1, block);
49230 });
49231 APPEND_OPCODES.add(105
49232 /* ResolveMaybeLocal */
49233 , (vm, {
49234 op1: _name
49235 }) => {
49236 var name = vm[CONSTANTS].getValue(_name);
49237 var locals = vm.scope().getPartialMap();
49238 var ref = locals[name];
49239
49240 if (ref === undefined) {
49241 ref = vm.getSelf().get(name);
49242 }
49243
49244 vm.stack.pushJs(ref);
49245 });
49246 APPEND_OPCODES.add(37
49247 /* RootScope */
49248 , (vm, {
49249 op1: symbols
49250 }) => {
49251 vm.pushRootScope(symbols);
49252 });
49253 APPEND_OPCODES.add(23
49254 /* GetProperty */
49255 , (vm, {
49256 op1: _key
49257 }) => {
49258 var key = vm[CONSTANTS].getValue(_key);
49259 var expr = vm.stack.popJs();
49260 vm.stack.pushJs(expr.get(key));
49261 });
49262 APPEND_OPCODES.add(24
49263 /* GetBlock */
49264 , (vm, {
49265 op1: _block
49266 }) => {
49267 var {
49268 stack
49269 } = vm;
49270 var block = vm.scope().getBlock(_block);
49271
49272 if (block === null) {
49273 stack.pushNull();
49274 } else {
49275 stack.pushJs(block);
49276 }
49277 });
49278 APPEND_OPCODES.add(25
49279 /* JitSpreadBlock */
49280 , vm => {
49281 var {
49282 stack
49283 } = vm;
49284 var block = stack.popJs();
49285
49286 if (block && !isUndefinedReference(block)) {
49287 var [handleOrCompilable, scope, table] = block;
49288 stack.pushJs(table);
49289 stack.pushJs(scope);
49290
49291 if (typeof handleOrCompilable === 'number') {
49292 stack.pushSmallInt(handleOrCompilable);
49293 } else {
49294 stack.pushJs(handleOrCompilable);
49295 }
49296 } else {
49297 stack.pushNull();
49298 stack.pushNull();
49299 stack.pushNull();
49300 }
49301 });
49302
49303 function isUndefinedReference(input) {
49304 return input === UNDEFINED_REFERENCE;
49305 }
49306
49307 APPEND_OPCODES.add(26
49308 /* HasBlock */
49309 , vm => {
49310 var {
49311 stack
49312 } = vm;
49313 var block = stack.pop();
49314
49315 if (block && !isUndefinedReference(block)) {
49316 stack.pushJs(TRUE_REFERENCE);
49317 } else {
49318 stack.pushJs(FALSE_REFERENCE);
49319 }
49320 });
49321 APPEND_OPCODES.add(27
49322 /* HasBlockParams */
49323 , vm => {
49324 // FIXME(mmun): should only need to push the symbol table
49325 var block = vm.stack.pop();
49326 var scope = vm.stack.popJs();
49327 var table = vm.stack.popJs();
49328 var hasBlockParams = table && table.parameters.length;
49329 vm.stack.pushJs(hasBlockParams ? TRUE_REFERENCE : FALSE_REFERENCE);
49330 });
49331 APPEND_OPCODES.add(28
49332 /* Concat */
49333 , (vm, {
49334 op1: count
49335 }) => {
49336 var out = new Array(count);
49337
49338 for (var i = count; i > 0; i--) {
49339 var offset = i - 1;
49340 out[offset] = vm.stack.pop();
49341 }
49342
49343 vm.stack.pushJs(new ConcatReference(out));
49344 });
49345 /**
49346 * Converts a ComponentCapabilities object into a 32-bit integer representation.
49347 */
49348
49349 function capabilityFlagsFrom(capabilities) {
49350 return 0 | (capabilities.dynamicLayout ? 1
49351 /* DynamicLayout */
49352 : 0) | (capabilities.dynamicTag ? 2
49353 /* DynamicTag */
49354 : 0) | (capabilities.prepareArgs ? 4
49355 /* PrepareArgs */
49356 : 0) | (capabilities.createArgs ? 8
49357 /* CreateArgs */
49358 : 0) | (capabilities.attributeHook ? 16
49359 /* AttributeHook */
49360 : 0) | (capabilities.elementHook ? 32
49361 /* ElementHook */
49362 : 0) | (capabilities.dynamicScope ? 64
49363 /* DynamicScope */
49364 : 0) | (capabilities.createCaller ? 128
49365 /* CreateCaller */
49366 : 0) | (capabilities.updateHook ? 256
49367 /* UpdateHook */
49368 : 0) | (capabilities.createInstance ? 512
49369 /* CreateInstance */
49370 : 0) | (capabilities.wrapped ? 1024
49371 /* Wrapped */
49372 : 0) | (capabilities.willDestroy ? 2048
49373 /* WillDestroy */
49374 : 0);
49375 }
49376
49377 function managerHasCapability(_manager, capabilities, capability) {
49378 return !!(capabilities & capability);
49379 }
49380
49381 function hasCapability(capabilities, capability) {
49382 return !!(capabilities & capability);
49383 }
49384
49385 var _a$2;
49386
49387 var CURRIED_COMPONENT_DEFINITION_BRAND = (0, _util.symbol)('CURRIED COMPONENT DEFINITION');
49388
49389 function isCurriedComponentDefinition(definition) {
49390 return !!(definition && definition[CURRIED_COMPONENT_DEFINITION_BRAND]);
49391 }
49392
49393 function isComponentDefinition(definition) {
49394 return !!(definition && definition[CURRIED_COMPONENT_DEFINITION_BRAND]);
49395 }
49396
49397 class CurriedComponentDefinition {
49398 /** @internal */
49399 constructor(inner, args) {
49400 this.inner = inner;
49401 this.args = args;
49402 this[_a$2] = true;
49403 }
49404
49405 unwrap(args) {
49406 args.realloc(this.offset);
49407 var definition = this;
49408
49409 while (true) {
49410 var {
49411 args: curriedArgs,
49412 inner
49413 } = definition;
49414
49415 if (curriedArgs) {
49416 args.positional.prepend(curriedArgs.positional);
49417 args.named.merge(curriedArgs.named);
49418 }
49419
49420 if (!isCurriedComponentDefinition(inner)) {
49421 return inner;
49422 }
49423
49424 definition = inner;
49425 }
49426 }
49427 /** @internal */
49428
49429
49430 get offset() {
49431 var {
49432 inner,
49433 args
49434 } = this;
49435 var length = args ? args.positional.length : 0;
49436 return isCurriedComponentDefinition(inner) ? length + inner.offset : length;
49437 }
49438
49439 }
49440
49441 _exports.CurriedComponentDefinition = CurriedComponentDefinition;
49442 _a$2 = CURRIED_COMPONENT_DEFINITION_BRAND;
49443
49444 function curry(spec, args = null) {
49445 return new CurriedComponentDefinition(spec, args);
49446 }
49447
49448 function resolveComponent(resolver, name, meta) {
49449 var definition = resolver.lookupComponent(name, meta);
49450 return definition;
49451 }
49452
49453 class ClassListReference {
49454 constructor(list) {
49455 this.list = list;
49456 this.tag = combineTagged(list);
49457 this.list = list;
49458 }
49459
49460 value() {
49461 var ret = [];
49462 var {
49463 list
49464 } = this;
49465
49466 for (var i = 0; i < list.length; i++) {
49467 var value = normalizeStringValue(list[i].value());
49468 if (value) ret.push(value);
49469 }
49470
49471 return ret.length === 0 ? null : ret.join(' ');
49472 }
49473
49474 }
49475
49476 class CurryComponentReference {
49477 constructor(inner, resolver, meta, args) {
49478 this.inner = inner;
49479 this.resolver = resolver;
49480 this.meta = meta;
49481 this.args = args;
49482 this.tag = inner.tag;
49483 this.lastValue = null;
49484 this.lastDefinition = null;
49485 }
49486
49487 value() {
49488 var {
49489 inner,
49490 lastValue
49491 } = this;
49492 var value = inner.value();
49493
49494 if (value === lastValue) {
49495 return this.lastDefinition;
49496 }
49497
49498 var definition = null;
49499
49500 if (isCurriedComponentDefinition(value)) {
49501 definition = value;
49502 } else if (typeof value === 'string' && value) {
49503 var {
49504 resolver,
49505 meta
49506 } = this;
49507 definition = resolveComponent(resolver, value, meta);
49508 }
49509
49510 definition = this.curry(definition);
49511 this.lastValue = value;
49512 this.lastDefinition = definition;
49513 return definition;
49514 }
49515
49516 get() {
49517 return UNDEFINED_REFERENCE;
49518 }
49519
49520 curry(definition) {
49521 var {
49522 args
49523 } = this;
49524
49525 if (!args && isCurriedComponentDefinition(definition)) {
49526 return definition;
49527 } else if (!definition) {
49528 return null;
49529 } else {
49530 return new CurriedComponentDefinition(definition, args);
49531 }
49532 }
49533
49534 }
49535
49536 class DynamicTextContent extends UpdatingOpcode {
49537 constructor(node, reference, lastValue) {
49538 super();
49539 this.node = node;
49540 this.reference = reference;
49541 this.lastValue = lastValue;
49542 this.type = 'dynamic-text';
49543 this.tag = reference.tag;
49544 this.lastRevision = (0, _validator.valueForTag)(this.tag);
49545 }
49546
49547 evaluate() {
49548 var {
49549 reference,
49550 tag
49551 } = this;
49552
49553 if (!(0, _validator.validateTag)(tag, this.lastRevision)) {
49554 this.lastRevision = (0, _validator.valueForTag)(tag);
49555 this.update(reference.value());
49556 }
49557 }
49558
49559 update(value) {
49560 var {
49561 lastValue
49562 } = this;
49563 if (value === lastValue) return;
49564 var normalized;
49565
49566 if (isEmpty(value)) {
49567 normalized = '';
49568 } else if (isString(value)) {
49569 normalized = value;
49570 } else {
49571 normalized = String(value);
49572 }
49573
49574 if (normalized !== lastValue) {
49575 var textNode = this.node;
49576 textNode.nodeValue = this.lastValue = normalized;
49577 }
49578 }
49579
49580 }
49581
49582 class ContentTypeReference {
49583 constructor(inner) {
49584 this.inner = inner;
49585 this.tag = inner.tag;
49586 }
49587
49588 value() {
49589 var value = this.inner.value();
49590
49591 if (shouldCoerce(value)) {
49592 return 1
49593 /* String */
49594 ;
49595 } else if (isComponentDefinition(value)) {
49596 return 0
49597 /* Component */
49598 ;
49599 } else if (isSafeString(value)) {
49600 return 3
49601 /* SafeString */
49602 ;
49603 } else if (isFragment(value)) {
49604 return 4
49605 /* Fragment */
49606 ;
49607 } else if (isNode(value)) {
49608 return 5
49609 /* Node */
49610 ;
49611 } else {
49612 return 1
49613 /* String */
49614 ;
49615 }
49616 }
49617
49618 }
49619
49620 APPEND_OPCODES.add(43
49621 /* AppendHTML */
49622 , vm => {
49623 var reference = vm.stack.popJs();
49624 var rawValue = reference.value();
49625 var value = isEmpty(rawValue) ? '' : String(rawValue);
49626 vm.elements().appendDynamicHTML(value);
49627 });
49628 APPEND_OPCODES.add(44
49629 /* AppendSafeHTML */
49630 , vm => {
49631 var reference = vm.stack.popJs();
49632 var rawValue = reference.value().toHTML();
49633 var value = isEmpty(rawValue) ? '' : rawValue;
49634 vm.elements().appendDynamicHTML(value);
49635 });
49636 APPEND_OPCODES.add(47
49637 /* AppendText */
49638 , vm => {
49639 var reference = vm.stack.popJs();
49640 var rawValue = reference.value();
49641 var value = isEmpty(rawValue) ? '' : String(rawValue);
49642 var node = vm.elements().appendDynamicText(value);
49643
49644 if (!(0, _validator.isConstTagged)(reference)) {
49645 vm.updateWith(new DynamicTextContent(node, reference, value));
49646 }
49647 });
49648 APPEND_OPCODES.add(45
49649 /* AppendDocumentFragment */
49650 , vm => {
49651 var reference = vm.stack.popJs();
49652 var value = reference.value();
49653 vm.elements().appendDynamicFragment(value);
49654 });
49655 APPEND_OPCODES.add(46
49656 /* AppendNode */
49657 , vm => {
49658 var reference = vm.stack.popJs();
49659 var value = reference.value();
49660 vm.elements().appendDynamicNode(value);
49661 });
49662 APPEND_OPCODES.add(39
49663 /* ChildScope */
49664 , vm => vm.pushChildScope());
49665 APPEND_OPCODES.add(40
49666 /* PopScope */
49667 , vm => vm.popScope());
49668 APPEND_OPCODES.add(59
49669 /* PushDynamicScope */
49670 , vm => vm.pushDynamicScope());
49671 APPEND_OPCODES.add(60
49672 /* PopDynamicScope */
49673 , vm => vm.popDynamicScope());
49674 APPEND_OPCODES.add(29
49675 /* Constant */
49676 , (vm, {
49677 op1: other
49678 }) => {
49679 vm.stack.pushJs(vm[CONSTANTS].getValue((0, _util.decodeHandle)(other)));
49680 });
49681 APPEND_OPCODES.add(30
49682 /* Primitive */
49683 , (vm, {
49684 op1: primitive
49685 }) => {
49686 var stack = vm.stack;
49687
49688 if ((0, _util.isNonPrimitiveHandle)(primitive)) {
49689 // it is a handle which does not already exist on the stack
49690 var value = vm[CONSTANTS].getValue((0, _util.decodeHandle)(primitive));
49691 stack.pushJs(value);
49692 } else {
49693 // is already an encoded immediate or primitive handle
49694 stack.pushRaw(primitive);
49695 }
49696 });
49697 APPEND_OPCODES.add(31
49698 /* PrimitiveReference */
49699 , vm => {
49700 var stack = vm.stack;
49701 stack.pushJs(PrimitiveReference.create(stack.pop()));
49702 });
49703 APPEND_OPCODES.add(32
49704 /* ReifyU32 */
49705 , vm => {
49706 var stack = vm.stack;
49707 stack.pushSmallInt(stack.peekJs().value());
49708 });
49709 APPEND_OPCODES.add(33
49710 /* Dup */
49711 , (vm, {
49712 op1: register,
49713 op2: offset
49714 }) => {
49715 var position = vm.fetchValue(register) - offset;
49716 vm.stack.dup(position);
49717 });
49718 APPEND_OPCODES.add(34
49719 /* Pop */
49720 , (vm, {
49721 op1: count
49722 }) => {
49723 vm.stack.pop(count);
49724 });
49725 APPEND_OPCODES.add(35
49726 /* Load */
49727 , (vm, {
49728 op1: register
49729 }) => {
49730 vm.load(register);
49731 });
49732 APPEND_OPCODES.add(36
49733 /* Fetch */
49734 , (vm, {
49735 op1: register
49736 }) => {
49737 vm.fetch(register);
49738 });
49739 APPEND_OPCODES.add(58
49740 /* BindDynamicScope */
49741 , (vm, {
49742 op1: _names
49743 }) => {
49744 var names = vm[CONSTANTS].getArray(_names);
49745 vm.bindDynamicScope(names);
49746 });
49747 APPEND_OPCODES.add(69
49748 /* Enter */
49749 , (vm, {
49750 op1: args
49751 }) => {
49752 vm.enter(args);
49753 });
49754 APPEND_OPCODES.add(70
49755 /* Exit */
49756 , vm => {
49757 vm.exit();
49758 });
49759 APPEND_OPCODES.add(63
49760 /* PushSymbolTable */
49761 , (vm, {
49762 op1: _table
49763 }) => {
49764 var stack = vm.stack;
49765 stack.pushJs(vm[CONSTANTS].getSerializable(_table));
49766 });
49767 APPEND_OPCODES.add(62
49768 /* PushBlockScope */
49769 , vm => {
49770 var stack = vm.stack;
49771 stack.pushJs(vm.scope());
49772 });
49773 APPEND_OPCODES.add(61
49774 /* CompileBlock */
49775 , vm => {
49776 var stack = vm.stack;
49777 var block = stack.pop();
49778
49779 if (block) {
49780 stack.pushSmallInt(vm.compile(block));
49781 } else {
49782 stack.pushNull();
49783 }
49784 }, 'jit');
49785 APPEND_OPCODES.add(64
49786 /* InvokeYield */
49787 , vm => {
49788 var {
49789 stack
49790 } = vm;
49791 var handle = stack.pop();
49792 var scope = stack.popJs();
49793 var table = stack.popJs();
49794 var args = stack.pop();
49795
49796 if (table === null) {
49797 // To balance the pop{Frame,Scope}
49798 vm.pushFrame();
49799 vm.pushScope(scope); // Could be null but it doesnt matter as it is immediatelly popped.
49800
49801 return;
49802 }
49803
49804 var invokingScope = scope; // If necessary, create a child scope
49805
49806 {
49807 var locals = table.parameters;
49808 var localsCount = locals.length;
49809
49810 if (localsCount > 0) {
49811 invokingScope = invokingScope.child();
49812
49813 for (var i = 0; i < localsCount; i++) {
49814 invokingScope.bindSymbol(locals[i], args.at(i));
49815 }
49816 }
49817 }
49818 vm.pushFrame();
49819 vm.pushScope(invokingScope);
49820 vm.call(handle);
49821 });
49822 APPEND_OPCODES.add(65
49823 /* JumpIf */
49824 , (vm, {
49825 op1: target
49826 }) => {
49827 var reference = vm.stack.popJs();
49828
49829 if ((0, _validator.isConstTagged)(reference)) {
49830 if (reference.value()) {
49831 vm.goto(target);
49832 }
49833 } else {
49834 var cache = new _reference.ReferenceCache(reference);
49835
49836 if (cache.peek()) {
49837 vm.goto(target);
49838 }
49839
49840 vm.updateWith(new Assert(cache));
49841 }
49842 });
49843 APPEND_OPCODES.add(66
49844 /* JumpUnless */
49845 , (vm, {
49846 op1: target
49847 }) => {
49848 var reference = vm.stack.popJs();
49849
49850 if ((0, _validator.isConstTagged)(reference)) {
49851 if (!reference.value()) {
49852 vm.goto(target);
49853 }
49854 } else {
49855 var cache = new _reference.ReferenceCache(reference);
49856
49857 if (!cache.peek()) {
49858 vm.goto(target);
49859 }
49860
49861 vm.updateWith(new Assert(cache));
49862 }
49863 });
49864 APPEND_OPCODES.add(67
49865 /* JumpEq */
49866 , (vm, {
49867 op1: target,
49868 op2: comparison
49869 }) => {
49870 var other = vm.stack.peekSmallInt();
49871
49872 if (other === comparison) {
49873 vm.goto(target);
49874 }
49875 });
49876 APPEND_OPCODES.add(68
49877 /* AssertSame */
49878 , vm => {
49879 var reference = vm.stack.peekJs();
49880
49881 if (!(0, _validator.isConstTagged)(reference)) {
49882 vm.updateWith(Assert.initialize(new _reference.ReferenceCache(reference)));
49883 }
49884 });
49885 APPEND_OPCODES.add(71
49886 /* ToBoolean */
49887 , vm => {
49888 var {
49889 env,
49890 stack
49891 } = vm;
49892 stack.pushJs(env.toConditionalReference(stack.popJs()));
49893 });
49894
49895 class Assert extends UpdatingOpcode {
49896 constructor(cache) {
49897 super();
49898 this.type = 'assert';
49899 this.tag = cache.tag;
49900 this.cache = cache;
49901 }
49902
49903 static initialize(cache) {
49904 var assert = new Assert(cache);
49905 cache.peek();
49906 return assert;
49907 }
49908
49909 evaluate(vm) {
49910 var {
49911 cache
49912 } = this;
49913
49914 if ((0, _reference.isModified)(cache.revalidate())) {
49915 vm.throw();
49916 }
49917 }
49918
49919 }
49920
49921 class JumpIfNotModifiedOpcode extends UpdatingOpcode {
49922 constructor(index) {
49923 super();
49924 this.index = index;
49925 this.type = 'jump-if-not-modified';
49926 this.tag = _validator.CONSTANT_TAG;
49927 this.lastRevision = _validator.INITIAL;
49928 }
49929
49930 finalize(tag, target) {
49931 this.tag = tag;
49932 this.target = target;
49933 }
49934
49935 evaluate(vm) {
49936 var {
49937 tag,
49938 target,
49939 lastRevision
49940 } = this;
49941
49942 if (!vm.alwaysRevalidate && (0, _validator.validateTag)(tag, lastRevision)) {
49943 vm.goto(target);
49944 }
49945 }
49946
49947 didModify() {
49948 this.lastRevision = (0, _validator.valueForTag)(this.tag);
49949 }
49950
49951 }
49952
49953 class DidModifyOpcode extends UpdatingOpcode {
49954 constructor(target) {
49955 super();
49956 this.target = target;
49957 this.type = 'did-modify';
49958 this.tag = _validator.CONSTANT_TAG;
49959 }
49960
49961 evaluate() {
49962 this.target.didModify();
49963 }
49964
49965 }
49966
49967 APPEND_OPCODES.add(41
49968 /* Text */
49969 , (vm, {
49970 op1: text
49971 }) => {
49972 vm.elements().appendText(vm[CONSTANTS].getValue(text));
49973 });
49974 APPEND_OPCODES.add(42
49975 /* Comment */
49976 , (vm, {
49977 op1: text
49978 }) => {
49979 vm.elements().appendComment(vm[CONSTANTS].getValue(text));
49980 });
49981 APPEND_OPCODES.add(48
49982 /* OpenElement */
49983 , (vm, {
49984 op1: tag
49985 }) => {
49986 vm.elements().openElement(vm[CONSTANTS].getValue(tag));
49987 });
49988 APPEND_OPCODES.add(49
49989 /* OpenDynamicElement */
49990 , vm => {
49991 var tagName = vm.stack.popJs().value();
49992 vm.elements().openElement(tagName);
49993 });
49994 APPEND_OPCODES.add(50
49995 /* PushRemoteElement */
49996 , vm => {
49997 var elementRef = vm.stack.popJs();
49998 var insertBeforeRef = vm.stack.popJs();
49999 var guidRef = vm.stack.popJs();
50000 var element;
50001 var insertBefore;
50002 var guid = guidRef.value();
50003
50004 if ((0, _validator.isConstTagged)(elementRef)) {
50005 element = elementRef.value();
50006 } else {
50007 var cache = new _reference.ReferenceCache(elementRef);
50008 element = cache.peek();
50009 vm.updateWith(new Assert(cache));
50010 }
50011
50012 if (insertBeforeRef.value() !== undefined) {
50013 if ((0, _validator.isConstTagged)(insertBeforeRef)) {
50014 insertBefore = insertBeforeRef.value();
50015 } else {
50016 var _cache = new _reference.ReferenceCache(insertBeforeRef);
50017
50018 insertBefore = _cache.peek();
50019 vm.updateWith(new Assert(_cache));
50020 }
50021 }
50022
50023 var block = vm.elements().pushRemoteElement(element, guid, insertBefore);
50024 if (block) vm.associateDestroyable(block);
50025 });
50026 APPEND_OPCODES.add(56
50027 /* PopRemoteElement */
50028 , vm => {
50029 vm.elements().popRemoteElement();
50030 });
50031 APPEND_OPCODES.add(54
50032 /* FlushElement */
50033 , vm => {
50034 var operations = vm.fetchValue(_vm2.$t0);
50035 var modifiers = null;
50036
50037 if (operations) {
50038 modifiers = operations.flush(vm);
50039 vm.loadValue(_vm2.$t0, null);
50040 }
50041
50042 vm.elements().flushElement(modifiers);
50043 });
50044 APPEND_OPCODES.add(55
50045 /* CloseElement */
50046 , vm => {
50047 var modifiers = vm.elements().closeElement();
50048
50049 if (modifiers) {
50050 modifiers.forEach(([manager, modifier]) => {
50051 vm.env.scheduleInstallModifier(modifier, manager);
50052 var d = manager.getDestroyable(modifier);
50053
50054 if (d) {
50055 vm.associateDestroyable(d);
50056 }
50057 });
50058 }
50059 });
50060 APPEND_OPCODES.add(57
50061 /* Modifier */
50062 , (vm, {
50063 op1: handle
50064 }) => {
50065 var {
50066 manager,
50067 state
50068 } = vm.runtime.resolver.resolve(handle);
50069 var stack = vm.stack;
50070 var args = stack.popJs();
50071 var {
50072 constructing,
50073 updateOperations
50074 } = vm.elements();
50075 var dynamicScope = vm.dynamicScope();
50076 var modifier = manager.create(constructing, state, args, dynamicScope, updateOperations);
50077 var operations = vm.fetchValue(_vm2.$t0);
50078 operations.addModifier(manager, modifier);
50079 var tag = manager.getTag(modifier);
50080
50081 if (!(0, _validator.isConstTag)(tag)) {
50082 vm.updateWith(new UpdateModifierOpcode(tag, manager, modifier));
50083 }
50084 });
50085
50086 class UpdateModifierOpcode extends UpdatingOpcode {
50087 constructor(tag, manager, modifier) {
50088 super();
50089 this.tag = tag;
50090 this.manager = manager;
50091 this.modifier = modifier;
50092 this.type = 'update-modifier';
50093 this.lastUpdated = (0, _validator.valueForTag)(tag);
50094 }
50095
50096 evaluate(vm) {
50097 var {
50098 manager,
50099 modifier,
50100 tag,
50101 lastUpdated
50102 } = this;
50103
50104 if (!(0, _validator.validateTag)(tag, lastUpdated)) {
50105 vm.env.scheduleUpdateModifier(modifier, manager);
50106 this.lastUpdated = (0, _validator.valueForTag)(tag);
50107 }
50108 }
50109
50110 }
50111
50112 APPEND_OPCODES.add(51
50113 /* StaticAttr */
50114 , (vm, {
50115 op1: _name,
50116 op2: _value,
50117 op3: _namespace
50118 }) => {
50119 var name = vm[CONSTANTS].getValue(_name);
50120 var value = vm[CONSTANTS].getValue(_value);
50121 var namespace = _namespace ? vm[CONSTANTS].getValue(_namespace) : null;
50122 vm.elements().setStaticAttribute(name, value, namespace);
50123 });
50124 APPEND_OPCODES.add(52
50125 /* DynamicAttr */
50126 , (vm, {
50127 op1: _name,
50128 op2: trusting,
50129 op3: _namespace
50130 }) => {
50131 var name = vm[CONSTANTS].getValue(_name);
50132 var reference = vm.stack.popJs();
50133 var value = reference.value();
50134 var namespace = _namespace ? vm[CONSTANTS].getValue(_namespace) : null;
50135 var attribute = vm.elements().setDynamicAttribute(name, value, !!trusting, namespace);
50136
50137 if (!(0, _validator.isConstTagged)(reference)) {
50138 vm.updateWith(new UpdateDynamicAttributeOpcode(reference, attribute));
50139 }
50140 });
50141
50142 class UpdateDynamicAttributeOpcode extends UpdatingOpcode {
50143 constructor(reference, attribute) {
50144 super();
50145 this.reference = reference;
50146 this.attribute = attribute;
50147 this.type = 'patch-element';
50148 var {
50149 tag
50150 } = reference;
50151 this.tag = tag;
50152 this.lastRevision = (0, _validator.valueForTag)(tag);
50153 }
50154
50155 evaluate(vm) {
50156 var {
50157 attribute,
50158 reference,
50159 tag
50160 } = this;
50161
50162 if (!(0, _validator.validateTag)(tag, this.lastRevision)) {
50163 attribute.update(reference.value(), vm.env);
50164 this.lastRevision = (0, _validator.valueForTag)(tag);
50165 }
50166 }
50167
50168 }
50169 /**
50170 * The VM creates a new ComponentInstance data structure for every component
50171 * invocation it encounters.
50172 *
50173 * Similar to how a ComponentDefinition contains state about all components of a
50174 * particular type, a ComponentInstance contains state specific to a particular
50175 * instance of a component type. It also contains a pointer back to its
50176 * component type's ComponentDefinition.
50177 */
50178
50179
50180 var COMPONENT_INSTANCE = (0, _util.symbol)('COMPONENT_INSTANCE');
50181 APPEND_OPCODES.add(77
50182 /* IsComponent */
50183 , vm => {
50184 var stack = vm.stack;
50185 var ref = stack.popJs();
50186 stack.pushJs(new ConditionalReference(ref, isCurriedComponentDefinition));
50187 });
50188 APPEND_OPCODES.add(78
50189 /* ContentType */
50190 , vm => {
50191 var stack = vm.stack;
50192 var ref = stack.peekJs();
50193 stack.pushJs(new ContentTypeReference(ref));
50194 });
50195 APPEND_OPCODES.add(79
50196 /* CurryComponent */
50197 , (vm, {
50198 op1: _meta
50199 }) => {
50200 var stack = vm.stack;
50201 var definition = stack.popJs();
50202 var capturedArgs = stack.popJs();
50203 var meta = vm[CONSTANTS].getValue((0, _util.decodeHandle)(_meta));
50204 var resolver = vm.runtime.resolver;
50205 vm.loadValue(_vm2.$v0, new CurryComponentReference(definition, resolver, meta, capturedArgs)); // expectStackChange(vm.stack, -args.length - 1, 'CurryComponent');
50206 });
50207 APPEND_OPCODES.add(80
50208 /* PushComponentDefinition */
50209 , (vm, {
50210 op1: handle
50211 }) => {
50212 var definition = vm.runtime.resolver.resolve(handle);
50213 var {
50214 manager
50215 } = definition;
50216 var capabilities = capabilityFlagsFrom(manager.getCapabilities(definition.state));
50217 var instance = {
50218 [COMPONENT_INSTANCE]: true,
50219 definition,
50220 manager,
50221 capabilities,
50222 state: null,
50223 handle: null,
50224 table: null,
50225 lookup: null
50226 };
50227 vm.stack.pushJs(instance);
50228 });
50229 APPEND_OPCODES.add(83
50230 /* ResolveDynamicComponent */
50231 , (vm, {
50232 op1: _meta
50233 }) => {
50234 var stack = vm.stack;
50235 var component = stack.popJs().value();
50236 var meta = vm[CONSTANTS].getValue((0, _util.decodeHandle)(_meta));
50237 vm.loadValue(_vm2.$t1, null); // Clear the temp register
50238
50239 var definition;
50240
50241 if (typeof component === 'string') {
50242 var resolvedDefinition = resolveComponent(vm.runtime.resolver, component, meta);
50243 definition = resolvedDefinition;
50244 } else if (isCurriedComponentDefinition(component)) {
50245 definition = component;
50246 } else {
50247 throw (0, _util.unreachable)();
50248 }
50249
50250 stack.pushJs(definition);
50251 });
50252 APPEND_OPCODES.add(81
50253 /* PushDynamicComponentInstance */
50254 , vm => {
50255 var {
50256 stack
50257 } = vm;
50258 var definition = stack.pop();
50259 var capabilities, manager;
50260
50261 if (isCurriedComponentDefinition(definition)) {
50262 manager = capabilities = null;
50263 } else {
50264 manager = definition.manager;
50265 capabilities = capabilityFlagsFrom(manager.getCapabilities(definition.state));
50266 }
50267
50268 stack.pushJs({
50269 definition,
50270 capabilities,
50271 manager,
50272 state: null,
50273 handle: null,
50274 table: null
50275 });
50276 });
50277 APPEND_OPCODES.add(82
50278 /* PushCurriedComponent */
50279 , vm => {
50280 var stack = vm.stack;
50281 var component = stack.popJs().value();
50282 var definition;
50283
50284 if (isCurriedComponentDefinition(component)) {
50285 definition = component;
50286 } else {
50287 throw (0, _util.unreachable)();
50288 }
50289
50290 stack.pushJs(definition);
50291 });
50292 APPEND_OPCODES.add(84
50293 /* PushArgs */
50294 , (vm, {
50295 op1: _names,
50296 op2: _blockNames,
50297 op3: flags
50298 }) => {
50299 var stack = vm.stack;
50300 var names = vm[CONSTANTS].getArray(_names);
50301 var positionalCount = flags >> 4;
50302 var atNames = flags & 0b1000;
50303 var blockNames = flags & 0b0111 ? vm[CONSTANTS].getArray(_blockNames) : _util.EMPTY_ARRAY;
50304 vm[ARGS].setup(stack, names, blockNames, positionalCount, !!atNames);
50305 stack.pushJs(vm[ARGS]);
50306 });
50307 APPEND_OPCODES.add(85
50308 /* PushEmptyArgs */
50309 , vm => {
50310 var {
50311 stack
50312 } = vm;
50313 stack.pushJs(vm[ARGS].empty(stack));
50314 });
50315 APPEND_OPCODES.add(88
50316 /* CaptureArgs */
50317 , vm => {
50318 var stack = vm.stack;
50319 var args = stack.popJs();
50320 var capturedArgs = args.capture();
50321 stack.pushJs(capturedArgs);
50322 });
50323 APPEND_OPCODES.add(87
50324 /* PrepareArgs */
50325 , (vm, {
50326 op1: _state
50327 }) => {
50328 var stack = vm.stack;
50329 var instance = vm.fetchValue(_state);
50330 var args = stack.popJs();
50331 var {
50332 definition
50333 } = instance;
50334
50335 if (isCurriedComponentDefinition(definition)) {
50336 definition = resolveCurriedComponentDefinition(instance, definition, args);
50337 }
50338
50339 var {
50340 manager,
50341 state
50342 } = definition;
50343 var capabilities = instance.capabilities;
50344
50345 if (!managerHasCapability(manager, capabilities, 4
50346 /* PrepareArgs */
50347 )) {
50348 stack.pushJs(args);
50349 return;
50350 }
50351
50352 var blocks = args.blocks.values;
50353 var blockNames = args.blocks.names;
50354 var preparedArgs = manager.prepareArgs(state, args);
50355
50356 if (preparedArgs) {
50357 args.clear();
50358
50359 for (var i = 0; i < blocks.length; i++) {
50360 var block = blocks[i];
50361
50362 if (typeof block === 'number') {
50363 stack.pushSmallInt(block);
50364 } else {
50365 stack.pushJs(block);
50366 }
50367 }
50368
50369 var {
50370 positional,
50371 named
50372 } = preparedArgs;
50373 var positionalCount = positional.length;
50374
50375 for (var _i4 = 0; _i4 < positionalCount; _i4++) {
50376 stack.pushJs(positional[_i4]);
50377 }
50378
50379 var names = Object.keys(named);
50380
50381 for (var _i5 = 0; _i5 < names.length; _i5++) {
50382 stack.pushJs(named[names[_i5]]);
50383 }
50384
50385 args.setup(stack, names, blockNames, positionalCount, false);
50386 }
50387
50388 stack.pushJs(args);
50389 });
50390
50391 function resolveCurriedComponentDefinition(instance, definition, args) {
50392 var unwrappedDefinition = instance.definition = definition.unwrap(args);
50393 var {
50394 manager,
50395 state
50396 } = unwrappedDefinition;
50397 instance.manager = manager;
50398 instance.capabilities = capabilityFlagsFrom(manager.getCapabilities(state));
50399 return unwrappedDefinition;
50400 }
50401
50402 APPEND_OPCODES.add(89
50403 /* CreateComponent */
50404 , (vm, {
50405 op1: flags,
50406 op2: _state
50407 }) => {
50408 var instance = vm.fetchValue(_state);
50409 var {
50410 definition,
50411 manager
50412 } = instance;
50413 var capabilities = instance.capabilities = capabilityFlagsFrom(manager.getCapabilities(definition.state));
50414
50415 if (!managerHasCapability(manager, capabilities, 512
50416 /* CreateInstance */
50417 )) {
50418 throw new Error(`BUG`);
50419 }
50420
50421 var dynamicScope = null;
50422
50423 if (managerHasCapability(manager, capabilities, 64
50424 /* DynamicScope */
50425 )) {
50426 dynamicScope = vm.dynamicScope();
50427 }
50428
50429 var hasDefaultBlock = flags & 1;
50430 var args = null;
50431
50432 if (managerHasCapability(manager, capabilities, 8
50433 /* CreateArgs */
50434 )) {
50435 args = vm.stack.peekJs();
50436 }
50437
50438 var self = null;
50439
50440 if (managerHasCapability(manager, capabilities, 128
50441 /* CreateCaller */
50442 )) {
50443 self = vm.getSelf();
50444 }
50445
50446 var 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
50447 // only transition at exactly one place.
50448
50449 instance.state = state;
50450 var tag = manager.getTag(state);
50451
50452 if (managerHasCapability(manager, capabilities, 256
50453 /* UpdateHook */
50454 ) && !(0, _validator.isConstTag)(tag)) {
50455 vm.updateWith(new UpdateComponentOpcode(tag, state, manager, dynamicScope));
50456 }
50457 });
50458 APPEND_OPCODES.add(90
50459 /* RegisterComponentDestructor */
50460 , (vm, {
50461 op1: _state
50462 }) => {
50463 var {
50464 manager,
50465 state,
50466 capabilities
50467 } = vm.fetchValue(_state);
50468 var d = manager.getDestroyable(state);
50469
50470 if (true
50471 /* DEBUG */
50472 && !hasCapability(capabilities, 2048
50473 /* WillDestroy */
50474 ) && d !== null && typeof 'willDestroy' in d) {
50475 throw new Error('BUG: Destructor has willDestroy, but the willDestroy capability was not enabled for this component. Pre-destruction hooks must be explicitly opted into');
50476 }
50477
50478 if (d) vm.associateDestroyable(d);
50479 });
50480 APPEND_OPCODES.add(100
50481 /* BeginComponentTransaction */
50482 , vm => {
50483 vm.beginCacheGroup();
50484 vm.elements().pushSimpleBlock();
50485 });
50486 APPEND_OPCODES.add(91
50487 /* PutComponentOperations */
50488 , vm => {
50489 vm.loadValue(_vm2.$t0, new ComponentElementOperations());
50490 });
50491 APPEND_OPCODES.add(53
50492 /* ComponentAttr */
50493 , (vm, {
50494 op1: _name,
50495 op2: trusting,
50496 op3: _namespace
50497 }) => {
50498 var name = vm[CONSTANTS].getValue(_name);
50499 var reference = vm.stack.popJs();
50500 var namespace = _namespace ? vm[CONSTANTS].getValue(_namespace) : null;
50501 vm.fetchValue(_vm2.$t0).setAttribute(name, reference, !!trusting, namespace);
50502 });
50503 APPEND_OPCODES.add(108
50504 /* StaticComponentAttr */
50505 , (vm, {
50506 op1: _name,
50507 op2: _value,
50508 op3: _namespace
50509 }) => {
50510 var name = vm[CONSTANTS].getValue(_name);
50511 var value = vm[CONSTANTS].getValue(_value);
50512 var namespace = _namespace ? vm[CONSTANTS].getValue(_namespace) : null;
50513 vm.fetchValue(_vm2.$t0).setStaticAttribute(name, value, namespace);
50514 });
50515
50516 class ComponentElementOperations {
50517 constructor() {
50518 this.attributes = (0, _util.dict)();
50519 this.classes = [];
50520 this.modifiers = [];
50521 }
50522
50523 setAttribute(name, value, trusting, namespace) {
50524 var deferred = {
50525 value,
50526 namespace,
50527 trusting
50528 };
50529
50530 if (name === 'class') {
50531 this.classes.push(value);
50532 }
50533
50534 this.attributes[name] = deferred;
50535 }
50536
50537 setStaticAttribute(name, value, namespace) {
50538 var deferred = {
50539 value,
50540 namespace
50541 };
50542
50543 if (name === 'class') {
50544 this.classes.push(value);
50545 }
50546
50547 this.attributes[name] = deferred;
50548 }
50549
50550 addModifier(manager, state) {
50551 this.modifiers.push([manager, state]);
50552 }
50553
50554 flush(vm) {
50555 var type;
50556 var attributes = this.attributes;
50557
50558 for (var _name3 in this.attributes) {
50559 if (_name3 === 'type') {
50560 type = attributes[_name3];
50561 continue;
50562 }
50563
50564 var attr = this.attributes[_name3];
50565
50566 if (_name3 === 'class') {
50567 setDeferredAttr(vm, 'class', mergeClasses(this.classes), attr.namespace, attr.trusting);
50568 } else {
50569 setDeferredAttr(vm, _name3, attr.value, attr.namespace, attr.trusting);
50570 }
50571 }
50572
50573 if (type !== undefined) {
50574 setDeferredAttr(vm, 'type', type.value, type.namespace, type.trusting);
50575 }
50576
50577 return this.modifiers;
50578 }
50579
50580 }
50581
50582 function mergeClasses(classes) {
50583 if (classes.length === 0) {
50584 return '';
50585 }
50586
50587 if (classes.length === 1) {
50588 return classes[0];
50589 }
50590
50591 if (allStringClasses(classes)) {
50592 return classes.join(' ');
50593 }
50594
50595 return makeClassList(classes);
50596 }
50597
50598 function makeClassList(classes) {
50599 for (var i = 0; i < classes.length; i++) {
50600 var value = classes[i];
50601
50602 if (typeof value === 'string') {
50603 classes[i] = PrimitiveReference.create(value);
50604 }
50605 }
50606
50607 return new ClassListReference(classes);
50608 }
50609
50610 function allStringClasses(classes) {
50611 for (var i = 0; i < classes.length; i++) {
50612 if (typeof classes[i] !== 'string') {
50613 return false;
50614 }
50615 }
50616
50617 return true;
50618 }
50619
50620 function setDeferredAttr(vm, name, value, namespace, trusting = false) {
50621 if (typeof value === 'string') {
50622 vm.elements().setStaticAttribute(name, value, namespace);
50623 } else {
50624 var attribute = vm.elements().setDynamicAttribute(name, value.value(), trusting, namespace);
50625
50626 if (!(0, _validator.isConstTagged)(value)) {
50627 vm.updateWith(new UpdateDynamicAttributeOpcode(value, attribute));
50628 }
50629 }
50630 }
50631
50632 APPEND_OPCODES.add(102
50633 /* DidCreateElement */
50634 , (vm, {
50635 op1: _state
50636 }) => {
50637 var {
50638 definition,
50639 state
50640 } = vm.fetchValue(_state);
50641 var {
50642 manager
50643 } = definition;
50644 var operations = vm.fetchValue(_vm2.$t0);
50645 manager.didCreateElement(state, vm.elements().constructing, operations);
50646 });
50647 APPEND_OPCODES.add(92
50648 /* GetComponentSelf */
50649 , (vm, {
50650 op1: _state
50651 }) => {
50652 var {
50653 definition,
50654 state
50655 } = vm.fetchValue(_state);
50656 var {
50657 manager
50658 } = definition;
50659 vm.stack.pushJs(manager.getSelf(state));
50660 });
50661 APPEND_OPCODES.add(93
50662 /* GetComponentTagName */
50663 , (vm, {
50664 op1: _state
50665 }) => {
50666 var {
50667 definition,
50668 state
50669 } = vm.fetchValue(_state);
50670 var {
50671 manager
50672 } = definition;
50673 var tagName = manager.getTagName(state); // User provided value from JS, so we don't bother to encode
50674
50675 vm.stack.pushJs(tagName);
50676 }); // Dynamic Invocation Only
50677
50678 APPEND_OPCODES.add(95
50679 /* GetJitComponentLayout */
50680 , (vm, {
50681 op1: _state
50682 }) => {
50683 var instance = vm.fetchValue(_state);
50684 var manager = instance.manager;
50685 var {
50686 definition
50687 } = instance;
50688 var {
50689 stack
50690 } = vm;
50691 var {
50692 capabilities
50693 } = instance; // let invoke: { handle: number; symbolTable: ProgramSymbolTable };
50694
50695 var layout;
50696
50697 if (hasStaticLayoutCapability(capabilities, manager)) {
50698 layout = manager.getJitStaticLayout(definition.state, vm.runtime.resolver);
50699 } else if (hasDynamicLayoutCapability(capabilities, manager)) {
50700 var template = (0, _util.unwrapTemplate)(manager.getJitDynamicLayout(instance.state, vm.runtime.resolver));
50701
50702 if (hasCapability(capabilities, 1024
50703 /* Wrapped */
50704 )) {
50705 layout = template.asWrappedLayout();
50706 } else {
50707 layout = template.asLayout();
50708 }
50709 } else {
50710 throw (0, _util.unreachable)();
50711 }
50712
50713 var handle = layout.compile(vm.context);
50714 stack.pushJs(layout.symbolTable);
50715
50716 if (true
50717 /* DEBUG */
50718 && (0, _util.isErrHandle)(handle)) {
50719 stack.pushJs(handle);
50720 } else {
50721 stack.pushSmallInt(handle);
50722 }
50723 }, 'jit'); // Dynamic Invocation Only
50724
50725 APPEND_OPCODES.add(94
50726 /* GetAotComponentLayout */
50727 , (vm, {
50728 op1: _state
50729 }) => {
50730 var instance = vm.fetchValue(_state);
50731 var {
50732 manager,
50733 definition
50734 } = instance;
50735 var {
50736 stack
50737 } = vm;
50738 var {
50739 state: instanceState,
50740 capabilities
50741 } = instance;
50742 var {
50743 state: definitionState
50744 } = definition;
50745 var invoke;
50746
50747 if (hasStaticLayoutCapability(capabilities, manager)) {
50748 invoke = manager.getAotStaticLayout(definitionState, vm.runtime.resolver);
50749 } else if (hasDynamicLayoutCapability(capabilities, manager)) {
50750 invoke = manager.getAotDynamicLayout(instanceState, vm.runtime.resolver);
50751 } else {
50752 throw (0, _util.unreachable)();
50753 }
50754
50755 stack.pushJs(invoke.symbolTable);
50756
50757 if (true
50758 /* DEBUG */
50759 && (0, _util.isErrHandle)(invoke.handle)) {
50760 stack.pushJs(invoke.handle);
50761 } else {
50762 stack.pushSmallInt(invoke.handle);
50763 }
50764 }); // These types are absurd here
50765
50766 function hasStaticLayoutCapability(capabilities, _manager) {
50767 return managerHasCapability(_manager, capabilities, 1
50768 /* DynamicLayout */
50769 ) === false;
50770 }
50771
50772 function hasDynamicLayoutCapability(capabilities, _manager) {
50773 return managerHasCapability(_manager, capabilities, 1
50774 /* DynamicLayout */
50775 ) === true;
50776 }
50777
50778 APPEND_OPCODES.add(76
50779 /* Main */
50780 , (vm, {
50781 op1: register
50782 }) => {
50783 var definition = vm.stack.popJs();
50784 var invocation = vm.stack.popJs();
50785 var {
50786 manager
50787 } = definition;
50788 var capabilities = capabilityFlagsFrom(manager.getCapabilities(definition.state));
50789 var state = {
50790 [COMPONENT_INSTANCE]: true,
50791 definition,
50792 manager,
50793 capabilities,
50794 state: null,
50795 handle: invocation.handle,
50796 table: invocation.symbolTable,
50797 lookup: null
50798 };
50799 vm.loadValue(register, state);
50800 });
50801 APPEND_OPCODES.add(98
50802 /* PopulateLayout */
50803 , (vm, {
50804 op1: _state
50805 }) => {
50806 var {
50807 stack
50808 } = vm; // In DEBUG handles could be ErrHandle objects
50809
50810 var handle = true
50811 /* DEBUG */
50812 ? stack.pop() : stack.popSmallInt();
50813 var table = stack.popJs();
50814 var state = vm.fetchValue(_state);
50815 state.handle = handle;
50816 state.table = table;
50817 });
50818 APPEND_OPCODES.add(38
50819 /* VirtualRootScope */
50820 , (vm, {
50821 op1: _state
50822 }) => {
50823 var {
50824 symbols
50825 } = vm.fetchValue(_state).table;
50826 vm.pushRootScope(symbols.length + 1);
50827 });
50828 APPEND_OPCODES.add(97
50829 /* SetupForEval */
50830 , (vm, {
50831 op1: _state
50832 }) => {
50833 var state = vm.fetchValue(_state);
50834
50835 if (state.table.hasEval) {
50836 var lookup = state.lookup = (0, _util.dict)();
50837 vm.scope().bindEvalScope(lookup);
50838 }
50839 });
50840 APPEND_OPCODES.add(17
50841 /* SetNamedVariables */
50842 , (vm, {
50843 op1: _state
50844 }) => {
50845 var state = vm.fetchValue(_state);
50846 var scope = vm.scope();
50847 var args = vm.stack.peekJs();
50848 var callerNames = args.named.atNames;
50849
50850 for (var i = callerNames.length - 1; i >= 0; i--) {
50851 var atName = callerNames[i];
50852 var symbol$$1 = state.table.symbols.indexOf(callerNames[i]);
50853 var value = args.named.get(atName, true);
50854 if (symbol$$1 !== -1) scope.bindSymbol(symbol$$1 + 1, value);
50855 if (state.lookup) state.lookup[atName] = value;
50856 }
50857 });
50858
50859 function bindBlock(symbolName, blockName, state, blocks, vm) {
50860 var symbol$$1 = state.table.symbols.indexOf(symbolName);
50861 var block = blocks.get(blockName);
50862 if (symbol$$1 !== -1) vm.scope().bindBlock(symbol$$1 + 1, block);
50863 if (state.lookup) state.lookup[symbolName] = block;
50864 }
50865
50866 APPEND_OPCODES.add(18
50867 /* SetBlocks */
50868 , (vm, {
50869 op1: _state
50870 }) => {
50871 var state = vm.fetchValue(_state);
50872 var {
50873 blocks
50874 } = vm.stack.peekJs();
50875
50876 for (var i = 0; i < blocks.names.length; i++) {
50877 bindBlock(blocks.symbolNames[i], blocks.names[i], state, blocks, vm);
50878 }
50879 }); // Dynamic Invocation Only
50880
50881 APPEND_OPCODES.add(99
50882 /* InvokeComponentLayout */
50883 , (vm, {
50884 op1: _state
50885 }) => {
50886 var state = vm.fetchValue(_state);
50887 vm.call(state.handle);
50888 });
50889 APPEND_OPCODES.add(103
50890 /* DidRenderLayout */
50891 , (vm, {
50892 op1: _state
50893 }) => {
50894 var {
50895 manager,
50896 state,
50897 capabilities
50898 } = vm.fetchValue(_state);
50899 var bounds = vm.elements().popBlock();
50900
50901 if (!managerHasCapability(manager, capabilities, 512
50902 /* CreateInstance */
50903 )) {
50904 throw new Error(`BUG`);
50905 }
50906
50907 var mgr = manager;
50908 mgr.didRenderLayout(state, bounds);
50909 vm.env.didCreate(state, manager);
50910 vm.updateWith(new DidUpdateLayoutOpcode(manager, state, bounds));
50911 });
50912 APPEND_OPCODES.add(101
50913 /* CommitComponentTransaction */
50914 , vm => {
50915 vm.commitCacheGroup();
50916 });
50917
50918 class UpdateComponentOpcode extends UpdatingOpcode {
50919 constructor(tag, component, manager, dynamicScope) {
50920 super();
50921 this.tag = tag;
50922 this.component = component;
50923 this.manager = manager;
50924 this.dynamicScope = dynamicScope;
50925 this.type = 'update-component';
50926 }
50927
50928 evaluate(_vm) {
50929 var {
50930 component,
50931 manager,
50932 dynamicScope
50933 } = this;
50934 manager.update(component, dynamicScope);
50935 }
50936
50937 }
50938
50939 class DidUpdateLayoutOpcode extends UpdatingOpcode {
50940 constructor(manager, component, bounds) {
50941 super();
50942 this.manager = manager;
50943 this.component = component;
50944 this.bounds = bounds;
50945 this.type = 'did-update-layout';
50946 this.tag = _validator.CONSTANT_TAG;
50947 }
50948
50949 evaluate(vm) {
50950 var {
50951 manager,
50952 component,
50953 bounds
50954 } = this;
50955 manager.didUpdateLayout(component, bounds);
50956 vm.env.didUpdate(component, manager);
50957 }
50958
50959 }
50960
50961 function debugCallback(context, get) {
50962 console.info('Use `context`, and `get(<path>)` to debug this template.'); // for example...
50963 // eslint-disable-next-line no-unused-expressions
50964
50965 context === get('this'); // eslint-disable-next-line no-debugger
50966
50967 debugger;
50968 }
50969
50970 var callback = debugCallback; // For testing purposes
50971
50972 function setDebuggerCallback(cb) {
50973 callback = cb;
50974 }
50975
50976 function resetDebuggerCallback() {
50977 callback = debugCallback;
50978 }
50979
50980 class ScopeInspector {
50981 constructor(scope, symbols, evalInfo) {
50982 this.scope = scope;
50983 this.locals = (0, _util.dict)();
50984
50985 for (var i = 0; i < evalInfo.length; i++) {
50986 var slot = evalInfo[i];
50987 var _name4 = symbols[slot - 1];
50988 var ref = scope.getSymbol(slot);
50989 this.locals[_name4] = ref;
50990 }
50991 }
50992
50993 get(path) {
50994 var {
50995 scope,
50996 locals
50997 } = this;
50998 var parts = path.split('.');
50999 var [head, ...tail] = path.split('.');
51000 var evalScope = scope.getEvalScope();
51001 var ref;
51002
51003 if (head === 'this') {
51004 ref = scope.getSelf();
51005 } else if (locals[head]) {
51006 ref = locals[head];
51007 } else if (head.indexOf('@') === 0 && evalScope[head]) {
51008 ref = evalScope[head];
51009 } else {
51010 ref = this.scope.getSelf();
51011 tail = parts;
51012 }
51013
51014 return tail.reduce((r, part) => r.get(part), ref);
51015 }
51016
51017 }
51018
51019 APPEND_OPCODES.add(106
51020 /* Debugger */
51021 , (vm, {
51022 op1: _symbols,
51023 op2: _evalInfo
51024 }) => {
51025 var symbols = vm[CONSTANTS].getArray(_symbols);
51026 var evalInfo = vm[CONSTANTS].getValue((0, _util.decodeHandle)(_evalInfo));
51027 var inspector = new ScopeInspector(vm.scope(), symbols, evalInfo);
51028 callback(vm.getSelf().value(), path => inspector.get(path).value());
51029 });
51030 APPEND_OPCODES.add(104
51031 /* InvokePartial */
51032 , (vm, {
51033 op1: _meta,
51034 op2: _symbols,
51035 op3: _evalInfo
51036 }) => {
51037 var {
51038 [CONSTANTS]: constants$$1,
51039 stack
51040 } = vm;
51041 var name = stack.popJs().value();
51042 var meta = constants$$1.getValue((0, _util.decodeHandle)(_meta));
51043 var outerSymbols = constants$$1.getArray(_symbols);
51044 var evalInfo = constants$$1.getValue((0, _util.decodeHandle)(_evalInfo));
51045 var handle = vm.runtime.resolver.lookupPartial(name, meta);
51046 var definition = vm.runtime.resolver.resolve(handle);
51047 var {
51048 symbolTable,
51049 handle: vmHandle
51050 } = definition.getPartial(vm.context);
51051 {
51052 var partialSymbols = symbolTable.symbols;
51053 var outerScope = vm.scope();
51054 var partialScope = vm.pushRootScope(partialSymbols.length);
51055 var evalScope = outerScope.getEvalScope();
51056 partialScope.bindEvalScope(evalScope);
51057 partialScope.bindSelf(outerScope.getSelf());
51058 var locals = Object.create(outerScope.getPartialMap());
51059
51060 for (var i = 0; i < evalInfo.length; i++) {
51061 var slot = evalInfo[i];
51062 var _name5 = outerSymbols[slot - 1];
51063 var ref = outerScope.getSymbol(slot);
51064 locals[_name5] = ref;
51065 }
51066
51067 if (evalScope) {
51068 for (var _i6 = 0; _i6 < partialSymbols.length; _i6++) {
51069 var _name6 = partialSymbols[_i6];
51070 var symbol$$1 = _i6 + 1;
51071 var value = evalScope[_name6];
51072 if (value !== undefined) partialScope.bind(symbol$$1, value);
51073 }
51074 }
51075
51076 partialScope.bindPartialMap(locals);
51077 vm.pushFrame(); // sp += 2
51078
51079 vm.call((0, _util.unwrapHandle)(vmHandle));
51080 }
51081 }, 'jit');
51082 APPEND_OPCODES.add(74
51083 /* PutIterator */
51084 , vm => {
51085 var stack = vm.stack;
51086 var listRef = stack.popJs();
51087 var keyRef = stack.popJs();
51088 var keyValue = keyRef.value();
51089 var key = keyValue === null ? '@identity' : String(keyValue);
51090 var iterableRef = new _reference.IterableReference(listRef, key, vm.env); // Push the first time to push the iterator onto the stack for iteration
51091
51092 stack.pushJs(iterableRef); // Push the second time to push it as a reference for presence in general
51093 // (e.g whether or not it is empty). This reference will be used to skip
51094 // iteration entirely.
51095
51096 stack.pushJs(iterableRef);
51097 });
51098 APPEND_OPCODES.add(72
51099 /* EnterList */
51100 , (vm, {
51101 op1: relativeStart
51102 }) => {
51103 vm.enterList(relativeStart);
51104 });
51105 APPEND_OPCODES.add(73
51106 /* ExitList */
51107 , vm => {
51108 vm.exitList();
51109 });
51110 APPEND_OPCODES.add(75
51111 /* Iterate */
51112 , (vm, {
51113 op1: breaks
51114 }) => {
51115 var stack = vm.stack;
51116 var iterable = stack.peekJs();
51117 var item = iterable.next();
51118
51119 if (item) {
51120 var opcode = vm.enterItem(iterable, item);
51121 vm.registerItem(opcode);
51122 } else {
51123 vm.goto(breaks);
51124 }
51125 });
51126 /** @internal */
51127
51128 var DEFAULT_CAPABILITIES = {
51129 dynamicLayout: true,
51130 dynamicTag: true,
51131 prepareArgs: true,
51132 createArgs: true,
51133 attributeHook: false,
51134 elementHook: false,
51135 dynamicScope: true,
51136 createCaller: false,
51137 updateHook: true,
51138 createInstance: true,
51139 wrapped: false,
51140 willDestroy: false
51141 };
51142 _exports.DEFAULT_CAPABILITIES = DEFAULT_CAPABILITIES;
51143 var MINIMAL_CAPABILITIES = {
51144 dynamicLayout: false,
51145 dynamicTag: false,
51146 prepareArgs: false,
51147 createArgs: false,
51148 attributeHook: false,
51149 elementHook: false,
51150 dynamicScope: false,
51151 createCaller: false,
51152 updateHook: false,
51153 createInstance: false,
51154 wrapped: false,
51155 willDestroy: false
51156 };
51157 _exports.MINIMAL_CAPABILITIES = MINIMAL_CAPABILITIES;
51158
51159 class SimpleComponentManager {
51160 getCapabilities(_state) {
51161 return MINIMAL_CAPABILITIES;
51162 }
51163
51164 prepareArgs(_state, _args) {
51165 throw new Error(`Unimplemented prepareArgs in SimpleComponentManager`);
51166 }
51167
51168 create(_env, _state, _args, _dynamicScope, _caller, _hasDefaultBlock) {
51169 throw new Error(`Unimplemented create in SimpleComponentManager`);
51170 }
51171
51172 getSelf(_state) {
51173 return UNDEFINED_REFERENCE;
51174 }
51175
51176 getTag(_state) {
51177 throw new Error(`Unimplemented getTag in SimpleComponentManager`);
51178 }
51179
51180 didRenderLayout(_state, _bounds) {
51181 throw new Error(`Unimplemented didRenderLayout in SimpleComponentManager`);
51182 }
51183
51184 didCreate(_state) {
51185 throw new Error(`Unimplemented didCreate in SimpleComponentManager`);
51186 }
51187
51188 update(_state, _dynamicScope) {
51189 throw new Error(`Unimplemented update in SimpleComponentManager`);
51190 }
51191
51192 didUpdateLayout(_state, _bounds) {
51193 throw new Error(`Unimplemented didUpdateLayout in SimpleComponentManager`);
51194 }
51195
51196 didUpdate(_state) {
51197 throw new Error(`Unimplemented didUpdate in SimpleComponentManager`);
51198 }
51199
51200 getDestroyable(_state) {
51201 return null;
51202 }
51203
51204 }
51205
51206 _exports.SimpleComponentManager = SimpleComponentManager;
51207 var TEMPLATE_ONLY_COMPONENT = {
51208 state: null,
51209 manager: new SimpleComponentManager()
51210 };
51211 _exports.TEMPLATE_ONLY_COMPONENT = TEMPLATE_ONLY_COMPONENT;
51212
51213 class DefaultDynamicScope {
51214 constructor(bucket) {
51215 if (bucket) {
51216 this.bucket = (0, _util.assign)({}, bucket);
51217 } else {
51218 this.bucket = {};
51219 }
51220 }
51221
51222 get(key) {
51223 return this.bucket[key];
51224 }
51225
51226 set(key, reference) {
51227 return this.bucket[key] = reference;
51228 }
51229
51230 child() {
51231 return new DefaultDynamicScope(this.bucket);
51232 }
51233
51234 }
51235
51236 _exports.DefaultDynamicScope = DefaultDynamicScope;
51237
51238 class DynamicVarReference {
51239 constructor(scope, nameRef) {
51240 this.scope = scope;
51241 this.nameRef = nameRef;
51242 var varTag = this.varTag = (0, _validator.createUpdatableTag)();
51243 this.tag = (0, _validator.combine)([nameRef.tag, varTag]);
51244 }
51245
51246 value() {
51247 return this.getVar().value();
51248 }
51249
51250 get(key) {
51251 return this.getVar().get(key);
51252 }
51253
51254 getVar() {
51255 var name = String(this.nameRef.value());
51256 var ref = this.scope.get(name);
51257 (0, _validator.updateTag)(this.varTag, ref.tag);
51258 return ref;
51259 }
51260
51261 }
51262
51263 function getDynamicVar(args, vm) {
51264 var scope = vm.dynamicScope();
51265 var nameRef = args.positional.at(0);
51266 return new DynamicVarReference(scope, nameRef);
51267 }
51268 /*
51269 The calling convention is:
51270
51271 * 0-N block arguments at the bottom
51272 * 0-N positional arguments next (left-to-right)
51273 * 0-N named arguments next
51274 */
51275
51276
51277 class VMArgumentsImpl {
51278 constructor() {
51279 this.stack = null;
51280 this.positional = new PositionalArgumentsImpl();
51281 this.named = new NamedArgumentsImpl();
51282 this.blocks = new BlockArgumentsImpl();
51283 }
51284
51285 empty(stack) {
51286 var base = stack[REGISTERS][_vm2.$sp] + 1;
51287 this.named.empty(stack, base);
51288 this.positional.empty(stack, base);
51289 this.blocks.empty(stack, base);
51290 return this;
51291 }
51292
51293 setup(stack, names, blockNames, positionalCount, atNames) {
51294 this.stack = stack;
51295 /*
51296 | ... | blocks | positional | named |
51297 | ... | b0 b1 | p0 p1 p2 p3 | n0 n1 |
51298 index | ... | 4/5/6 7/8/9 | 10 11 12 13 | 14 15 |
51299 ^ ^ ^ ^
51300 bbase pbase nbase sp
51301 */
51302
51303 var named = this.named;
51304 var namedCount = names.length;
51305 var namedBase = stack[REGISTERS][_vm2.$sp] - namedCount + 1;
51306 named.setup(stack, namedBase, namedCount, names, atNames);
51307 var positional = this.positional;
51308 var positionalBase = namedBase - positionalCount;
51309 positional.setup(stack, positionalBase, positionalCount);
51310 var blocks = this.blocks;
51311 var blocksCount = blockNames.length;
51312 var blocksBase = positionalBase - blocksCount * 3;
51313 blocks.setup(stack, blocksBase, blocksCount, blockNames);
51314 }
51315
51316 get tag() {
51317 return combineTagged([this.positional, this.named]);
51318 }
51319
51320 get base() {
51321 return this.blocks.base;
51322 }
51323
51324 get length() {
51325 return this.positional.length + this.named.length + this.blocks.length * 3;
51326 }
51327
51328 at(pos) {
51329 return this.positional.at(pos);
51330 }
51331
51332 realloc(offset) {
51333 var {
51334 stack
51335 } = this;
51336
51337 if (offset > 0 && stack !== null) {
51338 var {
51339 positional,
51340 named
51341 } = this;
51342 var newBase = positional.base + offset;
51343 var length = positional.length + named.length;
51344
51345 for (var i = length - 1; i >= 0; i--) {
51346 stack.copy(i + positional.base, i + newBase);
51347 }
51348
51349 positional.base += offset;
51350 named.base += offset;
51351 stack[REGISTERS][_vm2.$sp] += offset;
51352 }
51353 }
51354
51355 capture() {
51356 var positional = this.positional.length === 0 ? EMPTY_POSITIONAL : this.positional.capture();
51357 var named = this.named.length === 0 ? EMPTY_NAMED : this.named.capture();
51358 return new CapturedArgumentsImpl(this.tag, positional, named, this.length);
51359 }
51360
51361 clear() {
51362 var {
51363 stack,
51364 length
51365 } = this;
51366 if (length > 0 && stack !== null) stack.pop(length);
51367 }
51368
51369 }
51370
51371 class PositionalArgumentsImpl {
51372 constructor() {
51373 this.base = 0;
51374 this.length = 0;
51375 this.stack = null;
51376 this._tag = null;
51377 this._references = null;
51378 }
51379
51380 empty(stack, base) {
51381 this.stack = stack;
51382 this.base = base;
51383 this.length = 0;
51384 this._tag = _validator.CONSTANT_TAG;
51385 this._references = _util.EMPTY_ARRAY;
51386 }
51387
51388 setup(stack, base, length) {
51389 this.stack = stack;
51390 this.base = base;
51391 this.length = length;
51392
51393 if (length === 0) {
51394 this._tag = _validator.CONSTANT_TAG;
51395 this._references = _util.EMPTY_ARRAY;
51396 } else {
51397 this._tag = null;
51398 this._references = null;
51399 }
51400 }
51401
51402 get tag() {
51403 var tag = this._tag;
51404
51405 if (!tag) {
51406 tag = this._tag = combineTagged(this.references);
51407 }
51408
51409 return tag;
51410 }
51411
51412 at(position) {
51413 var {
51414 base,
51415 length,
51416 stack
51417 } = this;
51418
51419 if (position < 0 || position >= length) {
51420 return UNDEFINED_REFERENCE;
51421 }
51422
51423 return stack.get(position, base);
51424 }
51425
51426 capture() {
51427 return new CapturedPositionalArgumentsImpl(this.tag, this.references);
51428 }
51429
51430 prepend(other) {
51431 var additions = other.length;
51432
51433 if (additions > 0) {
51434 var {
51435 base,
51436 length,
51437 stack
51438 } = this;
51439 this.base = base = base - additions;
51440 this.length = length + additions;
51441
51442 for (var i = 0; i < additions; i++) {
51443 stack.set(other.at(i), i, base);
51444 }
51445
51446 this._tag = null;
51447 this._references = null;
51448 }
51449 }
51450
51451 get references() {
51452 var references = this._references;
51453
51454 if (!references) {
51455 var {
51456 stack,
51457 base,
51458 length
51459 } = this;
51460 references = this._references = stack.slice(base, base + length);
51461 }
51462
51463 return references;
51464 }
51465
51466 }
51467
51468 class CapturedPositionalArgumentsImpl {
51469 constructor(tag, references, length = references.length) {
51470 this.tag = tag;
51471 this.references = references;
51472 this.length = length;
51473 }
51474
51475 static empty() {
51476 return new CapturedPositionalArgumentsImpl(_validator.CONSTANT_TAG, _util.EMPTY_ARRAY, 0);
51477 }
51478
51479 at(position) {
51480 return this.references[position];
51481 }
51482
51483 value() {
51484 return this.references.map(this.valueOf);
51485 }
51486
51487 get(name) {
51488 var {
51489 references,
51490 length
51491 } = this;
51492
51493 if (name === 'length') {
51494 return PrimitiveReference.create(length);
51495 } else {
51496 var idx = parseInt(name, 10);
51497
51498 if (idx < 0 || idx >= length) {
51499 return UNDEFINED_REFERENCE;
51500 } else {
51501 return references[idx];
51502 }
51503 }
51504 }
51505
51506 valueOf(reference) {
51507 return reference.value();
51508 }
51509
51510 }
51511
51512 _exports.CapturedPositionalArgumentsImpl = CapturedPositionalArgumentsImpl;
51513
51514 class NamedArgumentsImpl {
51515 constructor() {
51516 this.base = 0;
51517 this.length = 0;
51518 this._references = null;
51519 this._names = _util.EMPTY_ARRAY;
51520 this._atNames = _util.EMPTY_ARRAY;
51521 }
51522
51523 empty(stack, base) {
51524 this.stack = stack;
51525 this.base = base;
51526 this.length = 0;
51527 this._references = _util.EMPTY_ARRAY;
51528 this._names = _util.EMPTY_ARRAY;
51529 this._atNames = _util.EMPTY_ARRAY;
51530 }
51531
51532 setup(stack, base, length, names, atNames) {
51533 this.stack = stack;
51534 this.base = base;
51535 this.length = length;
51536
51537 if (length === 0) {
51538 this._references = _util.EMPTY_ARRAY;
51539 this._names = _util.EMPTY_ARRAY;
51540 this._atNames = _util.EMPTY_ARRAY;
51541 } else {
51542 this._references = null;
51543
51544 if (atNames) {
51545 this._names = null;
51546 this._atNames = names;
51547 } else {
51548 this._names = names;
51549 this._atNames = null;
51550 }
51551 }
51552 }
51553
51554 get tag() {
51555 return combineTagged(this.references);
51556 }
51557
51558 get names() {
51559 var names = this._names;
51560
51561 if (!names) {
51562 names = this._names = this._atNames.map(this.toSyntheticName);
51563 }
51564
51565 return names;
51566 }
51567
51568 get atNames() {
51569 var atNames = this._atNames;
51570
51571 if (!atNames) {
51572 atNames = this._atNames = this._names.map(this.toAtName);
51573 }
51574
51575 return atNames;
51576 }
51577
51578 has(name) {
51579 return this.names.indexOf(name) !== -1;
51580 }
51581
51582 get(name, atNames = false) {
51583 var {
51584 base,
51585 stack
51586 } = this;
51587 var names = atNames ? this.atNames : this.names;
51588 var idx = names.indexOf(name);
51589
51590 if (idx === -1) {
51591 return UNDEFINED_REFERENCE;
51592 }
51593
51594 return stack.get(idx, base);
51595 }
51596
51597 capture() {
51598 return new CapturedNamedArgumentsImpl(this.tag, this.names, this.references);
51599 }
51600
51601 merge(other) {
51602 var {
51603 length: extras
51604 } = other;
51605
51606 if (extras > 0) {
51607 var {
51608 names,
51609 length,
51610 stack
51611 } = this;
51612 var {
51613 names: extraNames
51614 } = other;
51615 var newNames = names.slice();
51616
51617 for (var i = 0; i < extras; i++) {
51618 var _name7 = extraNames[i];
51619 var idx = newNames.indexOf(_name7);
51620
51621 if (idx === -1) {
51622 length = newNames.push(_name7);
51623 stack.pushJs(other.references[i]);
51624 }
51625 }
51626
51627 this.length = length;
51628 this._references = null;
51629 this._names = newNames;
51630 this._atNames = null;
51631 }
51632 }
51633
51634 get references() {
51635 var references = this._references;
51636
51637 if (!references) {
51638 var {
51639 base,
51640 length,
51641 stack
51642 } = this;
51643 references = this._references = stack.slice(base, base + length);
51644 }
51645
51646 return references;
51647 }
51648
51649 toSyntheticName(name) {
51650 return name.slice(1);
51651 }
51652
51653 toAtName(name) {
51654 return `@${name}`;
51655 }
51656
51657 }
51658
51659 class CapturedNamedArgumentsImpl {
51660 constructor(tag, names, references) {
51661 this.tag = tag;
51662 this.names = names;
51663 this.references = references;
51664 this.length = names.length;
51665 this._map = null;
51666 }
51667
51668 get map() {
51669 var map = this._map;
51670
51671 if (!map) {
51672 var {
51673 names,
51674 references
51675 } = this;
51676 map = this._map = (0, _util.dict)();
51677
51678 for (var i = 0; i < names.length; i++) {
51679 var _name8 = names[i];
51680 map[_name8] = references[i];
51681 }
51682 }
51683
51684 return map;
51685 }
51686
51687 has(name) {
51688 return this.names.indexOf(name) !== -1;
51689 }
51690
51691 get(name) {
51692 var {
51693 names,
51694 references
51695 } = this;
51696 var idx = names.indexOf(name);
51697
51698 if (idx === -1) {
51699 return UNDEFINED_REFERENCE;
51700 } else {
51701 return references[idx];
51702 }
51703 }
51704
51705 value() {
51706 var {
51707 names,
51708 references
51709 } = this;
51710 var out = (0, _util.dict)();
51711
51712 for (var i = 0; i < names.length; i++) {
51713 var _name9 = names[i];
51714 out[_name9] = references[i].value();
51715 }
51716
51717 return out;
51718 }
51719
51720 }
51721
51722 _exports.CapturedNamedArgumentsImpl = CapturedNamedArgumentsImpl;
51723
51724 function toSymbolName(name) {
51725 return `&${name}`;
51726 }
51727
51728 class BlockArgumentsImpl {
51729 constructor() {
51730 this.internalValues = null;
51731 this._symbolNames = null;
51732 this.internalTag = null;
51733 this.names = _util.EMPTY_ARRAY;
51734 this.length = 0;
51735 this.base = 0;
51736 }
51737
51738 empty(stack, base) {
51739 this.stack = stack;
51740 this.names = _util.EMPTY_ARRAY;
51741 this.base = base;
51742 this.length = 0;
51743 this._symbolNames = null;
51744 this.internalTag = _validator.CONSTANT_TAG;
51745 this.internalValues = _util.EMPTY_ARRAY;
51746 }
51747
51748 setup(stack, base, length, names) {
51749 this.stack = stack;
51750 this.names = names;
51751 this.base = base;
51752 this.length = length;
51753 this._symbolNames = null;
51754
51755 if (length === 0) {
51756 this.internalTag = _validator.CONSTANT_TAG;
51757 this.internalValues = _util.EMPTY_ARRAY;
51758 } else {
51759 this.internalTag = null;
51760 this.internalValues = null;
51761 }
51762 }
51763
51764 get values() {
51765 var values = this.internalValues;
51766
51767 if (!values) {
51768 var {
51769 base,
51770 length,
51771 stack
51772 } = this;
51773 values = this.internalValues = stack.slice(base, base + length * 3);
51774 }
51775
51776 return values;
51777 }
51778
51779 has(name) {
51780 return this.names.indexOf(name) !== -1;
51781 }
51782
51783 get(name) {
51784 var idx = this.names.indexOf(name);
51785
51786 if (idx === -1) {
51787 return null;
51788 }
51789
51790 var {
51791 base,
51792 stack
51793 } = this;
51794 var table = stack.get(idx * 3, base);
51795 var scope = stack.get(idx * 3 + 1, base);
51796 var handle = stack.get(idx * 3 + 2, base);
51797 return handle === null ? null : [handle, scope, table];
51798 }
51799
51800 capture() {
51801 return new CapturedBlockArgumentsImpl(this.names, this.values);
51802 }
51803
51804 get symbolNames() {
51805 var symbolNames = this._symbolNames;
51806
51807 if (symbolNames === null) {
51808 symbolNames = this._symbolNames = this.names.map(toSymbolName);
51809 }
51810
51811 return symbolNames;
51812 }
51813
51814 }
51815
51816 class CapturedBlockArgumentsImpl {
51817 constructor(names, values) {
51818 this.names = names;
51819 this.values = values;
51820 this.length = names.length;
51821 }
51822
51823 has(name) {
51824 return this.names.indexOf(name) !== -1;
51825 }
51826
51827 get(name) {
51828 var idx = this.names.indexOf(name);
51829 if (idx === -1) return null;
51830 return [this.values[idx * 3 + 2], this.values[idx * 3 + 1], this.values[idx * 3]];
51831 }
51832
51833 }
51834
51835 class CapturedArgumentsImpl {
51836 constructor(tag, positional, named, length) {
51837 this.tag = tag;
51838 this.positional = positional;
51839 this.named = named;
51840 this.length = length;
51841 }
51842
51843 value() {
51844 return {
51845 named: this.named.value(),
51846 positional: this.positional.value()
51847 };
51848 }
51849
51850 }
51851
51852 _exports.CapturedArgumentsImpl = CapturedArgumentsImpl;
51853 var EMPTY_NAMED = new CapturedNamedArgumentsImpl(_validator.CONSTANT_TAG, _util.EMPTY_ARRAY, _util.EMPTY_ARRAY);
51854 var EMPTY_POSITIONAL = new CapturedPositionalArgumentsImpl(_validator.CONSTANT_TAG, _util.EMPTY_ARRAY);
51855 var EMPTY_ARGS = new CapturedArgumentsImpl(_validator.CONSTANT_TAG, EMPTY_POSITIONAL, EMPTY_NAMED, 0);
51856 _exports.EMPTY_ARGS = EMPTY_ARGS;
51857
51858 function initializeRegistersWithSP(sp) {
51859 return [0, -1, sp, 0];
51860 }
51861
51862 class LowLevelVM {
51863 constructor(stack, heap, program, externs, registers) {
51864 this.stack = stack;
51865 this.heap = heap;
51866 this.program = program;
51867 this.externs = externs;
51868 this.registers = registers;
51869 this.currentOpSize = 0;
51870 }
51871
51872 fetchRegister(register) {
51873 return this.registers[register];
51874 }
51875
51876 loadRegister(register, value) {
51877 this.registers[register] = value;
51878 }
51879
51880 setPc(pc) {
51881 this.registers[_vm2.$pc] = pc;
51882 } // Start a new frame and save $ra and $fp on the stack
51883
51884
51885 pushFrame() {
51886 this.stack.pushSmallInt(this.registers[_vm2.$ra]);
51887 this.stack.pushSmallInt(this.registers[_vm2.$fp]);
51888 this.registers[_vm2.$fp] = this.registers[_vm2.$sp] - 1;
51889 } // Restore $ra, $sp and $fp
51890
51891
51892 popFrame() {
51893 this.registers[_vm2.$sp] = this.registers[_vm2.$fp] - 1;
51894 this.registers[_vm2.$ra] = this.stack.get(0);
51895 this.registers[_vm2.$fp] = this.stack.get(1);
51896 }
51897
51898 pushSmallFrame() {
51899 this.stack.pushSmallInt(this.registers[_vm2.$ra]);
51900 }
51901
51902 popSmallFrame() {
51903 this.registers[_vm2.$ra] = this.stack.popSmallInt();
51904 } // Jump to an address in `program`
51905
51906
51907 goto(offset) {
51908 this.setPc(this.target(offset));
51909 }
51910
51911 target(offset) {
51912 return this.registers[_vm2.$pc] + offset - this.currentOpSize;
51913 } // Save $pc into $ra, then jump to a new address in `program` (jal in MIPS)
51914
51915
51916 call(handle) {
51917 this.registers[_vm2.$ra] = this.registers[_vm2.$pc];
51918 this.setPc(this.heap.getaddr(handle));
51919 } // Put a specific `program` address in $ra
51920
51921
51922 returnTo(offset) {
51923 this.registers[_vm2.$ra] = this.target(offset);
51924 } // Return to the `program` address stored in $ra
51925
51926
51927 return() {
51928 this.setPc(this.registers[_vm2.$ra]);
51929 }
51930
51931 nextStatement() {
51932 var {
51933 registers,
51934 program
51935 } = this;
51936 var pc = registers[_vm2.$pc];
51937
51938 if (pc === -1) {
51939 return null;
51940 } // We have to save off the current operations size so that
51941 // when we do a jump we can calculate the correct offset
51942 // to where we are going. We can't simply ask for the size
51943 // in a jump because we have have already incremented the
51944 // program counter to the next instruction prior to executing.
51945
51946
51947 var opcode = program.opcode(pc);
51948 var operationSize = this.currentOpSize = opcode.size;
51949 this.registers[_vm2.$pc] += operationSize;
51950 return opcode;
51951 }
51952
51953 evaluateOuter(opcode, vm) {
51954 {
51955 this.evaluateInner(opcode, vm);
51956 }
51957 }
51958
51959 evaluateInner(opcode, vm) {
51960 if (opcode.isMachine) {
51961 this.evaluateMachine(opcode);
51962 } else {
51963 this.evaluateSyscall(opcode, vm);
51964 }
51965 }
51966
51967 evaluateMachine(opcode) {
51968 switch (opcode.type) {
51969 case 0
51970 /* PushFrame */
51971 :
51972 return this.pushFrame();
51973
51974 case 1
51975 /* PopFrame */
51976 :
51977 return this.popFrame();
51978
51979 case 3
51980 /* InvokeStatic */
51981 :
51982 return this.call(opcode.op1);
51983
51984 case 2
51985 /* InvokeVirtual */
51986 :
51987 return this.call(this.stack.popSmallInt());
51988
51989 case 4
51990 /* Jump */
51991 :
51992 return this.goto(opcode.op1);
51993
51994 case 5
51995 /* Return */
51996 :
51997 return this.return();
51998
51999 case 6
52000 /* ReturnTo */
52001 :
52002 return this.returnTo(opcode.op1);
52003 }
52004 }
52005
52006 evaluateSyscall(opcode, vm) {
52007 APPEND_OPCODES.evaluate(vm, opcode, opcode.type);
52008 }
52009
52010 }
52011
52012 class UpdatingVM {
52013 constructor(env, {
52014 alwaysRevalidate = false
52015 }) {
52016 this.frameStack = new _util.Stack();
52017 this.env = env;
52018 this.dom = env.getDOM();
52019 this.alwaysRevalidate = alwaysRevalidate;
52020 }
52021
52022 execute(opcodes, handler) {
52023 var {
52024 frameStack
52025 } = this;
52026 this.try(opcodes, handler);
52027
52028 while (true) {
52029 if (frameStack.isEmpty()) break;
52030 var opcode = this.frame.nextStatement();
52031
52032 if (opcode === undefined) {
52033 frameStack.pop();
52034 continue;
52035 }
52036
52037 opcode.evaluate(this);
52038 }
52039 }
52040
52041 get frame() {
52042 return this.frameStack.current;
52043 }
52044
52045 goto(index) {
52046 this.frame.goto(index);
52047 }
52048
52049 try(ops, handler) {
52050 this.frameStack.push(new UpdatingVMFrame(ops, handler));
52051 }
52052
52053 throw() {
52054 this.frame.handleException();
52055 this.frameStack.pop();
52056 }
52057
52058 }
52059
52060 _exports.UpdatingVM = UpdatingVM;
52061
52062 class ResumableVMStateImpl {
52063 constructor(state, resumeCallback) {
52064 this.state = state;
52065 this.resumeCallback = resumeCallback;
52066 }
52067
52068 resume(runtime, builder) {
52069 return this.resumeCallback(runtime, this.state, builder);
52070 }
52071
52072 }
52073
52074 class BlockOpcode extends UpdatingOpcode {
52075 constructor(state, runtime, bounds, children) {
52076 super();
52077 this.state = state;
52078 this.runtime = runtime;
52079 this.type = 'block';
52080 this.children = children;
52081 this.bounds = bounds;
52082 }
52083
52084 parentElement() {
52085 return this.bounds.parentElement();
52086 }
52087
52088 firstNode() {
52089 return this.bounds.firstNode();
52090 }
52091
52092 lastNode() {
52093 return this.bounds.lastNode();
52094 }
52095
52096 evaluate(vm) {
52097 vm.try(this.children, null);
52098 }
52099
52100 }
52101
52102 class TryOpcode extends BlockOpcode {
52103 constructor(state, runtime, bounds, children) {
52104 super(state, runtime, bounds, children);
52105 this.type = 'try';
52106 this.tag = this._tag = (0, _validator.createUpdatableTag)();
52107 }
52108
52109 didInitializeChildren() {
52110 (0, _validator.updateTag)(this._tag, combineTagged(this.children));
52111 }
52112
52113 evaluate(vm) {
52114 vm.try(this.children, this);
52115 }
52116
52117 handleException() {
52118 var {
52119 state,
52120 bounds,
52121 runtime
52122 } = this;
52123 destroyChildren(this);
52124 var elementStack = NewElementBuilder.resume(runtime.env, bounds);
52125 var vm = state.resume(runtime, elementStack);
52126 var updating = [];
52127 var children = this.children = [];
52128 var result = vm.execute(vm => {
52129 vm.pushUpdating(updating);
52130 vm.updateWith(this);
52131 vm.pushUpdating(children);
52132 });
52133 associateDestroyableChild(this, result.drop);
52134 }
52135
52136 }
52137
52138 class ListItemOpcode extends TryOpcode {
52139 constructor(state, runtime, bounds, key, memo, value) {
52140 super(state, runtime, bounds, []);
52141 this.key = key;
52142 this.memo = memo;
52143 this.value = value;
52144 this.retained = false;
52145 this.index = -1;
52146 }
52147
52148 updateReferences(item) {
52149 this.retained = true;
52150 this.value.update(item.value);
52151 this.memo.update(item.memo);
52152 }
52153
52154 shouldRemove() {
52155 return !this.retained;
52156 }
52157
52158 reset() {
52159 this.retained = false;
52160 }
52161
52162 }
52163
52164 class ListBlockOpcode extends BlockOpcode {
52165 constructor(state, runtime, bounds, children, iterableRef) {
52166 super(state, runtime, bounds, children);
52167 this.iterableRef = iterableRef;
52168 this.type = 'list-block';
52169 this.lastIterated = _validator.INITIAL;
52170 this.opcodeMap = new Map();
52171 this.marker = null;
52172
52173 var _tag = this._tag = (0, _validator.createUpdatableTag)();
52174
52175 this.tag = (0, _validator.combine)([iterableRef.tag, _tag]);
52176 }
52177
52178 initializeChild(opcode) {
52179 opcode.index = this.children.length - 1;
52180 this.opcodeMap.set(opcode.key, opcode);
52181 }
52182
52183 didInitializeChildren() {
52184 this.lastIterated = (0, _validator.valueForTag)(this.tag);
52185 (0, _validator.updateTag)(this._tag, combineTagged(this.children));
52186 }
52187
52188 evaluate(vm) {
52189 var {
52190 iterableRef,
52191 lastIterated
52192 } = this;
52193
52194 if (!(0, _validator.validateTag)(iterableRef.tag, lastIterated)) {
52195 var {
52196 bounds
52197 } = this;
52198 var {
52199 dom
52200 } = vm;
52201 var marker = this.marker = dom.createComment('');
52202 dom.insertAfter(bounds.parentElement(), marker, bounds.lastNode());
52203 var didChange = this.sync();
52204 this.parentElement().removeChild(marker);
52205 this.marker = null;
52206
52207 if (didChange) {
52208 (0, _validator.updateTag)(this._tag, combineTagged(this.children));
52209 }
52210
52211 this.lastIterated = (0, _validator.valueForTag)(this.iterableRef.tag);
52212 } // Run now-updated updating opcodes
52213
52214
52215 super.evaluate(vm);
52216 }
52217
52218 sync() {
52219 var {
52220 iterableRef,
52221 opcodeMap: itemMap,
52222 children
52223 } = this;
52224 var currentOpcodeIndex = 0;
52225 var seenIndex = 0;
52226 var didChange = false;
52227 this.children = this.bounds.boundList = [];
52228
52229 while (true) {
52230 var item = iterableRef.next();
52231 if (item === null) break;
52232 var opcode = children[currentOpcodeIndex];
52233 var {
52234 key
52235 } = item; // Items that have already been found and moved will already be retained,
52236 // we can continue until we find the next unretained item
52237
52238 while (opcode !== undefined && opcode.retained === true) {
52239 opcode = children[++currentOpcodeIndex];
52240 }
52241
52242 if (opcode !== undefined && opcode.key === key) {
52243 this.retainItem(opcode, item);
52244 currentOpcodeIndex++;
52245 } else if (itemMap.has(key)) {
52246 var itemOpcode = itemMap.get(key); // The item opcode was seen already, so we should move it.
52247
52248 if (itemOpcode.index < seenIndex) {
52249 this.moveItem(itemOpcode, item, opcode);
52250 } else {
52251 // Update the seen index, we are going to be moving this item around
52252 // so any other items that come before it will likely need to move as
52253 // well.
52254 seenIndex = itemOpcode.index;
52255 var seenUnretained = false; // iterate through all of the opcodes between the current position and
52256 // the position of the item's opcode, and determine if they are all
52257 // retained.
52258
52259 for (var i = currentOpcodeIndex + 1; i < seenIndex; i++) {
52260 if (children[i].retained === false) {
52261 seenUnretained = true;
52262 break;
52263 }
52264 } // If we have seen only retained opcodes between this and the matching
52265 // opcode, it means that all the opcodes in between have been moved
52266 // already, and we can safely retain this item's opcode.
52267
52268
52269 if (seenUnretained === false) {
52270 this.retainItem(itemOpcode, item);
52271 currentOpcodeIndex = seenIndex + 1;
52272 } else {
52273 this.moveItem(itemOpcode, item, opcode);
52274 currentOpcodeIndex++;
52275 }
52276 }
52277 } else {
52278 didChange = true;
52279 this.insertItem(item, opcode);
52280 }
52281 }
52282
52283 for (var _i7 = 0; _i7 < children.length; _i7++) {
52284 var _opcode = children[_i7];
52285
52286 if (_opcode.retained === false) {
52287 didChange = true;
52288 this.deleteItem(_opcode);
52289 } else {
52290 _opcode.reset();
52291 }
52292 }
52293
52294 return didChange;
52295 }
52296
52297 retainItem(opcode, item) {
52298 var {
52299 children
52300 } = this;
52301 opcode.memo.update(item.memo);
52302 opcode.value.update(item.value);
52303 opcode.retained = true;
52304 opcode.index = children.length;
52305 children.push(opcode);
52306 }
52307
52308 insertItem(item, before) {
52309 var {
52310 opcodeMap,
52311 bounds,
52312 state,
52313 runtime,
52314 iterableRef,
52315 children
52316 } = this;
52317 var {
52318 key
52319 } = item;
52320 var nextSibling = before === undefined ? this.marker : before.firstNode();
52321 var elementStack = NewElementBuilder.forInitialRender(runtime.env, {
52322 element: bounds.parentElement(),
52323 nextSibling
52324 });
52325 var vm = state.resume(runtime, elementStack);
52326 vm.execute(vm => {
52327 vm.pushUpdating();
52328 var opcode = vm.enterItem(iterableRef, item);
52329 opcode.index = children.length;
52330 children.push(opcode);
52331 opcodeMap.set(key, opcode);
52332 associateDestroyableChild(this, opcode);
52333 });
52334 }
52335
52336 moveItem(opcode, item, before) {
52337 var {
52338 children
52339 } = this;
52340 opcode.memo.update(item.memo);
52341 opcode.value.update(item.value);
52342 opcode.retained = true;
52343 var currentSibling, nextSibling;
52344
52345 if (before === undefined) {
52346 move(opcode, this.marker);
52347 } else {
52348 currentSibling = opcode.lastNode().nextSibling;
52349 nextSibling = before.firstNode(); // Items are moved throughout the algorithm, so there are cases where the
52350 // the items already happen to be siblings (e.g. an item in between was
52351 // moved before this move happened). Check to see if they are siblings
52352 // first before doing the move.
52353
52354 if (currentSibling !== nextSibling) {
52355 move(opcode, nextSibling);
52356 }
52357 }
52358
52359 opcode.index = children.length;
52360 children.push(opcode);
52361 }
52362
52363 deleteItem(opcode) {
52364 destroy(opcode);
52365 clear(opcode);
52366 this.opcodeMap.delete(opcode.key);
52367 }
52368
52369 }
52370
52371 class UpdatingVMFrame {
52372 constructor(ops, exceptionHandler) {
52373 this.ops = ops;
52374 this.exceptionHandler = exceptionHandler;
52375 this.current = 0;
52376 }
52377
52378 goto(index) {
52379 this.current = index;
52380 }
52381
52382 nextStatement() {
52383 return this.ops[this.current++];
52384 }
52385
52386 handleException() {
52387 if (this.exceptionHandler) {
52388 this.exceptionHandler.handleException();
52389 }
52390 }
52391
52392 }
52393
52394 class RenderResultImpl {
52395 constructor(env, updating, bounds, drop) {
52396 this.env = env;
52397 this.updating = updating;
52398 this.bounds = bounds;
52399 this.drop = drop;
52400 associateDestroyableChild(this, drop);
52401 registerDestructor(this, () => clear(this.bounds));
52402 }
52403
52404 rerender({
52405 alwaysRevalidate = false
52406 } = {
52407 alwaysRevalidate: false
52408 }) {
52409 var {
52410 env,
52411 updating
52412 } = this;
52413 var vm = new UpdatingVM(env, {
52414 alwaysRevalidate
52415 });
52416 vm.execute(updating, this);
52417 }
52418
52419 parentElement() {
52420 return this.bounds.parentElement();
52421 }
52422
52423 firstNode() {
52424 return this.bounds.firstNode();
52425 }
52426
52427 lastNode() {
52428 return this.bounds.lastNode();
52429 }
52430
52431 handleException() {
52432 throw 'this should never happen';
52433 }
52434
52435 }
52436
52437 class InnerStack {
52438 constructor(inner = new _lowLevel.Stack(), js) {
52439 this.inner = inner;
52440 this.js = (0, _util.constants)();
52441
52442 if (js !== undefined) {
52443 this.js = this.js.concat(js);
52444 }
52445 }
52446
52447 slice(start, end) {
52448 var out = [];
52449
52450 if (start === -1) {
52451 return out;
52452 }
52453
52454 for (var i = start; i < end; i++) {
52455 out.push(this.get(i));
52456 }
52457
52458 return out;
52459 }
52460
52461 copy(from, to) {
52462 this.inner.copy(from, to);
52463 }
52464
52465 writeJs(pos, value) {
52466 var idx = this.js.length;
52467 this.js.push(value);
52468 this.inner.writeRaw(pos, (0, _util.encodeHandle)(idx));
52469 }
52470
52471 writeSmallInt(pos, value) {
52472 this.inner.writeRaw(pos, (0, _util.encodeImmediate)(value));
52473 }
52474
52475 writeTrue(pos) {
52476 this.inner.writeRaw(pos, 1
52477 /* ENCODED_TRUE_HANDLE */
52478 );
52479 }
52480
52481 writeFalse(pos) {
52482 this.inner.writeRaw(pos, 0
52483 /* ENCODED_FALSE_HANDLE */
52484 );
52485 }
52486
52487 writeNull(pos) {
52488 this.inner.writeRaw(pos, 2
52489 /* ENCODED_NULL_HANDLE */
52490 );
52491 }
52492
52493 writeUndefined(pos) {
52494 this.inner.writeRaw(pos, 3
52495 /* ENCODED_UNDEFINED_HANDLE */
52496 );
52497 }
52498
52499 writeRaw(pos, value) {
52500 this.inner.writeRaw(pos, value);
52501 }
52502
52503 getJs(pos) {
52504 var value = this.inner.getRaw(pos);
52505 return this.js[(0, _util.decodeHandle)(value)];
52506 }
52507
52508 getSmallInt(pos) {
52509 var value = this.inner.getRaw(pos);
52510 return (0, _util.decodeImmediate)(value);
52511 }
52512
52513 get(pos) {
52514 var value = this.inner.getRaw(pos) | 0;
52515
52516 if ((0, _util.isHandle)(value)) {
52517 return this.js[(0, _util.decodeHandle)(value)];
52518 } else {
52519 return (0, _util.decodeImmediate)(value);
52520 }
52521 }
52522
52523 reset() {
52524 this.inner.reset();
52525 this.js.length = 0;
52526 }
52527
52528 get length() {
52529 return this.inner.len();
52530 }
52531
52532 }
52533
52534 class EvaluationStackImpl {
52535 // fp -> sp
52536 constructor(stack, registers) {
52537 this.stack = stack;
52538 this[REGISTERS] = registers;
52539 }
52540
52541 static restore(snapshot) {
52542 var stack = new InnerStack();
52543
52544 for (var i = 0; i < snapshot.length; i++) {
52545 var value = snapshot[i];
52546
52547 if (typeof value === 'number' && (0, _util.isSmallInt)(value)) {
52548 stack.writeRaw(i, (0, _util.encodeImmediate)(value));
52549 } else if (value === true) {
52550 stack.writeTrue(i);
52551 } else if (value === false) {
52552 stack.writeFalse(i);
52553 } else if (value === null) {
52554 stack.writeNull(i);
52555 } else if (value === undefined) {
52556 stack.writeUndefined(i);
52557 } else {
52558 stack.writeJs(i, value);
52559 }
52560 }
52561
52562 return new this(stack, initializeRegistersWithSP(snapshot.length - 1));
52563 }
52564
52565 pushJs(value) {
52566 this.stack.writeJs(++this[REGISTERS][_vm2.$sp], value);
52567 }
52568
52569 pushSmallInt(value) {
52570 this.stack.writeSmallInt(++this[REGISTERS][_vm2.$sp], value);
52571 }
52572
52573 pushTrue() {
52574 this.stack.writeTrue(++this[REGISTERS][_vm2.$sp]);
52575 }
52576
52577 pushFalse() {
52578 this.stack.writeFalse(++this[REGISTERS][_vm2.$sp]);
52579 }
52580
52581 pushNull() {
52582 this.stack.writeNull(++this[REGISTERS][_vm2.$sp]);
52583 }
52584
52585 pushUndefined() {
52586 this.stack.writeUndefined(++this[REGISTERS][_vm2.$sp]);
52587 }
52588
52589 pushRaw(value) {
52590 this.stack.writeRaw(++this[REGISTERS][_vm2.$sp], value);
52591 }
52592
52593 dup(position = this[REGISTERS][_vm2.$sp]) {
52594 this.stack.copy(position, ++this[REGISTERS][_vm2.$sp]);
52595 }
52596
52597 copy(from, to) {
52598 this.stack.copy(from, to);
52599 }
52600
52601 popJs(n = 1) {
52602 var top = this.stack.getJs(this[REGISTERS][_vm2.$sp]);
52603 this[REGISTERS][_vm2.$sp] -= n;
52604 return top;
52605 }
52606
52607 popSmallInt(n = 1) {
52608 var top = this.stack.getSmallInt(this[REGISTERS][_vm2.$sp]);
52609 this[REGISTERS][_vm2.$sp] -= n;
52610 return top;
52611 }
52612
52613 pop(n = 1) {
52614 var top = this.stack.get(this[REGISTERS][_vm2.$sp]);
52615 this[REGISTERS][_vm2.$sp] -= n;
52616 return top;
52617 }
52618
52619 peekJs(offset = 0) {
52620 return this.stack.getJs(this[REGISTERS][_vm2.$sp] - offset);
52621 }
52622
52623 peekSmallInt(offset = 0) {
52624 return this.stack.getSmallInt(this[REGISTERS][_vm2.$sp] - offset);
52625 }
52626
52627 peek(offset = 0) {
52628 return this.stack.get(this[REGISTERS][_vm2.$sp] - offset);
52629 }
52630
52631 get(offset, base = this[REGISTERS][_vm2.$fp]) {
52632 return this.stack.get(base + offset);
52633 }
52634
52635 set(value, offset, base = this[REGISTERS][_vm2.$fp]) {
52636 this.stack.writeJs(base + offset, value);
52637 }
52638
52639 slice(start, end) {
52640 return this.stack.slice(start, end);
52641 }
52642
52643 capture(items) {
52644 var end = this[REGISTERS][_vm2.$sp] + 1;
52645 var start = end - items;
52646 return this.stack.slice(start, end);
52647 }
52648
52649 reset() {
52650 this.stack.reset();
52651 }
52652
52653 toArray() {
52654 console.log(this[REGISTERS]);
52655 return this.stack.slice(this[REGISTERS][_vm2.$fp], this[REGISTERS][_vm2.$sp] + 1);
52656 }
52657
52658 }
52659
52660 var _a$3, _b;
52661
52662 class Stacks {
52663 constructor() {
52664 this.scope = new _util.Stack();
52665 this.dynamicScope = new _util.Stack();
52666 this.updating = new _util.Stack();
52667 this.cache = new _util.Stack();
52668 this.list = new _util.Stack();
52669 }
52670
52671 }
52672
52673 class VM {
52674 /**
52675 * End of migrated.
52676 */
52677 constructor(runtime, {
52678 pc,
52679 scope,
52680 dynamicScope,
52681 stack
52682 }, elementStack) {
52683 this.runtime = runtime;
52684 this.elementStack = elementStack;
52685 this[_a$3] = new Stacks();
52686 this[_b] = new _util.Stack();
52687 this.s0 = null;
52688 this.s1 = null;
52689 this.t0 = null;
52690 this.t1 = null;
52691 this.v0 = null;
52692 var evalStack = EvaluationStackImpl.restore(stack);
52693 evalStack[REGISTERS][_vm2.$pc] = pc;
52694 evalStack[REGISTERS][_vm2.$sp] = stack.length - 1;
52695 evalStack[REGISTERS][_vm2.$fp] = -1;
52696 this[HEAP] = this.program.heap;
52697 this[CONSTANTS] = this.program.constants;
52698 this.elementStack = elementStack;
52699 this[STACKS].scope.push(scope);
52700 this[STACKS].dynamicScope.push(dynamicScope);
52701 this[ARGS] = new VMArgumentsImpl();
52702 this[INNER_VM] = new LowLevelVM(evalStack, this[HEAP], runtime.program, {
52703 debugBefore: opcode => {
52704 return APPEND_OPCODES.debugBefore(this, opcode);
52705 },
52706 debugAfter: state => {
52707 APPEND_OPCODES.debugAfter(this, state);
52708 }
52709 }, evalStack[REGISTERS]);
52710 this.destructor = {};
52711 this[DESTROYABLE_STACK].push(this.destructor);
52712 }
52713
52714 get stack() {
52715 return this[INNER_VM].stack;
52716 }
52717 /* Registers */
52718
52719
52720 get pc() {
52721 return this[INNER_VM].fetchRegister(_vm2.$pc);
52722 } // Fetch a value from a register onto the stack
52723
52724
52725 fetch(register) {
52726 var value = this.fetchValue(register);
52727 this.stack.pushJs(value);
52728 } // Load a value from the stack into a register
52729
52730
52731 load(register) {
52732 var value = this.stack.pop();
52733 this.loadValue(register, value);
52734 }
52735
52736 fetchValue(register) {
52737 if ((0, _vm2.isLowLevelRegister)(register)) {
52738 return this[INNER_VM].fetchRegister(register);
52739 }
52740
52741 switch (register) {
52742 case _vm2.$s0:
52743 return this.s0;
52744
52745 case _vm2.$s1:
52746 return this.s1;
52747
52748 case _vm2.$t0:
52749 return this.t0;
52750
52751 case _vm2.$t1:
52752 return this.t1;
52753
52754 case _vm2.$v0:
52755 return this.v0;
52756 }
52757 } // Load a value into a register
52758
52759
52760 loadValue(register, value) {
52761 if ((0, _vm2.isLowLevelRegister)(register)) {
52762 this[INNER_VM].loadRegister(register, value);
52763 }
52764
52765 switch (register) {
52766 case _vm2.$s0:
52767 this.s0 = value;
52768 break;
52769
52770 case _vm2.$s1:
52771 this.s1 = value;
52772 break;
52773
52774 case _vm2.$t0:
52775 this.t0 = value;
52776 break;
52777
52778 case _vm2.$t1:
52779 this.t1 = value;
52780 break;
52781
52782 case _vm2.$v0:
52783 this.v0 = value;
52784 break;
52785 }
52786 }
52787 /**
52788 * Migrated to Inner
52789 */
52790 // Start a new frame and save $ra and $fp on the stack
52791
52792
52793 pushFrame() {
52794 this[INNER_VM].pushFrame();
52795 } // Restore $ra, $sp and $fp
52796
52797
52798 popFrame() {
52799 this[INNER_VM].popFrame();
52800 } // Jump to an address in `program`
52801
52802
52803 goto(offset) {
52804 this[INNER_VM].goto(offset);
52805 } // Save $pc into $ra, then jump to a new address in `program` (jal in MIPS)
52806
52807
52808 call(handle) {
52809 this[INNER_VM].call(handle);
52810 } // Put a specific `program` address in $ra
52811
52812
52813 returnTo(offset) {
52814 this[INNER_VM].returnTo(offset);
52815 } // Return to the `program` address stored in $ra
52816
52817
52818 return() {
52819 this[INNER_VM].return();
52820 }
52821
52822 get program() {
52823 return this.runtime.program;
52824 }
52825
52826 get env() {
52827 return this.runtime.env;
52828 }
52829
52830 captureState(args, pc = this[INNER_VM].fetchRegister(_vm2.$pc)) {
52831 return {
52832 pc,
52833 dynamicScope: this.dynamicScope(),
52834 scope: this.scope(),
52835 stack: this.stack.capture(args)
52836 };
52837 }
52838
52839 beginCacheGroup() {
52840 var opcodes = this.updating();
52841 var guard = new JumpIfNotModifiedOpcode(opcodes.length);
52842 opcodes.push(guard);
52843 this[STACKS].cache.push(guard);
52844 }
52845
52846 commitCacheGroup() {
52847 var opcodes = this.updating();
52848 var guard = this[STACKS].cache.pop();
52849 var startIndex = guard.index;
52850 var tag = combineFromIndex(opcodes, startIndex);
52851 opcodes.push(new DidModifyOpcode(guard));
52852 guard.finalize(tag, opcodes.length);
52853 }
52854
52855 enter(args) {
52856 var updating = [];
52857 var state = this.capture(args);
52858 var block = this.elements().pushUpdatableBlock();
52859 var tryOpcode = new TryOpcode(state, this.runtime, block, updating);
52860 this.didEnter(tryOpcode);
52861 }
52862
52863 enterItem(iterableRef, {
52864 key,
52865 value,
52866 memo
52867 }) {
52868 var {
52869 stack
52870 } = this;
52871 var valueRef = iterableRef.childRefFor(key, value);
52872 var memoRef = iterableRef.childRefFor(key, memo);
52873 stack.pushJs(valueRef);
52874 stack.pushJs(memoRef);
52875 var state = this.capture(2);
52876 var block = this.elements().pushUpdatableBlock();
52877 var opcode = new ListItemOpcode(state, this.runtime, block, key, memoRef, valueRef);
52878 this.didEnter(opcode);
52879 return opcode;
52880 }
52881
52882 registerItem(opcode) {
52883 this.listBlock().initializeChild(opcode);
52884 }
52885
52886 enterList(offset) {
52887 var updating = [];
52888 var addr = this[INNER_VM].target(offset);
52889 var state = this.capture(0, addr);
52890 var list = this.elements().pushBlockList(updating);
52891 var iterableRef = this.stack.peekJs();
52892 var opcode = new ListBlockOpcode(state, this.runtime, list, updating, iterableRef);
52893 this[STACKS].list.push(opcode);
52894 this.didEnter(opcode);
52895 }
52896
52897 didEnter(opcode) {
52898 this.associateDestroyable(opcode);
52899 this[DESTROYABLE_STACK].push(opcode);
52900 this.updateWith(opcode);
52901 this.pushUpdating(opcode.children);
52902 }
52903
52904 exit() {
52905 this[DESTROYABLE_STACK].pop();
52906 this.elements().popBlock();
52907 this.popUpdating();
52908 var updating = this.updating();
52909 var parent = updating[updating.length - 1];
52910 parent.didInitializeChildren();
52911 }
52912
52913 exitList() {
52914 this.exit();
52915 this[STACKS].list.pop();
52916 }
52917
52918 pushUpdating(list = []) {
52919 this[STACKS].updating.push(list);
52920 }
52921
52922 popUpdating() {
52923 return this[STACKS].updating.pop();
52924 }
52925
52926 updateWith(opcode) {
52927 this.updating().push(opcode);
52928 }
52929
52930 listBlock() {
52931 return this[STACKS].list.current;
52932 }
52933
52934 associateDestroyable(child) {
52935 var parent = this[DESTROYABLE_STACK].current;
52936 associateDestroyableChild(parent, child);
52937 }
52938
52939 tryUpdating() {
52940 return this[STACKS].updating.current;
52941 }
52942
52943 updating() {
52944 return this[STACKS].updating.current;
52945 }
52946
52947 elements() {
52948 return this.elementStack;
52949 }
52950
52951 scope() {
52952 return this[STACKS].scope.current;
52953 }
52954
52955 dynamicScope() {
52956 return this[STACKS].dynamicScope.current;
52957 }
52958
52959 pushChildScope() {
52960 this[STACKS].scope.push(this.scope().child());
52961 }
52962
52963 pushDynamicScope() {
52964 var child = this.dynamicScope().child();
52965 this[STACKS].dynamicScope.push(child);
52966 return child;
52967 }
52968
52969 pushRootScope(size) {
52970 var scope = ScopeImpl.sized(size);
52971 this[STACKS].scope.push(scope);
52972 return scope;
52973 }
52974
52975 pushScope(scope) {
52976 this[STACKS].scope.push(scope);
52977 }
52978
52979 popScope() {
52980 this[STACKS].scope.pop();
52981 }
52982
52983 popDynamicScope() {
52984 this[STACKS].dynamicScope.pop();
52985 } /// SCOPE HELPERS
52986
52987
52988 getSelf() {
52989 return this.scope().getSelf();
52990 }
52991
52992 referenceForSymbol(symbol$$1) {
52993 return this.scope().getSymbol(symbol$$1);
52994 } /// EXECUTION
52995
52996
52997 execute(initialize) {
52998 if (initialize) initialize(this);
52999 var result;
53000
53001 try {
53002 while (true) {
53003 result = this.next();
53004 if (result.done) break;
53005 }
53006 } finally {
53007 // If any existing blocks are open, due to an error or something like
53008 // that, we need to close them all and clean things up properly.
53009 var elements = this.elements();
53010
53011 while (elements.hasBlocks) {
53012 elements.popBlock();
53013 }
53014 }
53015
53016 return result.value;
53017 }
53018
53019 next() {
53020 var {
53021 env,
53022 elementStack
53023 } = this;
53024 var opcode = this[INNER_VM].nextStatement();
53025 var result;
53026
53027 if (opcode !== null) {
53028 this[INNER_VM].evaluateOuter(opcode, this);
53029 result = {
53030 done: false,
53031 value: null
53032 };
53033 } else {
53034 // Unload the stack
53035 this.stack.reset();
53036 result = {
53037 done: true,
53038 value: new RenderResultImpl(env, this.popUpdating(), elementStack.popBlock(), this.destructor)
53039 };
53040 }
53041
53042 return result;
53043 }
53044
53045 bindDynamicScope(names) {
53046 var scope = this.dynamicScope();
53047
53048 for (var i = names.length - 1; i >= 0; i--) {
53049 var _name10 = names[i];
53050 scope.set(_name10, this.stack.popJs());
53051 }
53052 }
53053
53054 }
53055
53056 _exports.LowLevelVM = VM;
53057 _a$3 = STACKS, _b = DESTROYABLE_STACK;
53058
53059 function vmState(pc, scope = ScopeImpl.root(UNDEFINED_REFERENCE, 0), dynamicScope) {
53060 return {
53061 pc,
53062 scope,
53063 dynamicScope,
53064 stack: []
53065 };
53066 }
53067
53068 class AotVM extends VM {
53069 static empty(runtime, {
53070 handle,
53071 treeBuilder,
53072 dynamicScope
53073 }) {
53074 var vm = initAOT(runtime, vmState(runtime.program.heap.getaddr(handle), ScopeImpl.root(UNDEFINED_REFERENCE, 0), dynamicScope), treeBuilder);
53075 vm.pushUpdating();
53076 return vm;
53077 }
53078
53079 static initial(runtime, {
53080 handle,
53081 self,
53082 treeBuilder,
53083 dynamicScope
53084 }) {
53085 var scopeSize = runtime.program.heap.scopesizeof(handle);
53086 var scope = ScopeImpl.root(self, scopeSize);
53087 var pc = runtime.program.heap.getaddr(handle);
53088 var state = vmState(pc, scope, dynamicScope);
53089 var vm = initAOT(runtime, state, treeBuilder);
53090 vm.pushUpdating();
53091 return vm;
53092 }
53093
53094 capture(args, pc = this[INNER_VM].fetchRegister(_vm2.$pc)) {
53095 return new ResumableVMStateImpl(this.captureState(args, pc), initAOT);
53096 }
53097
53098 }
53099
53100 function initAOT(runtime, state, builder) {
53101 return new AotVM(runtime, state, builder);
53102 }
53103
53104 function initJIT(context) {
53105 return (runtime, state, builder) => new JitVM(runtime, state, builder, context);
53106 }
53107
53108 class JitVM extends VM {
53109 constructor(runtime, state, elementStack, context) {
53110 super(runtime, state, elementStack);
53111 this.context = context;
53112 this.resume = initJIT(this.context);
53113 }
53114
53115 static initial(runtime, context, {
53116 handle,
53117 self,
53118 dynamicScope,
53119 treeBuilder
53120 }) {
53121 var scopeSize = runtime.program.heap.scopesizeof(handle);
53122 var scope = ScopeImpl.root(self, scopeSize);
53123 var state = vmState(runtime.program.heap.getaddr(handle), scope, dynamicScope);
53124 var vm = initJIT(context)(runtime, state, treeBuilder);
53125 vm.pushUpdating();
53126 return vm;
53127 }
53128
53129 static empty(runtime, {
53130 handle,
53131 treeBuilder,
53132 dynamicScope
53133 }, context) {
53134 var vm = initJIT(context)(runtime, vmState(runtime.program.heap.getaddr(handle), ScopeImpl.root(UNDEFINED_REFERENCE, 0), dynamicScope), treeBuilder);
53135 vm.pushUpdating();
53136 return vm;
53137 }
53138
53139 capture(args, pc = this[INNER_VM].fetchRegister(_vm2.$pc)) {
53140 return new ResumableVMStateImpl(this.captureState(args, pc), this.resume);
53141 }
53142
53143 compile(block) {
53144 var handle = (0, _util.unwrapHandle)(block.compile(this.context));
53145 return handle;
53146 }
53147
53148 }
53149
53150 class TemplateIteratorImpl {
53151 constructor(vm) {
53152 this.vm = vm;
53153 }
53154
53155 next() {
53156 return this.vm.next();
53157 }
53158
53159 sync() {
53160 return renderSync(this.vm.runtime.env, this);
53161 }
53162
53163 }
53164
53165 function renderSync(env, iterator) {
53166 try {
53167 env.begin();
53168 var iteratorResult;
53169
53170 do {
53171 iteratorResult = iterator.next();
53172 } while (!iteratorResult.done);
53173
53174 return iteratorResult.value;
53175 } finally {
53176 env.commit();
53177 }
53178 }
53179
53180 function renderAotMain(runtime, self, treeBuilder, handle, dynamicScope = new DefaultDynamicScope()) {
53181 var vm = AotVM.initial(runtime, {
53182 self,
53183 dynamicScope,
53184 treeBuilder,
53185 handle
53186 });
53187 return new TemplateIteratorImpl(vm);
53188 }
53189
53190 function renderAot(runtime, handle, cursor, self = UNDEFINED_REFERENCE) {
53191 var treeBuilder = NewElementBuilder.forInitialRender(runtime.env, cursor);
53192 var dynamicScope = new DefaultDynamicScope();
53193 var vm = AotVM.initial(runtime, {
53194 self,
53195 dynamicScope,
53196 treeBuilder,
53197 handle
53198 });
53199 return new TemplateIteratorImpl(vm);
53200 }
53201
53202 function renderJitMain(runtime, context, self, treeBuilder, handle, dynamicScope = new DefaultDynamicScope()) {
53203 var vm = JitVM.initial(runtime, context, {
53204 self,
53205 dynamicScope,
53206 treeBuilder,
53207 handle
53208 });
53209 return new TemplateIteratorImpl(vm);
53210 }
53211
53212 function renderInvocation(vm, invocation, definition, args) {
53213 // Get a list of tuples of argument names and references, like
53214 // [['title', reference], ['name', reference]]
53215 var argList = Object.keys(args).map(key => [key, args[key]]);
53216 var blockNames = ['main', 'else', 'attrs']; // Prefix argument names with `@` symbol
53217
53218 var argNames = argList.map(([name]) => `@${name}`);
53219 vm.pushFrame(); // Push blocks on to the stack, three stack values per block
53220
53221 for (var i = 0; i < 3 * blockNames.length; i++) {
53222 vm.stack.pushNull();
53223 }
53224
53225 vm.stack.pushNull(); // For each argument, push its backing reference on to the stack
53226
53227 argList.forEach(([, reference]) => {
53228 vm.stack.pushJs(reference);
53229 }); // Configure VM based on blocks and args just pushed on to the stack.
53230
53231 vm[ARGS].setup(vm.stack, argNames, blockNames, 0, true); // Needed for the Op.Main opcode: arguments, component invocation object, and
53232 // component definition.
53233
53234 vm.stack.pushJs(vm[ARGS]);
53235 vm.stack.pushJs(invocation);
53236 vm.stack.pushJs(definition);
53237 return new TemplateIteratorImpl(vm);
53238 }
53239
53240 function renderAotComponent(runtime, treeBuilder, main, name, args = {}, dynamicScope = new DefaultDynamicScope()) {
53241 var vm = AotVM.empty(runtime, {
53242 treeBuilder,
53243 handle: main,
53244 dynamicScope
53245 });
53246 var definition = resolveComponent(vm.runtime.resolver, name);
53247 var {
53248 manager,
53249 state
53250 } = definition;
53251 var capabilities = capabilityFlagsFrom(manager.getCapabilities(state));
53252 var invocation;
53253
53254 if (hasStaticLayoutCapability(capabilities, manager)) {
53255 invocation = manager.getAotStaticLayout(state, vm.runtime.resolver);
53256 } else {
53257 throw new Error('Cannot invoke components with dynamic layouts as a root component.');
53258 }
53259
53260 return renderInvocation(vm, invocation, definition, args);
53261 }
53262
53263 function renderJitComponent(runtime, treeBuilder, context, main, name, args = {}, dynamicScope = new DefaultDynamicScope()) {
53264 var vm = JitVM.empty(runtime, {
53265 treeBuilder,
53266 handle: main,
53267 dynamicScope
53268 }, context);
53269 var definition = resolveComponent(vm.runtime.resolver, name);
53270 var {
53271 manager,
53272 state
53273 } = definition;
53274 var capabilities = capabilityFlagsFrom(manager.getCapabilities(state));
53275 var invocation;
53276
53277 if (hasStaticLayoutCapability(capabilities, manager)) {
53278 var layout = manager.getJitStaticLayout(state, vm.runtime.resolver);
53279 var handle = (0, _util.unwrapHandle)(layout.compile(context));
53280
53281 if (Array.isArray(handle)) {
53282 var error = handle[0];
53283 throw new Error(`Compile Error: ${error.problem} ${error.span.start}..${error.span.end} :: TODO (thread better)`);
53284 }
53285
53286 invocation = {
53287 handle,
53288 symbolTable: layout.symbolTable
53289 };
53290 } else {
53291 throw new Error('Cannot invoke components with dynamic layouts as a root component.');
53292 }
53293
53294 return renderInvocation(vm, invocation, definition, args);
53295 }
53296
53297 var SERIALIZATION_FIRST_NODE_STRING = '%+b:0%';
53298 _exports.SERIALIZATION_FIRST_NODE_STRING = SERIALIZATION_FIRST_NODE_STRING;
53299
53300 function isSerializationFirstNode(node) {
53301 return node.nodeValue === SERIALIZATION_FIRST_NODE_STRING;
53302 }
53303
53304 class RehydratingCursor extends CursorImpl {
53305 constructor(element, nextSibling, startingBlockDepth) {
53306 super(element, nextSibling);
53307 this.startingBlockDepth = startingBlockDepth;
53308 this.candidate = null;
53309 this.injectedOmittedNode = false;
53310 this.openBlockDepth = startingBlockDepth - 1;
53311 }
53312
53313 }
53314
53315 class RehydrateBuilder extends NewElementBuilder {
53316 constructor(env, parentNode, nextSibling) {
53317 super(env, parentNode, nextSibling);
53318 this.unmatchedAttributes = null;
53319 this.blockDepth = 0;
53320 if (nextSibling) throw new Error('Rehydration with nextSibling not supported');
53321 var node = this.currentCursor.element.firstChild;
53322
53323 while (node !== null) {
53324 if (isComment(node) && isSerializationFirstNode(node)) {
53325 break;
53326 }
53327
53328 node = node.nextSibling;
53329 }
53330
53331 this.candidate = node;
53332 }
53333
53334 get currentCursor() {
53335 return this[CURSOR_STACK].current;
53336 }
53337
53338 get candidate() {
53339 if (this.currentCursor) {
53340 return this.currentCursor.candidate;
53341 }
53342
53343 return null;
53344 }
53345
53346 set candidate(node) {
53347 var currentCursor = this.currentCursor;
53348 currentCursor.candidate = node;
53349 }
53350
53351 disableRehydration(nextSibling) {
53352 var currentCursor = this.currentCursor; // rehydration will be disabled until we either:
53353 // * hit popElement (and return to using the parent elements cursor)
53354 // * hit closeBlock and the next sibling is a close block comment
53355 // matching the expected openBlockDepth
53356
53357 currentCursor.candidate = null;
53358 currentCursor.nextSibling = nextSibling;
53359 }
53360
53361 enableRehydration(candidate) {
53362 var currentCursor = this.currentCursor;
53363 currentCursor.candidate = candidate;
53364 currentCursor.nextSibling = null;
53365 }
53366
53367 pushElement(element, nextSibling = null) {
53368 var cursor = new RehydratingCursor(element, nextSibling, this.blockDepth || 0);
53369 /**
53370 * <div> <--------------- currentCursor.element
53371 * <!--%+b:1%--> <------- would have been removed during openBlock
53372 * <div> <--------------- currentCursor.candidate -> cursor.element
53373 * <!--%+b:2%--> <----- currentCursor.candidate.firstChild -> cursor.candidate
53374 * Foo
53375 * <!--%-b:2%-->
53376 * </div>
53377 * <!--%-b:1%--> <------ becomes currentCursor.candidate
53378 */
53379
53380 if (this.candidate !== null) {
53381 cursor.candidate = element.firstChild;
53382 this.candidate = element.nextSibling;
53383 }
53384
53385 this[CURSOR_STACK].push(cursor);
53386 } // clears until the end of the current container
53387 // either the current open block or higher
53388
53389
53390 clearMismatch(candidate) {
53391 var current = candidate;
53392 var currentCursor = this.currentCursor;
53393
53394 if (currentCursor !== null) {
53395 var openBlockDepth = currentCursor.openBlockDepth;
53396
53397 if (openBlockDepth >= currentCursor.startingBlockDepth) {
53398 while (current) {
53399 if (isCloseBlock(current)) {
53400 var closeBlockDepth = getBlockDepth(current);
53401
53402 if (openBlockDepth >= closeBlockDepth) {
53403 break;
53404 }
53405 }
53406
53407 current = this.remove(current);
53408 }
53409 } else {
53410 while (current !== null) {
53411 current = this.remove(current);
53412 }
53413 } // current cursor parentNode should be openCandidate if element
53414 // or openCandidate.parentNode if comment
53415
53416
53417 this.disableRehydration(current);
53418 }
53419 }
53420
53421 __openBlock() {
53422 var {
53423 currentCursor
53424 } = this;
53425 if (currentCursor === null) return;
53426 var blockDepth = this.blockDepth;
53427 this.blockDepth++;
53428 var {
53429 candidate
53430 } = currentCursor;
53431 if (candidate === null) return;
53432 var {
53433 tagName
53434 } = currentCursor.element;
53435
53436 if (isOpenBlock(candidate) && getBlockDepth(candidate) === blockDepth) {
53437 this.candidate = this.remove(candidate);
53438 currentCursor.openBlockDepth = blockDepth;
53439 } else if (tagName !== 'TITLE' && tagName !== 'SCRIPT' && tagName !== 'STYLE') {
53440 this.clearMismatch(candidate);
53441 }
53442 }
53443
53444 __closeBlock() {
53445 var {
53446 currentCursor
53447 } = this;
53448 if (currentCursor === null) return; // openBlock is the last rehydrated open block
53449
53450 var openBlockDepth = currentCursor.openBlockDepth; // this currently is the expected next open block depth
53451
53452 this.blockDepth--;
53453 var {
53454 candidate
53455 } = currentCursor;
53456 var isRehydrating = false;
53457
53458 if (candidate !== null) {
53459 isRehydrating = true; //assert(
53460 // openBlockDepth === this.blockDepth,
53461 // 'when rehydrating, openBlockDepth should match this.blockDepth here'
53462 //);
53463
53464 if (isCloseBlock(candidate) && getBlockDepth(candidate) === openBlockDepth) {
53465 var nextSibling = this.remove(candidate);
53466 this.candidate = nextSibling;
53467 currentCursor.openBlockDepth--;
53468 } else {
53469 // close the block and clear mismatch in parent container
53470 // we will be either at the end of the element
53471 // or at the end of our containing block
53472 this.clearMismatch(candidate);
53473 isRehydrating = false;
53474 }
53475 }
53476
53477 if (isRehydrating === false) {
53478 // check if nextSibling matches our expected close block
53479 // if so, we remove the close block comment and
53480 // restore rehydration after clearMismatch disabled
53481 var _nextSibling = currentCursor.nextSibling;
53482
53483 if (_nextSibling !== null && isCloseBlock(_nextSibling) && getBlockDepth(_nextSibling) === this.blockDepth) {
53484 // restore rehydration state
53485 var _candidate2 = this.remove(_nextSibling);
53486
53487 this.enableRehydration(_candidate2);
53488 currentCursor.openBlockDepth--;
53489 }
53490 }
53491 }
53492
53493 __appendNode(node) {
53494 var {
53495 candidate
53496 } = this; // This code path is only used when inserting precisely one node. It needs more
53497 // comparison logic, but we can probably lean on the cases where this code path
53498 // is actually used.
53499
53500 if (candidate) {
53501 return candidate;
53502 } else {
53503 return super.__appendNode(node);
53504 }
53505 }
53506
53507 __appendHTML(html) {
53508 var candidateBounds = this.markerBounds();
53509
53510 if (candidateBounds) {
53511 var first = candidateBounds.firstNode();
53512 var last = candidateBounds.lastNode();
53513 var newBounds = new ConcreteBounds(this.element, first.nextSibling, last.previousSibling);
53514 var possibleEmptyMarker = this.remove(first);
53515 this.remove(last);
53516
53517 if (possibleEmptyMarker !== null && isEmpty$1(possibleEmptyMarker)) {
53518 this.candidate = this.remove(possibleEmptyMarker);
53519
53520 if (this.candidate !== null) {
53521 this.clearMismatch(this.candidate);
53522 }
53523 }
53524
53525 return newBounds;
53526 } else {
53527 return super.__appendHTML(html);
53528 }
53529 }
53530
53531 remove(node) {
53532 var element = node.parentNode;
53533 var next = node.nextSibling;
53534 element.removeChild(node);
53535 return next;
53536 }
53537
53538 markerBounds() {
53539 var _candidate = this.candidate;
53540
53541 if (_candidate && isMarker(_candidate)) {
53542 var first = _candidate;
53543 var last = first.nextSibling;
53544
53545 while (last && !isMarker(last)) {
53546 last = last.nextSibling;
53547 }
53548
53549 return new ConcreteBounds(this.element, first, last);
53550 } else {
53551 return null;
53552 }
53553 }
53554
53555 __appendText(string) {
53556 var {
53557 candidate
53558 } = this;
53559
53560 if (candidate) {
53561 if (isTextNode(candidate)) {
53562 if (candidate.nodeValue !== string) {
53563 candidate.nodeValue = string;
53564 }
53565
53566 this.candidate = candidate.nextSibling;
53567 return candidate;
53568 } else if (isSeparator(candidate)) {
53569 this.candidate = this.remove(candidate);
53570 return this.__appendText(string);
53571 } else if (isEmpty$1(candidate) && string === '') {
53572 this.candidate = this.remove(candidate);
53573 return this.__appendText(string);
53574 } else {
53575 this.clearMismatch(candidate);
53576 return super.__appendText(string);
53577 }
53578 } else {
53579 return super.__appendText(string);
53580 }
53581 }
53582
53583 __appendComment(string) {
53584 var _candidate = this.candidate;
53585
53586 if (_candidate && isComment(_candidate)) {
53587 if (_candidate.nodeValue !== string) {
53588 _candidate.nodeValue = string;
53589 }
53590
53591 this.candidate = _candidate.nextSibling;
53592 return _candidate;
53593 } else if (_candidate) {
53594 this.clearMismatch(_candidate);
53595 }
53596
53597 return super.__appendComment(string);
53598 }
53599
53600 __openElement(tag) {
53601 var _candidate = this.candidate;
53602
53603 if (_candidate && isElement(_candidate) && isSameNodeType(_candidate, tag)) {
53604 this.unmatchedAttributes = [].slice.call(_candidate.attributes);
53605 return _candidate;
53606 } else if (_candidate) {
53607 if (isElement(_candidate) && _candidate.tagName === 'TBODY') {
53608 this.pushElement(_candidate, null);
53609 this.currentCursor.injectedOmittedNode = true;
53610 return this.__openElement(tag);
53611 }
53612
53613 this.clearMismatch(_candidate);
53614 }
53615
53616 return super.__openElement(tag);
53617 }
53618
53619 __setAttribute(name, value, namespace) {
53620 var unmatched = this.unmatchedAttributes;
53621
53622 if (unmatched) {
53623 var attr = findByName(unmatched, name);
53624
53625 if (attr) {
53626 if (attr.value !== value) {
53627 attr.value = value;
53628 }
53629
53630 unmatched.splice(unmatched.indexOf(attr), 1);
53631 return;
53632 }
53633 }
53634
53635 return super.__setAttribute(name, value, namespace);
53636 }
53637
53638 __setProperty(name, value) {
53639 var unmatched = this.unmatchedAttributes;
53640
53641 if (unmatched) {
53642 var attr = findByName(unmatched, name);
53643
53644 if (attr) {
53645 if (attr.value !== value) {
53646 attr.value = value;
53647 }
53648
53649 unmatched.splice(unmatched.indexOf(attr), 1);
53650 return;
53651 }
53652 }
53653
53654 return super.__setProperty(name, value);
53655 }
53656
53657 __flushElement(parent, constructing) {
53658 var {
53659 unmatchedAttributes: unmatched
53660 } = this;
53661
53662 if (unmatched) {
53663 for (var i = 0; i < unmatched.length; i++) {
53664 this.constructing.removeAttribute(unmatched[i].name);
53665 }
53666
53667 this.unmatchedAttributes = null;
53668 } else {
53669 super.__flushElement(parent, constructing);
53670 }
53671 }
53672
53673 willCloseElement() {
53674 var {
53675 candidate,
53676 currentCursor
53677 } = this;
53678
53679 if (candidate !== null) {
53680 this.clearMismatch(candidate);
53681 }
53682
53683 if (currentCursor && currentCursor.injectedOmittedNode) {
53684 this.popElement();
53685 }
53686
53687 super.willCloseElement();
53688 }
53689
53690 getMarker(element, guid) {
53691 var marker = element.querySelector(`script[glmr="${guid}"]`);
53692
53693 if (marker) {
53694 return marker;
53695 }
53696
53697 return null;
53698 }
53699
53700 __pushRemoteElement(element, cursorId, insertBefore) {
53701 var marker = this.getMarker(element, cursorId);
53702
53703 if (insertBefore === undefined) {
53704 while (element.firstChild !== null && element.firstChild !== marker) {
53705 this.remove(element.firstChild);
53706 }
53707
53708 insertBefore = null;
53709 }
53710
53711 var cursor = new RehydratingCursor(element, null, this.blockDepth);
53712 this[CURSOR_STACK].push(cursor);
53713
53714 if (marker === null) {
53715 this.disableRehydration(insertBefore);
53716 } else {
53717 this.candidate = this.remove(marker);
53718 }
53719
53720 var block = new RemoteLiveBlock(element);
53721 return this.pushLiveBlock(block, true);
53722 }
53723
53724 didAppendBounds(bounds) {
53725 super.didAppendBounds(bounds);
53726
53727 if (this.candidate) {
53728 var last = bounds.lastNode();
53729 this.candidate = last && last.nextSibling;
53730 }
53731
53732 return bounds;
53733 }
53734
53735 }
53736
53737 _exports.RehydrateBuilder = RehydrateBuilder;
53738
53739 function isTextNode(node) {
53740 return node.nodeType === 3;
53741 }
53742
53743 function isComment(node) {
53744 return node.nodeType === 8;
53745 }
53746
53747 function isOpenBlock(node) {
53748 return node.nodeType === 8
53749 /* COMMENT_NODE */
53750 && node.nodeValue.lastIndexOf('%+b:', 0) === 0;
53751 }
53752
53753 function isCloseBlock(node) {
53754 return node.nodeType === 8
53755 /* COMMENT_NODE */
53756 && node.nodeValue.lastIndexOf('%-b:', 0) === 0;
53757 }
53758
53759 function getBlockDepth(node) {
53760 return parseInt(node.nodeValue.slice(4), 10);
53761 }
53762
53763 function isElement(node) {
53764 return node.nodeType === 1;
53765 }
53766
53767 function isMarker(node) {
53768 return node.nodeType === 8 && node.nodeValue === '%glmr%';
53769 }
53770
53771 function isSeparator(node) {
53772 return node.nodeType === 8 && node.nodeValue === '%|%';
53773 }
53774
53775 function isEmpty$1(node) {
53776 return node.nodeType === 8 && node.nodeValue === '% %';
53777 }
53778
53779 function isSameNodeType(candidate, tag) {
53780 if (candidate.namespaceURI === "http://www.w3.org/2000/svg"
53781 /* SVG */
53782 ) {
53783 return candidate.tagName === tag;
53784 }
53785
53786 return candidate.tagName === tag.toUpperCase();
53787 }
53788
53789 function findByName(array, name) {
53790 for (var i = 0; i < array.length; i++) {
53791 var attr = array[i];
53792 if (attr.name === name) return attr;
53793 }
53794
53795 return undefined;
53796 }
53797
53798 function rehydrationBuilder(env, cursor) {
53799 return RehydrateBuilder.forInitialRender(env, cursor);
53800 }
53801});
53802define("@glimmer/util", ["exports"], function (_exports) {
53803 "use strict";
53804
53805 Object.defineProperty(_exports, "__esModule", {
53806 value: true
53807 });
53808 _exports.assertNever = assertNever;
53809 _exports.assert = debugAssert;
53810 _exports.deprecate = deprecate;
53811 _exports.dict = dict;
53812 _exports.isDict = isDict;
53813 _exports.isObject = isObject;
53814 _exports.ensureGuid = ensureGuid;
53815 _exports.initializeGuid = initializeGuid;
53816 _exports.isSerializationFirstNode = isSerializationFirstNode;
53817 _exports.assign = assign;
53818 _exports.fillNulls = fillNulls;
53819 _exports.values = values;
53820 _exports.clearElement = clearElement;
53821 _exports.keys = keys;
53822 _exports.unwrap = unwrap;
53823 _exports.expect = expect;
53824 _exports.unreachable = unreachable;
53825 _exports.exhausted = exhausted;
53826 _exports.strip = strip;
53827 _exports.isHandle = isHandle;
53828 _exports.isNonPrimitiveHandle = isNonPrimitiveHandle;
53829 _exports.constants = constants;
53830 _exports.isSmallInt = isSmallInt;
53831 _exports.encodeNegative = encodeNegative;
53832 _exports.decodeNegative = decodeNegative;
53833 _exports.encodePositive = encodePositive;
53834 _exports.decodePositive = decodePositive;
53835 _exports.encodeHandle = encodeHandle;
53836 _exports.decodeHandle = decodeHandle;
53837 _exports.encodeImmediate = encodeImmediate;
53838 _exports.decodeImmediate = decodeImmediate;
53839 _exports.unwrapHandle = unwrapHandle;
53840 _exports.unwrapTemplate = unwrapTemplate;
53841 _exports.extractHandle = extractHandle;
53842 _exports.isOkHandle = isOkHandle;
53843 _exports.isErrHandle = isErrHandle;
53844 _exports.symbol = _exports.tuple = _exports.verifySteps = _exports.logStep = _exports.endTestSteps = _exports.beginTestSteps = _exports.debugToString = _exports.SERIALIZATION_FIRST_NODE_STRING = _exports.Stack = _exports.DictSet = _exports.EMPTY_ARRAY = void 0;
53845 var EMPTY_ARRAY = Object.freeze([]); // import Logger from './logger';
53846 // let alreadyWarned = false;
53847
53848 _exports.EMPTY_ARRAY = EMPTY_ARRAY;
53849
53850 function debugAssert(test, msg) {
53851 // if (!alreadyWarned) {
53852 // alreadyWarned = true;
53853 // Logger.warn("Don't leave debug assertions on in public builds");
53854 // }
53855 if (!test) {
53856 throw new Error(msg || 'assertion failure');
53857 }
53858 }
53859
53860 function deprecate(desc) {
53861 console.warn(`DEPRECATION: ${desc}`);
53862 }
53863
53864 var GUID = 0;
53865
53866 function initializeGuid(object) {
53867 return object._guid = ++GUID;
53868 }
53869
53870 function ensureGuid(object) {
53871 return object._guid || initializeGuid(object);
53872 }
53873
53874 function dict() {
53875 return Object.create(null);
53876 }
53877
53878 function isDict(u) {
53879 return u !== null && u !== undefined;
53880 }
53881
53882 function isObject(u) {
53883 return typeof u === 'object' && u !== null;
53884 }
53885
53886 class DictSet {
53887 constructor() {
53888 this.dict = dict();
53889 }
53890
53891 add(obj) {
53892 if (typeof obj === 'string') this.dict[obj] = obj;else this.dict[ensureGuid(obj)] = obj;
53893 return this;
53894 }
53895
53896 delete(obj) {
53897 if (typeof obj === 'string') delete this.dict[obj];else if (obj._guid) delete this.dict[obj._guid];
53898 }
53899
53900 }
53901
53902 _exports.DictSet = DictSet;
53903
53904 class StackImpl {
53905 constructor() {
53906 this.stack = [];
53907 this.current = null;
53908 }
53909
53910 get size() {
53911 return this.stack.length;
53912 }
53913
53914 push(item) {
53915 this.current = item;
53916 this.stack.push(item);
53917 }
53918
53919 pop() {
53920 var item = this.stack.pop();
53921 var len = this.stack.length;
53922 this.current = len === 0 ? null : this.stack[len - 1];
53923 return item === undefined ? null : item;
53924 }
53925
53926 nth(from) {
53927 var len = this.stack.length;
53928 return len < from ? null : this.stack[len - from];
53929 }
53930
53931 isEmpty() {
53932 return this.stack.length === 0;
53933 }
53934
53935 toArray() {
53936 return this.stack;
53937 }
53938
53939 }
53940
53941 _exports.Stack = StackImpl;
53942
53943 function clearElement(parent) {
53944 var current = parent.firstChild;
53945
53946 while (current) {
53947 var next = current.nextSibling;
53948 parent.removeChild(current);
53949 current = next;
53950 }
53951 }
53952
53953 var SERIALIZATION_FIRST_NODE_STRING = '%+b:0%';
53954 _exports.SERIALIZATION_FIRST_NODE_STRING = SERIALIZATION_FIRST_NODE_STRING;
53955
53956 function isSerializationFirstNode(node) {
53957 return node.nodeValue === SERIALIZATION_FIRST_NODE_STRING;
53958 }
53959
53960 var {
53961 keys: objKeys
53962 } = Object;
53963
53964 function assign(obj) {
53965 for (var i = 1; i < arguments.length; i++) {
53966 var assignment = arguments[i];
53967 if (assignment === null || typeof assignment !== 'object') continue;
53968
53969 var _keys = objKeys(assignment);
53970
53971 for (var j = 0; j < _keys.length; j++) {
53972 var key = _keys[j];
53973 obj[key] = assignment[key];
53974 }
53975 }
53976
53977 return obj;
53978 }
53979
53980 function fillNulls(count) {
53981 var arr = new Array(count);
53982
53983 for (var i = 0; i < count; i++) {
53984 arr[i] = null;
53985 }
53986
53987 return arr;
53988 }
53989
53990 function values(obj) {
53991 var vals = [];
53992
53993 for (var key in obj) {
53994 vals.push(obj[key]);
53995 }
53996
53997 return vals;
53998 }
53999
54000 function keys(obj) {
54001 return Object.keys(obj);
54002 }
54003
54004 function unwrap(val) {
54005 if (val === null || val === undefined) throw new Error(`Expected value to be present`);
54006 return val;
54007 }
54008
54009 function expect(val, message) {
54010 if (val === null || val === undefined) throw new Error(message);
54011 return val;
54012 }
54013
54014 function unreachable(message = 'unreachable') {
54015 return new Error(message);
54016 }
54017
54018 function exhausted(value) {
54019 throw new Error(`Exhausted ${value}`);
54020 }
54021
54022 var tuple = (...args) => args;
54023
54024 _exports.tuple = tuple;
54025 var symbol = typeof Symbol !== 'undefined' ? Symbol : key => `__${key}${Math.floor(Math.random() * Date.now())}__`;
54026 _exports.symbol = symbol;
54027
54028 function strip(strings, ...args) {
54029 var out = '';
54030
54031 for (var i = 0; i < strings.length; i++) {
54032 var string = strings[i];
54033 var dynamic = args[i] !== undefined ? String(args[i]) : '';
54034 out += `${string}${dynamic}`;
54035 }
54036
54037 var lines = out.split('\n');
54038
54039 while (lines.length && lines[0].match(/^\s*$/)) {
54040 lines.shift();
54041 }
54042
54043 while (lines.length && lines[lines.length - 1].match(/^\s*$/)) {
54044 lines.pop();
54045 }
54046
54047 var min = Infinity;
54048
54049 for (var line of lines) {
54050 var leading = line.match(/^\s*/)[0].length;
54051 min = Math.min(min, leading);
54052 }
54053
54054 var stripped = [];
54055
54056 for (var _line of lines) {
54057 stripped.push(_line.slice(min));
54058 }
54059
54060 return stripped.join('\n');
54061 }
54062
54063 function isHandle(value) {
54064 return value >= 0;
54065 }
54066
54067 function isNonPrimitiveHandle(value) {
54068 return value > 3
54069 /* ENCODED_UNDEFINED_HANDLE */
54070 ;
54071 }
54072
54073 function constants(...values) {
54074 return [false, true, null, undefined, ...values];
54075 }
54076
54077 function isSmallInt(value) {
54078 return value % 1 === 0 && value <= 536870911
54079 /* MAX_INT */
54080 && value >= -536870912
54081 /* MIN_INT */
54082 ;
54083 }
54084
54085 function encodeNegative(num) {
54086 return num & -536870913
54087 /* SIGN_BIT */
54088 ;
54089 }
54090
54091 function decodeNegative(num) {
54092 return num | ~-536870913
54093 /* SIGN_BIT */
54094 ;
54095 }
54096
54097 function encodePositive(num) {
54098 return ~num;
54099 }
54100
54101 function decodePositive(num) {
54102 return ~num;
54103 }
54104
54105 function encodeHandle(num) {
54106 return num;
54107 }
54108
54109 function decodeHandle(num) {
54110 return num;
54111 }
54112
54113 function encodeImmediate(num) {
54114 num |= 0;
54115 return num < 0 ? encodeNegative(num) : encodePositive(num);
54116 }
54117
54118 function decodeImmediate(num) {
54119 num |= 0;
54120 return num > -536870913
54121 /* SIGN_BIT */
54122 ? decodePositive(num) : decodeNegative(num);
54123 } // Warm
54124
54125
54126 [1, -1].forEach(x => decodeImmediate(encodeImmediate(x)));
54127
54128 function unwrapHandle(handle) {
54129 if (typeof handle === 'number') {
54130 return handle;
54131 } else {
54132 var error = handle.errors[0];
54133 throw new Error(`Compile Error: ${error.problem} @ ${error.span.start}..${error.span.end}`);
54134 }
54135 }
54136
54137 function unwrapTemplate(template) {
54138 if (template.result === 'error') {
54139 throw new Error(`Compile Error: ${template.problem} @ ${template.span.start}..${template.span.end}`);
54140 }
54141
54142 return template;
54143 }
54144
54145 function extractHandle(handle) {
54146 if (typeof handle === 'number') {
54147 return handle;
54148 } else {
54149 return handle.handle;
54150 }
54151 }
54152
54153 function isOkHandle(handle) {
54154 return typeof handle === 'number';
54155 }
54156
54157 function isErrHandle(handle) {
54158 return typeof handle === 'number';
54159 }
54160
54161 var debugToString;
54162
54163 if (true
54164 /* DEBUG */
54165 ) {
54166 var getFunctionName = fn => {
54167 var functionName = fn.name;
54168
54169 if (functionName === undefined) {
54170 var match = Function.prototype.toString.call(fn).match(/function (\w+)\s*\(/);
54171 functionName = match && match[1] || '';
54172 }
54173
54174 return functionName.replace(/^bound /, '');
54175 };
54176
54177 var getObjectName = obj => {
54178 var name;
54179 var className;
54180
54181 if (obj.constructor && obj.constructor !== Object) {
54182 className = getFunctionName(obj.constructor);
54183 }
54184
54185 if ('toString' in obj && obj.toString !== Object.prototype.toString && obj.toString !== Function.prototype.toString) {
54186 name = obj.toString();
54187 } // If the class has a decent looking name, and the `toString` is one of the
54188 // default Ember toStrings, replace the constructor portion of the toString
54189 // with the class name. We check the length of the class name to prevent doing
54190 // this when the value is minified.
54191
54192
54193 if (name && name.match(/<.*:ember\d+>/) && className && className[0] !== '_' && className.length > 2 && className !== 'Class') {
54194 return name.replace(/<.*:/, `<${className}:`);
54195 }
54196
54197 return name || className;
54198 };
54199
54200 var getPrimitiveName = value => {
54201 return String(value);
54202 };
54203
54204 debugToString = value => {
54205 if (typeof value === 'function') {
54206 return getFunctionName(value) || `(unknown function)`;
54207 } else if (typeof value === 'object' && value !== null) {
54208 return getObjectName(value) || `(unknown object)`;
54209 } else {
54210 return getPrimitiveName(value);
54211 }
54212 };
54213 }
54214
54215 var debugToString$1 = debugToString;
54216 _exports.debugToString = debugToString$1;
54217 var beginTestSteps;
54218 _exports.beginTestSteps = beginTestSteps;
54219 var endTestSteps;
54220 _exports.endTestSteps = endTestSteps;
54221 var verifySteps;
54222 _exports.verifySteps = verifySteps;
54223 var logStep;
54224 _exports.logStep = logStep;
54225
54226 function assertNever(value, desc = 'unexpected unreachable branch') {
54227 console.log('unreachable', value);
54228 console.trace(`${desc} :: ${JSON.stringify(value)} (${value})`);
54229 }
54230});
54231define("@glimmer/validator", ["exports", "@ember/polyfills"], function (_exports, _polyfills) {
54232 "use strict";
54233
54234 Object.defineProperty(_exports, "__esModule", {
54235 value: true
54236 });
54237 _exports.bump = bump;
54238 _exports.combine = combine;
54239 _exports.createCombinatorTag = createCombinatorTag;
54240 _exports.createTag = createTag;
54241 _exports.createUpdatableTag = createUpdatableTag;
54242 _exports.isConstTagged = isConstTagged;
54243 _exports.isConstTag = isConstTag;
54244 _exports.validateTag = validateTag;
54245 _exports.valueForTag = valueForTag;
54246 _exports.dirtyTagFor = dirtyTagFor;
54247 _exports.tagFor = tagFor;
54248 _exports.tagMetaFor = tagMetaFor;
54249 _exports.setPropertyDidChange = setPropertyDidChange;
54250 _exports.beginTrackFrame = beginTrackFrame;
54251 _exports.endTrackFrame = endTrackFrame;
54252 _exports.consumeTag = consumeTag;
54253 _exports.isTracking = isTracking;
54254 _exports.track = track;
54255 _exports.memo = memo;
54256 _exports.untrack = untrack;
54257 _exports.isConstMemo = isConstMemo;
54258 _exports.createCache = createCache;
54259 _exports.isConst = isConst;
54260 _exports.getValue = getValue;
54261 _exports.trackedData = trackedData;
54262 _exports.deprecateMutationsInAutotrackingTransaction = _exports.runInAutotrackingTransaction = _exports.setAutotrackingTransactionEnv = _exports.VOLATILE = _exports.VOLATILE_TAG = _exports.VolatileTag = _exports.updateTag = _exports.INITIAL = _exports.dirtyTag = _exports.CURRENT_TAG = _exports.CurrentTag = _exports.CONSTANT = _exports.CONSTANT_TAG = _exports.COMPUTE = _exports.ALLOW_CYCLES = void 0;
54263 // This is a duplicate utility from @glimmer/util because `@glimmer/validator`
54264 // should not depend on any other @glimmer packages, in order to avoid pulling
54265 // in types and prevent regressions in `@glimmer/tracking` (which has public types).
54266 var symbol = typeof Symbol !== 'undefined' ? Symbol : key => `__${key}${Math.floor(Math.random() * Date.now())}__`;
54267 var symbolFor = typeof Symbol !== 'undefined' ? Symbol.for : key => `__GLIMMER_VALIDATOR_SYMBOL_FOR_${key}`;
54268
54269 function getGlobal() {
54270 // eslint-disable-next-line node/no-unsupported-features/es-builtins
54271 if (typeof globalThis !== 'undefined') return globalThis;
54272 if (typeof self !== 'undefined') return self;
54273 if (typeof window !== 'undefined') return window;
54274 if (typeof global !== 'undefined') return global;
54275 throw new Error('unable to locate global object');
54276 }
54277
54278 var runInAutotrackingTransaction;
54279 _exports.runInAutotrackingTransaction = runInAutotrackingTransaction;
54280 var deprecateMutationsInAutotrackingTransaction;
54281 _exports.deprecateMutationsInAutotrackingTransaction = deprecateMutationsInAutotrackingTransaction;
54282 var setAutotrackingTransactionEnv;
54283 _exports.setAutotrackingTransactionEnv = setAutotrackingTransactionEnv;
54284 var assertTagNotConsumed;
54285 var markTagAsConsumed;
54286
54287 if (true
54288 /* DEBUG */
54289 ) {
54290 var DEPRECATE_IN_AUTOTRACKING_TRANSACTION = false;
54291 var AUTOTRACKING_TRANSACTION = null;
54292 var debuggingContexts = []; /////////
54293
54294 var TRANSACTION_ENV = {
54295 assert(message) {
54296 throw new Error(message);
54297 },
54298
54299 deprecate(message) {
54300 console.warn(message);
54301 },
54302
54303 debugMessage(obj, keyName) {
54304 var objName;
54305
54306 if (typeof obj === 'function') {
54307 objName = obj.name;
54308 } else if (typeof obj === 'object' && obj !== null) {
54309 var className = obj.constructor && obj.constructor.name || '(unknown class)';
54310 objName = `(an instance of ${className})`;
54311 } else if (obj === undefined) {
54312 objName = '(an unknown tag)';
54313 } else {
54314 objName = String(obj);
54315 }
54316
54317 var dirtyString = keyName ? `\`${keyName}\` on \`${objName}\`` : `\`${objName}\``;
54318 return `You attempted to update ${dirtyString}, but it had already been used previously in the same computation. Attempting to update a value after using it in a computation can cause logical errors, infinite revalidation bugs, and performance issues, and is not supported.`;
54319 }
54320
54321 };
54322
54323 _exports.setAutotrackingTransactionEnv = setAutotrackingTransactionEnv = env => (0, _polyfills.assign)(TRANSACTION_ENV, env);
54324 /**
54325 * Creates a global autotracking transaction. This will prevent any backflow
54326 * in any `track` calls within the transaction, even if they are not
54327 * externally consumed.
54328 *
54329 * `runInAutotrackingTransaction` can be called within itself, and it will add
54330 * onto the existing transaction if one exists.
54331 *
54332 * TODO: Only throw an error if the `track` is consumed.
54333 */
54334
54335
54336 _exports.runInAutotrackingTransaction = runInAutotrackingTransaction = (fn, debuggingContext) => {
54337 var previousDeprecateState = DEPRECATE_IN_AUTOTRACKING_TRANSACTION;
54338 var previousTransactionState = AUTOTRACKING_TRANSACTION;
54339 DEPRECATE_IN_AUTOTRACKING_TRANSACTION = false;
54340
54341 if (previousTransactionState === null) {
54342 // if there was no transaction start it. Otherwise, the transaction already exists.
54343 AUTOTRACKING_TRANSACTION = new WeakMap();
54344 }
54345
54346 if (debuggingContext) {
54347 debuggingContexts.unshift(debuggingContext);
54348 }
54349
54350 try {
54351 fn();
54352 } finally {
54353 if (debuggingContext) {
54354 debuggingContexts.shift();
54355 }
54356
54357 DEPRECATE_IN_AUTOTRACKING_TRANSACTION = previousDeprecateState;
54358 AUTOTRACKING_TRANSACTION = previousTransactionState;
54359 }
54360 };
54361 /**
54362 * Switches to deprecating within an autotracking transaction, if one exists.
54363 * If `runInAutotrackingTransaction` is called within the callback of this
54364 * method, it switches back to throwing an error, allowing zebra-striping of
54365 * the types of errors that are thrown.
54366 *
54367 * Does not start an autotracking transaction.
54368 *
54369 * NOTE: For Ember usage only, in general you should assert that these
54370 * invariants are true.
54371 */
54372
54373
54374 _exports.deprecateMutationsInAutotrackingTransaction = deprecateMutationsInAutotrackingTransaction = fn => {
54375 var previousDeprecateState = DEPRECATE_IN_AUTOTRACKING_TRANSACTION;
54376 DEPRECATE_IN_AUTOTRACKING_TRANSACTION = true;
54377
54378 try {
54379 fn();
54380 } finally {
54381 DEPRECATE_IN_AUTOTRACKING_TRANSACTION = previousDeprecateState;
54382 }
54383 };
54384
54385 var nthIndex = (str, pattern, n, startingPos = -1) => {
54386 var i = startingPos;
54387
54388 while (n-- > 0 && i++ < str.length) {
54389 i = str.indexOf(pattern, i);
54390 if (i < 0) break;
54391 }
54392
54393 return i;
54394 };
54395
54396 var makeAutotrackingErrorMessage = (sourceData, obj, keyName) => {
54397 var message = [TRANSACTION_ENV.debugMessage(obj, keyName && String(keyName))];
54398
54399 if (sourceData.context) {
54400 message.push(`\`${String(keyName)}\` was first used:\n\n${sourceData.context}`);
54401 }
54402
54403 message.push(`Stack trace for the update:`);
54404 return message.join('\n\n');
54405 };
54406
54407 markTagAsConsumed = _tag => {
54408 if (!AUTOTRACKING_TRANSACTION || AUTOTRACKING_TRANSACTION.has(_tag)) return;
54409 AUTOTRACKING_TRANSACTION.set(_tag, {
54410 context: debuggingContexts.map(c => c.replace(/^/gm, ' ').replace(/^ /, '-')).join('\n\n')
54411 }); // We need to mark the tag and all of its subtags as consumed, so we need to
54412 // cast it and access its internals. In the future this shouldn't be necessary,
54413 // this is only for computed properties.
54414
54415 var tag = _tag;
54416
54417 if (tag.subtag) {
54418 markTagAsConsumed(tag.subtag);
54419 }
54420
54421 if (tag.subtags) {
54422 tag.subtags.forEach(tag => markTagAsConsumed(tag));
54423 }
54424 };
54425
54426 assertTagNotConsumed = (tag, obj, keyName, forceHardError = false) => {
54427 if (AUTOTRACKING_TRANSACTION === null) return;
54428 var sourceData = AUTOTRACKING_TRANSACTION.get(tag);
54429 if (!sourceData) return;
54430
54431 if (DEPRECATE_IN_AUTOTRACKING_TRANSACTION && !forceHardError) {
54432 TRANSACTION_ENV.deprecate(makeAutotrackingErrorMessage(sourceData, obj, keyName));
54433 } else {
54434 // This hack makes the assertion message nicer, we can cut off the first
54435 // few lines of the stack trace and let users know where the actual error
54436 // occurred.
54437 try {
54438 TRANSACTION_ENV.assert(makeAutotrackingErrorMessage(sourceData, obj, keyName));
54439 } catch (e) {
54440 if (e.stack) {
54441 var updateStackBegin = e.stack.indexOf('Stack trace for the update:');
54442
54443 if (updateStackBegin !== -1) {
54444 var start = nthIndex(e.stack, '\n', 1, updateStackBegin);
54445 var end = nthIndex(e.stack, '\n', 4, updateStackBegin);
54446 e.stack = e.stack.substr(0, start) + e.stack.substr(end);
54447 }
54448 }
54449
54450 throw e;
54451 }
54452 }
54453 };
54454 }
54455
54456 var CONSTANT = 0;
54457 _exports.CONSTANT = CONSTANT;
54458 var INITIAL = 1;
54459 _exports.INITIAL = INITIAL;
54460 var VOLATILE = NaN;
54461 _exports.VOLATILE = VOLATILE;
54462 var $REVISION = INITIAL;
54463
54464 function bump() {
54465 $REVISION++;
54466 } //////////
54467
54468
54469 var COMPUTE = symbol('TAG_COMPUTE'); //////////
54470
54471 /**
54472 * `value` receives a tag and returns an opaque Revision based on that tag. This
54473 * snapshot can then later be passed to `validate` with the same tag to
54474 * determine if the tag has changed at all since the time that `value` was
54475 * called.
54476 *
54477 * @param tag
54478 */
54479
54480 _exports.COMPUTE = COMPUTE;
54481
54482 function valueForTag(tag) {
54483 return tag[COMPUTE]();
54484 }
54485 /**
54486 * `validate` receives a tag and a snapshot from a previous call to `value` with
54487 * the same tag, and determines if the tag is still valid compared to the
54488 * snapshot. If the tag's state has changed at all since then, `validate` will
54489 * return false, otherwise it will return true. This is used to determine if a
54490 * calculation related to the tags should be rerun.
54491 *
54492 * @param tag
54493 * @param snapshot
54494 */
54495
54496
54497 function validateTag(tag, snapshot) {
54498 return snapshot >= tag[COMPUTE]();
54499 }
54500
54501 var TYPE = symbol('TAG_TYPE');
54502 var ALLOW_CYCLES;
54503 _exports.ALLOW_CYCLES = ALLOW_CYCLES;
54504
54505 if (true
54506 /* DEBUG */
54507 ) {
54508 _exports.ALLOW_CYCLES = ALLOW_CYCLES = new WeakMap();
54509 }
54510
54511 class MonomorphicTagImpl {
54512 constructor(type) {
54513 this.revision = INITIAL;
54514 this.lastChecked = INITIAL;
54515 this.lastValue = INITIAL;
54516 this.isUpdating = false;
54517 this.subtag = null;
54518 this.subtagBufferCache = null;
54519 this[TYPE] = type;
54520 }
54521
54522 [COMPUTE]() {
54523 var {
54524 lastChecked
54525 } = this;
54526
54527 if (this.isUpdating === true) {
54528 if (true
54529 /* DEBUG */
54530 && !ALLOW_CYCLES.has(this)) {
54531 throw new Error('Cycles in tags are not allowed');
54532 }
54533
54534 this.lastChecked = ++$REVISION;
54535 } else if (lastChecked !== $REVISION) {
54536 this.isUpdating = true;
54537 this.lastChecked = $REVISION;
54538
54539 try {
54540 var {
54541 subtag,
54542 revision
54543 } = this;
54544
54545 if (subtag !== null) {
54546 if (Array.isArray(subtag)) {
54547 for (var i = 0; i < subtag.length; i++) {
54548 var value = subtag[i][COMPUTE]();
54549 revision = Math.max(value, revision);
54550 }
54551 } else {
54552 var subtagValue = subtag[COMPUTE]();
54553
54554 if (subtagValue === this.subtagBufferCache) {
54555 revision = Math.max(revision, this.lastValue);
54556 } else {
54557 // Clear the temporary buffer cache
54558 this.subtagBufferCache = null;
54559 revision = Math.max(revision, subtagValue);
54560 }
54561 }
54562 }
54563
54564 this.lastValue = revision;
54565 } finally {
54566 this.isUpdating = false;
54567 }
54568 }
54569
54570 return this.lastValue;
54571 }
54572
54573 static updateTag(_tag, _subtag) {
54574 if (true
54575 /* DEBUG */
54576 && _tag[TYPE] !== 1
54577 /* Updatable */
54578 ) {
54579 throw new Error('Attempted to update a tag that was not updatable');
54580 } // TODO: TS 3.7 should allow us to do this via assertion
54581
54582
54583 var tag = _tag;
54584 var subtag = _subtag;
54585
54586 if (subtag === CONSTANT_TAG) {
54587 tag.subtag = null;
54588 } else {
54589 // There are two different possibilities when updating a subtag:
54590 //
54591 // 1. subtag[COMPUTE]() <= tag[COMPUTE]();
54592 // 2. subtag[COMPUTE]() > tag[COMPUTE]();
54593 //
54594 // The first possibility is completely fine within our caching model, but
54595 // the second possibility presents a problem. If the parent tag has
54596 // already been read, then it's value is cached and will not update to
54597 // reflect the subtag's greater value. Next time the cache is busted, the
54598 // subtag's value _will_ be read, and it's value will be _greater_ than
54599 // the saved snapshot of the parent, causing the resulting calculation to
54600 // be rerun erroneously.
54601 //
54602 // In order to prevent this, when we first update to a new subtag we store
54603 // its computed value, and then check against that computed value on
54604 // subsequent updates. If its value hasn't changed, then we return the
54605 // parent's previous value. Once the subtag changes for the first time,
54606 // we clear the cache and everything is finally in sync with the parent.
54607 tag.subtagBufferCache = subtag[COMPUTE]();
54608 tag.subtag = subtag;
54609 }
54610 }
54611
54612 static dirtyTag(tag) {
54613 if (true
54614 /* DEBUG */
54615 && !(tag[TYPE] === 1
54616 /* Updatable */
54617 || tag[TYPE] === 0
54618 /* Dirtyable */
54619 )) {
54620 throw new Error('Attempted to dirty a tag that was not dirtyable');
54621 }
54622
54623 if (true
54624 /* DEBUG */
54625 ) {
54626 // Usually by this point, we've already asserted with better error information,
54627 // but this is our last line of defense.
54628 assertTagNotConsumed(tag);
54629 }
54630
54631 tag.revision = ++$REVISION;
54632 }
54633
54634 }
54635
54636 var dirtyTag = MonomorphicTagImpl.dirtyTag;
54637 _exports.dirtyTag = dirtyTag;
54638 var updateTag = MonomorphicTagImpl.updateTag; //////////
54639
54640 _exports.updateTag = updateTag;
54641
54642 function createTag() {
54643 return new MonomorphicTagImpl(0
54644 /* Dirtyable */
54645 );
54646 }
54647
54648 function createUpdatableTag() {
54649 return new MonomorphicTagImpl(1
54650 /* Updatable */
54651 );
54652 } //////////
54653
54654
54655 var CONSTANT_TAG = new MonomorphicTagImpl(3
54656 /* Constant */
54657 );
54658 _exports.CONSTANT_TAG = CONSTANT_TAG;
54659
54660 function isConstTagged({
54661 tag
54662 }) {
54663 return tag === CONSTANT_TAG;
54664 }
54665
54666 function isConstTag(tag) {
54667 return tag === CONSTANT_TAG;
54668 } //////////
54669
54670
54671 class VolatileTag {
54672 [COMPUTE]() {
54673 return VOLATILE;
54674 }
54675
54676 }
54677
54678 _exports.VolatileTag = VolatileTag;
54679 var VOLATILE_TAG = new VolatileTag(); //////////
54680
54681 _exports.VOLATILE_TAG = VOLATILE_TAG;
54682
54683 class CurrentTag {
54684 [COMPUTE]() {
54685 return $REVISION;
54686 }
54687
54688 }
54689
54690 _exports.CurrentTag = CurrentTag;
54691 var CURRENT_TAG = new CurrentTag(); //////////
54692
54693 _exports.CURRENT_TAG = CURRENT_TAG;
54694
54695 function combine(tags) {
54696 var optimized = [];
54697
54698 for (var i = 0, l = tags.length; i < l; i++) {
54699 var tag = tags[i];
54700 if (tag === CONSTANT_TAG) continue;
54701 optimized.push(tag);
54702 }
54703
54704 return createCombinatorTag(optimized);
54705 }
54706
54707 function createCombinatorTag(tags) {
54708 switch (tags.length) {
54709 case 0:
54710 return CONSTANT_TAG;
54711
54712 case 1:
54713 return tags[0];
54714
54715 default:
54716 var tag = new MonomorphicTagImpl(2
54717 /* Combinator */
54718 );
54719 tag.subtag = tags;
54720 return tag;
54721 }
54722 } // Warm
54723
54724
54725 var tag1 = createUpdatableTag();
54726 var tag2 = createUpdatableTag();
54727 var tag3 = createUpdatableTag();
54728 valueForTag(tag1);
54729 dirtyTag(tag1);
54730 valueForTag(tag1);
54731 updateTag(tag1, combine([tag2, tag3]));
54732 valueForTag(tag1);
54733 dirtyTag(tag2);
54734 valueForTag(tag1);
54735 dirtyTag(tag3);
54736 valueForTag(tag1);
54737 updateTag(tag1, tag3);
54738 valueForTag(tag1);
54739 dirtyTag(tag3);
54740 valueForTag(tag1);
54741
54742 var propertyDidChange = function () {};
54743
54744 function setPropertyDidChange(cb) {
54745 propertyDidChange = cb;
54746 }
54747
54748 function isObjectLike(u) {
54749 return typeof u === 'object' && u !== null || typeof u === 'function';
54750 }
54751
54752 var TRACKED_TAGS = new WeakMap();
54753
54754 function dirtyTagFor(obj, key) {
54755 if (true
54756 /* DEBUG */
54757 && !isObjectLike(obj)) {
54758 throw new Error(`BUG: Can't update a tag for a primitive`);
54759 }
54760
54761 var tags = TRACKED_TAGS.get(obj); // No tags have been setup for this object yet, return
54762
54763 if (tags === undefined) return; // Dirty the tag for the specific property if it exists
54764
54765 var propertyTag = tags.get(key);
54766
54767 if (propertyTag !== undefined) {
54768 if (true
54769 /* DEBUG */
54770 ) {
54771 assertTagNotConsumed(propertyTag, obj, key);
54772 }
54773
54774 dirtyTag(propertyTag);
54775 propertyDidChange();
54776 }
54777 }
54778
54779 function tagMetaFor(obj) {
54780 var tags = TRACKED_TAGS.get(obj);
54781
54782 if (tags === undefined) {
54783 tags = new Map();
54784 TRACKED_TAGS.set(obj, tags);
54785 }
54786
54787 return tags;
54788 }
54789
54790 function tagFor(obj, key, meta) {
54791 var tags = meta === undefined ? tagMetaFor(obj) : meta;
54792 var tag = tags.get(key);
54793
54794 if (tag === undefined) {
54795 tag = createUpdatableTag();
54796 tags.set(key, tag);
54797 }
54798
54799 return tag;
54800 }
54801 /**
54802 * An object that that tracks @tracked properties that were consumed.
54803 */
54804
54805
54806 class Tracker {
54807 constructor() {
54808 this.tags = new Set();
54809 this.last = null;
54810 }
54811
54812 add(tag) {
54813 this.tags.add(tag);
54814
54815 if (true
54816 /* DEBUG */
54817 ) {
54818 markTagAsConsumed(tag);
54819 }
54820
54821 this.last = tag;
54822 }
54823
54824 combine() {
54825 var {
54826 tags
54827 } = this;
54828
54829 if (tags.size === 0) {
54830 return CONSTANT_TAG;
54831 } else if (tags.size === 1) {
54832 return this.last;
54833 } else {
54834 var tagsArr = [];
54835 tags.forEach(tag => tagsArr.push(tag));
54836 return combine(tagsArr);
54837 }
54838 }
54839
54840 }
54841 /**
54842 * Whenever a tracked computed property is entered, the current tracker is
54843 * saved off and a new tracker is replaced.
54844 *
54845 * Any tracked properties consumed are added to the current tracker.
54846 *
54847 * When a tracked computed property is exited, the tracker's tags are
54848 * combined and added to the parent tracker.
54849 *
54850 * The consequence is that each tracked computed property has a tag
54851 * that corresponds to the tracked properties consumed inside of
54852 * itself, including child tracked computed properties.
54853 */
54854
54855
54856 var CURRENT_TRACKER = null;
54857 var OPEN_TRACK_FRAMES = [];
54858
54859 function beginTrackFrame() {
54860 OPEN_TRACK_FRAMES.push(CURRENT_TRACKER);
54861 CURRENT_TRACKER = new Tracker();
54862 }
54863
54864 function endTrackFrame() {
54865 var current = CURRENT_TRACKER;
54866
54867 if (true
54868 /* DEBUG */
54869 && OPEN_TRACK_FRAMES.length === 0) {
54870 throw new Error('attempted to close a tracking frame, but one was not open');
54871 }
54872
54873 CURRENT_TRACKER = OPEN_TRACK_FRAMES.pop();
54874 return current.combine();
54875 }
54876
54877 function isTracking() {
54878 return CURRENT_TRACKER !== null;
54879 }
54880
54881 function consumeTag(tag) {
54882 if (CURRENT_TRACKER !== null) {
54883 CURRENT_TRACKER.add(tag);
54884 }
54885 } //////////
54886
54887
54888 var CACHE_KEY = symbol('CACHE_KEY');
54889
54890 function memo(callback, debuggingContext) {
54891 var cache = createCache(callback, debuggingContext);
54892
54893 var memoized = () => getValue(cache);
54894
54895 memoized[CACHE_KEY] = cache;
54896 return memoized;
54897 }
54898
54899 function isConstMemo(fn) {
54900 return isMemo(fn) ? isConst(fn[CACHE_KEY]) : false;
54901 }
54902
54903 function isMemo(fn) {
54904 return CACHE_KEY in fn;
54905 }
54906
54907 var FN = symbol('FN');
54908 var LAST_VALUE = symbol('LAST_VALUE');
54909 var TAG = symbol('TAG');
54910 var SNAPSHOT = symbol('SNAPSHOT');
54911 var DEBUG_LABEL = symbol('DEBUG_LABEL');
54912
54913 function createCache(fn, debuggingLabel) {
54914 if (true
54915 /* DEBUG */
54916 && !(typeof fn === 'function')) {
54917 throw new Error(`createCache() must be passed a function as its first parameter. Called with: ${String(fn)}`);
54918 }
54919
54920 var cache = {
54921 [FN]: fn,
54922 [LAST_VALUE]: undefined,
54923 [TAG]: undefined,
54924 [SNAPSHOT]: -1
54925 };
54926
54927 if (true
54928 /* DEBUG */
54929 ) {
54930 cache[DEBUG_LABEL] = debuggingLabel;
54931 }
54932
54933 return cache;
54934 }
54935
54936 function getValue(cache) {
54937 assertCache(cache, 'getValue');
54938 var fn = cache[FN];
54939 var tag = cache[TAG];
54940 var snapshot = cache[SNAPSHOT];
54941
54942 if (tag === undefined || !validateTag(tag, snapshot)) {
54943 beginTrackFrame();
54944
54945 try {
54946 if (true
54947 /* DEBUG */
54948 ) {
54949 runInAutotrackingTransaction(() => cache[LAST_VALUE] = fn(), cache[DEBUG_LABEL]);
54950 } else {
54951 cache[LAST_VALUE] = fn();
54952 }
54953 } finally {
54954 tag = endTrackFrame();
54955 cache[TAG] = tag;
54956 cache[SNAPSHOT] = valueForTag(tag);
54957 consumeTag(tag);
54958 }
54959 } else {
54960 consumeTag(tag);
54961 }
54962
54963 return cache[LAST_VALUE];
54964 }
54965
54966 function isConst(cache) {
54967 assertCache(cache, 'isConst');
54968 var tag = cache[TAG];
54969 assertTag(tag, cache);
54970 return isConstTag(tag);
54971 }
54972
54973 function assertCache(value, fnName) {
54974 if (true
54975 /* DEBUG */
54976 && !(typeof value === 'object' && value !== null && FN in value)) {
54977 throw new Error(`${fnName}() can only be used on an instance of a cache created with createCache(). Called with: ${String(value)}`);
54978 }
54979 } // replace this with `expect` when we can
54980
54981
54982 function assertTag(tag, cache) {
54983 if (true
54984 /* DEBUG */
54985 && tag === undefined) {
54986 throw new Error(`isConst() can only be used on a cache once getValue() has been called at least once. Called with cache function:\n\n${String(cache[FN])}`);
54987 }
54988 } //////////
54989 // Legacy tracking APIs
54990 // track() shouldn't be necessary at all in the VM once the autotracking
54991 // refactors are merged, and we should generally be moving away from it. It may
54992 // be necessary in Ember for a while longer, but I think we'll be able to drop
54993 // it in favor of cache sooner rather than later.
54994
54995
54996 function track(callback, debuggingContext) {
54997 beginTrackFrame();
54998 var tag;
54999
55000 try {
55001 if (true
55002 /* DEBUG */
55003 ) {
55004 runInAutotrackingTransaction(callback, debuggingContext);
55005 } else {
55006 callback();
55007 }
55008 } finally {
55009 tag = endTrackFrame();
55010 }
55011
55012 return tag;
55013 } // untrack() is currently mainly used to handle places that were previously not
55014 // tracked, and that tracking now would cause backtracking rerender assertions.
55015 // I think once we move everyone forward onto modern APIs, we'll probably be
55016 // able to remove it, but I'm not sure yet.
55017
55018
55019 function untrack(callback) {
55020 OPEN_TRACK_FRAMES.push(CURRENT_TRACKER);
55021 CURRENT_TRACKER = null;
55022
55023 try {
55024 callback();
55025 } finally {
55026 CURRENT_TRACKER = OPEN_TRACK_FRAMES.pop();
55027 }
55028 }
55029
55030 function trackedData(key, initializer) {
55031 var values = new WeakMap();
55032 var hasInitializer = typeof initializer === 'function';
55033
55034 function getter(self) {
55035 consumeTag(tagFor(self, key));
55036 var value; // If the field has never been initialized, we should initialize it
55037
55038 if (hasInitializer && !values.has(self)) {
55039 value = initializer.call(self);
55040 values.set(self, value);
55041 } else {
55042 value = values.get(self);
55043 }
55044
55045 return value;
55046 }
55047
55048 function setter(self, value) {
55049 if (true
55050 /* DEBUG */
55051 ) {
55052 assertTagNotConsumed(tagFor(self, key), self, key, true);
55053 }
55054
55055 dirtyTagFor(self, key);
55056 values.set(self, value);
55057 }
55058
55059 return {
55060 getter,
55061 setter
55062 };
55063 }
55064
55065 var globalObj = getGlobal();
55066 var GLIMMER_VALIDATOR_REGISTRATION = symbolFor('GLIMMER_VALIDATOR_REGISTRATION');
55067
55068 if (globalObj[GLIMMER_VALIDATOR_REGISTRATION] === true) {
55069 throw new Error('The `@glimmer/validator` library has been included twice in this application. It could be different versions of the package, or the same version included twice by mistake. `@glimmer/validator` depends on having a single copy of the package in use at any time in an application, even if they are the same version. You must dedupe your build to remove the duplicate packages in order to prevent this error.');
55070 }
55071
55072 globalObj[GLIMMER_VALIDATOR_REGISTRATION] = true;
55073});
55074define("@glimmer/vm", ["exports"], function (_exports) {
55075 "use strict";
55076
55077 Object.defineProperty(_exports, "__esModule", {
55078 value: true
55079 });
55080 _exports.isMachineOp = isMachineOp;
55081 _exports.isOp = isOp;
55082 _exports.isLowLevelRegister = isLowLevelRegister;
55083 _exports.$v0 = _exports.$t1 = _exports.$t0 = _exports.$s1 = _exports.$s0 = _exports.$sp = _exports.$ra = _exports.$fp = _exports.$pc = _exports.TemporaryRegister = _exports.SavedRegister = void 0;
55084
55085 /* This file is generated by build/debug.js */
55086 function isMachineOp(value) {
55087 return value >= 0 && value <= 15;
55088 }
55089
55090 function isOp(value) {
55091 return value >= 16;
55092 }
55093 /**
55094 * Registers
55095 *
55096 * For the most part, these follows MIPS naming conventions, however the
55097 * register numbers are different.
55098 */
55099 // $0 or $pc (program counter): pointer into `program` for the next insturction; -1 means exit
55100
55101
55102 var $pc = 0; // $1 or $ra (return address): pointer into `program` for the return
55103
55104 _exports.$pc = $pc;
55105 var $ra = 1; // $2 or $fp (frame pointer): pointer into the `evalStack` for the base of the stack
55106
55107 _exports.$ra = $ra;
55108 var $fp = 2; // $3 or $sp (stack pointer): pointer into the `evalStack` for the top of the stack
55109
55110 _exports.$fp = $fp;
55111 var $sp = 3; // $4-$5 or $s0-$s1 (saved): callee saved general-purpose registers
55112
55113 _exports.$sp = $sp;
55114 var $s0 = 4;
55115 _exports.$s0 = $s0;
55116 var $s1 = 5; // $6-$7 or $t0-$t1 (temporaries): caller saved general-purpose registers
55117
55118 _exports.$s1 = $s1;
55119 var $t0 = 6;
55120 _exports.$t0 = $t0;
55121 var $t1 = 7; // $8 or $v0 (return value)
55122
55123 _exports.$t1 = $t1;
55124 var $v0 = 8;
55125 _exports.$v0 = $v0;
55126
55127 function isLowLevelRegister(register) {
55128 return register <= $sp;
55129 }
55130
55131 var SavedRegister;
55132 _exports.SavedRegister = SavedRegister;
55133
55134 (function (SavedRegister) {
55135 SavedRegister[SavedRegister["s0"] = 4] = "s0";
55136 SavedRegister[SavedRegister["s1"] = 5] = "s1";
55137 })(SavedRegister || (_exports.SavedRegister = SavedRegister = {}));
55138
55139 var TemporaryRegister;
55140 _exports.TemporaryRegister = TemporaryRegister;
55141
55142 (function (TemporaryRegister) {
55143 TemporaryRegister[TemporaryRegister["t0"] = 6] = "t0";
55144 TemporaryRegister[TemporaryRegister["t1"] = 7] = "t1";
55145 })(TemporaryRegister || (_exports.TemporaryRegister = TemporaryRegister = {}));
55146});
55147define("@glimmer/wire-format", ["exports"], function (_exports) {
55148 "use strict";
55149
55150 Object.defineProperty(_exports, "__esModule", {
55151 value: true
55152 });
55153 _exports.is = is;
55154 _exports.isAttribute = isAttribute;
55155 _exports.isArgument = isArgument;
55156 _exports.isHelper = isHelper;
55157 _exports.isGet = _exports.isFlushElement = void 0;
55158
55159 function is(variant) {
55160 return function (value) {
55161 return Array.isArray(value) && value[0] === variant;
55162 };
55163 } // Statements
55164
55165
55166 var isFlushElement = is(12
55167 /* FlushElement */
55168 );
55169 _exports.isFlushElement = isFlushElement;
55170
55171 function isAttribute(val) {
55172 return val[0] === 14
55173 /* StaticAttr */
55174 || val[0] === 15
55175 /* DynamicAttr */
55176 || val[0] === 22
55177 /* TrustingDynamicAttr */
55178 || val[0] === 16
55179 /* ComponentAttr */
55180 || val[0] === 24
55181 /* StaticComponentAttr */
55182 || val[0] === 23
55183 /* TrustingComponentAttr */
55184 || val[0] === 17
55185 /* AttrSplat */
55186 || val[0] === 4
55187 /* Modifier */
55188 ;
55189 }
55190
55191 function isArgument(val) {
55192 return val[0] === 21
55193 /* StaticArg */
55194 || val[0] === 20
55195 /* DynamicArg */
55196 ;
55197 }
55198
55199 function isHelper(expr) {
55200 return Array.isArray(expr) && expr[0] === 30
55201 /* Call */
55202 ;
55203 } // Expressions
55204
55205
55206 var isGet = is(32
55207 /* GetSymbol */
55208 );
55209 _exports.isGet = isGet;
55210});
55211define("@simple-dom/document", ["exports"], function (_exports) {
55212 "use strict";
55213
55214 Object.defineProperty(_exports, "__esModule", {
55215 value: true
55216 });
55217 _exports.default = void 0;
55218 var EMPTY_ATTRS = [];
55219
55220 function indexOfAttribute(attributes, namespaceURI, localName) {
55221 for (var i = 0; i < attributes.length; i++) {
55222 var attr = attributes[i];
55223
55224 if (attr.namespaceURI === namespaceURI && attr.localName === localName) {
55225 return i;
55226 }
55227 }
55228
55229 return -1;
55230 }
55231
55232 function adjustAttrName(namespaceURI, localName) {
55233 return namespaceURI === "http://www.w3.org/1999/xhtml"
55234 /* HTML */
55235 ? localName.toLowerCase() : localName;
55236 }
55237
55238 function getAttribute(attributes, namespaceURI, localName) {
55239 var index = indexOfAttribute(attributes, namespaceURI, localName);
55240 return index === -1 ? null : attributes[index].value;
55241 }
55242
55243 function removeAttribute(attributes, namespaceURI, localName) {
55244 var index = indexOfAttribute(attributes, namespaceURI, localName);
55245
55246 if (index !== -1) {
55247 attributes.splice(index, 1);
55248 }
55249 } // https://dom.spec.whatwg.org/#dom-element-setattributens
55250
55251
55252 function setAttribute(element, namespaceURI, prefix, localName, value) {
55253 if (typeof value !== 'string') {
55254 value = '' + value;
55255 }
55256
55257 var {
55258 attributes
55259 } = element;
55260
55261 if (attributes === EMPTY_ATTRS) {
55262 attributes = element.attributes = [];
55263 } else {
55264 var index = indexOfAttribute(attributes, namespaceURI, localName);
55265
55266 if (index !== -1) {
55267 attributes[index].value = value;
55268 return;
55269 }
55270 }
55271
55272 attributes.push({
55273 localName,
55274 name: prefix === null ? localName : prefix + ':' + localName,
55275 namespaceURI,
55276 prefix,
55277 specified: true,
55278 value
55279 });
55280 }
55281
55282 class ChildNodes {
55283 constructor(node) {
55284 this.node = node;
55285 this.stale = true;
55286 this._length = 0;
55287 }
55288
55289 get length() {
55290 if (this.stale) {
55291 this.stale = false;
55292 var len = 0;
55293 var child = this.node.firstChild;
55294
55295 for (; child !== null; len++) {
55296 this[len] = child;
55297 child = child.nextSibling;
55298 }
55299
55300 var oldLen = this._length;
55301 this._length = len;
55302
55303 for (; len < oldLen; len++) {
55304 delete this[len];
55305 }
55306 }
55307
55308 return this._length;
55309 }
55310
55311 item(index) {
55312 return index < this.length ? this[index] : null;
55313 }
55314
55315 }
55316
55317 function cloneNode(node, deep) {
55318 var clone = nodeFrom(node);
55319
55320 if (deep) {
55321 var child = node.firstChild;
55322 var nextChild = child;
55323
55324 while (child !== null) {
55325 nextChild = child.nextSibling;
55326 clone.appendChild(child.cloneNode(true));
55327 child = nextChild;
55328 }
55329 }
55330
55331 return clone;
55332 }
55333
55334 function nodeFrom(node) {
55335 var namespaceURI;
55336
55337 if (node.nodeType === 1
55338 /* ELEMENT_NODE */
55339 ) {
55340 namespaceURI = node.namespaceURI;
55341 }
55342
55343 var clone = new SimpleNodeImpl(node.ownerDocument, node.nodeType, node.nodeName, node.nodeValue, namespaceURI);
55344
55345 if (node.nodeType === 1
55346 /* ELEMENT_NODE */
55347 ) {
55348 clone.attributes = copyAttrs(node.attributes);
55349 }
55350
55351 return clone;
55352 }
55353
55354 function copyAttrs(attrs) {
55355 if (attrs === EMPTY_ATTRS) {
55356 return EMPTY_ATTRS;
55357 }
55358
55359 var copy = [];
55360
55361 for (var i = 0; i < attrs.length; i++) {
55362 var attr = attrs[i];
55363 copy.push({
55364 localName: attr.localName,
55365 name: attr.name,
55366 namespaceURI: attr.namespaceURI,
55367 prefix: attr.prefix,
55368 specified: true,
55369 value: attr.value
55370 });
55371 }
55372
55373 return copy;
55374 }
55375
55376 function insertBefore(parentNode, newChild, refChild) {
55377 invalidate(parentNode);
55378 insertBetween(parentNode, newChild, refChild === null ? parentNode.lastChild : refChild.previousSibling, refChild);
55379 }
55380
55381 function removeChild(parentNode, oldChild) {
55382 invalidate(parentNode);
55383 removeBetween(parentNode, oldChild, oldChild.previousSibling, oldChild.nextSibling);
55384 }
55385
55386 function invalidate(parentNode) {
55387 var childNodes = parentNode._childNodes;
55388
55389 if (childNodes !== undefined) {
55390 childNodes.stale = true;
55391 }
55392 }
55393
55394 function insertBetween(parentNode, newChild, previousSibling, nextSibling) {
55395 if (newChild.nodeType === 11
55396 /* DOCUMENT_FRAGMENT_NODE */
55397 ) {
55398 insertFragment(newChild, parentNode, previousSibling, nextSibling);
55399 return;
55400 }
55401
55402 if (newChild.parentNode !== null) {
55403 removeChild(newChild.parentNode, newChild);
55404 }
55405
55406 newChild.parentNode = parentNode;
55407 newChild.previousSibling = previousSibling;
55408 newChild.nextSibling = nextSibling;
55409
55410 if (previousSibling === null) {
55411 parentNode.firstChild = newChild;
55412 } else {
55413 previousSibling.nextSibling = newChild;
55414 }
55415
55416 if (nextSibling === null) {
55417 parentNode.lastChild = newChild;
55418 } else {
55419 nextSibling.previousSibling = newChild;
55420 }
55421 }
55422
55423 function removeBetween(parentNode, oldChild, previousSibling, nextSibling) {
55424 oldChild.parentNode = null;
55425 oldChild.previousSibling = null;
55426 oldChild.nextSibling = null;
55427
55428 if (previousSibling === null) {
55429 parentNode.firstChild = nextSibling;
55430 } else {
55431 previousSibling.nextSibling = nextSibling;
55432 }
55433
55434 if (nextSibling === null) {
55435 parentNode.lastChild = previousSibling;
55436 } else {
55437 nextSibling.previousSibling = previousSibling;
55438 }
55439 }
55440
55441 function insertFragment(fragment, parentNode, previousSibling, nextSibling) {
55442 var firstChild = fragment.firstChild;
55443
55444 if (firstChild === null) {
55445 return;
55446 }
55447
55448 fragment.firstChild = null;
55449 fragment.lastChild = null;
55450 var lastChild = firstChild;
55451 var newChild = firstChild;
55452 firstChild.previousSibling = previousSibling;
55453
55454 if (previousSibling === null) {
55455 parentNode.firstChild = firstChild;
55456 } else {
55457 previousSibling.nextSibling = firstChild;
55458 }
55459
55460 while (newChild !== null) {
55461 newChild.parentNode = parentNode;
55462 lastChild = newChild;
55463 newChild = newChild.nextSibling;
55464 }
55465
55466 lastChild.nextSibling = nextSibling;
55467
55468 if (nextSibling === null) {
55469 parentNode.lastChild = lastChild;
55470 } else {
55471 nextSibling.previousSibling = lastChild;
55472 }
55473 }
55474
55475 function parseQualifiedName(qualifiedName) {
55476 var localName = qualifiedName;
55477 var prefix = null;
55478 var i = qualifiedName.indexOf(':');
55479
55480 if (i !== -1) {
55481 prefix = qualifiedName.slice(0, i);
55482 localName = qualifiedName.slice(i + 1);
55483 }
55484
55485 return [prefix, localName];
55486 }
55487
55488 class SimpleNodeImpl {
55489 constructor(ownerDocument, nodeType, nodeName, nodeValue, namespaceURI) {
55490 this.ownerDocument = ownerDocument;
55491 this.nodeType = nodeType;
55492 this.nodeName = nodeName;
55493 this.nodeValue = nodeValue;
55494 this.namespaceURI = namespaceURI;
55495 this.parentNode = null;
55496 this.previousSibling = null;
55497 this.nextSibling = null;
55498 this.firstChild = null;
55499 this.lastChild = null;
55500 this.attributes = EMPTY_ATTRS;
55501 /**
55502 * @internal
55503 */
55504
55505 this._childNodes = undefined;
55506 }
55507
55508 get tagName() {
55509 return this.nodeName;
55510 }
55511
55512 get childNodes() {
55513 var children = this._childNodes;
55514
55515 if (children === undefined) {
55516 children = this._childNodes = new ChildNodes(this);
55517 }
55518
55519 return children;
55520 }
55521
55522 cloneNode(deep) {
55523 return cloneNode(this, deep === true);
55524 }
55525
55526 appendChild(newChild) {
55527 insertBefore(this, newChild, null);
55528 return newChild;
55529 }
55530
55531 insertBefore(newChild, refChild) {
55532 insertBefore(this, newChild, refChild);
55533 return newChild;
55534 }
55535
55536 removeChild(oldChild) {
55537 removeChild(this, oldChild);
55538 return oldChild;
55539 }
55540
55541 insertAdjacentHTML(position, html) {
55542 var raw = new SimpleNodeImpl(this.ownerDocument, -1
55543 /* RAW_NODE */
55544 , '#raw', html, void 0);
55545 var parentNode;
55546 var nextSibling;
55547
55548 switch (position) {
55549 case 'beforebegin':
55550 parentNode = this.parentNode;
55551 nextSibling = this;
55552 break;
55553
55554 case 'afterbegin':
55555 parentNode = this;
55556 nextSibling = this.firstChild;
55557 break;
55558
55559 case 'beforeend':
55560 parentNode = this;
55561 nextSibling = null;
55562 break;
55563
55564 case 'afterend':
55565 parentNode = this.parentNode;
55566 nextSibling = this.nextSibling;
55567 break;
55568
55569 default:
55570 throw new Error('invalid position');
55571 }
55572
55573 if (parentNode === null) {
55574 throw new Error(`${position} requires a parentNode`);
55575 }
55576
55577 insertBefore(parentNode, raw, nextSibling);
55578 }
55579
55580 getAttribute(name) {
55581 var localName = adjustAttrName(this.namespaceURI, name);
55582 return getAttribute(this.attributes, null, localName);
55583 }
55584
55585 getAttributeNS(namespaceURI, localName) {
55586 return getAttribute(this.attributes, namespaceURI, localName);
55587 }
55588
55589 setAttribute(name, value) {
55590 var localName = adjustAttrName(this.namespaceURI, name);
55591 setAttribute(this, null, null, localName, value);
55592 }
55593
55594 setAttributeNS(namespaceURI, qualifiedName, value) {
55595 var [prefix, localName] = parseQualifiedName(qualifiedName);
55596 setAttribute(this, namespaceURI, prefix, localName, value);
55597 }
55598
55599 removeAttribute(name) {
55600 var localName = adjustAttrName(this.namespaceURI, name);
55601 removeAttribute(this.attributes, null, localName);
55602 }
55603
55604 removeAttributeNS(namespaceURI, localName) {
55605 removeAttribute(this.attributes, namespaceURI, localName);
55606 }
55607
55608 get doctype() {
55609 return this.firstChild;
55610 }
55611
55612 get documentElement() {
55613 return this.lastChild;
55614 }
55615
55616 get head() {
55617 return this.documentElement.firstChild;
55618 }
55619
55620 get body() {
55621 return this.documentElement.lastChild;
55622 }
55623
55624 createElement(name) {
55625 return new SimpleNodeImpl(this, 1
55626 /* ELEMENT_NODE */
55627 , name.toUpperCase(), null, "http://www.w3.org/1999/xhtml"
55628 /* HTML */
55629 );
55630 }
55631
55632 createElementNS(namespace, qualifiedName) {
55633 // Node name is case-preserving in XML contexts, but returns canonical uppercase form in HTML contexts
55634 // https://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-104682815
55635 var nodeName = namespace === "http://www.w3.org/1999/xhtml"
55636 /* HTML */
55637 ? qualifiedName.toUpperCase() : qualifiedName; // we don't care to parse the qualified name because we only support HTML documents
55638 // which don't support prefixed elements
55639
55640 return new SimpleNodeImpl(this, 1
55641 /* ELEMENT_NODE */
55642 , nodeName, null, namespace);
55643 }
55644
55645 createTextNode(text) {
55646 return new SimpleNodeImpl(this, 3
55647 /* TEXT_NODE */
55648 , '#text', text, void 0);
55649 }
55650
55651 createComment(text) {
55652 return new SimpleNodeImpl(this, 8
55653 /* COMMENT_NODE */
55654 , '#comment', text, void 0);
55655 }
55656 /**
55657 * Backwards compat
55658 * @deprecated
55659 */
55660
55661
55662 createRawHTMLSection(text) {
55663 return new SimpleNodeImpl(this, -1
55664 /* RAW_NODE */
55665 , '#raw', text, void 0);
55666 }
55667
55668 createDocumentFragment() {
55669 return new SimpleNodeImpl(this, 11
55670 /* DOCUMENT_FRAGMENT_NODE */
55671 , '#document-fragment', null, void 0);
55672 }
55673
55674 }
55675
55676 function createHTMLDocument() {
55677 // dom.d.ts types ownerDocument as Document but for a document ownerDocument is null
55678 var document = new SimpleNodeImpl(null, 9
55679 /* DOCUMENT_NODE */
55680 , '#document', null, "http://www.w3.org/1999/xhtml"
55681 /* HTML */
55682 );
55683 var doctype = new SimpleNodeImpl(document, 10
55684 /* DOCUMENT_TYPE_NODE */
55685 , 'html', null, "http://www.w3.org/1999/xhtml"
55686 /* HTML */
55687 );
55688 var html = new SimpleNodeImpl(document, 1
55689 /* ELEMENT_NODE */
55690 , 'HTML', null, "http://www.w3.org/1999/xhtml"
55691 /* HTML */
55692 );
55693 var head = new SimpleNodeImpl(document, 1
55694 /* ELEMENT_NODE */
55695 , 'HEAD', null, "http://www.w3.org/1999/xhtml"
55696 /* HTML */
55697 );
55698 var body = new SimpleNodeImpl(document, 1
55699 /* ELEMENT_NODE */
55700 , 'BODY', null, "http://www.w3.org/1999/xhtml"
55701 /* HTML */
55702 );
55703 html.appendChild(head);
55704 html.appendChild(body);
55705 document.appendChild(doctype);
55706 document.appendChild(html);
55707 return document;
55708 }
55709
55710 var _default = createHTMLDocument;
55711 _exports.default = _default;
55712});
55713define("backburner", ["exports"], function (_exports) {
55714 "use strict";
55715
55716 Object.defineProperty(_exports, "__esModule", {
55717 value: true
55718 });
55719 _exports.buildPlatform = buildPlatform;
55720 _exports.default = void 0;
55721 var SET_TIMEOUT = setTimeout;
55722
55723 var NOOP = () => {};
55724
55725 function buildNext(flush) {
55726 // Using "promises first" here to:
55727 //
55728 // 1) Ensure more consistent experience on browsers that
55729 // have differently queued microtasks (separate queues for
55730 // MutationObserver vs Promises).
55731 // 2) Ensure better debugging experiences (it shows up in Chrome
55732 // call stack as "Promise.then (async)") which is more consistent
55733 // with user expectations
55734 //
55735 // When Promise is unavailable use MutationObserver (mostly so that we
55736 // still get microtasks on IE11), and when neither MutationObserver and
55737 // Promise are present use a plain old setTimeout.
55738 if (typeof Promise === 'function') {
55739 var autorunPromise = Promise.resolve();
55740 return () => autorunPromise.then(flush);
55741 } else if (typeof MutationObserver === 'function') {
55742 var iterations = 0;
55743 var observer = new MutationObserver(flush);
55744 var node = document.createTextNode('');
55745 observer.observe(node, {
55746 characterData: true
55747 });
55748 return () => {
55749 iterations = ++iterations % 2;
55750 node.data = '' + iterations;
55751 return iterations;
55752 };
55753 } else {
55754 return () => SET_TIMEOUT(flush, 0);
55755 }
55756 }
55757
55758 function buildPlatform(flush) {
55759 var clearNext = NOOP;
55760 return {
55761 setTimeout(fn, ms) {
55762 return setTimeout(fn, ms);
55763 },
55764
55765 clearTimeout(timerId) {
55766 return clearTimeout(timerId);
55767 },
55768
55769 now() {
55770 return Date.now();
55771 },
55772
55773 next: buildNext(flush),
55774 clearNext
55775 };
55776 }
55777
55778 var NUMBER = /\d+/;
55779 var TIMERS_OFFSET = 6;
55780
55781 function isCoercableNumber(suspect) {
55782 var type = typeof suspect;
55783 return type === 'number' && suspect === suspect || type === 'string' && NUMBER.test(suspect);
55784 }
55785
55786 function getOnError(options) {
55787 return options.onError || options.onErrorTarget && options.onErrorTarget[options.onErrorMethod];
55788 }
55789
55790 function findItem(target, method, collection) {
55791 var index = -1;
55792
55793 for (var i = 0, l = collection.length; i < l; i += 4) {
55794 if (collection[i] === target && collection[i + 1] === method) {
55795 index = i;
55796 break;
55797 }
55798 }
55799
55800 return index;
55801 }
55802
55803 function findTimerItem(target, method, collection) {
55804 var index = -1;
55805
55806 for (var i = 2, l = collection.length; i < l; i += 6) {
55807 if (collection[i] === target && collection[i + 1] === method) {
55808 index = i - 2;
55809 break;
55810 }
55811 }
55812
55813 return index;
55814 }
55815
55816 function getQueueItems(items, queueItemLength, queueItemPositionOffset = 0) {
55817 var queueItems = [];
55818
55819 for (var i = 0; i < items.length; i += queueItemLength) {
55820 var maybeError = items[i + 3
55821 /* stack */
55822 + queueItemPositionOffset];
55823 var queueItem = {
55824 target: items[i + 0
55825 /* target */
55826 + queueItemPositionOffset],
55827 method: items[i + 1
55828 /* method */
55829 + queueItemPositionOffset],
55830 args: items[i + 2
55831 /* args */
55832 + queueItemPositionOffset],
55833 stack: maybeError !== undefined && 'stack' in maybeError ? maybeError.stack : ''
55834 };
55835 queueItems.push(queueItem);
55836 }
55837
55838 return queueItems;
55839 }
55840
55841 function binarySearch(time, timers) {
55842 var start = 0;
55843 var end = timers.length - TIMERS_OFFSET;
55844 var middle;
55845 var l;
55846
55847 while (start < end) {
55848 // since timers is an array of pairs 'l' will always
55849 // be an integer
55850 l = (end - start) / TIMERS_OFFSET; // compensate for the index in case even number
55851 // of pairs inside timers
55852
55853 middle = start + l - l % TIMERS_OFFSET;
55854
55855 if (time >= timers[middle]) {
55856 start = middle + TIMERS_OFFSET;
55857 } else {
55858 end = middle;
55859 }
55860 }
55861
55862 return time >= timers[start] ? start + TIMERS_OFFSET : start;
55863 }
55864
55865 var QUEUE_ITEM_LENGTH = 4;
55866
55867 class Queue {
55868 constructor(name, options = {}, globalOptions = {}) {
55869 this._queueBeingFlushed = [];
55870 this.targetQueues = new Map();
55871 this.index = 0;
55872 this._queue = [];
55873 this.name = name;
55874 this.options = options;
55875 this.globalOptions = globalOptions;
55876 }
55877
55878 stackFor(index) {
55879 if (index < this._queue.length) {
55880 var entry = this._queue[index * 3 + QUEUE_ITEM_LENGTH];
55881
55882 if (entry) {
55883 return entry.stack;
55884 } else {
55885 return null;
55886 }
55887 }
55888 }
55889
55890 flush(sync) {
55891 var {
55892 before,
55893 after
55894 } = this.options;
55895 var target;
55896 var method;
55897 var args;
55898 var errorRecordedForStack;
55899 this.targetQueues.clear();
55900
55901 if (this._queueBeingFlushed.length === 0) {
55902 this._queueBeingFlushed = this._queue;
55903 this._queue = [];
55904 }
55905
55906 if (before !== undefined) {
55907 before();
55908 }
55909
55910 var invoke;
55911 var queueItems = this._queueBeingFlushed;
55912
55913 if (queueItems.length > 0) {
55914 var onError = getOnError(this.globalOptions);
55915 invoke = onError ? this.invokeWithOnError : this.invoke;
55916
55917 for (var i = this.index; i < queueItems.length; i += QUEUE_ITEM_LENGTH) {
55918 this.index += QUEUE_ITEM_LENGTH;
55919 method = queueItems[i + 1]; // method could have been nullified / canceled during flush
55920
55921 if (method !== null) {
55922 //
55923 // ** Attention intrepid developer **
55924 //
55925 // To find out the stack of this task when it was scheduled onto
55926 // the run loop, add the following to your app.js:
55927 //
55928 // Ember.run.backburner.DEBUG = true; // NOTE: This slows your app, don't leave it on in production.
55929 //
55930 // Once that is in place, when you are at a breakpoint and navigate
55931 // here in the stack explorer, you can look at `errorRecordedForStack.stack`,
55932 // which will be the captured stack when this job was scheduled.
55933 //
55934 // One possible long-term solution is the following Chrome issue:
55935 // https://bugs.chromium.org/p/chromium/issues/detail?id=332624
55936 //
55937 target = queueItems[i];
55938 args = queueItems[i + 2];
55939 errorRecordedForStack = queueItems[i + 3]; // Debugging assistance
55940
55941 invoke(target, method, args, onError, errorRecordedForStack);
55942 }
55943
55944 if (this.index !== this._queueBeingFlushed.length && this.globalOptions.mustYield && this.globalOptions.mustYield()) {
55945 return 1
55946 /* Pause */
55947 ;
55948 }
55949 }
55950 }
55951
55952 if (after !== undefined) {
55953 after();
55954 }
55955
55956 this._queueBeingFlushed.length = 0;
55957 this.index = 0;
55958
55959 if (sync !== false && this._queue.length > 0) {
55960 // check if new items have been added
55961 this.flush(true);
55962 }
55963 }
55964
55965 hasWork() {
55966 return this._queueBeingFlushed.length > 0 || this._queue.length > 0;
55967 }
55968
55969 cancel({
55970 target,
55971 method
55972 }) {
55973 var queue = this._queue;
55974 var targetQueueMap = this.targetQueues.get(target);
55975
55976 if (targetQueueMap !== undefined) {
55977 targetQueueMap.delete(method);
55978 }
55979
55980 var index = findItem(target, method, queue);
55981
55982 if (index > -1) {
55983 queue.splice(index, QUEUE_ITEM_LENGTH);
55984 return true;
55985 } // if not found in current queue
55986 // could be in the queue that is being flushed
55987
55988
55989 queue = this._queueBeingFlushed;
55990 index = findItem(target, method, queue);
55991
55992 if (index > -1) {
55993 queue[index + 1] = null;
55994 return true;
55995 }
55996
55997 return false;
55998 }
55999
56000 push(target, method, args, stack) {
56001 this._queue.push(target, method, args, stack);
56002
56003 return {
56004 queue: this,
56005 target,
56006 method
56007 };
56008 }
56009
56010 pushUnique(target, method, args, stack) {
56011 var localQueueMap = this.targetQueues.get(target);
56012
56013 if (localQueueMap === undefined) {
56014 localQueueMap = new Map();
56015 this.targetQueues.set(target, localQueueMap);
56016 }
56017
56018 var index = localQueueMap.get(method);
56019
56020 if (index === undefined) {
56021 var queueIndex = this._queue.push(target, method, args, stack) - QUEUE_ITEM_LENGTH;
56022 localQueueMap.set(method, queueIndex);
56023 } else {
56024 var queue = this._queue;
56025 queue[index + 2] = args; // replace args
56026
56027 queue[index + 3] = stack; // replace stack
56028 }
56029
56030 return {
56031 queue: this,
56032 target,
56033 method
56034 };
56035 }
56036
56037 _getDebugInfo(debugEnabled) {
56038 if (debugEnabled) {
56039 var debugInfo = getQueueItems(this._queue, QUEUE_ITEM_LENGTH);
56040 return debugInfo;
56041 }
56042
56043 return undefined;
56044 }
56045
56046 invoke(target, method, args
56047 /*, onError, errorRecordedForStack */
56048 ) {
56049 if (args === undefined) {
56050 method.call(target);
56051 } else {
56052 method.apply(target, args);
56053 }
56054 }
56055
56056 invokeWithOnError(target, method, args, onError, errorRecordedForStack) {
56057 try {
56058 if (args === undefined) {
56059 method.call(target);
56060 } else {
56061 method.apply(target, args);
56062 }
56063 } catch (error) {
56064 onError(error, errorRecordedForStack);
56065 }
56066 }
56067
56068 }
56069
56070 class DeferredActionQueues {
56071 constructor(queueNames = [], options) {
56072 this.queues = {};
56073 this.queueNameIndex = 0;
56074 this.queueNames = queueNames;
56075 queueNames.reduce(function (queues, queueName) {
56076 queues[queueName] = new Queue(queueName, options[queueName], options);
56077 return queues;
56078 }, this.queues);
56079 }
56080 /**
56081 * @method schedule
56082 * @param {String} queueName
56083 * @param {Any} target
56084 * @param {Any} method
56085 * @param {Any} args
56086 * @param {Boolean} onceFlag
56087 * @param {Any} stack
56088 * @return queue
56089 */
56090
56091
56092 schedule(queueName, target, method, args, onceFlag, stack) {
56093 var queues = this.queues;
56094 var queue = queues[queueName];
56095
56096 if (queue === undefined) {
56097 throw new Error(`You attempted to schedule an action in a queue (${queueName}) that doesn\'t exist`);
56098 }
56099
56100 if (method === undefined || method === null) {
56101 throw new Error(`You attempted to schedule an action in a queue (${queueName}) for a method that doesn\'t exist`);
56102 }
56103
56104 this.queueNameIndex = 0;
56105
56106 if (onceFlag) {
56107 return queue.pushUnique(target, method, args, stack);
56108 } else {
56109 return queue.push(target, method, args, stack);
56110 }
56111 }
56112 /**
56113 * DeferredActionQueues.flush() calls Queue.flush()
56114 *
56115 * @method flush
56116 * @param {Boolean} fromAutorun
56117 */
56118
56119
56120 flush(fromAutorun = false) {
56121 var queue;
56122 var queueName;
56123 var numberOfQueues = this.queueNames.length;
56124
56125 while (this.queueNameIndex < numberOfQueues) {
56126 queueName = this.queueNames[this.queueNameIndex];
56127 queue = this.queues[queueName];
56128
56129 if (queue.hasWork() === false) {
56130 this.queueNameIndex++;
56131
56132 if (fromAutorun && this.queueNameIndex < numberOfQueues) {
56133 return 1
56134 /* Pause */
56135 ;
56136 }
56137 } else {
56138 if (queue.flush(false
56139 /* async */
56140 ) === 1
56141 /* Pause */
56142 ) {
56143 return 1
56144 /* Pause */
56145 ;
56146 }
56147 }
56148 }
56149 }
56150 /**
56151 * Returns debug information for the current queues.
56152 *
56153 * @method _getDebugInfo
56154 * @param {Boolean} debugEnabled
56155 * @returns {IDebugInfo | undefined}
56156 */
56157
56158
56159 _getDebugInfo(debugEnabled) {
56160 if (debugEnabled) {
56161 var debugInfo = {};
56162 var queue;
56163 var queueName;
56164 var numberOfQueues = this.queueNames.length;
56165 var i = 0;
56166
56167 while (i < numberOfQueues) {
56168 queueName = this.queueNames[i];
56169 queue = this.queues[queueName];
56170 debugInfo[queueName] = queue._getDebugInfo(debugEnabled);
56171 i++;
56172 }
56173
56174 return debugInfo;
56175 }
56176
56177 return;
56178 }
56179
56180 }
56181
56182 function iteratorDrain(fn) {
56183 var iterator = fn();
56184 var result = iterator.next();
56185
56186 while (result.done === false) {
56187 result.value();
56188 result = iterator.next();
56189 }
56190 }
56191
56192 var noop = function () {};
56193
56194 var DISABLE_SCHEDULE = Object.freeze([]);
56195
56196 function parseArgs() {
56197 var length = arguments.length;
56198 var args;
56199 var method;
56200 var target;
56201
56202 if (length === 0) {} else if (length === 1) {
56203 target = null;
56204 method = arguments[0];
56205 } else {
56206 var argsIndex = 2;
56207 var methodOrTarget = arguments[0];
56208 var methodOrArgs = arguments[1];
56209 var type = typeof methodOrArgs;
56210
56211 if (type === 'function') {
56212 target = methodOrTarget;
56213 method = methodOrArgs;
56214 } else if (methodOrTarget !== null && type === 'string' && methodOrArgs in methodOrTarget) {
56215 target = methodOrTarget;
56216 method = target[methodOrArgs];
56217 } else if (typeof methodOrTarget === 'function') {
56218 argsIndex = 1;
56219 target = null;
56220 method = methodOrTarget;
56221 }
56222
56223 if (length > argsIndex) {
56224 var len = length - argsIndex;
56225 args = new Array(len);
56226
56227 for (var i = 0; i < len; i++) {
56228 args[i] = arguments[i + argsIndex];
56229 }
56230 }
56231 }
56232
56233 return [target, method, args];
56234 }
56235
56236 function parseTimerArgs() {
56237 var [target, method, args] = parseArgs(...arguments);
56238 var wait = 0;
56239 var length = args !== undefined ? args.length : 0;
56240
56241 if (length > 0) {
56242 var last = args[length - 1];
56243
56244 if (isCoercableNumber(last)) {
56245 wait = parseInt(args.pop(), 10);
56246 }
56247 }
56248
56249 return [target, method, args, wait];
56250 }
56251
56252 function parseDebounceArgs() {
56253 var target;
56254 var method;
56255 var isImmediate;
56256 var args;
56257 var wait;
56258
56259 if (arguments.length === 2) {
56260 method = arguments[0];
56261 wait = arguments[1];
56262 target = null;
56263 } else {
56264 [target, method, args] = parseArgs(...arguments);
56265
56266 if (args === undefined) {
56267 wait = 0;
56268 } else {
56269 wait = args.pop();
56270
56271 if (!isCoercableNumber(wait)) {
56272 isImmediate = wait === true;
56273 wait = args.pop();
56274 }
56275 }
56276 }
56277
56278 wait = parseInt(wait, 10);
56279 return [target, method, args, wait, isImmediate];
56280 }
56281
56282 var UUID = 0;
56283 var beginCount = 0;
56284 var endCount = 0;
56285 var beginEventCount = 0;
56286 var endEventCount = 0;
56287 var runCount = 0;
56288 var joinCount = 0;
56289 var deferCount = 0;
56290 var scheduleCount = 0;
56291 var scheduleIterableCount = 0;
56292 var deferOnceCount = 0;
56293 var scheduleOnceCount = 0;
56294 var setTimeoutCount = 0;
56295 var laterCount = 0;
56296 var throttleCount = 0;
56297 var debounceCount = 0;
56298 var cancelTimersCount = 0;
56299 var cancelCount = 0;
56300 var autorunsCreatedCount = 0;
56301 var autorunsCompletedCount = 0;
56302 var deferredActionQueuesCreatedCount = 0;
56303 var nestedDeferredActionQueuesCreated = 0;
56304
56305 class Backburner {
56306 constructor(queueNames, options) {
56307 this.DEBUG = false;
56308 this.currentInstance = null;
56309 this.instanceStack = [];
56310 this._eventCallbacks = {
56311 end: [],
56312 begin: []
56313 };
56314 this._timerTimeoutId = null;
56315 this._timers = [];
56316 this._autorun = false;
56317 this._autorunStack = null;
56318 this.queueNames = queueNames;
56319 this.options = options || {};
56320
56321 if (typeof this.options.defaultQueue === 'string') {
56322 this._defaultQueue = this.options.defaultQueue;
56323 } else {
56324 this._defaultQueue = this.queueNames[0];
56325 }
56326
56327 this._onBegin = this.options.onBegin || noop;
56328 this._onEnd = this.options.onEnd || noop;
56329 this._boundRunExpiredTimers = this._runExpiredTimers.bind(this);
56330
56331 this._boundAutorunEnd = () => {
56332 autorunsCompletedCount++; // if the autorun was already flushed, do nothing
56333
56334 if (this._autorun === false) {
56335 return;
56336 }
56337
56338 this._autorun = false;
56339 this._autorunStack = null;
56340
56341 this._end(true
56342 /* fromAutorun */
56343 );
56344 };
56345
56346 var builder = this.options._buildPlatform || buildPlatform;
56347 this._platform = builder(this._boundAutorunEnd);
56348 }
56349
56350 get counters() {
56351 return {
56352 begin: beginCount,
56353 end: endCount,
56354 events: {
56355 begin: beginEventCount,
56356 end: endEventCount
56357 },
56358 autoruns: {
56359 created: autorunsCreatedCount,
56360 completed: autorunsCompletedCount
56361 },
56362 run: runCount,
56363 join: joinCount,
56364 defer: deferCount,
56365 schedule: scheduleCount,
56366 scheduleIterable: scheduleIterableCount,
56367 deferOnce: deferOnceCount,
56368 scheduleOnce: scheduleOnceCount,
56369 setTimeout: setTimeoutCount,
56370 later: laterCount,
56371 throttle: throttleCount,
56372 debounce: debounceCount,
56373 cancelTimers: cancelTimersCount,
56374 cancel: cancelCount,
56375 loops: {
56376 total: deferredActionQueuesCreatedCount,
56377 nested: nestedDeferredActionQueuesCreated
56378 }
56379 };
56380 }
56381
56382 get defaultQueue() {
56383 return this._defaultQueue;
56384 }
56385 /*
56386 @method begin
56387 @return instantiated class DeferredActionQueues
56388 */
56389
56390
56391 begin() {
56392 beginCount++;
56393 var options = this.options;
56394 var previousInstance = this.currentInstance;
56395 var current;
56396
56397 if (this._autorun !== false) {
56398 current = previousInstance;
56399
56400 this._cancelAutorun();
56401 } else {
56402 if (previousInstance !== null) {
56403 nestedDeferredActionQueuesCreated++;
56404 this.instanceStack.push(previousInstance);
56405 }
56406
56407 deferredActionQueuesCreatedCount++;
56408 current = this.currentInstance = new DeferredActionQueues(this.queueNames, options);
56409 beginEventCount++;
56410
56411 this._trigger('begin', current, previousInstance);
56412 }
56413
56414 this._onBegin(current, previousInstance);
56415
56416 return current;
56417 }
56418
56419 end() {
56420 endCount++;
56421
56422 this._end(false);
56423 }
56424
56425 on(eventName, callback) {
56426 if (typeof callback !== 'function') {
56427 throw new TypeError(`Callback must be a function`);
56428 }
56429
56430 var callbacks = this._eventCallbacks[eventName];
56431
56432 if (callbacks !== undefined) {
56433 callbacks.push(callback);
56434 } else {
56435 throw new TypeError(`Cannot on() event ${eventName} because it does not exist`);
56436 }
56437 }
56438
56439 off(eventName, callback) {
56440 var callbacks = this._eventCallbacks[eventName];
56441
56442 if (!eventName || callbacks === undefined) {
56443 throw new TypeError(`Cannot off() event ${eventName} because it does not exist`);
56444 }
56445
56446 var callbackFound = false;
56447
56448 if (callback) {
56449 for (var i = 0; i < callbacks.length; i++) {
56450 if (callbacks[i] === callback) {
56451 callbackFound = true;
56452 callbacks.splice(i, 1);
56453 i--;
56454 }
56455 }
56456 }
56457
56458 if (!callbackFound) {
56459 throw new TypeError(`Cannot off() callback that does not exist`);
56460 }
56461 }
56462
56463 run() {
56464 runCount++;
56465 var [target, method, args] = parseArgs(...arguments);
56466 return this._run(target, method, args);
56467 }
56468
56469 join() {
56470 joinCount++;
56471 var [target, method, args] = parseArgs(...arguments);
56472 return this._join(target, method, args);
56473 }
56474 /**
56475 * @deprecated please use schedule instead.
56476 */
56477
56478
56479 defer(queueName, target, method, ...args) {
56480 deferCount++;
56481 return this.schedule(queueName, target, method, ...args);
56482 }
56483
56484 schedule(queueName, ..._args) {
56485 scheduleCount++;
56486 var [target, method, args] = parseArgs(..._args);
56487 var stack = this.DEBUG ? new Error() : undefined;
56488 return this._ensureInstance().schedule(queueName, target, method, args, false, stack);
56489 }
56490 /*
56491 Defer the passed iterable of functions to run inside the specified queue.
56492 @method scheduleIterable
56493 @param {String} queueName
56494 @param {Iterable} an iterable of functions to execute
56495 @return method result
56496 */
56497
56498
56499 scheduleIterable(queueName, iterable) {
56500 scheduleIterableCount++;
56501 var stack = this.DEBUG ? new Error() : undefined;
56502 return this._ensureInstance().schedule(queueName, null, iteratorDrain, [iterable], false, stack);
56503 }
56504 /**
56505 * @deprecated please use scheduleOnce instead.
56506 */
56507
56508
56509 deferOnce(queueName, target, method, ...args) {
56510 deferOnceCount++;
56511 return this.scheduleOnce(queueName, target, method, ...args);
56512 }
56513
56514 scheduleOnce(queueName, ..._args) {
56515 scheduleOnceCount++;
56516 var [target, method, args] = parseArgs(..._args);
56517 var stack = this.DEBUG ? new Error() : undefined;
56518 return this._ensureInstance().schedule(queueName, target, method, args, true, stack);
56519 }
56520
56521 setTimeout() {
56522 setTimeoutCount++;
56523 return this.later(...arguments);
56524 }
56525
56526 later() {
56527 laterCount++;
56528 var [target, method, args, wait] = parseTimerArgs(...arguments);
56529 return this._later(target, method, args, wait);
56530 }
56531
56532 throttle() {
56533 throttleCount++;
56534 var [target, method, args, wait, isImmediate = true] = parseDebounceArgs(...arguments);
56535 var index = findTimerItem(target, method, this._timers);
56536 var timerId;
56537
56538 if (index === -1) {
56539 timerId = this._later(target, method, isImmediate ? DISABLE_SCHEDULE : args, wait);
56540
56541 if (isImmediate) {
56542 this._join(target, method, args);
56543 }
56544 } else {
56545 timerId = this._timers[index + 1];
56546 var argIndex = index + 4;
56547
56548 if (this._timers[argIndex] !== DISABLE_SCHEDULE) {
56549 this._timers[argIndex] = args;
56550 }
56551 }
56552
56553 return timerId;
56554 }
56555
56556 debounce() {
56557 debounceCount++;
56558 var [target, method, args, wait, isImmediate = false] = parseDebounceArgs(...arguments);
56559 var _timers = this._timers;
56560 var index = findTimerItem(target, method, _timers);
56561 var timerId;
56562
56563 if (index === -1) {
56564 timerId = this._later(target, method, isImmediate ? DISABLE_SCHEDULE : args, wait);
56565
56566 if (isImmediate) {
56567 this._join(target, method, args);
56568 }
56569 } else {
56570 var executeAt = this._platform.now() + wait;
56571 var argIndex = index + 4;
56572
56573 if (_timers[argIndex] === DISABLE_SCHEDULE) {
56574 args = DISABLE_SCHEDULE;
56575 }
56576
56577 timerId = _timers[index + 1];
56578 var i = binarySearch(executeAt, _timers);
56579
56580 if (index + TIMERS_OFFSET === i) {
56581 _timers[index] = executeAt;
56582 _timers[argIndex] = args;
56583 } else {
56584 var stack = this._timers[index + 5];
56585
56586 this._timers.splice(i, 0, executeAt, timerId, target, method, args, stack);
56587
56588 this._timers.splice(index, TIMERS_OFFSET);
56589 }
56590
56591 if (index === 0) {
56592 this._reinstallTimerTimeout();
56593 }
56594 }
56595
56596 return timerId;
56597 }
56598
56599 cancelTimers() {
56600 cancelTimersCount++;
56601
56602 this._clearTimerTimeout();
56603
56604 this._timers = [];
56605
56606 this._cancelAutorun();
56607 }
56608
56609 hasTimers() {
56610 return this._timers.length > 0 || this._autorun;
56611 }
56612
56613 cancel(timer) {
56614 cancelCount++;
56615
56616 if (timer === null || timer === undefined) {
56617 return false;
56618 }
56619
56620 var timerType = typeof timer;
56621
56622 if (timerType === 'number') {
56623 // we're cancelling a setTimeout or throttle or debounce
56624 return this._cancelLaterTimer(timer);
56625 } else if (timerType === 'object' && timer.queue && timer.method) {
56626 // we're cancelling a deferOnce
56627 return timer.queue.cancel(timer);
56628 }
56629
56630 return false;
56631 }
56632
56633 ensureInstance() {
56634 this._ensureInstance();
56635 }
56636 /**
56637 * Returns debug information related to the current instance of Backburner
56638 *
56639 * @method getDebugInfo
56640 * @returns {Object | undefined} Will return and Object containing debug information if
56641 * the DEBUG flag is set to true on the current instance of Backburner, else undefined.
56642 */
56643
56644
56645 getDebugInfo() {
56646 if (this.DEBUG) {
56647 return {
56648 autorun: this._autorunStack,
56649 counters: this.counters,
56650 timers: getQueueItems(this._timers, TIMERS_OFFSET, 2),
56651 instanceStack: [this.currentInstance, ...this.instanceStack].map(deferredActionQueue => deferredActionQueue && deferredActionQueue._getDebugInfo(this.DEBUG))
56652 };
56653 }
56654
56655 return undefined;
56656 }
56657
56658 _end(fromAutorun) {
56659 var currentInstance = this.currentInstance;
56660 var nextInstance = null;
56661
56662 if (currentInstance === null) {
56663 throw new Error(`end called without begin`);
56664 } // Prevent double-finally bug in Safari 6.0.2 and iOS 6
56665 // This bug appears to be resolved in Safari 6.0.5 and iOS 7
56666
56667
56668 var finallyAlreadyCalled = false;
56669 var result;
56670
56671 try {
56672 result = currentInstance.flush(fromAutorun);
56673 } finally {
56674 if (!finallyAlreadyCalled) {
56675 finallyAlreadyCalled = true;
56676
56677 if (result === 1
56678 /* Pause */
56679 ) {
56680 var plannedNextQueue = this.queueNames[currentInstance.queueNameIndex];
56681
56682 this._scheduleAutorun(plannedNextQueue);
56683 } else {
56684 this.currentInstance = null;
56685
56686 if (this.instanceStack.length > 0) {
56687 nextInstance = this.instanceStack.pop();
56688 this.currentInstance = nextInstance;
56689 }
56690
56691 this._trigger('end', currentInstance, nextInstance);
56692
56693 this._onEnd(currentInstance, nextInstance);
56694 }
56695 }
56696 }
56697 }
56698
56699 _join(target, method, args) {
56700 if (this.currentInstance === null) {
56701 return this._run(target, method, args);
56702 }
56703
56704 if (target === undefined && args === undefined) {
56705 return method();
56706 } else {
56707 return method.apply(target, args);
56708 }
56709 }
56710
56711 _run(target, method, args) {
56712 var onError = getOnError(this.options);
56713 this.begin();
56714
56715 if (onError) {
56716 try {
56717 return method.apply(target, args);
56718 } catch (error) {
56719 onError(error);
56720 } finally {
56721 this.end();
56722 }
56723 } else {
56724 try {
56725 return method.apply(target, args);
56726 } finally {
56727 this.end();
56728 }
56729 }
56730 }
56731
56732 _cancelAutorun() {
56733 if (this._autorun) {
56734 this._platform.clearNext();
56735
56736 this._autorun = false;
56737 this._autorunStack = null;
56738 }
56739 }
56740
56741 _later(target, method, args, wait) {
56742 var stack = this.DEBUG ? new Error() : undefined;
56743 var executeAt = this._platform.now() + wait;
56744 var id = UUID++;
56745
56746 if (this._timers.length === 0) {
56747 this._timers.push(executeAt, id, target, method, args, stack);
56748
56749 this._installTimerTimeout();
56750 } else {
56751 // find position to insert
56752 var i = binarySearch(executeAt, this._timers);
56753
56754 this._timers.splice(i, 0, executeAt, id, target, method, args, stack); // always reinstall since it could be out of sync
56755
56756
56757 this._reinstallTimerTimeout();
56758 }
56759
56760 return id;
56761 }
56762
56763 _cancelLaterTimer(timer) {
56764 for (var i = 1; i < this._timers.length; i += TIMERS_OFFSET) {
56765 if (this._timers[i] === timer) {
56766 this._timers.splice(i - 1, TIMERS_OFFSET);
56767
56768 if (i === 1) {
56769 this._reinstallTimerTimeout();
56770 }
56771
56772 return true;
56773 }
56774 }
56775
56776 return false;
56777 }
56778 /**
56779 Trigger an event. Supports up to two arguments. Designed around
56780 triggering transition events from one run loop instance to the
56781 next, which requires an argument for the instance and then
56782 an argument for the next instance.
56783 @private
56784 @method _trigger
56785 @param {String} eventName
56786 @param {any} arg1
56787 @param {any} arg2
56788 */
56789
56790
56791 _trigger(eventName, arg1, arg2) {
56792 var callbacks = this._eventCallbacks[eventName];
56793
56794 if (callbacks !== undefined) {
56795 for (var i = 0; i < callbacks.length; i++) {
56796 callbacks[i](arg1, arg2);
56797 }
56798 }
56799 }
56800
56801 _runExpiredTimers() {
56802 this._timerTimeoutId = null;
56803
56804 if (this._timers.length > 0) {
56805 this.begin();
56806
56807 this._scheduleExpiredTimers();
56808
56809 this.end();
56810 }
56811 }
56812
56813 _scheduleExpiredTimers() {
56814 var timers = this._timers;
56815 var i = 0;
56816 var l = timers.length;
56817 var defaultQueue = this._defaultQueue;
56818
56819 var n = this._platform.now();
56820
56821 for (; i < l; i += TIMERS_OFFSET) {
56822 var executeAt = timers[i];
56823
56824 if (executeAt > n) {
56825 break;
56826 }
56827
56828 var args = timers[i + 4];
56829
56830 if (args !== DISABLE_SCHEDULE) {
56831 var target = timers[i + 2];
56832 var method = timers[i + 3];
56833 var stack = timers[i + 5];
56834 this.currentInstance.schedule(defaultQueue, target, method, args, false, stack);
56835 }
56836 }
56837
56838 timers.splice(0, i);
56839
56840 this._installTimerTimeout();
56841 }
56842
56843 _reinstallTimerTimeout() {
56844 this._clearTimerTimeout();
56845
56846 this._installTimerTimeout();
56847 }
56848
56849 _clearTimerTimeout() {
56850 if (this._timerTimeoutId === null) {
56851 return;
56852 }
56853
56854 this._platform.clearTimeout(this._timerTimeoutId);
56855
56856 this._timerTimeoutId = null;
56857 }
56858
56859 _installTimerTimeout() {
56860 if (this._timers.length === 0) {
56861 return;
56862 }
56863
56864 var minExpiresAt = this._timers[0];
56865
56866 var n = this._platform.now();
56867
56868 var wait = Math.max(0, minExpiresAt - n);
56869 this._timerTimeoutId = this._platform.setTimeout(this._boundRunExpiredTimers, wait);
56870 }
56871
56872 _ensureInstance() {
56873 var currentInstance = this.currentInstance;
56874
56875 if (currentInstance === null) {
56876 this._autorunStack = this.DEBUG ? new Error() : undefined;
56877 currentInstance = this.begin();
56878
56879 this._scheduleAutorun(this.queueNames[0]);
56880 }
56881
56882 return currentInstance;
56883 }
56884
56885 _scheduleAutorun(plannedNextQueue) {
56886 autorunsCreatedCount++;
56887 var next = this._platform.next;
56888 var flush = this.options.flush;
56889
56890 if (flush) {
56891 flush(plannedNextQueue, next);
56892 } else {
56893 next();
56894 }
56895
56896 this._autorun = true;
56897 }
56898
56899 }
56900
56901 Backburner.Queue = Queue;
56902 Backburner.buildPlatform = buildPlatform;
56903 Backburner.buildNext = buildNext;
56904 var _default = Backburner;
56905 _exports.default = _default;
56906});
56907define("dag-map", ["exports"], function (_exports) {
56908 "use strict";
56909
56910 Object.defineProperty(_exports, "__esModule", {
56911 value: true
56912 });
56913 _exports.default = void 0;
56914
56915 /**
56916 * A topologically ordered map of key/value pairs with a simple API for adding constraints.
56917 *
56918 * Edges can forward reference keys that have not been added yet (the forward reference will
56919 * map the key to undefined).
56920 */
56921 var DAG = function () {
56922 function DAG() {
56923 this._vertices = new Vertices();
56924 }
56925 /**
56926 * Adds a key/value pair with dependencies on other key/value pairs.
56927 *
56928 * @public
56929 * @param key The key of the vertex to be added.
56930 * @param value The value of that vertex.
56931 * @param before A key or array of keys of the vertices that must
56932 * be visited before this vertex.
56933 * @param after An string or array of strings with the keys of the
56934 * vertices that must be after this vertex is visited.
56935 */
56936
56937
56938 DAG.prototype.add = function (key, value, before, after) {
56939 if (!key) throw new Error('argument `key` is required');
56940 var vertices = this._vertices;
56941 var v = vertices.add(key);
56942 v.val = value;
56943
56944 if (before) {
56945 if (typeof before === "string") {
56946 vertices.addEdge(v, vertices.add(before));
56947 } else {
56948 for (var i = 0; i < before.length; i++) {
56949 vertices.addEdge(v, vertices.add(before[i]));
56950 }
56951 }
56952 }
56953
56954 if (after) {
56955 if (typeof after === "string") {
56956 vertices.addEdge(vertices.add(after), v);
56957 } else {
56958 for (var i = 0; i < after.length; i++) {
56959 vertices.addEdge(vertices.add(after[i]), v);
56960 }
56961 }
56962 }
56963 };
56964 /**
56965 * @deprecated please use add.
56966 */
56967
56968
56969 DAG.prototype.addEdges = function (key, value, before, after) {
56970 this.add(key, value, before, after);
56971 };
56972 /**
56973 * Visits key/value pairs in topological order.
56974 *
56975 * @public
56976 * @param callback The function to be invoked with each key/value.
56977 */
56978
56979
56980 DAG.prototype.each = function (callback) {
56981 this._vertices.walk(callback);
56982 };
56983 /**
56984 * @deprecated please use each.
56985 */
56986
56987
56988 DAG.prototype.topsort = function (callback) {
56989 this.each(callback);
56990 };
56991
56992 return DAG;
56993 }();
56994
56995 var _default = DAG;
56996 /** @private */
56997
56998 _exports.default = _default;
56999
57000 var Vertices = function () {
57001 function Vertices() {
57002 this.length = 0;
57003 this.stack = new IntStack();
57004 this.path = new IntStack();
57005 this.result = new IntStack();
57006 }
57007
57008 Vertices.prototype.add = function (key) {
57009 if (!key) throw new Error("missing key");
57010 var l = this.length | 0;
57011 var vertex;
57012
57013 for (var i = 0; i < l; i++) {
57014 vertex = this[i];
57015 if (vertex.key === key) return vertex;
57016 }
57017
57018 this.length = l + 1;
57019 return this[l] = {
57020 idx: l,
57021 key: key,
57022 val: undefined,
57023 out: false,
57024 flag: false,
57025 length: 0
57026 };
57027 };
57028
57029 Vertices.prototype.addEdge = function (v, w) {
57030 this.check(v, w.key);
57031 var l = w.length | 0;
57032
57033 for (var i = 0; i < l; i++) {
57034 if (w[i] === v.idx) return;
57035 }
57036
57037 w.length = l + 1;
57038 w[l] = v.idx;
57039 v.out = true;
57040 };
57041
57042 Vertices.prototype.walk = function (cb) {
57043 this.reset();
57044
57045 for (var i = 0; i < this.length; i++) {
57046 var vertex = this[i];
57047 if (vertex.out) continue;
57048 this.visit(vertex, "");
57049 }
57050
57051 this.each(this.result, cb);
57052 };
57053
57054 Vertices.prototype.check = function (v, w) {
57055 if (v.key === w) {
57056 throw new Error("cycle detected: " + w + " <- " + w);
57057 } // quick check
57058
57059
57060 if (v.length === 0) return; // shallow check
57061
57062 for (var i = 0; i < v.length; i++) {
57063 var key = this[v[i]].key;
57064
57065 if (key === w) {
57066 throw new Error("cycle detected: " + w + " <- " + v.key + " <- " + w);
57067 }
57068 } // deep check
57069
57070
57071 this.reset();
57072 this.visit(v, w);
57073
57074 if (this.path.length > 0) {
57075 var msg_1 = "cycle detected: " + w;
57076 this.each(this.path, function (key) {
57077 msg_1 += " <- " + key;
57078 });
57079 throw new Error(msg_1);
57080 }
57081 };
57082
57083 Vertices.prototype.reset = function () {
57084 this.stack.length = 0;
57085 this.path.length = 0;
57086 this.result.length = 0;
57087
57088 for (var i = 0, l = this.length; i < l; i++) {
57089 this[i].flag = false;
57090 }
57091 };
57092
57093 Vertices.prototype.visit = function (start, search) {
57094 var _a = this,
57095 stack = _a.stack,
57096 path = _a.path,
57097 result = _a.result;
57098
57099 stack.push(start.idx);
57100
57101 while (stack.length) {
57102 var index = stack.pop() | 0;
57103
57104 if (index >= 0) {
57105 // enter
57106 var vertex = this[index];
57107 if (vertex.flag) continue;
57108 vertex.flag = true;
57109 path.push(index);
57110 if (search === vertex.key) break; // push exit
57111
57112 stack.push(~index);
57113 this.pushIncoming(vertex);
57114 } else {
57115 // exit
57116 path.pop();
57117 result.push(~index);
57118 }
57119 }
57120 };
57121
57122 Vertices.prototype.pushIncoming = function (incomming) {
57123 var stack = this.stack;
57124
57125 for (var i = incomming.length - 1; i >= 0; i--) {
57126 var index = incomming[i];
57127
57128 if (!this[index].flag) {
57129 stack.push(index);
57130 }
57131 }
57132 };
57133
57134 Vertices.prototype.each = function (indices, cb) {
57135 for (var i = 0, l = indices.length; i < l; i++) {
57136 var vertex = this[indices[i]];
57137 cb(vertex.key, vertex.val);
57138 }
57139 };
57140
57141 return Vertices;
57142 }();
57143 /** @private */
57144
57145
57146 var IntStack = function () {
57147 function IntStack() {
57148 this.length = 0;
57149 }
57150
57151 IntStack.prototype.push = function (n) {
57152 this[this.length++] = n | 0;
57153 };
57154
57155 IntStack.prototype.pop = function () {
57156 return this[--this.length] | 0;
57157 };
57158
57159 return IntStack;
57160 }();
57161});
57162define("ember-babel", ["exports"], function (_exports) {
57163 "use strict";
57164
57165 Object.defineProperty(_exports, "__esModule", {
57166 value: true
57167 });
57168 _exports.wrapNativeSuper = wrapNativeSuper;
57169 _exports.classCallCheck = classCallCheck;
57170 _exports.inheritsLoose = inheritsLoose;
57171 _exports.taggedTemplateLiteralLoose = taggedTemplateLiteralLoose;
57172 _exports.createClass = createClass;
57173 _exports.assertThisInitialized = assertThisInitialized;
57174 _exports.possibleConstructorReturn = possibleConstructorReturn;
57175 _exports.objectDestructuringEmpty = objectDestructuringEmpty;
57176 _exports.createSuper = createSuper;
57177 _exports.createForOfIteratorHelperLoose = createForOfIteratorHelperLoose;
57178
57179 /* globals Reflect */
57180 var setPrototypeOf = Object.setPrototypeOf;
57181 var getPrototypeOf = Object.getPrototypeOf;
57182 var hasReflectConstruct = typeof Reflect === 'object' && typeof Reflect.construct === 'function';
57183 var nativeWrapperCache = new Map(); // Super minimal version of Babel's wrapNativeSuper. We only use this for
57184 // extending Function, for ComputedDecoratorImpl and AliasDecoratorImpl. We know
57185 // we will never directly create an instance of these classes so no need to
57186 // include `construct` code or other helpers.
57187
57188 function wrapNativeSuper(Class) {
57189 if (nativeWrapperCache.has(Class)) {
57190 return nativeWrapperCache.get(Class);
57191 }
57192
57193 function Wrapper() {}
57194
57195 Wrapper.prototype = Object.create(Class.prototype, {
57196 constructor: {
57197 value: Wrapper,
57198 enumerable: false,
57199 writable: true,
57200 configurable: true
57201 }
57202 });
57203 nativeWrapperCache.set(Class, Wrapper);
57204 return setPrototypeOf(Wrapper, Class);
57205 }
57206
57207 function classCallCheck(instance, Constructor) {
57208 if (true
57209 /* DEBUG */
57210 ) {
57211 if (!(instance instanceof Constructor)) {
57212 throw new TypeError('Cannot call a class as a function');
57213 }
57214 }
57215 }
57216 /*
57217 Overrides default `inheritsLoose` to _also_ call `Object.setPrototypeOf`.
57218 This is needed so that we can use `loose` option with the
57219 `@babel/plugin-transform-classes` (because we want simple assignment to the
57220 prototype wherever possible) but also keep our constructor based prototypal
57221 inheritance working properly
57222 */
57223
57224
57225 function inheritsLoose(subClass, superClass) {
57226 if (true
57227 /* DEBUG */
57228 ) {
57229 if (typeof superClass !== 'function' && superClass !== null) {
57230 throw new TypeError('Super expression must either be null or a function');
57231 }
57232 }
57233
57234 subClass.prototype = Object.create(superClass === null ? null : superClass.prototype, {
57235 constructor: {
57236 value: subClass,
57237 writable: true,
57238 configurable: true
57239 }
57240 });
57241
57242 if (superClass !== null) {
57243 setPrototypeOf(subClass, superClass);
57244 }
57245 }
57246
57247 function taggedTemplateLiteralLoose(strings, raw) {
57248 if (!raw) {
57249 raw = strings.slice(0);
57250 }
57251
57252 strings.raw = raw;
57253 return strings;
57254 }
57255
57256 function _defineProperties(target, props) {
57257 for (var i = 0; i < props.length; i++) {
57258 var descriptor = props[i];
57259 descriptor.enumerable = descriptor.enumerable || false;
57260 descriptor.configurable = true;
57261 if ('value' in descriptor) descriptor.writable = true;
57262 Object.defineProperty(target, descriptor.key, descriptor);
57263 }
57264 }
57265 /*
57266 Differs from default implementation by avoiding boolean coercion of
57267 `protoProps` and `staticProps`.
57268 */
57269
57270
57271 function createClass(Constructor, protoProps, staticProps) {
57272 if (protoProps !== null && protoProps !== undefined) {
57273 _defineProperties(Constructor.prototype, protoProps);
57274 }
57275
57276 if (staticProps !== null && staticProps !== undefined) {
57277 _defineProperties(Constructor, staticProps);
57278 }
57279
57280 return Constructor;
57281 }
57282
57283 function assertThisInitialized(self) {
57284 if (true
57285 /* DEBUG */
57286 && self === void 0) {
57287 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
57288 }
57289
57290 return self;
57291 }
57292 /*
57293 Adds `DEBUG` guard to error being thrown, and avoids boolean coercion of `call`.
57294 */
57295
57296
57297 function possibleConstructorReturn(self, call) {
57298 if (typeof call === 'object' && call !== null || typeof call === 'function') {
57299 return call;
57300 }
57301
57302 return assertThisInitialized(self);
57303 }
57304
57305 function objectDestructuringEmpty(obj) {
57306 if (true
57307 /* DEBUG */
57308 && (obj === null || obj === undefined)) {
57309 throw new TypeError('Cannot destructure undefined');
57310 }
57311 }
57312 /*
57313 Differs from default implementation by checking for _any_ `Reflect.construct`
57314 (the default implementation tries to ensure that `Reflect.construct` is truly
57315 the native one).
57316
57317 Original source: https://github.com/babel/babel/blob/v7.9.2/packages/babel-helpers/src/helpers.js#L738-L757
57318 */
57319
57320
57321 function createSuper(Derived) {
57322 return function () {
57323 var Super = getPrototypeOf(Derived);
57324 var result;
57325
57326 if (hasReflectConstruct) {
57327 // NOTE: This doesn't work if this.__proto__.constructor has been modified.
57328 var NewTarget = getPrototypeOf(this).constructor;
57329 result = Reflect.construct(Super, arguments, NewTarget);
57330 } else {
57331 result = Super.apply(this, arguments);
57332 }
57333
57334 return possibleConstructorReturn(this, result);
57335 };
57336 }
57337 /*
57338 Does not differ from default implementation.
57339 */
57340
57341
57342 function arrayLikeToArray(arr, len) {
57343 if (len == null || len > arr.length) len = arr.length;
57344 var arr2 = new Array(len);
57345
57346 for (var i = 0; i < len; i++) {
57347 arr2[i] = arr[i];
57348 }
57349
57350 return arr2;
57351 }
57352 /*
57353 Does not differ from default implementation.
57354 */
57355
57356
57357 function unsupportedIterableToArray(o, minLen) {
57358 if (!o) return;
57359 if (typeof o === 'string') return arrayLikeToArray(o, minLen);
57360 var n = Object.prototype.toString.call(o).slice(8, -1);
57361 if (n === 'Object' && o.constructor) n = o.constructor.name;
57362 if (n === 'Map' || n === 'Set') return Array.from(n);
57363 if (n === 'Arguments' || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
57364 }
57365 /*
57366 Does not differ from default implementation.
57367 */
57368
57369
57370 function createForOfIteratorHelperLoose(o) {
57371 var i = 0;
57372
57373 if (typeof Symbol === 'undefined' || o[Symbol.iterator] == null) {
57374 // Fallback for engines without symbol support
57375 if (Array.isArray(o) || (o = unsupportedIterableToArray(o))) return function () {
57376 if (i >= o.length) return {
57377 done: true
57378 };
57379 return {
57380 done: false,
57381 value: o[i++]
57382 };
57383 };
57384 throw new TypeError('Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.');
57385 }
57386
57387 i = o[Symbol.iterator]();
57388 return i.next.bind(i);
57389 }
57390});
57391define("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, _support, _application, _rsvp, _helpers, _initializers) {
57392 "use strict";
57393
57394 Object.defineProperty(_exports, "__esModule", {
57395 value: true
57396 });
57397 Object.defineProperty(_exports, "Test", {
57398 enumerable: true,
57399 get: function () {
57400 return _test.default;
57401 }
57402 });
57403 Object.defineProperty(_exports, "Adapter", {
57404 enumerable: true,
57405 get: function () {
57406 return _adapter.default;
57407 }
57408 });
57409 Object.defineProperty(_exports, "setupForTesting", {
57410 enumerable: true,
57411 get: function () {
57412 return _setup_for_testing.default;
57413 }
57414 });
57415 Object.defineProperty(_exports, "QUnitAdapter", {
57416 enumerable: true,
57417 get: function () {
57418 return _qunit.default;
57419 }
57420 });
57421});
57422define("ember-testing/lib/adapters/adapter", ["exports", "@ember/-internals/runtime"], function (_exports, _runtime) {
57423 "use strict";
57424
57425 Object.defineProperty(_exports, "__esModule", {
57426 value: true
57427 });
57428 _exports.default = void 0;
57429
57430 function K() {
57431 return this;
57432 }
57433 /**
57434 @module @ember/test
57435 */
57436
57437 /**
57438 The primary purpose of this class is to create hooks that can be implemented
57439 by an adapter for various test frameworks.
57440
57441 @class TestAdapter
57442 @public
57443 */
57444
57445
57446 var _default = _runtime.Object.extend({
57447 /**
57448 This callback will be called whenever an async operation is about to start.
57449 Override this to call your framework's methods that handle async
57450 operations.
57451 @public
57452 @method asyncStart
57453 */
57454 asyncStart: K,
57455
57456 /**
57457 This callback will be called whenever an async operation has completed.
57458 @public
57459 @method asyncEnd
57460 */
57461 asyncEnd: K,
57462
57463 /**
57464 Override this method with your testing framework's false assertion.
57465 This function is called whenever an exception occurs causing the testing
57466 promise to fail.
57467 QUnit example:
57468 ```javascript
57469 exception: function(error) {
57470 ok(false, error);
57471 };
57472 ```
57473 @public
57474 @method exception
57475 @param {String} error The exception to be raised.
57476 */
57477 exception(error) {
57478 throw error;
57479 }
57480
57481 });
57482
57483 _exports.default = _default;
57484});
57485define("ember-testing/lib/adapters/qunit", ["exports", "@ember/-internals/utils", "ember-testing/lib/adapters/adapter"], function (_exports, _utils, _adapter) {
57486 "use strict";
57487
57488 Object.defineProperty(_exports, "__esModule", {
57489 value: true
57490 });
57491 _exports.default = void 0;
57492
57493 /* globals QUnit */
57494
57495 /**
57496 @module ember
57497 */
57498
57499 /**
57500 This class implements the methods defined by TestAdapter for the
57501 QUnit testing framework.
57502
57503 @class QUnitAdapter
57504 @namespace Ember.Test
57505 @extends TestAdapter
57506 @public
57507 */
57508 var _default = _adapter.default.extend({
57509 init() {
57510 this.doneCallbacks = [];
57511 },
57512
57513 asyncStart() {
57514 if (typeof QUnit.stop === 'function') {
57515 // very old QUnit version
57516 QUnit.stop();
57517 } else {
57518 this.doneCallbacks.push(QUnit.config.current ? QUnit.config.current.assert.async() : null);
57519 }
57520 },
57521
57522 asyncEnd() {
57523 // checking for QUnit.stop here (even though we _need_ QUnit.start) because
57524 // QUnit.start() still exists in QUnit 2.x (it just throws an error when calling
57525 // inside a test context)
57526 if (typeof QUnit.stop === 'function') {
57527 QUnit.start();
57528 } else {
57529 var done = this.doneCallbacks.pop(); // This can be null if asyncStart() was called outside of a test
57530
57531 if (done) {
57532 done();
57533 }
57534 }
57535 },
57536
57537 exception(error) {
57538 QUnit.config.current.assert.ok(false, (0, _utils.inspect)(error));
57539 }
57540
57541 });
57542
57543 _exports.default = _default;
57544});
57545define("ember-testing/lib/events", ["exports", "@ember/runloop", "@ember/polyfills", "ember-testing/lib/helpers/-is-form-control"], function (_exports, _runloop, _polyfills, _isFormControl) {
57546 "use strict";
57547
57548 Object.defineProperty(_exports, "__esModule", {
57549 value: true
57550 });
57551 _exports.focus = focus;
57552 _exports.fireEvent = fireEvent;
57553 var DEFAULT_EVENT_OPTIONS = {
57554 canBubble: true,
57555 cancelable: true
57556 };
57557 var KEYBOARD_EVENT_TYPES = ['keydown', 'keypress', 'keyup'];
57558 var MOUSE_EVENT_TYPES = ['click', 'mousedown', 'mouseup', 'dblclick', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover'];
57559
57560 function focus(el) {
57561 if (!el) {
57562 return;
57563 }
57564
57565 if (el.isContentEditable || (0, _isFormControl.default)(el)) {
57566 var type = el.getAttribute('type');
57567
57568 if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') {
57569 (0, _runloop.run)(null, function () {
57570 var browserIsNotFocused = document.hasFocus && !document.hasFocus(); // makes `document.activeElement` be `element`. If the browser is focused, it also fires a focus event
57571
57572 el.focus(); // Firefox does not trigger the `focusin` event if the window
57573 // does not have focus. If the document does not have focus then
57574 // fire `focusin` event as well.
57575
57576 if (browserIsNotFocused) {
57577 // if the browser is not focused the previous `el.focus()` didn't fire an event, so we simulate it
57578 fireEvent(el, 'focus', {
57579 bubbles: false
57580 });
57581 fireEvent(el, 'focusin');
57582 }
57583 });
57584 }
57585 }
57586 }
57587
57588 function fireEvent(element, type, options = {}) {
57589 if (!element) {
57590 return;
57591 }
57592
57593 var event;
57594
57595 if (KEYBOARD_EVENT_TYPES.indexOf(type) > -1) {
57596 event = buildKeyboardEvent(type, options);
57597 } else if (MOUSE_EVENT_TYPES.indexOf(type) > -1) {
57598 var rect = element.getBoundingClientRect();
57599 var x = rect.left + 1;
57600 var y = rect.top + 1;
57601 var simulatedCoordinates = {
57602 screenX: x + 5,
57603 screenY: y + 95,
57604 clientX: x,
57605 clientY: y
57606 };
57607 event = buildMouseEvent(type, (0, _polyfills.assign)(simulatedCoordinates, options));
57608 } else {
57609 event = buildBasicEvent(type, options);
57610 }
57611
57612 element.dispatchEvent(event);
57613 }
57614
57615 function buildBasicEvent(type, options = {}) {
57616 var event = document.createEvent('Events'); // Event.bubbles is read only
57617
57618 var bubbles = options.bubbles !== undefined ? options.bubbles : true;
57619 var cancelable = options.cancelable !== undefined ? options.cancelable : true;
57620 delete options.bubbles;
57621 delete options.cancelable;
57622 event.initEvent(type, bubbles, cancelable);
57623 (0, _polyfills.assign)(event, options);
57624 return event;
57625 }
57626
57627 function buildMouseEvent(type, options = {}) {
57628 var event;
57629
57630 try {
57631 event = document.createEvent('MouseEvents');
57632 var eventOpts = (0, _polyfills.assign)({}, DEFAULT_EVENT_OPTIONS, options);
57633 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);
57634 } catch (e) {
57635 event = buildBasicEvent(type, options);
57636 }
57637
57638 return event;
57639 }
57640
57641 function buildKeyboardEvent(type, options = {}) {
57642 var event;
57643
57644 try {
57645 event = document.createEvent('KeyEvents');
57646 var eventOpts = (0, _polyfills.assign)({}, DEFAULT_EVENT_OPTIONS, options);
57647 event.initKeyEvent(type, eventOpts.canBubble, eventOpts.cancelable, window, eventOpts.ctrlKey, eventOpts.altKey, eventOpts.shiftKey, eventOpts.metaKey, eventOpts.keyCode, eventOpts.charCode);
57648 } catch (e) {
57649 event = buildBasicEvent(type, options);
57650 }
57651
57652 return event;
57653 }
57654});
57655define("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) {
57656 "use strict";
57657
57658 _application.default.reopen({
57659 /**
57660 This property contains the testing helpers for the current application. These
57661 are created once you call `injectTestHelpers` on your `Application`
57662 instance. The included helpers are also available on the `window` object by
57663 default, but can be used from this object on the individual application also.
57664 @property testHelpers
57665 @type {Object}
57666 @default {}
57667 @public
57668 */
57669 testHelpers: {},
57670
57671 /**
57672 This property will contain the original methods that were registered
57673 on the `helperContainer` before `injectTestHelpers` is called.
57674 When `removeTestHelpers` is called, these methods are restored to the
57675 `helperContainer`.
57676 @property originalMethods
57677 @type {Object}
57678 @default {}
57679 @private
57680 @since 1.3.0
57681 */
57682 originalMethods: {},
57683
57684 /**
57685 This property indicates whether or not this application is currently in
57686 testing mode. This is set when `setupForTesting` is called on the current
57687 application.
57688 @property testing
57689 @type {Boolean}
57690 @default false
57691 @since 1.3.0
57692 @public
57693 */
57694 testing: false,
57695
57696 /**
57697 This hook defers the readiness of the application, so that you can start
57698 the app when your tests are ready to run. It also sets the router's
57699 location to 'none', so that the window's location will not be modified
57700 (preventing both accidental leaking of state between tests and interference
57701 with your testing framework). `setupForTesting` should only be called after
57702 setting a custom `router` class (for example `App.Router = Router.extend(`).
57703 Example:
57704 ```
57705 App.setupForTesting();
57706 ```
57707 @method setupForTesting
57708 @public
57709 */
57710 setupForTesting() {
57711 (0, _setup_for_testing.default)();
57712 this.testing = true;
57713 this.resolveRegistration('router:main').reopen({
57714 location: 'none'
57715 });
57716 },
57717
57718 /**
57719 This will be used as the container to inject the test helpers into. By
57720 default the helpers are injected into `window`.
57721 @property helperContainer
57722 @type {Object} The object to be used for test helpers.
57723 @default window
57724 @since 1.2.0
57725 @private
57726 */
57727 helperContainer: null,
57728
57729 /**
57730 This injects the test helpers into the `helperContainer` object. If an object is provided
57731 it will be used as the helperContainer. If `helperContainer` is not set it will default
57732 to `window`. If a function of the same name has already been defined it will be cached
57733 (so that it can be reset if the helper is removed with `unregisterHelper` or
57734 `removeTestHelpers`).
57735 Any callbacks registered with `onInjectHelpers` will be called once the
57736 helpers have been injected.
57737 Example:
57738 ```
57739 App.injectTestHelpers();
57740 ```
57741 @method injectTestHelpers
57742 @public
57743 */
57744 injectTestHelpers(helperContainer) {
57745 if (helperContainer) {
57746 this.helperContainer = helperContainer;
57747 } else {
57748 this.helperContainer = window;
57749 }
57750
57751 this.reopen({
57752 willDestroy() {
57753 this._super(...arguments);
57754
57755 this.removeTestHelpers();
57756 }
57757
57758 });
57759 this.testHelpers = {};
57760
57761 for (var name in _helpers.helpers) {
57762 this.originalMethods[name] = this.helperContainer[name];
57763 this.testHelpers[name] = this.helperContainer[name] = helper(this, name);
57764 protoWrap(_promise.default.prototype, name, helper(this, name), _helpers.helpers[name].meta.wait);
57765 }
57766
57767 (0, _on_inject_helpers.invokeInjectHelpersCallbacks)(this);
57768 },
57769
57770 /**
57771 This removes all helpers that have been registered, and resets and functions
57772 that were overridden by the helpers.
57773 Example:
57774 ```javascript
57775 App.removeTestHelpers();
57776 ```
57777 @public
57778 @method removeTestHelpers
57779 */
57780 removeTestHelpers() {
57781 if (!this.helperContainer) {
57782 return;
57783 }
57784
57785 for (var name in _helpers.helpers) {
57786 this.helperContainer[name] = this.originalMethods[name];
57787 delete _promise.default.prototype[name];
57788 delete this.testHelpers[name];
57789 delete this.originalMethods[name];
57790 }
57791 }
57792
57793 }); // This method is no longer needed
57794 // But still here for backwards compatibility
57795 // of helper chaining
57796
57797
57798 function protoWrap(proto, name, callback, isAsync) {
57799 proto[name] = function (...args) {
57800 if (isAsync) {
57801 return callback.apply(this, args);
57802 } else {
57803 return this.then(function () {
57804 return callback.apply(this, args);
57805 });
57806 }
57807 };
57808 }
57809
57810 function helper(app, name) {
57811 var fn = _helpers.helpers[name].method;
57812 var meta = _helpers.helpers[name].meta;
57813
57814 if (!meta.wait) {
57815 return (...args) => fn.apply(app, [app, ...args]);
57816 }
57817
57818 return (...args) => {
57819 var lastPromise = (0, _run.default)(() => (0, _promise.resolve)((0, _promise.getLastPromise)())); // wait for last helper's promise to resolve and then
57820 // execute. To be safe, we need to tell the adapter we're going
57821 // asynchronous here, because fn may not be invoked before we
57822 // return.
57823
57824 (0, _adapter.asyncStart)();
57825 return lastPromise.then(() => fn.apply(app, [app, ...args])).finally(_adapter.asyncEnd);
57826 };
57827 }
57828});
57829define("ember-testing/lib/ext/rsvp", ["exports", "@ember/-internals/runtime", "@ember/runloop", "@ember/debug", "ember-testing/lib/test/adapter"], function (_exports, _runtime, _runloop, _debug, _adapter) {
57830 "use strict";
57831
57832 Object.defineProperty(_exports, "__esModule", {
57833 value: true
57834 });
57835 _exports.default = void 0;
57836
57837 _runtime.RSVP.configure('async', function (callback, promise) {
57838 // if schedule will cause autorun, we need to inform adapter
57839 if ((0, _debug.isTesting)() && !_runloop.backburner.currentInstance) {
57840 (0, _adapter.asyncStart)();
57841
57842 _runloop.backburner.schedule('actions', () => {
57843 (0, _adapter.asyncEnd)();
57844 callback(promise);
57845 });
57846 } else {
57847 _runloop.backburner.schedule('actions', () => callback(promise));
57848 }
57849 });
57850
57851 var _default = _runtime.RSVP;
57852 _exports.default = _default;
57853});
57854define("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) {
57855 "use strict";
57856
57857 (0, _helpers.registerAsyncHelper)('visit', _visit.default);
57858 (0, _helpers.registerAsyncHelper)('click', _click.default);
57859 (0, _helpers.registerAsyncHelper)('keyEvent', _key_event.default);
57860 (0, _helpers.registerAsyncHelper)('fillIn', _fill_in.default);
57861 (0, _helpers.registerAsyncHelper)('wait', _wait.default);
57862 (0, _helpers.registerAsyncHelper)('andThen', _and_then.default);
57863 (0, _helpers.registerAsyncHelper)('pauseTest', _pause_test.pauseTest);
57864 (0, _helpers.registerAsyncHelper)('triggerEvent', _trigger_event.default);
57865 (0, _helpers.registerHelper)('find', _find.default);
57866 (0, _helpers.registerHelper)('findWithAssert', _find_with_assert.default);
57867 (0, _helpers.registerHelper)('currentRouteName', _current_route_name.default);
57868 (0, _helpers.registerHelper)('currentPath', _current_path.default);
57869 (0, _helpers.registerHelper)('currentURL', _current_url.default);
57870 (0, _helpers.registerHelper)('resumeTest', _pause_test.resumeTest);
57871});
57872define("ember-testing/lib/helpers/-is-form-control", ["exports"], function (_exports) {
57873 "use strict";
57874
57875 Object.defineProperty(_exports, "__esModule", {
57876 value: true
57877 });
57878 _exports.default = isFormControl;
57879 var FORM_CONTROL_TAGS = ['INPUT', 'BUTTON', 'SELECT', 'TEXTAREA'];
57880 /**
57881 @private
57882 @param {Element} element the element to check
57883 @returns {boolean} `true` when the element is a form control, `false` otherwise
57884 */
57885
57886 function isFormControl(element) {
57887 var {
57888 tagName,
57889 type
57890 } = element;
57891
57892 if (type === 'hidden') {
57893 return false;
57894 }
57895
57896 return FORM_CONTROL_TAGS.indexOf(tagName) > -1;
57897 }
57898});
57899define("ember-testing/lib/helpers/and_then", ["exports"], function (_exports) {
57900 "use strict";
57901
57902 Object.defineProperty(_exports, "__esModule", {
57903 value: true
57904 });
57905 _exports.default = andThen;
57906
57907 function andThen(app, callback) {
57908 return app.testHelpers.wait(callback(app));
57909 }
57910});
57911define("ember-testing/lib/helpers/click", ["exports", "ember-testing/lib/events"], function (_exports, _events) {
57912 "use strict";
57913
57914 Object.defineProperty(_exports, "__esModule", {
57915 value: true
57916 });
57917 _exports.default = click;
57918
57919 /**
57920 @module ember
57921 */
57922
57923 /**
57924 Clicks an element and triggers any actions triggered by the element's `click`
57925 event.
57926
57927 Example:
57928
57929 ```javascript
57930 click('.some-jQuery-selector').then(function() {
57931 // assert something
57932 });
57933 ```
57934
57935 @method click
57936 @param {String} selector jQuery selector for finding element on the DOM
57937 @param {Object} context A DOM Element, Document, or jQuery to use as context
57938 @return {RSVP.Promise<undefined>}
57939 @public
57940 */
57941 function click(app, selector, context) {
57942 var $el = app.testHelpers.findWithAssert(selector, context);
57943 var el = $el[0];
57944 (0, _events.fireEvent)(el, 'mousedown');
57945 (0, _events.focus)(el);
57946 (0, _events.fireEvent)(el, 'mouseup');
57947 (0, _events.fireEvent)(el, 'click');
57948 return app.testHelpers.wait();
57949 }
57950});
57951define("ember-testing/lib/helpers/current_path", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
57952 "use strict";
57953
57954 Object.defineProperty(_exports, "__esModule", {
57955 value: true
57956 });
57957 _exports.default = currentPath;
57958
57959 /**
57960 @module ember
57961 */
57962
57963 /**
57964 Returns the current path.
57965
57966 Example:
57967
57968 ```javascript
57969 function validateURL() {
57970 equal(currentPath(), 'some.path.index', "correct path was transitioned into.");
57971 }
57972
57973 click('#some-link-id').then(validateURL);
57974 ```
57975
57976 @method currentPath
57977 @return {Object} The currently active path.
57978 @since 1.5.0
57979 @public
57980 */
57981 function currentPath(app) {
57982 var routingService = app.__container__.lookup('service:-routing');
57983
57984 return (0, _metal.get)(routingService, 'currentPath');
57985 }
57986});
57987define("ember-testing/lib/helpers/current_route_name", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
57988 "use strict";
57989
57990 Object.defineProperty(_exports, "__esModule", {
57991 value: true
57992 });
57993 _exports.default = currentRouteName;
57994
57995 /**
57996 @module ember
57997 */
57998
57999 /**
58000 Returns the currently active route name.
58001
58002 Example:
58003
58004 ```javascript
58005 function validateRouteName() {
58006 equal(currentRouteName(), 'some.path', "correct route was transitioned into.");
58007 }
58008 visit('/some/path').then(validateRouteName)
58009 ```
58010
58011 @method currentRouteName
58012 @return {Object} The name of the currently active route.
58013 @since 1.5.0
58014 @public
58015 */
58016 function currentRouteName(app) {
58017 var routingService = app.__container__.lookup('service:-routing');
58018
58019 return (0, _metal.get)(routingService, 'currentRouteName');
58020 }
58021});
58022define("ember-testing/lib/helpers/current_url", ["exports", "@ember/-internals/metal"], function (_exports, _metal) {
58023 "use strict";
58024
58025 Object.defineProperty(_exports, "__esModule", {
58026 value: true
58027 });
58028 _exports.default = currentURL;
58029
58030 /**
58031 @module ember
58032 */
58033
58034 /**
58035 Returns the current URL.
58036
58037 Example:
58038
58039 ```javascript
58040 function validateURL() {
58041 equal(currentURL(), '/some/path', "correct URL was transitioned into.");
58042 }
58043
58044 click('#some-link-id').then(validateURL);
58045 ```
58046
58047 @method currentURL
58048 @return {Object} The currently active URL.
58049 @since 1.5.0
58050 @public
58051 */
58052 function currentURL(app) {
58053 var router = app.__container__.lookup('router:main');
58054
58055 return (0, _metal.get)(router, 'location').getURL();
58056 }
58057});
58058define("ember-testing/lib/helpers/fill_in", ["exports", "ember-testing/lib/events", "ember-testing/lib/helpers/-is-form-control"], function (_exports, _events, _isFormControl) {
58059 "use strict";
58060
58061 Object.defineProperty(_exports, "__esModule", {
58062 value: true
58063 });
58064 _exports.default = fillIn;
58065
58066 /**
58067 @module ember
58068 */
58069
58070 /**
58071 Fills in an input element with some text.
58072
58073 Example:
58074
58075 ```javascript
58076 fillIn('#email', 'you@example.com').then(function() {
58077 // assert something
58078 });
58079 ```
58080
58081 @method fillIn
58082 @param {String} selector jQuery selector finding an input element on the DOM
58083 to fill text with
58084 @param {String} text text to place inside the input element
58085 @return {RSVP.Promise<undefined>}
58086 @public
58087 */
58088 function fillIn(app, selector, contextOrText, text) {
58089 var $el, el, context;
58090
58091 if (text === undefined) {
58092 text = contextOrText;
58093 } else {
58094 context = contextOrText;
58095 }
58096
58097 $el = app.testHelpers.findWithAssert(selector, context);
58098 el = $el[0];
58099 (0, _events.focus)(el);
58100
58101 if ((0, _isFormControl.default)(el)) {
58102 el.value = text;
58103 } else {
58104 el.innerHTML = text;
58105 }
58106
58107 (0, _events.fireEvent)(el, 'input');
58108 (0, _events.fireEvent)(el, 'change');
58109 return app.testHelpers.wait();
58110 }
58111});
58112define("ember-testing/lib/helpers/find", ["exports", "@ember/-internals/metal", "@ember/debug", "@ember/-internals/views"], function (_exports, _metal, _debug, _views) {
58113 "use strict";
58114
58115 Object.defineProperty(_exports, "__esModule", {
58116 value: true
58117 });
58118 _exports.default = find;
58119
58120 /**
58121 @module ember
58122 */
58123
58124 /**
58125 Finds an element in the context of the app's container element. A simple alias
58126 for `app.$(selector)`.
58127
58128 Example:
58129
58130 ```javascript
58131 var $el = find('.my-selector');
58132 ```
58133
58134 With the `context` param:
58135
58136 ```javascript
58137 var $el = find('.my-selector', '.parent-element-class');
58138 ```
58139
58140 @method find
58141 @param {String} selector jQuery selector for element lookup
58142 @param {String} [context] (optional) jQuery selector that will limit the selector
58143 argument to find only within the context's children
58144 @return {Object} DOM element representing the results of the query
58145 @public
58146 */
58147 function find(app, selector, context) {
58148 if (_views.jQueryDisabled) {
58149 (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.'));
58150 }
58151
58152 var $el;
58153 context = context || (0, _metal.get)(app, 'rootElement');
58154 $el = app.$(selector, context);
58155 return $el;
58156 }
58157});
58158define("ember-testing/lib/helpers/find_with_assert", ["exports"], function (_exports) {
58159 "use strict";
58160
58161 Object.defineProperty(_exports, "__esModule", {
58162 value: true
58163 });
58164 _exports.default = findWithAssert;
58165
58166 /**
58167 @module ember
58168 */
58169
58170 /**
58171 Like `find`, but throws an error if the element selector returns no results.
58172
58173 Example:
58174
58175 ```javascript
58176 var $el = findWithAssert('.doesnt-exist'); // throws error
58177 ```
58178
58179 With the `context` param:
58180
58181 ```javascript
58182 var $el = findWithAssert('.selector-id', '.parent-element-class'); // assert will pass
58183 ```
58184
58185 @method findWithAssert
58186 @param {String} selector jQuery selector string for finding an element within
58187 the DOM
58188 @param {String} [context] (optional) jQuery selector that will limit the
58189 selector argument to find only within the context's children
58190 @return {Object} jQuery object representing the results of the query
58191 @throws {Error} throws error if object returned has a length of 0
58192 @public
58193 */
58194 function findWithAssert(app, selector, context) {
58195 var $el = app.testHelpers.find(selector, context);
58196
58197 if ($el.length === 0) {
58198 throw new Error('Element ' + selector + ' not found.');
58199 }
58200
58201 return $el;
58202 }
58203});
58204define("ember-testing/lib/helpers/key_event", ["exports"], function (_exports) {
58205 "use strict";
58206
58207 Object.defineProperty(_exports, "__esModule", {
58208 value: true
58209 });
58210 _exports.default = keyEvent;
58211
58212 /**
58213 @module ember
58214 */
58215
58216 /**
58217 Simulates a key event, e.g. `keypress`, `keydown`, `keyup` with the desired keyCode
58218 Example:
58219 ```javascript
58220 keyEvent('.some-jQuery-selector', 'keypress', 13).then(function() {
58221 // assert something
58222 });
58223 ```
58224 @method keyEvent
58225 @param {String} selector jQuery selector for finding element on the DOM
58226 @param {String} type the type of key event, e.g. `keypress`, `keydown`, `keyup`
58227 @param {Number} keyCode the keyCode of the simulated key event
58228 @return {RSVP.Promise<undefined>}
58229 @since 1.5.0
58230 @public
58231 */
58232 function keyEvent(app, selector, contextOrType, typeOrKeyCode, keyCode) {
58233 var context, type;
58234
58235 if (keyCode === undefined) {
58236 context = null;
58237 keyCode = typeOrKeyCode;
58238 type = contextOrType;
58239 } else {
58240 context = contextOrType;
58241 type = typeOrKeyCode;
58242 }
58243
58244 return app.testHelpers.triggerEvent(selector, context, type, {
58245 keyCode,
58246 which: keyCode
58247 });
58248 }
58249});
58250define("ember-testing/lib/helpers/pause_test", ["exports", "@ember/-internals/runtime", "@ember/debug"], function (_exports, _runtime, _debug) {
58251 "use strict";
58252
58253 Object.defineProperty(_exports, "__esModule", {
58254 value: true
58255 });
58256 _exports.resumeTest = resumeTest;
58257 _exports.pauseTest = pauseTest;
58258
58259 /**
58260 @module ember
58261 */
58262 var resume;
58263 /**
58264 Resumes a test paused by `pauseTest`.
58265
58266 @method resumeTest
58267 @return {void}
58268 @public
58269 */
58270
58271 function resumeTest() {
58272 (true && !(resume) && (0, _debug.assert)('Testing has not been paused. There is nothing to resume.', resume));
58273 resume();
58274 resume = undefined;
58275 }
58276 /**
58277 Pauses the current test - this is useful for debugging while testing or for test-driving.
58278 It allows you to inspect the state of your application at any point.
58279 Example (The test will pause before clicking the button):
58280
58281 ```javascript
58282 visit('/')
58283 return pauseTest();
58284 click('.btn');
58285 ```
58286
58287 You may want to turn off the timeout before pausing.
58288
58289 qunit (timeout available to use as of 2.4.0):
58290
58291 ```
58292 visit('/');
58293 assert.timeout(0);
58294 return pauseTest();
58295 click('.btn');
58296 ```
58297
58298 mocha (timeout happens automatically as of ember-mocha v0.14.0):
58299
58300 ```
58301 visit('/');
58302 this.timeout(0);
58303 return pauseTest();
58304 click('.btn');
58305 ```
58306
58307
58308 @since 1.9.0
58309 @method pauseTest
58310 @return {Object} A promise that will never resolve
58311 @public
58312 */
58313
58314
58315 function pauseTest() {
58316 (0, _debug.info)('Testing paused. Use `resumeTest()` to continue.');
58317 return new _runtime.RSVP.Promise(resolve => {
58318 resume = resolve;
58319 }, 'TestAdapter paused promise');
58320 }
58321});
58322define("ember-testing/lib/helpers/trigger_event", ["exports", "ember-testing/lib/events"], function (_exports, _events) {
58323 "use strict";
58324
58325 Object.defineProperty(_exports, "__esModule", {
58326 value: true
58327 });
58328 _exports.default = triggerEvent;
58329
58330 /**
58331 @module ember
58332 */
58333
58334 /**
58335 Triggers the given DOM event on the element identified by the provided selector.
58336 Example:
58337 ```javascript
58338 triggerEvent('#some-elem-id', 'blur');
58339 ```
58340 This is actually used internally by the `keyEvent` helper like so:
58341 ```javascript
58342 triggerEvent('#some-elem-id', 'keypress', { keyCode: 13 });
58343 ```
58344 @method triggerEvent
58345 @param {String} selector jQuery selector for finding element on the DOM
58346 @param {String} [context] jQuery selector that will limit the selector
58347 argument to find only within the context's children
58348 @param {String} type The event type to be triggered.
58349 @param {Object} [options] The options to be passed to jQuery.Event.
58350 @return {RSVP.Promise<undefined>}
58351 @since 1.5.0
58352 @public
58353 */
58354 function triggerEvent(app, selector, contextOrType, typeOrOptions, possibleOptions) {
58355 var arity = arguments.length;
58356 var context, type, options;
58357
58358 if (arity === 3) {
58359 // context and options are optional, so this is
58360 // app, selector, type
58361 context = null;
58362 type = contextOrType;
58363 options = {};
58364 } else if (arity === 4) {
58365 // context and options are optional, so this is
58366 if (typeof typeOrOptions === 'object') {
58367 // either
58368 // app, selector, type, options
58369 context = null;
58370 type = contextOrType;
58371 options = typeOrOptions;
58372 } else {
58373 // or
58374 // app, selector, context, type
58375 context = contextOrType;
58376 type = typeOrOptions;
58377 options = {};
58378 }
58379 } else {
58380 context = contextOrType;
58381 type = typeOrOptions;
58382 options = possibleOptions;
58383 }
58384
58385 var $el = app.testHelpers.findWithAssert(selector, context);
58386 var el = $el[0];
58387 (0, _events.fireEvent)(el, type, options);
58388 return app.testHelpers.wait();
58389 }
58390});
58391define("ember-testing/lib/helpers/visit", ["exports", "@ember/runloop"], function (_exports, _runloop) {
58392 "use strict";
58393
58394 Object.defineProperty(_exports, "__esModule", {
58395 value: true
58396 });
58397 _exports.default = visit;
58398
58399 /**
58400 Loads a route, sets up any controllers, and renders any templates associated
58401 with the route as though a real user had triggered the route change while
58402 using your app.
58403
58404 Example:
58405
58406 ```javascript
58407 visit('posts/index').then(function() {
58408 // assert something
58409 });
58410 ```
58411
58412 @method visit
58413 @param {String} url the name of the route
58414 @return {RSVP.Promise<undefined>}
58415 @public
58416 */
58417 function visit(app, url) {
58418 var router = app.__container__.lookup('router:main');
58419
58420 var shouldHandleURL = false;
58421 app.boot().then(() => {
58422 router.location.setURL(url);
58423
58424 if (shouldHandleURL) {
58425 (0, _runloop.run)(app.__deprecatedInstance__, 'handleURL', url);
58426 }
58427 });
58428
58429 if (app._readinessDeferrals > 0) {
58430 router.initialURL = url;
58431 (0, _runloop.run)(app, 'advanceReadiness');
58432 delete router.initialURL;
58433 } else {
58434 shouldHandleURL = true;
58435 }
58436
58437 return app.testHelpers.wait();
58438 }
58439});
58440define("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) {
58441 "use strict";
58442
58443 Object.defineProperty(_exports, "__esModule", {
58444 value: true
58445 });
58446 _exports.default = wait;
58447
58448 /**
58449 @module ember
58450 */
58451
58452 /**
58453 Causes the run loop to process any pending events. This is used to ensure that
58454 any async operations from other helpers (or your assertions) have been processed.
58455
58456 This is most often used as the return value for the helper functions (see 'click',
58457 'fillIn','visit',etc). However, there is a method to register a test helper which
58458 utilizes this method without the need to actually call `wait()` in your helpers.
58459
58460 The `wait` helper is built into `registerAsyncHelper` by default. You will not need
58461 to `return app.testHelpers.wait();` - the wait behavior is provided for you.
58462
58463 Example:
58464
58465 ```javascript
58466 import { registerAsyncHelper } from '@ember/test';
58467
58468 registerAsyncHelper('loginUser', function(app, username, password) {
58469 visit('secured/path/here')
58470 .fillIn('#username', username)
58471 .fillIn('#password', password)
58472 .click('.submit');
58473 });
58474 ```
58475
58476 @method wait
58477 @param {Object} value The value to be returned.
58478 @return {RSVP.Promise<any>} Promise that resolves to the passed value.
58479 @public
58480 @since 1.0.0
58481 */
58482 function wait(app, value) {
58483 return new _runtime.RSVP.Promise(function (resolve) {
58484 var router = app.__container__.lookup('router:main'); // Every 10ms, poll for the async thing to have finished
58485
58486
58487 var watcher = setInterval(() => {
58488 // 1. If the router is loading, keep polling
58489 var routerIsLoading = router._routerMicrolib && Boolean(router._routerMicrolib.activeTransition);
58490
58491 if (routerIsLoading) {
58492 return;
58493 } // 2. If there are pending Ajax requests, keep polling
58494
58495
58496 if ((0, _pending_requests.pendingRequests)()) {
58497 return;
58498 } // 3. If there are scheduled timers or we are inside of a run loop, keep polling
58499
58500
58501 if ((0, _runloop.hasScheduledTimers)() || (0, _runloop.getCurrentRunLoop)()) {
58502 return;
58503 }
58504
58505 if ((0, _waiters.checkWaiters)()) {
58506 return;
58507 } // Stop polling
58508
58509
58510 clearInterval(watcher); // Synchronously resolve the promise
58511
58512 (0, _runloop.run)(null, resolve, value);
58513 }, 10);
58514 });
58515 }
58516});
58517define("ember-testing/lib/initializers", ["@ember/application"], function (_application) {
58518 "use strict";
58519
58520 var name = 'deferReadiness in `testing` mode';
58521 (0, _application.onLoad)('Ember.Application', function (Application) {
58522 if (!Application.initializers[name]) {
58523 Application.initializer({
58524 name: name,
58525
58526 initialize(application) {
58527 if (application.testing) {
58528 application.deferReadiness();
58529 }
58530 }
58531
58532 });
58533 }
58534 });
58535});
58536define("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) {
58537 "use strict";
58538
58539 Object.defineProperty(_exports, "__esModule", {
58540 value: true
58541 });
58542 _exports.default = setupForTesting;
58543
58544 /* global self */
58545
58546 /**
58547 Sets Ember up for testing. This is useful to perform
58548 basic setup steps in order to unit test.
58549
58550 Use `App.setupForTesting` to perform integration tests (full
58551 application testing).
58552
58553 @method setupForTesting
58554 @namespace Ember
58555 @since 1.5.0
58556 @private
58557 */
58558 function setupForTesting() {
58559 (0, _debug.setTesting)(true);
58560 var adapter = (0, _adapter.getAdapter)(); // if adapter is not manually set default to QUnit
58561
58562 if (!adapter) {
58563 (0, _adapter.setAdapter)(typeof self.QUnit === 'undefined' ? _adapter2.default.create() : _qunit.default.create());
58564 }
58565
58566 if (!_views.jQueryDisabled) {
58567 (0, _views.jQuery)(document).off('ajaxSend', _pending_requests.incrementPendingRequests);
58568 (0, _views.jQuery)(document).off('ajaxComplete', _pending_requests.decrementPendingRequests);
58569 (0, _pending_requests.clearPendingRequests)();
58570 (0, _views.jQuery)(document).on('ajaxSend', _pending_requests.incrementPendingRequests);
58571 (0, _views.jQuery)(document).on('ajaxComplete', _pending_requests.decrementPendingRequests);
58572 }
58573 }
58574});
58575define("ember-testing/lib/support", ["@ember/debug", "@ember/-internals/views", "@ember/-internals/browser-environment"], function (_debug, _views, _browserEnvironment) {
58576 "use strict";
58577
58578 /**
58579 @module ember
58580 */
58581 var $ = _views.jQuery;
58582 /**
58583 This method creates a checkbox and triggers the click event to fire the
58584 passed in handler. It is used to correct for a bug in older versions
58585 of jQuery (e.g 1.8.3).
58586
58587 @private
58588 @method testCheckboxClick
58589 */
58590
58591 function testCheckboxClick(handler) {
58592 var input = document.createElement('input');
58593 $(input).attr('type', 'checkbox').css({
58594 position: 'absolute',
58595 left: '-1000px',
58596 top: '-1000px'
58597 }).appendTo('body').on('click', handler).trigger('click').remove();
58598 }
58599
58600 if (_browserEnvironment.hasDOM && !_views.jQueryDisabled) {
58601 $(function () {
58602 /*
58603 Determine whether a checkbox checked using jQuery's "click" method will have
58604 the correct value for its checked property.
58605 If we determine that the current jQuery version exhibits this behavior,
58606 patch it to work correctly as in the commit for the actual fix:
58607 https://github.com/jquery/jquery/commit/1fb2f92.
58608 */
58609 testCheckboxClick(function () {
58610 if (!this.checked && !$.event.special.click) {
58611 $.event.special.click = {
58612 // For checkbox, fire native event so checked state will be right
58613 trigger() {
58614 if (this.nodeName === 'INPUT' && this.type === 'checkbox' && this.click) {
58615 this.click();
58616 return false;
58617 }
58618 }
58619
58620 };
58621 }
58622 }); // Try again to verify that the patch took effect or blow up.
58623
58624 testCheckboxClick(function () {
58625 (true && (0, _debug.warn)("clicked checkboxes should be checked! the jQuery patch didn't work", this.checked, {
58626 id: 'ember-testing.test-checkbox-click'
58627 }));
58628 });
58629 });
58630 }
58631});
58632define("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) {
58633 "use strict";
58634
58635 Object.defineProperty(_exports, "__esModule", {
58636 value: true
58637 });
58638 _exports.default = void 0;
58639
58640 /**
58641 @module ember
58642 */
58643
58644 /**
58645 This is a container for an assortment of testing related functionality:
58646
58647 * Choose your default test adapter (for your framework of choice).
58648 * Register/Unregister additional test helpers.
58649 * Setup callbacks to be fired when the test helpers are injected into
58650 your application.
58651
58652 @class Test
58653 @namespace Ember
58654 @public
58655 */
58656 var Test = {
58657 /**
58658 Hash containing all known test helpers.
58659 @property _helpers
58660 @private
58661 @since 1.7.0
58662 */
58663 _helpers: _helpers.helpers,
58664 registerHelper: _helpers.registerHelper,
58665 registerAsyncHelper: _helpers.registerAsyncHelper,
58666 unregisterHelper: _helpers.unregisterHelper,
58667 onInjectHelpers: _on_inject_helpers.onInjectHelpers,
58668 Promise: _promise.default,
58669 promise: _promise.promise,
58670 resolve: _promise.resolve,
58671 registerWaiter: _waiters.registerWaiter,
58672 unregisterWaiter: _waiters.unregisterWaiter,
58673 checkWaiters: _waiters.checkWaiters
58674 };
58675 /**
58676 Used to allow ember-testing to communicate with a specific testing
58677 framework.
58678
58679 You can manually set it before calling `App.setupForTesting()`.
58680
58681 Example:
58682
58683 ```javascript
58684 Ember.Test.adapter = MyCustomAdapter.create()
58685 ```
58686
58687 If you do not set it, ember-testing will default to `Ember.Test.QUnitAdapter`.
58688
58689 @public
58690 @for Ember.Test
58691 @property adapter
58692 @type {Class} The adapter to be used.
58693 @default Ember.Test.QUnitAdapter
58694 */
58695
58696 Object.defineProperty(Test, 'adapter', {
58697 get: _adapter.getAdapter,
58698 set: _adapter.setAdapter
58699 });
58700 var _default = Test;
58701 _exports.default = _default;
58702});
58703define("ember-testing/lib/test/adapter", ["exports", "@ember/-internals/error-handling"], function (_exports, _errorHandling) {
58704 "use strict";
58705
58706 Object.defineProperty(_exports, "__esModule", {
58707 value: true
58708 });
58709 _exports.getAdapter = getAdapter;
58710 _exports.setAdapter = setAdapter;
58711 _exports.asyncStart = asyncStart;
58712 _exports.asyncEnd = asyncEnd;
58713 var adapter;
58714
58715 function getAdapter() {
58716 return adapter;
58717 }
58718
58719 function setAdapter(value) {
58720 adapter = value;
58721
58722 if (value && typeof value.exception === 'function') {
58723 (0, _errorHandling.setDispatchOverride)(adapterDispatch);
58724 } else {
58725 (0, _errorHandling.setDispatchOverride)(null);
58726 }
58727 }
58728
58729 function asyncStart() {
58730 if (adapter) {
58731 adapter.asyncStart();
58732 }
58733 }
58734
58735 function asyncEnd() {
58736 if (adapter) {
58737 adapter.asyncEnd();
58738 }
58739 }
58740
58741 function adapterDispatch(error) {
58742 adapter.exception(error);
58743 console.error(error.stack); // eslint-disable-line no-console
58744 }
58745});
58746define("ember-testing/lib/test/helpers", ["exports", "ember-testing/lib/test/promise"], function (_exports, _promise) {
58747 "use strict";
58748
58749 Object.defineProperty(_exports, "__esModule", {
58750 value: true
58751 });
58752 _exports.registerHelper = registerHelper;
58753 _exports.registerAsyncHelper = registerAsyncHelper;
58754 _exports.unregisterHelper = unregisterHelper;
58755 _exports.helpers = void 0;
58756 var helpers = {};
58757 /**
58758 @module @ember/test
58759 */
58760
58761 /**
58762 `registerHelper` is used to register a test helper that will be injected
58763 when `App.injectTestHelpers` is called.
58764
58765 The helper method will always be called with the current Application as
58766 the first parameter.
58767
58768 For example:
58769
58770 ```javascript
58771 import { registerHelper } from '@ember/test';
58772 import { run } from '@ember/runloop';
58773
58774 registerHelper('boot', function(app) {
58775 run(app, app.advanceReadiness);
58776 });
58777 ```
58778
58779 This helper can later be called without arguments because it will be
58780 called with `app` as the first parameter.
58781
58782 ```javascript
58783 import Application from '@ember/application';
58784
58785 App = Application.create();
58786 App.injectTestHelpers();
58787 boot();
58788 ```
58789
58790 @public
58791 @for @ember/test
58792 @static
58793 @method registerHelper
58794 @param {String} name The name of the helper method to add.
58795 @param {Function} helperMethod
58796 @param options {Object}
58797 */
58798
58799 _exports.helpers = helpers;
58800
58801 function registerHelper(name, helperMethod) {
58802 helpers[name] = {
58803 method: helperMethod,
58804 meta: {
58805 wait: false
58806 }
58807 };
58808 }
58809 /**
58810 `registerAsyncHelper` is used to register an async test helper that will be injected
58811 when `App.injectTestHelpers` is called.
58812
58813 The helper method will always be called with the current Application as
58814 the first parameter.
58815
58816 For example:
58817
58818 ```javascript
58819 import { registerAsyncHelper } from '@ember/test';
58820 import { run } from '@ember/runloop';
58821
58822 registerAsyncHelper('boot', function(app) {
58823 run(app, app.advanceReadiness);
58824 });
58825 ```
58826
58827 The advantage of an async helper is that it will not run
58828 until the last async helper has completed. All async helpers
58829 after it will wait for it complete before running.
58830
58831
58832 For example:
58833
58834 ```javascript
58835 import { registerAsyncHelper } from '@ember/test';
58836
58837 registerAsyncHelper('deletePost', function(app, postId) {
58838 click('.delete-' + postId);
58839 });
58840
58841 // ... in your test
58842 visit('/post/2');
58843 deletePost(2);
58844 visit('/post/3');
58845 deletePost(3);
58846 ```
58847
58848 @public
58849 @for @ember/test
58850 @method registerAsyncHelper
58851 @param {String} name The name of the helper method to add.
58852 @param {Function} helperMethod
58853 @since 1.2.0
58854 */
58855
58856
58857 function registerAsyncHelper(name, helperMethod) {
58858 helpers[name] = {
58859 method: helperMethod,
58860 meta: {
58861 wait: true
58862 }
58863 };
58864 }
58865 /**
58866 Remove a previously added helper method.
58867
58868 Example:
58869
58870 ```javascript
58871 import { unregisterHelper } from '@ember/test';
58872
58873 unregisterHelper('wait');
58874 ```
58875
58876 @public
58877 @method unregisterHelper
58878 @static
58879 @for @ember/test
58880 @param {String} name The helper to remove.
58881 */
58882
58883
58884 function unregisterHelper(name) {
58885 delete helpers[name];
58886 delete _promise.default.prototype[name];
58887 }
58888});
58889define("ember-testing/lib/test/on_inject_helpers", ["exports"], function (_exports) {
58890 "use strict";
58891
58892 Object.defineProperty(_exports, "__esModule", {
58893 value: true
58894 });
58895 _exports.onInjectHelpers = onInjectHelpers;
58896 _exports.invokeInjectHelpersCallbacks = invokeInjectHelpersCallbacks;
58897 _exports.callbacks = void 0;
58898 var callbacks = [];
58899 /**
58900 Used to register callbacks to be fired whenever `App.injectTestHelpers`
58901 is called.
58902
58903 The callback will receive the current application as an argument.
58904
58905 Example:
58906
58907 ```javascript
58908 import $ from 'jquery';
58909
58910 Ember.Test.onInjectHelpers(function() {
58911 $(document).ajaxSend(function() {
58912 Test.pendingRequests++;
58913 });
58914
58915 $(document).ajaxComplete(function() {
58916 Test.pendingRequests--;
58917 });
58918 });
58919 ```
58920
58921 @public
58922 @for Ember.Test
58923 @method onInjectHelpers
58924 @param {Function} callback The function to be called.
58925 */
58926
58927 _exports.callbacks = callbacks;
58928
58929 function onInjectHelpers(callback) {
58930 callbacks.push(callback);
58931 }
58932
58933 function invokeInjectHelpersCallbacks(app) {
58934 for (var i = 0; i < callbacks.length; i++) {
58935 callbacks[i](app);
58936 }
58937 }
58938});
58939define("ember-testing/lib/test/pending_requests", ["exports"], function (_exports) {
58940 "use strict";
58941
58942 Object.defineProperty(_exports, "__esModule", {
58943 value: true
58944 });
58945 _exports.pendingRequests = pendingRequests;
58946 _exports.clearPendingRequests = clearPendingRequests;
58947 _exports.incrementPendingRequests = incrementPendingRequests;
58948 _exports.decrementPendingRequests = decrementPendingRequests;
58949 var requests = [];
58950
58951 function pendingRequests() {
58952 return requests.length;
58953 }
58954
58955 function clearPendingRequests() {
58956 requests.length = 0;
58957 }
58958
58959 function incrementPendingRequests(_, xhr) {
58960 requests.push(xhr);
58961 }
58962
58963 function decrementPendingRequests(_, xhr) {
58964 setTimeout(function () {
58965 for (var i = 0; i < requests.length; i++) {
58966 if (xhr === requests[i]) {
58967 requests.splice(i, 1);
58968 break;
58969 }
58970 }
58971 }, 0);
58972 }
58973});
58974define("ember-testing/lib/test/promise", ["exports", "@ember/-internals/runtime", "ember-testing/lib/test/run"], function (_exports, _runtime, _run) {
58975 "use strict";
58976
58977 Object.defineProperty(_exports, "__esModule", {
58978 value: true
58979 });
58980 _exports.promise = promise;
58981 _exports.resolve = resolve;
58982 _exports.getLastPromise = getLastPromise;
58983 _exports.default = void 0;
58984 var lastPromise;
58985
58986 class TestPromise extends _runtime.RSVP.Promise {
58987 constructor() {
58988 super(...arguments);
58989 lastPromise = this;
58990 }
58991
58992 then(_onFulfillment, ...args) {
58993 var onFulfillment = typeof _onFulfillment === 'function' ? result => isolate(_onFulfillment, result) : undefined;
58994 return super.then(onFulfillment, ...args);
58995 }
58996
58997 }
58998 /**
58999 This returns a thenable tailored for testing. It catches failed
59000 `onSuccess` callbacks and invokes the `Ember.Test.adapter.exception`
59001 callback in the last chained then.
59002
59003 This method should be returned by async helpers such as `wait`.
59004
59005 @public
59006 @for Ember.Test
59007 @method promise
59008 @param {Function} resolver The function used to resolve the promise.
59009 @param {String} label An optional string for identifying the promise.
59010 */
59011
59012
59013 _exports.default = TestPromise;
59014
59015 function promise(resolver, label) {
59016 var fullLabel = `Ember.Test.promise: ${label || '<Unknown Promise>'}`;
59017 return new TestPromise(resolver, fullLabel);
59018 }
59019 /**
59020 Replacement for `Ember.RSVP.resolve`
59021 The only difference is this uses
59022 an instance of `Ember.Test.Promise`
59023
59024 @public
59025 @for Ember.Test
59026 @method resolve
59027 @param {Mixed} The value to resolve
59028 @since 1.2.0
59029 */
59030
59031
59032 function resolve(result, label) {
59033 return TestPromise.resolve(result, label);
59034 }
59035
59036 function getLastPromise() {
59037 return lastPromise;
59038 } // This method isolates nested async methods
59039 // so that they don't conflict with other last promises.
59040 //
59041 // 1. Set `Ember.Test.lastPromise` to null
59042 // 2. Invoke method
59043 // 3. Return the last promise created during method
59044
59045
59046 function isolate(onFulfillment, result) {
59047 // Reset lastPromise for nested helpers
59048 lastPromise = null;
59049 var value = onFulfillment(result);
59050 var promise = lastPromise;
59051 lastPromise = null; // If the method returned a promise
59052 // return that promise. If not,
59053 // return the last async helper's promise
59054
59055 if (value && value instanceof TestPromise || !promise) {
59056 return value;
59057 } else {
59058 return (0, _run.default)(() => resolve(promise).then(() => value));
59059 }
59060 }
59061});
59062define("ember-testing/lib/test/run", ["exports", "@ember/runloop"], function (_exports, _runloop) {
59063 "use strict";
59064
59065 Object.defineProperty(_exports, "__esModule", {
59066 value: true
59067 });
59068 _exports.default = run;
59069
59070 function run(fn) {
59071 if (!(0, _runloop.getCurrentRunLoop)()) {
59072 return (0, _runloop.run)(fn);
59073 } else {
59074 return fn();
59075 }
59076 }
59077});
59078define("ember-testing/lib/test/waiters", ["exports"], function (_exports) {
59079 "use strict";
59080
59081 Object.defineProperty(_exports, "__esModule", {
59082 value: true
59083 });
59084 _exports.registerWaiter = registerWaiter;
59085 _exports.unregisterWaiter = unregisterWaiter;
59086 _exports.checkWaiters = checkWaiters;
59087
59088 /**
59089 @module @ember/test
59090 */
59091 var contexts = [];
59092 var callbacks = [];
59093 /**
59094 This allows ember-testing to play nicely with other asynchronous
59095 events, such as an application that is waiting for a CSS3
59096 transition or an IndexDB transaction. The waiter runs periodically
59097 after each async helper (i.e. `click`, `andThen`, `visit`, etc) has executed,
59098 until the returning result is truthy. After the waiters finish, the next async helper
59099 is executed and the process repeats.
59100
59101 For example:
59102
59103 ```javascript
59104 import { registerWaiter } from '@ember/test';
59105
59106 registerWaiter(function() {
59107 return myPendingTransactions() === 0;
59108 });
59109 ```
59110 The `context` argument allows you to optionally specify the `this`
59111 with which your callback will be invoked.
59112
59113 For example:
59114
59115 ```javascript
59116 import { registerWaiter } from '@ember/test';
59117
59118 registerWaiter(MyDB, MyDB.hasPendingTransactions);
59119 ```
59120
59121 @public
59122 @for @ember/test
59123 @static
59124 @method registerWaiter
59125 @param {Object} context (optional)
59126 @param {Function} callback
59127 @since 1.2.0
59128 */
59129
59130 function registerWaiter(context, callback) {
59131 if (arguments.length === 1) {
59132 callback = context;
59133 context = null;
59134 }
59135
59136 if (indexOf(context, callback) > -1) {
59137 return;
59138 }
59139
59140 contexts.push(context);
59141 callbacks.push(callback);
59142 }
59143 /**
59144 `unregisterWaiter` is used to unregister a callback that was
59145 registered with `registerWaiter`.
59146
59147 @public
59148 @for @ember/test
59149 @static
59150 @method unregisterWaiter
59151 @param {Object} context (optional)
59152 @param {Function} callback
59153 @since 1.2.0
59154 */
59155
59156
59157 function unregisterWaiter(context, callback) {
59158 if (!callbacks.length) {
59159 return;
59160 }
59161
59162 if (arguments.length === 1) {
59163 callback = context;
59164 context = null;
59165 }
59166
59167 var i = indexOf(context, callback);
59168
59169 if (i === -1) {
59170 return;
59171 }
59172
59173 contexts.splice(i, 1);
59174 callbacks.splice(i, 1);
59175 }
59176 /**
59177 Iterates through each registered test waiter, and invokes
59178 its callback. If any waiter returns false, this method will return
59179 true indicating that the waiters have not settled yet.
59180
59181 This is generally used internally from the acceptance/integration test
59182 infrastructure.
59183
59184 @public
59185 @for @ember/test
59186 @static
59187 @method checkWaiters
59188 */
59189
59190
59191 function checkWaiters() {
59192 if (!callbacks.length) {
59193 return false;
59194 }
59195
59196 for (var i = 0; i < callbacks.length; i++) {
59197 var context = contexts[i];
59198 var callback = callbacks[i];
59199
59200 if (!callback.call(context)) {
59201 return true;
59202 }
59203 }
59204
59205 return false;
59206 }
59207
59208 function indexOf(context, callback) {
59209 for (var i = 0; i < callbacks.length; i++) {
59210 if (callbacks[i] === callback && contexts[i] === context) {
59211 return i;
59212 }
59213 }
59214
59215 return -1;
59216 }
59217});
59218define("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", "@ember/object/compat", "@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/polyfills", "@ember/deprecated-features", "@ember/component/template-only", "@glimmer/runtime"], function (_exports, _require, _environment, _nodeModule, utils, _container, instrumentation, _meta, metal, _canaryFeatures, EmberDebug, _backburner, _console, _controller, _controller_mixin, _string, _service, _object, _compat, _computed, _runtime, _glimmer, _version, views, routing, extensionSupport, _error, runloop, _errorHandling, _owner, _application, _globalsResolver, _instance, _engine, _instance2, _polyfills, _deprecatedFeatures, _templateOnly, _runtime2) {
59219 "use strict";
59220
59221 Object.defineProperty(_exports, "__esModule", {
59222 value: true
59223 });
59224 _exports.default = void 0;
59225 // eslint-disable-next-line import/no-unresolved
59226 // ****@ember/-internals/environment****
59227 var Ember = typeof _environment.context.imports.Ember === 'object' && _environment.context.imports.Ember || {};
59228 Ember.isNamespace = true;
59229
59230 Ember.toString = function () {
59231 return 'Ember';
59232 };
59233
59234 Object.defineProperty(Ember, 'ENV', {
59235 get: _environment.getENV,
59236 enumerable: false
59237 });
59238 Object.defineProperty(Ember, 'lookup', {
59239 get: _environment.getLookup,
59240 set: _environment.setLookup,
59241 enumerable: false
59242 });
59243
59244 if (_deprecatedFeatures.EMBER_EXTEND_PROTOTYPES) {
59245 Object.defineProperty(Ember, 'EXTEND_PROTOTYPES', {
59246 enumerable: false,
59247
59248 get() {
59249 (true && !(false) && (0, EmberDebug.deprecate)('Accessing Ember.EXTEND_PROTOTYPES is deprecated, please migrate to Ember.ENV.EXTEND_PROTOTYPES', false, {
59250 id: 'ember-env.old-extend-prototypes',
59251 until: '4.0.0'
59252 }));
59253 return _environment.ENV.EXTEND_PROTOTYPES;
59254 }
59255
59256 });
59257 } // ****@ember/application****
59258
59259
59260 Ember.getOwner = _owner.getOwner;
59261 Ember.setOwner = _owner.setOwner;
59262 Ember.Application = _application.default;
59263 Ember.ApplicationInstance = _instance.default;
59264 Object.defineProperty(Ember, 'Resolver', {
59265 get() {
59266 (true && !(false) && (0, EmberDebug.deprecate)('Using the globals resolver is deprecated. Use the ember-resolver package instead. See https://deprecations.emberjs.com/v3.x#toc_ember-deprecate-globals-resolver', false, {
59267 id: 'ember.globals-resolver',
59268 until: '4.0.0',
59269 url: 'https://deprecations.emberjs.com/v3.x#toc_ember-deprecate-globals-resolver'
59270 }));
59271 return _globalsResolver.default;
59272 }
59273
59274 });
59275 Object.defineProperty(Ember, 'DefaultResolver', {
59276 get() {
59277 return Ember.Resolver;
59278 }
59279
59280 }); // ****@ember/engine****
59281
59282 Ember.Engine = _engine.default;
59283 Ember.EngineInstance = _instance2.default; // ****@ember/polyfills****
59284
59285 Ember.assign = _polyfills.assign;
59286 Ember.merge = _polyfills.merge; // ****@ember/-internals/utils****
59287
59288 Ember.generateGuid = utils.generateGuid;
59289 Ember.GUID_KEY = utils.GUID_KEY;
59290 Ember.guidFor = utils.guidFor;
59291 Ember.inspect = utils.inspect;
59292 Ember.makeArray = utils.makeArray;
59293 Ember.canInvoke = utils.canInvoke;
59294 Ember.tryInvoke = utils.tryInvoke;
59295 Ember.wrap = utils.wrap;
59296 Ember.uuid = utils.uuid; // ****@ember/-internals/container****
59297
59298 Ember.Container = _container.Container;
59299 Ember.Registry = _container.Registry; // ****@ember/debug****
59300
59301 Ember.assert = EmberDebug.assert;
59302 Ember.warn = EmberDebug.warn;
59303 Ember.debug = EmberDebug.debug;
59304 Ember.deprecate = EmberDebug.deprecate;
59305 Ember.deprecateFunc = EmberDebug.deprecateFunc;
59306 Ember.runInDebug = EmberDebug.runInDebug; // ****@ember/error****
59307
59308 Ember.Error = _error.default;
59309 /**
59310 @public
59311 @class Ember.Debug
59312 */
59313
59314 Ember.Debug = {
59315 registerDeprecationHandler: EmberDebug.registerDeprecationHandler,
59316 registerWarnHandler: EmberDebug.registerWarnHandler,
59317 isComputed: metal.isComputed
59318 }; // ****@ember/instrumentation****
59319
59320 Ember.instrument = instrumentation.instrument;
59321 Ember.subscribe = instrumentation.subscribe;
59322 Ember.Instrumentation = {
59323 instrument: instrumentation.instrument,
59324 subscribe: instrumentation.subscribe,
59325 unsubscribe: instrumentation.unsubscribe,
59326 reset: instrumentation.reset
59327 }; // ****@ember/runloop****
59328 // Using _globalsRun here so that mutating the function (adding
59329 // `next`, `later`, etc to it) is only available in globals builds
59330
59331 Ember.run = runloop._globalsRun;
59332 Ember.run.backburner = runloop.backburner;
59333 Ember.run.begin = runloop.begin;
59334 Ember.run.bind = runloop.bind;
59335 Ember.run.cancel = runloop.cancel;
59336 Ember.run.debounce = runloop.debounce;
59337 Ember.run.end = runloop.end;
59338 Ember.run.hasScheduledTimers = runloop.hasScheduledTimers;
59339 Ember.run.join = runloop.join;
59340 Ember.run.later = runloop.later;
59341 Ember.run.next = runloop.next;
59342 Ember.run.once = runloop.once;
59343 Ember.run.schedule = runloop.schedule;
59344 Ember.run.scheduleOnce = runloop.scheduleOnce;
59345 Ember.run.throttle = runloop.throttle;
59346 Ember.run.cancelTimers = runloop.cancelTimers;
59347 Object.defineProperty(Ember.run, 'currentRunLoop', {
59348 get: runloop.getCurrentRunLoop,
59349 enumerable: false
59350 }); // ****@ember/-internals/metal****
59351 // Using _globalsComputed here so that mutating the function is only available
59352 // in globals builds
59353
59354 var computed = metal._globalsComputed;
59355 Ember.computed = computed;
59356 Ember._descriptor = metal.nativeDescDecorator;
59357 Ember._tracked = metal.tracked;
59358 computed.alias = metal.alias;
59359 Ember.cacheFor = metal.getCachedValueFor;
59360 Ember.ComputedProperty = metal.ComputedProperty;
59361 Ember._setClassicDecorator = metal.setClassicDecorator;
59362 Ember.meta = _meta.meta;
59363 Ember.get = metal.get;
59364 Ember.getWithDefault = metal.getWithDefault;
59365 Ember._getPath = metal._getPath;
59366 Ember.set = metal.set;
59367 Ember.trySet = metal.trySet;
59368 Ember.FEATURES = (0, _polyfills.assign)({
59369 isEnabled: _canaryFeatures.isEnabled
59370 }, _canaryFeatures.FEATURES);
59371 Ember._Cache = utils.Cache;
59372 Ember.on = metal.on;
59373 Ember.addListener = metal.addListener;
59374 Ember.removeListener = metal.removeListener;
59375 Ember.sendEvent = metal.sendEvent;
59376 Ember.hasListeners = metal.hasListeners;
59377 Ember.isNone = metal.isNone;
59378 Ember.isEmpty = metal.isEmpty;
59379 Ember.isBlank = metal.isBlank;
59380 Ember.isPresent = metal.isPresent;
59381 Ember.notifyPropertyChange = metal.notifyPropertyChange;
59382 Ember.beginPropertyChanges = metal.beginPropertyChanges;
59383 Ember.endPropertyChanges = metal.endPropertyChanges;
59384 Ember.changeProperties = metal.changeProperties;
59385 Ember.platform = {
59386 defineProperty: true,
59387 hasPropertyAccessors: true
59388 };
59389 Ember.defineProperty = metal.defineProperty;
59390 Ember.destroy = _runtime2.destroy;
59391 Ember.libraries = metal.libraries;
59392 Ember.getProperties = metal.getProperties;
59393 Ember.setProperties = metal.setProperties;
59394 Ember.expandProperties = metal.expandProperties;
59395 Ember.addObserver = metal.addObserver;
59396 Ember.removeObserver = metal.removeObserver;
59397 Ember.aliasMethod = metal.aliasMethod;
59398 Ember.observer = metal.observer;
59399 Ember.mixin = metal.mixin;
59400 Ember.Mixin = metal.Mixin;
59401
59402 if (false
59403 /* EMBER_CACHE_API */
59404 ) {
59405 Ember._createCache = metal.createCache;
59406 Ember._cacheGetValue = metal.getValue;
59407 Ember._cacheIsConst = metal.isConst;
59408 }
59409 /**
59410 A function may be assigned to `Ember.onerror` to be called when Ember
59411 internals encounter an error. This is useful for specialized error handling
59412 and reporting code.
59413
59414 ```javascript
59415 import $ from 'jquery';
59416
59417 Ember.onerror = function(error) {
59418 $.ajax('/report-error', 'POST', {
59419 stack: error.stack,
59420 otherInformation: 'whatever app state you want to provide'
59421 });
59422 };
59423 ```
59424
59425 Internally, `Ember.onerror` is used as Backburner's error handler.
59426
59427 @event onerror
59428 @for Ember
59429 @param {Exception} error the error object
59430 @public
59431 */
59432
59433
59434 Object.defineProperty(Ember, 'onerror', {
59435 get: _errorHandling.getOnerror,
59436 set: _errorHandling.setOnerror,
59437 enumerable: false
59438 });
59439 Object.defineProperty(Ember, 'testing', {
59440 get: EmberDebug.isTesting,
59441 set: EmberDebug.setTesting,
59442 enumerable: false
59443 });
59444 Ember._Backburner = _backburner.default; // ****@ember/-internals/console****
59445
59446 if (_deprecatedFeatures.LOGGER) {
59447 Ember.Logger = _console.default;
59448 } // ****@ember/-internals/runtime****
59449
59450
59451 Ember.A = _runtime.A;
59452 Ember.String = {
59453 loc: _string.loc,
59454 w: _string.w,
59455 dasherize: _string.dasherize,
59456 decamelize: _string.decamelize,
59457 camelize: _string.camelize,
59458 classify: _string.classify,
59459 underscore: _string.underscore,
59460 capitalize: _string.capitalize
59461 };
59462 Ember.Object = _runtime.Object;
59463 Ember._RegistryProxyMixin = _runtime.RegistryProxyMixin;
59464 Ember._ContainerProxyMixin = _runtime.ContainerProxyMixin;
59465 Ember.compare = _runtime.compare;
59466 Ember.copy = _runtime.copy;
59467 Ember.isEqual = _runtime.isEqual;
59468 /**
59469 @module ember
59470 */
59471
59472 /**
59473 Namespace for injection helper methods.
59474
59475 @class inject
59476 @namespace Ember
59477 @static
59478 @public
59479 */
59480
59481 Ember.inject = function inject() {
59482 (true && !(false) && (0, EmberDebug.assert)(`Injected properties must be created through helpers, see '${Object.keys(inject).map(k => `'inject.${k}'`).join(' or ')}'`));
59483 };
59484
59485 Ember.inject.service = _service.inject;
59486 Ember.inject.controller = _controller.inject;
59487 Ember.Array = _runtime.Array;
59488 Ember.Comparable = _runtime.Comparable;
59489 Ember.Enumerable = _runtime.Enumerable;
59490 Ember.ArrayProxy = _runtime.ArrayProxy;
59491 Ember.ObjectProxy = _runtime.ObjectProxy;
59492 Ember.ActionHandler = _runtime.ActionHandler;
59493 Ember.CoreObject = _runtime.CoreObject;
59494 Ember.NativeArray = _runtime.NativeArray;
59495 Ember.Copyable = _runtime.Copyable;
59496 Ember.MutableEnumerable = _runtime.MutableEnumerable;
59497 Ember.MutableArray = _runtime.MutableArray;
59498 Ember.TargetActionSupport = _runtime.TargetActionSupport;
59499 Ember.Evented = _runtime.Evented;
59500 Ember.PromiseProxyMixin = _runtime.PromiseProxyMixin;
59501 Ember.Observable = _runtime.Observable;
59502 Ember.typeOf = _runtime.typeOf;
59503 Ember.isArray = _runtime.isArray;
59504 Ember.Object = _runtime.Object;
59505 Ember.onLoad = _application.onLoad;
59506 Ember.runLoadHooks = _application.runLoadHooks;
59507 Ember.Controller = _controller.default;
59508 Ember.ControllerMixin = _controller_mixin.default;
59509 Ember.Service = _service.default;
59510 Ember._ProxyMixin = _runtime._ProxyMixin;
59511 Ember.RSVP = _runtime.RSVP;
59512 Ember.Namespace = _runtime.Namespace;
59513 Ember._action = _object.action;
59514 Ember._dependentKeyCompat = _compat.dependentKeyCompat;
59515 computed.empty = _computed.empty;
59516 computed.notEmpty = _computed.notEmpty;
59517 computed.none = _computed.none;
59518 computed.not = _computed.not;
59519 computed.bool = _computed.bool;
59520 computed.match = _computed.match;
59521 computed.equal = _computed.equal;
59522 computed.gt = _computed.gt;
59523 computed.gte = _computed.gte;
59524 computed.lt = _computed.lt;
59525 computed.lte = _computed.lte;
59526 computed.oneWay = _computed.oneWay;
59527 computed.reads = _computed.oneWay;
59528 computed.readOnly = _computed.readOnly;
59529 computed.deprecatingAlias = _computed.deprecatingAlias;
59530 computed.and = _computed.and;
59531 computed.or = _computed.or;
59532 computed.sum = _computed.sum;
59533 computed.min = _computed.min;
59534 computed.max = _computed.max;
59535 computed.map = _computed.map;
59536 computed.sort = _computed.sort;
59537 computed.setDiff = _computed.setDiff;
59538 computed.mapBy = _computed.mapBy;
59539 computed.filter = _computed.filter;
59540 computed.filterBy = _computed.filterBy;
59541 computed.uniq = _computed.uniq;
59542 computed.uniqBy = _computed.uniqBy;
59543 computed.union = _computed.union;
59544 computed.intersect = _computed.intersect;
59545 computed.collect = _computed.collect;
59546 /**
59547 Defines the hash of localized strings for the current language. Used by
59548 the `String.loc` helper. To localize, add string values to this
59549 hash.
59550
59551 @property STRINGS
59552 @for Ember
59553 @type Object
59554 @private
59555 */
59556
59557 Object.defineProperty(Ember, 'STRINGS', {
59558 configurable: false,
59559 get: _string._getStrings,
59560 set: _string._setStrings
59561 });
59562 /**
59563 Whether searching on the global for new Namespace instances is enabled.
59564
59565 This is only exported here as to not break any addons. Given the new
59566 visit API, you will have issues if you treat this as a indicator of
59567 booted.
59568
59569 Internally this is only exposing a flag in Namespace.
59570
59571 @property BOOTED
59572 @for Ember
59573 @type Boolean
59574 @private
59575 */
59576
59577 Object.defineProperty(Ember, 'BOOTED', {
59578 configurable: false,
59579 enumerable: false,
59580 get: metal.isNamespaceSearchDisabled,
59581 set: metal.setNamespaceSearchDisabled
59582 }); // ****@ember/-internals/glimmer****
59583
59584 Ember.Component = _glimmer.Component;
59585 _glimmer.Helper.helper = _glimmer.helper;
59586 Ember.Helper = _glimmer.Helper;
59587 Ember.Checkbox = _glimmer.Checkbox;
59588 Ember.TextField = _glimmer.TextField;
59589 Ember.TextArea = _glimmer.TextArea;
59590 Ember.LinkComponent = _glimmer.LinkComponent;
59591 Ember._setComponentManager = _glimmer.setComponentManager;
59592 Ember._componentManagerCapabilities = _glimmer.capabilities;
59593 Ember._setModifierManager = _glimmer.setModifierManager;
59594 Ember._modifierManagerCapabilities = _glimmer.modifierCapabilities;
59595
59596 if (true
59597 /* EMBER_GLIMMER_SET_COMPONENT_TEMPLATE */
59598 ) {
59599 Ember._getComponentTemplate = _glimmer.getComponentTemplate;
59600 Ember._setComponentTemplate = _glimmer.setComponentTemplate;
59601 Ember._templateOnlyComponent = _templateOnly.default;
59602 }
59603
59604 Ember._captureRenderTree = EmberDebug.captureRenderTree;
59605 Ember.Handlebars = {
59606 template: _glimmer.template,
59607 Utils: {
59608 escapeExpression: _glimmer.escapeExpression
59609 }
59610 };
59611 Ember.HTMLBars = {
59612 template: _glimmer.template
59613 };
59614
59615 if (_environment.ENV.EXTEND_PROTOTYPES.String) {
59616 String.prototype.htmlSafe = function () {
59617 return (0, _glimmer.htmlSafe)(this);
59618 };
59619 }
59620
59621 Ember.String.htmlSafe = _glimmer.htmlSafe;
59622 Ember.String.isHTMLSafe = _glimmer.isHTMLSafe;
59623 /**
59624 Global hash of shared templates. This will automatically be populated
59625 by the build tools so that you can store your Handlebars templates in
59626 separate files that get loaded into JavaScript at buildtime.
59627
59628 @property TEMPLATES
59629 @for Ember
59630 @type Object
59631 @private
59632 */
59633
59634 Object.defineProperty(Ember, 'TEMPLATES', {
59635 get: _glimmer.getTemplates,
59636 set: _glimmer.setTemplates,
59637 configurable: false,
59638 enumerable: false
59639 });
59640 /**
59641 The semantic version
59642
59643 @property VERSION
59644 @type String
59645 @public
59646 */
59647
59648 Ember.VERSION = _version.default; // ****@ember/-internals/views****
59649
59650 if (_deprecatedFeatures.JQUERY_INTEGRATION && !views.jQueryDisabled) {
59651 Object.defineProperty(Ember, '$', {
59652 get() {
59653 (true && !(false) && (0, EmberDebug.deprecate)("Using Ember.$() has been deprecated, use `import jQuery from 'jquery';` instead", false, {
59654 id: 'ember-views.curly-components.jquery-element',
59655 until: '4.0.0',
59656 url: 'https://emberjs.com/deprecations/v3.x#toc_jquery-apis'
59657 }));
59658 return views.jQuery;
59659 },
59660
59661 configurable: true,
59662 enumerable: true
59663 });
59664 }
59665
59666 Ember.ViewUtils = {
59667 isSimpleClick: views.isSimpleClick,
59668 getElementView: views.getElementView,
59669 getViewElement: views.getViewElement,
59670 getViewBounds: views.getViewBounds,
59671 getViewClientRects: views.getViewClientRects,
59672 getViewBoundingClientRect: views.getViewBoundingClientRect,
59673 getRootViews: views.getRootViews,
59674 getChildViews: views.getChildViews,
59675 isSerializationFirstNode: _glimmer.isSerializationFirstNode
59676 };
59677 Ember.TextSupport = views.TextSupport;
59678 Ember.ComponentLookup = views.ComponentLookup;
59679 Ember.EventDispatcher = views.EventDispatcher; // ****@ember/-internals/routing****
59680
59681 Ember.Location = routing.Location;
59682 Ember.AutoLocation = routing.AutoLocation;
59683 Ember.HashLocation = routing.HashLocation;
59684 Ember.HistoryLocation = routing.HistoryLocation;
59685 Ember.NoneLocation = routing.NoneLocation;
59686 Ember.controllerFor = routing.controllerFor;
59687 Ember.generateControllerFactory = routing.generateControllerFactory;
59688 Ember.generateController = routing.generateController;
59689 Ember.RouterDSL = routing.RouterDSL;
59690 Ember.Router = routing.Router;
59691 Ember.Route = routing.Route;
59692 (0, _application.runLoadHooks)('Ember.Application', _application.default);
59693 Ember.DataAdapter = extensionSupport.DataAdapter;
59694 Ember.ContainerDebugAdapter = extensionSupport.ContainerDebugAdapter;
59695
59696 if ((0, _require.has)('ember-template-compiler')) {
59697 (0, _require.default)("ember-template-compiler");
59698 } // do this to ensure that Ember.Test is defined properly on the global
59699 // if it is present.
59700
59701
59702 if ((0, _require.has)('ember-testing')) {
59703 var testing = (0, _require.default)("ember-testing");
59704 Ember.Test = testing.Test;
59705 Ember.Test.Adapter = testing.Adapter;
59706 Ember.Test.QUnitAdapter = testing.QUnitAdapter;
59707 Ember.setupForTesting = testing.setupForTesting;
59708 }
59709
59710 (0, _application.runLoadHooks)('Ember');
59711 var _default = Ember;
59712 _exports.default = _default;
59713
59714 if (_nodeModule.IS_NODE) {
59715 _nodeModule.module.exports = Ember;
59716 } else {
59717 _environment.context.exports.Ember = _environment.context.exports.Em = Ember;
59718 }
59719 /**
59720 @module jquery
59721 @public
59722 */
59723
59724 /**
59725 @class jquery
59726 @public
59727 @static
59728 */
59729
59730 /**
59731 Alias for jQuery
59732
59733 @for jquery
59734 @method $
59735 @static
59736 @public
59737 */
59738
59739});
59740define("ember/version", ["exports"], function (_exports) {
59741 "use strict";
59742
59743 Object.defineProperty(_exports, "__esModule", {
59744 value: true
59745 });
59746 _exports.default = void 0;
59747 var _default = "3.21.3";
59748 _exports.default = _default;
59749});
59750define("node-module/index", ["exports"], function (_exports) {
59751 "use strict";
59752
59753 Object.defineProperty(_exports, "__esModule", {
59754 value: true
59755 });
59756 _exports.require = _exports.module = _exports.IS_NODE = void 0;
59757
59758 /*global module */
59759 var IS_NODE = typeof module === 'object' && typeof module.require === 'function';
59760 _exports.IS_NODE = IS_NODE;
59761 var exportModule;
59762 _exports.module = exportModule;
59763 var exportRequire;
59764 _exports.require = exportRequire;
59765
59766 if (IS_NODE) {
59767 _exports.module = exportModule = module;
59768 _exports.require = exportRequire = module.require;
59769 } else {
59770 _exports.module = exportModule = null;
59771 _exports.require = exportRequire = null;
59772 }
59773});
59774define("route-recognizer", ["exports"], function (_exports) {
59775 "use strict";
59776
59777 Object.defineProperty(_exports, "__esModule", {
59778 value: true
59779 });
59780 _exports.default = void 0;
59781 var createObject = Object.create;
59782
59783 function createMap() {
59784 var map = createObject(null);
59785 map["__"] = undefined;
59786 delete map["__"];
59787 return map;
59788 }
59789
59790 var Target = function Target(path, matcher, delegate) {
59791 this.path = path;
59792 this.matcher = matcher;
59793 this.delegate = delegate;
59794 };
59795
59796 Target.prototype.to = function to(target, callback) {
59797 var delegate = this.delegate;
59798
59799 if (delegate && delegate.willAddRoute) {
59800 target = delegate.willAddRoute(this.matcher.target, target);
59801 }
59802
59803 this.matcher.add(this.path, target);
59804
59805 if (callback) {
59806 if (callback.length === 0) {
59807 throw new Error("You must have an argument in the function passed to `to`");
59808 }
59809
59810 this.matcher.addChild(this.path, target, callback, this.delegate);
59811 }
59812 };
59813
59814 var Matcher = function Matcher(target) {
59815 this.routes = createMap();
59816 this.children = createMap();
59817 this.target = target;
59818 };
59819
59820 Matcher.prototype.add = function add(path, target) {
59821 this.routes[path] = target;
59822 };
59823
59824 Matcher.prototype.addChild = function addChild(path, target, callback, delegate) {
59825 var matcher = new Matcher(target);
59826 this.children[path] = matcher;
59827 var match = generateMatch(path, matcher, delegate);
59828
59829 if (delegate && delegate.contextEntered) {
59830 delegate.contextEntered(target, match);
59831 }
59832
59833 callback(match);
59834 };
59835
59836 function generateMatch(startingPath, matcher, delegate) {
59837 function match(path, callback) {
59838 var fullPath = startingPath + path;
59839
59840 if (callback) {
59841 callback(generateMatch(fullPath, matcher, delegate));
59842 } else {
59843 return new Target(fullPath, matcher, delegate);
59844 }
59845 }
59846
59847 return match;
59848 }
59849
59850 function addRoute(routeArray, path, handler) {
59851 var len = 0;
59852
59853 for (var i = 0; i < routeArray.length; i++) {
59854 len += routeArray[i].path.length;
59855 }
59856
59857 path = path.substr(len);
59858 var route = {
59859 path: path,
59860 handler: handler
59861 };
59862 routeArray.push(route);
59863 }
59864
59865 function eachRoute(baseRoute, matcher, callback, binding) {
59866 var routes = matcher.routes;
59867 var paths = Object.keys(routes);
59868
59869 for (var i = 0; i < paths.length; i++) {
59870 var path = paths[i];
59871 var routeArray = baseRoute.slice();
59872 addRoute(routeArray, path, routes[path]);
59873 var nested = matcher.children[path];
59874
59875 if (nested) {
59876 eachRoute(routeArray, nested, callback, binding);
59877 } else {
59878 callback.call(binding, routeArray);
59879 }
59880 }
59881 }
59882
59883 var map = function (callback, addRouteCallback) {
59884 var matcher = new Matcher();
59885 callback(generateMatch("", matcher, this.delegate));
59886 eachRoute([], matcher, function (routes) {
59887 if (addRouteCallback) {
59888 addRouteCallback(this, routes);
59889 } else {
59890 this.add(routes);
59891 }
59892 }, this);
59893 }; // Normalizes percent-encoded values in `path` to upper-case and decodes percent-encoded
59894 // values that are not reserved (i.e., unicode characters, emoji, etc). The reserved
59895 // chars are "/" and "%".
59896 // Safe to call multiple times on the same path.
59897 // Normalizes percent-encoded values in `path` to upper-case and decodes percent-encoded
59898
59899
59900 function normalizePath(path) {
59901 return path.split("/").map(normalizeSegment).join("/");
59902 } // We want to ensure the characters "%" and "/" remain in percent-encoded
59903 // form when normalizing paths, so replace them with their encoded form after
59904 // decoding the rest of the path
59905
59906
59907 var SEGMENT_RESERVED_CHARS = /%|\//g;
59908
59909 function normalizeSegment(segment) {
59910 if (segment.length < 3 || segment.indexOf("%") === -1) {
59911 return segment;
59912 }
59913
59914 return decodeURIComponent(segment).replace(SEGMENT_RESERVED_CHARS, encodeURIComponent);
59915 } // We do not want to encode these characters when generating dynamic path segments
59916 // See https://tools.ietf.org/html/rfc3986#section-3.3
59917 // sub-delims: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
59918 // others allowed by RFC 3986: ":", "@"
59919 //
59920 // First encode the entire path segment, then decode any of the encoded special chars.
59921 //
59922 // The chars "!", "'", "(", ")", "*" do not get changed by `encodeURIComponent`,
59923 // so the possible encoded chars are:
59924 // ['%24', '%26', '%2B', '%2C', '%3B', '%3D', '%3A', '%40'].
59925
59926
59927 var PATH_SEGMENT_ENCODINGS = /%(?:2(?:4|6|B|C)|3(?:B|D|A)|40)/g;
59928
59929 function encodePathSegment(str) {
59930 return encodeURIComponent(str).replace(PATH_SEGMENT_ENCODINGS, decodeURIComponent);
59931 }
59932
59933 var escapeRegex = /(\/|\.|\*|\+|\?|\||\(|\)|\[|\]|\{|\}|\\)/g;
59934 var isArray = Array.isArray;
59935 var hasOwnProperty = Object.prototype.hasOwnProperty;
59936
59937 function getParam(params, key) {
59938 if (typeof params !== "object" || params === null) {
59939 throw new Error("You must pass an object as the second argument to `generate`.");
59940 }
59941
59942 if (!hasOwnProperty.call(params, key)) {
59943 throw new Error("You must provide param `" + key + "` to `generate`.");
59944 }
59945
59946 var value = params[key];
59947 var str = typeof value === "string" ? value : "" + value;
59948
59949 if (str.length === 0) {
59950 throw new Error("You must provide a param `" + key + "`.");
59951 }
59952
59953 return str;
59954 }
59955
59956 var eachChar = [];
59957
59958 eachChar[0
59959 /* Static */
59960 ] = function (segment, currentState) {
59961 var state = currentState;
59962 var value = segment.value;
59963
59964 for (var i = 0; i < value.length; i++) {
59965 var ch = value.charCodeAt(i);
59966 state = state.put(ch, false, false);
59967 }
59968
59969 return state;
59970 };
59971
59972 eachChar[1
59973 /* Dynamic */
59974 ] = function (_, currentState) {
59975 return currentState.put(47
59976 /* SLASH */
59977 , true, true);
59978 };
59979
59980 eachChar[2
59981 /* Star */
59982 ] = function (_, currentState) {
59983 return currentState.put(-1
59984 /* ANY */
59985 , false, true);
59986 };
59987
59988 eachChar[4
59989 /* Epsilon */
59990 ] = function (_, currentState) {
59991 return currentState;
59992 };
59993
59994 var regex = [];
59995
59996 regex[0
59997 /* Static */
59998 ] = function (segment) {
59999 return segment.value.replace(escapeRegex, "\\$1");
60000 };
60001
60002 regex[1
60003 /* Dynamic */
60004 ] = function () {
60005 return "([^/]+)";
60006 };
60007
60008 regex[2
60009 /* Star */
60010 ] = function () {
60011 return "(.+)";
60012 };
60013
60014 regex[4
60015 /* Epsilon */
60016 ] = function () {
60017 return "";
60018 };
60019
60020 var generate = [];
60021
60022 generate[0
60023 /* Static */
60024 ] = function (segment) {
60025 return segment.value;
60026 };
60027
60028 generate[1
60029 /* Dynamic */
60030 ] = function (segment, params) {
60031 var value = getParam(params, segment.value);
60032
60033 if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) {
60034 return encodePathSegment(value);
60035 } else {
60036 return value;
60037 }
60038 };
60039
60040 generate[2
60041 /* Star */
60042 ] = function (segment, params) {
60043 return getParam(params, segment.value);
60044 };
60045
60046 generate[4
60047 /* Epsilon */
60048 ] = function () {
60049 return "";
60050 };
60051
60052 var EmptyObject = Object.freeze({});
60053 var EmptyArray = Object.freeze([]); // The `names` will be populated with the paramter name for each dynamic/star
60054 // segment. `shouldDecodes` will be populated with a boolean for each dyanamic/star
60055 // segment, indicating whether it should be decoded during recognition.
60056
60057 function parse(segments, route, types) {
60058 // normalize route as not starting with a "/". Recognition will
60059 // also normalize.
60060 if (route.length > 0 && route.charCodeAt(0) === 47
60061 /* SLASH */
60062 ) {
60063 route = route.substr(1);
60064 }
60065
60066 var parts = route.split("/");
60067 var names = undefined;
60068 var shouldDecodes = undefined;
60069
60070 for (var i = 0; i < parts.length; i++) {
60071 var part = parts[i];
60072 var flags = 0;
60073 var type = 0;
60074
60075 if (part === "") {
60076 type = 4
60077 /* Epsilon */
60078 ;
60079 } else if (part.charCodeAt(0) === 58
60080 /* COLON */
60081 ) {
60082 type = 1
60083 /* Dynamic */
60084 ;
60085 } else if (part.charCodeAt(0) === 42
60086 /* STAR */
60087 ) {
60088 type = 2
60089 /* Star */
60090 ;
60091 } else {
60092 type = 0
60093 /* Static */
60094 ;
60095 }
60096
60097 flags = 2 << type;
60098
60099 if (flags & 12
60100 /* Named */
60101 ) {
60102 part = part.slice(1);
60103 names = names || [];
60104 names.push(part);
60105 shouldDecodes = shouldDecodes || [];
60106 shouldDecodes.push((flags & 4
60107 /* Decoded */
60108 ) !== 0);
60109 }
60110
60111 if (flags & 14
60112 /* Counted */
60113 ) {
60114 types[type]++;
60115 }
60116
60117 segments.push({
60118 type: type,
60119 value: normalizeSegment(part)
60120 });
60121 }
60122
60123 return {
60124 names: names || EmptyArray,
60125 shouldDecodes: shouldDecodes || EmptyArray
60126 };
60127 }
60128
60129 function isEqualCharSpec(spec, char, negate) {
60130 return spec.char === char && spec.negate === negate;
60131 } // A State has a character specification and (`charSpec`) and a list of possible
60132 // subsequent states (`nextStates`).
60133 //
60134 // If a State is an accepting state, it will also have several additional
60135 // properties:
60136 //
60137 // * `regex`: A regular expression that is used to extract parameters from paths
60138 // that reached this accepting state.
60139 // * `handlers`: Information on how to convert the list of captures into calls
60140 // to registered handlers with the specified parameters
60141 // * `types`: How many static, dynamic or star segments in this route. Used to
60142 // decide which route to use if multiple registered routes match a path.
60143 //
60144 // Currently, State is implemented naively by looping over `nextStates` and
60145 // comparing a character specification against a character. A more efficient
60146 // implementation would use a hash of keys pointing at one or more next states.
60147
60148
60149 var State = function State(states, id, char, negate, repeat) {
60150 this.states = states;
60151 this.id = id;
60152 this.char = char;
60153 this.negate = negate;
60154 this.nextStates = repeat ? id : null;
60155 this.pattern = "";
60156 this._regex = undefined;
60157 this.handlers = undefined;
60158 this.types = undefined;
60159 };
60160
60161 State.prototype.regex = function regex$1() {
60162 if (!this._regex) {
60163 this._regex = new RegExp(this.pattern);
60164 }
60165
60166 return this._regex;
60167 };
60168
60169 State.prototype.get = function get(char, negate) {
60170 var this$1 = this;
60171 var nextStates = this.nextStates;
60172
60173 if (nextStates === null) {
60174 return;
60175 }
60176
60177 if (isArray(nextStates)) {
60178 for (var i = 0; i < nextStates.length; i++) {
60179 var child = this$1.states[nextStates[i]];
60180
60181 if (isEqualCharSpec(child, char, negate)) {
60182 return child;
60183 }
60184 }
60185 } else {
60186 var child$1 = this.states[nextStates];
60187
60188 if (isEqualCharSpec(child$1, char, negate)) {
60189 return child$1;
60190 }
60191 }
60192 };
60193
60194 State.prototype.put = function put(char, negate, repeat) {
60195 var state; // If the character specification already exists in a child of the current
60196 // state, just return that state.
60197
60198 if (state = this.get(char, negate)) {
60199 return state;
60200 } // Make a new state for the character spec
60201
60202
60203 var states = this.states;
60204 state = new State(states, states.length, char, negate, repeat);
60205 states[states.length] = state; // Insert the new state as a child of the current state
60206
60207 if (this.nextStates == null) {
60208 this.nextStates = state.id;
60209 } else if (isArray(this.nextStates)) {
60210 this.nextStates.push(state.id);
60211 } else {
60212 this.nextStates = [this.nextStates, state.id];
60213 } // Return the new state
60214
60215
60216 return state;
60217 }; // Find a list of child states matching the next character
60218
60219
60220 State.prototype.match = function match(ch) {
60221 var this$1 = this;
60222 var nextStates = this.nextStates;
60223
60224 if (!nextStates) {
60225 return [];
60226 }
60227
60228 var returned = [];
60229
60230 if (isArray(nextStates)) {
60231 for (var i = 0; i < nextStates.length; i++) {
60232 var child = this$1.states[nextStates[i]];
60233
60234 if (isMatch(child, ch)) {
60235 returned.push(child);
60236 }
60237 }
60238 } else {
60239 var child$1 = this.states[nextStates];
60240
60241 if (isMatch(child$1, ch)) {
60242 returned.push(child$1);
60243 }
60244 }
60245
60246 return returned;
60247 };
60248
60249 function isMatch(spec, char) {
60250 return spec.negate ? spec.char !== char && spec.char !== -1
60251 /* ANY */
60252 : spec.char === char || spec.char === -1
60253 /* ANY */
60254 ;
60255 } // This is a somewhat naive strategy, but should work in a lot of cases
60256 // A better strategy would properly resolve /posts/:id/new and /posts/edit/:id.
60257 //
60258 // This strategy generally prefers more static and less dynamic matching.
60259 // Specifically, it
60260 //
60261 // * prefers fewer stars to more, then
60262 // * prefers using stars for less of the match to more, then
60263 // * prefers fewer dynamic segments to more, then
60264 // * prefers more static segments to more
60265
60266
60267 function sortSolutions(states) {
60268 return states.sort(function (a, b) {
60269 var ref = a.types || [0, 0, 0];
60270 var astatics = ref[0];
60271 var adynamics = ref[1];
60272 var astars = ref[2];
60273 var ref$1 = b.types || [0, 0, 0];
60274 var bstatics = ref$1[0];
60275 var bdynamics = ref$1[1];
60276 var bstars = ref$1[2];
60277
60278 if (astars !== bstars) {
60279 return astars - bstars;
60280 }
60281
60282 if (astars) {
60283 if (astatics !== bstatics) {
60284 return bstatics - astatics;
60285 }
60286
60287 if (adynamics !== bdynamics) {
60288 return bdynamics - adynamics;
60289 }
60290 }
60291
60292 if (adynamics !== bdynamics) {
60293 return adynamics - bdynamics;
60294 }
60295
60296 if (astatics !== bstatics) {
60297 return bstatics - astatics;
60298 }
60299
60300 return 0;
60301 });
60302 }
60303
60304 function recognizeChar(states, ch) {
60305 var nextStates = [];
60306
60307 for (var i = 0, l = states.length; i < l; i++) {
60308 var state = states[i];
60309 nextStates = nextStates.concat(state.match(ch));
60310 }
60311
60312 return nextStates;
60313 }
60314
60315 var RecognizeResults = function RecognizeResults(queryParams) {
60316 this.length = 0;
60317 this.queryParams = queryParams || {};
60318 };
60319
60320 RecognizeResults.prototype.splice = Array.prototype.splice;
60321 RecognizeResults.prototype.slice = Array.prototype.slice;
60322 RecognizeResults.prototype.push = Array.prototype.push;
60323
60324 function findHandler(state, originalPath, queryParams) {
60325 var handlers = state.handlers;
60326 var regex = state.regex();
60327
60328 if (!regex || !handlers) {
60329 throw new Error("state not initialized");
60330 }
60331
60332 var captures = originalPath.match(regex);
60333 var currentCapture = 1;
60334 var result = new RecognizeResults(queryParams);
60335 result.length = handlers.length;
60336
60337 for (var i = 0; i < handlers.length; i++) {
60338 var handler = handlers[i];
60339 var names = handler.names;
60340 var shouldDecodes = handler.shouldDecodes;
60341 var params = EmptyObject;
60342 var isDynamic = false;
60343
60344 if (names !== EmptyArray && shouldDecodes !== EmptyArray) {
60345 for (var j = 0; j < names.length; j++) {
60346 isDynamic = true;
60347 var name = names[j];
60348 var capture = captures && captures[currentCapture++];
60349
60350 if (params === EmptyObject) {
60351 params = {};
60352 }
60353
60354 if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS && shouldDecodes[j]) {
60355 params[name] = capture && decodeURIComponent(capture);
60356 } else {
60357 params[name] = capture;
60358 }
60359 }
60360 }
60361
60362 result[i] = {
60363 handler: handler.handler,
60364 params: params,
60365 isDynamic: isDynamic
60366 };
60367 }
60368
60369 return result;
60370 }
60371
60372 function decodeQueryParamPart(part) {
60373 // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
60374 part = part.replace(/\+/gm, "%20");
60375 var result;
60376
60377 try {
60378 result = decodeURIComponent(part);
60379 } catch (error) {
60380 result = "";
60381 }
60382
60383 return result;
60384 }
60385
60386 var RouteRecognizer = function RouteRecognizer() {
60387 this.names = createMap();
60388 var states = [];
60389 var state = new State(states, 0, -1
60390 /* ANY */
60391 , true, false);
60392 states[0] = state;
60393 this.states = states;
60394 this.rootState = state;
60395 };
60396
60397 RouteRecognizer.prototype.add = function add(routes, options) {
60398 var currentState = this.rootState;
60399 var pattern = "^";
60400 var types = [0, 0, 0];
60401 var handlers = new Array(routes.length);
60402 var allSegments = [];
60403 var isEmpty = true;
60404 var j = 0;
60405
60406 for (var i = 0; i < routes.length; i++) {
60407 var route = routes[i];
60408 var ref = parse(allSegments, route.path, types);
60409 var names = ref.names;
60410 var shouldDecodes = ref.shouldDecodes; // preserve j so it points to the start of newly added segments
60411
60412 for (; j < allSegments.length; j++) {
60413 var segment = allSegments[j];
60414
60415 if (segment.type === 4
60416 /* Epsilon */
60417 ) {
60418 continue;
60419 }
60420
60421 isEmpty = false; // Add a "/" for the new segment
60422
60423 currentState = currentState.put(47
60424 /* SLASH */
60425 , false, false);
60426 pattern += "/"; // Add a representation of the segment to the NFA and regex
60427
60428 currentState = eachChar[segment.type](segment, currentState);
60429 pattern += regex[segment.type](segment);
60430 }
60431
60432 handlers[i] = {
60433 handler: route.handler,
60434 names: names,
60435 shouldDecodes: shouldDecodes
60436 };
60437 }
60438
60439 if (isEmpty) {
60440 currentState = currentState.put(47
60441 /* SLASH */
60442 , false, false);
60443 pattern += "/";
60444 }
60445
60446 currentState.handlers = handlers;
60447 currentState.pattern = pattern + "$";
60448 currentState.types = types;
60449 var name;
60450
60451 if (typeof options === "object" && options !== null && options.as) {
60452 name = options.as;
60453 }
60454
60455 if (name) {
60456 // if (this.names[name]) {
60457 // throw new Error("You may not add a duplicate route named `" + name + "`.");
60458 // }
60459 this.names[name] = {
60460 segments: allSegments,
60461 handlers: handlers
60462 };
60463 }
60464 };
60465
60466 RouteRecognizer.prototype.handlersFor = function handlersFor(name) {
60467 var route = this.names[name];
60468
60469 if (!route) {
60470 throw new Error("There is no route named " + name);
60471 }
60472
60473 var result = new Array(route.handlers.length);
60474
60475 for (var i = 0; i < route.handlers.length; i++) {
60476 var handler = route.handlers[i];
60477 result[i] = handler;
60478 }
60479
60480 return result;
60481 };
60482
60483 RouteRecognizer.prototype.hasRoute = function hasRoute(name) {
60484 return !!this.names[name];
60485 };
60486
60487 RouteRecognizer.prototype.generate = function generate$1(name, params) {
60488 var route = this.names[name];
60489 var output = "";
60490
60491 if (!route) {
60492 throw new Error("There is no route named " + name);
60493 }
60494
60495 var segments = route.segments;
60496
60497 for (var i = 0; i < segments.length; i++) {
60498 var segment = segments[i];
60499
60500 if (segment.type === 4
60501 /* Epsilon */
60502 ) {
60503 continue;
60504 }
60505
60506 output += "/";
60507 output += generate[segment.type](segment, params);
60508 }
60509
60510 if (output.charAt(0) !== "/") {
60511 output = "/" + output;
60512 }
60513
60514 if (params && params.queryParams) {
60515 output += this.generateQueryString(params.queryParams);
60516 }
60517
60518 return output;
60519 };
60520
60521 RouteRecognizer.prototype.generateQueryString = function generateQueryString(params) {
60522 var pairs = [];
60523 var keys = Object.keys(params);
60524 keys.sort();
60525
60526 for (var i = 0; i < keys.length; i++) {
60527 var key = keys[i];
60528 var value = params[key];
60529
60530 if (value == null) {
60531 continue;
60532 }
60533
60534 var pair = encodeURIComponent(key);
60535
60536 if (isArray(value)) {
60537 for (var j = 0; j < value.length; j++) {
60538 var arrayPair = key + "[]" + "=" + encodeURIComponent(value[j]);
60539 pairs.push(arrayPair);
60540 }
60541 } else {
60542 pair += "=" + encodeURIComponent(value);
60543 pairs.push(pair);
60544 }
60545 }
60546
60547 if (pairs.length === 0) {
60548 return "";
60549 }
60550
60551 return "?" + pairs.join("&");
60552 };
60553
60554 RouteRecognizer.prototype.parseQueryString = function parseQueryString(queryString) {
60555 var pairs = queryString.split("&");
60556 var queryParams = {};
60557
60558 for (var i = 0; i < pairs.length; i++) {
60559 var pair = pairs[i].split("="),
60560 key = decodeQueryParamPart(pair[0]),
60561 keyLength = key.length,
60562 isArray = false,
60563 value = void 0;
60564
60565 if (pair.length === 1) {
60566 value = "true";
60567 } else {
60568 // Handle arrays
60569 if (keyLength > 2 && key.slice(keyLength - 2) === "[]") {
60570 isArray = true;
60571 key = key.slice(0, keyLength - 2);
60572
60573 if (!queryParams[key]) {
60574 queryParams[key] = [];
60575 }
60576 }
60577
60578 value = pair[1] ? decodeQueryParamPart(pair[1]) : "";
60579 }
60580
60581 if (isArray) {
60582 queryParams[key].push(value);
60583 } else {
60584 queryParams[key] = value;
60585 }
60586 }
60587
60588 return queryParams;
60589 };
60590
60591 RouteRecognizer.prototype.recognize = function recognize(path) {
60592 var results;
60593 var states = [this.rootState];
60594 var queryParams = {};
60595 var isSlashDropped = false;
60596 var hashStart = path.indexOf("#");
60597
60598 if (hashStart !== -1) {
60599 path = path.substr(0, hashStart);
60600 }
60601
60602 var queryStart = path.indexOf("?");
60603
60604 if (queryStart !== -1) {
60605 var queryString = path.substr(queryStart + 1, path.length);
60606 path = path.substr(0, queryStart);
60607 queryParams = this.parseQueryString(queryString);
60608 }
60609
60610 if (path.charAt(0) !== "/") {
60611 path = "/" + path;
60612 }
60613
60614 var originalPath = path;
60615
60616 if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) {
60617 path = normalizePath(path);
60618 } else {
60619 path = decodeURI(path);
60620 originalPath = decodeURI(originalPath);
60621 }
60622
60623 var pathLen = path.length;
60624
60625 if (pathLen > 1 && path.charAt(pathLen - 1) === "/") {
60626 path = path.substr(0, pathLen - 1);
60627 originalPath = originalPath.substr(0, originalPath.length - 1);
60628 isSlashDropped = true;
60629 }
60630
60631 for (var i = 0; i < path.length; i++) {
60632 states = recognizeChar(states, path.charCodeAt(i));
60633
60634 if (!states.length) {
60635 break;
60636 }
60637 }
60638
60639 var solutions = [];
60640
60641 for (var i$1 = 0; i$1 < states.length; i$1++) {
60642 if (states[i$1].handlers) {
60643 solutions.push(states[i$1]);
60644 }
60645 }
60646
60647 states = sortSolutions(solutions);
60648 var state = solutions[0];
60649
60650 if (state && state.handlers) {
60651 // if a trailing slash was dropped and a star segment is the last segment
60652 // specified, put the trailing slash back
60653 if (isSlashDropped && state.pattern && state.pattern.slice(-5) === "(.+)$") {
60654 originalPath = originalPath + "/";
60655 }
60656
60657 results = findHandler(state, originalPath, queryParams);
60658 }
60659
60660 return results;
60661 };
60662
60663 RouteRecognizer.VERSION = "0.3.4"; // Set to false to opt-out of encoding and decoding path segments.
60664 // See https://github.com/tildeio/route-recognizer/pull/55
60665
60666 RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS = true;
60667 RouteRecognizer.Normalizer = {
60668 normalizeSegment: normalizeSegment,
60669 normalizePath: normalizePath,
60670 encodePathSegment: encodePathSegment
60671 };
60672 RouteRecognizer.prototype.map = map;
60673 var _default = RouteRecognizer;
60674 _exports.default = _default;
60675});
60676define("router_js", ["exports", "@ember/polyfills", "rsvp", "route-recognizer"], function (_exports, _polyfills, _rsvp, _routeRecognizer) {
60677 "use strict";
60678
60679 Object.defineProperty(_exports, "__esModule", {
60680 value: true
60681 });
60682 _exports.logAbort = logAbort;
60683 _exports.InternalRouteInfo = _exports.TransitionError = _exports.TransitionState = _exports.QUERY_PARAMS_SYMBOL = _exports.PARAMS_SYMBOL = _exports.STATE_SYMBOL = _exports.InternalTransition = _exports.default = void 0;
60684
60685 var TransitionAbortedError = function () {
60686 TransitionAbortedError.prototype = Object.create(Error.prototype);
60687 TransitionAbortedError.prototype.constructor = TransitionAbortedError;
60688
60689 function TransitionAbortedError(message) {
60690 var error = Error.call(this, message);
60691 this.name = 'TransitionAborted';
60692 this.message = message || 'TransitionAborted';
60693
60694 if (Error.captureStackTrace) {
60695 Error.captureStackTrace(this, TransitionAbortedError);
60696 } else {
60697 this.stack = error.stack;
60698 }
60699 }
60700
60701 return TransitionAbortedError;
60702 }();
60703
60704 var slice = Array.prototype.slice;
60705 var hasOwnProperty = Object.prototype.hasOwnProperty;
60706 /**
60707 Determines if an object is Promise by checking if it is "thenable".
60708 **/
60709
60710 function isPromise(p) {
60711 return p !== null && typeof p === 'object' && typeof p.then === 'function';
60712 }
60713
60714 function merge(hash, other) {
60715 for (var prop in other) {
60716 if (hasOwnProperty.call(other, prop)) {
60717 hash[prop] = other[prop];
60718 }
60719 }
60720 }
60721 /**
60722 @private
60723
60724 Extracts query params from the end of an array
60725 **/
60726
60727
60728 function extractQueryParams(array) {
60729 var len = array && array.length,
60730 head,
60731 queryParams;
60732
60733 if (len && len > 0) {
60734 var obj = array[len - 1];
60735
60736 if (isQueryParams(obj)) {
60737 queryParams = obj.queryParams;
60738 head = slice.call(array, 0, len - 1);
60739 return [head, queryParams];
60740 }
60741 }
60742
60743 return [array, null];
60744 }
60745
60746 function isQueryParams(obj) {
60747 return obj && hasOwnProperty.call(obj, 'queryParams');
60748 }
60749 /**
60750 @private
60751
60752 Coerces query param properties and array elements into strings.
60753 **/
60754
60755
60756 function coerceQueryParamsToString(queryParams) {
60757 for (var key in queryParams) {
60758 var val = queryParams[key];
60759
60760 if (typeof val === 'number') {
60761 queryParams[key] = '' + val;
60762 } else if (Array.isArray(val)) {
60763 for (var i = 0, l = val.length; i < l; i++) {
60764 val[i] = '' + val[i];
60765 }
60766 }
60767 }
60768 }
60769 /**
60770 @private
60771 */
60772
60773
60774 function log(router, ...args) {
60775 if (!router.log) {
60776 return;
60777 }
60778
60779 if (args.length === 2) {
60780 var [sequence, msg] = args;
60781 router.log('Transition #' + sequence + ': ' + msg);
60782 } else {
60783 var [_msg] = args;
60784 router.log(_msg);
60785 }
60786 }
60787
60788 function isParam(object) {
60789 return typeof object === 'string' || object instanceof String || typeof object === 'number' || object instanceof Number;
60790 }
60791
60792 function forEach(array, callback) {
60793 for (var i = 0, l = array.length; i < l && callback(array[i]) !== false; i++) {// empty intentionally
60794 }
60795 }
60796
60797 function getChangelist(oldObject, newObject) {
60798 var key;
60799 var results = {
60800 all: {},
60801 changed: {},
60802 removed: {}
60803 };
60804 merge(results.all, newObject);
60805 var didChange = false;
60806 coerceQueryParamsToString(oldObject);
60807 coerceQueryParamsToString(newObject); // Calculate removals
60808
60809 for (key in oldObject) {
60810 if (hasOwnProperty.call(oldObject, key)) {
60811 if (!hasOwnProperty.call(newObject, key)) {
60812 didChange = true;
60813 results.removed[key] = oldObject[key];
60814 }
60815 }
60816 } // Calculate changes
60817
60818
60819 for (key in newObject) {
60820 if (hasOwnProperty.call(newObject, key)) {
60821 var oldElement = oldObject[key];
60822 var newElement = newObject[key];
60823
60824 if (isArray(oldElement) && isArray(newElement)) {
60825 if (oldElement.length !== newElement.length) {
60826 results.changed[key] = newObject[key];
60827 didChange = true;
60828 } else {
60829 for (var i = 0, l = oldElement.length; i < l; i++) {
60830 if (oldElement[i] !== newElement[i]) {
60831 results.changed[key] = newObject[key];
60832 didChange = true;
60833 }
60834 }
60835 }
60836 } else if (oldObject[key] !== newObject[key]) {
60837 results.changed[key] = newObject[key];
60838 didChange = true;
60839 }
60840 }
60841 }
60842
60843 return didChange ? results : undefined;
60844 }
60845
60846 function isArray(obj) {
60847 return Array.isArray(obj);
60848 }
60849
60850 function promiseLabel(label) {
60851 return 'Router: ' + label;
60852 }
60853
60854 var STATE_SYMBOL = `__STATE__-2619860001345920-3322w3`;
60855 _exports.STATE_SYMBOL = STATE_SYMBOL;
60856 var PARAMS_SYMBOL = `__PARAMS__-261986232992830203-23323`;
60857 _exports.PARAMS_SYMBOL = PARAMS_SYMBOL;
60858 var QUERY_PARAMS_SYMBOL = `__QPS__-2619863929824844-32323`;
60859 /**
60860 A Transition is a thennable (a promise-like object) that represents
60861 an attempt to transition to another route. It can be aborted, either
60862 explicitly via `abort` or by attempting another transition while a
60863 previous one is still underway. An aborted transition can also
60864 be `retry()`d later.
60865
60866 @class Transition
60867 @constructor
60868 @param {Object} router
60869 @param {Object} intent
60870 @param {Object} state
60871 @param {Object} error
60872 @private
60873 */
60874
60875 _exports.QUERY_PARAMS_SYMBOL = QUERY_PARAMS_SYMBOL;
60876
60877 class Transition {
60878 constructor(router, intent, state, error = undefined, previousTransition = undefined) {
60879 this.from = null;
60880 this.to = undefined;
60881 this.isAborted = false;
60882 this.isActive = true;
60883 this.urlMethod = 'update';
60884 this.resolveIndex = 0;
60885 this.queryParamsOnly = false;
60886 this.isTransition = true;
60887 this.isCausedByAbortingTransition = false;
60888 this.isCausedByInitialTransition = false;
60889 this.isCausedByAbortingReplaceTransition = false;
60890 this._visibleQueryParams = {};
60891 this[STATE_SYMBOL] = state || router.state;
60892 this.intent = intent;
60893 this.router = router;
60894 this.data = intent && intent.data || {};
60895 this.resolvedModels = {};
60896 this[QUERY_PARAMS_SYMBOL] = {};
60897 this.promise = undefined;
60898 this.error = undefined;
60899 this[PARAMS_SYMBOL] = {};
60900 this.routeInfos = [];
60901 this.targetName = undefined;
60902 this.pivotHandler = undefined;
60903 this.sequence = -1;
60904
60905 if (error) {
60906 this.promise = _rsvp.Promise.reject(error);
60907 this.error = error;
60908 return;
60909 } // if you're doing multiple redirects, need the new transition to know if it
60910 // is actually part of the first transition or not. Any further redirects
60911 // in the initial transition also need to know if they are part of the
60912 // initial transition
60913
60914
60915 this.isCausedByAbortingTransition = !!previousTransition;
60916 this.isCausedByInitialTransition = !!previousTransition && (previousTransition.isCausedByInitialTransition || previousTransition.sequence === 0); // Every transition in the chain is a replace
60917
60918 this.isCausedByAbortingReplaceTransition = !!previousTransition && previousTransition.urlMethod === 'replace' && (!previousTransition.isCausedByAbortingTransition || previousTransition.isCausedByAbortingReplaceTransition);
60919
60920 if (state) {
60921 this[PARAMS_SYMBOL] = state.params;
60922 this[QUERY_PARAMS_SYMBOL] = state.queryParams;
60923 this.routeInfos = state.routeInfos;
60924 var len = state.routeInfos.length;
60925
60926 if (len) {
60927 this.targetName = state.routeInfos[len - 1].name;
60928 }
60929
60930 for (var i = 0; i < len; ++i) {
60931 var handlerInfo = state.routeInfos[i]; // TODO: this all seems hacky
60932
60933 if (!handlerInfo.isResolved) {
60934 break;
60935 }
60936
60937 this.pivotHandler = handlerInfo.route;
60938 }
60939
60940 this.sequence = router.currentSequence++;
60941 this.promise = state.resolve(() => {
60942 if (this.isAborted) {
60943 return _rsvp.Promise.reject(false, promiseLabel('Transition aborted - reject'));
60944 }
60945
60946 return _rsvp.Promise.resolve(true);
60947 }, this).catch(result => {
60948 return _rsvp.Promise.reject(this.router.transitionDidError(result, this));
60949 }, promiseLabel('Handle Abort'));
60950 } else {
60951 this.promise = _rsvp.Promise.resolve(this[STATE_SYMBOL]);
60952 this[PARAMS_SYMBOL] = {};
60953 }
60954 }
60955 /**
60956 The Transition's internal promise. Calling `.then` on this property
60957 is that same as calling `.then` on the Transition object itself, but
60958 this property is exposed for when you want to pass around a
60959 Transition's promise, but not the Transition object itself, since
60960 Transition object can be externally `abort`ed, while the promise
60961 cannot.
60962 @property promise
60963 @type {Object}
60964 @public
60965 */
60966
60967 /**
60968 Custom state can be stored on a Transition's `data` object.
60969 This can be useful for decorating a Transition within an earlier
60970 hook and shared with a later hook. Properties set on `data` will
60971 be copied to new transitions generated by calling `retry` on this
60972 transition.
60973 @property data
60974 @type {Object}
60975 @public
60976 */
60977
60978 /**
60979 A standard promise hook that resolves if the transition
60980 succeeds and rejects if it fails/redirects/aborts.
60981 Forwards to the internal `promise` property which you can
60982 use in situations where you want to pass around a thennable,
60983 but not the Transition itself.
60984 @method then
60985 @param {Function} onFulfilled
60986 @param {Function} onRejected
60987 @param {String} label optional string for labeling the promise.
60988 Useful for tooling.
60989 @return {Promise}
60990 @public
60991 */
60992
60993
60994 then(onFulfilled, onRejected, label) {
60995 return this.promise.then(onFulfilled, onRejected, label);
60996 }
60997 /**
60998 Forwards to the internal `promise` property which you can
60999 use in situations where you want to pass around a thennable,
61000 but not the Transition itself.
61001 @method catch
61002 @param {Function} onRejection
61003 @param {String} label optional string for labeling the promise.
61004 Useful for tooling.
61005 @return {Promise}
61006 @public
61007 */
61008
61009
61010 catch(onRejection, label) {
61011 return this.promise.catch(onRejection, label);
61012 }
61013 /**
61014 Forwards to the internal `promise` property which you can
61015 use in situations where you want to pass around a thennable,
61016 but not the Transition itself.
61017 @method finally
61018 @param {Function} callback
61019 @param {String} label optional string for labeling the promise.
61020 Useful for tooling.
61021 @return {Promise}
61022 @public
61023 */
61024
61025
61026 finally(callback, label) {
61027 return this.promise.finally(callback, label);
61028 }
61029 /**
61030 Aborts the Transition. Note you can also implicitly abort a transition
61031 by initiating another transition while a previous one is underway.
61032 @method abort
61033 @return {Transition} this transition
61034 @public
61035 */
61036
61037
61038 abort() {
61039 this.rollback();
61040 var transition = new Transition(this.router, undefined, undefined, undefined);
61041 transition.to = this.from;
61042 transition.from = this.from;
61043 transition.isAborted = true;
61044 this.router.routeWillChange(transition);
61045 this.router.routeDidChange(transition);
61046 return this;
61047 }
61048
61049 rollback() {
61050 if (!this.isAborted) {
61051 log(this.router, this.sequence, this.targetName + ': transition was aborted');
61052
61053 if (this.intent !== undefined && this.intent !== null) {
61054 this.intent.preTransitionState = this.router.state;
61055 }
61056
61057 this.isAborted = true;
61058 this.isActive = false;
61059 this.router.activeTransition = undefined;
61060 }
61061 }
61062
61063 redirect(newTransition) {
61064 this.rollback();
61065 this.router.routeWillChange(newTransition);
61066 }
61067 /**
61068 Retries a previously-aborted transition (making sure to abort the
61069 transition if it's still active). Returns a new transition that
61070 represents the new attempt to transition.
61071 @method retry
61072 @return {Transition} new transition
61073 @public
61074 */
61075
61076
61077 retry() {
61078 // TODO: add tests for merged state retry()s
61079 this.abort();
61080 var newTransition = this.router.transitionByIntent(this.intent, false); // inheriting a `null` urlMethod is not valid
61081 // the urlMethod is only set to `null` when
61082 // the transition is initiated *after* the url
61083 // has been updated (i.e. `router.handleURL`)
61084 //
61085 // in that scenario, the url method cannot be
61086 // inherited for a new transition because then
61087 // the url would not update even though it should
61088
61089 if (this.urlMethod !== null) {
61090 newTransition.method(this.urlMethod);
61091 }
61092
61093 return newTransition;
61094 }
61095 /**
61096 Sets the URL-changing method to be employed at the end of a
61097 successful transition. By default, a new Transition will just
61098 use `updateURL`, but passing 'replace' to this method will
61099 cause the URL to update using 'replaceWith' instead. Omitting
61100 a parameter will disable the URL change, allowing for transitions
61101 that don't update the URL at completion (this is also used for
61102 handleURL, since the URL has already changed before the
61103 transition took place).
61104 @method method
61105 @param {String} method the type of URL-changing method to use
61106 at the end of a transition. Accepted values are 'replace',
61107 falsy values, or any other non-falsy value (which is
61108 interpreted as an updateURL transition).
61109 @return {Transition} this transition
61110 @public
61111 */
61112
61113
61114 method(method) {
61115 this.urlMethod = method;
61116 return this;
61117 } // Alias 'trigger' as 'send'
61118
61119
61120 send(ignoreFailure = false, _name, err, transition, handler) {
61121 this.trigger(ignoreFailure, _name, err, transition, handler);
61122 }
61123 /**
61124 Fires an event on the current list of resolved/resolving
61125 handlers within this transition. Useful for firing events
61126 on route hierarchies that haven't fully been entered yet.
61127 Note: This method is also aliased as `send`
61128 @method trigger
61129 @param {Boolean} [ignoreFailure=false] a boolean specifying whether unhandled events throw an error
61130 @param {String} name the name of the event to fire
61131 @public
61132 */
61133
61134
61135 trigger(ignoreFailure = false, name, ...args) {
61136 // TODO: Deprecate the current signature
61137 if (typeof ignoreFailure === 'string') {
61138 name = ignoreFailure;
61139 ignoreFailure = false;
61140 }
61141
61142 this.router.triggerEvent(this[STATE_SYMBOL].routeInfos.slice(0, this.resolveIndex + 1), ignoreFailure, name, args);
61143 }
61144 /**
61145 Transitions are aborted and their promises rejected
61146 when redirects occur; this method returns a promise
61147 that will follow any redirects that occur and fulfill
61148 with the value fulfilled by any redirecting transitions
61149 that occur.
61150 @method followRedirects
61151 @return {Promise} a promise that fulfills with the same
61152 value that the final redirecting transition fulfills with
61153 @public
61154 */
61155
61156
61157 followRedirects() {
61158 var router = this.router;
61159 return this.promise.catch(function (reason) {
61160 if (router.activeTransition) {
61161 return router.activeTransition.followRedirects();
61162 }
61163
61164 return _rsvp.Promise.reject(reason);
61165 });
61166 }
61167
61168 toString() {
61169 return 'Transition (sequence ' + this.sequence + ')';
61170 }
61171 /**
61172 @private
61173 */
61174
61175
61176 log(message) {
61177 log(this.router, this.sequence, message);
61178 }
61179
61180 }
61181 /**
61182 @private
61183
61184 Logs and returns an instance of TransitionAborted.
61185 */
61186
61187
61188 _exports.InternalTransition = Transition;
61189
61190 function logAbort(transition) {
61191 log(transition.router, transition.sequence, 'detected abort.');
61192 return new TransitionAbortedError();
61193 }
61194
61195 function isTransition(obj) {
61196 return typeof obj === 'object' && obj instanceof Transition && obj.isTransition;
61197 }
61198
61199 function prepareResult(obj) {
61200 if (isTransition(obj)) {
61201 return null;
61202 }
61203
61204 return obj;
61205 }
61206
61207 var ROUTE_INFOS = new WeakMap();
61208
61209 function toReadOnlyRouteInfo(routeInfos, queryParams = {}, includeAttributes = false) {
61210 return routeInfos.map((info, i) => {
61211 var {
61212 name,
61213 params,
61214 paramNames,
61215 context,
61216 route
61217 } = info;
61218
61219 if (ROUTE_INFOS.has(info) && includeAttributes) {
61220 var _routeInfo = ROUTE_INFOS.get(info);
61221
61222 _routeInfo = attachMetadata(route, _routeInfo);
61223 var routeInfoWithAttribute = createRouteInfoWithAttributes(_routeInfo, context);
61224 ROUTE_INFOS.set(info, routeInfoWithAttribute);
61225 return routeInfoWithAttribute;
61226 }
61227
61228 var routeInfo = {
61229 find(predicate, thisArg) {
61230 var publicInfo;
61231 var arr = [];
61232
61233 if (predicate.length === 3) {
61234 arr = routeInfos.map(info => ROUTE_INFOS.get(info));
61235 }
61236
61237 for (var _i = 0; routeInfos.length > _i; _i++) {
61238 publicInfo = ROUTE_INFOS.get(routeInfos[_i]);
61239
61240 if (predicate.call(thisArg, publicInfo, _i, arr)) {
61241 return publicInfo;
61242 }
61243 }
61244
61245 return undefined;
61246 },
61247
61248 get name() {
61249 return name;
61250 },
61251
61252 get paramNames() {
61253 return paramNames;
61254 },
61255
61256 get metadata() {
61257 return buildRouteInfoMetadata(info.route);
61258 },
61259
61260 get parent() {
61261 var parent = routeInfos[i - 1];
61262
61263 if (parent === undefined) {
61264 return null;
61265 }
61266
61267 return ROUTE_INFOS.get(parent);
61268 },
61269
61270 get child() {
61271 var child = routeInfos[i + 1];
61272
61273 if (child === undefined) {
61274 return null;
61275 }
61276
61277 return ROUTE_INFOS.get(child);
61278 },
61279
61280 get localName() {
61281 var parts = this.name.split('.');
61282 return parts[parts.length - 1];
61283 },
61284
61285 get params() {
61286 return params;
61287 },
61288
61289 get queryParams() {
61290 return queryParams;
61291 }
61292
61293 };
61294
61295 if (includeAttributes) {
61296 routeInfo = createRouteInfoWithAttributes(routeInfo, context);
61297 }
61298
61299 ROUTE_INFOS.set(info, routeInfo);
61300 return routeInfo;
61301 });
61302 }
61303
61304 function createRouteInfoWithAttributes(routeInfo, context) {
61305 var attributes = {
61306 get attributes() {
61307 return context;
61308 }
61309
61310 };
61311
61312 if (!Object.isExtensible(routeInfo) || routeInfo.hasOwnProperty('attributes')) {
61313 return Object.freeze((0, _polyfills.assign)({}, routeInfo, attributes));
61314 }
61315
61316 return (0, _polyfills.assign)(routeInfo, attributes);
61317 }
61318
61319 function buildRouteInfoMetadata(route) {
61320 if (route !== undefined && route !== null && route.buildRouteInfoMetadata !== undefined) {
61321 return route.buildRouteInfoMetadata();
61322 }
61323
61324 return null;
61325 }
61326
61327 function attachMetadata(route, routeInfo) {
61328 var metadata = {
61329 get metadata() {
61330 return buildRouteInfoMetadata(route);
61331 }
61332
61333 };
61334
61335 if (!Object.isExtensible(routeInfo) || routeInfo.hasOwnProperty('metadata')) {
61336 return Object.freeze((0, _polyfills.assign)({}, routeInfo, metadata));
61337 }
61338
61339 return (0, _polyfills.assign)(routeInfo, metadata);
61340 }
61341
61342 class InternalRouteInfo {
61343 constructor(router, name, paramNames, route) {
61344 this._routePromise = undefined;
61345 this._route = null;
61346 this.params = {};
61347 this.isResolved = false;
61348 this.name = name;
61349 this.paramNames = paramNames;
61350 this.router = router;
61351
61352 if (route) {
61353 this._processRoute(route);
61354 }
61355 }
61356
61357 getModel(_transition) {
61358 return _rsvp.Promise.resolve(this.context);
61359 }
61360
61361 serialize(_context) {
61362 return this.params || {};
61363 }
61364
61365 resolve(shouldContinue, transition) {
61366 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));
61367 }
61368
61369 becomeResolved(transition, resolvedContext) {
61370 var params = this.serialize(resolvedContext);
61371
61372 if (transition) {
61373 this.stashResolvedModel(transition, resolvedContext);
61374 transition[PARAMS_SYMBOL] = transition[PARAMS_SYMBOL] || {};
61375 transition[PARAMS_SYMBOL][this.name] = params;
61376 }
61377
61378 var context;
61379 var contextsMatch = resolvedContext === this.context;
61380
61381 if ('context' in this || !contextsMatch) {
61382 context = resolvedContext;
61383 }
61384
61385 var cached = ROUTE_INFOS.get(this);
61386 var resolved = new ResolvedRouteInfo(this.router, this.name, this.paramNames, params, this.route, context);
61387
61388 if (cached !== undefined) {
61389 ROUTE_INFOS.set(resolved, cached);
61390 }
61391
61392 return resolved;
61393 }
61394
61395 shouldSupercede(routeInfo) {
61396 // Prefer this newer routeInfo over `other` if:
61397 // 1) The other one doesn't exist
61398 // 2) The names don't match
61399 // 3) This route has a context that doesn't match
61400 // the other one (or the other one doesn't have one).
61401 // 4) This route has parameters that don't match the other.
61402 if (!routeInfo) {
61403 return true;
61404 }
61405
61406 var contextsMatch = routeInfo.context === this.context;
61407 return routeInfo.name !== this.name || 'context' in this && !contextsMatch || this.hasOwnProperty('params') && !paramsMatch(this.params, routeInfo.params);
61408 }
61409
61410 get route() {
61411 // _route could be set to either a route object or undefined, so we
61412 // compare against null to know when it's been set
61413 if (this._route !== null) {
61414 return this._route;
61415 }
61416
61417 return this.fetchRoute();
61418 }
61419
61420 set route(route) {
61421 this._route = route;
61422 }
61423
61424 get routePromise() {
61425 if (this._routePromise) {
61426 return this._routePromise;
61427 }
61428
61429 this.fetchRoute();
61430 return this._routePromise;
61431 }
61432
61433 set routePromise(routePromise) {
61434 this._routePromise = routePromise;
61435 }
61436
61437 log(transition, message) {
61438 if (transition.log) {
61439 transition.log(this.name + ': ' + message);
61440 }
61441 }
61442
61443 updateRoute(route) {
61444 route._internalName = this.name;
61445 return this.route = route;
61446 }
61447
61448 runBeforeModelHook(transition) {
61449 if (transition.trigger) {
61450 transition.trigger(true, 'willResolveModel', transition, this.route);
61451 }
61452
61453 var result;
61454
61455 if (this.route) {
61456 if (this.route.beforeModel !== undefined) {
61457 result = this.route.beforeModel(transition);
61458 }
61459 }
61460
61461 if (isTransition(result)) {
61462 result = null;
61463 }
61464
61465 return _rsvp.Promise.resolve(result);
61466 }
61467
61468 runAfterModelHook(transition, resolvedModel) {
61469 // Stash the resolved model on the payload.
61470 // This makes it possible for users to swap out
61471 // the resolved model in afterModel.
61472 var name = this.name;
61473 this.stashResolvedModel(transition, resolvedModel);
61474 var result;
61475
61476 if (this.route !== undefined) {
61477 if (this.route.afterModel !== undefined) {
61478 result = this.route.afterModel(resolvedModel, transition);
61479 }
61480 }
61481
61482 result = prepareResult(result);
61483 return _rsvp.Promise.resolve(result).then(() => {
61484 // Ignore the fulfilled value returned from afterModel.
61485 // Return the value stashed in resolvedModels, which
61486 // might have been swapped out in afterModel.
61487 return transition.resolvedModels[name];
61488 });
61489 }
61490
61491 checkForAbort(shouldContinue, value) {
61492 return _rsvp.Promise.resolve(shouldContinue()).then(function () {
61493 // We don't care about shouldContinue's resolve value;
61494 // pass along the original value passed to this fn.
61495 return value;
61496 }, null);
61497 }
61498
61499 stashResolvedModel(transition, resolvedModel) {
61500 transition.resolvedModels = transition.resolvedModels || {};
61501 transition.resolvedModels[this.name] = resolvedModel;
61502 }
61503
61504 fetchRoute() {
61505 var route = this.router.getRoute(this.name);
61506 return this._processRoute(route);
61507 }
61508
61509 _processRoute(route) {
61510 // Setup a routePromise so that we can wait for asynchronously loaded routes
61511 this.routePromise = _rsvp.Promise.resolve(route); // Wait until the 'route' property has been updated when chaining to a route
61512 // that is a promise
61513
61514 if (isPromise(route)) {
61515 this.routePromise = this.routePromise.then(r => {
61516 return this.updateRoute(r);
61517 }); // set to undefined to avoid recursive loop in the route getter
61518
61519 return this.route = undefined;
61520 } else if (route) {
61521 return this.updateRoute(route);
61522 }
61523
61524 return undefined;
61525 }
61526
61527 }
61528
61529 _exports.InternalRouteInfo = InternalRouteInfo;
61530
61531 class ResolvedRouteInfo extends InternalRouteInfo {
61532 constructor(router, name, paramNames, params, route, context) {
61533 super(router, name, paramNames, route);
61534 this.params = params;
61535 this.isResolved = true;
61536 this.context = context;
61537 }
61538
61539 resolve(_shouldContinue, transition) {
61540 // A ResolvedRouteInfo just resolved with itself.
61541 if (transition && transition.resolvedModels) {
61542 transition.resolvedModels[this.name] = this.context;
61543 }
61544
61545 return _rsvp.Promise.resolve(this);
61546 }
61547
61548 }
61549
61550 class UnresolvedRouteInfoByParam extends InternalRouteInfo {
61551 constructor(router, name, paramNames, params, route) {
61552 super(router, name, paramNames, route);
61553 this.params = {};
61554 this.params = params;
61555 }
61556
61557 getModel(transition) {
61558 var fullParams = this.params;
61559
61560 if (transition && transition[QUERY_PARAMS_SYMBOL]) {
61561 fullParams = {};
61562 merge(fullParams, this.params);
61563 fullParams.queryParams = transition[QUERY_PARAMS_SYMBOL];
61564 }
61565
61566 var route = this.route;
61567 var result = undefined;
61568
61569 if (route.deserialize) {
61570 result = route.deserialize(fullParams, transition);
61571 } else if (route.model) {
61572 result = route.model(fullParams, transition);
61573 }
61574
61575 if (result && isTransition(result)) {
61576 result = undefined;
61577 }
61578
61579 return _rsvp.Promise.resolve(result);
61580 }
61581
61582 }
61583
61584 class UnresolvedRouteInfoByObject extends InternalRouteInfo {
61585 constructor(router, name, paramNames, context) {
61586 super(router, name, paramNames);
61587 this.context = context;
61588 this.serializer = this.router.getSerializer(name);
61589 }
61590
61591 getModel(transition) {
61592 if (this.router.log !== undefined) {
61593 this.router.log(this.name + ': resolving provided model');
61594 }
61595
61596 return super.getModel(transition);
61597 }
61598 /**
61599 @private
61600 Serializes a route using its custom `serialize` method or
61601 by a default that looks up the expected property name from
61602 the dynamic segment.
61603 @param {Object} model the model to be serialized for this route
61604 */
61605
61606
61607 serialize(model) {
61608 var {
61609 paramNames,
61610 context
61611 } = this;
61612
61613 if (!model) {
61614 model = context;
61615 }
61616
61617 var object = {};
61618
61619 if (isParam(model)) {
61620 object[paramNames[0]] = model;
61621 return object;
61622 } // Use custom serialize if it exists.
61623
61624
61625 if (this.serializer) {
61626 // invoke this.serializer unbound (getSerializer returns a stateless function)
61627 return this.serializer.call(null, model, paramNames);
61628 } else if (this.route !== undefined) {
61629 if (this.route.serialize) {
61630 return this.route.serialize(model, paramNames);
61631 }
61632 }
61633
61634 if (paramNames.length !== 1) {
61635 return;
61636 }
61637
61638 var name = paramNames[0];
61639
61640 if (/_id$/.test(name)) {
61641 object[name] = model.id;
61642 } else {
61643 object[name] = model;
61644 }
61645
61646 return object;
61647 }
61648
61649 }
61650
61651 function paramsMatch(a, b) {
61652 if (!a !== !b) {
61653 // Only one is null.
61654 return false;
61655 }
61656
61657 if (!a) {
61658 // Both must be null.
61659 return true;
61660 } // Note: this assumes that both params have the same
61661 // number of keys, but since we're comparing the
61662 // same routes, they should.
61663
61664
61665 for (var k in a) {
61666 if (a.hasOwnProperty(k) && a[k] !== b[k]) {
61667 return false;
61668 }
61669 }
61670
61671 return true;
61672 }
61673
61674 class TransitionIntent {
61675 constructor(router, data = {}) {
61676 this.router = router;
61677 this.data = data;
61678 }
61679
61680 }
61681
61682 class TransitionState {
61683 constructor() {
61684 this.routeInfos = [];
61685 this.queryParams = {};
61686 this.params = {};
61687 }
61688
61689 promiseLabel(label) {
61690 var targetName = '';
61691 forEach(this.routeInfos, function (routeInfo) {
61692 if (targetName !== '') {
61693 targetName += '.';
61694 }
61695
61696 targetName += routeInfo.name;
61697 return true;
61698 });
61699 return promiseLabel("'" + targetName + "': " + label);
61700 }
61701
61702 resolve(shouldContinue, transition) {
61703 // First, calculate params for this state. This is useful
61704 // information to provide to the various route hooks.
61705 var params = this.params;
61706 forEach(this.routeInfos, routeInfo => {
61707 params[routeInfo.name] = routeInfo.params || {};
61708 return true;
61709 });
61710 transition.resolveIndex = 0;
61711 var currentState = this;
61712 var wasAborted = false; // The prelude RSVP.resolve() asyncs us into the promise land.
61713
61714 return _rsvp.Promise.resolve(null, this.promiseLabel('Start transition')).then(resolveOneRouteInfo, null, this.promiseLabel('Resolve route')).catch(handleError, this.promiseLabel('Handle error'));
61715
61716 function innerShouldContinue() {
61717 return _rsvp.Promise.resolve(shouldContinue(), currentState.promiseLabel('Check if should continue')).catch(function (reason) {
61718 // We distinguish between errors that occurred
61719 // during resolution (e.g. before"Model/model/afterModel),
61720 // and aborts due to a rejecting promise from shouldContinue().
61721 wasAborted = true;
61722 return _rsvp.Promise.reject(reason);
61723 }, currentState.promiseLabel('Handle abort'));
61724 }
61725
61726 function handleError(error) {
61727 // This is the only possible
61728 // reject value of TransitionState#resolve
61729 var routeInfos = currentState.routeInfos;
61730 var errorHandlerIndex = transition.resolveIndex >= routeInfos.length ? routeInfos.length - 1 : transition.resolveIndex;
61731 return _rsvp.Promise.reject(new TransitionError(error, currentState.routeInfos[errorHandlerIndex].route, wasAborted, currentState));
61732 }
61733
61734 function proceed(resolvedRouteInfo) {
61735 var wasAlreadyResolved = currentState.routeInfos[transition.resolveIndex].isResolved; // Swap the previously unresolved routeInfo with
61736 // the resolved routeInfo
61737
61738 currentState.routeInfos[transition.resolveIndex++] = resolvedRouteInfo;
61739
61740 if (!wasAlreadyResolved) {
61741 // Call the redirect hook. The reason we call it here
61742 // vs. afterModel is so that redirects into child
61743 // routes don't re-run the model hooks for this
61744 // already-resolved route.
61745 var {
61746 route
61747 } = resolvedRouteInfo;
61748
61749 if (route !== undefined) {
61750 if (route.redirect) {
61751 route.redirect(resolvedRouteInfo.context, transition);
61752 }
61753 }
61754 } // Proceed after ensuring that the redirect hook
61755 // didn't abort this transition by transitioning elsewhere.
61756
61757
61758 return innerShouldContinue().then(resolveOneRouteInfo, null, currentState.promiseLabel('Resolve route'));
61759 }
61760
61761 function resolveOneRouteInfo() {
61762 if (transition.resolveIndex === currentState.routeInfos.length) {
61763 // This is is the only possible
61764 // fulfill value of TransitionState#resolve
61765 return currentState;
61766 }
61767
61768 var routeInfo = currentState.routeInfos[transition.resolveIndex];
61769 return routeInfo.resolve(innerShouldContinue, transition).then(proceed, null, currentState.promiseLabel('Proceed'));
61770 }
61771 }
61772
61773 }
61774
61775 _exports.TransitionState = TransitionState;
61776
61777 class TransitionError {
61778 constructor(error, route, wasAborted, state) {
61779 this.error = error;
61780 this.route = route;
61781 this.wasAborted = wasAborted;
61782 this.state = state;
61783 }
61784
61785 }
61786
61787 _exports.TransitionError = TransitionError;
61788
61789 class NamedTransitionIntent extends TransitionIntent {
61790 constructor(router, name, pivotHandler, contexts = [], queryParams = {}, data) {
61791 super(router, data);
61792 this.preTransitionState = undefined;
61793 this.name = name;
61794 this.pivotHandler = pivotHandler;
61795 this.contexts = contexts;
61796 this.queryParams = queryParams;
61797 }
61798
61799 applyToState(oldState, isIntermediate) {
61800 // TODO: WTF fix me
61801 var partitionedArgs = extractQueryParams([this.name].concat(this.contexts)),
61802 pureArgs = partitionedArgs[0],
61803 handlers = this.router.recognizer.handlersFor(pureArgs[0]);
61804 var targetRouteName = handlers[handlers.length - 1].handler;
61805 return this.applyToHandlers(oldState, handlers, targetRouteName, isIntermediate, false);
61806 }
61807
61808 applyToHandlers(oldState, parsedHandlers, targetRouteName, isIntermediate, checkingIfActive) {
61809 var i, len;
61810 var newState = new TransitionState();
61811 var objects = this.contexts.slice(0);
61812 var invalidateIndex = parsedHandlers.length; // Pivot handlers are provided for refresh transitions
61813
61814 if (this.pivotHandler) {
61815 for (i = 0, len = parsedHandlers.length; i < len; ++i) {
61816 if (parsedHandlers[i].handler === this.pivotHandler._internalName) {
61817 invalidateIndex = i;
61818 break;
61819 }
61820 }
61821 }
61822
61823 for (i = parsedHandlers.length - 1; i >= 0; --i) {
61824 var result = parsedHandlers[i];
61825 var name = result.handler;
61826 var oldHandlerInfo = oldState.routeInfos[i];
61827 var newHandlerInfo = null;
61828
61829 if (result.names.length > 0) {
61830 if (i >= invalidateIndex) {
61831 newHandlerInfo = this.createParamHandlerInfo(name, result.names, objects, oldHandlerInfo);
61832 } else {
61833 newHandlerInfo = this.getHandlerInfoForDynamicSegment(name, result.names, objects, oldHandlerInfo, targetRouteName, i);
61834 }
61835 } else {
61836 // This route has no dynamic segment.
61837 // Therefore treat as a param-based handlerInfo
61838 // with empty params. This will cause the `model`
61839 // hook to be called with empty params, which is desirable.
61840 newHandlerInfo = this.createParamHandlerInfo(name, result.names, objects, oldHandlerInfo);
61841 }
61842
61843 if (checkingIfActive) {
61844 // If we're performing an isActive check, we want to
61845 // serialize URL params with the provided context, but
61846 // ignore mismatches between old and new context.
61847 newHandlerInfo = newHandlerInfo.becomeResolved(null, newHandlerInfo.context);
61848 var oldContext = oldHandlerInfo && oldHandlerInfo.context;
61849
61850 if (result.names.length > 0 && oldHandlerInfo.context !== undefined && newHandlerInfo.context === oldContext) {
61851 // If contexts match in isActive test, assume params also match.
61852 // This allows for flexibility in not requiring that every last
61853 // handler provide a `serialize` method
61854 newHandlerInfo.params = oldHandlerInfo && oldHandlerInfo.params;
61855 }
61856
61857 newHandlerInfo.context = oldContext;
61858 }
61859
61860 var handlerToUse = oldHandlerInfo;
61861
61862 if (i >= invalidateIndex || newHandlerInfo.shouldSupercede(oldHandlerInfo)) {
61863 invalidateIndex = Math.min(i, invalidateIndex);
61864 handlerToUse = newHandlerInfo;
61865 }
61866
61867 if (isIntermediate && !checkingIfActive) {
61868 handlerToUse = handlerToUse.becomeResolved(null, handlerToUse.context);
61869 }
61870
61871 newState.routeInfos.unshift(handlerToUse);
61872 }
61873
61874 if (objects.length > 0) {
61875 throw new Error('More context objects were passed than there are dynamic segments for the route: ' + targetRouteName);
61876 }
61877
61878 if (!isIntermediate) {
61879 this.invalidateChildren(newState.routeInfos, invalidateIndex);
61880 }
61881
61882 merge(newState.queryParams, this.queryParams || {});
61883 return newState;
61884 }
61885
61886 invalidateChildren(handlerInfos, invalidateIndex) {
61887 for (var i = invalidateIndex, l = handlerInfos.length; i < l; ++i) {
61888 var handlerInfo = handlerInfos[i];
61889
61890 if (handlerInfo.isResolved) {
61891 var {
61892 name,
61893 params,
61894 route,
61895 paramNames
61896 } = handlerInfos[i];
61897 handlerInfos[i] = new UnresolvedRouteInfoByParam(this.router, name, paramNames, params, route);
61898 }
61899 }
61900 }
61901
61902 getHandlerInfoForDynamicSegment(name, names, objects, oldHandlerInfo, _targetRouteName, i) {
61903 var objectToUse;
61904
61905 if (objects.length > 0) {
61906 // Use the objects provided for this transition.
61907 objectToUse = objects[objects.length - 1];
61908
61909 if (isParam(objectToUse)) {
61910 return this.createParamHandlerInfo(name, names, objects, oldHandlerInfo);
61911 } else {
61912 objects.pop();
61913 }
61914 } else if (oldHandlerInfo && oldHandlerInfo.name === name) {
61915 // Reuse the matching oldHandlerInfo
61916 return oldHandlerInfo;
61917 } else {
61918 if (this.preTransitionState) {
61919 var preTransitionHandlerInfo = this.preTransitionState.routeInfos[i];
61920 objectToUse = preTransitionHandlerInfo && preTransitionHandlerInfo.context;
61921 } else {
61922 // Ideally we should throw this error to provide maximal
61923 // information to the user that not enough context objects
61924 // were provided, but this proves too cumbersome in Ember
61925 // in cases where inner template helpers are evaluated
61926 // before parent helpers un-render, in which cases this
61927 // error somewhat prematurely fires.
61928 //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(', ') + "]");
61929 return oldHandlerInfo;
61930 }
61931 }
61932
61933 return new UnresolvedRouteInfoByObject(this.router, name, names, objectToUse);
61934 }
61935
61936 createParamHandlerInfo(name, names, objects, oldHandlerInfo) {
61937 var params = {}; // Soak up all the provided string/numbers
61938
61939 var numNames = names.length;
61940 var missingParams = [];
61941
61942 while (numNames--) {
61943 // Only use old params if the names match with the new handler
61944 var oldParams = oldHandlerInfo && name === oldHandlerInfo.name && oldHandlerInfo.params || {};
61945 var peek = objects[objects.length - 1];
61946 var paramName = names[numNames];
61947
61948 if (isParam(peek)) {
61949 params[paramName] = '' + objects.pop();
61950 } else {
61951 // If we're here, this means only some of the params
61952 // were string/number params, so try and use a param
61953 // value from a previous handler.
61954 if (oldParams.hasOwnProperty(paramName)) {
61955 params[paramName] = oldParams[paramName];
61956 } else {
61957 missingParams.push(paramName);
61958 }
61959 }
61960 }
61961
61962 if (missingParams.length > 0) {
61963 throw new Error(`You didn't provide enough string/numeric parameters to satisfy all of the dynamic segments for route ${name}.` + ` Missing params: ${missingParams}`);
61964 }
61965
61966 return new UnresolvedRouteInfoByParam(this.router, name, names, params);
61967 }
61968
61969 }
61970
61971 var UnrecognizedURLError = function () {
61972 UnrecognizedURLError.prototype = Object.create(Error.prototype);
61973 UnrecognizedURLError.prototype.constructor = UnrecognizedURLError;
61974
61975 function UnrecognizedURLError(message) {
61976 var error = Error.call(this, message);
61977 this.name = 'UnrecognizedURLError';
61978 this.message = message || 'UnrecognizedURL';
61979
61980 if (Error.captureStackTrace) {
61981 Error.captureStackTrace(this, UnrecognizedURLError);
61982 } else {
61983 this.stack = error.stack;
61984 }
61985 }
61986
61987 return UnrecognizedURLError;
61988 }();
61989
61990 class URLTransitionIntent extends TransitionIntent {
61991 constructor(router, url, data) {
61992 super(router, data);
61993 this.url = url;
61994 this.preTransitionState = undefined;
61995 }
61996
61997 applyToState(oldState) {
61998 var newState = new TransitionState();
61999 var results = this.router.recognizer.recognize(this.url),
62000 i,
62001 len;
62002
62003 if (!results) {
62004 throw new UnrecognizedURLError(this.url);
62005 }
62006
62007 var statesDiffer = false;
62008 var _url = this.url; // Checks if a handler is accessible by URL. If it is not, an error is thrown.
62009 // For the case where the handler is loaded asynchronously, the error will be
62010 // thrown once it is loaded.
62011
62012 function checkHandlerAccessibility(handler) {
62013 if (handler && handler.inaccessibleByURL) {
62014 throw new UnrecognizedURLError(_url);
62015 }
62016
62017 return handler;
62018 }
62019
62020 for (i = 0, len = results.length; i < len; ++i) {
62021 var result = results[i];
62022 var name = result.handler;
62023 var paramNames = [];
62024
62025 if (this.router.recognizer.hasRoute(name)) {
62026 paramNames = this.router.recognizer.handlersFor(name)[i].names;
62027 }
62028
62029 var newRouteInfo = new UnresolvedRouteInfoByParam(this.router, name, paramNames, result.params);
62030 var route = newRouteInfo.route;
62031
62032 if (route) {
62033 checkHandlerAccessibility(route);
62034 } else {
62035 // If the hanlder is being loaded asynchronously, check if we can
62036 // access it after it has resolved
62037 newRouteInfo.routePromise = newRouteInfo.routePromise.then(checkHandlerAccessibility);
62038 }
62039
62040 var oldRouteInfo = oldState.routeInfos[i];
62041
62042 if (statesDiffer || newRouteInfo.shouldSupercede(oldRouteInfo)) {
62043 statesDiffer = true;
62044 newState.routeInfos[i] = newRouteInfo;
62045 } else {
62046 newState.routeInfos[i] = oldRouteInfo;
62047 }
62048 }
62049
62050 merge(newState.queryParams, results.queryParams);
62051 return newState;
62052 }
62053
62054 }
62055
62056 class Router {
62057 constructor(logger) {
62058 this._lastQueryParams = {};
62059 this.state = undefined;
62060 this.oldState = undefined;
62061 this.activeTransition = undefined;
62062 this.currentRouteInfos = undefined;
62063 this._changedQueryParams = undefined;
62064 this.currentSequence = 0;
62065 this.log = logger;
62066 this.recognizer = new _routeRecognizer.default();
62067 this.reset();
62068 }
62069 /**
62070 The main entry point into the router. The API is essentially
62071 the same as the `map` method in `route-recognizer`.
62072 This method extracts the String handler at the last `.to()`
62073 call and uses it as the name of the whole route.
62074 @param {Function} callback
62075 */
62076
62077
62078 map(callback) {
62079 this.recognizer.map(callback, function (recognizer, routes) {
62080 for (var i = routes.length - 1, proceed = true; i >= 0 && proceed; --i) {
62081 var route = routes[i];
62082 var handler = route.handler;
62083 recognizer.add(routes, {
62084 as: handler
62085 });
62086 proceed = route.path === '/' || route.path === '' || handler.slice(-6) === '.index';
62087 }
62088 });
62089 }
62090
62091 hasRoute(route) {
62092 return this.recognizer.hasRoute(route);
62093 }
62094
62095 queryParamsTransition(changelist, wasTransitioning, oldState, newState) {
62096 this.fireQueryParamDidChange(newState, changelist);
62097
62098 if (!wasTransitioning && this.activeTransition) {
62099 // One of the routes in queryParamsDidChange
62100 // caused a transition. Just return that transition.
62101 return this.activeTransition;
62102 } else {
62103 // Running queryParamsDidChange didn't change anything.
62104 // Just update query params and be on our way.
62105 // We have to return a noop transition that will
62106 // perform a URL update at the end. This gives
62107 // the user the ability to set the url update
62108 // method (default is replaceState).
62109 var newTransition = new Transition(this, undefined, undefined);
62110 newTransition.queryParamsOnly = true;
62111 oldState.queryParams = this.finalizeQueryParamChange(newState.routeInfos, newState.queryParams, newTransition);
62112 newTransition[QUERY_PARAMS_SYMBOL] = newState.queryParams;
62113 this.toReadOnlyInfos(newTransition, newState);
62114 this.routeWillChange(newTransition);
62115 newTransition.promise = newTransition.promise.then(result => {
62116 if (!newTransition.isAborted) {
62117 this._updateURL(newTransition, oldState);
62118
62119 this.didTransition(this.currentRouteInfos);
62120 this.toInfos(newTransition, newState.routeInfos, true);
62121 this.routeDidChange(newTransition);
62122 }
62123
62124 return result;
62125 }, null, promiseLabel('Transition complete'));
62126 return newTransition;
62127 }
62128 }
62129
62130 transitionByIntent(intent, isIntermediate) {
62131 try {
62132 return this.getTransitionByIntent(intent, isIntermediate);
62133 } catch (e) {
62134 return new Transition(this, intent, undefined, e, undefined);
62135 }
62136 }
62137
62138 recognize(url) {
62139 var intent = new URLTransitionIntent(this, url);
62140 var newState = this.generateNewState(intent);
62141
62142 if (newState === null) {
62143 return newState;
62144 }
62145
62146 var readonlyInfos = toReadOnlyRouteInfo(newState.routeInfos, newState.queryParams);
62147 return readonlyInfos[readonlyInfos.length - 1];
62148 }
62149
62150 recognizeAndLoad(url) {
62151 var intent = new URLTransitionIntent(this, url);
62152 var newState = this.generateNewState(intent);
62153
62154 if (newState === null) {
62155 return _rsvp.Promise.reject(`URL ${url} was not recognized`);
62156 }
62157
62158 var newTransition = new Transition(this, intent, newState, undefined);
62159 return newTransition.then(() => {
62160 var routeInfosWithAttributes = toReadOnlyRouteInfo(newState.routeInfos, newTransition[QUERY_PARAMS_SYMBOL], true);
62161 return routeInfosWithAttributes[routeInfosWithAttributes.length - 1];
62162 });
62163 }
62164
62165 generateNewState(intent) {
62166 try {
62167 return intent.applyToState(this.state, false);
62168 } catch (e) {
62169 return null;
62170 }
62171 }
62172
62173 getTransitionByIntent(intent, isIntermediate) {
62174 var wasTransitioning = !!this.activeTransition;
62175 var oldState = wasTransitioning ? this.activeTransition[STATE_SYMBOL] : this.state;
62176 var newTransition;
62177 var newState = intent.applyToState(oldState, isIntermediate);
62178 var queryParamChangelist = getChangelist(oldState.queryParams, newState.queryParams);
62179
62180 if (routeInfosEqual(newState.routeInfos, oldState.routeInfos)) {
62181 // This is a no-op transition. See if query params changed.
62182 if (queryParamChangelist) {
62183 var _newTransition = this.queryParamsTransition(queryParamChangelist, wasTransitioning, oldState, newState);
62184
62185 _newTransition.queryParamsOnly = true;
62186 return _newTransition;
62187 } // No-op. No need to create a new transition.
62188
62189
62190 return this.activeTransition || new Transition(this, undefined, undefined);
62191 }
62192
62193 if (isIntermediate) {
62194 var transition = new Transition(this, undefined, undefined);
62195 this.toReadOnlyInfos(transition, newState);
62196 this.setupContexts(newState);
62197 this.routeWillChange(transition);
62198 return this.activeTransition;
62199 } // Create a new transition to the destination route.
62200
62201
62202 newTransition = new Transition(this, intent, newState, undefined, this.activeTransition); // transition is to same route with same params, only query params differ.
62203 // not caught above probably because refresh() has been used
62204
62205 if (routeInfosSameExceptQueryParams(newState.routeInfos, oldState.routeInfos)) {
62206 newTransition.queryParamsOnly = true;
62207 }
62208
62209 this.toReadOnlyInfos(newTransition, newState); // Abort and usurp any previously active transition.
62210
62211 if (this.activeTransition) {
62212 this.activeTransition.redirect(newTransition);
62213 }
62214
62215 this.activeTransition = newTransition; // Transition promises by default resolve with resolved state.
62216 // For our purposes, swap out the promise to resolve
62217 // after the transition has been finalized.
62218
62219 newTransition.promise = newTransition.promise.then(result => {
62220 return this.finalizeTransition(newTransition, result);
62221 }, null, promiseLabel('Settle transition promise when transition is finalized'));
62222
62223 if (!wasTransitioning) {
62224 this.notifyExistingHandlers(newState, newTransition);
62225 }
62226
62227 this.fireQueryParamDidChange(newState, queryParamChangelist);
62228 return newTransition;
62229 }
62230 /**
62231 @private
62232 Begins and returns a Transition based on the provided
62233 arguments. Accepts arguments in the form of both URL
62234 transitions and named transitions.
62235 @param {Router} router
62236 @param {Array[Object]} args arguments passed to transitionTo,
62237 replaceWith, or handleURL
62238 */
62239
62240
62241 doTransition(name, modelsArray = [], isIntermediate = false) {
62242 var lastArg = modelsArray[modelsArray.length - 1];
62243 var queryParams = {};
62244
62245 if (lastArg !== undefined && lastArg.hasOwnProperty('queryParams')) {
62246 queryParams = modelsArray.pop().queryParams;
62247 }
62248
62249 var intent;
62250
62251 if (name === undefined) {
62252 log(this, 'Updating query params'); // A query param update is really just a transition
62253 // into the route you're already on.
62254
62255 var {
62256 routeInfos
62257 } = this.state;
62258 intent = new NamedTransitionIntent(this, routeInfos[routeInfos.length - 1].name, undefined, [], queryParams);
62259 } else if (name.charAt(0) === '/') {
62260 log(this, 'Attempting URL transition to ' + name);
62261 intent = new URLTransitionIntent(this, name);
62262 } else {
62263 log(this, 'Attempting transition to ' + name);
62264 intent = new NamedTransitionIntent(this, name, undefined, modelsArray, queryParams);
62265 }
62266
62267 return this.transitionByIntent(intent, isIntermediate);
62268 }
62269 /**
62270 @private
62271 Updates the URL (if necessary) and calls `setupContexts`
62272 to update the router's array of `currentRouteInfos`.
62273 */
62274
62275
62276 finalizeTransition(transition, newState) {
62277 try {
62278 log(transition.router, transition.sequence, 'Resolved all models on destination route; finalizing transition.');
62279 var routeInfos = newState.routeInfos; // Run all the necessary enter/setup/exit hooks
62280
62281 this.setupContexts(newState, transition); // Check if a redirect occurred in enter/setup
62282
62283 if (transition.isAborted) {
62284 // TODO: cleaner way? distinguish b/w targetRouteInfos?
62285 this.state.routeInfos = this.currentRouteInfos;
62286 return _rsvp.Promise.reject(logAbort(transition));
62287 }
62288
62289 this._updateURL(transition, newState);
62290
62291 transition.isActive = false;
62292 this.activeTransition = undefined;
62293 this.triggerEvent(this.currentRouteInfos, true, 'didTransition', []);
62294 this.didTransition(this.currentRouteInfos);
62295 this.toInfos(transition, newState.routeInfos, true);
62296 this.routeDidChange(transition);
62297 log(this, transition.sequence, 'TRANSITION COMPLETE.'); // Resolve with the final route.
62298
62299 return routeInfos[routeInfos.length - 1].route;
62300 } catch (e) {
62301 if (!(e instanceof TransitionAbortedError)) {
62302 var infos = transition[STATE_SYMBOL].routeInfos;
62303 transition.trigger(true, 'error', e, transition, infos[infos.length - 1].route);
62304 transition.abort();
62305 }
62306
62307 throw e;
62308 }
62309 }
62310 /**
62311 @private
62312 Takes an Array of `RouteInfo`s, figures out which ones are
62313 exiting, entering, or changing contexts, and calls the
62314 proper route hooks.
62315 For example, consider the following tree of routes. Each route is
62316 followed by the URL segment it handles.
62317 ```
62318 |~index ("/")
62319 | |~posts ("/posts")
62320 | | |-showPost ("/:id")
62321 | | |-newPost ("/new")
62322 | | |-editPost ("/edit")
62323 | |~about ("/about/:id")
62324 ```
62325 Consider the following transitions:
62326 1. A URL transition to `/posts/1`.
62327 1. Triggers the `*model` callbacks on the
62328 `index`, `posts`, and `showPost` routes
62329 2. Triggers the `enter` callback on the same
62330 3. Triggers the `setup` callback on the same
62331 2. A direct transition to `newPost`
62332 1. Triggers the `exit` callback on `showPost`
62333 2. Triggers the `enter` callback on `newPost`
62334 3. Triggers the `setup` callback on `newPost`
62335 3. A direct transition to `about` with a specified
62336 context object
62337 1. Triggers the `exit` callback on `newPost`
62338 and `posts`
62339 2. Triggers the `serialize` callback on `about`
62340 3. Triggers the `enter` callback on `about`
62341 4. Triggers the `setup` callback on `about`
62342 @param {Router} transition
62343 @param {TransitionState} newState
62344 */
62345
62346
62347 setupContexts(newState, transition) {
62348 var partition = this.partitionRoutes(this.state, newState);
62349 var i, l, route;
62350
62351 for (i = 0, l = partition.exited.length; i < l; i++) {
62352 route = partition.exited[i].route;
62353 delete route.context;
62354
62355 if (route !== undefined) {
62356 if (route._internalReset !== undefined) {
62357 route._internalReset(true, transition);
62358 }
62359
62360 if (route.exit !== undefined) {
62361 route.exit(transition);
62362 }
62363 }
62364 }
62365
62366 var oldState = this.oldState = this.state;
62367 this.state = newState;
62368 var currentRouteInfos = this.currentRouteInfos = partition.unchanged.slice();
62369
62370 try {
62371 for (i = 0, l = partition.reset.length; i < l; i++) {
62372 route = partition.reset[i].route;
62373
62374 if (route !== undefined) {
62375 if (route._internalReset !== undefined) {
62376 route._internalReset(false, transition);
62377 }
62378 }
62379 }
62380
62381 for (i = 0, l = partition.updatedContext.length; i < l; i++) {
62382 this.routeEnteredOrUpdated(currentRouteInfos, partition.updatedContext[i], false, transition);
62383 }
62384
62385 for (i = 0, l = partition.entered.length; i < l; i++) {
62386 this.routeEnteredOrUpdated(currentRouteInfos, partition.entered[i], true, transition);
62387 }
62388 } catch (e) {
62389 this.state = oldState;
62390 this.currentRouteInfos = oldState.routeInfos;
62391 throw e;
62392 }
62393
62394 this.state.queryParams = this.finalizeQueryParamChange(currentRouteInfos, newState.queryParams, transition);
62395 }
62396 /**
62397 @private
62398 Fires queryParamsDidChange event
62399 */
62400
62401
62402 fireQueryParamDidChange(newState, queryParamChangelist) {
62403 // If queryParams changed trigger event
62404 if (queryParamChangelist) {
62405 // This is a little hacky but we need some way of storing
62406 // changed query params given that no activeTransition
62407 // is guaranteed to have occurred.
62408 this._changedQueryParams = queryParamChangelist.all;
62409 this.triggerEvent(newState.routeInfos, true, 'queryParamsDidChange', [queryParamChangelist.changed, queryParamChangelist.all, queryParamChangelist.removed]);
62410 this._changedQueryParams = undefined;
62411 }
62412 }
62413 /**
62414 @private
62415 Helper method used by setupContexts. Handles errors or redirects
62416 that may happen in enter/setup.
62417 */
62418
62419
62420 routeEnteredOrUpdated(currentRouteInfos, routeInfo, enter, transition) {
62421 var route = routeInfo.route,
62422 context = routeInfo.context;
62423
62424 function _routeEnteredOrUpdated(route) {
62425 if (enter) {
62426 if (route.enter !== undefined) {
62427 route.enter(transition);
62428 }
62429 }
62430
62431 if (transition && transition.isAborted) {
62432 throw new TransitionAbortedError();
62433 }
62434
62435 route.context = context;
62436
62437 if (route.contextDidChange !== undefined) {
62438 route.contextDidChange();
62439 }
62440
62441 if (route.setup !== undefined) {
62442 route.setup(context, transition);
62443 }
62444
62445 if (transition && transition.isAborted) {
62446 throw new TransitionAbortedError();
62447 }
62448
62449 currentRouteInfos.push(routeInfo);
62450 return route;
62451 } // If the route doesn't exist, it means we haven't resolved the route promise yet
62452
62453
62454 if (route === undefined) {
62455 routeInfo.routePromise = routeInfo.routePromise.then(_routeEnteredOrUpdated);
62456 } else {
62457 _routeEnteredOrUpdated(route);
62458 }
62459
62460 return true;
62461 }
62462 /**
62463 @private
62464 This function is called when transitioning from one URL to
62465 another to determine which routes are no longer active,
62466 which routes are newly active, and which routes remain
62467 active but have their context changed.
62468 Take a list of old routes and new routes and partition
62469 them into four buckets:
62470 * unchanged: the route was active in both the old and
62471 new URL, and its context remains the same
62472 * updated context: the route was active in both the
62473 old and new URL, but its context changed. The route's
62474 `setup` method, if any, will be called with the new
62475 context.
62476 * exited: the route was active in the old URL, but is
62477 no longer active.
62478 * entered: the route was not active in the old URL, but
62479 is now active.
62480 The PartitionedRoutes structure has four fields:
62481 * `updatedContext`: a list of `RouteInfo` objects that
62482 represent routes that remain active but have a changed
62483 context
62484 * `entered`: a list of `RouteInfo` objects that represent
62485 routes that are newly active
62486 * `exited`: a list of `RouteInfo` objects that are no
62487 longer active.
62488 * `unchanged`: a list of `RouteInfo` objects that remain active.
62489 @param {Array[InternalRouteInfo]} oldRoutes a list of the route
62490 information for the previous URL (or `[]` if this is the
62491 first handled transition)
62492 @param {Array[InternalRouteInfo]} newRoutes a list of the route
62493 information for the new URL
62494 @return {Partition}
62495 */
62496
62497
62498 partitionRoutes(oldState, newState) {
62499 var oldRouteInfos = oldState.routeInfos;
62500 var newRouteInfos = newState.routeInfos;
62501 var routes = {
62502 updatedContext: [],
62503 exited: [],
62504 entered: [],
62505 unchanged: [],
62506 reset: []
62507 };
62508 var routeChanged,
62509 contextChanged = false,
62510 i,
62511 l;
62512
62513 for (i = 0, l = newRouteInfos.length; i < l; i++) {
62514 var oldRouteInfo = oldRouteInfos[i],
62515 newRouteInfo = newRouteInfos[i];
62516
62517 if (!oldRouteInfo || oldRouteInfo.route !== newRouteInfo.route) {
62518 routeChanged = true;
62519 }
62520
62521 if (routeChanged) {
62522 routes.entered.push(newRouteInfo);
62523
62524 if (oldRouteInfo) {
62525 routes.exited.unshift(oldRouteInfo);
62526 }
62527 } else if (contextChanged || oldRouteInfo.context !== newRouteInfo.context) {
62528 contextChanged = true;
62529 routes.updatedContext.push(newRouteInfo);
62530 } else {
62531 routes.unchanged.push(oldRouteInfo);
62532 }
62533 }
62534
62535 for (i = newRouteInfos.length, l = oldRouteInfos.length; i < l; i++) {
62536 routes.exited.unshift(oldRouteInfos[i]);
62537 }
62538
62539 routes.reset = routes.updatedContext.slice();
62540 routes.reset.reverse();
62541 return routes;
62542 }
62543
62544 _updateURL(transition, state) {
62545 var urlMethod = transition.urlMethod;
62546
62547 if (!urlMethod) {
62548 return;
62549 }
62550
62551 var {
62552 routeInfos
62553 } = state;
62554 var {
62555 name: routeName
62556 } = routeInfos[routeInfos.length - 1];
62557 var params = {};
62558
62559 for (var i = routeInfos.length - 1; i >= 0; --i) {
62560 var routeInfo = routeInfos[i];
62561 merge(params, routeInfo.params);
62562
62563 if (routeInfo.route.inaccessibleByURL) {
62564 urlMethod = null;
62565 }
62566 }
62567
62568 if (urlMethod) {
62569 params.queryParams = transition._visibleQueryParams || state.queryParams;
62570 var url = this.recognizer.generate(routeName, params); // transitions during the initial transition must always use replaceURL.
62571 // When the app boots, you are at a url, e.g. /foo. If some route
62572 // redirects to bar as part of the initial transition, you don't want to
62573 // add a history entry for /foo. If you do, pressing back will immediately
62574 // hit the redirect again and take you back to /bar, thus killing the back
62575 // button
62576
62577 var initial = transition.isCausedByInitialTransition; // say you are at / and you click a link to route /foo. In /foo's
62578 // route, the transition is aborted using replacewith('/bar').
62579 // Because the current url is still /, the history entry for / is
62580 // removed from the history. Clicking back will take you to the page
62581 // you were on before /, which is often not even the app, thus killing
62582 // the back button. That's why updateURL is always correct for an
62583 // aborting transition that's not the initial transition
62584
62585 var replaceAndNotAborting = urlMethod === 'replace' && !transition.isCausedByAbortingTransition; // because calling refresh causes an aborted transition, this needs to be
62586 // special cased - if the initial transition is a replace transition, the
62587 // urlMethod should be honored here.
62588
62589 var isQueryParamsRefreshTransition = transition.queryParamsOnly && urlMethod === 'replace'; // say you are at / and you a `replaceWith(/foo)` is called. Then, that
62590 // transition is aborted with `replaceWith(/bar)`. At the end, we should
62591 // end up with /bar replacing /. We are replacing the replace. We only
62592 // will replace the initial route if all subsequent aborts are also
62593 // replaces. However, there is some ambiguity around the correct behavior
62594 // here.
62595
62596 var replacingReplace = urlMethod === 'replace' && transition.isCausedByAbortingReplaceTransition;
62597
62598 if (initial || replaceAndNotAborting || isQueryParamsRefreshTransition || replacingReplace) {
62599 this.replaceURL(url);
62600 } else {
62601 this.updateURL(url);
62602 }
62603 }
62604 }
62605
62606 finalizeQueryParamChange(resolvedHandlers, newQueryParams, transition) {
62607 // We fire a finalizeQueryParamChange event which
62608 // gives the new route hierarchy a chance to tell
62609 // us which query params it's consuming and what
62610 // their final values are. If a query param is
62611 // no longer consumed in the final route hierarchy,
62612 // its serialized segment will be removed
62613 // from the URL.
62614 for (var k in newQueryParams) {
62615 if (newQueryParams.hasOwnProperty(k) && newQueryParams[k] === null) {
62616 delete newQueryParams[k];
62617 }
62618 }
62619
62620 var finalQueryParamsArray = [];
62621 this.triggerEvent(resolvedHandlers, true, 'finalizeQueryParamChange', [newQueryParams, finalQueryParamsArray, transition]);
62622
62623 if (transition) {
62624 transition._visibleQueryParams = {};
62625 }
62626
62627 var finalQueryParams = {};
62628
62629 for (var i = 0, len = finalQueryParamsArray.length; i < len; ++i) {
62630 var qp = finalQueryParamsArray[i];
62631 finalQueryParams[qp.key] = qp.value;
62632
62633 if (transition && qp.visible !== false) {
62634 transition._visibleQueryParams[qp.key] = qp.value;
62635 }
62636 }
62637
62638 return finalQueryParams;
62639 }
62640
62641 toReadOnlyInfos(newTransition, newState) {
62642 var oldRouteInfos = this.state.routeInfos;
62643 this.fromInfos(newTransition, oldRouteInfos);
62644 this.toInfos(newTransition, newState.routeInfos);
62645 this._lastQueryParams = newState.queryParams;
62646 }
62647
62648 fromInfos(newTransition, oldRouteInfos) {
62649 if (newTransition !== undefined && oldRouteInfos.length > 0) {
62650 var fromInfos = toReadOnlyRouteInfo(oldRouteInfos, (0, _polyfills.assign)({}, this._lastQueryParams), true);
62651 newTransition.from = fromInfos[fromInfos.length - 1] || null;
62652 }
62653 }
62654
62655 toInfos(newTransition, newRouteInfos, includeAttributes = false) {
62656 if (newTransition !== undefined && newRouteInfos.length > 0) {
62657 var toInfos = toReadOnlyRouteInfo(newRouteInfos, (0, _polyfills.assign)({}, newTransition[QUERY_PARAMS_SYMBOL]), includeAttributes);
62658 newTransition.to = toInfos[toInfos.length - 1] || null;
62659 }
62660 }
62661
62662 notifyExistingHandlers(newState, newTransition) {
62663 var oldRouteInfos = this.state.routeInfos,
62664 i,
62665 oldRouteInfoLen,
62666 oldHandler,
62667 newRouteInfo;
62668 oldRouteInfoLen = oldRouteInfos.length;
62669
62670 for (i = 0; i < oldRouteInfoLen; i++) {
62671 oldHandler = oldRouteInfos[i];
62672 newRouteInfo = newState.routeInfos[i];
62673
62674 if (!newRouteInfo || oldHandler.name !== newRouteInfo.name) {
62675 break;
62676 }
62677
62678 if (!newRouteInfo.isResolved) {}
62679 }
62680
62681 this.triggerEvent(oldRouteInfos, true, 'willTransition', [newTransition]);
62682 this.routeWillChange(newTransition);
62683 this.willTransition(oldRouteInfos, newState.routeInfos, newTransition);
62684 }
62685 /**
62686 Clears the current and target route routes and triggers exit
62687 on each of them starting at the leaf and traversing up through
62688 its ancestors.
62689 */
62690
62691
62692 reset() {
62693 if (this.state) {
62694 forEach(this.state.routeInfos.slice().reverse(), function (routeInfo) {
62695 var route = routeInfo.route;
62696
62697 if (route !== undefined) {
62698 if (route.exit !== undefined) {
62699 route.exit();
62700 }
62701 }
62702
62703 return true;
62704 });
62705 }
62706
62707 this.oldState = undefined;
62708 this.state = new TransitionState();
62709 this.currentRouteInfos = undefined;
62710 }
62711 /**
62712 let handler = routeInfo.handler;
62713 The entry point for handling a change to the URL (usually
62714 via the back and forward button).
62715 Returns an Array of handlers and the parameters associated
62716 with those parameters.
62717 @param {String} url a URL to process
62718 @return {Array} an Array of `[handler, parameter]` tuples
62719 */
62720
62721
62722 handleURL(url) {
62723 // Perform a URL-based transition, but don't change
62724 // the URL afterward, since it already happened.
62725 if (url.charAt(0) !== '/') {
62726 url = '/' + url;
62727 }
62728
62729 return this.doTransition(url).method(null);
62730 }
62731 /**
62732 Transition into the specified named route.
62733 If necessary, trigger the exit callback on any routes
62734 that are no longer represented by the target route.
62735 @param {String} name the name of the route
62736 */
62737
62738
62739 transitionTo(name, ...contexts) {
62740 if (typeof name === 'object') {
62741 contexts.push(name);
62742 return this.doTransition(undefined, contexts, false);
62743 }
62744
62745 return this.doTransition(name, contexts);
62746 }
62747
62748 intermediateTransitionTo(name, ...args) {
62749 return this.doTransition(name, args, true);
62750 }
62751
62752 refresh(pivotRoute) {
62753 var previousTransition = this.activeTransition;
62754 var state = previousTransition ? previousTransition[STATE_SYMBOL] : this.state;
62755 var routeInfos = state.routeInfos;
62756
62757 if (pivotRoute === undefined) {
62758 pivotRoute = routeInfos[0].route;
62759 }
62760
62761 log(this, 'Starting a refresh transition');
62762 var name = routeInfos[routeInfos.length - 1].name;
62763 var intent = new NamedTransitionIntent(this, name, pivotRoute, [], this._changedQueryParams || state.queryParams);
62764 var newTransition = this.transitionByIntent(intent, false); // if the previous transition is a replace transition, that needs to be preserved
62765
62766 if (previousTransition && previousTransition.urlMethod === 'replace') {
62767 newTransition.method(previousTransition.urlMethod);
62768 }
62769
62770 return newTransition;
62771 }
62772 /**
62773 Identical to `transitionTo` except that the current URL will be replaced
62774 if possible.
62775 This method is intended primarily for use with `replaceState`.
62776 @param {String} name the name of the route
62777 */
62778
62779
62780 replaceWith(name) {
62781 return this.doTransition(name).method('replace');
62782 }
62783 /**
62784 Take a named route and context objects and generate a
62785 URL.
62786 @param {String} name the name of the route to generate
62787 a URL for
62788 @param {...Object} objects a list of objects to serialize
62789 @return {String} a URL
62790 */
62791
62792
62793 generate(routeName, ...args) {
62794 var partitionedArgs = extractQueryParams(args),
62795 suppliedParams = partitionedArgs[0],
62796 queryParams = partitionedArgs[1]; // Construct a TransitionIntent with the provided params
62797 // and apply it to the present state of the router.
62798
62799 var intent = new NamedTransitionIntent(this, routeName, undefined, suppliedParams);
62800 var state = intent.applyToState(this.state, false);
62801 var params = {};
62802
62803 for (var i = 0, len = state.routeInfos.length; i < len; ++i) {
62804 var routeInfo = state.routeInfos[i];
62805 var routeParams = routeInfo.serialize();
62806 merge(params, routeParams);
62807 }
62808
62809 params.queryParams = queryParams;
62810 return this.recognizer.generate(routeName, params);
62811 }
62812
62813 applyIntent(routeName, contexts) {
62814 var intent = new NamedTransitionIntent(this, routeName, undefined, contexts);
62815 var state = this.activeTransition && this.activeTransition[STATE_SYMBOL] || this.state;
62816 return intent.applyToState(state, false);
62817 }
62818
62819 isActiveIntent(routeName, contexts, queryParams, _state) {
62820 var state = _state || this.state,
62821 targetRouteInfos = state.routeInfos,
62822 routeInfo,
62823 len;
62824
62825 if (!targetRouteInfos.length) {
62826 return false;
62827 }
62828
62829 var targetHandler = targetRouteInfos[targetRouteInfos.length - 1].name;
62830 var recogHandlers = this.recognizer.handlersFor(targetHandler);
62831 var index = 0;
62832
62833 for (len = recogHandlers.length; index < len; ++index) {
62834 routeInfo = targetRouteInfos[index];
62835
62836 if (routeInfo.name === routeName) {
62837 break;
62838 }
62839 }
62840
62841 if (index === recogHandlers.length) {
62842 // The provided route name isn't even in the route hierarchy.
62843 return false;
62844 }
62845
62846 var testState = new TransitionState();
62847 testState.routeInfos = targetRouteInfos.slice(0, index + 1);
62848 recogHandlers = recogHandlers.slice(0, index + 1);
62849 var intent = new NamedTransitionIntent(this, targetHandler, undefined, contexts);
62850 var newState = intent.applyToHandlers(testState, recogHandlers, targetHandler, true, true);
62851 var routesEqual = routeInfosEqual(newState.routeInfos, testState.routeInfos);
62852
62853 if (!queryParams || !routesEqual) {
62854 return routesEqual;
62855 } // Get a hash of QPs that will still be active on new route
62856
62857
62858 var activeQPsOnNewHandler = {};
62859 merge(activeQPsOnNewHandler, queryParams);
62860 var activeQueryParams = state.queryParams;
62861
62862 for (var key in activeQueryParams) {
62863 if (activeQueryParams.hasOwnProperty(key) && activeQPsOnNewHandler.hasOwnProperty(key)) {
62864 activeQPsOnNewHandler[key] = activeQueryParams[key];
62865 }
62866 }
62867
62868 return routesEqual && !getChangelist(activeQPsOnNewHandler, queryParams);
62869 }
62870
62871 isActive(routeName, ...args) {
62872 var partitionedArgs = extractQueryParams(args);
62873 return this.isActiveIntent(routeName, partitionedArgs[0], partitionedArgs[1]);
62874 }
62875
62876 trigger(name, ...args) {
62877 this.triggerEvent(this.currentRouteInfos, false, name, args);
62878 }
62879
62880 }
62881
62882 function routeInfosEqual(routeInfos, otherRouteInfos) {
62883 if (routeInfos.length !== otherRouteInfos.length) {
62884 return false;
62885 }
62886
62887 for (var i = 0, len = routeInfos.length; i < len; ++i) {
62888 if (routeInfos[i] !== otherRouteInfos[i]) {
62889 return false;
62890 }
62891 }
62892
62893 return true;
62894 }
62895
62896 function routeInfosSameExceptQueryParams(routeInfos, otherRouteInfos) {
62897 if (routeInfos.length !== otherRouteInfos.length) {
62898 return false;
62899 }
62900
62901 for (var i = 0, len = routeInfos.length; i < len; ++i) {
62902 if (routeInfos[i].name !== otherRouteInfos[i].name) {
62903 return false;
62904 }
62905
62906 if (!paramsEqual(routeInfos[i].params, otherRouteInfos[i].params)) {
62907 return false;
62908 }
62909 }
62910
62911 return true;
62912 }
62913
62914 function paramsEqual(params, otherParams) {
62915 if (!params && !otherParams) {
62916 return true;
62917 } else if (!params && !!otherParams || !!params && !otherParams) {
62918 // one is falsy but other is not;
62919 return false;
62920 }
62921
62922 var keys = Object.keys(params);
62923 var otherKeys = Object.keys(otherParams);
62924
62925 if (keys.length !== otherKeys.length) {
62926 return false;
62927 }
62928
62929 for (var i = 0, len = keys.length; i < len; ++i) {
62930 var key = keys[i];
62931
62932 if (params[key] !== otherParams[key]) {
62933 return false;
62934 }
62935 }
62936
62937 return true;
62938 }
62939
62940 var _default = Router;
62941 _exports.default = _default;
62942});
62943define("rsvp", ["exports"], function (_exports) {
62944 "use strict";
62945
62946 Object.defineProperty(_exports, "__esModule", {
62947 value: true
62948 });
62949 _exports.asap = asap;
62950 _exports.all = all$1;
62951 _exports.allSettled = allSettled;
62952 _exports.race = race$1;
62953 _exports.hash = hash;
62954 _exports.hashSettled = hashSettled;
62955 _exports.rethrow = rethrow;
62956 _exports.defer = defer;
62957 _exports.denodeify = denodeify;
62958 _exports.configure = configure;
62959 _exports.on = on;
62960 _exports.off = off;
62961 _exports.resolve = resolve$2;
62962 _exports.reject = reject$2;
62963 _exports.map = map;
62964 _exports.filter = filter;
62965 _exports.async = _exports.EventTarget = _exports.Promise = _exports.cast = _exports.default = void 0;
62966
62967 function callbacksFor(object) {
62968 var callbacks = object._promiseCallbacks;
62969
62970 if (!callbacks) {
62971 callbacks = object._promiseCallbacks = {};
62972 }
62973
62974 return callbacks;
62975 }
62976 /**
62977 @class EventTarget
62978 @for rsvp
62979 @public
62980 */
62981
62982
62983 var EventTarget = {
62984 /**
62985 `EventTarget.mixin` extends an object with EventTarget methods. For
62986 Example:
62987 ```javascript
62988 import EventTarget from 'rsvp';
62989 let object = {};
62990 EventTarget.mixin(object);
62991 object.on('finished', function(event) {
62992 // handle event
62993 });
62994 object.trigger('finished', { detail: value });
62995 ```
62996 `EventTarget.mixin` also works with prototypes:
62997 ```javascript
62998 import EventTarget from 'rsvp';
62999 let Person = function() {};
63000 EventTarget.mixin(Person.prototype);
63001 let yehuda = new Person();
63002 let tom = new Person();
63003 yehuda.on('poke', function(event) {
63004 console.log('Yehuda says OW');
63005 });
63006 tom.on('poke', function(event) {
63007 console.log('Tom says OW');
63008 });
63009 yehuda.trigger('poke');
63010 tom.trigger('poke');
63011 ```
63012 @method mixin
63013 @for rsvp
63014 @private
63015 @param {Object} object object to extend with EventTarget methods
63016 */
63017 mixin(object) {
63018 object.on = this.on;
63019 object.off = this.off;
63020 object.trigger = this.trigger;
63021 object._promiseCallbacks = undefined;
63022 return object;
63023 },
63024
63025 /**
63026 Registers a callback to be executed when `eventName` is triggered
63027 ```javascript
63028 object.on('event', function(eventInfo){
63029 // handle the event
63030 });
63031 object.trigger('event');
63032 ```
63033 @method on
63034 @for EventTarget
63035 @private
63036 @param {String} eventName name of the event to listen for
63037 @param {Function} callback function to be called when the event is triggered.
63038 */
63039 on(eventName, callback) {
63040 if (typeof callback !== 'function') {
63041 throw new TypeError('Callback must be a function');
63042 }
63043
63044 var allCallbacks = callbacksFor(this);
63045 var callbacks = allCallbacks[eventName];
63046
63047 if (!callbacks) {
63048 callbacks = allCallbacks[eventName] = [];
63049 }
63050
63051 if (callbacks.indexOf(callback) === -1) {
63052 callbacks.push(callback);
63053 }
63054 },
63055
63056 /**
63057 You can use `off` to stop firing a particular callback for an event:
63058 ```javascript
63059 function doStuff() { // do stuff! }
63060 object.on('stuff', doStuff);
63061 object.trigger('stuff'); // doStuff will be called
63062 // Unregister ONLY the doStuff callback
63063 object.off('stuff', doStuff);
63064 object.trigger('stuff'); // doStuff will NOT be called
63065 ```
63066 If you don't pass a `callback` argument to `off`, ALL callbacks for the
63067 event will not be executed when the event fires. For example:
63068 ```javascript
63069 let callback1 = function(){};
63070 let callback2 = function(){};
63071 object.on('stuff', callback1);
63072 object.on('stuff', callback2);
63073 object.trigger('stuff'); // callback1 and callback2 will be executed.
63074 object.off('stuff');
63075 object.trigger('stuff'); // callback1 and callback2 will not be executed!
63076 ```
63077 @method off
63078 @for rsvp
63079 @private
63080 @param {String} eventName event to stop listening to
63081 @param {Function} [callback] optional argument. If given, only the function
63082 given will be removed from the event's callback queue. If no `callback`
63083 argument is given, all callbacks will be removed from the event's callback
63084 queue.
63085 */
63086 off(eventName, callback) {
63087 var allCallbacks = callbacksFor(this);
63088
63089 if (!callback) {
63090 allCallbacks[eventName] = [];
63091 return;
63092 }
63093
63094 var callbacks = allCallbacks[eventName];
63095 var index = callbacks.indexOf(callback);
63096
63097 if (index !== -1) {
63098 callbacks.splice(index, 1);
63099 }
63100 },
63101
63102 /**
63103 Use `trigger` to fire custom events. For example:
63104 ```javascript
63105 object.on('foo', function(){
63106 console.log('foo event happened!');
63107 });
63108 object.trigger('foo');
63109 // 'foo event happened!' logged to the console
63110 ```
63111 You can also pass a value as a second argument to `trigger` that will be
63112 passed as an argument to all event listeners for the event:
63113 ```javascript
63114 object.on('foo', function(value){
63115 console.log(value.name);
63116 });
63117 object.trigger('foo', { name: 'bar' });
63118 // 'bar' logged to the console
63119 ```
63120 @method trigger
63121 @for rsvp
63122 @private
63123 @param {String} eventName name of the event to be triggered
63124 @param {*} [options] optional value to be passed to any event handlers for
63125 the given `eventName`
63126 */
63127 trigger(eventName, options, label) {
63128 var allCallbacks = callbacksFor(this);
63129 var callbacks = allCallbacks[eventName];
63130
63131 if (callbacks) {
63132 // Don't cache the callbacks.length since it may grow
63133 var callback;
63134
63135 for (var i = 0; i < callbacks.length; i++) {
63136 callback = callbacks[i];
63137 callback(options, label);
63138 }
63139 }
63140 }
63141
63142 };
63143 _exports.EventTarget = EventTarget;
63144 var config = {
63145 instrument: false
63146 };
63147 EventTarget['mixin'](config);
63148
63149 function configure(name, value) {
63150 if (arguments.length === 2) {
63151 config[name] = value;
63152 } else {
63153 return config[name];
63154 }
63155 }
63156
63157 var queue = [];
63158
63159 function scheduleFlush() {
63160 setTimeout(() => {
63161 for (var i = 0; i < queue.length; i++) {
63162 var entry = queue[i];
63163 var payload = entry.payload;
63164 payload.guid = payload.key + payload.id;
63165 payload.childGuid = payload.key + payload.childId;
63166
63167 if (payload.error) {
63168 payload.stack = payload.error.stack;
63169 }
63170
63171 config['trigger'](entry.name, entry.payload);
63172 }
63173
63174 queue.length = 0;
63175 }, 50);
63176 }
63177
63178 function instrument(eventName, promise, child) {
63179 if (1 === queue.push({
63180 name: eventName,
63181 payload: {
63182 key: promise._guidKey,
63183 id: promise._id,
63184 eventName: eventName,
63185 detail: promise._result,
63186 childId: child && child._id,
63187 label: promise._label,
63188 timeStamp: Date.now(),
63189 error: config["instrument-with-stack"] ? new Error(promise._label) : null
63190 }
63191 })) {
63192 scheduleFlush();
63193 }
63194 }
63195 /**
63196 `Promise.resolve` returns a promise that will become resolved with the
63197 passed `value`. It is shorthand for the following:
63198
63199 ```javascript
63200 import Promise from 'rsvp';
63201
63202 let promise = new Promise(function(resolve, reject){
63203 resolve(1);
63204 });
63205
63206 promise.then(function(value){
63207 // value === 1
63208 });
63209 ```
63210
63211 Instead of writing the above, your code now simply becomes the following:
63212
63213 ```javascript
63214 import Promise from 'rsvp';
63215
63216 let promise = RSVP.Promise.resolve(1);
63217
63218 promise.then(function(value){
63219 // value === 1
63220 });
63221 ```
63222
63223 @method resolve
63224 @for Promise
63225 @static
63226 @param {*} object value that the returned promise will be resolved with
63227 @param {String} [label] optional string for identifying the returned promise.
63228 Useful for tooling.
63229 @return {Promise} a promise that will become fulfilled with the given
63230 `value`
63231 */
63232
63233
63234 function resolve$$1(object, label) {
63235 /*jshint validthis:true */
63236 var Constructor = this;
63237
63238 if (object && typeof object === 'object' && object.constructor === Constructor) {
63239 return object;
63240 }
63241
63242 var promise = new Constructor(noop, label);
63243 resolve$1(promise, object);
63244 return promise;
63245 }
63246
63247 function withOwnPromise() {
63248 return new TypeError('A promises callback cannot return that same promise.');
63249 }
63250
63251 function objectOrFunction(x) {
63252 var type = typeof x;
63253 return x !== null && (type === 'object' || type === 'function');
63254 }
63255
63256 function noop() {}
63257
63258 var PENDING = void 0;
63259 var FULFILLED = 1;
63260 var REJECTED = 2;
63261
63262 function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
63263 try {
63264 then$$1.call(value, fulfillmentHandler, rejectionHandler);
63265 } catch (e) {
63266 return e;
63267 }
63268 }
63269
63270 function handleForeignThenable(promise, thenable, then$$1) {
63271 config.async(promise => {
63272 var sealed = false;
63273 var error = tryThen(then$$1, thenable, value => {
63274 if (sealed) {
63275 return;
63276 }
63277
63278 sealed = true;
63279
63280 if (thenable === value) {
63281 fulfill(promise, value);
63282 } else {
63283 resolve$1(promise, value);
63284 }
63285 }, reason => {
63286 if (sealed) {
63287 return;
63288 }
63289
63290 sealed = true;
63291 reject(promise, reason);
63292 }, 'Settle: ' + (promise._label || ' unknown promise'));
63293
63294 if (!sealed && error) {
63295 sealed = true;
63296 reject(promise, error);
63297 }
63298 }, promise);
63299 }
63300
63301 function handleOwnThenable(promise, thenable) {
63302 if (thenable._state === FULFILLED) {
63303 fulfill(promise, thenable._result);
63304 } else if (thenable._state === REJECTED) {
63305 thenable._onError = null;
63306 reject(promise, thenable._result);
63307 } else {
63308 subscribe(thenable, undefined, value => {
63309 if (thenable === value) {
63310 fulfill(promise, value);
63311 } else {
63312 resolve$1(promise, value);
63313 }
63314 }, reason => reject(promise, reason));
63315 }
63316 }
63317
63318 function handleMaybeThenable(promise, maybeThenable, then$$1) {
63319 var isOwnThenable = maybeThenable.constructor === promise.constructor && then$$1 === then && promise.constructor.resolve === resolve$$1;
63320
63321 if (isOwnThenable) {
63322 handleOwnThenable(promise, maybeThenable);
63323 } else if (typeof then$$1 === 'function') {
63324 handleForeignThenable(promise, maybeThenable, then$$1);
63325 } else {
63326 fulfill(promise, maybeThenable);
63327 }
63328 }
63329
63330 function resolve$1(promise, value) {
63331 if (promise === value) {
63332 fulfill(promise, value);
63333 } else if (objectOrFunction(value)) {
63334 var then$$1;
63335
63336 try {
63337 then$$1 = value.then;
63338 } catch (error) {
63339 reject(promise, error);
63340 return;
63341 }
63342
63343 handleMaybeThenable(promise, value, then$$1);
63344 } else {
63345 fulfill(promise, value);
63346 }
63347 }
63348
63349 function publishRejection(promise) {
63350 if (promise._onError) {
63351 promise._onError(promise._result);
63352 }
63353
63354 publish(promise);
63355 }
63356
63357 function fulfill(promise, value) {
63358 if (promise._state !== PENDING) {
63359 return;
63360 }
63361
63362 promise._result = value;
63363 promise._state = FULFILLED;
63364
63365 if (promise._subscribers.length === 0) {
63366 if (config.instrument) {
63367 instrument('fulfilled', promise);
63368 }
63369 } else {
63370 config.async(publish, promise);
63371 }
63372 }
63373
63374 function reject(promise, reason) {
63375 if (promise._state !== PENDING) {
63376 return;
63377 }
63378
63379 promise._state = REJECTED;
63380 promise._result = reason;
63381 config.async(publishRejection, promise);
63382 }
63383
63384 function subscribe(parent, child, onFulfillment, onRejection) {
63385 var subscribers = parent._subscribers;
63386 var length = subscribers.length;
63387 parent._onError = null;
63388 subscribers[length] = child;
63389 subscribers[length + FULFILLED] = onFulfillment;
63390 subscribers[length + REJECTED] = onRejection;
63391
63392 if (length === 0 && parent._state) {
63393 config.async(publish, parent);
63394 }
63395 }
63396
63397 function publish(promise) {
63398 var subscribers = promise._subscribers;
63399 var settled = promise._state;
63400
63401 if (config.instrument) {
63402 instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise);
63403 }
63404
63405 if (subscribers.length === 0) {
63406 return;
63407 }
63408
63409 var child,
63410 callback,
63411 result = promise._result;
63412
63413 for (var i = 0; i < subscribers.length; i += 3) {
63414 child = subscribers[i];
63415 callback = subscribers[i + settled];
63416
63417 if (child) {
63418 invokeCallback(settled, child, callback, result);
63419 } else {
63420 callback(result);
63421 }
63422 }
63423
63424 promise._subscribers.length = 0;
63425 }
63426
63427 function invokeCallback(state, promise, callback, result) {
63428 var hasCallback = typeof callback === 'function';
63429 var value,
63430 succeeded = true,
63431 error;
63432
63433 if (hasCallback) {
63434 try {
63435 value = callback(result);
63436 } catch (e) {
63437 succeeded = false;
63438 error = e;
63439 }
63440 } else {
63441 value = result;
63442 }
63443
63444 if (promise._state !== PENDING) {// noop
63445 } else if (value === promise) {
63446 reject(promise, withOwnPromise());
63447 } else if (succeeded === false) {
63448 reject(promise, error);
63449 } else if (hasCallback) {
63450 resolve$1(promise, value);
63451 } else if (state === FULFILLED) {
63452 fulfill(promise, value);
63453 } else if (state === REJECTED) {
63454 reject(promise, value);
63455 }
63456 }
63457
63458 function initializePromise(promise, resolver) {
63459 var resolved = false;
63460
63461 try {
63462 resolver(value => {
63463 if (resolved) {
63464 return;
63465 }
63466
63467 resolved = true;
63468 resolve$1(promise, value);
63469 }, reason => {
63470 if (resolved) {
63471 return;
63472 }
63473
63474 resolved = true;
63475 reject(promise, reason);
63476 });
63477 } catch (e) {
63478 reject(promise, e);
63479 }
63480 }
63481
63482 function then(onFulfillment, onRejection, label) {
63483 var parent = this;
63484 var state = parent._state;
63485
63486 if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) {
63487 config.instrument && instrument('chained', parent, parent);
63488 return parent;
63489 }
63490
63491 parent._onError = null;
63492 var child = new parent.constructor(noop, label);
63493 var result = parent._result;
63494 config.instrument && instrument('chained', parent, child);
63495
63496 if (state === PENDING) {
63497 subscribe(parent, child, onFulfillment, onRejection);
63498 } else {
63499 var callback = state === FULFILLED ? onFulfillment : onRejection;
63500 config.async(() => invokeCallback(state, child, callback, result));
63501 }
63502
63503 return child;
63504 }
63505
63506 class Enumerator {
63507 constructor(Constructor, input, abortOnReject, label) {
63508 this._instanceConstructor = Constructor;
63509 this.promise = new Constructor(noop, label);
63510 this._abortOnReject = abortOnReject;
63511 this._isUsingOwnPromise = Constructor === Promise;
63512 this._isUsingOwnResolve = Constructor.resolve === resolve$$1;
63513
63514 this._init(...arguments);
63515 }
63516
63517 _init(Constructor, input) {
63518 var len = input.length || 0;
63519 this.length = len;
63520 this._remaining = len;
63521 this._result = new Array(len);
63522
63523 this._enumerate(input);
63524 }
63525
63526 _enumerate(input) {
63527 var length = this.length;
63528 var promise = this.promise;
63529
63530 for (var i = 0; promise._state === PENDING && i < length; i++) {
63531 this._eachEntry(input[i], i, true);
63532 }
63533
63534 this._checkFullfillment();
63535 }
63536
63537 _checkFullfillment() {
63538 if (this._remaining === 0) {
63539 var result = this._result;
63540 fulfill(this.promise, result);
63541 this._result = null;
63542 }
63543 }
63544
63545 _settleMaybeThenable(entry, i, firstPass) {
63546 var c = this._instanceConstructor;
63547
63548 if (this._isUsingOwnResolve) {
63549 var then$$1,
63550 error,
63551 succeeded = true;
63552
63553 try {
63554 then$$1 = entry.then;
63555 } catch (e) {
63556 succeeded = false;
63557 error = e;
63558 }
63559
63560 if (then$$1 === then && entry._state !== PENDING) {
63561 entry._onError = null;
63562
63563 this._settledAt(entry._state, i, entry._result, firstPass);
63564 } else if (typeof then$$1 !== 'function') {
63565 this._settledAt(FULFILLED, i, entry, firstPass);
63566 } else if (this._isUsingOwnPromise) {
63567 var promise = new c(noop);
63568
63569 if (succeeded === false) {
63570 reject(promise, error);
63571 } else {
63572 handleMaybeThenable(promise, entry, then$$1);
63573
63574 this._willSettleAt(promise, i, firstPass);
63575 }
63576 } else {
63577 this._willSettleAt(new c(resolve => resolve(entry)), i, firstPass);
63578 }
63579 } else {
63580 this._willSettleAt(c.resolve(entry), i, firstPass);
63581 }
63582 }
63583
63584 _eachEntry(entry, i, firstPass) {
63585 if (entry !== null && typeof entry === 'object') {
63586 this._settleMaybeThenable(entry, i, firstPass);
63587 } else {
63588 this._setResultAt(FULFILLED, i, entry, firstPass);
63589 }
63590 }
63591
63592 _settledAt(state, i, value, firstPass) {
63593 var promise = this.promise;
63594
63595 if (promise._state === PENDING) {
63596 if (this._abortOnReject && state === REJECTED) {
63597 reject(promise, value);
63598 } else {
63599 this._setResultAt(state, i, value, firstPass);
63600
63601 this._checkFullfillment();
63602 }
63603 }
63604 }
63605
63606 _setResultAt(state, i, value, firstPass) {
63607 this._remaining--;
63608 this._result[i] = value;
63609 }
63610
63611 _willSettleAt(promise, i, firstPass) {
63612 subscribe(promise, undefined, value => this._settledAt(FULFILLED, i, value, firstPass), reason => this._settledAt(REJECTED, i, reason, firstPass));
63613 }
63614
63615 }
63616
63617 function setSettledResult(state, i, value) {
63618 this._remaining--;
63619
63620 if (state === FULFILLED) {
63621 this._result[i] = {
63622 state: 'fulfilled',
63623 value: value
63624 };
63625 } else {
63626 this._result[i] = {
63627 state: 'rejected',
63628 reason: value
63629 };
63630 }
63631 }
63632 /**
63633 `Promise.all` accepts an array of promises, and returns a new promise which
63634 is fulfilled with an array of fulfillment values for the passed promises, or
63635 rejected with the reason of the first passed promise to be rejected. It casts all
63636 elements of the passed iterable to promises as it runs this algorithm.
63637
63638 Example:
63639
63640 ```javascript
63641 import Promise, { resolve } from 'rsvp';
63642
63643 let promise1 = resolve(1);
63644 let promise2 = resolve(2);
63645 let promise3 = resolve(3);
63646 let promises = [ promise1, promise2, promise3 ];
63647
63648 Promise.all(promises).then(function(array){
63649 // The array here would be [ 1, 2, 3 ];
63650 });
63651 ```
63652
63653 If any of the `promises` given to `RSVP.all` are rejected, the first promise
63654 that is rejected will be given as an argument to the returned promises's
63655 rejection handler. For example:
63656
63657 Example:
63658
63659 ```javascript
63660 import Promise, { resolve, reject } from 'rsvp';
63661
63662 let promise1 = resolve(1);
63663 let promise2 = reject(new Error("2"));
63664 let promise3 = reject(new Error("3"));
63665 let promises = [ promise1, promise2, promise3 ];
63666
63667 Promise.all(promises).then(function(array){
63668 // Code here never runs because there are rejected promises!
63669 }, function(error) {
63670 // error.message === "2"
63671 });
63672 ```
63673
63674 @method all
63675 @for Promise
63676 @param {Array} entries array of promises
63677 @param {String} [label] optional string for labeling the promise.
63678 Useful for tooling.
63679 @return {Promise} promise that is fulfilled when all `promises` have been
63680 fulfilled, or rejected if any of them become rejected.
63681 @static
63682 */
63683
63684
63685 function all(entries, label) {
63686 if (!Array.isArray(entries)) {
63687 return this.reject(new TypeError("Promise.all must be called with an array"), label);
63688 }
63689
63690 return new Enumerator(this, entries, true
63691 /* abort on reject */
63692 , label).promise;
63693 }
63694 /**
63695 `Promise.race` returns a new promise which is settled in the same way as the
63696 first passed promise to settle.
63697
63698 Example:
63699
63700 ```javascript
63701 import Promise from 'rsvp';
63702
63703 let promise1 = new Promise(function(resolve, reject){
63704 setTimeout(function(){
63705 resolve('promise 1');
63706 }, 200);
63707 });
63708
63709 let promise2 = new Promise(function(resolve, reject){
63710 setTimeout(function(){
63711 resolve('promise 2');
63712 }, 100);
63713 });
63714
63715 Promise.race([promise1, promise2]).then(function(result){
63716 // result === 'promise 2' because it was resolved before promise1
63717 // was resolved.
63718 });
63719 ```
63720
63721 `Promise.race` is deterministic in that only the state of the first
63722 settled promise matters. For example, even if other promises given to the
63723 `promises` array argument are resolved, but the first settled promise has
63724 become rejected before the other promises became fulfilled, the returned
63725 promise will become rejected:
63726
63727 ```javascript
63728 import Promise from 'rsvp';
63729
63730 let promise1 = new Promise(function(resolve, reject){
63731 setTimeout(function(){
63732 resolve('promise 1');
63733 }, 200);
63734 });
63735
63736 let promise2 = new Promise(function(resolve, reject){
63737 setTimeout(function(){
63738 reject(new Error('promise 2'));
63739 }, 100);
63740 });
63741
63742 Promise.race([promise1, promise2]).then(function(result){
63743 // Code here never runs
63744 }, function(reason){
63745 // reason.message === 'promise 2' because promise 2 became rejected before
63746 // promise 1 became fulfilled
63747 });
63748 ```
63749
63750 An example real-world use case is implementing timeouts:
63751
63752 ```javascript
63753 import Promise from 'rsvp';
63754
63755 Promise.race([ajax('foo.json'), timeout(5000)])
63756 ```
63757
63758 @method race
63759 @for Promise
63760 @static
63761 @param {Array} entries array of promises to observe
63762 @param {String} [label] optional string for describing the promise returned.
63763 Useful for tooling.
63764 @return {Promise} a promise which settles in the same way as the first passed
63765 promise to settle.
63766 */
63767
63768
63769 function race(entries, label) {
63770 /*jshint validthis:true */
63771 var Constructor = this;
63772 var promise = new Constructor(noop, label);
63773
63774 if (!Array.isArray(entries)) {
63775 reject(promise, new TypeError('Promise.race must be called with an array'));
63776 return promise;
63777 }
63778
63779 for (var i = 0; promise._state === PENDING && i < entries.length; i++) {
63780 subscribe(Constructor.resolve(entries[i]), undefined, value => resolve$1(promise, value), reason => reject(promise, reason));
63781 }
63782
63783 return promise;
63784 }
63785 /**
63786 `Promise.reject` returns a promise rejected with the passed `reason`.
63787 It is shorthand for the following:
63788
63789 ```javascript
63790 import Promise from 'rsvp';
63791
63792 let promise = new Promise(function(resolve, reject){
63793 reject(new Error('WHOOPS'));
63794 });
63795
63796 promise.then(function(value){
63797 // Code here doesn't run because the promise is rejected!
63798 }, function(reason){
63799 // reason.message === 'WHOOPS'
63800 });
63801 ```
63802
63803 Instead of writing the above, your code now simply becomes the following:
63804
63805 ```javascript
63806 import Promise from 'rsvp';
63807
63808 let promise = Promise.reject(new Error('WHOOPS'));
63809
63810 promise.then(function(value){
63811 // Code here doesn't run because the promise is rejected!
63812 }, function(reason){
63813 // reason.message === 'WHOOPS'
63814 });
63815 ```
63816
63817 @method reject
63818 @for Promise
63819 @static
63820 @param {*} reason value that the returned promise will be rejected with.
63821 @param {String} [label] optional string for identifying the returned promise.
63822 Useful for tooling.
63823 @return {Promise} a promise rejected with the given `reason`.
63824 */
63825
63826
63827 function reject$1(reason, label) {
63828 /*jshint validthis:true */
63829 var Constructor = this;
63830 var promise = new Constructor(noop, label);
63831 reject(promise, reason);
63832 return promise;
63833 }
63834
63835 var guidKey = 'rsvp_' + Date.now() + '-';
63836 var counter = 0;
63837
63838 function needsResolver() {
63839 throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
63840 }
63841
63842 function needsNew() {
63843 throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
63844 }
63845 /**
63846 Promise objects represent the eventual result of an asynchronous operation. The
63847 primary way of interacting with a promise is through its `then` method, which
63848 registers callbacks to receive either a promise’s eventual value or the reason
63849 why the promise cannot be fulfilled.
63850
63851 Terminology
63852 -----------
63853
63854 - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
63855 - `thenable` is an object or function that defines a `then` method.
63856 - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
63857 - `exception` is a value that is thrown using the throw statement.
63858 - `reason` is a value that indicates why a promise was rejected.
63859 - `settled` the final resting state of a promise, fulfilled or rejected.
63860
63861 A promise can be in one of three states: pending, fulfilled, or rejected.
63862
63863 Promises that are fulfilled have a fulfillment value and are in the fulfilled
63864 state. Promises that are rejected have a rejection reason and are in the
63865 rejected state. A fulfillment value is never a thenable.
63866
63867 Promises can also be said to *resolve* a value. If this value is also a
63868 promise, then the original promise's settled state will match the value's
63869 settled state. So a promise that *resolves* a promise that rejects will
63870 itself reject, and a promise that *resolves* a promise that fulfills will
63871 itself fulfill.
63872
63873
63874 Basic Usage:
63875 ------------
63876
63877 ```js
63878 let promise = new Promise(function(resolve, reject) {
63879 // on success
63880 resolve(value);
63881
63882 // on failure
63883 reject(reason);
63884 });
63885
63886 promise.then(function(value) {
63887 // on fulfillment
63888 }, function(reason) {
63889 // on rejection
63890 });
63891 ```
63892
63893 Advanced Usage:
63894 ---------------
63895
63896 Promises shine when abstracting away asynchronous interactions such as
63897 `XMLHttpRequest`s.
63898
63899 ```js
63900 function getJSON(url) {
63901 return new Promise(function(resolve, reject){
63902 let xhr = new XMLHttpRequest();
63903
63904 xhr.open('GET', url);
63905 xhr.onreadystatechange = handler;
63906 xhr.responseType = 'json';
63907 xhr.setRequestHeader('Accept', 'application/json');
63908 xhr.send();
63909
63910 function handler() {
63911 if (this.readyState === this.DONE) {
63912 if (this.status === 200) {
63913 resolve(this.response);
63914 } else {
63915 reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
63916 }
63917 }
63918 };
63919 });
63920 }
63921
63922 getJSON('/posts.json').then(function(json) {
63923 // on fulfillment
63924 }, function(reason) {
63925 // on rejection
63926 });
63927 ```
63928
63929 Unlike callbacks, promises are great composable primitives.
63930
63931 ```js
63932 Promise.all([
63933 getJSON('/posts'),
63934 getJSON('/comments')
63935 ]).then(function(values){
63936 values[0] // => postsJSON
63937 values[1] // => commentsJSON
63938
63939 return values;
63940 });
63941 ```
63942
63943 @class Promise
63944 @public
63945 @param {function} resolver
63946 @param {String} [label] optional string for labeling the promise.
63947 Useful for tooling.
63948 @constructor
63949 */
63950
63951
63952 class Promise {
63953 constructor(resolver, label) {
63954 this._id = counter++;
63955 this._label = label;
63956 this._state = undefined;
63957 this._result = undefined;
63958 this._subscribers = [];
63959 config.instrument && instrument('created', this);
63960
63961 if (noop !== resolver) {
63962 typeof resolver !== 'function' && needsResolver();
63963 this instanceof Promise ? initializePromise(this, resolver) : needsNew();
63964 }
63965 }
63966
63967 _onError(reason) {
63968 config.after(() => {
63969 if (this._onError) {
63970 config.trigger('error', reason, this._label);
63971 }
63972 });
63973 }
63974 /**
63975 `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
63976 as the catch block of a try/catch statement.
63977
63978 ```js
63979 function findAuthor(){
63980 throw new Error('couldn\'t find that author');
63981 }
63982
63983 // synchronous
63984 try {
63985 findAuthor();
63986 } catch(reason) {
63987 // something went wrong
63988 }
63989
63990 // async with promises
63991 findAuthor().catch(function(reason){
63992 // something went wrong
63993 });
63994 ```
63995
63996 @method catch
63997 @param {Function} onRejection
63998 @param {String} [label] optional string for labeling the promise.
63999 Useful for tooling.
64000 @return {Promise}
64001 */
64002
64003
64004 catch(onRejection, label) {
64005 return this.then(undefined, onRejection, label);
64006 }
64007 /**
64008 `finally` will be invoked regardless of the promise's fate just as native
64009 try/catch/finally behaves
64010
64011 Synchronous example:
64012
64013 ```js
64014 findAuthor() {
64015 if (Math.random() > 0.5) {
64016 throw new Error();
64017 }
64018 return new Author();
64019 }
64020
64021 try {
64022 return findAuthor(); // succeed or fail
64023 } catch(error) {
64024 return findOtherAuthor();
64025 } finally {
64026 // always runs
64027 // doesn't affect the return value
64028 }
64029 ```
64030
64031 Asynchronous example:
64032
64033 ```js
64034 findAuthor().catch(function(reason){
64035 return findOtherAuthor();
64036 }).finally(function(){
64037 // author was either found, or not
64038 });
64039 ```
64040
64041 @method finally
64042 @param {Function} callback
64043 @param {String} [label] optional string for labeling the promise.
64044 Useful for tooling.
64045 @return {Promise}
64046 */
64047
64048
64049 finally(callback, label) {
64050 var promise = this;
64051 var constructor = promise.constructor;
64052
64053 if (typeof callback === 'function') {
64054 return promise.then(value => constructor.resolve(callback()).then(() => value), reason => constructor.resolve(callback()).then(() => {
64055 throw reason;
64056 }));
64057 }
64058
64059 return promise.then(callback, callback);
64060 }
64061
64062 }
64063
64064 _exports.Promise = Promise;
64065 Promise.cast = resolve$$1; // deprecated
64066
64067 Promise.all = all;
64068 Promise.race = race;
64069 Promise.resolve = resolve$$1;
64070 Promise.reject = reject$1;
64071 Promise.prototype._guidKey = guidKey;
64072 /**
64073 The primary way of interacting with a promise is through its `then` method,
64074 which registers callbacks to receive either a promise's eventual value or the
64075 reason why the promise cannot be fulfilled.
64076
64077 ```js
64078 findUser().then(function(user){
64079 // user is available
64080 }, function(reason){
64081 // user is unavailable, and you are given the reason why
64082 });
64083 ```
64084
64085 Chaining
64086 --------
64087
64088 The return value of `then` is itself a promise. This second, 'downstream'
64089 promise is resolved with the return value of the first promise's fulfillment
64090 or rejection handler, or rejected if the handler throws an exception.
64091
64092 ```js
64093 findUser().then(function (user) {
64094 return user.name;
64095 }, function (reason) {
64096 return 'default name';
64097 }).then(function (userName) {
64098 // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
64099 // will be `'default name'`
64100 });
64101
64102 findUser().then(function (user) {
64103 throw new Error('Found user, but still unhappy');
64104 }, function (reason) {
64105 throw new Error('`findUser` rejected and we\'re unhappy');
64106 }).then(function (value) {
64107 // never reached
64108 }, function (reason) {
64109 // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
64110 // If `findUser` rejected, `reason` will be '`findUser` rejected and we\'re unhappy'.
64111 });
64112 ```
64113 If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
64114
64115 ```js
64116 findUser().then(function (user) {
64117 throw new PedagogicalException('Upstream error');
64118 }).then(function (value) {
64119 // never reached
64120 }).then(function (value) {
64121 // never reached
64122 }, function (reason) {
64123 // The `PedgagocialException` is propagated all the way down to here
64124 });
64125 ```
64126
64127 Assimilation
64128 ------------
64129
64130 Sometimes the value you want to propagate to a downstream promise can only be
64131 retrieved asynchronously. This can be achieved by returning a promise in the
64132 fulfillment or rejection handler. The downstream promise will then be pending
64133 until the returned promise is settled. This is called *assimilation*.
64134
64135 ```js
64136 findUser().then(function (user) {
64137 return findCommentsByAuthor(user);
64138 }).then(function (comments) {
64139 // The user's comments are now available
64140 });
64141 ```
64142
64143 If the assimliated promise rejects, then the downstream promise will also reject.
64144
64145 ```js
64146 findUser().then(function (user) {
64147 return findCommentsByAuthor(user);
64148 }).then(function (comments) {
64149 // If `findCommentsByAuthor` fulfills, we'll have the value here
64150 }, function (reason) {
64151 // If `findCommentsByAuthor` rejects, we'll have the reason here
64152 });
64153 ```
64154
64155 Simple Example
64156 --------------
64157
64158 Synchronous Example
64159
64160 ```javascript
64161 let result;
64162
64163 try {
64164 result = findResult();
64165 // success
64166 } catch(reason) {
64167 // failure
64168 }
64169 ```
64170
64171 Errback Example
64172
64173 ```js
64174 findResult(function(result, err){
64175 if (err) {
64176 // failure
64177 } else {
64178 // success
64179 }
64180 });
64181 ```
64182
64183 Promise Example;
64184
64185 ```javascript
64186 findResult().then(function(result){
64187 // success
64188 }, function(reason){
64189 // failure
64190 });
64191 ```
64192
64193 Advanced Example
64194 --------------
64195
64196 Synchronous Example
64197
64198 ```javascript
64199 let author, books;
64200
64201 try {
64202 author = findAuthor();
64203 books = findBooksByAuthor(author);
64204 // success
64205 } catch(reason) {
64206 // failure
64207 }
64208 ```
64209
64210 Errback Example
64211
64212 ```js
64213
64214 function foundBooks(books) {
64215
64216 }
64217
64218 function failure(reason) {
64219
64220 }
64221
64222 findAuthor(function(author, err){
64223 if (err) {
64224 failure(err);
64225 // failure
64226 } else {
64227 try {
64228 findBoooksByAuthor(author, function(books, err) {
64229 if (err) {
64230 failure(err);
64231 } else {
64232 try {
64233 foundBooks(books);
64234 } catch(reason) {
64235 failure(reason);
64236 }
64237 }
64238 });
64239 } catch(error) {
64240 failure(err);
64241 }
64242 // success
64243 }
64244 });
64245 ```
64246
64247 Promise Example;
64248
64249 ```javascript
64250 findAuthor().
64251 then(findBooksByAuthor).
64252 then(function(books){
64253 // found books
64254 }).catch(function(reason){
64255 // something went wrong
64256 });
64257 ```
64258
64259 @method then
64260 @param {Function} onFulfillment
64261 @param {Function} onRejection
64262 @param {String} [label] optional string for labeling the promise.
64263 Useful for tooling.
64264 @return {Promise}
64265 */
64266
64267 Promise.prototype.then = then;
64268
64269 function makeObject(_, argumentNames) {
64270 var obj = {};
64271 var length = _.length;
64272 var args = new Array(length);
64273
64274 for (var x = 0; x < length; x++) {
64275 args[x] = _[x];
64276 }
64277
64278 for (var i = 0; i < argumentNames.length; i++) {
64279 var name = argumentNames[i];
64280 obj[name] = args[i + 1];
64281 }
64282
64283 return obj;
64284 }
64285
64286 function arrayResult(_) {
64287 var length = _.length;
64288 var args = new Array(length - 1);
64289
64290 for (var i = 1; i < length; i++) {
64291 args[i - 1] = _[i];
64292 }
64293
64294 return args;
64295 }
64296
64297 function wrapThenable(then, promise) {
64298 return {
64299 then(onFulFillment, onRejection) {
64300 return then.call(promise, onFulFillment, onRejection);
64301 }
64302
64303 };
64304 }
64305 /**
64306 `denodeify` takes a 'node-style' function and returns a function that
64307 will return an `Promise`. You can use `denodeify` in Node.js or the
64308 browser when you'd prefer to use promises over using callbacks. For example,
64309 `denodeify` transforms the following:
64310
64311 ```javascript
64312 let fs = require('fs');
64313
64314 fs.readFile('myfile.txt', function(err, data){
64315 if (err) return handleError(err);
64316 handleData(data);
64317 });
64318 ```
64319
64320 into:
64321
64322 ```javascript
64323 let fs = require('fs');
64324 let readFile = denodeify(fs.readFile);
64325
64326 readFile('myfile.txt').then(handleData, handleError);
64327 ```
64328
64329 If the node function has multiple success parameters, then `denodeify`
64330 just returns the first one:
64331
64332 ```javascript
64333 let request = denodeify(require('request'));
64334
64335 request('http://example.com').then(function(res) {
64336 // ...
64337 });
64338 ```
64339
64340 However, if you need all success parameters, setting `denodeify`'s
64341 second parameter to `true` causes it to return all success parameters
64342 as an array:
64343
64344 ```javascript
64345 let request = denodeify(require('request'), true);
64346
64347 request('http://example.com').then(function(result) {
64348 // result[0] -> res
64349 // result[1] -> body
64350 });
64351 ```
64352
64353 Or if you pass it an array with names it returns the parameters as a hash:
64354
64355 ```javascript
64356 let request = denodeify(require('request'), ['res', 'body']);
64357
64358 request('http://example.com').then(function(result) {
64359 // result.res
64360 // result.body
64361 });
64362 ```
64363
64364 Sometimes you need to retain the `this`:
64365
64366 ```javascript
64367 let app = require('express')();
64368 let render = denodeify(app.render.bind(app));
64369 ```
64370
64371 The denodified function inherits from the original function. It works in all
64372 environments, except IE 10 and below. Consequently all properties of the original
64373 function are available to you. However, any properties you change on the
64374 denodeified function won't be changed on the original function. Example:
64375
64376 ```javascript
64377 let request = denodeify(require('request')),
64378 cookieJar = request.jar(); // <- Inheritance is used here
64379
64380 request('http://example.com', {jar: cookieJar}).then(function(res) {
64381 // cookieJar.cookies holds now the cookies returned by example.com
64382 });
64383 ```
64384
64385 Using `denodeify` makes it easier to compose asynchronous operations instead
64386 of using callbacks. For example, instead of:
64387
64388 ```javascript
64389 let fs = require('fs');
64390
64391 fs.readFile('myfile.txt', function(err, data){
64392 if (err) { ... } // Handle error
64393 fs.writeFile('myfile2.txt', data, function(err){
64394 if (err) { ... } // Handle error
64395 console.log('done')
64396 });
64397 });
64398 ```
64399
64400 you can chain the operations together using `then` from the returned promise:
64401
64402 ```javascript
64403 let fs = require('fs');
64404 let readFile = denodeify(fs.readFile);
64405 let writeFile = denodeify(fs.writeFile);
64406
64407 readFile('myfile.txt').then(function(data){
64408 return writeFile('myfile2.txt', data);
64409 }).then(function(){
64410 console.log('done')
64411 }).catch(function(error){
64412 // Handle error
64413 });
64414 ```
64415
64416 @method denodeify
64417 @public
64418 @static
64419 @for rsvp
64420 @param {Function} nodeFunc a 'node-style' function that takes a callback as
64421 its last argument. The callback expects an error to be passed as its first
64422 argument (if an error occurred, otherwise null), and the value from the
64423 operation as its second argument ('function(err, value){ }').
64424 @param {Boolean|Array} [options] An optional paramter that if set
64425 to `true` causes the promise to fulfill with the callback's success arguments
64426 as an array. This is useful if the node function has multiple success
64427 paramters. If you set this paramter to an array with names, the promise will
64428 fulfill with a hash with these names as keys and the success parameters as
64429 values.
64430 @return {Function} a function that wraps `nodeFunc` to return a `Promise`
64431 */
64432
64433
64434 function denodeify(nodeFunc, options) {
64435 var fn = function () {
64436 var l = arguments.length;
64437 var args = new Array(l + 1);
64438 var promiseInput = false;
64439
64440 for (var i = 0; i < l; ++i) {
64441 var arg = arguments[i]; // TODO: this code really needs to be cleaned up
64442
64443 if (!promiseInput) {
64444 if (arg !== null && typeof arg === 'object') {
64445 if (arg.constructor === Promise) {
64446 promiseInput = true;
64447 } else {
64448 try {
64449 promiseInput = arg.then;
64450 } catch (error) {
64451 var p = new Promise(noop);
64452 reject(p, error);
64453 return p;
64454 }
64455 }
64456 } else {
64457 promiseInput = false;
64458 }
64459
64460 if (promiseInput && promiseInput !== true) {
64461 arg = wrapThenable(promiseInput, arg);
64462 }
64463 }
64464
64465 args[i] = arg;
64466 }
64467
64468 var promise = new Promise(noop);
64469
64470 args[l] = function (err, val) {
64471 if (err) {
64472 reject(promise, err);
64473 } else if (options === undefined) {
64474 resolve$1(promise, val);
64475 } else if (options === true) {
64476 resolve$1(promise, arrayResult(arguments));
64477 } else if (Array.isArray(options)) {
64478 resolve$1(promise, makeObject(arguments, options));
64479 } else {
64480 resolve$1(promise, val);
64481 }
64482 };
64483
64484 if (promiseInput) {
64485 return handlePromiseInput(promise, args, nodeFunc, this);
64486 } else {
64487 return handleValueInput(promise, args, nodeFunc, this);
64488 }
64489 };
64490
64491 fn.__proto__ = nodeFunc;
64492 return fn;
64493 }
64494
64495 function handleValueInput(promise, args, nodeFunc, self) {
64496 try {
64497 nodeFunc.apply(self, args);
64498 } catch (error) {
64499 reject(promise, error);
64500 }
64501
64502 return promise;
64503 }
64504
64505 function handlePromiseInput(promise, args, nodeFunc, self) {
64506 return Promise.all(args).then(args => handleValueInput(promise, args, nodeFunc, self));
64507 }
64508 /**
64509 This is a convenient alias for `Promise.all`.
64510
64511 @method all
64512 @public
64513 @static
64514 @for rsvp
64515 @param {Array} array Array of promises.
64516 @param {String} [label] An optional label. This is useful
64517 for tooling.
64518 */
64519
64520
64521 function all$1(array, label) {
64522 return Promise.all(array, label);
64523 }
64524 /**
64525 @module rsvp
64526 @public
64527 **/
64528
64529
64530 class AllSettled extends Enumerator {
64531 constructor(Constructor, entries, label) {
64532 super(Constructor, entries, false
64533 /* don't abort on reject */
64534 , label);
64535 }
64536
64537 }
64538
64539 AllSettled.prototype._setResultAt = setSettledResult;
64540 /**
64541 `RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing
64542 a fail-fast method, it waits until all the promises have returned and
64543 shows you all the results. This is useful if you want to handle multiple
64544 promises' failure states together as a set.
64545 Returns a promise that is fulfilled when all the given promises have been
64546 settled. The return promise is fulfilled with an array of the states of
64547 the promises passed into the `promises` array argument.
64548 Each state object will either indicate fulfillment or rejection, and
64549 provide the corresponding value or reason. The states will take one of
64550 the following formats:
64551 ```javascript
64552 { state: 'fulfilled', value: value }
64553 or
64554 { state: 'rejected', reason: reason }
64555 ```
64556 Example:
64557 ```javascript
64558 let promise1 = RSVP.Promise.resolve(1);
64559 let promise2 = RSVP.Promise.reject(new Error('2'));
64560 let promise3 = RSVP.Promise.reject(new Error('3'));
64561 let promises = [ promise1, promise2, promise3 ];
64562 RSVP.allSettled(promises).then(function(array){
64563 // array == [
64564 // { state: 'fulfilled', value: 1 },
64565 // { state: 'rejected', reason: Error },
64566 // { state: 'rejected', reason: Error }
64567 // ]
64568 // Note that for the second item, reason.message will be '2', and for the
64569 // third item, reason.message will be '3'.
64570 }, function(error) {
64571 // Not run. (This block would only be called if allSettled had failed,
64572 // for instance if passed an incorrect argument type.)
64573 });
64574 ```
64575 @method allSettled
64576 @public
64577 @static
64578 @for rsvp
64579 @param {Array} entries
64580 @param {String} [label] - optional string that describes the promise.
64581 Useful for tooling.
64582 @return {Promise} promise that is fulfilled with an array of the settled
64583 states of the constituent promises.
64584 */
64585
64586 function allSettled(entries, label) {
64587 if (!Array.isArray(entries)) {
64588 return Promise.reject(new TypeError("Promise.allSettled must be called with an array"), label);
64589 }
64590
64591 return new AllSettled(Promise, entries, label).promise;
64592 }
64593 /**
64594 This is a convenient alias for `Promise.race`.
64595
64596 @method race
64597 @public
64598 @static
64599 @for rsvp
64600 @param {Array} array Array of promises.
64601 @param {String} [label] An optional label. This is useful
64602 for tooling.
64603 */
64604
64605
64606 function race$1(array, label) {
64607 return Promise.race(array, label);
64608 }
64609
64610 class PromiseHash extends Enumerator {
64611 constructor(Constructor, object, abortOnReject = true, label) {
64612 super(Constructor, object, abortOnReject, label);
64613 }
64614
64615 _init(Constructor, object) {
64616 this._result = {};
64617
64618 this._enumerate(object);
64619 }
64620
64621 _enumerate(input) {
64622 var keys = Object.keys(input);
64623 var length = keys.length;
64624 var promise = this.promise;
64625 this._remaining = length;
64626 var key, val;
64627
64628 for (var i = 0; promise._state === PENDING && i < length; i++) {
64629 key = keys[i];
64630 val = input[key];
64631
64632 this._eachEntry(val, key, true);
64633 }
64634
64635 this._checkFullfillment();
64636 }
64637
64638 }
64639 /**
64640 `hash` is similar to `all`, but takes an object instead of an array
64641 for its `promises` argument.
64642
64643 Returns a promise that is fulfilled when all the given promises have been
64644 fulfilled, or rejected if any of them become rejected. The returned promise
64645 is fulfilled with a hash that has the same key names as the `promises` object
64646 argument. If any of the values in the object are not promises, they will
64647 simply be copied over to the fulfilled object.
64648
64649 Example:
64650
64651 ```javascript
64652 let promises = {
64653 myPromise: resolve(1),
64654 yourPromise: resolve(2),
64655 theirPromise: resolve(3),
64656 notAPromise: 4
64657 };
64658
64659 hash(promises).then(function(hash){
64660 // hash here is an object that looks like:
64661 // {
64662 // myPromise: 1,
64663 // yourPromise: 2,
64664 // theirPromise: 3,
64665 // notAPromise: 4
64666 // }
64667 });
64668 ```
64669
64670 If any of the `promises` given to `hash` are rejected, the first promise
64671 that is rejected will be given as the reason to the rejection handler.
64672
64673 Example:
64674
64675 ```javascript
64676 let promises = {
64677 myPromise: resolve(1),
64678 rejectedPromise: reject(new Error('rejectedPromise')),
64679 anotherRejectedPromise: reject(new Error('anotherRejectedPromise')),
64680 };
64681
64682 hash(promises).then(function(hash){
64683 // Code here never runs because there are rejected promises!
64684 }, function(reason) {
64685 // reason.message === 'rejectedPromise'
64686 });
64687 ```
64688
64689 An important note: `hash` is intended for plain JavaScript objects that
64690 are just a set of keys and values. `hash` will NOT preserve prototype
64691 chains.
64692
64693 Example:
64694
64695 ```javascript
64696 import { hash, resolve } from 'rsvp';
64697 function MyConstructor(){
64698 this.example = resolve('Example');
64699 }
64700
64701 MyConstructor.prototype = {
64702 protoProperty: resolve('Proto Property')
64703 };
64704
64705 let myObject = new MyConstructor();
64706
64707 hash(myObject).then(function(hash){
64708 // protoProperty will not be present, instead you will just have an
64709 // object that looks like:
64710 // {
64711 // example: 'Example'
64712 // }
64713 //
64714 // hash.hasOwnProperty('protoProperty'); // false
64715 // 'undefined' === typeof hash.protoProperty
64716 });
64717 ```
64718
64719 @method hash
64720 @public
64721 @static
64722 @for rsvp
64723 @param {Object} object
64724 @param {String} [label] optional string that describes the promise.
64725 Useful for tooling.
64726 @return {Promise} promise that is fulfilled when all properties of `promises`
64727 have been fulfilled, or rejected if any of them become rejected.
64728 */
64729
64730
64731 function hash(object, label) {
64732 return Promise.resolve(object, label).then(function (object) {
64733 if (object === null || typeof object !== 'object') {
64734 throw new TypeError("Promise.hash must be called with an object");
64735 }
64736
64737 return new PromiseHash(Promise, object, label).promise;
64738 });
64739 }
64740
64741 class HashSettled extends PromiseHash {
64742 constructor(Constructor, object, label) {
64743 super(Constructor, object, false, label);
64744 }
64745
64746 }
64747
64748 HashSettled.prototype._setResultAt = setSettledResult;
64749 /**
64750 `hashSettled` is similar to `allSettled`, but takes an object
64751 instead of an array for its `promises` argument.
64752
64753 Unlike `all` or `hash`, which implement a fail-fast method,
64754 but like `allSettled`, `hashSettled` waits until all the
64755 constituent promises have returned and then shows you all the results
64756 with their states and values/reasons. This is useful if you want to
64757 handle multiple promises' failure states together as a set.
64758
64759 Returns a promise that is fulfilled when all the given promises have been
64760 settled, or rejected if the passed parameters are invalid.
64761
64762 The returned promise is fulfilled with a hash that has the same key names as
64763 the `promises` object argument. If any of the values in the object are not
64764 promises, they will be copied over to the fulfilled object and marked with state
64765 'fulfilled'.
64766
64767 Example:
64768
64769 ```javascript
64770 import { hashSettled, resolve } from 'rsvp';
64771
64772 let promises = {
64773 myPromise: resolve(1),
64774 yourPromise: resolve(2),
64775 theirPromise: resolve(3),
64776 notAPromise: 4
64777 };
64778
64779 hashSettled(promises).then(function(hash){
64780 // hash here is an object that looks like:
64781 // {
64782 // myPromise: { state: 'fulfilled', value: 1 },
64783 // yourPromise: { state: 'fulfilled', value: 2 },
64784 // theirPromise: { state: 'fulfilled', value: 3 },
64785 // notAPromise: { state: 'fulfilled', value: 4 }
64786 // }
64787 });
64788 ```
64789
64790 If any of the `promises` given to `hash` are rejected, the state will
64791 be set to 'rejected' and the reason for rejection provided.
64792
64793 Example:
64794
64795 ```javascript
64796 import { hashSettled, reject, resolve } from 'rsvp';
64797
64798 let promises = {
64799 myPromise: resolve(1),
64800 rejectedPromise: reject(new Error('rejection')),
64801 anotherRejectedPromise: reject(new Error('more rejection')),
64802 };
64803
64804 hashSettled(promises).then(function(hash){
64805 // hash here is an object that looks like:
64806 // {
64807 // myPromise: { state: 'fulfilled', value: 1 },
64808 // rejectedPromise: { state: 'rejected', reason: Error },
64809 // anotherRejectedPromise: { state: 'rejected', reason: Error },
64810 // }
64811 // Note that for rejectedPromise, reason.message == 'rejection',
64812 // and for anotherRejectedPromise, reason.message == 'more rejection'.
64813 });
64814 ```
64815
64816 An important note: `hashSettled` is intended for plain JavaScript objects that
64817 are just a set of keys and values. `hashSettled` will NOT preserve prototype
64818 chains.
64819
64820 Example:
64821
64822 ```javascript
64823 import Promise, { hashSettled, resolve } from 'rsvp';
64824
64825 function MyConstructor(){
64826 this.example = resolve('Example');
64827 }
64828
64829 MyConstructor.prototype = {
64830 protoProperty: Promise.resolve('Proto Property')
64831 };
64832
64833 let myObject = new MyConstructor();
64834
64835 hashSettled(myObject).then(function(hash){
64836 // protoProperty will not be present, instead you will just have an
64837 // object that looks like:
64838 // {
64839 // example: { state: 'fulfilled', value: 'Example' }
64840 // }
64841 //
64842 // hash.hasOwnProperty('protoProperty'); // false
64843 // 'undefined' === typeof hash.protoProperty
64844 });
64845 ```
64846
64847 @method hashSettled
64848 @public
64849 @for rsvp
64850 @param {Object} object
64851 @param {String} [label] optional string that describes the promise.
64852 Useful for tooling.
64853 @return {Promise} promise that is fulfilled when when all properties of `promises`
64854 have been settled.
64855 @static
64856 */
64857
64858 function hashSettled(object, label) {
64859 return Promise.resolve(object, label).then(function (object) {
64860 if (object === null || typeof object !== 'object') {
64861 throw new TypeError("hashSettled must be called with an object");
64862 }
64863
64864 return new HashSettled(Promise, object, false, label).promise;
64865 });
64866 }
64867 /**
64868 `rethrow` will rethrow an error on the next turn of the JavaScript event
64869 loop in order to aid debugging.
64870
64871 Promises A+ specifies that any exceptions that occur with a promise must be
64872 caught by the promises implementation and bubbled to the last handler. For
64873 this reason, it is recommended that you always specify a second rejection
64874 handler function to `then`. However, `rethrow` will throw the exception
64875 outside of the promise, so it bubbles up to your console if in the browser,
64876 or domain/cause uncaught exception in Node. `rethrow` will also throw the
64877 error again so the error can be handled by the promise per the spec.
64878
64879 ```javascript
64880 import { rethrow } from 'rsvp';
64881
64882 function throws(){
64883 throw new Error('Whoops!');
64884 }
64885
64886 let promise = new Promise(function(resolve, reject){
64887 throws();
64888 });
64889
64890 promise.catch(rethrow).then(function(){
64891 // Code here doesn't run because the promise became rejected due to an
64892 // error!
64893 }, function (err){
64894 // handle the error here
64895 });
64896 ```
64897
64898 The 'Whoops' error will be thrown on the next turn of the event loop
64899 and you can watch for it in your console. You can also handle it using a
64900 rejection handler given to `.then` or `.catch` on the returned promise.
64901
64902 @method rethrow
64903 @public
64904 @static
64905 @for rsvp
64906 @param {Error} reason reason the promise became rejected.
64907 @throws Error
64908 @static
64909 */
64910
64911
64912 function rethrow(reason) {
64913 setTimeout(() => {
64914 throw reason;
64915 });
64916 throw reason;
64917 }
64918 /**
64919 `defer` returns an object similar to jQuery's `$.Deferred`.
64920 `defer` should be used when porting over code reliant on `$.Deferred`'s
64921 interface. New code should use the `Promise` constructor instead.
64922
64923 The object returned from `defer` is a plain object with three properties:
64924
64925 * promise - an `Promise`.
64926 * reject - a function that causes the `promise` property on this object to
64927 become rejected
64928 * resolve - a function that causes the `promise` property on this object to
64929 become fulfilled.
64930
64931 Example:
64932
64933 ```javascript
64934 let deferred = defer();
64935
64936 deferred.resolve("Success!");
64937
64938 deferred.promise.then(function(value){
64939 // value here is "Success!"
64940 });
64941 ```
64942
64943 @method defer
64944 @public
64945 @static
64946 @for rsvp
64947 @param {String} [label] optional string for labeling the promise.
64948 Useful for tooling.
64949 @return {Object}
64950 */
64951
64952
64953 function defer(label) {
64954 var deferred = {
64955 resolve: undefined,
64956 reject: undefined
64957 };
64958 deferred.promise = new Promise((resolve, reject) => {
64959 deferred.resolve = resolve;
64960 deferred.reject = reject;
64961 }, label);
64962 return deferred;
64963 }
64964
64965 class MapEnumerator extends Enumerator {
64966 constructor(Constructor, entries, mapFn, label) {
64967 super(Constructor, entries, true, label, mapFn);
64968 }
64969
64970 _init(Constructor, input, bool, label, mapFn) {
64971 var len = input.length || 0;
64972 this.length = len;
64973 this._remaining = len;
64974 this._result = new Array(len);
64975 this._mapFn = mapFn;
64976
64977 this._enumerate(input);
64978 }
64979
64980 _setResultAt(state, i, value, firstPass) {
64981 if (firstPass) {
64982 try {
64983 this._eachEntry(this._mapFn(value, i), i, false);
64984 } catch (error) {
64985 this._settledAt(REJECTED, i, error, false);
64986 }
64987 } else {
64988 this._remaining--;
64989 this._result[i] = value;
64990 }
64991 }
64992
64993 }
64994 /**
64995 `map` is similar to JavaScript's native `map` method. `mapFn` is eagerly called
64996 meaning that as soon as any promise resolves its value will be passed to `mapFn`.
64997 `map` returns a promise that will become fulfilled with the result of running
64998 `mapFn` on the values the promises become fulfilled with.
64999
65000 For example:
65001
65002 ```javascript
65003 import { map, resolve } from 'rsvp';
65004
65005 let promise1 = resolve(1);
65006 let promise2 = resolve(2);
65007 let promise3 = resolve(3);
65008 let promises = [ promise1, promise2, promise3 ];
65009
65010 let mapFn = function(item){
65011 return item + 1;
65012 };
65013
65014 map(promises, mapFn).then(function(result){
65015 // result is [ 2, 3, 4 ]
65016 });
65017 ```
65018
65019 If any of the `promises` given to `map` are rejected, the first promise
65020 that is rejected will be given as an argument to the returned promise's
65021 rejection handler. For example:
65022
65023 ```javascript
65024 import { map, reject, resolve } from 'rsvp';
65025
65026 let promise1 = resolve(1);
65027 let promise2 = reject(new Error('2'));
65028 let promise3 = reject(new Error('3'));
65029 let promises = [ promise1, promise2, promise3 ];
65030
65031 let mapFn = function(item){
65032 return item + 1;
65033 };
65034
65035 map(promises, mapFn).then(function(array){
65036 // Code here never runs because there are rejected promises!
65037 }, function(reason) {
65038 // reason.message === '2'
65039 });
65040 ```
65041
65042 `map` will also wait if a promise is returned from `mapFn`. For example,
65043 say you want to get all comments from a set of blog posts, but you need
65044 the blog posts first because they contain a url to those comments.
65045
65046 ```javscript
65047 import { map } from 'rsvp';
65048
65049 let mapFn = function(blogPost){
65050 // getComments does some ajax and returns an Promise that is fulfilled
65051 // with some comments data
65052 return getComments(blogPost.comments_url);
65053 };
65054
65055 // getBlogPosts does some ajax and returns an Promise that is fulfilled
65056 // with some blog post data
65057 map(getBlogPosts(), mapFn).then(function(comments){
65058 // comments is the result of asking the server for the comments
65059 // of all blog posts returned from getBlogPosts()
65060 });
65061 ```
65062
65063 @method map
65064 @public
65065 @static
65066 @for rsvp
65067 @param {Array} promises
65068 @param {Function} mapFn function to be called on each fulfilled promise.
65069 @param {String} [label] optional string for labeling the promise.
65070 Useful for tooling.
65071 @return {Promise} promise that is fulfilled with the result of calling
65072 `mapFn` on each fulfilled promise or value when they become fulfilled.
65073 The promise will be rejected if any of the given `promises` become rejected.
65074 */
65075
65076
65077 function map(promises, mapFn, label) {
65078 if (typeof mapFn !== 'function') {
65079 return Promise.reject(new TypeError("map expects a function as a second argument"), label);
65080 }
65081
65082 return Promise.resolve(promises, label).then(function (promises) {
65083 if (!Array.isArray(promises)) {
65084 throw new TypeError("map must be called with an array");
65085 }
65086
65087 return new MapEnumerator(Promise, promises, mapFn, label).promise;
65088 });
65089 }
65090 /**
65091 This is a convenient alias for `Promise.resolve`.
65092
65093 @method resolve
65094 @public
65095 @static
65096 @for rsvp
65097 @param {*} value value that the returned promise will be resolved with
65098 @param {String} [label] optional string for identifying the returned promise.
65099 Useful for tooling.
65100 @return {Promise} a promise that will become fulfilled with the given
65101 `value`
65102 */
65103
65104
65105 function resolve$2(value, label) {
65106 return Promise.resolve(value, label);
65107 }
65108 /**
65109 This is a convenient alias for `Promise.reject`.
65110
65111 @method reject
65112 @public
65113 @static
65114 @for rsvp
65115 @param {*} reason value that the returned promise will be rejected with.
65116 @param {String} [label] optional string for identifying the returned promise.
65117 Useful for tooling.
65118 @return {Promise} a promise rejected with the given `reason`.
65119 */
65120
65121
65122 function reject$2(reason, label) {
65123 return Promise.reject(reason, label);
65124 }
65125
65126 var EMPTY_OBJECT = {};
65127
65128 class FilterEnumerator extends MapEnumerator {
65129 _checkFullfillment() {
65130 if (this._remaining === 0 && this._result !== null) {
65131 var result = this._result.filter(val => val !== EMPTY_OBJECT);
65132
65133 fulfill(this.promise, result);
65134 this._result = null;
65135 }
65136 }
65137
65138 _setResultAt(state, i, value, firstPass) {
65139 if (firstPass) {
65140 this._result[i] = value;
65141 var val,
65142 succeeded = true;
65143
65144 try {
65145 val = this._mapFn(value, i);
65146 } catch (error) {
65147 succeeded = false;
65148
65149 this._settledAt(REJECTED, i, error, false);
65150 }
65151
65152 if (succeeded) {
65153 this._eachEntry(val, i, false);
65154 }
65155 } else {
65156 this._remaining--;
65157
65158 if (!value) {
65159 this._result[i] = EMPTY_OBJECT;
65160 }
65161 }
65162 }
65163
65164 }
65165 /**
65166 `filter` is similar to JavaScript's native `filter` method.
65167 `filterFn` is eagerly called meaning that as soon as any promise
65168 resolves its value will be passed to `filterFn`. `filter` returns
65169 a promise that will become fulfilled with the result of running
65170 `filterFn` on the values the promises become fulfilled with.
65171
65172 For example:
65173
65174 ```javascript
65175 import { filter, resolve } from 'rsvp';
65176
65177 let promise1 = resolve(1);
65178 let promise2 = resolve(2);
65179 let promise3 = resolve(3);
65180
65181 let promises = [promise1, promise2, promise3];
65182
65183 let filterFn = function(item){
65184 return item > 1;
65185 };
65186
65187 filter(promises, filterFn).then(function(result){
65188 // result is [ 2, 3 ]
65189 });
65190 ```
65191
65192 If any of the `promises` given to `filter` are rejected, the first promise
65193 that is rejected will be given as an argument to the returned promise's
65194 rejection handler. For example:
65195
65196 ```javascript
65197 import { filter, reject, resolve } from 'rsvp';
65198
65199 let promise1 = resolve(1);
65200 let promise2 = reject(new Error('2'));
65201 let promise3 = reject(new Error('3'));
65202 let promises = [ promise1, promise2, promise3 ];
65203
65204 let filterFn = function(item){
65205 return item > 1;
65206 };
65207
65208 filter(promises, filterFn).then(function(array){
65209 // Code here never runs because there are rejected promises!
65210 }, function(reason) {
65211 // reason.message === '2'
65212 });
65213 ```
65214
65215 `filter` will also wait for any promises returned from `filterFn`.
65216 For instance, you may want to fetch a list of users then return a subset
65217 of those users based on some asynchronous operation:
65218
65219 ```javascript
65220 import { filter, resolve } from 'rsvp';
65221
65222 let alice = { name: 'alice' };
65223 let bob = { name: 'bob' };
65224 let users = [ alice, bob ];
65225
65226 let promises = users.map(function(user){
65227 return resolve(user);
65228 });
65229
65230 let filterFn = function(user){
65231 // Here, Alice has permissions to create a blog post, but Bob does not.
65232 return getPrivilegesForUser(user).then(function(privs){
65233 return privs.can_create_blog_post === true;
65234 });
65235 };
65236 filter(promises, filterFn).then(function(users){
65237 // true, because the server told us only Alice can create a blog post.
65238 users.length === 1;
65239 // false, because Alice is the only user present in `users`
65240 users[0] === bob;
65241 });
65242 ```
65243
65244 @method filter
65245 @public
65246 @static
65247 @for rsvp
65248 @param {Array} promises
65249 @param {Function} filterFn - function to be called on each resolved value to
65250 filter the final results.
65251 @param {String} [label] optional string describing the promise. Useful for
65252 tooling.
65253 @return {Promise}
65254 */
65255
65256
65257 function filter(promises, filterFn, label) {
65258 if (typeof filterFn !== 'function') {
65259 return Promise.reject(new TypeError("filter expects function as a second argument"), label);
65260 }
65261
65262 return Promise.resolve(promises, label).then(function (promises) {
65263 if (!Array.isArray(promises)) {
65264 throw new TypeError("filter must be called with an array");
65265 }
65266
65267 return new FilterEnumerator(Promise, promises, filterFn, label).promise;
65268 });
65269 }
65270
65271 var len = 0;
65272 var vertxNext;
65273
65274 function asap(callback, arg) {
65275 queue$1[len] = callback;
65276 queue$1[len + 1] = arg;
65277 len += 2;
65278
65279 if (len === 2) {
65280 // If len is 1, that means that we need to schedule an async flush.
65281 // If additional callbacks are queued before the queue is flushed, they
65282 // will be processed by this flush that we are scheduling.
65283 scheduleFlush$1();
65284 }
65285 }
65286
65287 var browserWindow = typeof window !== 'undefined' ? window : undefined;
65288 var browserGlobal = browserWindow || {};
65289 var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
65290 var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; // test for web worker but not in IE10
65291
65292 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node
65293
65294 function useNextTick() {
65295 var nextTick = process.nextTick; // node version 0.10.x displays a deprecation warning when nextTick is used recursively
65296 // setImmediate should be used instead instead
65297
65298 var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);
65299
65300 if (Array.isArray(version) && version[1] === '0' && version[2] === '10') {
65301 nextTick = setImmediate;
65302 }
65303
65304 return () => nextTick(flush);
65305 } // vertx
65306
65307
65308 function useVertxTimer() {
65309 if (typeof vertxNext !== 'undefined') {
65310 return function () {
65311 vertxNext(flush);
65312 };
65313 }
65314
65315 return useSetTimeout();
65316 }
65317
65318 function useMutationObserver() {
65319 var iterations = 0;
65320 var observer = new BrowserMutationObserver(flush);
65321 var node = document.createTextNode('');
65322 observer.observe(node, {
65323 characterData: true
65324 });
65325 return () => node.data = iterations = ++iterations % 2;
65326 } // web worker
65327
65328
65329 function useMessageChannel() {
65330 var channel = new MessageChannel();
65331 channel.port1.onmessage = flush;
65332 return () => channel.port2.postMessage(0);
65333 }
65334
65335 function useSetTimeout() {
65336 return () => setTimeout(flush, 1);
65337 }
65338
65339 var queue$1 = new Array(1000);
65340
65341 function flush() {
65342 for (var i = 0; i < len; i += 2) {
65343 var callback = queue$1[i];
65344 var arg = queue$1[i + 1];
65345 callback(arg);
65346 queue$1[i] = undefined;
65347 queue$1[i + 1] = undefined;
65348 }
65349
65350 len = 0;
65351 }
65352
65353 function attemptVertex() {
65354 try {
65355 var vertx = Function('return this')().require('vertx');
65356
65357 vertxNext = vertx.runOnLoop || vertx.runOnContext;
65358 return useVertxTimer();
65359 } catch (e) {
65360 return useSetTimeout();
65361 }
65362 }
65363
65364 var scheduleFlush$1; // Decide what async method to use to triggering processing of queued callbacks:
65365
65366 if (isNode) {
65367 scheduleFlush$1 = useNextTick();
65368 } else if (BrowserMutationObserver) {
65369 scheduleFlush$1 = useMutationObserver();
65370 } else if (isWorker) {
65371 scheduleFlush$1 = useMessageChannel();
65372 } else if (browserWindow === undefined && typeof require === 'function') {
65373 scheduleFlush$1 = attemptVertex();
65374 } else {
65375 scheduleFlush$1 = useSetTimeout();
65376 } // defaults
65377
65378
65379 config.async = asap;
65380
65381 config.after = cb => setTimeout(cb, 0);
65382
65383 var cast = resolve$2;
65384 _exports.cast = cast;
65385
65386 var async = (callback, arg) => config.async(callback, arg);
65387
65388 _exports.async = async;
65389
65390 function on() {
65391 config.on(...arguments);
65392 }
65393
65394 function off() {
65395 config.off(...arguments);
65396 } // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__`
65397
65398
65399 if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') {
65400 var callbacks = window['__PROMISE_INSTRUMENTATION__'];
65401 configure('instrument', true);
65402
65403 for (var eventName in callbacks) {
65404 if (callbacks.hasOwnProperty(eventName)) {
65405 on(eventName, callbacks[eventName]);
65406 }
65407 }
65408 } // the default export here is for backwards compat:
65409 // https://github.com/tildeio/rsvp.js/issues/434
65410
65411
65412 var rsvp = {
65413 asap,
65414 cast,
65415 Promise,
65416 EventTarget,
65417 all: all$1,
65418 allSettled,
65419 race: race$1,
65420 hash,
65421 hashSettled,
65422 rethrow,
65423 defer,
65424 denodeify,
65425 configure,
65426 on,
65427 off,
65428 resolve: resolve$2,
65429 reject: reject$2,
65430 map,
65431 async,
65432 filter
65433 };
65434 var _default = rsvp;
65435 _exports.default = _default;
65436});
65437require('ember');
65438}());
65439//# sourceMappingURL=ember.map