UNPKG

1.27 MBJavaScriptView Raw
1/**
2 * @license Angular v10.0.10
3 * (c) 2010-2020 Google LLC. https://angular.io/
4 * License: MIT
5 */
6
7import { Subject, Subscription, Observable, merge as merge$1 } from 'rxjs';
8import { share } from 'rxjs/operators';
9
10/**
11 * @license
12 * Copyright Google LLC All Rights Reserved.
13 *
14 * Use of this source code is governed by an MIT-style license that can be
15 * found in the LICENSE file at https://angular.io/license
16 */
17/**
18 * Convince closure compiler that the wrapped function has no side-effects.
19 *
20 * Closure compiler always assumes that `toString` has no side-effects. We use this quirk to
21 * allow us to execute a function but have closure compiler mark the call as no-side-effects.
22 * It is important that the return value for the `noSideEffects` function be assigned
23 * to something which is retained otherwise the call to `noSideEffects` will be removed by closure
24 * compiler.
25 */
26function noSideEffects(fn) {
27 return { toString: fn }.toString();
28}
29
30/**
31 * @license
32 * Copyright Google LLC All Rights Reserved.
33 *
34 * Use of this source code is governed by an MIT-style license that can be
35 * found in the LICENSE file at https://angular.io/license
36 */
37const ANNOTATIONS = '__annotations__';
38const PARAMETERS = '__parameters__';
39const PROP_METADATA = '__prop__metadata__';
40/**
41 * @suppress {globalThis}
42 */
43function makeDecorator(name, props, parentClass, additionalProcessing, typeFn) {
44 return noSideEffects(() => {
45 const metaCtor = makeMetadataCtor(props);
46 function DecoratorFactory(...args) {
47 if (this instanceof DecoratorFactory) {
48 metaCtor.call(this, ...args);
49 return this;
50 }
51 const annotationInstance = new DecoratorFactory(...args);
52 return function TypeDecorator(cls) {
53 if (typeFn)
54 typeFn(cls, ...args);
55 // Use of Object.defineProperty is important since it creates non-enumerable property which
56 // prevents the property is copied during subclassing.
57 const annotations = cls.hasOwnProperty(ANNOTATIONS) ?
58 cls[ANNOTATIONS] :
59 Object.defineProperty(cls, ANNOTATIONS, { value: [] })[ANNOTATIONS];
60 annotations.push(annotationInstance);
61 if (additionalProcessing)
62 additionalProcessing(cls);
63 return cls;
64 };
65 }
66 if (parentClass) {
67 DecoratorFactory.prototype = Object.create(parentClass.prototype);
68 }
69 DecoratorFactory.prototype.ngMetadataName = name;
70 DecoratorFactory.annotationCls = DecoratorFactory;
71 return DecoratorFactory;
72 });
73}
74function makeMetadataCtor(props) {
75 return function ctor(...args) {
76 if (props) {
77 const values = props(...args);
78 for (const propName in values) {
79 this[propName] = values[propName];
80 }
81 }
82 };
83}
84function makeParamDecorator(name, props, parentClass) {
85 return noSideEffects(() => {
86 const metaCtor = makeMetadataCtor(props);
87 function ParamDecoratorFactory(...args) {
88 if (this instanceof ParamDecoratorFactory) {
89 metaCtor.apply(this, args);
90 return this;
91 }
92 const annotationInstance = new ParamDecoratorFactory(...args);
93 ParamDecorator.annotation = annotationInstance;
94 return ParamDecorator;
95 function ParamDecorator(cls, unusedKey, index) {
96 // Use of Object.defineProperty is important since it creates non-enumerable property which
97 // prevents the property is copied during subclassing.
98 const parameters = cls.hasOwnProperty(PARAMETERS) ?
99 cls[PARAMETERS] :
100 Object.defineProperty(cls, PARAMETERS, { value: [] })[PARAMETERS];
101 // there might be gaps if some in between parameters do not have annotations.
102 // we pad with nulls.
103 while (parameters.length <= index) {
104 parameters.push(null);
105 }
106 (parameters[index] = parameters[index] || []).push(annotationInstance);
107 return cls;
108 }
109 }
110 if (parentClass) {
111 ParamDecoratorFactory.prototype = Object.create(parentClass.prototype);
112 }
113 ParamDecoratorFactory.prototype.ngMetadataName = name;
114 ParamDecoratorFactory.annotationCls = ParamDecoratorFactory;
115 return ParamDecoratorFactory;
116 });
117}
118function makePropDecorator(name, props, parentClass, additionalProcessing) {
119 return noSideEffects(() => {
120 const metaCtor = makeMetadataCtor(props);
121 function PropDecoratorFactory(...args) {
122 if (this instanceof PropDecoratorFactory) {
123 metaCtor.apply(this, args);
124 return this;
125 }
126 const decoratorInstance = new PropDecoratorFactory(...args);
127 function PropDecorator(target, name) {
128 const constructor = target.constructor;
129 // Use of Object.defineProperty is important because it creates a non-enumerable property
130 // which prevents the property from being copied during subclassing.
131 const meta = constructor.hasOwnProperty(PROP_METADATA) ?
132 constructor[PROP_METADATA] :
133 Object.defineProperty(constructor, PROP_METADATA, { value: {} })[PROP_METADATA];
134 meta[name] = meta.hasOwnProperty(name) && meta[name] || [];
135 meta[name].unshift(decoratorInstance);
136 if (additionalProcessing)
137 additionalProcessing(target, name, ...args);
138 }
139 return PropDecorator;
140 }
141 if (parentClass) {
142 PropDecoratorFactory.prototype = Object.create(parentClass.prototype);
143 }
144 PropDecoratorFactory.prototype.ngMetadataName = name;
145 PropDecoratorFactory.annotationCls = PropDecoratorFactory;
146 return PropDecoratorFactory;
147 });
148}
149
150/**
151 * @license
152 * Copyright Google LLC All Rights Reserved.
153 *
154 * Use of this source code is governed by an MIT-style license that can be
155 * found in the LICENSE file at https://angular.io/license
156 */
157const ɵ0 = (token) => ({ token });
158/**
159 * Inject decorator and metadata.
160 *
161 * @Annotation
162 * @publicApi
163 */
164const Inject = makeParamDecorator('Inject', ɵ0);
165/**
166 * Optional decorator and metadata.
167 *
168 * @Annotation
169 * @publicApi
170 */
171const Optional = makeParamDecorator('Optional');
172/**
173 * Self decorator and metadata.
174 *
175 * @Annotation
176 * @publicApi
177 */
178const Self = makeParamDecorator('Self');
179/**
180 * `SkipSelf` decorator and metadata.
181 *
182 * @Annotation
183 * @publicApi
184 */
185const SkipSelf = makeParamDecorator('SkipSelf');
186/**
187 * Host decorator and metadata.
188 *
189 * @Annotation
190 * @publicApi
191 */
192const Host = makeParamDecorator('Host');
193const ɵ1 = (attributeName) => ({ attributeName });
194/**
195 * Attribute decorator and metadata.
196 *
197 * @Annotation
198 * @publicApi
199 */
200const Attribute = makeParamDecorator('Attribute', ɵ1);
201
202/**
203 * @license
204 * Copyright Google LLC All Rights Reserved.
205 *
206 * Use of this source code is governed by an MIT-style license that can be
207 * found in the LICENSE file at https://angular.io/license
208 */
209/**
210 * Injection flags for DI.
211 *
212 * @publicApi
213 */
214var InjectFlags;
215(function (InjectFlags) {
216 // TODO(alxhub): make this 'const' when ngc no longer writes exports of it into ngfactory files.
217 /** Check self and check parent injector if needed */
218 InjectFlags[InjectFlags["Default"] = 0] = "Default";
219 /**
220 * Specifies that an injector should retrieve a dependency from any injector until reaching the
221 * host element of the current component. (Only used with Element Injector)
222 */
223 InjectFlags[InjectFlags["Host"] = 1] = "Host";
224 /** Don't ascend to ancestors of the node requesting injection. */
225 InjectFlags[InjectFlags["Self"] = 2] = "Self";
226 /** Skip the node that is requesting injection. */
227 InjectFlags[InjectFlags["SkipSelf"] = 4] = "SkipSelf";
228 /** Inject `defaultValue` instead if token not found. */
229 InjectFlags[InjectFlags["Optional"] = 8] = "Optional";
230})(InjectFlags || (InjectFlags = {}));
231
232/**
233 * @license
234 * Copyright Google LLC All Rights Reserved.
235 *
236 * Use of this source code is governed by an MIT-style license that can be
237 * found in the LICENSE file at https://angular.io/license
238 */
239function getClosureSafeProperty(objWithPropertyToExtract) {
240 for (let key in objWithPropertyToExtract) {
241 if (objWithPropertyToExtract[key] === getClosureSafeProperty) {
242 return key;
243 }
244 }
245 throw Error('Could not find renamed property on target object.');
246}
247/**
248 * Sets properties on a target object from a source object, but only if
249 * the property doesn't already exist on the target object.
250 * @param target The target to set properties on
251 * @param source The source of the property keys and values to set
252 */
253function fillProperties(target, source) {
254 for (const key in source) {
255 if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
256 target[key] = source[key];
257 }
258 }
259}
260
261/**
262 * @license
263 * Copyright Google LLC All Rights Reserved.
264 *
265 * Use of this source code is governed by an MIT-style license that can be
266 * found in the LICENSE file at https://angular.io/license
267 */
268/**
269 * Construct an `InjectableDef` which defines how a token will be constructed by the DI system, and
270 * in which injectors (if any) it will be available.
271 *
272 * This should be assigned to a static `ɵprov` field on a type, which will then be an
273 * `InjectableType`.
274 *
275 * Options:
276 * * `providedIn` determines which injectors will include the injectable, by either associating it
277 * with an `@NgModule` or other `InjectorType`, or by specifying that this injectable should be
278 * provided in the `'root'` injector, which will be the application-level injector in most apps.
279 * * `factory` gives the zero argument function which will create an instance of the injectable.
280 * The factory can call `inject` to access the `Injector` and request injection of dependencies.
281 *
282 * @codeGenApi
283 * @publicApi This instruction has been emitted by ViewEngine for some time and is deployed to npm.
284 */
285function ɵɵdefineInjectable(opts) {
286 return {
287 token: opts.token,
288 providedIn: opts.providedIn || null,
289 factory: opts.factory,
290 value: undefined,
291 };
292}
293/**
294 * @deprecated in v8, delete after v10. This API should be used only be generated code, and that
295 * code should now use ɵɵdefineInjectable instead.
296 * @publicApi
297 */
298const defineInjectable = ɵɵdefineInjectable;
299/**
300 * Construct an `InjectorDef` which configures an injector.
301 *
302 * This should be assigned to a static injector def (`ɵinj`) field on a type, which will then be an
303 * `InjectorType`.
304 *
305 * Options:
306 *
307 * * `factory`: an `InjectorType` is an instantiable type, so a zero argument `factory` function to
308 * create the type must be provided. If that factory function needs to inject arguments, it can
309 * use the `inject` function.
310 * * `providers`: an optional array of providers to add to the injector. Each provider must
311 * either have a factory or point to a type which has a `ɵprov` static property (the
312 * type must be an `InjectableType`).
313 * * `imports`: an optional array of imports of other `InjectorType`s or `InjectorTypeWithModule`s
314 * whose providers will also be added to the injector. Locally provided types will override
315 * providers from imports.
316 *
317 * @codeGenApi
318 */
319function ɵɵdefineInjector(options) {
320 return {
321 factory: options.factory,
322 providers: options.providers || [],
323 imports: options.imports || [],
324 };
325}
326/**
327 * Read the injectable def (`ɵprov`) for `type` in a way which is immune to accidentally reading
328 * inherited value.
329 *
330 * @param type A type which may have its own (non-inherited) `ɵprov`.
331 */
332function getInjectableDef(type) {
333 return getOwnDefinition(type, type[NG_PROV_DEF]) ||
334 getOwnDefinition(type, type[NG_INJECTABLE_DEF]);
335}
336/**
337 * Return `def` only if it is defined directly on `type` and is not inherited from a base
338 * class of `type`.
339 *
340 * The function `Object.hasOwnProperty` is not sufficient to distinguish this case because in older
341 * browsers (e.g. IE10) static property inheritance is implemented by copying the properties.
342 *
343 * Instead, the definition's `token` is compared to the `type`, and if they don't match then the
344 * property was not defined directly on the type itself, and was likely inherited. The definition
345 * is only returned if the `type` matches the `def.token`.
346 */
347function getOwnDefinition(type, def) {
348 return def && def.token === type ? def : null;
349}
350/**
351 * Read the injectable def (`ɵprov`) for `type` or read the `ɵprov` from one of its ancestors.
352 *
353 * @param type A type which may have `ɵprov`, via inheritance.
354 *
355 * @deprecated Will be removed in a future version of Angular, where an error will occur in the
356 * scenario if we find the `ɵprov` on an ancestor only.
357 */
358function getInheritedInjectableDef(type) {
359 // See `jit/injectable.ts#compileInjectable` for context on NG_PROV_DEF_FALLBACK.
360 const def = type &&
361 (type[NG_PROV_DEF] || type[NG_INJECTABLE_DEF] ||
362 (type[NG_PROV_DEF_FALLBACK] && type[NG_PROV_DEF_FALLBACK]()));
363 if (def) {
364 const typeName = getTypeName(type);
365 // TODO(FW-1307): Re-add ngDevMode when closure can handle it
366 // ngDevMode &&
367 console.warn(`DEPRECATED: DI is instantiating a token "${typeName}" that inherits its @Injectable decorator but does not provide one itself.\n` +
368 `This will become an error in a future version of Angular. Please add @Injectable() to the "${typeName}" class.`);
369 return def;
370 }
371 else {
372 return null;
373 }
374}
375/** Gets the name of a type, accounting for some cross-browser differences. */
376function getTypeName(type) {
377 // `Function.prototype.name` behaves differently between IE and other browsers. In most browsers
378 // it'll always return the name of the function itself, no matter how many other functions it
379 // inherits from. On IE the function doesn't have its own `name` property, but it takes it from
380 // the lowest level in the prototype chain. E.g. if we have `class Foo extends Parent` most
381 // browsers will evaluate `Foo.name` to `Foo` while IE will return `Parent`. We work around
382 // the issue by converting the function to a string and parsing its name out that way via a regex.
383 if (type.hasOwnProperty('name')) {
384 return type.name;
385 }
386 const match = ('' + type).match(/^function\s*([^\s(]+)/);
387 return match === null ? '' : match[1];
388}
389/**
390 * Read the injector def type in a way which is immune to accidentally reading inherited value.
391 *
392 * @param type type which may have an injector def (`ɵinj`)
393 */
394function getInjectorDef(type) {
395 return type && (type.hasOwnProperty(NG_INJ_DEF) || type.hasOwnProperty(NG_INJECTOR_DEF)) ?
396 type[NG_INJ_DEF] :
397 null;
398}
399const NG_PROV_DEF = getClosureSafeProperty({ ɵprov: getClosureSafeProperty });
400const NG_INJ_DEF = getClosureSafeProperty({ ɵinj: getClosureSafeProperty });
401// On IE10 properties defined via `defineProperty` won't be inherited by child classes,
402// which will break inheriting the injectable definition from a grandparent through an
403// undecorated parent class. We work around it by defining a fallback method which will be
404// used to retrieve the definition. This should only be a problem in JIT mode, because in
405// AOT TypeScript seems to have a workaround for static properties. When inheriting from an
406// undecorated parent is no longer supported in v10, this can safely be removed.
407const NG_PROV_DEF_FALLBACK = getClosureSafeProperty({ ɵprovFallback: getClosureSafeProperty });
408// We need to keep these around so we can read off old defs if new defs are unavailable
409const NG_INJECTABLE_DEF = getClosureSafeProperty({ ngInjectableDef: getClosureSafeProperty });
410const NG_INJECTOR_DEF = getClosureSafeProperty({ ngInjectorDef: getClosureSafeProperty });
411
412/**
413 * @license
414 * Copyright Google LLC All Rights Reserved.
415 *
416 * Use of this source code is governed by an MIT-style license that can be
417 * found in the LICENSE file at https://angular.io/license
418 */
419function stringify(token) {
420 if (typeof token === 'string') {
421 return token;
422 }
423 if (Array.isArray(token)) {
424 return '[' + token.map(stringify).join(', ') + ']';
425 }
426 if (token == null) {
427 return '' + token;
428 }
429 if (token.overriddenName) {
430 return `${token.overriddenName}`;
431 }
432 if (token.name) {
433 return `${token.name}`;
434 }
435 const res = token.toString();
436 if (res == null) {
437 return '' + res;
438 }
439 const newLineIndex = res.indexOf('\n');
440 return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
441}
442/**
443 * Concatenates two strings with separator, allocating new strings only when necessary.
444 *
445 * @param before before string.
446 * @param separator separator string.
447 * @param after after string.
448 * @returns concatenated string.
449 */
450function concatStringsWithSpace(before, after) {
451 return (before == null || before === '') ?
452 (after === null ? '' : after) :
453 ((after == null || after === '') ? before : before + ' ' + after);
454}
455
456/**
457 * @license
458 * Copyright Google LLC All Rights Reserved.
459 *
460 * Use of this source code is governed by an MIT-style license that can be
461 * found in the LICENSE file at https://angular.io/license
462 */
463const __forward_ref__ = getClosureSafeProperty({ __forward_ref__: getClosureSafeProperty });
464/**
465 * Allows to refer to references which are not yet defined.
466 *
467 * For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
468 * DI is declared, but not yet defined. It is also used when the `token` which we use when creating
469 * a query is not yet defined.
470 *
471 * @usageNotes
472 * ### Example
473 * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}
474 * @publicApi
475 */
476function forwardRef(forwardRefFn) {
477 forwardRefFn.__forward_ref__ = forwardRef;
478 forwardRefFn.toString = function () {
479 return stringify(this());
480 };
481 return forwardRefFn;
482}
483/**
484 * Lazily retrieves the reference value from a forwardRef.
485 *
486 * Acts as the identity function when given a non-forward-ref value.
487 *
488 * @usageNotes
489 * ### Example
490 *
491 * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}
492 *
493 * @see `forwardRef`
494 * @publicApi
495 */
496function resolveForwardRef(type) {
497 return isForwardRef(type) ? type() : type;
498}
499/** Checks whether a function is wrapped by a `forwardRef`. */
500function isForwardRef(fn) {
501 return typeof fn === 'function' && fn.hasOwnProperty(__forward_ref__) &&
502 fn.__forward_ref__ === forwardRef;
503}
504
505/**
506 * @license
507 * Copyright Google LLC All Rights Reserved.
508 *
509 * Use of this source code is governed by an MIT-style license that can be
510 * found in the LICENSE file at https://angular.io/license
511 */
512const __globalThis = typeof globalThis !== 'undefined' && globalThis;
513const __window = typeof window !== 'undefined' && window;
514const __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
515 self instanceof WorkerGlobalScope && self;
516const __global = typeof global !== 'undefined' && global;
517// Always use __globalThis if available, which is the spec-defined global variable across all
518// environments, then fallback to __global first, because in Node tests both __global and
519// __window may be defined and _global should be __global in that case.
520const _global = __globalThis || __global || __window || __self;
521
522/**
523 * @license
524 * Copyright Google LLC All Rights Reserved.
525 *
526 * Use of this source code is governed by an MIT-style license that can be
527 * found in the LICENSE file at https://angular.io/license
528 */
529var R3ResolvedDependencyType;
530(function (R3ResolvedDependencyType) {
531 R3ResolvedDependencyType[R3ResolvedDependencyType["Token"] = 0] = "Token";
532 R3ResolvedDependencyType[R3ResolvedDependencyType["Attribute"] = 1] = "Attribute";
533 R3ResolvedDependencyType[R3ResolvedDependencyType["ChangeDetectorRef"] = 2] = "ChangeDetectorRef";
534 R3ResolvedDependencyType[R3ResolvedDependencyType["Invalid"] = 3] = "Invalid";
535})(R3ResolvedDependencyType || (R3ResolvedDependencyType = {}));
536var R3FactoryTarget;
537(function (R3FactoryTarget) {
538 R3FactoryTarget[R3FactoryTarget["Directive"] = 0] = "Directive";
539 R3FactoryTarget[R3FactoryTarget["Component"] = 1] = "Component";
540 R3FactoryTarget[R3FactoryTarget["Injectable"] = 2] = "Injectable";
541 R3FactoryTarget[R3FactoryTarget["Pipe"] = 3] = "Pipe";
542 R3FactoryTarget[R3FactoryTarget["NgModule"] = 4] = "NgModule";
543})(R3FactoryTarget || (R3FactoryTarget = {}));
544var ViewEncapsulation;
545(function (ViewEncapsulation) {
546 ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
547 ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native";
548 ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
549 ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
550})(ViewEncapsulation || (ViewEncapsulation = {}));
551
552/**
553 * @license
554 * Copyright Google LLC All Rights Reserved.
555 *
556 * Use of this source code is governed by an MIT-style license that can be
557 * found in the LICENSE file at https://angular.io/license
558 */
559function getCompilerFacade() {
560 const globalNg = _global['ng'];
561 if (!globalNg || !globalNg.ɵcompilerFacade) {
562 throw new Error(`Angular JIT compilation failed: '@angular/compiler' not loaded!\n` +
563 ` - JIT compilation is discouraged for production use-cases! Consider AOT mode instead.\n` +
564 ` - Did you bootstrap using '@angular/platform-browser-dynamic' or '@angular/platform-server'?\n` +
565 ` - Alternatively provide the compiler with 'import "@angular/compiler";' before bootstrapping.`);
566 }
567 return globalNg.ɵcompilerFacade;
568}
569
570/**
571 * @license
572 * Copyright Google LLC All Rights Reserved.
573 *
574 * Use of this source code is governed by an MIT-style license that can be
575 * found in the LICENSE file at https://angular.io/license
576 */
577const NG_COMP_DEF = getClosureSafeProperty({ ɵcmp: getClosureSafeProperty });
578const NG_DIR_DEF = getClosureSafeProperty({ ɵdir: getClosureSafeProperty });
579const NG_PIPE_DEF = getClosureSafeProperty({ ɵpipe: getClosureSafeProperty });
580const NG_MOD_DEF = getClosureSafeProperty({ ɵmod: getClosureSafeProperty });
581const NG_LOC_ID_DEF = getClosureSafeProperty({ ɵloc: getClosureSafeProperty });
582const NG_FACTORY_DEF = getClosureSafeProperty({ ɵfac: getClosureSafeProperty });
583/**
584 * If a directive is diPublic, bloomAdd sets a property on the type with this constant as
585 * the key and the directive's unique ID as the value. This allows us to map directives to their
586 * bloom filter bit for DI.
587 */
588// TODO(misko): This is wrong. The NG_ELEMENT_ID should never be minified.
589const NG_ELEMENT_ID = getClosureSafeProperty({ __NG_ELEMENT_ID__: getClosureSafeProperty });
590
591/**
592 * @license
593 * Copyright Google LLC All Rights Reserved.
594 *
595 * Use of this source code is governed by an MIT-style license that can be
596 * found in the LICENSE file at https://angular.io/license
597 */
598function ngDevModeResetPerfCounters() {
599 const locationString = typeof location !== 'undefined' ? location.toString() : '';
600 const newCounters = {
601 namedConstructors: locationString.indexOf('ngDevMode=namedConstructors') != -1,
602 firstCreatePass: 0,
603 tNode: 0,
604 tView: 0,
605 rendererCreateTextNode: 0,
606 rendererSetText: 0,
607 rendererCreateElement: 0,
608 rendererAddEventListener: 0,
609 rendererSetAttribute: 0,
610 rendererRemoveAttribute: 0,
611 rendererSetProperty: 0,
612 rendererSetClassName: 0,
613 rendererAddClass: 0,
614 rendererRemoveClass: 0,
615 rendererSetStyle: 0,
616 rendererRemoveStyle: 0,
617 rendererDestroy: 0,
618 rendererDestroyNode: 0,
619 rendererMoveNode: 0,
620 rendererRemoveNode: 0,
621 rendererAppendChild: 0,
622 rendererInsertBefore: 0,
623 rendererCreateComment: 0,
624 };
625 // Make sure to refer to ngDevMode as ['ngDevMode'] for closure.
626 const allowNgDevModeTrue = locationString.indexOf('ngDevMode=false') === -1;
627 _global['ngDevMode'] = allowNgDevModeTrue && newCounters;
628 return newCounters;
629}
630/**
631 * This function checks to see if the `ngDevMode` has been set. If yes,
632 * then we honor it, otherwise we default to dev mode with additional checks.
633 *
634 * The idea is that unless we are doing production build where we explicitly
635 * set `ngDevMode == false` we should be helping the developer by providing
636 * as much early warning and errors as possible.
637 *
638 * `ɵɵdefineComponent` is guaranteed to have been called before any component template functions
639 * (and thus Ivy instructions), so a single initialization there is sufficient to ensure ngDevMode
640 * is defined for the entire instruction set.
641 *
642 * When checking `ngDevMode` on toplevel, always init it before referencing it
643 * (e.g. `((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode())`), otherwise you can
644 * get a `ReferenceError` like in https://github.com/angular/angular/issues/31595.
645 *
646 * Details on possible values for `ngDevMode` can be found on its docstring.
647 *
648 * NOTE:
649 * - changes to the `ngDevMode` name must be synced with `compiler-cli/src/tooling.ts`.
650 */
651function initNgDevMode() {
652 // The below checks are to ensure that calling `initNgDevMode` multiple times does not
653 // reset the counters.
654 // If the `ngDevMode` is not an object, then it means we have not created the perf counters
655 // yet.
656 if (typeof ngDevMode === 'undefined' || ngDevMode) {
657 if (typeof ngDevMode !== 'object') {
658 ngDevModeResetPerfCounters();
659 }
660 return !!ngDevMode;
661 }
662 return false;
663}
664
665/**
666 * @license
667 * Copyright Google LLC All Rights Reserved.
668 *
669 * Use of this source code is governed by an MIT-style license that can be
670 * found in the LICENSE file at https://angular.io/license
671 */
672/**
673 * Creates a token that can be used in a DI Provider.
674 *
675 * Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a
676 * runtime representation) such as when injecting an interface, callable type, array or
677 * parameterized type.
678 *
679 * `InjectionToken` is parameterized on `T` which is the type of object which will be returned by
680 * the `Injector`. This provides additional level of type safety.
681 *
682 * ```
683 * interface MyInterface {...}
684 * var myInterface = injector.get(new InjectionToken<MyInterface>('SomeToken'));
685 * // myInterface is inferred to be MyInterface.
686 * ```
687 *
688 * When creating an `InjectionToken`, you can optionally specify a factory function which returns
689 * (possibly by creating) a default value of the parameterized type `T`. This sets up the
690 * `InjectionToken` using this factory as a provider as if it was defined explicitly in the
691 * application's root injector. If the factory function, which takes zero arguments, needs to inject
692 * dependencies, it can do so using the `inject` function. See below for an example.
693 *
694 * Additionally, if a `factory` is specified you can also specify the `providedIn` option, which
695 * overrides the above behavior and marks the token as belonging to a particular `@NgModule`. As
696 * mentioned above, `'root'` is the default value for `providedIn`.
697 *
698 * @usageNotes
699 * ### Basic Example
700 *
701 * ### Plain InjectionToken
702 *
703 * {@example core/di/ts/injector_spec.ts region='InjectionToken'}
704 *
705 * ### Tree-shakable InjectionToken
706 *
707 * {@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
708 *
709 *
710 * @publicApi
711 */
712class InjectionToken {
713 constructor(_desc, options) {
714 this._desc = _desc;
715 /** @internal */
716 this.ngMetadataName = 'InjectionToken';
717 this.ɵprov = undefined;
718 if (typeof options == 'number') {
719 // This is a special hack to assign __NG_ELEMENT_ID__ to this instance.
720 // __NG_ELEMENT_ID__ is Used by Ivy to determine bloom filter id.
721 // We are using it to assign `-1` which is used to identify `Injector`.
722 this.__NG_ELEMENT_ID__ = options;
723 }
724 else if (options !== undefined) {
725 this.ɵprov = ɵɵdefineInjectable({
726 token: this,
727 providedIn: options.providedIn || 'root',
728 factory: options.factory,
729 });
730 }
731 }
732 toString() {
733 return `InjectionToken ${this._desc}`;
734 }
735}
736
737/**
738 * @license
739 * Copyright Google LLC All Rights Reserved.
740 *
741 * Use of this source code is governed by an MIT-style license that can be
742 * found in the LICENSE file at https://angular.io/license
743 */
744/**
745 * An InjectionToken that gets the current `Injector` for `createInjector()`-style injectors.
746 *
747 * Requesting this token instead of `Injector` allows `StaticInjector` to be tree-shaken from a
748 * project.
749 *
750 * @publicApi
751 */
752const INJECTOR = new InjectionToken('INJECTOR', -1 // `-1` is used by Ivy DI system as special value to recognize it as `Injector`.
753);
754const _THROW_IF_NOT_FOUND = {};
755const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
756const NG_TEMP_TOKEN_PATH = 'ngTempTokenPath';
757const NG_TOKEN_PATH = 'ngTokenPath';
758const NEW_LINE = /\n/gm;
759const NO_NEW_LINE = 'ɵ';
760const SOURCE = '__source';
761const ɵ0$1 = getClosureSafeProperty;
762const USE_VALUE = getClosureSafeProperty({ provide: String, useValue: ɵ0$1 });
763/**
764 * Current injector value used by `inject`.
765 * - `undefined`: it is an error to call `inject`
766 * - `null`: `inject` can be called but there is no injector (limp-mode).
767 * - Injector instance: Use the injector for resolution.
768 */
769let _currentInjector = undefined;
770function setCurrentInjector(injector) {
771 const former = _currentInjector;
772 _currentInjector = injector;
773 return former;
774}
775/**
776 * Current implementation of inject.
777 *
778 * By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed
779 * to `directiveInject`, which brings in the `NodeInjector` system of ivy. It is designed this
780 * way for two reasons:
781 * 1. `Injector` should not depend on ivy logic.
782 * 2. To maintain tree shake-ability we don't want to bring in unnecessary code.
783 */
784let _injectImplementation;
785/**
786 * Sets the current inject implementation.
787 */
788function setInjectImplementation(impl) {
789 const previous = _injectImplementation;
790 _injectImplementation = impl;
791 return previous;
792}
793function injectInjectorOnly(token, flags = InjectFlags.Default) {
794 if (_currentInjector === undefined) {
795 throw new Error(`inject() must be called from an injection context`);
796 }
797 else if (_currentInjector === null) {
798 return injectRootLimpMode(token, undefined, flags);
799 }
800 else {
801 return _currentInjector.get(token, flags & InjectFlags.Optional ? null : undefined, flags);
802 }
803}
804function ɵɵinject(token, flags = InjectFlags.Default) {
805 return (_injectImplementation || injectInjectorOnly)(resolveForwardRef(token), flags);
806}
807/**
808 * Throws an error indicating that a factory function could not be generated by the compiler for a
809 * particular class.
810 *
811 * This instruction allows the actual error message to be optimized away when ngDevMode is turned
812 * off, saving bytes of generated code while still providing a good experience in dev mode.
813 *
814 * The name of the class is not mentioned here, but will be in the generated factory function name
815 * and thus in the stack trace.
816 *
817 * @codeGenApi
818 */
819function ɵɵinvalidFactoryDep(index) {
820 const msg = ngDevMode ?
821 `This constructor is not compatible with Angular Dependency Injection because its dependency at index ${index} of the parameter list is invalid.
822This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator.
823
824Please check that 1) the type for the parameter at index ${index} is correct and 2) the correct Angular decorators are defined for this class and its ancestors.` :
825 'invalid';
826 throw new Error(msg);
827}
828/**
829 * Injects a token from the currently active injector.
830 *
831 * Must be used in the context of a factory function such as one defined for an
832 * `InjectionToken`. Throws an error if not called from such a context.
833 *
834 * Within such a factory function, using this function to request injection of a dependency
835 * is faster and more type-safe than providing an additional array of dependencies
836 * (as has been common with `useFactory` providers).
837 *
838 * @param token The injection token for the dependency to be injected.
839 * @param flags Optional flags that control how injection is executed.
840 * The flags correspond to injection strategies that can be specified with
841 * parameter decorators `@Host`, `@Self`, `@SkipSef`, and `@Optional`.
842 * @returns True if injection is successful, null otherwise.
843 *
844 * @usageNotes
845 *
846 * ### Example
847 *
848 * {@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
849 *
850 * @publicApi
851 */
852const inject = ɵɵinject;
853/**
854 * Injects `root` tokens in limp mode.
855 *
856 * If no injector exists, we can still inject tree-shakable providers which have `providedIn` set to
857 * `"root"`. This is known as the limp mode injection. In such case the value is stored in the
858 * `InjectableDef`.
859 */
860function injectRootLimpMode(token, notFoundValue, flags) {
861 const injectableDef = getInjectableDef(token);
862 if (injectableDef && injectableDef.providedIn == 'root') {
863 return injectableDef.value === undefined ? injectableDef.value = injectableDef.factory() :
864 injectableDef.value;
865 }
866 if (flags & InjectFlags.Optional)
867 return null;
868 if (notFoundValue !== undefined)
869 return notFoundValue;
870 throw new Error(`Injector: NOT_FOUND [${stringify(token)}]`);
871}
872function injectArgs(types) {
873 const args = [];
874 for (let i = 0; i < types.length; i++) {
875 const arg = resolveForwardRef(types[i]);
876 if (Array.isArray(arg)) {
877 if (arg.length === 0) {
878 throw new Error('Arguments array must have arguments.');
879 }
880 let type = undefined;
881 let flags = InjectFlags.Default;
882 for (let j = 0; j < arg.length; j++) {
883 const meta = arg[j];
884 if (meta instanceof Optional || meta.ngMetadataName === 'Optional' || meta === Optional) {
885 flags |= InjectFlags.Optional;
886 }
887 else if (meta instanceof SkipSelf || meta.ngMetadataName === 'SkipSelf' || meta === SkipSelf) {
888 flags |= InjectFlags.SkipSelf;
889 }
890 else if (meta instanceof Self || meta.ngMetadataName === 'Self' || meta === Self) {
891 flags |= InjectFlags.Self;
892 }
893 else if (meta instanceof Inject || meta === Inject) {
894 type = meta.token;
895 }
896 else {
897 type = meta;
898 }
899 }
900 args.push(ɵɵinject(type, flags));
901 }
902 else {
903 args.push(ɵɵinject(arg));
904 }
905 }
906 return args;
907}
908class NullInjector {
909 get(token, notFoundValue = THROW_IF_NOT_FOUND) {
910 if (notFoundValue === THROW_IF_NOT_FOUND) {
911 // Intentionally left behind: With dev tools open the debugger will stop here. There is no
912 // reason why correctly written application should cause this exception.
913 // TODO(misko): uncomment the next line once `ngDevMode` works with closure.
914 // if (ngDevMode) debugger;
915 const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`);
916 error.name = 'NullInjectorError';
917 throw error;
918 }
919 return notFoundValue;
920 }
921}
922function catchInjectorError(e, token, injectorErrorName, source) {
923 const tokenPath = e[NG_TEMP_TOKEN_PATH];
924 if (token[SOURCE]) {
925 tokenPath.unshift(token[SOURCE]);
926 }
927 e.message = formatError('\n' + e.message, tokenPath, injectorErrorName, source);
928 e[NG_TOKEN_PATH] = tokenPath;
929 e[NG_TEMP_TOKEN_PATH] = null;
930 throw e;
931}
932function formatError(text, obj, injectorErrorName, source = null) {
933 text = text && text.charAt(0) === '\n' && text.charAt(1) == NO_NEW_LINE ? text.substr(2) : text;
934 let context = stringify(obj);
935 if (Array.isArray(obj)) {
936 context = obj.map(stringify).join(' -> ');
937 }
938 else if (typeof obj === 'object') {
939 let parts = [];
940 for (let key in obj) {
941 if (obj.hasOwnProperty(key)) {
942 let value = obj[key];
943 parts.push(key + ':' + (typeof value === 'string' ? JSON.stringify(value) : stringify(value)));
944 }
945 }
946 context = `{${parts.join(', ')}}`;
947 }
948 return `${injectorErrorName}${source ? '(' + source + ')' : ''}[${context}]: ${text.replace(NEW_LINE, '\n ')}`;
949}
950
951/**
952 * @license
953 * Copyright Google LLC All Rights Reserved.
954 *
955 * Use of this source code is governed by an MIT-style license that can be
956 * found in the LICENSE file at https://angular.io/license
957 */
958/**
959 * A mapping of the @angular/core API surface used in generated expressions to the actual symbols.
960 *
961 * This should be kept up to date with the public exports of @angular/core.
962 */
963const angularCoreDiEnv = {
964 'ɵɵdefineInjectable': ɵɵdefineInjectable,
965 'ɵɵdefineInjector': ɵɵdefineInjector,
966 'ɵɵinject': ɵɵinject,
967 'ɵɵgetFactoryOf': getFactoryOf,
968 'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
969};
970function getFactoryOf(type) {
971 const typeAny = type;
972 if (isForwardRef(type)) {
973 return (() => {
974 const factory = getFactoryOf(resolveForwardRef(typeAny));
975 return factory ? factory() : null;
976 });
977 }
978 const def = getInjectableDef(typeAny) || getInjectorDef(typeAny);
979 if (!def || def.factory === undefined) {
980 return null;
981 }
982 return def.factory;
983}
984
985/**
986 * @license
987 * Copyright Google LLC All Rights Reserved.
988 *
989 * Use of this source code is governed by an MIT-style license that can be
990 * found in the LICENSE file at https://angular.io/license
991 */
992/**
993 * Represents an instance of an `NgModule` created by an `NgModuleFactory`.
994 * Provides access to the `NgModule` instance and related objects.
995 *
996 * @publicApi
997 */
998class NgModuleRef {
999}
1000/**
1001 * @publicApi
1002 */
1003class NgModuleFactory {
1004}
1005
1006/**
1007 * @license
1008 * Copyright Google LLC All Rights Reserved.
1009 *
1010 * Use of this source code is governed by an MIT-style license that can be
1011 * found in the LICENSE file at https://angular.io/license
1012 */
1013function assertNumber(actual, msg) {
1014 if (!(typeof actual === 'number')) {
1015 throwError(msg, typeof actual, 'number', '===');
1016 }
1017}
1018function assertNumberInRange(actual, minInclusive, maxInclusive) {
1019 assertNumber(actual, 'Expected a number');
1020 assertLessThanOrEqual(actual, maxInclusive, 'Expected number to be less than or equal to');
1021 assertGreaterThanOrEqual(actual, minInclusive, 'Expected number to be greater than or equal to');
1022}
1023function assertString(actual, msg) {
1024 if (!(typeof actual === 'string')) {
1025 throwError(msg, actual === null ? 'null' : typeof actual, 'string', '===');
1026 }
1027}
1028function assertEqual(actual, expected, msg) {
1029 if (!(actual == expected)) {
1030 throwError(msg, actual, expected, '==');
1031 }
1032}
1033function assertNotEqual(actual, expected, msg) {
1034 if (!(actual != expected)) {
1035 throwError(msg, actual, expected, '!=');
1036 }
1037}
1038function assertSame(actual, expected, msg) {
1039 if (!(actual === expected)) {
1040 throwError(msg, actual, expected, '===');
1041 }
1042}
1043function assertNotSame(actual, expected, msg) {
1044 if (!(actual !== expected)) {
1045 throwError(msg, actual, expected, '!==');
1046 }
1047}
1048function assertLessThan(actual, expected, msg) {
1049 if (!(actual < expected)) {
1050 throwError(msg, actual, expected, '<');
1051 }
1052}
1053function assertLessThanOrEqual(actual, expected, msg) {
1054 if (!(actual <= expected)) {
1055 throwError(msg, actual, expected, '<=');
1056 }
1057}
1058function assertGreaterThan(actual, expected, msg) {
1059 if (!(actual > expected)) {
1060 throwError(msg, actual, expected, '>');
1061 }
1062}
1063function assertGreaterThanOrEqual(actual, expected, msg) {
1064 if (!(actual >= expected)) {
1065 throwError(msg, actual, expected, '>=');
1066 }
1067}
1068function assertNotDefined(actual, msg) {
1069 if (actual != null) {
1070 throwError(msg, actual, null, '==');
1071 }
1072}
1073function assertDefined(actual, msg) {
1074 if (actual == null) {
1075 throwError(msg, actual, null, '!=');
1076 }
1077}
1078function throwError(msg, actual, expected, comparison) {
1079 throw new Error(`ASSERTION ERROR: ${msg}` +
1080 (comparison == null ? '' : ` [Expected=> ${expected} ${comparison} ${actual} <=Actual]`));
1081}
1082function assertDomNode(node) {
1083 // If we're in a worker, `Node` will not be defined.
1084 assertEqual((typeof Node !== 'undefined' && node instanceof Node) ||
1085 (typeof node === 'object' && node != null &&
1086 node.constructor.name === 'WebWorkerRenderNode'), true, `The provided value must be an instance of a DOM Node but got ${stringify(node)}`);
1087}
1088function assertIndexInRange(arr, index) {
1089 const maxLen = arr ? arr.length : 0;
1090 assertLessThan(index, maxLen, `Index expected to be less than ${maxLen} but got ${index}`);
1091}
1092
1093/**
1094 * @license
1095 * Copyright Google LLC All Rights Reserved.
1096 *
1097 * Use of this source code is governed by an MIT-style license that can be
1098 * found in the LICENSE file at https://angular.io/license
1099 */
1100/**
1101 * Equivalent to ES6 spread, add each item to an array.
1102 *
1103 * @param items The items to add
1104 * @param arr The array to which you want to add the items
1105 */
1106function addAllToArray(items, arr) {
1107 for (let i = 0; i < items.length; i++) {
1108 arr.push(items[i]);
1109 }
1110}
1111/**
1112 * Flattens an array.
1113 */
1114function flatten(list, dst) {
1115 if (dst === undefined)
1116 dst = list;
1117 for (let i = 0; i < list.length; i++) {
1118 let item = list[i];
1119 if (Array.isArray(item)) {
1120 // we need to inline it.
1121 if (dst === list) {
1122 // Our assumption that the list was already flat was wrong and
1123 // we need to clone flat since we need to write to it.
1124 dst = list.slice(0, i);
1125 }
1126 flatten(item, dst);
1127 }
1128 else if (dst !== list) {
1129 dst.push(item);
1130 }
1131 }
1132 return dst;
1133}
1134function deepForEach(input, fn) {
1135 input.forEach(value => Array.isArray(value) ? deepForEach(value, fn) : fn(value));
1136}
1137function addToArray(arr, index, value) {
1138 // perf: array.push is faster than array.splice!
1139 if (index >= arr.length) {
1140 arr.push(value);
1141 }
1142 else {
1143 arr.splice(index, 0, value);
1144 }
1145}
1146function removeFromArray(arr, index) {
1147 // perf: array.pop is faster than array.splice!
1148 if (index >= arr.length - 1) {
1149 return arr.pop();
1150 }
1151 else {
1152 return arr.splice(index, 1)[0];
1153 }
1154}
1155function newArray(size, value) {
1156 const list = [];
1157 for (let i = 0; i < size; i++) {
1158 list.push(value);
1159 }
1160 return list;
1161}
1162/**
1163 * Remove item from array (Same as `Array.splice()` but faster.)
1164 *
1165 * `Array.splice()` is not as fast because it has to allocate an array for the elements which were
1166 * removed. This causes memory pressure and slows down code when most of the time we don't
1167 * care about the deleted items array.
1168 *
1169 * https://jsperf.com/fast-array-splice (About 20x faster)
1170 *
1171 * @param array Array to splice
1172 * @param index Index of element in array to remove.
1173 * @param count Number of items to remove.
1174 */
1175function arraySplice(array, index, count) {
1176 const length = array.length - count;
1177 while (index < length) {
1178 array[index] = array[index + count];
1179 index++;
1180 }
1181 while (count--) {
1182 array.pop(); // shrink the array
1183 }
1184}
1185/**
1186 * Same as `Array.splice(index, 0, value)` but faster.
1187 *
1188 * `Array.splice()` is not fast because it has to allocate an array for the elements which were
1189 * removed. This causes memory pressure and slows down code when most of the time we don't
1190 * care about the deleted items array.
1191 *
1192 * @param array Array to splice.
1193 * @param index Index in array where the `value` should be added.
1194 * @param value Value to add to array.
1195 */
1196function arrayInsert(array, index, value) {
1197 ngDevMode && assertLessThanOrEqual(index, array.length, 'Can\'t insert past array end.');
1198 let end = array.length;
1199 while (end > index) {
1200 const previousEnd = end - 1;
1201 array[end] = array[previousEnd];
1202 end = previousEnd;
1203 }
1204 array[index] = value;
1205}
1206/**
1207 * Same as `Array.splice2(index, 0, value1, value2)` but faster.
1208 *
1209 * `Array.splice()` is not fast because it has to allocate an array for the elements which were
1210 * removed. This causes memory pressure and slows down code when most of the time we don't
1211 * care about the deleted items array.
1212 *
1213 * @param array Array to splice.
1214 * @param index Index in array where the `value` should be added.
1215 * @param value1 Value to add to array.
1216 * @param value2 Value to add to array.
1217 */
1218function arrayInsert2(array, index, value1, value2) {
1219 ngDevMode && assertLessThanOrEqual(index, array.length, 'Can\'t insert past array end.');
1220 let end = array.length;
1221 if (end == index) {
1222 // inserting at the end.
1223 array.push(value1, value2);
1224 }
1225 else if (end === 1) {
1226 // corner case when we have less items in array than we have items to insert.
1227 array.push(value2, array[0]);
1228 array[0] = value1;
1229 }
1230 else {
1231 end--;
1232 array.push(array[end - 1], array[end]);
1233 while (end > index) {
1234 const previousEnd = end - 2;
1235 array[end] = array[previousEnd];
1236 end--;
1237 }
1238 array[index] = value1;
1239 array[index + 1] = value2;
1240 }
1241}
1242/**
1243 * Insert a `value` into an `array` so that the array remains sorted.
1244 *
1245 * NOTE:
1246 * - Duplicates are not allowed, and are ignored.
1247 * - This uses binary search algorithm for fast inserts.
1248 *
1249 * @param array A sorted array to insert into.
1250 * @param value The value to insert.
1251 * @returns index of the inserted value.
1252 */
1253function arrayInsertSorted(array, value) {
1254 let index = arrayIndexOfSorted(array, value);
1255 if (index < 0) {
1256 // if we did not find it insert it.
1257 index = ~index;
1258 arrayInsert(array, index, value);
1259 }
1260 return index;
1261}
1262/**
1263 * Remove `value` from a sorted `array`.
1264 *
1265 * NOTE:
1266 * - This uses binary search algorithm for fast removals.
1267 *
1268 * @param array A sorted array to remove from.
1269 * @param value The value to remove.
1270 * @returns index of the removed value.
1271 * - positive index if value found and removed.
1272 * - negative index if value not found. (`~index` to get the value where it should have been
1273 * inserted)
1274 */
1275function arrayRemoveSorted(array, value) {
1276 const index = arrayIndexOfSorted(array, value);
1277 if (index >= 0) {
1278 arraySplice(array, index, 1);
1279 }
1280 return index;
1281}
1282/**
1283 * Get an index of an `value` in a sorted `array`.
1284 *
1285 * NOTE:
1286 * - This uses binary search algorithm for fast removals.
1287 *
1288 * @param array A sorted array to binary search.
1289 * @param value The value to look for.
1290 * @returns index of the value.
1291 * - positive index if value found.
1292 * - negative index if value not found. (`~index` to get the value where it should have been
1293 * located)
1294 */
1295function arrayIndexOfSorted(array, value) {
1296 return _arrayIndexOfSorted(array, value, 0);
1297}
1298/**
1299 * Set a `value` for a `key`.
1300 *
1301 * @param keyValueArray to modify.
1302 * @param key The key to locate or create.
1303 * @param value The value to set for a `key`.
1304 * @returns index (always even) of where the value vas set.
1305 */
1306function keyValueArraySet(keyValueArray, key, value) {
1307 let index = keyValueArrayIndexOf(keyValueArray, key);
1308 if (index >= 0) {
1309 // if we found it set it.
1310 keyValueArray[index | 1] = value;
1311 }
1312 else {
1313 index = ~index;
1314 arrayInsert2(keyValueArray, index, key, value);
1315 }
1316 return index;
1317}
1318/**
1319 * Retrieve a `value` for a `key` (on `undefined` if not found.)
1320 *
1321 * @param keyValueArray to search.
1322 * @param key The key to locate.
1323 * @return The `value` stored at the `key` location or `undefined if not found.
1324 */
1325function keyValueArrayGet(keyValueArray, key) {
1326 const index = keyValueArrayIndexOf(keyValueArray, key);
1327 if (index >= 0) {
1328 // if we found it retrieve it.
1329 return keyValueArray[index | 1];
1330 }
1331 return undefined;
1332}
1333/**
1334 * Retrieve a `key` index value in the array or `-1` if not found.
1335 *
1336 * @param keyValueArray to search.
1337 * @param key The key to locate.
1338 * @returns index of where the key is (or should have been.)
1339 * - positive (even) index if key found.
1340 * - negative index if key not found. (`~index` (even) to get the index where it should have
1341 * been inserted.)
1342 */
1343function keyValueArrayIndexOf(keyValueArray, key) {
1344 return _arrayIndexOfSorted(keyValueArray, key, 1);
1345}
1346/**
1347 * Delete a `key` (and `value`) from the `KeyValueArray`.
1348 *
1349 * @param keyValueArray to modify.
1350 * @param key The key to locate or delete (if exist).
1351 * @returns index of where the key was (or should have been.)
1352 * - positive (even) index if key found and deleted.
1353 * - negative index if key not found. (`~index` (even) to get the index where it should have
1354 * been.)
1355 */
1356function keyValueArrayDelete(keyValueArray, key) {
1357 const index = keyValueArrayIndexOf(keyValueArray, key);
1358 if (index >= 0) {
1359 // if we found it remove it.
1360 arraySplice(keyValueArray, index, 2);
1361 }
1362 return index;
1363}
1364/**
1365 * INTERNAL: Get an index of an `value` in a sorted `array` by grouping search by `shift`.
1366 *
1367 * NOTE:
1368 * - This uses binary search algorithm for fast removals.
1369 *
1370 * @param array A sorted array to binary search.
1371 * @param value The value to look for.
1372 * @param shift grouping shift.
1373 * - `0` means look at every location
1374 * - `1` means only look at every other (even) location (the odd locations are to be ignored as
1375 * they are values.)
1376 * @returns index of the value.
1377 * - positive index if value found.
1378 * - negative index if value not found. (`~index` to get the value where it should have been
1379 * inserted)
1380 */
1381function _arrayIndexOfSorted(array, value, shift) {
1382 ngDevMode && assertEqual(Array.isArray(array), true, 'Expecting an array');
1383 let start = 0;
1384 let end = array.length >> shift;
1385 while (end !== start) {
1386 const middle = start + ((end - start) >> 1); // find the middle.
1387 const current = array[middle << shift];
1388 if (value === current) {
1389 return (middle << shift);
1390 }
1391 else if (current > value) {
1392 end = middle;
1393 }
1394 else {
1395 start = middle + 1; // We already searched middle so make it non-inclusive by adding 1
1396 }
1397 }
1398 return ~(end << shift);
1399}
1400
1401/**
1402 * @license
1403 * Copyright Google LLC All Rights Reserved.
1404 *
1405 * Use of this source code is governed by an MIT-style license that can be
1406 * found in the LICENSE file at https://angular.io/license
1407 */
1408/**
1409 * The strategy that the default change detector uses to detect changes.
1410 * When set, takes effect the next time change detection is triggered.
1411 *
1412 * @see {@link ChangeDetectorRef#usage-notes Change detection usage}
1413 *
1414 * @publicApi
1415 */
1416var ChangeDetectionStrategy;
1417(function (ChangeDetectionStrategy) {
1418 /**
1419 * Use the `CheckOnce` strategy, meaning that automatic change detection is deactivated
1420 * until reactivated by setting the strategy to `Default` (`CheckAlways`).
1421 * Change detection can still be explicitly invoked.
1422 * This strategy applies to all child directives and cannot be overridden.
1423 */
1424 ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
1425 /**
1426 * Use the default `CheckAlways` strategy, in which change detection is automatic until
1427 * explicitly deactivated.
1428 */
1429 ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
1430})(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));
1431/**
1432 * Defines the possible states of the default change detector.
1433 * @see `ChangeDetectorRef`
1434 */
1435var ChangeDetectorStatus;
1436(function (ChangeDetectorStatus) {
1437 /**
1438 * A state in which, after calling `detectChanges()`, the change detector
1439 * state becomes `Checked`, and must be explicitly invoked or reactivated.
1440 */
1441 ChangeDetectorStatus[ChangeDetectorStatus["CheckOnce"] = 0] = "CheckOnce";
1442 /**
1443 * A state in which change detection is skipped until the change detector mode
1444 * becomes `CheckOnce`.
1445 */
1446 ChangeDetectorStatus[ChangeDetectorStatus["Checked"] = 1] = "Checked";
1447 /**
1448 * A state in which change detection continues automatically until explicitly
1449 * deactivated.
1450 */
1451 ChangeDetectorStatus[ChangeDetectorStatus["CheckAlways"] = 2] = "CheckAlways";
1452 /**
1453 * A state in which a change detector sub tree is not a part of the main tree and
1454 * should be skipped.
1455 */
1456 ChangeDetectorStatus[ChangeDetectorStatus["Detached"] = 3] = "Detached";
1457 /**
1458 * Indicates that the change detector encountered an error checking a binding
1459 * or calling a directive lifecycle method and is now in an inconsistent state. Change
1460 * detectors in this state do not detect changes.
1461 */
1462 ChangeDetectorStatus[ChangeDetectorStatus["Errored"] = 4] = "Errored";
1463 /**
1464 * Indicates that the change detector has been destroyed.
1465 */
1466 ChangeDetectorStatus[ChangeDetectorStatus["Destroyed"] = 5] = "Destroyed";
1467})(ChangeDetectorStatus || (ChangeDetectorStatus = {}));
1468/**
1469 * Reports whether a given strategy is currently the default for change detection.
1470 * @param changeDetectionStrategy The strategy to check.
1471 * @returns True if the given strategy is the current default, false otherwise.
1472 * @see `ChangeDetectorStatus`
1473 * @see `ChangeDetectorRef`
1474 */
1475function isDefaultChangeDetectionStrategy(changeDetectionStrategy) {
1476 return changeDetectionStrategy == null ||
1477 changeDetectionStrategy === ChangeDetectionStrategy.Default;
1478}
1479
1480/**
1481 * @license
1482 * Copyright Google LLC All Rights Reserved.
1483 *
1484 * Use of this source code is governed by an MIT-style license that can be
1485 * found in the LICENSE file at https://angular.io/license
1486 */
1487/**
1488 * Defines template and style encapsulation options available for Component's {@link Component}.
1489 *
1490 * See {@link Component#encapsulation encapsulation}.
1491 *
1492 * @usageNotes
1493 * ### Example
1494 *
1495 * {@example core/ts/metadata/encapsulation.ts region='longform'}
1496 *
1497 * @publicApi
1498 */
1499var ViewEncapsulation$1;
1500(function (ViewEncapsulation) {
1501 /**
1502 * Emulate `Native` scoping of styles by adding an attribute containing surrogate id to the Host
1503 * Element and pre-processing the style rules provided via {@link Component#styles styles} or
1504 * {@link Component#styleUrls styleUrls}, and adding the new Host Element attribute to all
1505 * selectors.
1506 *
1507 * This is the default option.
1508 */
1509 ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
1510 /**
1511 * @deprecated v6.1.0 - use {ViewEncapsulation.ShadowDom} instead.
1512 * Use the native encapsulation mechanism of the renderer.
1513 *
1514 * For the DOM this means using the deprecated [Shadow DOM
1515 * v0](https://w3c.github.io/webcomponents/spec/shadow/) and
1516 * creating a ShadowRoot for Component's Host Element.
1517 */
1518 ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native";
1519 /**
1520 * Don't provide any template or style encapsulation.
1521 */
1522 ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
1523 /**
1524 * Use Shadow DOM to encapsulate styles.
1525 *
1526 * For the DOM this means using modern [Shadow
1527 * DOM](https://w3c.github.io/webcomponents/spec/shadow/) and
1528 * creating a ShadowRoot for Component's Host Element.
1529 */
1530 ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
1531})(ViewEncapsulation$1 || (ViewEncapsulation$1 = {}));
1532
1533/**
1534 * @license
1535 * Copyright Google LLC All Rights Reserved.
1536 *
1537 * Use of this source code is governed by an MIT-style license that can be
1538 * found in the LICENSE file at https://angular.io/license
1539 */
1540/**
1541 * This file contains reuseable "empty" symbols that can be used as default return values
1542 * in different parts of the rendering code. Because the same symbols are returned, this
1543 * allows for identity checks against these values to be consistently used by the framework
1544 * code.
1545 */
1546const EMPTY_OBJ = {};
1547const EMPTY_ARRAY = [];
1548// freezing the values prevents any code from accidentally inserting new values in
1549if ((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode()) {
1550 // These property accesses can be ignored because ngDevMode will be set to false
1551 // when optimizing code and the whole if statement will be dropped.
1552 // tslint:disable-next-line:no-toplevel-property-access
1553 Object.freeze(EMPTY_OBJ);
1554 // tslint:disable-next-line:no-toplevel-property-access
1555 Object.freeze(EMPTY_ARRAY);
1556}
1557
1558/**
1559 * @license
1560 * Copyright Google LLC All Rights Reserved.
1561 *
1562 * Use of this source code is governed by an MIT-style license that can be
1563 * found in the LICENSE file at https://angular.io/license
1564 */
1565let _renderCompCount = 0;
1566/**
1567 * Create a component definition object.
1568 *
1569 *
1570 * # Example
1571 * ```
1572 * class MyDirective {
1573 * // Generated by Angular Template Compiler
1574 * // [Symbol] syntax will not be supported by TypeScript until v2.7
1575 * static ɵcmp = defineComponent({
1576 * ...
1577 * });
1578 * }
1579 * ```
1580 * @codeGenApi
1581 */
1582function ɵɵdefineComponent(componentDefinition) {
1583 return noSideEffects(() => {
1584 // Initialize ngDevMode. This must be the first statement in ɵɵdefineComponent.
1585 // See the `initNgDevMode` docstring for more information.
1586 (typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode();
1587 const type = componentDefinition.type;
1588 const typePrototype = type.prototype;
1589 const declaredInputs = {};
1590 const def = {
1591 type: type,
1592 providersResolver: null,
1593 decls: componentDefinition.decls,
1594 vars: componentDefinition.vars,
1595 factory: null,
1596 template: componentDefinition.template || null,
1597 consts: componentDefinition.consts || null,
1598 ngContentSelectors: componentDefinition.ngContentSelectors,
1599 hostBindings: componentDefinition.hostBindings || null,
1600 hostVars: componentDefinition.hostVars || 0,
1601 hostAttrs: componentDefinition.hostAttrs || null,
1602 contentQueries: componentDefinition.contentQueries || null,
1603 declaredInputs: declaredInputs,
1604 inputs: null,
1605 outputs: null,
1606 exportAs: componentDefinition.exportAs || null,
1607 onPush: componentDefinition.changeDetection === ChangeDetectionStrategy.OnPush,
1608 directiveDefs: null,
1609 pipeDefs: null,
1610 selectors: componentDefinition.selectors || EMPTY_ARRAY,
1611 viewQuery: componentDefinition.viewQuery || null,
1612 features: componentDefinition.features || null,
1613 data: componentDefinition.data || {},
1614 // TODO(misko): convert ViewEncapsulation into const enum so that it can be used
1615 // directly in the next line. Also `None` should be 0 not 2.
1616 encapsulation: componentDefinition.encapsulation || ViewEncapsulation$1.Emulated,
1617 id: 'c',
1618 styles: componentDefinition.styles || EMPTY_ARRAY,
1619 _: null,
1620 setInput: null,
1621 schemas: componentDefinition.schemas || null,
1622 tView: null,
1623 };
1624 const directiveTypes = componentDefinition.directives;
1625 const feature = componentDefinition.features;
1626 const pipeTypes = componentDefinition.pipes;
1627 def.id += _renderCompCount++;
1628 def.inputs = invertObject(componentDefinition.inputs, declaredInputs),
1629 def.outputs = invertObject(componentDefinition.outputs),
1630 feature && feature.forEach((fn) => fn(def));
1631 def.directiveDefs = directiveTypes ?
1632 () => (typeof directiveTypes === 'function' ? directiveTypes() : directiveTypes)
1633 .map(extractDirectiveDef) :
1634 null;
1635 def.pipeDefs = pipeTypes ?
1636 () => (typeof pipeTypes === 'function' ? pipeTypes() : pipeTypes).map(extractPipeDef) :
1637 null;
1638 return def;
1639 });
1640}
1641/**
1642 * @codeGenApi
1643 */
1644function ɵɵsetComponentScope(type, directives, pipes) {
1645 const def = type.ɵcmp;
1646 def.directiveDefs = () => directives.map(extractDirectiveDef);
1647 def.pipeDefs = () => pipes.map(extractPipeDef);
1648}
1649function extractDirectiveDef(type) {
1650 const def = getComponentDef(type) || getDirectiveDef(type);
1651 if (ngDevMode && !def) {
1652 throw new Error(`'${type.name}' is neither 'ComponentType' or 'DirectiveType'.`);
1653 }
1654 return def;
1655}
1656function extractPipeDef(type) {
1657 const def = getPipeDef(type);
1658 if (ngDevMode && !def) {
1659 throw new Error(`'${type.name}' is not a 'PipeType'.`);
1660 }
1661 return def;
1662}
1663const autoRegisterModuleById = {};
1664/**
1665 * @codeGenApi
1666 */
1667function ɵɵdefineNgModule(def) {
1668 const res = {
1669 type: def.type,
1670 bootstrap: def.bootstrap || EMPTY_ARRAY,
1671 declarations: def.declarations || EMPTY_ARRAY,
1672 imports: def.imports || EMPTY_ARRAY,
1673 exports: def.exports || EMPTY_ARRAY,
1674 transitiveCompileScopes: null,
1675 schemas: def.schemas || null,
1676 id: def.id || null,
1677 };
1678 if (def.id != null) {
1679 noSideEffects(() => {
1680 autoRegisterModuleById[def.id] = def.type;
1681 });
1682 }
1683 return res;
1684}
1685/**
1686 * Adds the module metadata that is necessary to compute the module's transitive scope to an
1687 * existing module definition.
1688 *
1689 * Scope metadata of modules is not used in production builds, so calls to this function can be
1690 * marked pure to tree-shake it from the bundle, allowing for all referenced declarations
1691 * to become eligible for tree-shaking as well.
1692 *
1693 * @codeGenApi
1694 */
1695function ɵɵsetNgModuleScope(type, scope) {
1696 return noSideEffects(() => {
1697 const ngModuleDef = getNgModuleDef(type, true);
1698 ngModuleDef.declarations = scope.declarations || EMPTY_ARRAY;
1699 ngModuleDef.imports = scope.imports || EMPTY_ARRAY;
1700 ngModuleDef.exports = scope.exports || EMPTY_ARRAY;
1701 });
1702}
1703/**
1704 * Inverts an inputs or outputs lookup such that the keys, which were the
1705 * minified keys, are part of the values, and the values are parsed so that
1706 * the publicName of the property is the new key
1707 *
1708 * e.g. for
1709 *
1710 * ```
1711 * class Comp {
1712 * @Input()
1713 * propName1: string;
1714 *
1715 * @Input('publicName2')
1716 * declaredPropName2: number;
1717 * }
1718 * ```
1719 *
1720 * will be serialized as
1721 *
1722 * ```
1723 * {
1724 * propName1: 'propName1',
1725 * declaredPropName2: ['publicName2', 'declaredPropName2'],
1726 * }
1727 * ```
1728 *
1729 * which is than translated by the minifier as:
1730 *
1731 * ```
1732 * {
1733 * minifiedPropName1: 'propName1',
1734 * minifiedPropName2: ['publicName2', 'declaredPropName2'],
1735 * }
1736 * ```
1737 *
1738 * becomes: (public name => minifiedName)
1739 *
1740 * ```
1741 * {
1742 * 'propName1': 'minifiedPropName1',
1743 * 'publicName2': 'minifiedPropName2',
1744 * }
1745 * ```
1746 *
1747 * Optionally the function can take `secondary` which will result in: (public name => declared name)
1748 *
1749 * ```
1750 * {
1751 * 'propName1': 'propName1',
1752 * 'publicName2': 'declaredPropName2',
1753 * }
1754 * ```
1755 *
1756
1757 */
1758function invertObject(obj, secondary) {
1759 if (obj == null)
1760 return EMPTY_OBJ;
1761 const newLookup = {};
1762 for (const minifiedKey in obj) {
1763 if (obj.hasOwnProperty(minifiedKey)) {
1764 let publicName = obj[minifiedKey];
1765 let declaredName = publicName;
1766 if (Array.isArray(publicName)) {
1767 declaredName = publicName[1];
1768 publicName = publicName[0];
1769 }
1770 newLookup[publicName] = minifiedKey;
1771 if (secondary) {
1772 (secondary[publicName] = declaredName);
1773 }
1774 }
1775 }
1776 return newLookup;
1777}
1778/**
1779 * Create a directive definition object.
1780 *
1781 * # Example
1782 * ```ts
1783 * class MyDirective {
1784 * // Generated by Angular Template Compiler
1785 * // [Symbol] syntax will not be supported by TypeScript until v2.7
1786 * static ɵdir = ɵɵdefineDirective({
1787 * ...
1788 * });
1789 * }
1790 * ```
1791 *
1792 * @codeGenApi
1793 */
1794const ɵɵdefineDirective = ɵɵdefineComponent;
1795/**
1796 * Create a pipe definition object.
1797 *
1798 * # Example
1799 * ```
1800 * class MyPipe implements PipeTransform {
1801 * // Generated by Angular Template Compiler
1802 * static ɵpipe = definePipe({
1803 * ...
1804 * });
1805 * }
1806 * ```
1807 * @param pipeDef Pipe definition generated by the compiler
1808 *
1809 * @codeGenApi
1810 */
1811function ɵɵdefinePipe(pipeDef) {
1812 return {
1813 type: pipeDef.type,
1814 name: pipeDef.name,
1815 factory: null,
1816 pure: pipeDef.pure !== false,
1817 onDestroy: pipeDef.type.prototype.ngOnDestroy || null
1818 };
1819}
1820/**
1821 * The following getter methods retrieve the definition form the type. Currently the retrieval
1822 * honors inheritance, but in the future we may change the rule to require that definitions are
1823 * explicit. This would require some sort of migration strategy.
1824 */
1825function getComponentDef(type) {
1826 return type[NG_COMP_DEF] || null;
1827}
1828function getDirectiveDef(type) {
1829 return type[NG_DIR_DEF] || null;
1830}
1831function getPipeDef(type) {
1832 return type[NG_PIPE_DEF] || null;
1833}
1834function getFactoryDef(type, throwNotFound) {
1835 const hasFactoryDef = type.hasOwnProperty(NG_FACTORY_DEF);
1836 if (!hasFactoryDef && throwNotFound === true && ngDevMode) {
1837 throw new Error(`Type ${stringify(type)} does not have 'ɵfac' property.`);
1838 }
1839 return hasFactoryDef ? type[NG_FACTORY_DEF] : null;
1840}
1841function getNgModuleDef(type, throwNotFound) {
1842 const ngModuleDef = type[NG_MOD_DEF] || null;
1843 if (!ngModuleDef && throwNotFound === true) {
1844 throw new Error(`Type ${stringify(type)} does not have 'ɵmod' property.`);
1845 }
1846 return ngModuleDef;
1847}
1848function getNgLocaleIdDef(type) {
1849 return type[NG_LOC_ID_DEF] || null;
1850}
1851
1852/**
1853 * @license
1854 * Copyright Google LLC All Rights Reserved.
1855 *
1856 * Use of this source code is governed by an MIT-style license that can be
1857 * found in the LICENSE file at https://angular.io/license
1858 */
1859// Below are constants for LView indices to help us look up LView members
1860// without having to remember the specific indices.
1861// Uglify will inline these when minifying so there shouldn't be a cost.
1862const HOST = 0;
1863const TVIEW = 1;
1864const FLAGS = 2;
1865const PARENT = 3;
1866const NEXT = 4;
1867const TRANSPLANTED_VIEWS_TO_REFRESH = 5;
1868const T_HOST = 6;
1869const CLEANUP = 7;
1870const CONTEXT = 8;
1871const INJECTOR$1 = 9;
1872const RENDERER_FACTORY = 10;
1873const RENDERER = 11;
1874const SANITIZER = 12;
1875const CHILD_HEAD = 13;
1876const CHILD_TAIL = 14;
1877const DECLARATION_VIEW = 15;
1878const DECLARATION_COMPONENT_VIEW = 16;
1879const DECLARATION_LCONTAINER = 17;
1880const PREORDER_HOOK_FLAGS = 18;
1881const QUERIES = 19;
1882/** Size of LView's header. Necessary to adjust for it when setting slots. */
1883const HEADER_OFFSET = 20;
1884// Note: This hack is necessary so we don't erroneously get a circular dependency
1885// failure based on types.
1886const unusedValueExportToPlacateAjd = 1;
1887
1888/**
1889 * @license
1890 * Copyright Google LLC All Rights Reserved.
1891 *
1892 * Use of this source code is governed by an MIT-style license that can be
1893 * found in the LICENSE file at https://angular.io/license
1894 */
1895/**
1896 * Special location which allows easy identification of type. If we have an array which was
1897 * retrieved from the `LView` and that array has `true` at `TYPE` location, we know it is
1898 * `LContainer`.
1899 */
1900const TYPE = 1;
1901/**
1902 * Below are constants for LContainer indices to help us look up LContainer members
1903 * without having to remember the specific indices.
1904 * Uglify will inline these when minifying so there shouldn't be a cost.
1905 */
1906/**
1907 * Flag to signify that this `LContainer` may have transplanted views which need to be change
1908 * detected. (see: `LView[DECLARATION_COMPONENT_VIEW])`.
1909 *
1910 * This flag, once set, is never unset for the `LContainer`. This means that when unset we can skip
1911 * a lot of work in `refreshEmbeddedViews`. But when set we still need to verify
1912 * that the `MOVED_VIEWS` are transplanted and on-push.
1913 */
1914const HAS_TRANSPLANTED_VIEWS = 2;
1915// PARENT, NEXT, TRANSPLANTED_VIEWS_TO_REFRESH are indices 3, 4, and 5
1916// As we already have these constants in LView, we don't need to re-create them.
1917// T_HOST is index 6
1918// We already have this constants in LView, we don't need to re-create it.
1919const NATIVE = 7;
1920const VIEW_REFS = 8;
1921const MOVED_VIEWS = 9;
1922/**
1923 * Size of LContainer's header. Represents the index after which all views in the
1924 * container will be inserted. We need to keep a record of current views so we know
1925 * which views are already in the DOM (and don't need to be re-added) and so we can
1926 * remove views from the DOM when they are no longer required.
1927 */
1928const CONTAINER_HEADER_OFFSET = 10;
1929// Note: This hack is necessary so we don't erroneously get a circular dependency
1930// failure based on types.
1931const unusedValueExportToPlacateAjd$1 = 1;
1932
1933/**
1934 * @license
1935 * Copyright Google LLC All Rights Reserved.
1936 *
1937 * Use of this source code is governed by an MIT-style license that can be
1938 * found in the LICENSE file at https://angular.io/license
1939 */
1940/**
1941 * True if `value` is `LView`.
1942 * @param value wrapped value of `RNode`, `LView`, `LContainer`
1943 */
1944function isLView(value) {
1945 return Array.isArray(value) && typeof value[TYPE] === 'object';
1946}
1947/**
1948 * True if `value` is `LContainer`.
1949 * @param value wrapped value of `RNode`, `LView`, `LContainer`
1950 */
1951function isLContainer(value) {
1952 return Array.isArray(value) && value[TYPE] === true;
1953}
1954function isContentQueryHost(tNode) {
1955 return (tNode.flags & 8 /* hasContentQuery */) !== 0;
1956}
1957function isComponentHost(tNode) {
1958 return (tNode.flags & 2 /* isComponentHost */) === 2 /* isComponentHost */;
1959}
1960function isDirectiveHost(tNode) {
1961 return (tNode.flags & 1 /* isDirectiveHost */) === 1 /* isDirectiveHost */;
1962}
1963function isComponentDef(def) {
1964 return def.template !== null;
1965}
1966function isRootView(target) {
1967 return (target[FLAGS] & 512 /* IsRoot */) !== 0;
1968}
1969
1970/**
1971 * @license
1972 * Copyright Google LLC All Rights Reserved.
1973 *
1974 * Use of this source code is governed by an MIT-style license that can be
1975 * found in the LICENSE file at https://angular.io/license
1976 */
1977// [Assert functions do not constraint type when they are guarded by a truthy
1978// expression.](https://github.com/microsoft/TypeScript/issues/37295)
1979function assertTNodeForLView(tNode, lView) {
1980 tNode.hasOwnProperty('tView_') &&
1981 assertEqual(tNode.tView_, lView[TVIEW], 'This TNode does not belong to this LView.');
1982}
1983function assertComponentType(actual, msg = 'Type passed in is not ComponentType, it does not have \'ɵcmp\' property.') {
1984 if (!getComponentDef(actual)) {
1985 throwError(msg);
1986 }
1987}
1988function assertNgModuleType(actual, msg = 'Type passed in is not NgModuleType, it does not have \'ɵmod\' property.') {
1989 if (!getNgModuleDef(actual)) {
1990 throwError(msg);
1991 }
1992}
1993function assertPreviousIsParent(isParent) {
1994 assertEqual(isParent, true, 'previousOrParentTNode should be a parent');
1995}
1996function assertHasParent(tNode) {
1997 assertDefined(tNode, 'previousOrParentTNode should exist!');
1998 assertDefined(tNode.parent, 'previousOrParentTNode should have a parent');
1999}
2000function assertDataNext(lView, index, arr) {
2001 if (arr == null)
2002 arr = lView;
2003 assertEqual(arr.length, index, `index ${index} expected to be at the end of arr (length ${arr.length})`);
2004}
2005function assertLContainer(value) {
2006 assertDefined(value, 'LContainer must be defined');
2007 assertEqual(isLContainer(value), true, 'Expecting LContainer');
2008}
2009function assertLViewOrUndefined(value) {
2010 value && assertEqual(isLView(value), true, 'Expecting LView or undefined or null');
2011}
2012function assertLView(value) {
2013 assertDefined(value, 'LView must be defined');
2014 assertEqual(isLView(value), true, 'Expecting LView');
2015}
2016function assertFirstCreatePass(tView, errMessage) {
2017 assertEqual(tView.firstCreatePass, true, errMessage || 'Should only be called in first create pass.');
2018}
2019function assertFirstUpdatePass(tView, errMessage) {
2020 assertEqual(tView.firstUpdatePass, true, errMessage || 'Should only be called in first update pass.');
2021}
2022/**
2023 * This is a basic sanity check that an object is probably a directive def. DirectiveDef is
2024 * an interface, so we can't do a direct instanceof check.
2025 */
2026function assertDirectiveDef(obj) {
2027 if (obj.type === undefined || obj.selectors == undefined || obj.inputs === undefined) {
2028 throwError(`Expected a DirectiveDef/ComponentDef and this object does not seem to have the expected shape.`);
2029 }
2030}
2031
2032/**
2033 * @license
2034 * Copyright Google LLC All Rights Reserved.
2035 *
2036 * Use of this source code is governed by an MIT-style license that can be
2037 * found in the LICENSE file at https://angular.io/license
2038 */
2039/**
2040 * Represents a basic change from a previous to a new value for a single
2041 * property on a directive instance. Passed as a value in a
2042 * {@link SimpleChanges} object to the `ngOnChanges` hook.
2043 *
2044 * @see `OnChanges`
2045 *
2046 * @publicApi
2047 */
2048class SimpleChange {
2049 constructor(previousValue, currentValue, firstChange) {
2050 this.previousValue = previousValue;
2051 this.currentValue = currentValue;
2052 this.firstChange = firstChange;
2053 }
2054 /**
2055 * Check whether the new value is the first value assigned.
2056 */
2057 isFirstChange() {
2058 return this.firstChange;
2059 }
2060}
2061
2062/**
2063 * @license
2064 * Copyright Google LLC All Rights Reserved.
2065 *
2066 * Use of this source code is governed by an MIT-style license that can be
2067 * found in the LICENSE file at https://angular.io/license
2068 */
2069/**
2070 * The NgOnChangesFeature decorates a component with support for the ngOnChanges
2071 * lifecycle hook, so it should be included in any component that implements
2072 * that hook.
2073 *
2074 * If the component or directive uses inheritance, the NgOnChangesFeature MUST
2075 * be included as a feature AFTER {@link InheritDefinitionFeature}, otherwise
2076 * inherited properties will not be propagated to the ngOnChanges lifecycle
2077 * hook.
2078 *
2079 * Example usage:
2080 *
2081 * ```
2082 * static ɵcmp = defineComponent({
2083 * ...
2084 * inputs: {name: 'publicName'},
2085 * features: [NgOnChangesFeature]
2086 * });
2087 * ```
2088 *
2089 * @codeGenApi
2090 */
2091function ɵɵNgOnChangesFeature() {
2092 return NgOnChangesFeatureImpl;
2093}
2094function NgOnChangesFeatureImpl(definition) {
2095 if (definition.type.prototype.ngOnChanges) {
2096 definition.setInput = ngOnChangesSetInput;
2097 }
2098 return rememberChangeHistoryAndInvokeOnChangesHook;
2099}
2100// This option ensures that the ngOnChanges lifecycle hook will be inherited
2101// from superclasses (in InheritDefinitionFeature).
2102/** @nocollapse */
2103// tslint:disable-next-line:no-toplevel-property-access
2104ɵɵNgOnChangesFeature.ngInherit = true;
2105/**
2106 * This is a synthetic lifecycle hook which gets inserted into `TView.preOrderHooks` to simulate
2107 * `ngOnChanges`.
2108 *
2109 * The hook reads the `NgSimpleChangesStore` data from the component instance and if changes are
2110 * found it invokes `ngOnChanges` on the component instance.
2111 *
2112 * @param this Component instance. Because this function gets inserted into `TView.preOrderHooks`,
2113 * it is guaranteed to be called with component instance.
2114 */
2115function rememberChangeHistoryAndInvokeOnChangesHook() {
2116 const simpleChangesStore = getSimpleChangesStore(this);
2117 const current = simpleChangesStore === null || simpleChangesStore === void 0 ? void 0 : simpleChangesStore.current;
2118 if (current) {
2119 const previous = simpleChangesStore.previous;
2120 if (previous === EMPTY_OBJ) {
2121 simpleChangesStore.previous = current;
2122 }
2123 else {
2124 // New changes are copied to the previous store, so that we don't lose history for inputs
2125 // which were not changed this time
2126 for (let key in current) {
2127 previous[key] = current[key];
2128 }
2129 }
2130 simpleChangesStore.current = null;
2131 this.ngOnChanges(current);
2132 }
2133}
2134function ngOnChangesSetInput(instance, value, publicName, privateName) {
2135 const simpleChangesStore = getSimpleChangesStore(instance) ||
2136 setSimpleChangesStore(instance, { previous: EMPTY_OBJ, current: null });
2137 const current = simpleChangesStore.current || (simpleChangesStore.current = {});
2138 const previous = simpleChangesStore.previous;
2139 const declaredName = this.declaredInputs[publicName];
2140 const previousChange = previous[declaredName];
2141 current[declaredName] = new SimpleChange(previousChange && previousChange.currentValue, value, previous === EMPTY_OBJ);
2142 instance[privateName] = value;
2143}
2144const SIMPLE_CHANGES_STORE = '__ngSimpleChanges__';
2145function getSimpleChangesStore(instance) {
2146 return instance[SIMPLE_CHANGES_STORE] || null;
2147}
2148function setSimpleChangesStore(instance, store) {
2149 return instance[SIMPLE_CHANGES_STORE] = store;
2150}
2151
2152/**
2153 * @license
2154 * Copyright Google LLC All Rights Reserved.
2155 *
2156 * Use of this source code is governed by an MIT-style license that can be
2157 * found in the LICENSE file at https://angular.io/license
2158 */
2159const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
2160const MATH_ML_NAMESPACE = 'http://www.w3.org/1998/MathML/';
2161
2162/**
2163 * @license
2164 * Copyright Google LLC All Rights Reserved.
2165 *
2166 * Use of this source code is governed by an MIT-style license that can be
2167 * found in the LICENSE file at https://angular.io/license
2168 */
2169/**
2170 * This property will be monkey-patched on elements, components and directives
2171 */
2172const MONKEY_PATCH_KEY_NAME = '__ngContext__';
2173
2174/**
2175 * @license
2176 * Copyright Google LLC All Rights Reserved.
2177 *
2178 * Use of this source code is governed by an MIT-style license that can be
2179 * found in the LICENSE file at https://angular.io/license
2180 */
2181/**
2182 * Most of the use of `document` in Angular is from within the DI system so it is possible to simply
2183 * inject the `DOCUMENT` token and are done.
2184 *
2185 * Ivy is special because it does not rely upon the DI and must get hold of the document some other
2186 * way.
2187 *
2188 * The solution is to define `getDocument()` and `setDocument()` top-level functions for ivy.
2189 * Wherever ivy needs the global document, it calls `getDocument()` instead.
2190 *
2191 * When running ivy outside of a browser environment, it is necessary to call `setDocument()` to
2192 * tell ivy what the global `document` is.
2193 *
2194 * Angular does this for us in each of the standard platforms (`Browser`, `Server`, and `WebWorker`)
2195 * by calling `setDocument()` when providing the `DOCUMENT` token.
2196 */
2197let DOCUMENT = undefined;
2198/**
2199 * Tell ivy what the `document` is for this platform.
2200 *
2201 * It is only necessary to call this if the current platform is not a browser.
2202 *
2203 * @param document The object representing the global `document` in this environment.
2204 */
2205function setDocument(document) {
2206 DOCUMENT = document;
2207}
2208/**
2209 * Access the object that represents the `document` for this platform.
2210 *
2211 * Ivy calls this whenever it needs to access the `document` object.
2212 * For example to create the renderer or to do sanitization.
2213 */
2214function getDocument() {
2215 if (DOCUMENT !== undefined) {
2216 return DOCUMENT;
2217 }
2218 else if (typeof document !== 'undefined') {
2219 return document;
2220 }
2221 // No "document" can be found. This should only happen if we are running ivy outside Angular and
2222 // the current platform is not a browser. Since this is not a supported scenario at the moment
2223 // this should not happen in Angular apps.
2224 // Once we support running ivy outside of Angular we will need to publish `setDocument()` as a
2225 // public API. Meanwhile we just return `undefined` and let the application fail.
2226 return undefined;
2227}
2228
2229/**
2230 * @license
2231 * Copyright Google LLC All Rights Reserved.
2232 *
2233 * Use of this source code is governed by an MIT-style license that can be
2234 * found in the LICENSE file at https://angular.io/license
2235 */
2236// TODO: cleanup once the code is merged in angular/angular
2237var RendererStyleFlags3;
2238(function (RendererStyleFlags3) {
2239 RendererStyleFlags3[RendererStyleFlags3["Important"] = 1] = "Important";
2240 RendererStyleFlags3[RendererStyleFlags3["DashCase"] = 2] = "DashCase";
2241})(RendererStyleFlags3 || (RendererStyleFlags3 = {}));
2242/** Returns whether the `renderer` is a `ProceduralRenderer3` */
2243function isProceduralRenderer(renderer) {
2244 return !!(renderer.listen);
2245}
2246const ɵ0$2 = (hostElement, rendererType) => {
2247 return getDocument();
2248};
2249const domRendererFactory3 = {
2250 createRenderer: ɵ0$2
2251};
2252// Note: This hack is necessary so we don't erroneously get a circular dependency
2253// failure based on types.
2254const unusedValueExportToPlacateAjd$2 = 1;
2255
2256/**
2257 * @license
2258 * Copyright Google LLC All Rights Reserved.
2259 *
2260 * Use of this source code is governed by an MIT-style license that can be
2261 * found in the LICENSE file at https://angular.io/license
2262 */
2263/**
2264 * For efficiency reasons we often put several different data types (`RNode`, `LView`, `LContainer`)
2265 * in same location in `LView`. This is because we don't want to pre-allocate space for it
2266 * because the storage is sparse. This file contains utilities for dealing with such data types.
2267 *
2268 * How do we know what is stored at a given location in `LView`.
2269 * - `Array.isArray(value) === false` => `RNode` (The normal storage value)
2270 * - `Array.isArray(value) === true` => then the `value[0]` represents the wrapped value.
2271 * - `typeof value[TYPE] === 'object'` => `LView`
2272 * - This happens when we have a component at a given location
2273 * - `typeof value[TYPE] === true` => `LContainer`
2274 * - This happens when we have `LContainer` binding at a given location.
2275 *
2276 *
2277 * NOTE: it is assumed that `Array.isArray` and `typeof` operations are very efficient.
2278 */
2279/**
2280 * Returns `RNode`.
2281 * @param value wrapped value of `RNode`, `LView`, `LContainer`
2282 */
2283function unwrapRNode(value) {
2284 while (Array.isArray(value)) {
2285 value = value[HOST];
2286 }
2287 return value;
2288}
2289/**
2290 * Returns `LView` or `null` if not found.
2291 * @param value wrapped value of `RNode`, `LView`, `LContainer`
2292 */
2293function unwrapLView(value) {
2294 while (Array.isArray(value)) {
2295 // This check is same as `isLView()` but we don't call at as we don't want to call
2296 // `Array.isArray()` twice and give JITer more work for inlining.
2297 if (typeof value[TYPE] === 'object')
2298 return value;
2299 value = value[HOST];
2300 }
2301 return null;
2302}
2303/**
2304 * Returns `LContainer` or `null` if not found.
2305 * @param value wrapped value of `RNode`, `LView`, `LContainer`
2306 */
2307function unwrapLContainer(value) {
2308 while (Array.isArray(value)) {
2309 // This check is same as `isLContainer()` but we don't call at as we don't want to call
2310 // `Array.isArray()` twice and give JITer more work for inlining.
2311 if (value[TYPE] === true)
2312 return value;
2313 value = value[HOST];
2314 }
2315 return null;
2316}
2317/**
2318 * Retrieves an element value from the provided `viewData`, by unwrapping
2319 * from any containers, component views, or style contexts.
2320 */
2321function getNativeByIndex(index, lView) {
2322 return unwrapRNode(lView[index + HEADER_OFFSET]);
2323}
2324/**
2325 * Retrieve an `RNode` for a given `TNode` and `LView`.
2326 *
2327 * This function guarantees in dev mode to retrieve a non-null `RNode`.
2328 *
2329 * @param tNode
2330 * @param lView
2331 */
2332function getNativeByTNode(tNode, lView) {
2333 ngDevMode && assertTNodeForLView(tNode, lView);
2334 ngDevMode && assertIndexInRange(lView, tNode.index);
2335 const node = unwrapRNode(lView[tNode.index]);
2336 ngDevMode && !isProceduralRenderer(lView[RENDERER]) && assertDomNode(node);
2337 return node;
2338}
2339/**
2340 * Retrieve an `RNode` or `null` for a given `TNode` and `LView`.
2341 *
2342 * Some `TNode`s don't have associated `RNode`s. For example `Projection`
2343 *
2344 * @param tNode
2345 * @param lView
2346 */
2347function getNativeByTNodeOrNull(tNode, lView) {
2348 const index = tNode.index;
2349 if (index !== -1) {
2350 ngDevMode && assertTNodeForLView(tNode, lView);
2351 const node = unwrapRNode(lView[index]);
2352 ngDevMode && node !== null && !isProceduralRenderer(lView[RENDERER]) && assertDomNode(node);
2353 return node;
2354 }
2355 return null;
2356}
2357function getTNode(tView, index) {
2358 ngDevMode && assertGreaterThan(index, -1, 'wrong index for TNode');
2359 ngDevMode && assertLessThan(index, tView.data.length, 'wrong index for TNode');
2360 return tView.data[index + HEADER_OFFSET];
2361}
2362/** Retrieves a value from any `LView` or `TData`. */
2363function load(view, index) {
2364 ngDevMode && assertIndexInRange(view, index + HEADER_OFFSET);
2365 return view[index + HEADER_OFFSET];
2366}
2367function getComponentLViewByIndex(nodeIndex, hostView) {
2368 // Could be an LView or an LContainer. If LContainer, unwrap to find LView.
2369 ngDevMode && assertIndexInRange(hostView, nodeIndex);
2370 const slotValue = hostView[nodeIndex];
2371 const lView = isLView(slotValue) ? slotValue : slotValue[HOST];
2372 return lView;
2373}
2374/**
2375 * Returns the monkey-patch value data present on the target (which could be
2376 * a component, directive or a DOM node).
2377 */
2378function readPatchedData(target) {
2379 ngDevMode && assertDefined(target, 'Target expected');
2380 return target[MONKEY_PATCH_KEY_NAME] || null;
2381}
2382function readPatchedLView(target) {
2383 const value = readPatchedData(target);
2384 if (value) {
2385 return Array.isArray(value) ? value : value.lView;
2386 }
2387 return null;
2388}
2389/** Checks whether a given view is in creation mode */
2390function isCreationMode(view) {
2391 return (view[FLAGS] & 4 /* CreationMode */) === 4 /* CreationMode */;
2392}
2393/**
2394 * Returns a boolean for whether the view is attached to the change detection tree.
2395 *
2396 * Note: This determines whether a view should be checked, not whether it's inserted
2397 * into a container. For that, you'll want `viewAttachedToContainer` below.
2398 */
2399function viewAttachedToChangeDetector(view) {
2400 return (view[FLAGS] & 128 /* Attached */) === 128 /* Attached */;
2401}
2402/** Returns a boolean for whether the view is attached to a container. */
2403function viewAttachedToContainer(view) {
2404 return isLContainer(view[PARENT]);
2405}
2406/** Returns a constant from `TConstants` instance. */
2407function getConstant(consts, index) {
2408 return consts === null || index == null ? null : consts[index];
2409}
2410/**
2411 * Resets the pre-order hook flags of the view.
2412 * @param lView the LView on which the flags are reset
2413 */
2414function resetPreOrderHookFlags(lView) {
2415 lView[PREORDER_HOOK_FLAGS] = 0;
2416}
2417/**
2418 * Updates the `TRANSPLANTED_VIEWS_TO_REFRESH` counter on the `LContainer` as well as the parents
2419 * whose
2420 * 1. counter goes from 0 to 1, indicating that there is a new child that has a view to refresh
2421 * or
2422 * 2. counter goes from 1 to 0, indicating there are no more descendant views to refresh
2423 */
2424function updateTransplantedViewCount(lContainer, amount) {
2425 lContainer[TRANSPLANTED_VIEWS_TO_REFRESH] += amount;
2426 let viewOrContainer = lContainer;
2427 let parent = lContainer[PARENT];
2428 while (parent !== null &&
2429 ((amount === 1 && viewOrContainer[TRANSPLANTED_VIEWS_TO_REFRESH] === 1) ||
2430 (amount === -1 && viewOrContainer[TRANSPLANTED_VIEWS_TO_REFRESH] === 0))) {
2431 parent[TRANSPLANTED_VIEWS_TO_REFRESH] += amount;
2432 viewOrContainer = parent;
2433 parent = parent[PARENT];
2434 }
2435}
2436
2437/**
2438 * @license
2439 * Copyright Google LLC All Rights Reserved.
2440 *
2441 * Use of this source code is governed by an MIT-style license that can be
2442 * found in the LICENSE file at https://angular.io/license
2443 */
2444const instructionState = {
2445 lFrame: createLFrame(null),
2446 bindingsEnabled: true,
2447 checkNoChangesMode: false,
2448};
2449function getElementDepthCount() {
2450 return instructionState.lFrame.elementDepthCount;
2451}
2452function increaseElementDepthCount() {
2453 instructionState.lFrame.elementDepthCount++;
2454}
2455function decreaseElementDepthCount() {
2456 instructionState.lFrame.elementDepthCount--;
2457}
2458function getBindingsEnabled() {
2459 return instructionState.bindingsEnabled;
2460}
2461/**
2462 * Enables directive matching on elements.
2463 *
2464 * * Example:
2465 * ```
2466 * <my-comp my-directive>
2467 * Should match component / directive.
2468 * </my-comp>
2469 * <div ngNonBindable>
2470 * <!-- ɵɵdisableBindings() -->
2471 * <my-comp my-directive>
2472 * Should not match component / directive because we are in ngNonBindable.
2473 * </my-comp>
2474 * <!-- ɵɵenableBindings() -->
2475 * </div>
2476 * ```
2477 *
2478 * @codeGenApi
2479 */
2480function ɵɵenableBindings() {
2481 instructionState.bindingsEnabled = true;
2482}
2483/**
2484 * Disables directive matching on element.
2485 *
2486 * * Example:
2487 * ```
2488 * <my-comp my-directive>
2489 * Should match component / directive.
2490 * </my-comp>
2491 * <div ngNonBindable>
2492 * <!-- ɵɵdisableBindings() -->
2493 * <my-comp my-directive>
2494 * Should not match component / directive because we are in ngNonBindable.
2495 * </my-comp>
2496 * <!-- ɵɵenableBindings() -->
2497 * </div>
2498 * ```
2499 *
2500 * @codeGenApi
2501 */
2502function ɵɵdisableBindings() {
2503 instructionState.bindingsEnabled = false;
2504}
2505/**
2506 * Return the current `LView`.
2507 */
2508function getLView() {
2509 return instructionState.lFrame.lView;
2510}
2511/**
2512 * Return the current `TView`.
2513 */
2514function getTView() {
2515 return instructionState.lFrame.tView;
2516}
2517/**
2518 * Restores `contextViewData` to the given OpaqueViewState instance.
2519 *
2520 * Used in conjunction with the getCurrentView() instruction to save a snapshot
2521 * of the current view and restore it when listeners are invoked. This allows
2522 * walking the declaration view tree in listeners to get vars from parent views.
2523 *
2524 * @param viewToRestore The OpaqueViewState instance to restore.
2525 *
2526 * @codeGenApi
2527 */
2528function ɵɵrestoreView(viewToRestore) {
2529 instructionState.lFrame.contextLView = viewToRestore;
2530}
2531function getPreviousOrParentTNode() {
2532 return instructionState.lFrame.previousOrParentTNode;
2533}
2534function setPreviousOrParentTNode(tNode, isParent) {
2535 instructionState.lFrame.previousOrParentTNode = tNode;
2536 instructionState.lFrame.isParent = isParent;
2537}
2538function getIsParent() {
2539 return instructionState.lFrame.isParent;
2540}
2541function setIsNotParent() {
2542 instructionState.lFrame.isParent = false;
2543}
2544function setIsParent() {
2545 instructionState.lFrame.isParent = true;
2546}
2547function getContextLView() {
2548 return instructionState.lFrame.contextLView;
2549}
2550function getCheckNoChangesMode() {
2551 // TODO(misko): remove this from the LView since it is ngDevMode=true mode only.
2552 return instructionState.checkNoChangesMode;
2553}
2554function setCheckNoChangesMode(mode) {
2555 instructionState.checkNoChangesMode = mode;
2556}
2557// top level variables should not be exported for performance reasons (PERF_NOTES.md)
2558function getBindingRoot() {
2559 const lFrame = instructionState.lFrame;
2560 let index = lFrame.bindingRootIndex;
2561 if (index === -1) {
2562 index = lFrame.bindingRootIndex = lFrame.tView.bindingStartIndex;
2563 }
2564 return index;
2565}
2566function getBindingIndex() {
2567 return instructionState.lFrame.bindingIndex;
2568}
2569function setBindingIndex(value) {
2570 return instructionState.lFrame.bindingIndex = value;
2571}
2572function nextBindingIndex() {
2573 return instructionState.lFrame.bindingIndex++;
2574}
2575function incrementBindingIndex(count) {
2576 const lFrame = instructionState.lFrame;
2577 const index = lFrame.bindingIndex;
2578 lFrame.bindingIndex = lFrame.bindingIndex + count;
2579 return index;
2580}
2581/**
2582 * Set a new binding root index so that host template functions can execute.
2583 *
2584 * Bindings inside the host template are 0 index. But because we don't know ahead of time
2585 * how many host bindings we have we can't pre-compute them. For this reason they are all
2586 * 0 index and we just shift the root so that they match next available location in the LView.
2587 *
2588 * @param bindingRootIndex Root index for `hostBindings`
2589 * @param currentDirectiveIndex `TData[currentDirectiveIndex]` will point to the current directive
2590 * whose `hostBindings` are being processed.
2591 */
2592function setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex) {
2593 const lFrame = instructionState.lFrame;
2594 lFrame.bindingIndex = lFrame.bindingRootIndex = bindingRootIndex;
2595 setCurrentDirectiveIndex(currentDirectiveIndex);
2596}
2597/**
2598 * When host binding is executing this points to the directive index.
2599 * `TView.data[getCurrentDirectiveIndex()]` is `DirectiveDef`
2600 * `LView[getCurrentDirectiveIndex()]` is directive instance.
2601 */
2602function getCurrentDirectiveIndex() {
2603 return instructionState.lFrame.currentDirectiveIndex;
2604}
2605/**
2606 * Sets an index of a directive whose `hostBindings` are being processed.
2607 *
2608 * @param currentDirectiveIndex `TData` index where current directive instance can be found.
2609 */
2610function setCurrentDirectiveIndex(currentDirectiveIndex) {
2611 instructionState.lFrame.currentDirectiveIndex = currentDirectiveIndex;
2612}
2613/**
2614 * Retrieve the current `DirectiveDef` which is active when `hostBindings` instruction is being
2615 * executed.
2616 *
2617 * @param tData Current `TData` where the `DirectiveDef` will be looked up at.
2618 */
2619function getCurrentDirectiveDef(tData) {
2620 const currentDirectiveIndex = instructionState.lFrame.currentDirectiveIndex;
2621 return currentDirectiveIndex === -1 ? null : tData[currentDirectiveIndex];
2622}
2623function getCurrentQueryIndex() {
2624 return instructionState.lFrame.currentQueryIndex;
2625}
2626function setCurrentQueryIndex(value) {
2627 instructionState.lFrame.currentQueryIndex = value;
2628}
2629/**
2630 * This is a light weight version of the `enterView` which is needed by the DI system.
2631 * @param newView
2632 * @param tNode
2633 */
2634function enterDI(newView, tNode) {
2635 ngDevMode && assertLViewOrUndefined(newView);
2636 const newLFrame = allocLFrame();
2637 instructionState.lFrame = newLFrame;
2638 newLFrame.previousOrParentTNode = tNode;
2639 newLFrame.lView = newView;
2640}
2641/**
2642 * Swap the current lView with a new lView.
2643 *
2644 * For performance reasons we store the lView in the top level of the module.
2645 * This way we minimize the number of properties to read. Whenever a new view
2646 * is entered we have to store the lView for later, and when the view is
2647 * exited the state has to be restored
2648 *
2649 * @param newView New lView to become active
2650 * @param tNode Element to which the View is a child of
2651 * @returns the previously active lView;
2652 */
2653function enterView(newView, tNode) {
2654 ngDevMode && assertLViewOrUndefined(newView);
2655 const newLFrame = allocLFrame();
2656 if (ngDevMode) {
2657 assertEqual(newLFrame.isParent, true, 'Expected clean LFrame');
2658 assertEqual(newLFrame.lView, null, 'Expected clean LFrame');
2659 assertEqual(newLFrame.tView, null, 'Expected clean LFrame');
2660 assertEqual(newLFrame.selectedIndex, 0, 'Expected clean LFrame');
2661 assertEqual(newLFrame.elementDepthCount, 0, 'Expected clean LFrame');
2662 assertEqual(newLFrame.currentDirectiveIndex, -1, 'Expected clean LFrame');
2663 assertEqual(newLFrame.currentNamespace, null, 'Expected clean LFrame');
2664 assertEqual(newLFrame.bindingRootIndex, -1, 'Expected clean LFrame');
2665 assertEqual(newLFrame.currentQueryIndex, 0, 'Expected clean LFrame');
2666 }
2667 const tView = newView[TVIEW];
2668 instructionState.lFrame = newLFrame;
2669 newLFrame.previousOrParentTNode = tNode;
2670 newLFrame.lView = newView;
2671 newLFrame.tView = tView;
2672 newLFrame.contextLView = newView;
2673 newLFrame.bindingIndex = tView.bindingStartIndex;
2674}
2675/**
2676 * Allocates next free LFrame. This function tries to reuse the `LFrame`s to lower memory pressure.
2677 */
2678function allocLFrame() {
2679 const currentLFrame = instructionState.lFrame;
2680 const childLFrame = currentLFrame === null ? null : currentLFrame.child;
2681 const newLFrame = childLFrame === null ? createLFrame(currentLFrame) : childLFrame;
2682 return newLFrame;
2683}
2684function createLFrame(parent) {
2685 const lFrame = {
2686 previousOrParentTNode: null,
2687 isParent: true,
2688 lView: null,
2689 tView: null,
2690 selectedIndex: 0,
2691 contextLView: null,
2692 elementDepthCount: 0,
2693 currentNamespace: null,
2694 currentDirectiveIndex: -1,
2695 bindingRootIndex: -1,
2696 bindingIndex: -1,
2697 currentQueryIndex: 0,
2698 parent: parent,
2699 child: null,
2700 };
2701 parent !== null && (parent.child = lFrame); // link the new LFrame for reuse.
2702 return lFrame;
2703}
2704/**
2705 * A lightweight version of leave which is used with DI.
2706 *
2707 * This function only resets `previousOrParentTNode` and `LView` as those are the only properties
2708 * used with DI (`enterDI()`).
2709 *
2710 * NOTE: This function is reexported as `leaveDI`. However `leaveDI` has return type of `void` where
2711 * as `leaveViewLight` has `LFrame`. This is so that `leaveViewLight` can be used in `leaveView`.
2712 */
2713function leaveViewLight() {
2714 const oldLFrame = instructionState.lFrame;
2715 instructionState.lFrame = oldLFrame.parent;
2716 oldLFrame.previousOrParentTNode = null;
2717 oldLFrame.lView = null;
2718 return oldLFrame;
2719}
2720/**
2721 * This is a lightweight version of the `leaveView` which is needed by the DI system.
2722 *
2723 * NOTE: this function is an alias so that we can change the type of the function to have `void`
2724 * return type.
2725 */
2726const leaveDI = leaveViewLight;
2727/**
2728 * Leave the current `LView`
2729 *
2730 * This pops the `LFrame` with the associated `LView` from the stack.
2731 *
2732 * IMPORTANT: We must zero out the `LFrame` values here otherwise they will be retained. This is
2733 * because for performance reasons we don't release `LFrame` but rather keep it for next use.
2734 */
2735function leaveView() {
2736 const oldLFrame = leaveViewLight();
2737 oldLFrame.isParent = true;
2738 oldLFrame.tView = null;
2739 oldLFrame.selectedIndex = 0;
2740 oldLFrame.contextLView = null;
2741 oldLFrame.elementDepthCount = 0;
2742 oldLFrame.currentDirectiveIndex = -1;
2743 oldLFrame.currentNamespace = null;
2744 oldLFrame.bindingRootIndex = -1;
2745 oldLFrame.bindingIndex = -1;
2746 oldLFrame.currentQueryIndex = 0;
2747}
2748function nextContextImpl(level) {
2749 const contextLView = instructionState.lFrame.contextLView =
2750 walkUpViews(level, instructionState.lFrame.contextLView);
2751 return contextLView[CONTEXT];
2752}
2753function walkUpViews(nestingLevel, currentView) {
2754 while (nestingLevel > 0) {
2755 ngDevMode &&
2756 assertDefined(currentView[DECLARATION_VIEW], 'Declaration view should be defined if nesting level is greater than 0.');
2757 currentView = currentView[DECLARATION_VIEW];
2758 nestingLevel--;
2759 }
2760 return currentView;
2761}
2762/**
2763 * Gets the currently selected element index.
2764 *
2765 * Used with {@link property} instruction (and more in the future) to identify the index in the
2766 * current `LView` to act on.
2767 */
2768function getSelectedIndex() {
2769 return instructionState.lFrame.selectedIndex;
2770}
2771/**
2772 * Sets the most recent index passed to {@link select}
2773 *
2774 * Used with {@link property} instruction (and more in the future) to identify the index in the
2775 * current `LView` to act on.
2776 *
2777 * (Note that if an "exit function" was set earlier (via `setElementExitFn()`) then that will be
2778 * run if and when the provided `index` value is different from the current selected index value.)
2779 */
2780function setSelectedIndex(index) {
2781 instructionState.lFrame.selectedIndex = index;
2782}
2783/**
2784 * Gets the `tNode` that represents currently selected element.
2785 */
2786function getSelectedTNode() {
2787 const lFrame = instructionState.lFrame;
2788 return getTNode(lFrame.tView, lFrame.selectedIndex);
2789}
2790/**
2791 * Sets the namespace used to create elements to `'http://www.w3.org/2000/svg'` in global state.
2792 *
2793 * @codeGenApi
2794 */
2795function ɵɵnamespaceSVG() {
2796 instructionState.lFrame.currentNamespace = SVG_NAMESPACE;
2797}
2798/**
2799 * Sets the namespace used to create elements to `'http://www.w3.org/1998/MathML/'` in global state.
2800 *
2801 * @codeGenApi
2802 */
2803function ɵɵnamespaceMathML() {
2804 instructionState.lFrame.currentNamespace = MATH_ML_NAMESPACE;
2805}
2806/**
2807 * Sets the namespace used to create elements to `null`, which forces element creation to use
2808 * `createElement` rather than `createElementNS`.
2809 *
2810 * @codeGenApi
2811 */
2812function ɵɵnamespaceHTML() {
2813 namespaceHTMLInternal();
2814}
2815/**
2816 * Sets the namespace used to create elements to `null`, which forces element creation to use
2817 * `createElement` rather than `createElementNS`.
2818 */
2819function namespaceHTMLInternal() {
2820 instructionState.lFrame.currentNamespace = null;
2821}
2822function getNamespace() {
2823 return instructionState.lFrame.currentNamespace;
2824}
2825
2826/**
2827 * @license
2828 * Copyright Google LLC All Rights Reserved.
2829 *
2830 * Use of this source code is governed by an MIT-style license that can be
2831 * found in the LICENSE file at https://angular.io/license
2832 */
2833/**
2834 * Adds all directive lifecycle hooks from the given `DirectiveDef` to the given `TView`.
2835 *
2836 * Must be run *only* on the first template pass.
2837 *
2838 * Sets up the pre-order hooks on the provided `tView`,
2839 * see {@link HookData} for details about the data structure.
2840 *
2841 * @param directiveIndex The index of the directive in LView
2842 * @param directiveDef The definition containing the hooks to setup in tView
2843 * @param tView The current TView
2844 */
2845function registerPreOrderHooks(directiveIndex, directiveDef, tView) {
2846 ngDevMode && assertFirstCreatePass(tView);
2847 const { ngOnChanges, ngOnInit, ngDoCheck } = directiveDef.type.prototype;
2848 if (ngOnChanges) {
2849 const wrappedOnChanges = NgOnChangesFeatureImpl(directiveDef);
2850 (tView.preOrderHooks || (tView.preOrderHooks = [])).push(directiveIndex, wrappedOnChanges);
2851 (tView.preOrderCheckHooks || (tView.preOrderCheckHooks = []))
2852 .push(directiveIndex, wrappedOnChanges);
2853 }
2854 if (ngOnInit) {
2855 (tView.preOrderHooks || (tView.preOrderHooks = [])).push(0 - directiveIndex, ngOnInit);
2856 }
2857 if (ngDoCheck) {
2858 (tView.preOrderHooks || (tView.preOrderHooks = [])).push(directiveIndex, ngDoCheck);
2859 (tView.preOrderCheckHooks || (tView.preOrderCheckHooks = [])).push(directiveIndex, ngDoCheck);
2860 }
2861}
2862/**
2863 *
2864 * Loops through the directives on the provided `tNode` and queues hooks to be
2865 * run that are not initialization hooks.
2866 *
2867 * Should be executed during `elementEnd()` and similar to
2868 * preserve hook execution order. Content, view, and destroy hooks for projected
2869 * components and directives must be called *before* their hosts.
2870 *
2871 * Sets up the content, view, and destroy hooks on the provided `tView`,
2872 * see {@link HookData} for details about the data structure.
2873 *
2874 * NOTE: This does not set up `onChanges`, `onInit` or `doCheck`, those are set up
2875 * separately at `elementStart`.
2876 *
2877 * @param tView The current TView
2878 * @param tNode The TNode whose directives are to be searched for hooks to queue
2879 */
2880function registerPostOrderHooks(tView, tNode) {
2881 ngDevMode && assertFirstCreatePass(tView);
2882 // It's necessary to loop through the directives at elementEnd() (rather than processing in
2883 // directiveCreate) so we can preserve the current hook order. Content, view, and destroy
2884 // hooks for projected components and directives must be called *before* their hosts.
2885 for (let i = tNode.directiveStart, end = tNode.directiveEnd; i < end; i++) {
2886 const directiveDef = tView.data[i];
2887 const lifecycleHooks = directiveDef.type.prototype;
2888 const { ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked, ngOnDestroy } = lifecycleHooks;
2889 if (ngAfterContentInit) {
2890 (tView.contentHooks || (tView.contentHooks = [])).push(-i, ngAfterContentInit);
2891 }
2892 if (ngAfterContentChecked) {
2893 (tView.contentHooks || (tView.contentHooks = [])).push(i, ngAfterContentChecked);
2894 (tView.contentCheckHooks || (tView.contentCheckHooks = [])).push(i, ngAfterContentChecked);
2895 }
2896 if (ngAfterViewInit) {
2897 (tView.viewHooks || (tView.viewHooks = [])).push(-i, ngAfterViewInit);
2898 }
2899 if (ngAfterViewChecked) {
2900 (tView.viewHooks || (tView.viewHooks = [])).push(i, ngAfterViewChecked);
2901 (tView.viewCheckHooks || (tView.viewCheckHooks = [])).push(i, ngAfterViewChecked);
2902 }
2903 if (ngOnDestroy != null) {
2904 (tView.destroyHooks || (tView.destroyHooks = [])).push(i, ngOnDestroy);
2905 }
2906 }
2907}
2908/**
2909 * Executing hooks requires complex logic as we need to deal with 2 constraints.
2910 *
2911 * 1. Init hooks (ngOnInit, ngAfterContentInit, ngAfterViewInit) must all be executed once and only
2912 * once, across many change detection cycles. This must be true even if some hooks throw, or if
2913 * some recursively trigger a change detection cycle.
2914 * To solve that, it is required to track the state of the execution of these init hooks.
2915 * This is done by storing and maintaining flags in the view: the {@link InitPhaseState},
2916 * and the index within that phase. They can be seen as a cursor in the following structure:
2917 * [[onInit1, onInit2], [afterContentInit1], [afterViewInit1, afterViewInit2, afterViewInit3]]
2918 * They are are stored as flags in LView[FLAGS].
2919 *
2920 * 2. Pre-order hooks can be executed in batches, because of the select instruction.
2921 * To be able to pause and resume their execution, we also need some state about the hook's array
2922 * that is being processed:
2923 * - the index of the next hook to be executed
2924 * - the number of init hooks already found in the processed part of the array
2925 * They are are stored as flags in LView[PREORDER_HOOK_FLAGS].
2926 */
2927/**
2928 * Executes pre-order check hooks ( OnChanges, DoChanges) given a view where all the init hooks were
2929 * executed once. This is a light version of executeInitAndCheckPreOrderHooks where we can skip read
2930 * / write of the init-hooks related flags.
2931 * @param lView The LView where hooks are defined
2932 * @param hooks Hooks to be run
2933 * @param nodeIndex 3 cases depending on the value:
2934 * - undefined: all hooks from the array should be executed (post-order case)
2935 * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
2936 * flushing the remaining hooks)
2937 * - number: execute hooks only from the saved index until that node index exclusive (pre-order
2938 * case, when executing select(number))
2939 */
2940function executeCheckHooks(lView, hooks, nodeIndex) {
2941 callHooks(lView, hooks, 3 /* InitPhaseCompleted */, nodeIndex);
2942}
2943/**
2944 * Executes post-order init and check hooks (one of AfterContentInit, AfterContentChecked,
2945 * AfterViewInit, AfterViewChecked) given a view where there are pending init hooks to be executed.
2946 * @param lView The LView where hooks are defined
2947 * @param hooks Hooks to be run
2948 * @param initPhase A phase for which hooks should be run
2949 * @param nodeIndex 3 cases depending on the value:
2950 * - undefined: all hooks from the array should be executed (post-order case)
2951 * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
2952 * flushing the remaining hooks)
2953 * - number: execute hooks only from the saved index until that node index exclusive (pre-order
2954 * case, when executing select(number))
2955 */
2956function executeInitAndCheckHooks(lView, hooks, initPhase, nodeIndex) {
2957 ngDevMode &&
2958 assertNotEqual(initPhase, 3 /* InitPhaseCompleted */, 'Init pre-order hooks should not be called more than once');
2959 if ((lView[FLAGS] & 3 /* InitPhaseStateMask */) === initPhase) {
2960 callHooks(lView, hooks, initPhase, nodeIndex);
2961 }
2962}
2963function incrementInitPhaseFlags(lView, initPhase) {
2964 ngDevMode &&
2965 assertNotEqual(initPhase, 3 /* InitPhaseCompleted */, 'Init hooks phase should not be incremented after all init hooks have been run.');
2966 let flags = lView[FLAGS];
2967 if ((flags & 3 /* InitPhaseStateMask */) === initPhase) {
2968 flags &= 2047 /* IndexWithinInitPhaseReset */;
2969 flags += 1 /* InitPhaseStateIncrementer */;
2970 lView[FLAGS] = flags;
2971 }
2972}
2973/**
2974 * Calls lifecycle hooks with their contexts, skipping init hooks if it's not
2975 * the first LView pass
2976 *
2977 * @param currentView The current view
2978 * @param arr The array in which the hooks are found
2979 * @param initPhaseState the current state of the init phase
2980 * @param currentNodeIndex 3 cases depending on the value:
2981 * - undefined: all hooks from the array should be executed (post-order case)
2982 * - null: execute hooks only from the saved index until the end of the array (pre-order case, when
2983 * flushing the remaining hooks)
2984 * - number: execute hooks only from the saved index until that node index exclusive (pre-order
2985 * case, when executing select(number))
2986 */
2987function callHooks(currentView, arr, initPhase, currentNodeIndex) {
2988 ngDevMode &&
2989 assertEqual(getCheckNoChangesMode(), false, 'Hooks should never be run in the check no changes mode.');
2990 const startIndex = currentNodeIndex !== undefined ?
2991 (currentView[PREORDER_HOOK_FLAGS] & 65535 /* IndexOfTheNextPreOrderHookMaskMask */) :
2992 0;
2993 const nodeIndexLimit = currentNodeIndex != null ? currentNodeIndex : -1;
2994 let lastNodeIndexFound = 0;
2995 for (let i = startIndex; i < arr.length; i++) {
2996 const hook = arr[i + 1];
2997 if (typeof hook === 'number') {
2998 lastNodeIndexFound = arr[i];
2999 if (currentNodeIndex != null && lastNodeIndexFound >= currentNodeIndex) {
3000 break;
3001 }
3002 }
3003 else {
3004 const isInitHook = arr[i] < 0;
3005 if (isInitHook)
3006 currentView[PREORDER_HOOK_FLAGS] += 65536 /* NumberOfInitHooksCalledIncrementer */;
3007 if (lastNodeIndexFound < nodeIndexLimit || nodeIndexLimit == -1) {
3008 callHook(currentView, initPhase, arr, i);
3009 currentView[PREORDER_HOOK_FLAGS] =
3010 (currentView[PREORDER_HOOK_FLAGS] & 4294901760 /* NumberOfInitHooksCalledMask */) + i +
3011 2;
3012 }
3013 i++;
3014 }
3015 }
3016}
3017/**
3018 * Execute one hook against the current `LView`.
3019 *
3020 * @param currentView The current view
3021 * @param initPhaseState the current state of the init phase
3022 * @param arr The array in which the hooks are found
3023 * @param i The current index within the hook data array
3024 */
3025function callHook(currentView, initPhase, arr, i) {
3026 const isInitHook = arr[i] < 0;
3027 const hook = arr[i + 1];
3028 const directiveIndex = isInitHook ? -arr[i] : arr[i];
3029 const directive = currentView[directiveIndex];
3030 if (isInitHook) {
3031 const indexWithintInitPhase = currentView[FLAGS] >> 11 /* IndexWithinInitPhaseShift */;
3032 // The init phase state must be always checked here as it may have been recursively
3033 // updated
3034 if (indexWithintInitPhase <
3035 (currentView[PREORDER_HOOK_FLAGS] >> 16 /* NumberOfInitHooksCalledShift */) &&
3036 (currentView[FLAGS] & 3 /* InitPhaseStateMask */) === initPhase) {
3037 currentView[FLAGS] += 2048 /* IndexWithinInitPhaseIncrementer */;
3038 hook.call(directive);
3039 }
3040 }
3041 else {
3042 hook.call(directive);
3043 }
3044}
3045
3046/**
3047 * @license
3048 * Copyright Google LLC All Rights Reserved.
3049 *
3050 * Use of this source code is governed by an MIT-style license that can be
3051 * found in the LICENSE file at https://angular.io/license
3052 */
3053const TNODE = 8;
3054const PARENT_INJECTOR = 8;
3055const INJECTOR_BLOOM_PARENT_SIZE = 9;
3056const NO_PARENT_INJECTOR = -1;
3057/**
3058 * Each injector is saved in 9 contiguous slots in `LView` and 9 contiguous slots in
3059 * `TView.data`. This allows us to store information about the current node's tokens (which
3060 * can be shared in `TView`) as well as the tokens of its ancestor nodes (which cannot be
3061 * shared, so they live in `LView`).
3062 *
3063 * Each of these slots (aside from the last slot) contains a bloom filter. This bloom filter
3064 * determines whether a directive is available on the associated node or not. This prevents us
3065 * from searching the directives array at this level unless it's probable the directive is in it.
3066 *
3067 * See: https://en.wikipedia.org/wiki/Bloom_filter for more about bloom filters.
3068 *
3069 * Because all injectors have been flattened into `LView` and `TViewData`, they cannot typed
3070 * using interfaces as they were previously. The start index of each `LInjector` and `TInjector`
3071 * will differ based on where it is flattened into the main array, so it's not possible to know
3072 * the indices ahead of time and save their types here. The interfaces are still included here
3073 * for documentation purposes.
3074 *
3075 * export interface LInjector extends Array<any> {
3076 *
3077 * // Cumulative bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE)
3078 * [0]: number;
3079 *
3080 * // Cumulative bloom for directive IDs 32-63
3081 * [1]: number;
3082 *
3083 * // Cumulative bloom for directive IDs 64-95
3084 * [2]: number;
3085 *
3086 * // Cumulative bloom for directive IDs 96-127
3087 * [3]: number;
3088 *
3089 * // Cumulative bloom for directive IDs 128-159
3090 * [4]: number;
3091 *
3092 * // Cumulative bloom for directive IDs 160 - 191
3093 * [5]: number;
3094 *
3095 * // Cumulative bloom for directive IDs 192 - 223
3096 * [6]: number;
3097 *
3098 * // Cumulative bloom for directive IDs 224 - 255
3099 * [7]: number;
3100 *
3101 * // We need to store a reference to the injector's parent so DI can keep looking up
3102 * // the injector tree until it finds the dependency it's looking for.
3103 * [PARENT_INJECTOR]: number;
3104 * }
3105 *
3106 * export interface TInjector extends Array<any> {
3107 *
3108 * // Shared node bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE)
3109 * [0]: number;
3110 *
3111 * // Shared node bloom for directive IDs 32-63
3112 * [1]: number;
3113 *
3114 * // Shared node bloom for directive IDs 64-95
3115 * [2]: number;
3116 *
3117 * // Shared node bloom for directive IDs 96-127
3118 * [3]: number;
3119 *
3120 * // Shared node bloom for directive IDs 128-159
3121 * [4]: number;
3122 *
3123 * // Shared node bloom for directive IDs 160 - 191
3124 * [5]: number;
3125 *
3126 * // Shared node bloom for directive IDs 192 - 223
3127 * [6]: number;
3128 *
3129 * // Shared node bloom for directive IDs 224 - 255
3130 * [7]: number;
3131 *
3132 * // Necessary to find directive indices for a particular node.
3133 * [TNODE]: TElementNode|TElementContainerNode|TContainerNode;
3134 * }
3135 */
3136/**
3137 * Factory for creating instances of injectors in the NodeInjector.
3138 *
3139 * This factory is complicated by the fact that it can resolve `multi` factories as well.
3140 *
3141 * NOTE: Some of the fields are optional which means that this class has two hidden classes.
3142 * - One without `multi` support (most common)
3143 * - One with `multi` values, (rare).
3144 *
3145 * Since VMs can cache up to 4 inline hidden classes this is OK.
3146 *
3147 * - Single factory: Only `resolving` and `factory` is defined.
3148 * - `providers` factory: `componentProviders` is a number and `index = -1`.
3149 * - `viewProviders` factory: `componentProviders` is a number and `index` points to `providers`.
3150 */
3151class NodeInjectorFactory {
3152 constructor(
3153 /**
3154 * Factory to invoke in order to create a new instance.
3155 */
3156 factory,
3157 /**
3158 * Set to `true` if the token is declared in `viewProviders` (or if it is component).
3159 */
3160 isViewProvider, injectImplementation) {
3161 this.factory = factory;
3162 /**
3163 * Marker set to true during factory invocation to see if we get into recursive loop.
3164 * Recursive loop causes an error to be displayed.
3165 */
3166 this.resolving = false;
3167 this.canSeeViewProviders = isViewProvider;
3168 this.injectImpl = injectImplementation;
3169 }
3170}
3171function isFactory(obj) {
3172 return obj instanceof NodeInjectorFactory;
3173}
3174// Note: This hack is necessary so we don't erroneously get a circular dependency
3175// failure based on types.
3176const unusedValueExportToPlacateAjd$3 = 1;
3177
3178/**
3179 * @license
3180 * Copyright Google LLC All Rights Reserved.
3181 *
3182 * Use of this source code is governed by an MIT-style license that can be
3183 * found in the LICENSE file at https://angular.io/license
3184 */
3185function assertNodeType(tNode, type) {
3186 assertDefined(tNode, 'should be called with a TNode');
3187 assertEqual(tNode.type, type, `should be a ${typeName(type)}`);
3188}
3189function assertNodeOfPossibleTypes(tNode, types, message) {
3190 assertDefined(tNode, 'should be called with a TNode');
3191 const found = types.some(type => tNode.type === type);
3192 assertEqual(found, true, message !== null && message !== void 0 ? message : `Should be one of ${types.map(typeName).join(', ')} but got ${typeName(tNode.type)}`);
3193}
3194function assertNodeNotOfTypes(tNode, types, message) {
3195 assertDefined(tNode, 'should be called with a TNode');
3196 const found = types.some(type => tNode.type === type);
3197 assertEqual(found, false, message !== null && message !== void 0 ? message : `Should not be one of ${types.map(typeName).join(', ')} but got ${typeName(tNode.type)}`);
3198}
3199function typeName(type) {
3200 if (type == 1 /* Projection */)
3201 return 'Projection';
3202 if (type == 0 /* Container */)
3203 return 'Container';
3204 if (type == 5 /* IcuContainer */)
3205 return 'IcuContainer';
3206 if (type == 2 /* View */)
3207 return 'View';
3208 if (type == 3 /* Element */)
3209 return 'Element';
3210 if (type == 4 /* ElementContainer */)
3211 return 'ElementContainer';
3212 return '<unknown>';
3213}
3214
3215/**
3216 * Assigns all attribute values to the provided element via the inferred renderer.
3217 *
3218 * This function accepts two forms of attribute entries:
3219 *
3220 * default: (key, value):
3221 * attrs = [key1, value1, key2, value2]
3222 *
3223 * namespaced: (NAMESPACE_MARKER, uri, name, value)
3224 * attrs = [NAMESPACE_MARKER, uri, name, value, NAMESPACE_MARKER, uri, name, value]
3225 *
3226 * The `attrs` array can contain a mix of both the default and namespaced entries.
3227 * The "default" values are set without a marker, but if the function comes across
3228 * a marker value then it will attempt to set a namespaced value. If the marker is
3229 * not of a namespaced value then the function will quit and return the index value
3230 * where it stopped during the iteration of the attrs array.
3231 *
3232 * See [AttributeMarker] to understand what the namespace marker value is.
3233 *
3234 * Note that this instruction does not support assigning style and class values to
3235 * an element. See `elementStart` and `elementHostAttrs` to learn how styling values
3236 * are applied to an element.
3237 * @param renderer The renderer to be used
3238 * @param native The element that the attributes will be assigned to
3239 * @param attrs The attribute array of values that will be assigned to the element
3240 * @returns the index value that was last accessed in the attributes array
3241 */
3242function setUpAttributes(renderer, native, attrs) {
3243 const isProc = isProceduralRenderer(renderer);
3244 let i = 0;
3245 while (i < attrs.length) {
3246 const value = attrs[i];
3247 if (typeof value === 'number') {
3248 // only namespaces are supported. Other value types (such as style/class
3249 // entries) are not supported in this function.
3250 if (value !== 0 /* NamespaceURI */) {
3251 break;
3252 }
3253 // we just landed on the marker value ... therefore
3254 // we should skip to the next entry
3255 i++;
3256 const namespaceURI = attrs[i++];
3257 const attrName = attrs[i++];
3258 const attrVal = attrs[i++];
3259 ngDevMode && ngDevMode.rendererSetAttribute++;
3260 isProc ?
3261 renderer.setAttribute(native, attrName, attrVal, namespaceURI) :
3262 native.setAttributeNS(namespaceURI, attrName, attrVal);
3263 }
3264 else {
3265 // attrName is string;
3266 const attrName = value;
3267 const attrVal = attrs[++i];
3268 // Standard attributes
3269 ngDevMode && ngDevMode.rendererSetAttribute++;
3270 if (isAnimationProp(attrName)) {
3271 if (isProc) {
3272 renderer.setProperty(native, attrName, attrVal);
3273 }
3274 }
3275 else {
3276 isProc ?
3277 renderer.setAttribute(native, attrName, attrVal) :
3278 native.setAttribute(attrName, attrVal);
3279 }
3280 i++;
3281 }
3282 }
3283 // another piece of code may iterate over the same attributes array. Therefore
3284 // it may be helpful to return the exact spot where the attributes array exited
3285 // whether by running into an unsupported marker or if all the static values were
3286 // iterated over.
3287 return i;
3288}
3289/**
3290 * Test whether the given value is a marker that indicates that the following
3291 * attribute values in a `TAttributes` array are only the names of attributes,
3292 * and not name-value pairs.
3293 * @param marker The attribute marker to test.
3294 * @returns true if the marker is a "name-only" marker (e.g. `Bindings`, `Template` or `I18n`).
3295 */
3296function isNameOnlyAttributeMarker(marker) {
3297 return marker === 3 /* Bindings */ || marker === 4 /* Template */ ||
3298 marker === 6 /* I18n */;
3299}
3300function isAnimationProp(name) {
3301 // Perf note: accessing charCodeAt to check for the first character of a string is faster as
3302 // compared to accessing a character at index 0 (ex. name[0]). The main reason for this is that
3303 // charCodeAt doesn't allocate memory to return a substring.
3304 return name.charCodeAt(0) === 64 /* AT_SIGN */;
3305}
3306/**
3307 * Merges `src` `TAttributes` into `dst` `TAttributes` removing any duplicates in the process.
3308 *
3309 * This merge function keeps the order of attrs same.
3310 *
3311 * @param dst Location of where the merged `TAttributes` should end up.
3312 * @param src `TAttributes` which should be appended to `dst`
3313 */
3314function mergeHostAttrs(dst, src) {
3315 if (src === null || src.length === 0) {
3316 // do nothing
3317 }
3318 else if (dst === null || dst.length === 0) {
3319 // We have source, but dst is empty, just make a copy.
3320 dst = src.slice();
3321 }
3322 else {
3323 let srcMarker = -1 /* ImplicitAttributes */;
3324 for (let i = 0; i < src.length; i++) {
3325 const item = src[i];
3326 if (typeof item === 'number') {
3327 srcMarker = item;
3328 }
3329 else {
3330 if (srcMarker === 0 /* NamespaceURI */) {
3331 // Case where we need to consume `key1`, `key2`, `value` items.
3332 }
3333 else if (srcMarker === -1 /* ImplicitAttributes */ ||
3334 srcMarker === 2 /* Styles */) {
3335 // Case where we have to consume `key1` and `value` only.
3336 mergeHostAttribute(dst, srcMarker, item, null, src[++i]);
3337 }
3338 else {
3339 // Case where we have to consume `key1` only.
3340 mergeHostAttribute(dst, srcMarker, item, null, null);
3341 }
3342 }
3343 }
3344 }
3345 return dst;
3346}
3347/**
3348 * Append `key`/`value` to existing `TAttributes` taking region marker and duplicates into account.
3349 *
3350 * @param dst `TAttributes` to append to.
3351 * @param marker Region where the `key`/`value` should be added.
3352 * @param key1 Key to add to `TAttributes`
3353 * @param key2 Key to add to `TAttributes` (in case of `AttributeMarker.NamespaceURI`)
3354 * @param value Value to add or to overwrite to `TAttributes` Only used if `marker` is not Class.
3355 */
3356function mergeHostAttribute(dst, marker, key1, key2, value) {
3357 let i = 0;
3358 // Assume that new markers will be inserted at the end.
3359 let markerInsertPosition = dst.length;
3360 // scan until correct type.
3361 if (marker === -1 /* ImplicitAttributes */) {
3362 markerInsertPosition = -1;
3363 }
3364 else {
3365 while (i < dst.length) {
3366 const dstValue = dst[i++];
3367 if (typeof dstValue === 'number') {
3368 if (dstValue === marker) {
3369 markerInsertPosition = -1;
3370 break;
3371 }
3372 else if (dstValue > marker) {
3373 // We need to save this as we want the markers to be inserted in specific order.
3374 markerInsertPosition = i - 1;
3375 break;
3376 }
3377 }
3378 }
3379 }
3380 // search until you find place of insertion
3381 while (i < dst.length) {
3382 const item = dst[i];
3383 if (typeof item === 'number') {
3384 // since `i` started as the index after the marker, we did not find it if we are at the next
3385 // marker
3386 break;
3387 }
3388 else if (item === key1) {
3389 // We already have same token
3390 if (key2 === null) {
3391 if (value !== null) {
3392 dst[i + 1] = value;
3393 }
3394 return;
3395 }
3396 else if (key2 === dst[i + 1]) {
3397 dst[i + 2] = value;
3398 return;
3399 }
3400 }
3401 // Increment counter.
3402 i++;
3403 if (key2 !== null)
3404 i++;
3405 if (value !== null)
3406 i++;
3407 }
3408 // insert at location.
3409 if (markerInsertPosition !== -1) {
3410 dst.splice(markerInsertPosition, 0, marker);
3411 i = markerInsertPosition + 1;
3412 }
3413 dst.splice(i++, 0, key1);
3414 if (key2 !== null) {
3415 dst.splice(i++, 0, key2);
3416 }
3417 if (value !== null) {
3418 dst.splice(i++, 0, value);
3419 }
3420}
3421
3422/**
3423 * @license
3424 * Copyright Google LLC All Rights Reserved.
3425 *
3426 * Use of this source code is governed by an MIT-style license that can be
3427 * found in the LICENSE file at https://angular.io/license
3428 */
3429/// Parent Injector Utils ///////////////////////////////////////////////////////////////
3430function hasParentInjector(parentLocation) {
3431 return parentLocation !== NO_PARENT_INJECTOR;
3432}
3433function getParentInjectorIndex(parentLocation) {
3434 return parentLocation & 32767 /* InjectorIndexMask */;
3435}
3436function getParentInjectorViewOffset(parentLocation) {
3437 return parentLocation >> 16 /* ViewOffsetShift */;
3438}
3439/**
3440 * Unwraps a parent injector location number to find the view offset from the current injector,
3441 * then walks up the declaration view tree until the view is found that contains the parent
3442 * injector.
3443 *
3444 * @param location The location of the parent injector, which contains the view offset
3445 * @param startView The LView instance from which to start walking up the view tree
3446 * @returns The LView instance that contains the parent injector
3447 */
3448function getParentInjectorView(location, startView) {
3449 let viewOffset = getParentInjectorViewOffset(location);
3450 let parentView = startView;
3451 // For most cases, the parent injector can be found on the host node (e.g. for component
3452 // or container), but we must keep the loop here to support the rarer case of deeply nested
3453 // <ng-template> tags or inline views, where the parent injector might live many views
3454 // above the child injector.
3455 while (viewOffset > 0) {
3456 parentView = parentView[DECLARATION_VIEW];
3457 viewOffset--;
3458 }
3459 return parentView;
3460}
3461
3462/**
3463 * @license
3464 * Copyright Google LLC All Rights Reserved.
3465 *
3466 * Use of this source code is governed by an MIT-style license that can be
3467 * found in the LICENSE file at https://angular.io/license
3468 */
3469/**
3470 * Used for stringify render output in Ivy.
3471 * Important! This function is very performance-sensitive and we should
3472 * be extra careful not to introduce megamorphic reads in it.
3473 */
3474function renderStringify(value) {
3475 if (typeof value === 'string')
3476 return value;
3477 if (value == null)
3478 return '';
3479 return '' + value;
3480}
3481/**
3482 * Used to stringify a value so that it can be displayed in an error message.
3483 * Important! This function contains a megamorphic read and should only be
3484 * used for error messages.
3485 */
3486function stringifyForError(value) {
3487 if (typeof value === 'function')
3488 return value.name || value.toString();
3489 if (typeof value === 'object' && value != null && typeof value.type === 'function') {
3490 return value.type.name || value.type.toString();
3491 }
3492 return renderStringify(value);
3493}
3494const ɵ0$3 = () => (typeof requestAnimationFrame !== 'undefined' &&
3495 requestAnimationFrame || // browser only
3496 setTimeout // everything else
3497)
3498 .bind(_global);
3499const defaultScheduler = (ɵ0$3)();
3500/**
3501 *
3502 * @codeGenApi
3503 */
3504function ɵɵresolveWindow(element) {
3505 return { name: 'window', target: element.ownerDocument.defaultView };
3506}
3507/**
3508 *
3509 * @codeGenApi
3510 */
3511function ɵɵresolveDocument(element) {
3512 return { name: 'document', target: element.ownerDocument };
3513}
3514/**
3515 *
3516 * @codeGenApi
3517 */
3518function ɵɵresolveBody(element) {
3519 return { name: 'body', target: element.ownerDocument.body };
3520}
3521/**
3522 * The special delimiter we use to separate property names, prefixes, and suffixes
3523 * in property binding metadata. See storeBindingMetadata().
3524 *
3525 * We intentionally use the Unicode "REPLACEMENT CHARACTER" (U+FFFD) as a delimiter
3526 * because it is a very uncommon character that is unlikely to be part of a user's
3527 * property names or interpolation strings. If it is in fact used in a property
3528 * binding, DebugElement.properties will not return the correct value for that
3529 * binding. However, there should be no runtime effect for real applications.
3530 *
3531 * This character is typically rendered as a question mark inside of a diamond.
3532 * See https://en.wikipedia.org/wiki/Specials_(Unicode_block)
3533 *
3534 */
3535const INTERPOLATION_DELIMITER = `�`;
3536/**
3537 * Unwrap a value which might be behind a closure (for forward declaration reasons).
3538 */
3539function maybeUnwrapFn(value) {
3540 if (value instanceof Function) {
3541 return value();
3542 }
3543 else {
3544 return value;
3545 }
3546}
3547
3548/**
3549 * @license
3550 * Copyright Google LLC All Rights Reserved.
3551 *
3552 * Use of this source code is governed by an MIT-style license that can be
3553 * found in the LICENSE file at https://angular.io/license
3554 */
3555/**
3556 * Defines if the call to `inject` should include `viewProviders` in its resolution.
3557 *
3558 * This is set to true when we try to instantiate a component. This value is reset in
3559 * `getNodeInjectable` to a value which matches the declaration location of the token about to be
3560 * instantiated. This is done so that if we are injecting a token which was declared outside of
3561 * `viewProviders` we don't accidentally pull `viewProviders` in.
3562 *
3563 * Example:
3564 *
3565 * ```
3566 * @Injectable()
3567 * class MyService {
3568 * constructor(public value: String) {}
3569 * }
3570 *
3571 * @Component({
3572 * providers: [
3573 * MyService,
3574 * {provide: String, value: 'providers' }
3575 * ]
3576 * viewProviders: [
3577 * {provide: String, value: 'viewProviders'}
3578 * ]
3579 * })
3580 * class MyComponent {
3581 * constructor(myService: MyService, value: String) {
3582 * // We expect that Component can see into `viewProviders`.
3583 * expect(value).toEqual('viewProviders');
3584 * // `MyService` was not declared in `viewProviders` hence it can't see it.
3585 * expect(myService.value).toEqual('providers');
3586 * }
3587 * }
3588 *
3589 * ```
3590 */
3591let includeViewProviders = true;
3592function setIncludeViewProviders(v) {
3593 const oldValue = includeViewProviders;
3594 includeViewProviders = v;
3595 return oldValue;
3596}
3597/**
3598 * The number of slots in each bloom filter (used by DI). The larger this number, the fewer
3599 * directives that will share slots, and thus, the fewer false positives when checking for
3600 * the existence of a directive.
3601 */
3602const BLOOM_SIZE = 256;
3603const BLOOM_MASK = BLOOM_SIZE - 1;
3604/** Counter used to generate unique IDs for directives. */
3605let nextNgElementId = 0;
3606/**
3607 * Registers this directive as present in its node's injector by flipping the directive's
3608 * corresponding bit in the injector's bloom filter.
3609 *
3610 * @param injectorIndex The index of the node injector where this token should be registered
3611 * @param tView The TView for the injector's bloom filters
3612 * @param type The directive token to register
3613 */
3614function bloomAdd(injectorIndex, tView, type) {
3615 ngDevMode && assertEqual(tView.firstCreatePass, true, 'expected firstCreatePass to be true');
3616 let id;
3617 if (typeof type === 'string') {
3618 id = type.charCodeAt(0) || 0;
3619 }
3620 else if (type.hasOwnProperty(NG_ELEMENT_ID)) {
3621 id = type[NG_ELEMENT_ID];
3622 }
3623 // Set a unique ID on the directive type, so if something tries to inject the directive,
3624 // we can easily retrieve the ID and hash it into the bloom bit that should be checked.
3625 if (id == null) {
3626 id = type[NG_ELEMENT_ID] = nextNgElementId++;
3627 }
3628 // We only have BLOOM_SIZE (256) slots in our bloom filter (8 buckets * 32 bits each),
3629 // so all unique IDs must be modulo-ed into a number from 0 - 255 to fit into the filter.
3630 const bloomBit = id & BLOOM_MASK;
3631 // Create a mask that targets the specific bit associated with the directive.
3632 // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
3633 // to bit positions 0 - 31 in a 32 bit integer.
3634 const mask = 1 << bloomBit;
3635 // Use the raw bloomBit number to determine which bloom filter bucket we should check
3636 // e.g: bf0 = [0 - 31], bf1 = [32 - 63], bf2 = [64 - 95], bf3 = [96 - 127], etc
3637 const b7 = bloomBit & 0x80;
3638 const b6 = bloomBit & 0x40;
3639 const b5 = bloomBit & 0x20;
3640 const tData = tView.data;
3641 if (b7) {
3642 b6 ? (b5 ? (tData[injectorIndex + 7] |= mask) : (tData[injectorIndex + 6] |= mask)) :
3643 (b5 ? (tData[injectorIndex + 5] |= mask) : (tData[injectorIndex + 4] |= mask));
3644 }
3645 else {
3646 b6 ? (b5 ? (tData[injectorIndex + 3] |= mask) : (tData[injectorIndex + 2] |= mask)) :
3647 (b5 ? (tData[injectorIndex + 1] |= mask) : (tData[injectorIndex] |= mask));
3648 }
3649}
3650/**
3651 * Creates (or gets an existing) injector for a given element or container.
3652 *
3653 * @param tNode for which an injector should be retrieved / created.
3654 * @param hostView View where the node is stored
3655 * @returns Node injector
3656 */
3657function getOrCreateNodeInjectorForNode(tNode, hostView) {
3658 const existingInjectorIndex = getInjectorIndex(tNode, hostView);
3659 if (existingInjectorIndex !== -1) {
3660 return existingInjectorIndex;
3661 }
3662 const tView = hostView[TVIEW];
3663 if (tView.firstCreatePass) {
3664 tNode.injectorIndex = hostView.length;
3665 insertBloom(tView.data, tNode); // foundation for node bloom
3666 insertBloom(hostView, null); // foundation for cumulative bloom
3667 insertBloom(tView.blueprint, null);
3668 }
3669 const parentLoc = getParentInjectorLocation(tNode, hostView);
3670 const injectorIndex = tNode.injectorIndex;
3671 // If a parent injector can't be found, its location is set to -1.
3672 // In that case, we don't need to set up a cumulative bloom
3673 if (hasParentInjector(parentLoc)) {
3674 const parentIndex = getParentInjectorIndex(parentLoc);
3675 const parentLView = getParentInjectorView(parentLoc, hostView);
3676 const parentData = parentLView[TVIEW].data;
3677 // Creates a cumulative bloom filter that merges the parent's bloom filter
3678 // and its own cumulative bloom (which contains tokens for all ancestors)
3679 for (let i = 0; i < 8; i++) {
3680 hostView[injectorIndex + i] = parentLView[parentIndex + i] | parentData[parentIndex + i];
3681 }
3682 }
3683 hostView[injectorIndex + PARENT_INJECTOR] = parentLoc;
3684 return injectorIndex;
3685}
3686function insertBloom(arr, footer) {
3687 arr.push(0, 0, 0, 0, 0, 0, 0, 0, footer);
3688}
3689function getInjectorIndex(tNode, hostView) {
3690 if (tNode.injectorIndex === -1 ||
3691 // If the injector index is the same as its parent's injector index, then the index has been
3692 // copied down from the parent node. No injector has been created yet on this node.
3693 (tNode.parent && tNode.parent.injectorIndex === tNode.injectorIndex) ||
3694 // After the first template pass, the injector index might exist but the parent values
3695 // might not have been calculated yet for this instance
3696 hostView[tNode.injectorIndex + PARENT_INJECTOR] == null) {
3697 return -1;
3698 }
3699 else {
3700 return tNode.injectorIndex;
3701 }
3702}
3703/**
3704 * Finds the index of the parent injector, with a view offset if applicable. Used to set the
3705 * parent injector initially.
3706 *
3707 * Returns a combination of number of `ViewData` we have to go up and index in that `Viewdata`
3708 */
3709function getParentInjectorLocation(tNode, view) {
3710 if (tNode.parent && tNode.parent.injectorIndex !== -1) {
3711 return tNode.parent.injectorIndex; // ViewOffset is 0
3712 }
3713 // For most cases, the parent injector index can be found on the host node (e.g. for component
3714 // or container), so this loop will be skipped, but we must keep the loop here to support
3715 // the rarer case of deeply nested <ng-template> tags or inline views.
3716 let hostTNode = view[T_HOST];
3717 let viewOffset = 1;
3718 while (hostTNode && hostTNode.injectorIndex === -1) {
3719 view = view[DECLARATION_VIEW];
3720 hostTNode = view ? view[T_HOST] : null;
3721 viewOffset++;
3722 }
3723 return hostTNode ?
3724 hostTNode.injectorIndex | (viewOffset << 16 /* ViewOffsetShift */) :
3725 -1;
3726}
3727/**
3728 * Makes a type or an injection token public to the DI system by adding it to an
3729 * injector's bloom filter.
3730 *
3731 * @param di The node injector in which a directive will be added
3732 * @param token The type or the injection token to be made public
3733 */
3734function diPublicInInjector(injectorIndex, tView, token) {
3735 bloomAdd(injectorIndex, tView, token);
3736}
3737/**
3738 * Inject static attribute value into directive constructor.
3739 *
3740 * This method is used with `factory` functions which are generated as part of
3741 * `defineDirective` or `defineComponent`. The method retrieves the static value
3742 * of an attribute. (Dynamic attributes are not supported since they are not resolved
3743 * at the time of injection and can change over time.)
3744 *
3745 * # Example
3746 * Given:
3747 * ```
3748 * @Component(...)
3749 * class MyComponent {
3750 * constructor(@Attribute('title') title: string) { ... }
3751 * }
3752 * ```
3753 * When instantiated with
3754 * ```
3755 * <my-component title="Hello"></my-component>
3756 * ```
3757 *
3758 * Then factory method generated is:
3759 * ```
3760 * MyComponent.ɵcmp = defineComponent({
3761 * factory: () => new MyComponent(injectAttribute('title'))
3762 * ...
3763 * })
3764 * ```
3765 *
3766 * @publicApi
3767 */
3768function injectAttributeImpl(tNode, attrNameToInject) {
3769 ngDevMode &&
3770 assertNodeOfPossibleTypes(tNode, [0 /* Container */, 3 /* Element */, 4 /* ElementContainer */]);
3771 ngDevMode && assertDefined(tNode, 'expecting tNode');
3772 if (attrNameToInject === 'class') {
3773 return tNode.classes;
3774 }
3775 if (attrNameToInject === 'style') {
3776 return tNode.styles;
3777 }
3778 const attrs = tNode.attrs;
3779 if (attrs) {
3780 const attrsLength = attrs.length;
3781 let i = 0;
3782 while (i < attrsLength) {
3783 const value = attrs[i];
3784 // If we hit a `Bindings` or `Template` marker then we are done.
3785 if (isNameOnlyAttributeMarker(value))
3786 break;
3787 // Skip namespaced attributes
3788 if (value === 0 /* NamespaceURI */) {
3789 // we skip the next two values
3790 // as namespaced attributes looks like
3791 // [..., AttributeMarker.NamespaceURI, 'http://someuri.com/test', 'test:exist',
3792 // 'existValue', ...]
3793 i = i + 2;
3794 }
3795 else if (typeof value === 'number') {
3796 // Skip to the first value of the marked attribute.
3797 i++;
3798 while (i < attrsLength && typeof attrs[i] === 'string') {
3799 i++;
3800 }
3801 }
3802 else if (value === attrNameToInject) {
3803 return attrs[i + 1];
3804 }
3805 else {
3806 i = i + 2;
3807 }
3808 }
3809 }
3810 return null;
3811}
3812/**
3813 * Returns the value associated to the given token from the NodeInjectors => ModuleInjector.
3814 *
3815 * Look for the injector providing the token by walking up the node injector tree and then
3816 * the module injector tree.
3817 *
3818 * This function patches `token` with `__NG_ELEMENT_ID__` which contains the id for the bloom
3819 * filter. Negative values are reserved for special objects.
3820 * - `-1` is reserved for injecting `Injector` (implemented by `NodeInjector`)
3821 *
3822 * @param tNode The Node where the search for the injector should start
3823 * @param lView The `LView` that contains the `tNode`
3824 * @param token The token to look for
3825 * @param flags Injection flags
3826 * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
3827 * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
3828 */
3829function getOrCreateInjectable(tNode, lView, token, flags = InjectFlags.Default, notFoundValue) {
3830 if (tNode !== null) {
3831 const bloomHash = bloomHashBitOrFactory(token);
3832 // If the ID stored here is a function, this is a special object like ElementRef or TemplateRef
3833 // so just call the factory function to create it.
3834 if (typeof bloomHash === 'function') {
3835 enterDI(lView, tNode);
3836 try {
3837 const value = bloomHash();
3838 if (value == null && !(flags & InjectFlags.Optional)) {
3839 throw new Error(`No provider for ${stringifyForError(token)}!`);
3840 }
3841 else {
3842 return value;
3843 }
3844 }
3845 finally {
3846 leaveDI();
3847 }
3848 }
3849 else if (typeof bloomHash == 'number') {
3850 if (bloomHash === -1) {
3851 // `-1` is a special value used to identify `Injector` types.
3852 return new NodeInjector(tNode, lView);
3853 }
3854 // If the token has a bloom hash, then it is a token which could be in NodeInjector.
3855 // A reference to the previous injector TView that was found while climbing the element
3856 // injector tree. This is used to know if viewProviders can be accessed on the current
3857 // injector.
3858 let previousTView = null;
3859 let injectorIndex = getInjectorIndex(tNode, lView);
3860 let parentLocation = NO_PARENT_INJECTOR;
3861 let hostTElementNode = flags & InjectFlags.Host ? lView[DECLARATION_COMPONENT_VIEW][T_HOST] : null;
3862 // If we should skip this injector, or if there is no injector on this node, start by
3863 // searching
3864 // the parent injector.
3865 if (injectorIndex === -1 || flags & InjectFlags.SkipSelf) {
3866 parentLocation = injectorIndex === -1 ? getParentInjectorLocation(tNode, lView) :
3867 lView[injectorIndex + PARENT_INJECTOR];
3868 if (!shouldSearchParent(flags, false)) {
3869 injectorIndex = -1;
3870 }
3871 else {
3872 previousTView = lView[TVIEW];
3873 injectorIndex = getParentInjectorIndex(parentLocation);
3874 lView = getParentInjectorView(parentLocation, lView);
3875 }
3876 }
3877 // Traverse up the injector tree until we find a potential match or until we know there
3878 // *isn't* a match.
3879 while (injectorIndex !== -1) {
3880 parentLocation = lView[injectorIndex + PARENT_INJECTOR];
3881 // Check the current injector. If it matches, see if it contains token.
3882 const tView = lView[TVIEW];
3883 if (bloomHasToken(bloomHash, injectorIndex, tView.data)) {
3884 // At this point, we have an injector which *may* contain the token, so we step through
3885 // the providers and directives associated with the injector's corresponding node to get
3886 // the instance.
3887 const instance = searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode);
3888 if (instance !== NOT_FOUND) {
3889 return instance;
3890 }
3891 }
3892 if (shouldSearchParent(flags, lView[TVIEW].data[injectorIndex + TNODE] === hostTElementNode) &&
3893 bloomHasToken(bloomHash, injectorIndex, lView)) {
3894 // The def wasn't found anywhere on this node, so it was a false positive.
3895 // Traverse up the tree and continue searching.
3896 previousTView = tView;
3897 injectorIndex = getParentInjectorIndex(parentLocation);
3898 lView = getParentInjectorView(parentLocation, lView);
3899 }
3900 else {
3901 // If we should not search parent OR If the ancestor bloom filter value does not have the
3902 // bit corresponding to the directive we can give up on traversing up to find the specific
3903 // injector.
3904 injectorIndex = -1;
3905 }
3906 }
3907 }
3908 }
3909 if (flags & InjectFlags.Optional && notFoundValue === undefined) {
3910 // This must be set or the NullInjector will throw for optional deps
3911 notFoundValue = null;
3912 }
3913 if ((flags & (InjectFlags.Self | InjectFlags.Host)) === 0) {
3914 const moduleInjector = lView[INJECTOR$1];
3915 // switch to `injectInjectorOnly` implementation for module injector, since module injector
3916 // should not have access to Component/Directive DI scope (that may happen through
3917 // `directiveInject` implementation)
3918 const previousInjectImplementation = setInjectImplementation(undefined);
3919 try {
3920 if (moduleInjector) {
3921 return moduleInjector.get(token, notFoundValue, flags & InjectFlags.Optional);
3922 }
3923 else {
3924 return injectRootLimpMode(token, notFoundValue, flags & InjectFlags.Optional);
3925 }
3926 }
3927 finally {
3928 setInjectImplementation(previousInjectImplementation);
3929 }
3930 }
3931 if (flags & InjectFlags.Optional) {
3932 return notFoundValue;
3933 }
3934 else {
3935 throw new Error(`NodeInjector: NOT_FOUND [${stringifyForError(token)}]`);
3936 }
3937}
3938const NOT_FOUND = {};
3939function searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode) {
3940 const currentTView = lView[TVIEW];
3941 const tNode = currentTView.data[injectorIndex + TNODE];
3942 // First, we need to determine if view providers can be accessed by the starting element.
3943 // There are two possibities
3944 const canAccessViewProviders = previousTView == null ?
3945 // 1) This is the first invocation `previousTView == null` which means that we are at the
3946 // `TNode` of where injector is starting to look. In such a case the only time we are allowed
3947 // to look into the ViewProviders is if:
3948 // - we are on a component
3949 // - AND the injector set `includeViewProviders` to true (implying that the token can see
3950 // ViewProviders because it is the Component or a Service which itself was declared in
3951 // ViewProviders)
3952 (isComponentHost(tNode) && includeViewProviders) :
3953 // 2) `previousTView != null` which means that we are now walking across the parent nodes.
3954 // In such a case we are only allowed to look into the ViewProviders if:
3955 // - We just crossed from child View to Parent View `previousTView != currentTView`
3956 // - AND the parent TNode is an Element.
3957 // This means that we just came from the Component's View and therefore are allowed to see
3958 // into the ViewProviders.
3959 (previousTView != currentTView && (tNode.type === 3 /* Element */));
3960 // This special case happens when there is a @host on the inject and when we are searching
3961 // on the host element node.
3962 const isHostSpecialCase = (flags & InjectFlags.Host) && hostTElementNode === tNode;
3963 const injectableIdx = locateDirectiveOrProvider(tNode, currentTView, token, canAccessViewProviders, isHostSpecialCase);
3964 if (injectableIdx !== null) {
3965 return getNodeInjectable(lView, currentTView, injectableIdx, tNode);
3966 }
3967 else {
3968 return NOT_FOUND;
3969 }
3970}
3971/**
3972 * Searches for the given token among the node's directives and providers.
3973 *
3974 * @param tNode TNode on which directives are present.
3975 * @param tView The tView we are currently processing
3976 * @param token Provider token or type of a directive to look for.
3977 * @param canAccessViewProviders Whether view providers should be considered.
3978 * @param isHostSpecialCase Whether the host special case applies.
3979 * @returns Index of a found directive or provider, or null when none found.
3980 */
3981function locateDirectiveOrProvider(tNode, tView, token, canAccessViewProviders, isHostSpecialCase) {
3982 const nodeProviderIndexes = tNode.providerIndexes;
3983 const tInjectables = tView.data;
3984 const injectablesStart = nodeProviderIndexes & 1048575 /* ProvidersStartIndexMask */;
3985 const directivesStart = tNode.directiveStart;
3986 const directiveEnd = tNode.directiveEnd;
3987 const cptViewProvidersCount = nodeProviderIndexes >> 20 /* CptViewProvidersCountShift */;
3988 const startingIndex = canAccessViewProviders ? injectablesStart : injectablesStart + cptViewProvidersCount;
3989 // When the host special case applies, only the viewProviders and the component are visible
3990 const endIndex = isHostSpecialCase ? injectablesStart + cptViewProvidersCount : directiveEnd;
3991 for (let i = startingIndex; i < endIndex; i++) {
3992 const providerTokenOrDef = tInjectables[i];
3993 if (i < directivesStart && token === providerTokenOrDef ||
3994 i >= directivesStart && providerTokenOrDef.type === token) {
3995 return i;
3996 }
3997 }
3998 if (isHostSpecialCase) {
3999 const dirDef = tInjectables[directivesStart];
4000 if (dirDef && isComponentDef(dirDef) && dirDef.type === token) {
4001 return directivesStart;
4002 }
4003 }
4004 return null;
4005}
4006/**
4007 * Retrieve or instantiate the injectable from the `LView` at particular `index`.
4008 *
4009 * This function checks to see if the value has already been instantiated and if so returns the
4010 * cached `injectable`. Otherwise if it detects that the value is still a factory it
4011 * instantiates the `injectable` and caches the value.
4012 */
4013function getNodeInjectable(lView, tView, index, tNode) {
4014 let value = lView[index];
4015 const tData = tView.data;
4016 if (isFactory(value)) {
4017 const factory = value;
4018 if (factory.resolving) {
4019 throw new Error(`Circular dep for ${stringifyForError(tData[index])}`);
4020 }
4021 const previousIncludeViewProviders = setIncludeViewProviders(factory.canSeeViewProviders);
4022 factory.resolving = true;
4023 let previousInjectImplementation;
4024 if (factory.injectImpl) {
4025 previousInjectImplementation = setInjectImplementation(factory.injectImpl);
4026 }
4027 enterDI(lView, tNode);
4028 try {
4029 value = lView[index] = factory.factory(undefined, tData, lView, tNode);
4030 // This code path is hit for both directives and providers.
4031 // For perf reasons, we want to avoid searching for hooks on providers.
4032 // It does no harm to try (the hooks just won't exist), but the extra
4033 // checks are unnecessary and this is a hot path. So we check to see
4034 // if the index of the dependency is in the directive range for this
4035 // tNode. If it's not, we know it's a provider and skip hook registration.
4036 if (tView.firstCreatePass && index >= tNode.directiveStart) {
4037 ngDevMode && assertDirectiveDef(tData[index]);
4038 registerPreOrderHooks(index, tData[index], tView);
4039 }
4040 }
4041 finally {
4042 if (factory.injectImpl)
4043 setInjectImplementation(previousInjectImplementation);
4044 setIncludeViewProviders(previousIncludeViewProviders);
4045 factory.resolving = false;
4046 leaveDI();
4047 }
4048 }
4049 return value;
4050}
4051/**
4052 * Returns the bit in an injector's bloom filter that should be used to determine whether or not
4053 * the directive might be provided by the injector.
4054 *
4055 * When a directive is public, it is added to the bloom filter and given a unique ID that can be
4056 * retrieved on the Type. When the directive isn't public or the token is not a directive `null`
4057 * is returned as the node injector can not possibly provide that token.
4058 *
4059 * @param token the injection token
4060 * @returns the matching bit to check in the bloom filter or `null` if the token is not known.
4061 * When the returned value is negative then it represents special values such as `Injector`.
4062 */
4063function bloomHashBitOrFactory(token) {
4064 ngDevMode && assertDefined(token, 'token must be defined');
4065 if (typeof token === 'string') {
4066 return token.charCodeAt(0) || 0;
4067 }
4068 const tokenId =
4069 // First check with `hasOwnProperty` so we don't get an inherited ID.
4070 token.hasOwnProperty(NG_ELEMENT_ID) ? token[NG_ELEMENT_ID] : undefined;
4071 // Negative token IDs are used for special objects such as `Injector`
4072 return (typeof tokenId === 'number' && tokenId > 0) ? tokenId & BLOOM_MASK : tokenId;
4073}
4074function bloomHasToken(bloomHash, injectorIndex, injectorView) {
4075 // Create a mask that targets the specific bit associated with the directive we're looking for.
4076 // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
4077 // to bit positions 0 - 31 in a 32 bit integer.
4078 const mask = 1 << bloomHash;
4079 const b7 = bloomHash & 0x80;
4080 const b6 = bloomHash & 0x40;
4081 const b5 = bloomHash & 0x20;
4082 // Our bloom filter size is 256 bits, which is eight 32-bit bloom filter buckets:
4083 // bf0 = [0 - 31], bf1 = [32 - 63], bf2 = [64 - 95], bf3 = [96 - 127], etc.
4084 // Get the bloom filter value from the appropriate bucket based on the directive's bloomBit.
4085 let value;
4086 if (b7) {
4087 value = b6 ? (b5 ? injectorView[injectorIndex + 7] : injectorView[injectorIndex + 6]) :
4088 (b5 ? injectorView[injectorIndex + 5] : injectorView[injectorIndex + 4]);
4089 }
4090 else {
4091 value = b6 ? (b5 ? injectorView[injectorIndex + 3] : injectorView[injectorIndex + 2]) :
4092 (b5 ? injectorView[injectorIndex + 1] : injectorView[injectorIndex]);
4093 }
4094 // If the bloom filter value has the bit corresponding to the directive's bloomBit flipped on,
4095 // this injector is a potential match.
4096 return !!(value & mask);
4097}
4098/** Returns true if flags prevent parent injector from being searched for tokens */
4099function shouldSearchParent(flags, isFirstHostTNode) {
4100 return !(flags & InjectFlags.Self) && !(flags & InjectFlags.Host && isFirstHostTNode);
4101}
4102class NodeInjector {
4103 constructor(_tNode, _lView) {
4104 this._tNode = _tNode;
4105 this._lView = _lView;
4106 }
4107 get(token, notFoundValue) {
4108 return getOrCreateInjectable(this._tNode, this._lView, token, undefined, notFoundValue);
4109 }
4110}
4111/**
4112 * @codeGenApi
4113 */
4114function ɵɵgetFactoryOf(type) {
4115 const typeAny = type;
4116 if (isForwardRef(type)) {
4117 return (() => {
4118 const factory = ɵɵgetFactoryOf(resolveForwardRef(typeAny));
4119 return factory ? factory() : null;
4120 });
4121 }
4122 let factory = getFactoryDef(typeAny);
4123 if (factory === null) {
4124 const injectorDef = getInjectorDef(typeAny);
4125 factory = injectorDef && injectorDef.factory;
4126 }
4127 return factory || null;
4128}
4129/**
4130 * @codeGenApi
4131 */
4132function ɵɵgetInheritedFactory(type) {
4133 return noSideEffects(() => {
4134 const ownConstructor = type.prototype.constructor;
4135 const ownFactory = ownConstructor[NG_FACTORY_DEF] || ɵɵgetFactoryOf(ownConstructor);
4136 const objectPrototype = Object.prototype;
4137 let parent = Object.getPrototypeOf(type.prototype).constructor;
4138 // Go up the prototype until we hit `Object`.
4139 while (parent && parent !== objectPrototype) {
4140 const factory = parent[NG_FACTORY_DEF] || ɵɵgetFactoryOf(parent);
4141 // If we hit something that has a factory and the factory isn't the same as the type,
4142 // we've found the inherited factory. Note the check that the factory isn't the type's
4143 // own factory is redundant in most cases, but if the user has custom decorators on the
4144 // class, this lookup will start one level down in the prototype chain, causing us to
4145 // find the own factory first and potentially triggering an infinite loop downstream.
4146 if (factory && factory !== ownFactory) {
4147 return factory;
4148 }
4149 parent = Object.getPrototypeOf(parent);
4150 }
4151 // There is no factory defined. Either this was improper usage of inheritance
4152 // (no Angular decorator on the superclass) or there is no constructor at all
4153 // in the inheritance chain. Since the two cases cannot be distinguished, the
4154 // latter has to be assumed.
4155 return t => new t();
4156 });
4157}
4158
4159/**
4160 * @license
4161 * Copyright Google LLC All Rights Reserved.
4162 *
4163 * Use of this source code is governed by an MIT-style license that can be
4164 * found in the LICENSE file at https://angular.io/license
4165 */
4166const ERROR_TYPE = 'ngType';
4167const ERROR_DEBUG_CONTEXT = 'ngDebugContext';
4168const ERROR_ORIGINAL_ERROR = 'ngOriginalError';
4169const ERROR_LOGGER = 'ngErrorLogger';
4170function wrappedError(message, originalError) {
4171 const msg = `${message} caused by: ${originalError instanceof Error ? originalError.message : originalError}`;
4172 const error = Error(msg);
4173 error[ERROR_ORIGINAL_ERROR] = originalError;
4174 return error;
4175}
4176
4177/**
4178 * @license
4179 * Copyright Google LLC All Rights Reserved.
4180 *
4181 * Use of this source code is governed by an MIT-style license that can be
4182 * found in the LICENSE file at https://angular.io/license
4183 */
4184function getType(error) {
4185 return error[ERROR_TYPE];
4186}
4187function getDebugContext(error) {
4188 return error[ERROR_DEBUG_CONTEXT];
4189}
4190function getOriginalError(error) {
4191 return error[ERROR_ORIGINAL_ERROR];
4192}
4193function getErrorLogger(error) {
4194 return error[ERROR_LOGGER] || defaultErrorLogger;
4195}
4196function defaultErrorLogger(console, ...values) {
4197 console.error(...values);
4198}
4199
4200/**
4201 * @license
4202 * Copyright Google LLC All Rights Reserved.
4203 *
4204 * Use of this source code is governed by an MIT-style license that can be
4205 * found in the LICENSE file at https://angular.io/license
4206 */
4207/**
4208 * Provides a hook for centralized exception handling.
4209 *
4210 * The default implementation of `ErrorHandler` prints error messages to the `console`. To
4211 * intercept error handling, write a custom exception handler that replaces this default as
4212 * appropriate for your app.
4213 *
4214 * @usageNotes
4215 * ### Example
4216 *
4217 * ```
4218 * class MyErrorHandler implements ErrorHandler {
4219 * handleError(error) {
4220 * // do something with the exception
4221 * }
4222 * }
4223 *
4224 * @NgModule({
4225 * providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
4226 * })
4227 * class MyModule {}
4228 * ```
4229 *
4230 * @publicApi
4231 */
4232class ErrorHandler {
4233 constructor() {
4234 /**
4235 * @internal
4236 */
4237 this._console = console;
4238 }
4239 handleError(error) {
4240 const originalError = this._findOriginalError(error);
4241 const context = this._findContext(error);
4242 // Note: Browser consoles show the place from where console.error was called.
4243 // We can use this to give users additional information about the error.
4244 const errorLogger = getErrorLogger(error);
4245 errorLogger(this._console, `ERROR`, error);
4246 if (originalError) {
4247 errorLogger(this._console, `ORIGINAL ERROR`, originalError);
4248 }
4249 if (context) {
4250 errorLogger(this._console, 'ERROR CONTEXT', context);
4251 }
4252 }
4253 /** @internal */
4254 _findContext(error) {
4255 if (error) {
4256 return getDebugContext(error) ? getDebugContext(error) :
4257 this._findContext(getOriginalError(error));
4258 }
4259 return null;
4260 }
4261 /** @internal */
4262 _findOriginalError(error) {
4263 let e = getOriginalError(error);
4264 while (e && getOriginalError(e)) {
4265 e = getOriginalError(e);
4266 }
4267 return e;
4268 }
4269}
4270
4271/**
4272 * @license
4273 * Copyright Google LLC All Rights Reserved.
4274 *
4275 * Use of this source code is governed by an MIT-style license that can be
4276 * found in the LICENSE file at https://angular.io/license
4277 */
4278/**
4279 * Defines a schema that allows an NgModule to contain the following:
4280 * - Non-Angular elements named with dash case (`-`).
4281 * - Element properties named with dash case (`-`).
4282 * Dash case is the naming convention for custom elements.
4283 *
4284 * @publicApi
4285 */
4286const CUSTOM_ELEMENTS_SCHEMA = {
4287 name: 'custom-elements'
4288};
4289/**
4290 * Defines a schema that allows any property on any element.
4291 *
4292 * @publicApi
4293 */
4294const NO_ERRORS_SCHEMA = {
4295 name: 'no-errors-schema'
4296};
4297
4298/**
4299 * @license
4300 * Copyright Google LLC All Rights Reserved.
4301 *
4302 * Use of this source code is governed by an MIT-style license that can be
4303 * found in the LICENSE file at https://angular.io/license
4304 */
4305class SafeValueImpl {
4306 constructor(changingThisBreaksApplicationSecurity) {
4307 this.changingThisBreaksApplicationSecurity = changingThisBreaksApplicationSecurity;
4308 }
4309 toString() {
4310 return `SafeValue must use [property]=binding: ${this.changingThisBreaksApplicationSecurity}` +
4311 ` (see http://g.co/ng/security#xss)`;
4312 }
4313}
4314class SafeHtmlImpl extends SafeValueImpl {
4315 getTypeName() {
4316 return "HTML" /* Html */;
4317 }
4318}
4319class SafeStyleImpl extends SafeValueImpl {
4320 getTypeName() {
4321 return "Style" /* Style */;
4322 }
4323}
4324class SafeScriptImpl extends SafeValueImpl {
4325 getTypeName() {
4326 return "Script" /* Script */;
4327 }
4328}
4329class SafeUrlImpl extends SafeValueImpl {
4330 getTypeName() {
4331 return "URL" /* Url */;
4332 }
4333}
4334class SafeResourceUrlImpl extends SafeValueImpl {
4335 getTypeName() {
4336 return "ResourceURL" /* ResourceUrl */;
4337 }
4338}
4339function unwrapSafeValue(value) {
4340 return value instanceof SafeValueImpl ? value.changingThisBreaksApplicationSecurity :
4341 value;
4342}
4343function allowSanitizationBypassAndThrow(value, type) {
4344 const actualType = getSanitizationBypassType(value);
4345 if (actualType != null && actualType !== type) {
4346 // Allow ResourceURLs in URL contexts, they are strictly more trusted.
4347 if (actualType === "ResourceURL" /* ResourceUrl */ && type === "URL" /* Url */)
4348 return true;
4349 throw new Error(`Required a safe ${type}, got a ${actualType} (see http://g.co/ng/security#xss)`);
4350 }
4351 return actualType === type;
4352}
4353function getSanitizationBypassType(value) {
4354 return value instanceof SafeValueImpl && value.getTypeName() || null;
4355}
4356/**
4357 * Mark `html` string as trusted.
4358 *
4359 * This function wraps the trusted string in `String` and brands it in a way which makes it
4360 * recognizable to {@link htmlSanitizer} to be trusted implicitly.
4361 *
4362 * @param trustedHtml `html` string which needs to be implicitly trusted.
4363 * @returns a `html` which has been branded to be implicitly trusted.
4364 */
4365function bypassSanitizationTrustHtml(trustedHtml) {
4366 return new SafeHtmlImpl(trustedHtml);
4367}
4368/**
4369 * Mark `style` string as trusted.
4370 *
4371 * This function wraps the trusted string in `String` and brands it in a way which makes it
4372 * recognizable to {@link styleSanitizer} to be trusted implicitly.
4373 *
4374 * @param trustedStyle `style` string which needs to be implicitly trusted.
4375 * @returns a `style` hich has been branded to be implicitly trusted.
4376 */
4377function bypassSanitizationTrustStyle(trustedStyle) {
4378 return new SafeStyleImpl(trustedStyle);
4379}
4380/**
4381 * Mark `script` string as trusted.
4382 *
4383 * This function wraps the trusted string in `String` and brands it in a way which makes it
4384 * recognizable to {@link scriptSanitizer} to be trusted implicitly.
4385 *
4386 * @param trustedScript `script` string which needs to be implicitly trusted.
4387 * @returns a `script` which has been branded to be implicitly trusted.
4388 */
4389function bypassSanitizationTrustScript(trustedScript) {
4390 return new SafeScriptImpl(trustedScript);
4391}
4392/**
4393 * Mark `url` string as trusted.
4394 *
4395 * This function wraps the trusted string in `String` and brands it in a way which makes it
4396 * recognizable to {@link urlSanitizer} to be trusted implicitly.
4397 *
4398 * @param trustedUrl `url` string which needs to be implicitly trusted.
4399 * @returns a `url` which has been branded to be implicitly trusted.
4400 */
4401function bypassSanitizationTrustUrl(trustedUrl) {
4402 return new SafeUrlImpl(trustedUrl);
4403}
4404/**
4405 * Mark `url` string as trusted.
4406 *
4407 * This function wraps the trusted string in `String` and brands it in a way which makes it
4408 * recognizable to {@link resourceUrlSanitizer} to be trusted implicitly.
4409 *
4410 * @param trustedResourceUrl `url` string which needs to be implicitly trusted.
4411 * @returns a `url` which has been branded to be implicitly trusted.
4412 */
4413function bypassSanitizationTrustResourceUrl(trustedResourceUrl) {
4414 return new SafeResourceUrlImpl(trustedResourceUrl);
4415}
4416
4417/**
4418 * @license
4419 * Copyright Google LLC All Rights Reserved.
4420 *
4421 * Use of this source code is governed by an MIT-style license that can be
4422 * found in the LICENSE file at https://angular.io/license
4423 */
4424/**
4425 * This file is used to control if the default rendering pipeline should be `ViewEngine` or `Ivy`.
4426 *
4427 * For more information on how to run and debug tests with either Ivy or View Engine (legacy),
4428 * please see [BAZEL.md](./docs/BAZEL.md).
4429 */
4430let _devMode = true;
4431let _runModeLocked = false;
4432/**
4433 * Returns whether Angular is in development mode. After called once,
4434 * the value is locked and won't change any more.
4435 *
4436 * By default, this is true, unless a user calls `enableProdMode` before calling this.
4437 *
4438 * @publicApi
4439 */
4440function isDevMode() {
4441 _runModeLocked = true;
4442 return _devMode;
4443}
4444/**
4445 * Disable Angular's development mode, which turns off assertions and other
4446 * checks within the framework.
4447 *
4448 * One important assertion this disables verifies that a change detection pass
4449 * does not result in additional changes to any bindings (also known as
4450 * unidirectional data flow).
4451 *
4452 * @publicApi
4453 */
4454function enableProdMode() {
4455 if (_runModeLocked) {
4456 throw new Error('Cannot enable prod mode after platform setup.');
4457 }
4458 _devMode = false;
4459}
4460
4461/**
4462 * @license
4463 * Copyright Google LLC All Rights Reserved.
4464 *
4465 * Use of this source code is governed by an MIT-style license that can be
4466 * found in the LICENSE file at https://angular.io/license
4467 */
4468/**
4469 * This helper is used to get hold of an inert tree of DOM elements containing dirty HTML
4470 * that needs sanitizing.
4471 * Depending upon browser support we use one of two strategies for doing this.
4472 * Default: DOMParser strategy
4473 * Fallback: InertDocument strategy
4474 */
4475function getInertBodyHelper(defaultDoc) {
4476 return isDOMParserAvailable() ? new DOMParserHelper() : new InertDocumentHelper(defaultDoc);
4477}
4478/**
4479 * Uses DOMParser to create and fill an inert body element.
4480 * This is the default strategy used in browsers that support it.
4481 */
4482class DOMParserHelper {
4483 getInertBodyElement(html) {
4484 // We add these extra elements to ensure that the rest of the content is parsed as expected
4485 // e.g. leading whitespace is maintained and tags like `<meta>` do not get hoisted to the
4486 // `<head>` tag.
4487 html = '<body><remove></remove>' + html + '</body>';
4488 try {
4489 const body = new window.DOMParser().parseFromString(html, 'text/html').body;
4490 body.removeChild(body.firstChild);
4491 return body;
4492 }
4493 catch (_a) {
4494 return null;
4495 }
4496 }
4497}
4498/**
4499 * Use an HTML5 `template` element, if supported, or an inert body element created via
4500 * `createHtmlDocument` to create and fill an inert DOM element.
4501 * This is the fallback strategy if the browser does not support DOMParser.
4502 */
4503class InertDocumentHelper {
4504 constructor(defaultDoc) {
4505 this.defaultDoc = defaultDoc;
4506 this.inertDocument = this.defaultDoc.implementation.createHTMLDocument('sanitization-inert');
4507 if (this.inertDocument.body == null) {
4508 // usually there should be only one body element in the document, but IE doesn't have any, so
4509 // we need to create one.
4510 const inertHtml = this.inertDocument.createElement('html');
4511 this.inertDocument.appendChild(inertHtml);
4512 const inertBodyElement = this.inertDocument.createElement('body');
4513 inertHtml.appendChild(inertBodyElement);
4514 }
4515 }
4516 getInertBodyElement(html) {
4517 // Prefer using <template> element if supported.
4518 const templateEl = this.inertDocument.createElement('template');
4519 if ('content' in templateEl) {
4520 templateEl.innerHTML = html;
4521 return templateEl;
4522 }
4523 // Note that previously we used to do something like `this.inertDocument.body.innerHTML = html`
4524 // and we returned the inert `body` node. This was changed, because IE seems to treat setting
4525 // `innerHTML` on an inserted element differently, compared to one that hasn't been inserted
4526 // yet. In particular, IE appears to split some of the text into multiple text nodes rather
4527 // than keeping them in a single one which ends up messing with Ivy's i18n parsing further
4528 // down the line. This has been worked around by creating a new inert `body` and using it as
4529 // the root node in which we insert the HTML.
4530 const inertBody = this.inertDocument.createElement('body');
4531 inertBody.innerHTML = html;
4532 // Support: IE 9-11 only
4533 // strip custom-namespaced attributes on IE<=11
4534 if (this.defaultDoc.documentMode) {
4535 this.stripCustomNsAttrs(inertBody);
4536 }
4537 return inertBody;
4538 }
4539 /**
4540 * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1'
4541 * attribute to declare ns1 namespace and prefixes the attribute with 'ns1' (e.g.
4542 * 'ns1:xlink:foo').
4543 *
4544 * This is undesirable since we don't want to allow any of these custom attributes. This method
4545 * strips them all.
4546 */
4547 stripCustomNsAttrs(el) {
4548 const elAttrs = el.attributes;
4549 // loop backwards so that we can support removals.
4550 for (let i = elAttrs.length - 1; 0 < i; i--) {
4551 const attrib = elAttrs.item(i);
4552 const attrName = attrib.name;
4553 if (attrName === 'xmlns:ns1' || attrName.indexOf('ns1:') === 0) {
4554 el.removeAttribute(attrName);
4555 }
4556 }
4557 let childNode = el.firstChild;
4558 while (childNode) {
4559 if (childNode.nodeType === Node.ELEMENT_NODE)
4560 this.stripCustomNsAttrs(childNode);
4561 childNode = childNode.nextSibling;
4562 }
4563 }
4564}
4565/**
4566 * We need to determine whether the DOMParser exists in the global context and
4567 * supports parsing HTML; HTML parsing support is not as wide as other formats, see
4568 * https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Browser_compatibility.
4569 *
4570 * @suppress {uselessCode}
4571 */
4572function isDOMParserAvailable() {
4573 try {
4574 return !!new window.DOMParser().parseFromString('', 'text/html');
4575 }
4576 catch (_a) {
4577 return false;
4578 }
4579}
4580
4581/**
4582 * @license
4583 * Copyright Google LLC All Rights Reserved.
4584 *
4585 * Use of this source code is governed by an MIT-style license that can be
4586 * found in the LICENSE file at https://angular.io/license
4587 */
4588/**
4589 * A pattern that recognizes a commonly useful subset of URLs that are safe.
4590 *
4591 * This regular expression matches a subset of URLs that will not cause script
4592 * execution if used in URL context within a HTML document. Specifically, this
4593 * regular expression matches if (comment from here on and regex copied from
4594 * Soy's EscapingConventions):
4595 * (1) Either an allowed protocol (http, https, mailto or ftp).
4596 * (2) or no protocol. A protocol must be followed by a colon. The below
4597 * allows that by allowing colons only after one of the characters [/?#].
4598 * A colon after a hash (#) must be in the fragment.
4599 * Otherwise, a colon after a (?) must be in a query.
4600 * Otherwise, a colon after a single solidus (/) must be in a path.
4601 * Otherwise, a colon after a double solidus (//) must be in the authority
4602 * (before port).
4603 *
4604 * The pattern disallows &, used in HTML entity declarations before
4605 * one of the characters in [/?#]. This disallows HTML entities used in the
4606 * protocol name, which should never happen, e.g. "h&#116;tp" for "http".
4607 * It also disallows HTML entities in the first path part of a relative path,
4608 * e.g. "foo&lt;bar/baz". Our existing escaping functions should not produce
4609 * that. More importantly, it disallows masking of a colon,
4610 * e.g. "javascript&#58;...".
4611 *
4612 * This regular expression was taken from the Closure sanitization library.
4613 */
4614const SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi;
4615/* A pattern that matches safe srcset values */
4616const SAFE_SRCSET_PATTERN = /^(?:(?:https?|file):|[^&:/?#]*(?:[/?#]|$))/gi;
4617/** A pattern that matches safe data URLs. Only matches image, video and audio types. */
4618const DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+\/]+=*$/i;
4619function _sanitizeUrl(url) {
4620 url = String(url);
4621 if (url.match(SAFE_URL_PATTERN) || url.match(DATA_URL_PATTERN))
4622 return url;
4623 if (isDevMode()) {
4624 console.warn(`WARNING: sanitizing unsafe URL value ${url} (see http://g.co/ng/security#xss)`);
4625 }
4626 return 'unsafe:' + url;
4627}
4628function sanitizeSrcset(srcset) {
4629 srcset = String(srcset);
4630 return srcset.split(',').map((srcset) => _sanitizeUrl(srcset.trim())).join(', ');
4631}
4632
4633/**
4634 * @license
4635 * Copyright Google LLC All Rights Reserved.
4636 *
4637 * Use of this source code is governed by an MIT-style license that can be
4638 * found in the LICENSE file at https://angular.io/license
4639 */
4640function tagSet(tags) {
4641 const res = {};
4642 for (const t of tags.split(','))
4643 res[t] = true;
4644 return res;
4645}
4646function merge(...sets) {
4647 const res = {};
4648 for (const s of sets) {
4649 for (const v in s) {
4650 if (s.hasOwnProperty(v))
4651 res[v] = true;
4652 }
4653 }
4654 return res;
4655}
4656// Good source of info about elements and attributes
4657// http://dev.w3.org/html5/spec/Overview.html#semantics
4658// http://simon.html5.org/html-elements
4659// Safe Void Elements - HTML5
4660// http://dev.w3.org/html5/spec/Overview.html#void-elements
4661const VOID_ELEMENTS = tagSet('area,br,col,hr,img,wbr');
4662// Elements that you can, intentionally, leave open (and which close themselves)
4663// http://dev.w3.org/html5/spec/Overview.html#optional-tags
4664const OPTIONAL_END_TAG_BLOCK_ELEMENTS = tagSet('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr');
4665const OPTIONAL_END_TAG_INLINE_ELEMENTS = tagSet('rp,rt');
4666const OPTIONAL_END_TAG_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, OPTIONAL_END_TAG_BLOCK_ELEMENTS);
4667// Safe Block Elements - HTML5
4668const BLOCK_ELEMENTS = merge(OPTIONAL_END_TAG_BLOCK_ELEMENTS, tagSet('address,article,' +
4669 'aside,blockquote,caption,center,del,details,dialog,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' +
4670 'h6,header,hgroup,hr,ins,main,map,menu,nav,ol,pre,section,summary,table,ul'));
4671// Inline Elements - HTML5
4672const INLINE_ELEMENTS = merge(OPTIONAL_END_TAG_INLINE_ELEMENTS, tagSet('a,abbr,acronym,audio,b,' +
4673 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,picture,q,ruby,rp,rt,s,' +
4674 'samp,small,source,span,strike,strong,sub,sup,time,track,tt,u,var,video'));
4675const VALID_ELEMENTS = merge(VOID_ELEMENTS, BLOCK_ELEMENTS, INLINE_ELEMENTS, OPTIONAL_END_TAG_ELEMENTS);
4676// Attributes that have href and hence need to be sanitized
4677const URI_ATTRS = tagSet('background,cite,href,itemtype,longdesc,poster,src,xlink:href');
4678// Attributes that have special href set hence need to be sanitized
4679const SRCSET_ATTRS = tagSet('srcset');
4680const HTML_ATTRS = tagSet('abbr,accesskey,align,alt,autoplay,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,' +
4681 'compact,controls,coords,datetime,default,dir,download,face,headers,height,hidden,hreflang,hspace,' +
4682 'ismap,itemscope,itemprop,kind,label,lang,language,loop,media,muted,nohref,nowrap,open,preload,rel,rev,role,rows,rowspan,rules,' +
4683 'scope,scrolling,shape,size,sizes,span,srclang,start,summary,tabindex,target,title,translate,type,usemap,' +
4684 'valign,value,vspace,width');
4685// Accessibility attributes as per WAI-ARIA 1.1 (W3C Working Draft 14 December 2018)
4686const ARIA_ATTRS = tagSet('aria-activedescendant,aria-atomic,aria-autocomplete,aria-busy,aria-checked,aria-colcount,aria-colindex,' +
4687 'aria-colspan,aria-controls,aria-current,aria-describedby,aria-details,aria-disabled,aria-dropeffect,' +
4688 'aria-errormessage,aria-expanded,aria-flowto,aria-grabbed,aria-haspopup,aria-hidden,aria-invalid,' +
4689 'aria-keyshortcuts,aria-label,aria-labelledby,aria-level,aria-live,aria-modal,aria-multiline,' +
4690 'aria-multiselectable,aria-orientation,aria-owns,aria-placeholder,aria-posinset,aria-pressed,aria-readonly,' +
4691 'aria-relevant,aria-required,aria-roledescription,aria-rowcount,aria-rowindex,aria-rowspan,aria-selected,' +
4692 'aria-setsize,aria-sort,aria-valuemax,aria-valuemin,aria-valuenow,aria-valuetext');
4693// NB: This currently consciously doesn't support SVG. SVG sanitization has had several security
4694// issues in the past, so it seems safer to leave it out if possible. If support for binding SVG via
4695// innerHTML is required, SVG attributes should be added here.
4696// NB: Sanitization does not allow <form> elements or other active elements (<button> etc). Those
4697// can be sanitized, but they increase security surface area without a legitimate use case, so they
4698// are left out here.
4699const VALID_ATTRS = merge(URI_ATTRS, SRCSET_ATTRS, HTML_ATTRS, ARIA_ATTRS);
4700// Elements whose content should not be traversed/preserved, if the elements themselves are invalid.
4701//
4702// Typically, `<invalid>Some content</invalid>` would traverse (and in this case preserve)
4703// `Some content`, but strip `invalid-element` opening/closing tags. For some elements, though, we
4704// don't want to preserve the content, if the elements themselves are going to be removed.
4705const SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS = tagSet('script,style,template');
4706/**
4707 * SanitizingHtmlSerializer serializes a DOM fragment, stripping out any unsafe elements and unsafe
4708 * attributes.
4709 */
4710class SanitizingHtmlSerializer {
4711 constructor() {
4712 // Explicitly track if something was stripped, to avoid accidentally warning of sanitization just
4713 // because characters were re-encoded.
4714 this.sanitizedSomething = false;
4715 this.buf = [];
4716 }
4717 sanitizeChildren(el) {
4718 // This cannot use a TreeWalker, as it has to run on Angular's various DOM adapters.
4719 // However this code never accesses properties off of `document` before deleting its contents
4720 // again, so it shouldn't be vulnerable to DOM clobbering.
4721 let current = el.firstChild;
4722 let traverseContent = true;
4723 while (current) {
4724 if (current.nodeType === Node.ELEMENT_NODE) {
4725 traverseContent = this.startElement(current);
4726 }
4727 else if (current.nodeType === Node.TEXT_NODE) {
4728 this.chars(current.nodeValue);
4729 }
4730 else {
4731 // Strip non-element, non-text nodes.
4732 this.sanitizedSomething = true;
4733 }
4734 if (traverseContent && current.firstChild) {
4735 current = current.firstChild;
4736 continue;
4737 }
4738 while (current) {
4739 // Leaving the element. Walk up and to the right, closing tags as we go.
4740 if (current.nodeType === Node.ELEMENT_NODE) {
4741 this.endElement(current);
4742 }
4743 let next = this.checkClobberedElement(current, current.nextSibling);
4744 if (next) {
4745 current = next;
4746 break;
4747 }
4748 current = this.checkClobberedElement(current, current.parentNode);
4749 }
4750 }
4751 return this.buf.join('');
4752 }
4753 /**
4754 * Sanitizes an opening element tag (if valid) and returns whether the element's contents should
4755 * be traversed. Element content must always be traversed (even if the element itself is not
4756 * valid/safe), unless the element is one of `SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS`.
4757 *
4758 * @param element The element to sanitize.
4759 * @return True if the element's contents should be traversed.
4760 */
4761 startElement(element) {
4762 const tagName = element.nodeName.toLowerCase();
4763 if (!VALID_ELEMENTS.hasOwnProperty(tagName)) {
4764 this.sanitizedSomething = true;
4765 return !SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS.hasOwnProperty(tagName);
4766 }
4767 this.buf.push('<');
4768 this.buf.push(tagName);
4769 const elAttrs = element.attributes;
4770 for (let i = 0; i < elAttrs.length; i++) {
4771 const elAttr = elAttrs.item(i);
4772 const attrName = elAttr.name;
4773 const lower = attrName.toLowerCase();
4774 if (!VALID_ATTRS.hasOwnProperty(lower)) {
4775 this.sanitizedSomething = true;
4776 continue;
4777 }
4778 let value = elAttr.value;
4779 // TODO(martinprobst): Special case image URIs for data:image/...
4780 if (URI_ATTRS[lower])
4781 value = _sanitizeUrl(value);
4782 if (SRCSET_ATTRS[lower])
4783 value = sanitizeSrcset(value);
4784 this.buf.push(' ', attrName, '="', encodeEntities(value), '"');
4785 }
4786 this.buf.push('>');
4787 return true;
4788 }
4789 endElement(current) {
4790 const tagName = current.nodeName.toLowerCase();
4791 if (VALID_ELEMENTS.hasOwnProperty(tagName) && !VOID_ELEMENTS.hasOwnProperty(tagName)) {
4792 this.buf.push('</');
4793 this.buf.push(tagName);
4794 this.buf.push('>');
4795 }
4796 }
4797 chars(chars) {
4798 this.buf.push(encodeEntities(chars));
4799 }
4800 checkClobberedElement(node, nextNode) {
4801 if (nextNode &&
4802 (node.compareDocumentPosition(nextNode) &
4803 Node.DOCUMENT_POSITION_CONTAINED_BY) === Node.DOCUMENT_POSITION_CONTAINED_BY) {
4804 throw new Error(`Failed to sanitize html because the element is clobbered: ${node.outerHTML}`);
4805 }
4806 return nextNode;
4807 }
4808}
4809// Regular Expressions for parsing tags and attributes
4810const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
4811// ! to ~ is the ASCII range.
4812const NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g;
4813/**
4814 * Escapes all potentially dangerous characters, so that the
4815 * resulting string can be safely inserted into attribute or
4816 * element text.
4817 * @param value
4818 */
4819function encodeEntities(value) {
4820 return value.replace(/&/g, '&amp;')
4821 .replace(SURROGATE_PAIR_REGEXP, function (match) {
4822 const hi = match.charCodeAt(0);
4823 const low = match.charCodeAt(1);
4824 return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
4825 })
4826 .replace(NON_ALPHANUMERIC_REGEXP, function (match) {
4827 return '&#' + match.charCodeAt(0) + ';';
4828 })
4829 .replace(/</g, '&lt;')
4830 .replace(/>/g, '&gt;');
4831}
4832let inertBodyHelper;
4833/**
4834 * Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to
4835 * the DOM in a browser environment.
4836 */
4837function _sanitizeHtml(defaultDoc, unsafeHtmlInput) {
4838 let inertBodyElement = null;
4839 try {
4840 inertBodyHelper = inertBodyHelper || getInertBodyHelper(defaultDoc);
4841 // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).
4842 let unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : '';
4843 inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
4844 // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser
4845 // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous.
4846 let mXSSAttempts = 5;
4847 let parsedHtml = unsafeHtml;
4848 do {
4849 if (mXSSAttempts === 0) {
4850 throw new Error('Failed to sanitize html because the input is unstable');
4851 }
4852 mXSSAttempts--;
4853 unsafeHtml = parsedHtml;
4854 parsedHtml = inertBodyElement.innerHTML;
4855 inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
4856 } while (unsafeHtml !== parsedHtml);
4857 const sanitizer = new SanitizingHtmlSerializer();
4858 const safeHtml = sanitizer.sanitizeChildren(getTemplateContent(inertBodyElement) || inertBodyElement);
4859 if (isDevMode() && sanitizer.sanitizedSomething) {
4860 console.warn('WARNING: sanitizing HTML stripped some content, see http://g.co/ng/security#xss');
4861 }
4862 return safeHtml;
4863 }
4864 finally {
4865 // In case anything goes wrong, clear out inertElement to reset the entire DOM structure.
4866 if (inertBodyElement) {
4867 const parent = getTemplateContent(inertBodyElement) || inertBodyElement;
4868 while (parent.firstChild) {
4869 parent.removeChild(parent.firstChild);
4870 }
4871 }
4872 }
4873}
4874function getTemplateContent(el) {
4875 return 'content' in el /** Microsoft/TypeScript#21517 */ && isTemplateElement(el) ?
4876 el.content :
4877 null;
4878}
4879function isTemplateElement(el) {
4880 return el.nodeType === Node.ELEMENT_NODE && el.nodeName === 'TEMPLATE';
4881}
4882
4883/**
4884 * @license
4885 * Copyright Google LLC All Rights Reserved.
4886 *
4887 * Use of this source code is governed by an MIT-style license that can be
4888 * found in the LICENSE file at https://angular.io/license
4889 */
4890/**
4891 * A SecurityContext marks a location that has dangerous security implications, e.g. a DOM property
4892 * like `innerHTML` that could cause Cross Site Scripting (XSS) security bugs when improperly
4893 * handled.
4894 *
4895 * See DomSanitizer for more details on security in Angular applications.
4896 *
4897 * @publicApi
4898 */
4899var SecurityContext;
4900(function (SecurityContext) {
4901 SecurityContext[SecurityContext["NONE"] = 0] = "NONE";
4902 SecurityContext[SecurityContext["HTML"] = 1] = "HTML";
4903 SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE";
4904 SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT";
4905 SecurityContext[SecurityContext["URL"] = 4] = "URL";
4906 SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL";
4907})(SecurityContext || (SecurityContext = {}));
4908
4909/**
4910 * @license
4911 * Copyright Google LLC All Rights Reserved.
4912 *
4913 * Use of this source code is governed by an MIT-style license that can be
4914 * found in the LICENSE file at https://angular.io/license
4915 */
4916/**
4917 * An `html` sanitizer which converts untrusted `html` **string** into trusted string by removing
4918 * dangerous content.
4919 *
4920 * This method parses the `html` and locates potentially dangerous content (such as urls and
4921 * javascript) and removes it.
4922 *
4923 * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustHtml}.
4924 *
4925 * @param unsafeHtml untrusted `html`, typically from the user.
4926 * @returns `html` string which is safe to display to user, because all of the dangerous javascript
4927 * and urls have been removed.
4928 *
4929 * @codeGenApi
4930 */
4931function ɵɵsanitizeHtml(unsafeHtml) {
4932 const sanitizer = getSanitizer();
4933 if (sanitizer) {
4934 return sanitizer.sanitize(SecurityContext.HTML, unsafeHtml) || '';
4935 }
4936 if (allowSanitizationBypassAndThrow(unsafeHtml, "HTML" /* Html */)) {
4937 return unwrapSafeValue(unsafeHtml);
4938 }
4939 return _sanitizeHtml(getDocument(), renderStringify(unsafeHtml));
4940}
4941/**
4942 * A `style` sanitizer which converts untrusted `style` **string** into trusted string by removing
4943 * dangerous content.
4944 *
4945 * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustStyle}.
4946 *
4947 * @param unsafeStyle untrusted `style`, typically from the user.
4948 * @returns `style` string which is safe to bind to the `style` properties.
4949 *
4950 * @codeGenApi
4951 */
4952function ɵɵsanitizeStyle(unsafeStyle) {
4953 const sanitizer = getSanitizer();
4954 if (sanitizer) {
4955 return sanitizer.sanitize(SecurityContext.STYLE, unsafeStyle) || '';
4956 }
4957 if (allowSanitizationBypassAndThrow(unsafeStyle, "Style" /* Style */)) {
4958 return unwrapSafeValue(unsafeStyle);
4959 }
4960 return renderStringify(unsafeStyle);
4961}
4962/**
4963 * A `url` sanitizer which converts untrusted `url` **string** into trusted string by removing
4964 * dangerous
4965 * content.
4966 *
4967 * This method parses the `url` and locates potentially dangerous content (such as javascript) and
4968 * removes it.
4969 *
4970 * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustUrl}.
4971 *
4972 * @param unsafeUrl untrusted `url`, typically from the user.
4973 * @returns `url` string which is safe to bind to the `src` properties such as `<img src>`, because
4974 * all of the dangerous javascript has been removed.
4975 *
4976 * @codeGenApi
4977 */
4978function ɵɵsanitizeUrl(unsafeUrl) {
4979 const sanitizer = getSanitizer();
4980 if (sanitizer) {
4981 return sanitizer.sanitize(SecurityContext.URL, unsafeUrl) || '';
4982 }
4983 if (allowSanitizationBypassAndThrow(unsafeUrl, "URL" /* Url */)) {
4984 return unwrapSafeValue(unsafeUrl);
4985 }
4986 return _sanitizeUrl(renderStringify(unsafeUrl));
4987}
4988/**
4989 * A `url` sanitizer which only lets trusted `url`s through.
4990 *
4991 * This passes only `url`s marked trusted by calling {@link bypassSanitizationTrustResourceUrl}.
4992 *
4993 * @param unsafeResourceUrl untrusted `url`, typically from the user.
4994 * @returns `url` string which is safe to bind to the `src` properties such as `<img src>`, because
4995 * only trusted `url`s have been allowed to pass.
4996 *
4997 * @codeGenApi
4998 */
4999function ɵɵsanitizeResourceUrl(unsafeResourceUrl) {
5000 const sanitizer = getSanitizer();
5001 if (sanitizer) {
5002 return sanitizer.sanitize(SecurityContext.RESOURCE_URL, unsafeResourceUrl) || '';
5003 }
5004 if (allowSanitizationBypassAndThrow(unsafeResourceUrl, "ResourceURL" /* ResourceUrl */)) {
5005 return unwrapSafeValue(unsafeResourceUrl);
5006 }
5007 throw new Error('unsafe value used in a resource URL context (see http://g.co/ng/security#xss)');
5008}
5009/**
5010 * A `script` sanitizer which only lets trusted javascript through.
5011 *
5012 * This passes only `script`s marked trusted by calling {@link
5013 * bypassSanitizationTrustScript}.
5014 *
5015 * @param unsafeScript untrusted `script`, typically from the user.
5016 * @returns `url` string which is safe to bind to the `<script>` element such as `<img src>`,
5017 * because only trusted `scripts` have been allowed to pass.
5018 *
5019 * @codeGenApi
5020 */
5021function ɵɵsanitizeScript(unsafeScript) {
5022 const sanitizer = getSanitizer();
5023 if (sanitizer) {
5024 return sanitizer.sanitize(SecurityContext.SCRIPT, unsafeScript) || '';
5025 }
5026 if (allowSanitizationBypassAndThrow(unsafeScript, "Script" /* Script */)) {
5027 return unwrapSafeValue(unsafeScript);
5028 }
5029 throw new Error('unsafe value used in a script context');
5030}
5031/**
5032 * Detects which sanitizer to use for URL property, based on tag name and prop name.
5033 *
5034 * The rules are based on the RESOURCE_URL context config from
5035 * `packages/compiler/src/schema/dom_security_schema.ts`.
5036 * If tag and prop names don't match Resource URL schema, use URL sanitizer.
5037 */
5038function getUrlSanitizer(tag, prop) {
5039 if ((prop === 'src' &&
5040 (tag === 'embed' || tag === 'frame' || tag === 'iframe' || tag === 'media' ||
5041 tag === 'script')) ||
5042 (prop === 'href' && (tag === 'base' || tag === 'link'))) {
5043 return ɵɵsanitizeResourceUrl;
5044 }
5045 return ɵɵsanitizeUrl;
5046}
5047/**
5048 * Sanitizes URL, selecting sanitizer function based on tag and property names.
5049 *
5050 * This function is used in case we can't define security context at compile time, when only prop
5051 * name is available. This happens when we generate host bindings for Directives/Components. The
5052 * host element is unknown at compile time, so we defer calculation of specific sanitizer to
5053 * runtime.
5054 *
5055 * @param unsafeUrl untrusted `url`, typically from the user.
5056 * @param tag target element tag name.
5057 * @param prop name of the property that contains the value.
5058 * @returns `url` string which is safe to bind.
5059 *
5060 * @codeGenApi
5061 */
5062function ɵɵsanitizeUrlOrResourceUrl(unsafeUrl, tag, prop) {
5063 return getUrlSanitizer(tag, prop)(unsafeUrl);
5064}
5065function validateAgainstEventProperties(name) {
5066 if (name.toLowerCase().startsWith('on')) {
5067 const msg = `Binding to event property '${name}' is disallowed for security reasons, ` +
5068 `please use (${name.slice(2)})=...` +
5069 `\nIf '${name}' is a directive input, make sure the directive is imported by the` +
5070 ` current module.`;
5071 throw new Error(msg);
5072 }
5073}
5074function validateAgainstEventAttributes(name) {
5075 if (name.toLowerCase().startsWith('on')) {
5076 const msg = `Binding to event attribute '${name}' is disallowed for security reasons, ` +
5077 `please use (${name.slice(2)})=...`;
5078 throw new Error(msg);
5079 }
5080}
5081function getSanitizer() {
5082 const lView = getLView();
5083 return lView && lView[SANITIZER];
5084}
5085
5086/**
5087 * @license
5088 * Copyright Google LLC All Rights Reserved.
5089 *
5090 * Use of this source code is governed by an MIT-style license that can be
5091 * found in the LICENSE file at https://angular.io/license
5092 */
5093/**
5094 * THIS FILE CONTAINS CODE WHICH SHOULD BE TREE SHAKEN AND NEVER CALLED FROM PRODUCTION CODE!!!
5095 */
5096/**
5097 * Creates an `Array` construction with a given name. This is useful when
5098 * looking for memory consumption to see what time of array it is.
5099 *
5100 *
5101 * @param name Name to give to the constructor
5102 * @returns A subclass of `Array` if possible. This can only be done in
5103 * environments which support `class` construct.
5104 */
5105function createNamedArrayType(name) {
5106 // This should never be called in prod mode, so let's verify that is the case.
5107 if (ngDevMode) {
5108 try {
5109 // We need to do it this way so that TypeScript does not down-level the below code.
5110 const FunctionConstructor = createNamedArrayType.constructor;
5111 return (new FunctionConstructor('Array', `return class ${name} extends Array{}`))(Array);
5112 }
5113 catch (e) {
5114 // If it does not work just give up and fall back to regular Array.
5115 return Array;
5116 }
5117 }
5118 else {
5119 throw new Error('Looks like we are in \'prod mode\', but we are creating a named Array type, which is wrong! Check your code');
5120 }
5121}
5122
5123/**
5124 * @license
5125 * Copyright Google LLC All Rights Reserved.
5126 *
5127 * Use of this source code is governed by an MIT-style license that can be
5128 * found in the LICENSE file at https://angular.io/license
5129 */
5130function normalizeDebugBindingName(name) {
5131 // Attribute names with `$` (eg `x-y$`) are valid per spec, but unsupported by some browsers
5132 name = camelCaseToDashCase(name.replace(/[$@]/g, '_'));
5133 return `ng-reflect-${name}`;
5134}
5135const CAMEL_CASE_REGEXP = /([A-Z])/g;
5136function camelCaseToDashCase(input) {
5137 return input.replace(CAMEL_CASE_REGEXP, (...m) => '-' + m[1].toLowerCase());
5138}
5139function normalizeDebugBindingValue(value) {
5140 try {
5141 // Limit the size of the value as otherwise the DOM just gets polluted.
5142 return value != null ? value.toString().slice(0, 30) : value;
5143 }
5144 catch (e) {
5145 return '[ERROR] Exception while trying to serialize the value';
5146 }
5147}
5148
5149/**
5150 * @license
5151 * Copyright Google LLC All Rights Reserved.
5152 *
5153 * Use of this source code is governed by an MIT-style license that can be
5154 * found in the LICENSE file at https://angular.io/license
5155 */
5156/**
5157 * Returns the matching `LContext` data for a given DOM node, directive or component instance.
5158 *
5159 * This function will examine the provided DOM element, component, or directive instance\'s
5160 * monkey-patched property to derive the `LContext` data. Once called then the monkey-patched
5161 * value will be that of the newly created `LContext`.
5162 *
5163 * If the monkey-patched value is the `LView` instance then the context value for that
5164 * target will be created and the monkey-patch reference will be updated. Therefore when this
5165 * function is called it may mutate the provided element\'s, component\'s or any of the associated
5166 * directive\'s monkey-patch values.
5167 *
5168 * If the monkey-patch value is not detected then the code will walk up the DOM until an element
5169 * is found which contains a monkey-patch reference. When that occurs then the provided element
5170 * will be updated with a new context (which is then returned). If the monkey-patch value is not
5171 * detected for a component/directive instance then it will throw an error (all components and
5172 * directives should be automatically monkey-patched by ivy).
5173 *
5174 * @param target Component, Directive or DOM Node.
5175 */
5176function getLContext(target) {
5177 let mpValue = readPatchedData(target);
5178 if (mpValue) {
5179 // only when it's an array is it considered an LView instance
5180 // ... otherwise it's an already constructed LContext instance
5181 if (Array.isArray(mpValue)) {
5182 const lView = mpValue;
5183 let nodeIndex;
5184 let component = undefined;
5185 let directives = undefined;
5186 if (isComponentInstance(target)) {
5187 nodeIndex = findViaComponent(lView, target);
5188 if (nodeIndex == -1) {
5189 throw new Error('The provided component was not found in the application');
5190 }
5191 component = target;
5192 }
5193 else if (isDirectiveInstance(target)) {
5194 nodeIndex = findViaDirective(lView, target);
5195 if (nodeIndex == -1) {
5196 throw new Error('The provided directive was not found in the application');
5197 }
5198 directives = getDirectivesAtNodeIndex(nodeIndex, lView, false);
5199 }
5200 else {
5201 nodeIndex = findViaNativeElement(lView, target);
5202 if (nodeIndex == -1) {
5203 return null;
5204 }
5205 }
5206 // the goal is not to fill the entire context full of data because the lookups
5207 // are expensive. Instead, only the target data (the element, component, container, ICU
5208 // expression or directive details) are filled into the context. If called multiple times
5209 // with different target values then the missing target data will be filled in.
5210 const native = unwrapRNode(lView[nodeIndex]);
5211 const existingCtx = readPatchedData(native);
5212 const context = (existingCtx && !Array.isArray(existingCtx)) ?
5213 existingCtx :
5214 createLContext(lView, nodeIndex, native);
5215 // only when the component has been discovered then update the monkey-patch
5216 if (component && context.component === undefined) {
5217 context.component = component;
5218 attachPatchData(context.component, context);
5219 }
5220 // only when the directives have been discovered then update the monkey-patch
5221 if (directives && context.directives === undefined) {
5222 context.directives = directives;
5223 for (let i = 0; i < directives.length; i++) {
5224 attachPatchData(directives[i], context);
5225 }
5226 }
5227 attachPatchData(context.native, context);
5228 mpValue = context;
5229 }
5230 }
5231 else {
5232 const rElement = target;
5233 ngDevMode && assertDomNode(rElement);
5234 // if the context is not found then we need to traverse upwards up the DOM
5235 // to find the nearest element that has already been monkey patched with data
5236 let parent = rElement;
5237 while (parent = parent.parentNode) {
5238 const parentContext = readPatchedData(parent);
5239 if (parentContext) {
5240 let lView;
5241 if (Array.isArray(parentContext)) {
5242 lView = parentContext;
5243 }
5244 else {
5245 lView = parentContext.lView;
5246 }
5247 // the edge of the app was also reached here through another means
5248 // (maybe because the DOM was changed manually).
5249 if (!lView) {
5250 return null;
5251 }
5252 const index = findViaNativeElement(lView, rElement);
5253 if (index >= 0) {
5254 const native = unwrapRNode(lView[index]);
5255 const context = createLContext(lView, index, native);
5256 attachPatchData(native, context);
5257 mpValue = context;
5258 break;
5259 }
5260 }
5261 }
5262 }
5263 return mpValue || null;
5264}
5265/**
5266 * Creates an empty instance of a `LContext` context
5267 */
5268function createLContext(lView, nodeIndex, native) {
5269 return {
5270 lView,
5271 nodeIndex,
5272 native,
5273 component: undefined,
5274 directives: undefined,
5275 localRefs: undefined,
5276 };
5277}
5278/**
5279 * Takes a component instance and returns the view for that component.
5280 *
5281 * @param componentInstance
5282 * @returns The component's view
5283 */
5284function getComponentViewByInstance(componentInstance) {
5285 let lView = readPatchedData(componentInstance);
5286 let view;
5287 if (Array.isArray(lView)) {
5288 const nodeIndex = findViaComponent(lView, componentInstance);
5289 view = getComponentLViewByIndex(nodeIndex, lView);
5290 const context = createLContext(lView, nodeIndex, view[HOST]);
5291 context.component = componentInstance;
5292 attachPatchData(componentInstance, context);
5293 attachPatchData(context.native, context);
5294 }
5295 else {
5296 const context = lView;
5297 view = getComponentLViewByIndex(context.nodeIndex, context.lView);
5298 }
5299 return view;
5300}
5301/**
5302 * Assigns the given data to the given target (which could be a component,
5303 * directive or DOM node instance) using monkey-patching.
5304 */
5305function attachPatchData(target, data) {
5306 target[MONKEY_PATCH_KEY_NAME] = data;
5307}
5308function isComponentInstance(instance) {
5309 return instance && instance.constructor && instance.constructor.ɵcmp;
5310}
5311function isDirectiveInstance(instance) {
5312 return instance && instance.constructor && instance.constructor.ɵdir;
5313}
5314/**
5315 * Locates the element within the given LView and returns the matching index
5316 */
5317function findViaNativeElement(lView, target) {
5318 let tNode = lView[TVIEW].firstChild;
5319 while (tNode) {
5320 const native = getNativeByTNodeOrNull(tNode, lView);
5321 if (native === target) {
5322 return tNode.index;
5323 }
5324 tNode = traverseNextElement(tNode);
5325 }
5326 return -1;
5327}
5328/**
5329 * Locates the next tNode (child, sibling or parent).
5330 */
5331function traverseNextElement(tNode) {
5332 if (tNode.child) {
5333 return tNode.child;
5334 }
5335 else if (tNode.next) {
5336 return tNode.next;
5337 }
5338 else {
5339 // Let's take the following template: <div><span>text</span></div><component/>
5340 // After checking the text node, we need to find the next parent that has a "next" TNode,
5341 // in this case the parent `div`, so that we can find the component.
5342 while (tNode.parent && !tNode.parent.next) {
5343 tNode = tNode.parent;
5344 }
5345 return tNode.parent && tNode.parent.next;
5346 }
5347}
5348/**
5349 * Locates the component within the given LView and returns the matching index
5350 */
5351function findViaComponent(lView, componentInstance) {
5352 const componentIndices = lView[TVIEW].components;
5353 if (componentIndices) {
5354 for (let i = 0; i < componentIndices.length; i++) {
5355 const elementComponentIndex = componentIndices[i];
5356 const componentView = getComponentLViewByIndex(elementComponentIndex, lView);
5357 if (componentView[CONTEXT] === componentInstance) {
5358 return elementComponentIndex;
5359 }
5360 }
5361 }
5362 else {
5363 const rootComponentView = getComponentLViewByIndex(HEADER_OFFSET, lView);
5364 const rootComponent = rootComponentView[CONTEXT];
5365 if (rootComponent === componentInstance) {
5366 // we are dealing with the root element here therefore we know that the
5367 // element is the very first element after the HEADER data in the lView
5368 return HEADER_OFFSET;
5369 }
5370 }
5371 return -1;
5372}
5373/**
5374 * Locates the directive within the given LView and returns the matching index
5375 */
5376function findViaDirective(lView, directiveInstance) {
5377 // if a directive is monkey patched then it will (by default)
5378 // have a reference to the LView of the current view. The
5379 // element bound to the directive being search lives somewhere
5380 // in the view data. We loop through the nodes and check their
5381 // list of directives for the instance.
5382 let tNode = lView[TVIEW].firstChild;
5383 while (tNode) {
5384 const directiveIndexStart = tNode.directiveStart;
5385 const directiveIndexEnd = tNode.directiveEnd;
5386 for (let i = directiveIndexStart; i < directiveIndexEnd; i++) {
5387 if (lView[i] === directiveInstance) {
5388 return tNode.index;
5389 }
5390 }
5391 tNode = traverseNextElement(tNode);
5392 }
5393 return -1;
5394}
5395/**
5396 * Returns a list of directives extracted from the given view based on the
5397 * provided list of directive index values.
5398 *
5399 * @param nodeIndex The node index
5400 * @param lView The target view data
5401 * @param includeComponents Whether or not to include components in returned directives
5402 */
5403function getDirectivesAtNodeIndex(nodeIndex, lView, includeComponents) {
5404 const tNode = lView[TVIEW].data[nodeIndex];
5405 let directiveStartIndex = tNode.directiveStart;
5406 if (directiveStartIndex == 0)
5407 return EMPTY_ARRAY;
5408 const directiveEndIndex = tNode.directiveEnd;
5409 if (!includeComponents && tNode.flags & 2 /* isComponentHost */)
5410 directiveStartIndex++;
5411 return lView.slice(directiveStartIndex, directiveEndIndex);
5412}
5413function getComponentAtNodeIndex(nodeIndex, lView) {
5414 const tNode = lView[TVIEW].data[nodeIndex];
5415 let directiveStartIndex = tNode.directiveStart;
5416 return tNode.flags & 2 /* isComponentHost */ ? lView[directiveStartIndex] : null;
5417}
5418/**
5419 * Returns a map of local references (local reference name => element or directive instance) that
5420 * exist on a given element.
5421 */
5422function discoverLocalRefs(lView, nodeIndex) {
5423 const tNode = lView[TVIEW].data[nodeIndex];
5424 if (tNode && tNode.localNames) {
5425 const result = {};
5426 let localIndex = tNode.index + 1;
5427 for (let i = 0; i < tNode.localNames.length; i += 2) {
5428 result[tNode.localNames[i]] = lView[localIndex];
5429 localIndex++;
5430 }
5431 return result;
5432 }
5433 return null;
5434}
5435
5436/** Called when directives inject each other (creating a circular dependency) */
5437function throwCyclicDependencyError(token) {
5438 throw new Error(`Cannot instantiate cyclic dependency! ${token}`);
5439}
5440/** Called when there are multiple component selectors that match a given node */
5441function throwMultipleComponentError(tNode) {
5442 throw new Error(`Multiple components match node with tagname ${tNode.tagName}`);
5443}
5444function throwMixedMultiProviderError() {
5445 throw new Error(`Cannot mix multi providers and regular providers`);
5446}
5447function throwInvalidProviderError(ngModuleType, providers, provider) {
5448 let ngModuleDetail = '';
5449 if (ngModuleType && providers) {
5450 const providerDetail = providers.map(v => v == provider ? '?' + provider + '?' : '...');
5451 ngModuleDetail =
5452 ` - only instances of Provider and Type are allowed, got: [${providerDetail.join(', ')}]`;
5453 }
5454 throw new Error(`Invalid provider for the NgModule '${stringify(ngModuleType)}'` + ngModuleDetail);
5455}
5456/** Throws an ExpressionChangedAfterChecked error if checkNoChanges mode is on. */
5457function throwErrorIfNoChangesMode(creationMode, oldValue, currValue, propName) {
5458 const field = propName ? ` for '${propName}'` : '';
5459 let msg = `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value${field}: '${oldValue}'. Current value: '${currValue}'.`;
5460 if (creationMode) {
5461 msg +=
5462 ` It seems like the view has been created after its parent and its children have been dirty checked.` +
5463 ` Has it been created in a change detection hook?`;
5464 }
5465 // TODO: include debug context, see `viewDebugError` function in
5466 // `packages/core/src/view/errors.ts` for reference.
5467 throw new Error(msg);
5468}
5469function constructDetailsForInterpolation(lView, rootIndex, expressionIndex, meta, changedValue) {
5470 const [propName, prefix, ...chunks] = meta.split(INTERPOLATION_DELIMITER);
5471 let oldValue = prefix, newValue = prefix;
5472 for (let i = 0; i < chunks.length; i++) {
5473 const slotIdx = rootIndex + i;
5474 oldValue += `${lView[slotIdx]}${chunks[i]}`;
5475 newValue += `${slotIdx === expressionIndex ? changedValue : lView[slotIdx]}${chunks[i]}`;
5476 }
5477 return { propName, oldValue, newValue };
5478}
5479/**
5480 * Constructs an object that contains details for the ExpressionChangedAfterItHasBeenCheckedError:
5481 * - property name (for property bindings or interpolations)
5482 * - old and new values, enriched using information from metadata
5483 *
5484 * More information on the metadata storage format can be found in `storePropertyBindingMetadata`
5485 * function description.
5486 */
5487function getExpressionChangedErrorDetails(lView, bindingIndex, oldValue, newValue) {
5488 const tData = lView[TVIEW].data;
5489 const metadata = tData[bindingIndex];
5490 if (typeof metadata === 'string') {
5491 // metadata for property interpolation
5492 if (metadata.indexOf(INTERPOLATION_DELIMITER) > -1) {
5493 return constructDetailsForInterpolation(lView, bindingIndex, bindingIndex, metadata, newValue);
5494 }
5495 // metadata for property binding
5496 return { propName: metadata, oldValue, newValue };
5497 }
5498 // metadata is not available for this expression, check if this expression is a part of the
5499 // property interpolation by going from the current binding index left and look for a string that
5500 // contains INTERPOLATION_DELIMITER, the layout in tView.data for this case will look like this:
5501 // [..., 'id�Prefix � and � suffix', null, null, null, ...]
5502 if (metadata === null) {
5503 let idx = bindingIndex - 1;
5504 while (typeof tData[idx] !== 'string' && tData[idx + 1] === null) {
5505 idx--;
5506 }
5507 const meta = tData[idx];
5508 if (typeof meta === 'string') {
5509 const matches = meta.match(new RegExp(INTERPOLATION_DELIMITER, 'g'));
5510 // first interpolation delimiter separates property name from interpolation parts (in case of
5511 // property interpolations), so we subtract one from total number of found delimiters
5512 if (matches && (matches.length - 1) > bindingIndex - idx) {
5513 return constructDetailsForInterpolation(lView, idx, bindingIndex, meta, newValue);
5514 }
5515 }
5516 }
5517 return { propName: undefined, oldValue, newValue };
5518}
5519
5520/**
5521 * Converts `TNodeType` into human readable text.
5522 * Make sure this matches with `TNodeType`
5523 */
5524const TNodeTypeAsString = [
5525 'Container',
5526 'Projection',
5527 'View',
5528 'Element',
5529 'ElementContainer',
5530 'IcuContainer' // 5
5531];
5532// Note: This hack is necessary so we don't erroneously get a circular dependency
5533// failure based on types.
5534const unusedValueExportToPlacateAjd$4 = 1;
5535/**
5536 * Returns `true` if the `TNode` has a directive which has `@Input()` for `class` binding.
5537 *
5538 * ```
5539 * <div my-dir [class]="exp"></div>
5540 * ```
5541 * and
5542 * ```
5543 * @Directive({
5544 * })
5545 * class MyDirective {
5546 * @Input()
5547 * class: string;
5548 * }
5549 * ```
5550 *
5551 * In the above case it is necessary to write the reconciled styling information into the
5552 * directive's input.
5553 *
5554 * @param tNode
5555 */
5556function hasClassInput(tNode) {
5557 return (tNode.flags & 16 /* hasClassInput */) !== 0;
5558}
5559/**
5560 * Returns `true` if the `TNode` has a directive which has `@Input()` for `style` binding.
5561 *
5562 * ```
5563 * <div my-dir [style]="exp"></div>
5564 * ```
5565 * and
5566 * ```
5567 * @Directive({
5568 * })
5569 * class MyDirective {
5570 * @Input()
5571 * class: string;
5572 * }
5573 * ```
5574 *
5575 * In the above case it is necessary to write the reconciled styling information into the
5576 * directive's input.
5577 *
5578 * @param tNode
5579 */
5580function hasStyleInput(tNode) {
5581 return (tNode.flags & 32 /* hasStyleInput */) !== 0;
5582}
5583
5584/**
5585 * @license
5586 * Copyright Google LLC All Rights Reserved.
5587 *
5588 * Use of this source code is governed by an MIT-style license that can be
5589 * found in the LICENSE file at https://angular.io/license
5590 */
5591// Note: This hack is necessary so we don't erroneously get a circular dependency
5592// failure based on types.
5593const unusedValueExportToPlacateAjd$5 = 1;
5594
5595/**
5596 * @license
5597 * Copyright Google LLC All Rights Reserved.
5598 *
5599 * Use of this source code is governed by an MIT-style license that can be
5600 * found in the LICENSE file at https://angular.io/license
5601 */
5602/**
5603 * Returns an index of `classToSearch` in `className` taking token boundaries into account.
5604 *
5605 * `classIndexOf('AB A', 'A', 0)` will be 3 (not 0 since `AB!==A`)
5606 *
5607 * @param className A string containing classes (whitespace separated)
5608 * @param classToSearch A class name to locate
5609 * @param startingIndex Starting location of search
5610 * @returns an index of the located class (or -1 if not found)
5611 */
5612function classIndexOf(className, classToSearch, startingIndex) {
5613 ngDevMode && assertNotEqual(classToSearch, '', 'can not look for "" string.');
5614 let end = className.length;
5615 while (true) {
5616 const foundIndex = className.indexOf(classToSearch, startingIndex);
5617 if (foundIndex === -1)
5618 return foundIndex;
5619 if (foundIndex === 0 || className.charCodeAt(foundIndex - 1) <= 32 /* SPACE */) {
5620 // Ensure that it has leading whitespace
5621 const length = classToSearch.length;
5622 if (foundIndex + length === end ||
5623 className.charCodeAt(foundIndex + length) <= 32 /* SPACE */) {
5624 // Ensure that it has trailing whitespace
5625 return foundIndex;
5626 }
5627 }
5628 // False positive, keep searching from where we left off.
5629 startingIndex = foundIndex + 1;
5630 }
5631}
5632
5633/**
5634 * @license
5635 * Copyright Google LLC All Rights Reserved.
5636 *
5637 * Use of this source code is governed by an MIT-style license that can be
5638 * found in the LICENSE file at https://angular.io/license
5639 */
5640const unusedValueToPlacateAjd = unusedValueExportToPlacateAjd$4 + unusedValueExportToPlacateAjd$5;
5641const NG_TEMPLATE_SELECTOR = 'ng-template';
5642/**
5643 * Search the `TAttributes` to see if it contains `cssClassToMatch` (case insensitive)
5644 *
5645 * @param attrs `TAttributes` to search through.
5646 * @param cssClassToMatch class to match (lowercase)
5647 * @param isProjectionMode Whether or not class matching should look into the attribute `class` in
5648 * addition to the `AttributeMarker.Classes`.
5649 */
5650function isCssClassMatching(attrs, cssClassToMatch, isProjectionMode) {
5651 // TODO(misko): The fact that this function needs to know about `isProjectionMode` seems suspect.
5652 // It is strange to me that sometimes the class information comes in form of `class` attribute
5653 // and sometimes in form of `AttributeMarker.Classes`. Some investigation is needed to determine
5654 // if that is the right behavior.
5655 ngDevMode &&
5656 assertEqual(cssClassToMatch, cssClassToMatch.toLowerCase(), 'Class name expected to be lowercase.');
5657 let i = 0;
5658 while (i < attrs.length) {
5659 let item = attrs[i++];
5660 if (isProjectionMode && item === 'class') {
5661 item = attrs[i];
5662 if (classIndexOf(item.toLowerCase(), cssClassToMatch, 0) !== -1) {
5663 return true;
5664 }
5665 }
5666 else if (item === 1 /* Classes */) {
5667 // We found the classes section. Start searching for the class.
5668 while (i < attrs.length && typeof (item = attrs[i++]) == 'string') {
5669 // while we have strings
5670 if (item.toLowerCase() === cssClassToMatch)
5671 return true;
5672 }
5673 return false;
5674 }
5675 }
5676 return false;
5677}
5678/**
5679 * Checks whether the `tNode` represents an inline template (e.g. `*ngFor`).
5680 *
5681 * @param tNode current TNode
5682 */
5683function isInlineTemplate(tNode) {
5684 return tNode.type === 0 /* Container */ && tNode.tagName !== NG_TEMPLATE_SELECTOR;
5685}
5686/**
5687 * Function that checks whether a given tNode matches tag-based selector and has a valid type.
5688 *
5689 * Matching can be performed in 2 modes: projection mode (when we project nodes) and regular
5690 * directive matching mode:
5691 * - in the "directive matching" mode we do _not_ take TContainer's tagName into account if it is
5692 * different from NG_TEMPLATE_SELECTOR (value different from NG_TEMPLATE_SELECTOR indicates that a
5693 * tag name was extracted from * syntax so we would match the same directive twice);
5694 * - in the "projection" mode, we use a tag name potentially extracted from the * syntax processing
5695 * (applicable to TNodeType.Container only).
5696 */
5697function hasTagAndTypeMatch(tNode, currentSelector, isProjectionMode) {
5698 const tagNameToCompare = tNode.type === 0 /* Container */ && !isProjectionMode ?
5699 NG_TEMPLATE_SELECTOR :
5700 tNode.tagName;
5701 return currentSelector === tagNameToCompare;
5702}
5703/**
5704 * A utility function to match an Ivy node static data against a simple CSS selector
5705 *
5706 * @param node static data of the node to match
5707 * @param selector The selector to try matching against the node.
5708 * @param isProjectionMode if `true` we are matching for content projection, otherwise we are doing
5709 * directive matching.
5710 * @returns true if node matches the selector.
5711 */
5712function isNodeMatchingSelector(tNode, selector, isProjectionMode) {
5713 ngDevMode && assertDefined(selector[0], 'Selector should have a tag name');
5714 let mode = 4 /* ELEMENT */;
5715 const nodeAttrs = tNode.attrs || [];
5716 // Find the index of first attribute that has no value, only a name.
5717 const nameOnlyMarkerIdx = getNameOnlyMarkerIndex(nodeAttrs);
5718 // When processing ":not" selectors, we skip to the next ":not" if the
5719 // current one doesn't match
5720 let skipToNextSelector = false;
5721 for (let i = 0; i < selector.length; i++) {
5722 const current = selector[i];
5723 if (typeof current === 'number') {
5724 // If we finish processing a :not selector and it hasn't failed, return false
5725 if (!skipToNextSelector && !isPositive(mode) && !isPositive(current)) {
5726 return false;
5727 }
5728 // If we are skipping to the next :not() and this mode flag is positive,
5729 // it's a part of the current :not() selector, and we should keep skipping
5730 if (skipToNextSelector && isPositive(current))
5731 continue;
5732 skipToNextSelector = false;
5733 mode = current | (mode & 1 /* NOT */);
5734 continue;
5735 }
5736 if (skipToNextSelector)
5737 continue;
5738 if (mode & 4 /* ELEMENT */) {
5739 mode = 2 /* ATTRIBUTE */ | mode & 1 /* NOT */;
5740 if (current !== '' && !hasTagAndTypeMatch(tNode, current, isProjectionMode) ||
5741 current === '' && selector.length === 1) {
5742 if (isPositive(mode))
5743 return false;
5744 skipToNextSelector = true;
5745 }
5746 }
5747 else {
5748 const selectorAttrValue = mode & 8 /* CLASS */ ? current : selector[++i];
5749 // special case for matching against classes when a tNode has been instantiated with
5750 // class and style values as separate attribute values (e.g. ['title', CLASS, 'foo'])
5751 if ((mode & 8 /* CLASS */) && tNode.attrs !== null) {
5752 if (!isCssClassMatching(tNode.attrs, selectorAttrValue, isProjectionMode)) {
5753 if (isPositive(mode))
5754 return false;
5755 skipToNextSelector = true;
5756 }
5757 continue;
5758 }
5759 const attrName = (mode & 8 /* CLASS */) ? 'class' : current;
5760 const attrIndexInNode = findAttrIndexInNode(attrName, nodeAttrs, isInlineTemplate(tNode), isProjectionMode);
5761 if (attrIndexInNode === -1) {
5762 if (isPositive(mode))
5763 return false;
5764 skipToNextSelector = true;
5765 continue;
5766 }
5767 if (selectorAttrValue !== '') {
5768 let nodeAttrValue;
5769 if (attrIndexInNode > nameOnlyMarkerIdx) {
5770 nodeAttrValue = '';
5771 }
5772 else {
5773 ngDevMode &&
5774 assertNotEqual(nodeAttrs[attrIndexInNode], 0 /* NamespaceURI */, 'We do not match directives on namespaced attributes');
5775 // we lowercase the attribute value to be able to match
5776 // selectors without case-sensitivity
5777 // (selectors are already in lowercase when generated)
5778 nodeAttrValue = nodeAttrs[attrIndexInNode + 1].toLowerCase();
5779 }
5780 const compareAgainstClassName = mode & 8 /* CLASS */ ? nodeAttrValue : null;
5781 if (compareAgainstClassName &&
5782 classIndexOf(compareAgainstClassName, selectorAttrValue, 0) !== -1 ||
5783 mode & 2 /* ATTRIBUTE */ && selectorAttrValue !== nodeAttrValue) {
5784 if (isPositive(mode))
5785 return false;
5786 skipToNextSelector = true;
5787 }
5788 }
5789 }
5790 }
5791 return isPositive(mode) || skipToNextSelector;
5792}
5793function isPositive(mode) {
5794 return (mode & 1 /* NOT */) === 0;
5795}
5796/**
5797 * Examines the attribute's definition array for a node to find the index of the
5798 * attribute that matches the given `name`.
5799 *
5800 * NOTE: This will not match namespaced attributes.
5801 *
5802 * Attribute matching depends upon `isInlineTemplate` and `isProjectionMode`.
5803 * The following table summarizes which types of attributes we attempt to match:
5804 *
5805 * ===========================================================================================================
5806 * Modes | Normal Attributes | Bindings Attributes | Template Attributes | I18n
5807 * Attributes
5808 * ===========================================================================================================
5809 * Inline + Projection | YES | YES | NO | YES
5810 * -----------------------------------------------------------------------------------------------------------
5811 * Inline + Directive | NO | NO | YES | NO
5812 * -----------------------------------------------------------------------------------------------------------
5813 * Non-inline + Projection | YES | YES | NO | YES
5814 * -----------------------------------------------------------------------------------------------------------
5815 * Non-inline + Directive | YES | YES | NO | YES
5816 * ===========================================================================================================
5817 *
5818 * @param name the name of the attribute to find
5819 * @param attrs the attribute array to examine
5820 * @param isInlineTemplate true if the node being matched is an inline template (e.g. `*ngFor`)
5821 * rather than a manually expanded template node (e.g `<ng-template>`).
5822 * @param isProjectionMode true if we are matching against content projection otherwise we are
5823 * matching against directives.
5824 */
5825function findAttrIndexInNode(name, attrs, isInlineTemplate, isProjectionMode) {
5826 if (attrs === null)
5827 return -1;
5828 let i = 0;
5829 if (isProjectionMode || !isInlineTemplate) {
5830 let bindingsMode = false;
5831 while (i < attrs.length) {
5832 const maybeAttrName = attrs[i];
5833 if (maybeAttrName === name) {
5834 return i;
5835 }
5836 else if (maybeAttrName === 3 /* Bindings */ || maybeAttrName === 6 /* I18n */) {
5837 bindingsMode = true;
5838 }
5839 else if (maybeAttrName === 1 /* Classes */ || maybeAttrName === 2 /* Styles */) {
5840 let value = attrs[++i];
5841 // We should skip classes here because we have a separate mechanism for
5842 // matching classes in projection mode.
5843 while (typeof value === 'string') {
5844 value = attrs[++i];
5845 }
5846 continue;
5847 }
5848 else if (maybeAttrName === 4 /* Template */) {
5849 // We do not care about Template attributes in this scenario.
5850 break;
5851 }
5852 else if (maybeAttrName === 0 /* NamespaceURI */) {
5853 // Skip the whole namespaced attribute and value. This is by design.
5854 i += 4;
5855 continue;
5856 }
5857 // In binding mode there are only names, rather than name-value pairs.
5858 i += bindingsMode ? 1 : 2;
5859 }
5860 // We did not match the attribute
5861 return -1;
5862 }
5863 else {
5864 return matchTemplateAttribute(attrs, name);
5865 }
5866}
5867function isNodeMatchingSelectorList(tNode, selector, isProjectionMode = false) {
5868 for (let i = 0; i < selector.length; i++) {
5869 if (isNodeMatchingSelector(tNode, selector[i], isProjectionMode)) {
5870 return true;
5871 }
5872 }
5873 return false;
5874}
5875function getProjectAsAttrValue(tNode) {
5876 const nodeAttrs = tNode.attrs;
5877 if (nodeAttrs != null) {
5878 const ngProjectAsAttrIdx = nodeAttrs.indexOf(5 /* ProjectAs */);
5879 // only check for ngProjectAs in attribute names, don't accidentally match attribute's value
5880 // (attribute names are stored at even indexes)
5881 if ((ngProjectAsAttrIdx & 1) === 0) {
5882 return nodeAttrs[ngProjectAsAttrIdx + 1];
5883 }
5884 }
5885 return null;
5886}
5887function getNameOnlyMarkerIndex(nodeAttrs) {
5888 for (let i = 0; i < nodeAttrs.length; i++) {
5889 const nodeAttr = nodeAttrs[i];
5890 if (isNameOnlyAttributeMarker(nodeAttr)) {
5891 return i;
5892 }
5893 }
5894 return nodeAttrs.length;
5895}
5896function matchTemplateAttribute(attrs, name) {
5897 let i = attrs.indexOf(4 /* Template */);
5898 if (i > -1) {
5899 i++;
5900 while (i < attrs.length) {
5901 const attr = attrs[i];
5902 // Return in case we checked all template attrs and are switching to the next section in the
5903 // attrs array (that starts with a number that represents an attribute marker).
5904 if (typeof attr === 'number')
5905 return -1;
5906 if (attr === name)
5907 return i;
5908 i++;
5909 }
5910 }
5911 return -1;
5912}
5913/**
5914 * Checks whether a selector is inside a CssSelectorList
5915 * @param selector Selector to be checked.
5916 * @param list List in which to look for the selector.
5917 */
5918function isSelectorInSelectorList(selector, list) {
5919 selectorListLoop: for (let i = 0; i < list.length; i++) {
5920 const currentSelectorInList = list[i];
5921 if (selector.length !== currentSelectorInList.length) {
5922 continue;
5923 }
5924 for (let j = 0; j < selector.length; j++) {
5925 if (selector[j] !== currentSelectorInList[j]) {
5926 continue selectorListLoop;
5927 }
5928 }
5929 return true;
5930 }
5931 return false;
5932}
5933function maybeWrapInNotSelector(isNegativeMode, chunk) {
5934 return isNegativeMode ? ':not(' + chunk.trim() + ')' : chunk;
5935}
5936function stringifyCSSSelector(selector) {
5937 let result = selector[0];
5938 let i = 1;
5939 let mode = 2 /* ATTRIBUTE */;
5940 let currentChunk = '';
5941 let isNegativeMode = false;
5942 while (i < selector.length) {
5943 let valueOrMarker = selector[i];
5944 if (typeof valueOrMarker === 'string') {
5945 if (mode & 2 /* ATTRIBUTE */) {
5946 const attrValue = selector[++i];
5947 currentChunk +=
5948 '[' + valueOrMarker + (attrValue.length > 0 ? '="' + attrValue + '"' : '') + ']';
5949 }
5950 else if (mode & 8 /* CLASS */) {
5951 currentChunk += '.' + valueOrMarker;
5952 }
5953 else if (mode & 4 /* ELEMENT */) {
5954 currentChunk += ' ' + valueOrMarker;
5955 }
5956 }
5957 else {
5958 //
5959 // Append current chunk to the final result in case we come across SelectorFlag, which
5960 // indicates that the previous section of a selector is over. We need to accumulate content
5961 // between flags to make sure we wrap the chunk later in :not() selector if needed, e.g.
5962 // ```
5963 // ['', Flags.CLASS, '.classA', Flags.CLASS | Flags.NOT, '.classB', '.classC']
5964 // ```
5965 // should be transformed to `.classA :not(.classB .classC)`.
5966 //
5967 // Note: for negative selector part, we accumulate content between flags until we find the
5968 // next negative flag. This is needed to support a case where `:not()` rule contains more than
5969 // one chunk, e.g. the following selector:
5970 // ```
5971 // ['', Flags.ELEMENT | Flags.NOT, 'p', Flags.CLASS, 'foo', Flags.CLASS | Flags.NOT, 'bar']
5972 // ```
5973 // should be stringified to `:not(p.foo) :not(.bar)`
5974 //
5975 if (currentChunk !== '' && !isPositive(valueOrMarker)) {
5976 result += maybeWrapInNotSelector(isNegativeMode, currentChunk);
5977 currentChunk = '';
5978 }
5979 mode = valueOrMarker;
5980 // According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative
5981 // mode is maintained for remaining chunks of a selector.
5982 isNegativeMode = isNegativeMode || !isPositive(mode);
5983 }
5984 i++;
5985 }
5986 if (currentChunk !== '') {
5987 result += maybeWrapInNotSelector(isNegativeMode, currentChunk);
5988 }
5989 return result;
5990}
5991/**
5992 * Generates string representation of CSS selector in parsed form.
5993 *
5994 * ComponentDef and DirectiveDef are generated with the selector in parsed form to avoid doing
5995 * additional parsing at runtime (for example, for directive matching). However in some cases (for
5996 * example, while bootstrapping a component), a string version of the selector is required to query
5997 * for the host element on the page. This function takes the parsed form of a selector and returns
5998 * its string representation.
5999 *
6000 * @param selectorList selector in parsed form
6001 * @returns string representation of a given selector
6002 */
6003function stringifyCSSSelectorList(selectorList) {
6004 return selectorList.map(stringifyCSSSelector).join(',');
6005}
6006/**
6007 * Extracts attributes and classes information from a given CSS selector.
6008 *
6009 * This function is used while creating a component dynamically. In this case, the host element
6010 * (that is created dynamically) should contain attributes and classes specified in component's CSS
6011 * selector.
6012 *
6013 * @param selector CSS selector in parsed form (in a form of array)
6014 * @returns object with `attrs` and `classes` fields that contain extracted information
6015 */
6016function extractAttrsAndClassesFromSelector(selector) {
6017 const attrs = [];
6018 const classes = [];
6019 let i = 1;
6020 let mode = 2 /* ATTRIBUTE */;
6021 while (i < selector.length) {
6022 let valueOrMarker = selector[i];
6023 if (typeof valueOrMarker === 'string') {
6024 if (mode === 2 /* ATTRIBUTE */) {
6025 if (valueOrMarker !== '') {
6026 attrs.push(valueOrMarker, selector[++i]);
6027 }
6028 }
6029 else if (mode === 8 /* CLASS */) {
6030 classes.push(valueOrMarker);
6031 }
6032 }
6033 else {
6034 // According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative
6035 // mode is maintained for remaining chunks of a selector. Since attributes and classes are
6036 // extracted only for "positive" part of the selector, we can stop here.
6037 if (!isPositive(mode))
6038 break;
6039 mode = valueOrMarker;
6040 }
6041 i++;
6042 }
6043 return { attrs, classes };
6044}
6045
6046/**
6047 * @license
6048 * Copyright Google LLC All Rights Reserved.
6049 *
6050 * Use of this source code is governed by an MIT-style license that can be
6051 * found in the LICENSE file at https://angular.io/license
6052 */
6053/** A special value which designates that a value has not changed. */
6054const NO_CHANGE = (typeof ngDevMode === 'undefined' || ngDevMode) ? { __brand__: 'NO_CHANGE' } : {};
6055
6056/**
6057 * @license
6058 * Copyright Google LLC All Rights Reserved.
6059 *
6060 * Use of this source code is governed by an MIT-style license that can be
6061 * found in the LICENSE file at https://angular.io/license
6062 */
6063/**
6064 * Gets the parent LView of the passed LView, if the PARENT is an LContainer, will get the parent of
6065 * that LContainer, which is an LView
6066 * @param lView the lView whose parent to get
6067 */
6068function getLViewParent(lView) {
6069 ngDevMode && assertLView(lView);
6070 const parent = lView[PARENT];
6071 return isLContainer(parent) ? parent[PARENT] : parent;
6072}
6073/**
6074 * Retrieve the root view from any component or `LView` by walking the parent `LView` until
6075 * reaching the root `LView`.
6076 *
6077 * @param componentOrLView any component or `LView`
6078 */
6079function getRootView(componentOrLView) {
6080 ngDevMode && assertDefined(componentOrLView, 'component');
6081 let lView = isLView(componentOrLView) ? componentOrLView : readPatchedLView(componentOrLView);
6082 while (lView && !(lView[FLAGS] & 512 /* IsRoot */)) {
6083 lView = getLViewParent(lView);
6084 }
6085 ngDevMode && assertLView(lView);
6086 return lView;
6087}
6088/**
6089 * Returns the `RootContext` instance that is associated with
6090 * the application where the target is situated. It does this by walking the parent views until it
6091 * gets to the root view, then getting the context off of that.
6092 *
6093 * @param viewOrComponent the `LView` or component to get the root context for.
6094 */
6095function getRootContext(viewOrComponent) {
6096 const rootView = getRootView(viewOrComponent);
6097 ngDevMode &&
6098 assertDefined(rootView[CONTEXT], 'RootView has no context. Perhaps it is disconnected?');
6099 return rootView[CONTEXT];
6100}
6101/**
6102 * Gets the first `LContainer` in the LView or `null` if none exists.
6103 */
6104function getFirstLContainer(lView) {
6105 return getNearestLContainer(lView[CHILD_HEAD]);
6106}
6107/**
6108 * Gets the next `LContainer` that is a sibling of the given container.
6109 */
6110function getNextLContainer(container) {
6111 return getNearestLContainer(container[NEXT]);
6112}
6113function getNearestLContainer(viewOrContainer) {
6114 while (viewOrContainer !== null && !isLContainer(viewOrContainer)) {
6115 viewOrContainer = viewOrContainer[NEXT];
6116 }
6117 return viewOrContainer;
6118}
6119
6120/**
6121 * @license
6122 * Copyright Google LLC All Rights Reserved.
6123 *
6124 * Use of this source code is governed by an MIT-style license that can be
6125 * found in the LICENSE file at https://angular.io/license
6126 */
6127/**
6128 * Advances to an element for later binding instructions.
6129 *
6130 * Used in conjunction with instructions like {@link property} to act on elements with specified
6131 * indices, for example those created with {@link element} or {@link elementStart}.
6132 *
6133 * ```ts
6134 * (rf: RenderFlags, ctx: any) => {
6135 * if (rf & 1) {
6136 * text(0, 'Hello');
6137 * text(1, 'Goodbye')
6138 * element(2, 'div');
6139 * }
6140 * if (rf & 2) {
6141 * advance(2); // Advance twice to the <div>.
6142 * property('title', 'test');
6143 * }
6144 * }
6145 * ```
6146 * @param delta Number of elements to advance forwards by.
6147 *
6148 * @codeGenApi
6149 */
6150function ɵɵadvance(delta) {
6151 ngDevMode && assertGreaterThan(delta, 0, 'Can only advance forward');
6152 selectIndexInternal(getTView(), getLView(), getSelectedIndex() + delta, getCheckNoChangesMode());
6153}
6154/**
6155 * Selects an element for later binding instructions.
6156 * @deprecated No longer being generated, but still used in unit tests.
6157 * @codeGenApi
6158 */
6159function ɵɵselect(index) {
6160 // TODO(misko): Remove this function as it is no longer being used.
6161 selectIndexInternal(getTView(), getLView(), index, getCheckNoChangesMode());
6162}
6163function selectIndexInternal(tView, lView, index, checkNoChangesMode) {
6164 ngDevMode && assertGreaterThan(index, -1, 'Invalid index');
6165 ngDevMode && assertIndexInRange(lView, index + HEADER_OFFSET);
6166 // Flush the initial hooks for elements in the view that have been added up to this point.
6167 // PERF WARNING: do NOT extract this to a separate function without running benchmarks
6168 if (!checkNoChangesMode) {
6169 const hooksInitPhaseCompleted = (lView[FLAGS] & 3 /* InitPhaseStateMask */) === 3 /* InitPhaseCompleted */;
6170 if (hooksInitPhaseCompleted) {
6171 const preOrderCheckHooks = tView.preOrderCheckHooks;
6172 if (preOrderCheckHooks !== null) {
6173 executeCheckHooks(lView, preOrderCheckHooks, index);
6174 }
6175 }
6176 else {
6177 const preOrderHooks = tView.preOrderHooks;
6178 if (preOrderHooks !== null) {
6179 executeInitAndCheckHooks(lView, preOrderHooks, 0 /* OnInitHooksToBeRun */, index);
6180 }
6181 }
6182 }
6183 // We must set the selected index *after* running the hooks, because hooks may have side-effects
6184 // that cause other template functions to run, thus updating the selected index, which is global
6185 // state. If we run `setSelectedIndex` *before* we run the hooks, in some cases the selected index
6186 // will be altered by the time we leave the `ɵɵadvance` instruction.
6187 setSelectedIndex(index);
6188}
6189
6190/**
6191 * @license
6192 * Copyright Google LLC All Rights Reserved.
6193 *
6194 * Use of this source code is governed by an MIT-style license that can be
6195 * found in the LICENSE file at https://angular.io/license
6196 */
6197function toTStylingRange(prev, next) {
6198 ngDevMode && assertNumberInRange(prev, 0, 32767 /* UNSIGNED_MASK */);
6199 ngDevMode && assertNumberInRange(next, 0, 32767 /* UNSIGNED_MASK */);
6200 return (prev << 17 /* PREV_SHIFT */ | next << 2 /* NEXT_SHIFT */);
6201}
6202function getTStylingRangePrev(tStylingRange) {
6203 ngDevMode && assertNumber(tStylingRange, 'expected number');
6204 return (tStylingRange >> 17 /* PREV_SHIFT */) & 32767 /* UNSIGNED_MASK */;
6205}
6206function getTStylingRangePrevDuplicate(tStylingRange) {
6207 ngDevMode && assertNumber(tStylingRange, 'expected number');
6208 return (tStylingRange & 2 /* PREV_DUPLICATE */) ==
6209 2 /* PREV_DUPLICATE */;
6210}
6211function setTStylingRangePrev(tStylingRange, previous) {
6212 ngDevMode && assertNumber(tStylingRange, 'expected number');
6213 ngDevMode && assertNumberInRange(previous, 0, 32767 /* UNSIGNED_MASK */);
6214 return ((tStylingRange & ~4294836224 /* PREV_MASK */) |
6215 (previous << 17 /* PREV_SHIFT */));
6216}
6217function setTStylingRangePrevDuplicate(tStylingRange) {
6218 ngDevMode && assertNumber(tStylingRange, 'expected number');
6219 return (tStylingRange | 2 /* PREV_DUPLICATE */);
6220}
6221function getTStylingRangeNext(tStylingRange) {
6222 ngDevMode && assertNumber(tStylingRange, 'expected number');
6223 return (tStylingRange & 131068 /* NEXT_MASK */) >> 2 /* NEXT_SHIFT */;
6224}
6225function setTStylingRangeNext(tStylingRange, next) {
6226 ngDevMode && assertNumber(tStylingRange, 'expected number');
6227 ngDevMode && assertNumberInRange(next, 0, 32767 /* UNSIGNED_MASK */);
6228 return ((tStylingRange & ~131068 /* NEXT_MASK */) | //
6229 next << 2 /* NEXT_SHIFT */);
6230}
6231function getTStylingRangeNextDuplicate(tStylingRange) {
6232 ngDevMode && assertNumber(tStylingRange, 'expected number');
6233 return (tStylingRange & 1 /* NEXT_DUPLICATE */) ===
6234 1 /* NEXT_DUPLICATE */;
6235}
6236function setTStylingRangeNextDuplicate(tStylingRange) {
6237 ngDevMode && assertNumber(tStylingRange, 'expected number');
6238 return (tStylingRange | 1 /* NEXT_DUPLICATE */);
6239}
6240function getTStylingRangeTail(tStylingRange) {
6241 ngDevMode && assertNumber(tStylingRange, 'expected number');
6242 const next = getTStylingRangeNext(tStylingRange);
6243 return next === 0 ? getTStylingRangePrev(tStylingRange) : next;
6244}
6245
6246/**
6247 * @license
6248 * Copyright Google LLC All Rights Reserved.
6249 *
6250 * Use of this source code is governed by an MIT-style license that can be
6251 * found in the LICENSE file at https://angular.io/license
6252 */
6253/**
6254 * Patch a `debug` property on top of the existing object.
6255 *
6256 * NOTE: always call this method with `ngDevMode && attachDebugObject(...)`
6257 *
6258 * @param obj Object to patch
6259 * @param debug Value to patch
6260 */
6261function attachDebugObject(obj, debug) {
6262 if (ngDevMode) {
6263 Object.defineProperty(obj, 'debug', { value: debug, enumerable: false });
6264 }
6265 else {
6266 throw new Error('This method should be guarded with `ngDevMode` so that it can be tree shaken in production!');
6267 }
6268}
6269/**
6270 * Patch a `debug` property getter on top of the existing object.
6271 *
6272 * NOTE: always call this method with `ngDevMode && attachDebugObject(...)`
6273 *
6274 * @param obj Object to patch
6275 * @param debugGetter Getter returning a value to patch
6276 */
6277function attachDebugGetter(obj, debugGetter) {
6278 if (ngDevMode) {
6279 Object.defineProperty(obj, 'debug', { get: debugGetter, enumerable: false });
6280 }
6281 else {
6282 throw new Error('This method should be guarded with `ngDevMode` so that it can be tree shaken in production!');
6283 }
6284}
6285
6286/**
6287 * @license
6288 * Copyright Google LLC All Rights Reserved.
6289 *
6290 * Use of this source code is governed by an MIT-style license that can be
6291 * found in the LICENSE file at https://angular.io/license
6292 */
6293const NG_DEV_MODE = ((typeof ngDevMode === 'undefined' || !!ngDevMode) && initNgDevMode());
6294/*
6295 * This file contains conditionally attached classes which provide human readable (debug) level
6296 * information for `LView`, `LContainer` and other internal data structures. These data structures
6297 * are stored internally as array which makes it very difficult during debugging to reason about the
6298 * current state of the system.
6299 *
6300 * Patching the array with extra property does change the array's hidden class' but it does not
6301 * change the cost of access, therefore this patching should not have significant if any impact in
6302 * `ngDevMode` mode. (see: https://jsperf.com/array-vs-monkey-patch-array)
6303 *
6304 * So instead of seeing:
6305 * ```
6306 * Array(30) [Object, 659, null, …]
6307 * ```
6308 *
6309 * You get to see:
6310 * ```
6311 * LViewDebug {
6312 * views: [...],
6313 * flags: {attached: true, ...}
6314 * nodes: [
6315 * {html: '<div id="123">', ..., nodes: [
6316 * {html: '<span>', ..., nodes: null}
6317 * ]}
6318 * ]
6319 * }
6320 * ```
6321 */
6322let LVIEW_COMPONENT_CACHE;
6323let LVIEW_EMBEDDED_CACHE;
6324let LVIEW_ROOT;
6325/**
6326 * This function clones a blueprint and creates LView.
6327 *
6328 * Simple slice will keep the same type, and we need it to be LView
6329 */
6330function cloneToLViewFromTViewBlueprint(tView) {
6331 const debugTView = tView;
6332 const lView = getLViewToClone(debugTView.type, tView.template && tView.template.name);
6333 return lView.concat(tView.blueprint);
6334}
6335function getLViewToClone(type, name) {
6336 switch (type) {
6337 case 0 /* Root */:
6338 if (LVIEW_ROOT === undefined)
6339 LVIEW_ROOT = new (createNamedArrayType('LRootView'))();
6340 return LVIEW_ROOT;
6341 case 1 /* Component */:
6342 if (LVIEW_COMPONENT_CACHE === undefined)
6343 LVIEW_COMPONENT_CACHE = new Map();
6344 let componentArray = LVIEW_COMPONENT_CACHE.get(name);
6345 if (componentArray === undefined) {
6346 componentArray = new (createNamedArrayType('LComponentView' + nameSuffix(name)))();
6347 LVIEW_COMPONENT_CACHE.set(name, componentArray);
6348 }
6349 return componentArray;
6350 case 2 /* Embedded */:
6351 if (LVIEW_EMBEDDED_CACHE === undefined)
6352 LVIEW_EMBEDDED_CACHE = new Map();
6353 let embeddedArray = LVIEW_EMBEDDED_CACHE.get(name);
6354 if (embeddedArray === undefined) {
6355 embeddedArray = new (createNamedArrayType('LEmbeddedView' + nameSuffix(name)))();
6356 LVIEW_EMBEDDED_CACHE.set(name, embeddedArray);
6357 }
6358 return embeddedArray;
6359 }
6360 throw new Error('unreachable code');
6361}
6362function nameSuffix(text) {
6363 if (text == null)
6364 return '';
6365 const index = text.lastIndexOf('_Template');
6366 return '_' + (index === -1 ? text : text.substr(0, index));
6367}
6368/**
6369 * This class is a debug version of Object literal so that we can have constructor name show up
6370 * in
6371 * debug tools in ngDevMode.
6372 */
6373const TViewConstructor = class TView {
6374 constructor(type, //
6375 id, //
6376 blueprint, //
6377 template, //
6378 queries, //
6379 viewQuery, //
6380 node, //
6381 data, //
6382 bindingStartIndex, //
6383 expandoStartIndex, //
6384 expandoInstructions, //
6385 firstCreatePass, //
6386 firstUpdatePass, //
6387 staticViewQueries, //
6388 staticContentQueries, //
6389 preOrderHooks, //
6390 preOrderCheckHooks, //
6391 contentHooks, //
6392 contentCheckHooks, //
6393 viewHooks, //
6394 viewCheckHooks, //
6395 destroyHooks, //
6396 cleanup, //
6397 contentQueries, //
6398 components, //
6399 directiveRegistry, //
6400 pipeRegistry, //
6401 firstChild, //
6402 schemas, //
6403 consts, //
6404 incompleteFirstPass, //
6405 _decls, //
6406 _vars) {
6407 this.type = type;
6408 this.id = id;
6409 this.blueprint = blueprint;
6410 this.template = template;
6411 this.queries = queries;
6412 this.viewQuery = viewQuery;
6413 this.node = node;
6414 this.data = data;
6415 this.bindingStartIndex = bindingStartIndex;
6416 this.expandoStartIndex = expandoStartIndex;
6417 this.expandoInstructions = expandoInstructions;
6418 this.firstCreatePass = firstCreatePass;
6419 this.firstUpdatePass = firstUpdatePass;
6420 this.staticViewQueries = staticViewQueries;
6421 this.staticContentQueries = staticContentQueries;
6422 this.preOrderHooks = preOrderHooks;
6423 this.preOrderCheckHooks = preOrderCheckHooks;
6424 this.contentHooks = contentHooks;
6425 this.contentCheckHooks = contentCheckHooks;
6426 this.viewHooks = viewHooks;
6427 this.viewCheckHooks = viewCheckHooks;
6428 this.destroyHooks = destroyHooks;
6429 this.cleanup = cleanup;
6430 this.contentQueries = contentQueries;
6431 this.components = components;
6432 this.directiveRegistry = directiveRegistry;
6433 this.pipeRegistry = pipeRegistry;
6434 this.firstChild = firstChild;
6435 this.schemas = schemas;
6436 this.consts = consts;
6437 this.incompleteFirstPass = incompleteFirstPass;
6438 this._decls = _decls;
6439 this._vars = _vars;
6440 }
6441 get template_() {
6442 const buf = [];
6443 processTNodeChildren(this.firstChild, buf);
6444 return buf.join('');
6445 }
6446};
6447class TNode {
6448 constructor(tView_, //
6449 type, //
6450 index, //
6451 injectorIndex, //
6452 directiveStart, //
6453 directiveEnd, //
6454 directiveStylingLast, //
6455 propertyBindings, //
6456 flags, //
6457 providerIndexes, //
6458 tagName, //
6459 attrs, //
6460 mergedAttrs, //
6461 localNames, //
6462 initialInputs, //
6463 inputs, //
6464 outputs, //
6465 tViews, //
6466 next, //
6467 projectionNext, //
6468 child, //
6469 parent, //
6470 projection, //
6471 styles, //
6472 stylesWithoutHost, //
6473 residualStyles, //
6474 classes, //
6475 classesWithoutHost, //
6476 residualClasses, //
6477 classBindings, //
6478 styleBindings) {
6479 this.tView_ = tView_;
6480 this.type = type;
6481 this.index = index;
6482 this.injectorIndex = injectorIndex;
6483 this.directiveStart = directiveStart;
6484 this.directiveEnd = directiveEnd;
6485 this.directiveStylingLast = directiveStylingLast;
6486 this.propertyBindings = propertyBindings;
6487 this.flags = flags;
6488 this.providerIndexes = providerIndexes;
6489 this.tagName = tagName;
6490 this.attrs = attrs;
6491 this.mergedAttrs = mergedAttrs;
6492 this.localNames = localNames;
6493 this.initialInputs = initialInputs;
6494 this.inputs = inputs;
6495 this.outputs = outputs;
6496 this.tViews = tViews;
6497 this.next = next;
6498 this.projectionNext = projectionNext;
6499 this.child = child;
6500 this.parent = parent;
6501 this.projection = projection;
6502 this.styles = styles;
6503 this.stylesWithoutHost = stylesWithoutHost;
6504 this.residualStyles = residualStyles;
6505 this.classes = classes;
6506 this.classesWithoutHost = classesWithoutHost;
6507 this.residualClasses = residualClasses;
6508 this.classBindings = classBindings;
6509 this.styleBindings = styleBindings;
6510 }
6511 get type_() {
6512 switch (this.type) {
6513 case 0 /* Container */:
6514 return 'TNodeType.Container';
6515 case 3 /* Element */:
6516 return 'TNodeType.Element';
6517 case 4 /* ElementContainer */:
6518 return 'TNodeType.ElementContainer';
6519 case 5 /* IcuContainer */:
6520 return 'TNodeType.IcuContainer';
6521 case 1 /* Projection */:
6522 return 'TNodeType.Projection';
6523 case 2 /* View */:
6524 return 'TNodeType.View';
6525 default:
6526 return 'TNodeType.???';
6527 }
6528 }
6529 get flags_() {
6530 const flags = [];
6531 if (this.flags & 16 /* hasClassInput */)
6532 flags.push('TNodeFlags.hasClassInput');
6533 if (this.flags & 8 /* hasContentQuery */)
6534 flags.push('TNodeFlags.hasContentQuery');
6535 if (this.flags & 32 /* hasStyleInput */)
6536 flags.push('TNodeFlags.hasStyleInput');
6537 if (this.flags & 128 /* hasHostBindings */)
6538 flags.push('TNodeFlags.hasHostBindings');
6539 if (this.flags & 2 /* isComponentHost */)
6540 flags.push('TNodeFlags.isComponentHost');
6541 if (this.flags & 1 /* isDirectiveHost */)
6542 flags.push('TNodeFlags.isDirectiveHost');
6543 if (this.flags & 64 /* isDetached */)
6544 flags.push('TNodeFlags.isDetached');
6545 if (this.flags & 4 /* isProjected */)
6546 flags.push('TNodeFlags.isProjected');
6547 return flags.join('|');
6548 }
6549 get template_() {
6550 const buf = [];
6551 buf.push('<', this.tagName || this.type_);
6552 if (this.attrs) {
6553 for (let i = 0; i < this.attrs.length;) {
6554 const attrName = this.attrs[i++];
6555 if (typeof attrName == 'number') {
6556 break;
6557 }
6558 const attrValue = this.attrs[i++];
6559 buf.push(' ', attrName, '="', attrValue, '"');
6560 }
6561 }
6562 buf.push('>');
6563 processTNodeChildren(this.child, buf);
6564 buf.push('</', this.tagName || this.type_, '>');
6565 return buf.join('');
6566 }
6567 get styleBindings_() {
6568 return toDebugStyleBinding(this, false);
6569 }
6570 get classBindings_() {
6571 return toDebugStyleBinding(this, true);
6572 }
6573}
6574const TNodeDebug = TNode;
6575function toDebugStyleBinding(tNode, isClassBased) {
6576 const tData = tNode.tView_.data;
6577 const bindings = [];
6578 const range = isClassBased ? tNode.classBindings : tNode.styleBindings;
6579 const prev = getTStylingRangePrev(range);
6580 const next = getTStylingRangeNext(range);
6581 let isTemplate = next !== 0;
6582 let cursor = isTemplate ? next : prev;
6583 while (cursor !== 0) {
6584 const itemKey = tData[cursor];
6585 const itemRange = tData[cursor + 1];
6586 bindings.unshift({
6587 key: itemKey,
6588 index: cursor,
6589 isTemplate: isTemplate,
6590 prevDuplicate: getTStylingRangePrevDuplicate(itemRange),
6591 nextDuplicate: getTStylingRangeNextDuplicate(itemRange),
6592 nextIndex: getTStylingRangeNext(itemRange),
6593 prevIndex: getTStylingRangePrev(itemRange),
6594 });
6595 if (cursor === prev)
6596 isTemplate = false;
6597 cursor = getTStylingRangePrev(itemRange);
6598 }
6599 bindings.push((isClassBased ? tNode.residualClasses : tNode.residualStyles) || null);
6600 return bindings;
6601}
6602function processTNodeChildren(tNode, buf) {
6603 while (tNode) {
6604 buf.push(tNode.template_);
6605 tNode = tNode.next;
6606 }
6607}
6608const TViewData = NG_DEV_MODE && createNamedArrayType('TViewData') || null;
6609let TVIEWDATA_EMPTY; // can't initialize here or it will not be tree shaken, because
6610// `LView` constructor could have side-effects.
6611/**
6612 * This function clones a blueprint and creates TData.
6613 *
6614 * Simple slice will keep the same type, and we need it to be TData
6615 */
6616function cloneToTViewData(list) {
6617 if (TVIEWDATA_EMPTY === undefined)
6618 TVIEWDATA_EMPTY = new TViewData();
6619 return TVIEWDATA_EMPTY.concat(list);
6620}
6621const LViewBlueprint = NG_DEV_MODE && createNamedArrayType('LViewBlueprint') || null;
6622const MatchesArray = NG_DEV_MODE && createNamedArrayType('MatchesArray') || null;
6623const TViewComponents = NG_DEV_MODE && createNamedArrayType('TViewComponents') || null;
6624const TNodeLocalNames = NG_DEV_MODE && createNamedArrayType('TNodeLocalNames') || null;
6625const TNodeInitialInputs = NG_DEV_MODE && createNamedArrayType('TNodeInitialInputs') || null;
6626const TNodeInitialData = NG_DEV_MODE && createNamedArrayType('TNodeInitialData') || null;
6627const LCleanup = NG_DEV_MODE && createNamedArrayType('LCleanup') || null;
6628const TCleanup = NG_DEV_MODE && createNamedArrayType('TCleanup') || null;
6629function attachLViewDebug(lView) {
6630 attachDebugObject(lView, new LViewDebug(lView));
6631}
6632function attachLContainerDebug(lContainer) {
6633 attachDebugObject(lContainer, new LContainerDebug(lContainer));
6634}
6635function toDebug(obj) {
6636 if (obj) {
6637 const debug = obj.debug;
6638 assertDefined(debug, 'Object does not have a debug representation.');
6639 return debug;
6640 }
6641 else {
6642 return obj;
6643 }
6644}
6645/**
6646 * Use this method to unwrap a native element in `LView` and convert it into HTML for easier
6647 * reading.
6648 *
6649 * @param value possibly wrapped native DOM node.
6650 * @param includeChildren If `true` then the serialized HTML form will include child elements
6651 * (same
6652 * as `outerHTML`). If `false` then the serialized HTML form will only contain the element
6653 * itself
6654 * (will not serialize child elements).
6655 */
6656function toHtml(value, includeChildren = false) {
6657 const node = unwrapRNode(value);
6658 if (node) {
6659 switch (node.nodeType) {
6660 case Node.TEXT_NODE:
6661 return node.textContent;
6662 case Node.COMMENT_NODE:
6663 return `<!--${node.textContent}-->`;
6664 case Node.ELEMENT_NODE:
6665 const outerHTML = node.outerHTML;
6666 if (includeChildren) {
6667 return outerHTML;
6668 }
6669 else {
6670 const innerHTML = '>' + node.innerHTML + '<';
6671 return (outerHTML.split(innerHTML)[0]) + '>';
6672 }
6673 }
6674 }
6675 return null;
6676}
6677class LViewDebug {
6678 constructor(_raw_lView) {
6679 this._raw_lView = _raw_lView;
6680 }
6681 /**
6682 * Flags associated with the `LView` unpacked into a more readable state.
6683 */
6684 get flags() {
6685 const flags = this._raw_lView[FLAGS];
6686 return {
6687 __raw__flags__: flags,
6688 initPhaseState: flags & 3 /* InitPhaseStateMask */,
6689 creationMode: !!(flags & 4 /* CreationMode */),
6690 firstViewPass: !!(flags & 8 /* FirstLViewPass */),
6691 checkAlways: !!(flags & 16 /* CheckAlways */),
6692 dirty: !!(flags & 64 /* Dirty */),
6693 attached: !!(flags & 128 /* Attached */),
6694 destroyed: !!(flags & 256 /* Destroyed */),
6695 isRoot: !!(flags & 512 /* IsRoot */),
6696 indexWithinInitPhase: flags >> 11 /* IndexWithinInitPhaseShift */,
6697 };
6698 }
6699 get parent() {
6700 return toDebug(this._raw_lView[PARENT]);
6701 }
6702 get hostHTML() {
6703 return toHtml(this._raw_lView[HOST], true);
6704 }
6705 get html() {
6706 return (this.nodes || []).map(node => toHtml(node.native, true)).join('');
6707 }
6708 get context() {
6709 return this._raw_lView[CONTEXT];
6710 }
6711 /**
6712 * The tree of nodes associated with the current `LView`. The nodes have been normalized into
6713 * a tree structure with relevant details pulled out for readability.
6714 */
6715 get nodes() {
6716 const lView = this._raw_lView;
6717 const tNode = lView[TVIEW].firstChild;
6718 return toDebugNodes(tNode, lView);
6719 }
6720 get tView() {
6721 return this._raw_lView[TVIEW];
6722 }
6723 get cleanup() {
6724 return this._raw_lView[CLEANUP];
6725 }
6726 get injector() {
6727 return this._raw_lView[INJECTOR$1];
6728 }
6729 get rendererFactory() {
6730 return this._raw_lView[RENDERER_FACTORY];
6731 }
6732 get renderer() {
6733 return this._raw_lView[RENDERER];
6734 }
6735 get sanitizer() {
6736 return this._raw_lView[SANITIZER];
6737 }
6738 get childHead() {
6739 return toDebug(this._raw_lView[CHILD_HEAD]);
6740 }
6741 get next() {
6742 return toDebug(this._raw_lView[NEXT]);
6743 }
6744 get childTail() {
6745 return toDebug(this._raw_lView[CHILD_TAIL]);
6746 }
6747 get declarationView() {
6748 return toDebug(this._raw_lView[DECLARATION_VIEW]);
6749 }
6750 get queries() {
6751 return this._raw_lView[QUERIES];
6752 }
6753 get tHost() {
6754 return this._raw_lView[T_HOST];
6755 }
6756 get decls() {
6757 const tView = this.tView;
6758 const start = HEADER_OFFSET;
6759 return toLViewRange(this.tView, this._raw_lView, start, start + tView._decls);
6760 }
6761 get vars() {
6762 const tView = this.tView;
6763 const start = HEADER_OFFSET + tView._decls;
6764 return toLViewRange(this.tView, this._raw_lView, start, start + tView._vars);
6765 }
6766 get i18n() {
6767 const tView = this.tView;
6768 const start = HEADER_OFFSET + tView._decls + tView._vars;
6769 return toLViewRange(this.tView, this._raw_lView, start, this.tView.expandoStartIndex);
6770 }
6771 get expando() {
6772 const tView = this.tView;
6773 return toLViewRange(this.tView, this._raw_lView, this.tView.expandoStartIndex, this._raw_lView.length);
6774 }
6775 /**
6776 * Normalized view of child views (and containers) attached at this location.
6777 */
6778 get childViews() {
6779 const childViews = [];
6780 let child = this.childHead;
6781 while (child) {
6782 childViews.push(child);
6783 child = child.next;
6784 }
6785 return childViews;
6786 }
6787}
6788function toLViewRange(tView, lView, start, end) {
6789 let content = [];
6790 for (let index = start; index < end; index++) {
6791 content.push({ index: index, t: tView.data[index], l: lView[index] });
6792 }
6793 return { start: start, end: end, length: end - start, content: content };
6794}
6795/**
6796 * Turns a flat list of nodes into a tree by walking the associated `TNode` tree.
6797 *
6798 * @param tNode
6799 * @param lView
6800 */
6801function toDebugNodes(tNode, lView) {
6802 if (tNode) {
6803 const debugNodes = [];
6804 let tNodeCursor = tNode;
6805 while (tNodeCursor) {
6806 debugNodes.push(buildDebugNode(tNodeCursor, lView, tNodeCursor.index));
6807 tNodeCursor = tNodeCursor.next;
6808 }
6809 return debugNodes;
6810 }
6811 else {
6812 return [];
6813 }
6814}
6815function buildDebugNode(tNode, lView, nodeIndex) {
6816 const rawValue = lView[nodeIndex];
6817 const native = unwrapRNode(rawValue);
6818 return {
6819 html: toHtml(native),
6820 type: TNodeTypeAsString[tNode.type],
6821 native: native,
6822 children: toDebugNodes(tNode.child, lView),
6823 };
6824}
6825class LContainerDebug {
6826 constructor(_raw_lContainer) {
6827 this._raw_lContainer = _raw_lContainer;
6828 }
6829 get hasTransplantedViews() {
6830 return this._raw_lContainer[HAS_TRANSPLANTED_VIEWS];
6831 }
6832 get views() {
6833 return this._raw_lContainer.slice(CONTAINER_HEADER_OFFSET)
6834 .map(toDebug);
6835 }
6836 get parent() {
6837 return toDebug(this._raw_lContainer[PARENT]);
6838 }
6839 get movedViews() {
6840 return this._raw_lContainer[MOVED_VIEWS];
6841 }
6842 get host() {
6843 return this._raw_lContainer[HOST];
6844 }
6845 get native() {
6846 return this._raw_lContainer[NATIVE];
6847 }
6848 get next() {
6849 return toDebug(this._raw_lContainer[NEXT]);
6850 }
6851}
6852/**
6853 * Return an `LView` value if found.
6854 *
6855 * @param value `LView` if any
6856 */
6857function readLViewValue(value) {
6858 while (Array.isArray(value)) {
6859 // This check is not quite right, as it does not take into account `StylingContext`
6860 // This is why it is in debug, not in util.ts
6861 if (value.length >= HEADER_OFFSET - 1)
6862 return value;
6863 value = value[HOST];
6864 }
6865 return null;
6866}
6867
6868const ɵ0$4 = () => Promise.resolve(null);
6869/**
6870 * A permanent marker promise which signifies that the current CD tree is
6871 * clean.
6872 */
6873const _CLEAN_PROMISE = (ɵ0$4)();
6874/**
6875 * Process the `TView.expandoInstructions`. (Execute the `hostBindings`.)
6876 *
6877 * @param tView `TView` containing the `expandoInstructions`
6878 * @param lView `LView` associated with the `TView`
6879 */
6880function setHostBindingsByExecutingExpandoInstructions(tView, lView) {
6881 ngDevMode && assertSame(tView, lView[TVIEW], '`LView` is not associated with the `TView`!');
6882 try {
6883 const expandoInstructions = tView.expandoInstructions;
6884 if (expandoInstructions !== null) {
6885 let bindingRootIndex = tView.expandoStartIndex;
6886 let currentDirectiveIndex = -1;
6887 let currentElementIndex = -1;
6888 // TODO(misko): PERF It is possible to get here with `TView.expandoInstructions` containing no
6889 // functions to execute. This is wasteful as there is no work to be done, but we still need
6890 // to iterate over the instructions.
6891 // In example of this is in this test: `host_binding_spec.ts`
6892 // `fit('should not cause problems if detectChanges is called when a property updates', ...`
6893 // In the above test we get here with expando [0, 0, 1] which requires a lot of processing but
6894 // there is no function to execute.
6895 for (let i = 0; i < expandoInstructions.length; i++) {
6896 const instruction = expandoInstructions[i];
6897 if (typeof instruction === 'number') {
6898 if (instruction <= 0) {
6899 // Negative numbers mean that we are starting new EXPANDO block and need to update
6900 // the current element and directive index.
6901 // Important: In JS `-x` and `0-x` is not the same! If `x===0` then `-x` will produce
6902 // `-0` which requires non standard math arithmetic and it can prevent VM optimizations.
6903 // `0-0` will always produce `0` and will not cause a potential deoptimization in VM.
6904 // TODO(misko): PERF This should be refactored to use `~instruction` as that does not
6905 // suffer from `-0` and it is faster/more compact.
6906 currentElementIndex = 0 - instruction;
6907 setSelectedIndex(currentElementIndex);
6908 // Injector block and providers are taken into account.
6909 const providerCount = expandoInstructions[++i];
6910 bindingRootIndex += INJECTOR_BLOOM_PARENT_SIZE + providerCount;
6911 currentDirectiveIndex = bindingRootIndex;
6912 }
6913 else {
6914 // This is either the injector size (so the binding root can skip over directives
6915 // and get to the first set of host bindings on this node) or the host var count
6916 // (to get to the next set of host bindings on this node).
6917 bindingRootIndex += instruction;
6918 }
6919 }
6920 else {
6921 // If it's not a number, it's a host binding function that needs to be executed.
6922 if (instruction !== null) {
6923 ngDevMode &&
6924 assertLessThan(currentDirectiveIndex, 1048576 /* CptViewProvidersCountShifter */, 'Reached the max number of host bindings');
6925 setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex);
6926 const hostCtx = lView[currentDirectiveIndex];
6927 instruction(2 /* Update */, hostCtx);
6928 }
6929 // TODO(misko): PERF Relying on incrementing the `currentDirectiveIndex` here is
6930 // sub-optimal. The implications are that if we have a lot of directives but none of them
6931 // have host bindings we nevertheless need to iterate over the expando instructions to
6932 // update the counter. It would be much better if we could encode the
6933 // `currentDirectiveIndex` into the `expandoInstruction` array so that we only need to
6934 // iterate over those directives which actually have `hostBindings`.
6935 currentDirectiveIndex++;
6936 }
6937 }
6938 }
6939 }
6940 finally {
6941 setSelectedIndex(-1);
6942 }
6943}
6944/** Refreshes all content queries declared by directives in a given view */
6945function refreshContentQueries(tView, lView) {
6946 const contentQueries = tView.contentQueries;
6947 if (contentQueries !== null) {
6948 for (let i = 0; i < contentQueries.length; i += 2) {
6949 const queryStartIdx = contentQueries[i];
6950 const directiveDefIdx = contentQueries[i + 1];
6951 if (directiveDefIdx !== -1) {
6952 const directiveDef = tView.data[directiveDefIdx];
6953 ngDevMode &&
6954 assertDefined(directiveDef.contentQueries, 'contentQueries function should be defined');
6955 setCurrentQueryIndex(queryStartIdx);
6956 directiveDef.contentQueries(2 /* Update */, lView[directiveDefIdx], directiveDefIdx);
6957 }
6958 }
6959 }
6960}
6961/** Refreshes child components in the current view (update mode). */
6962function refreshChildComponents(hostLView, components) {
6963 for (let i = 0; i < components.length; i++) {
6964 refreshComponent(hostLView, components[i]);
6965 }
6966}
6967/** Renders child components in the current view (creation mode). */
6968function renderChildComponents(hostLView, components) {
6969 for (let i = 0; i < components.length; i++) {
6970 renderComponent(hostLView, components[i]);
6971 }
6972}
6973/**
6974 * Creates a native element from a tag name, using a renderer.
6975 * @param name the tag name
6976 * @param renderer A renderer to use
6977 * @returns the element created
6978 */
6979function elementCreate(name, renderer, namespace) {
6980 if (isProceduralRenderer(renderer)) {
6981 return renderer.createElement(name, namespace);
6982 }
6983 else {
6984 return namespace === null ? renderer.createElement(name) :
6985 renderer.createElementNS(namespace, name);
6986 }
6987}
6988function createLView(parentLView, tView, context, flags, host, tHostNode, rendererFactory, renderer, sanitizer, injector) {
6989 const lView = ngDevMode ? cloneToLViewFromTViewBlueprint(tView) : tView.blueprint.slice();
6990 lView[HOST] = host;
6991 lView[FLAGS] = flags | 4 /* CreationMode */ | 128 /* Attached */ | 8 /* FirstLViewPass */;
6992 resetPreOrderHookFlags(lView);
6993 lView[PARENT] = lView[DECLARATION_VIEW] = parentLView;
6994 lView[CONTEXT] = context;
6995 lView[RENDERER_FACTORY] = (rendererFactory || parentLView && parentLView[RENDERER_FACTORY]);
6996 ngDevMode && assertDefined(lView[RENDERER_FACTORY], 'RendererFactory is required');
6997 lView[RENDERER] = (renderer || parentLView && parentLView[RENDERER]);
6998 ngDevMode && assertDefined(lView[RENDERER], 'Renderer is required');
6999 lView[SANITIZER] = sanitizer || parentLView && parentLView[SANITIZER] || null;
7000 lView[INJECTOR$1] = injector || parentLView && parentLView[INJECTOR$1] || null;
7001 lView[T_HOST] = tHostNode;
7002 ngDevMode &&
7003 assertEqual(tView.type == 2 /* Embedded */ ? parentLView !== null : true, true, 'Embedded views must have parentLView');
7004 lView[DECLARATION_COMPONENT_VIEW] =
7005 tView.type == 2 /* Embedded */ ? parentLView[DECLARATION_COMPONENT_VIEW] : lView;
7006 ngDevMode && attachLViewDebug(lView);
7007 return lView;
7008}
7009function getOrCreateTNode(tView, tHostNode, index, type, name, attrs) {
7010 // Keep this function short, so that the VM will inline it.
7011 const adjustedIndex = index + HEADER_OFFSET;
7012 const tNode = tView.data[adjustedIndex] ||
7013 createTNodeAtIndex(tView, tHostNode, adjustedIndex, type, name, attrs);
7014 setPreviousOrParentTNode(tNode, true);
7015 return tNode;
7016}
7017function createTNodeAtIndex(tView, tHostNode, adjustedIndex, type, name, attrs) {
7018 const previousOrParentTNode = getPreviousOrParentTNode();
7019 const isParent = getIsParent();
7020 const parent = isParent ? previousOrParentTNode : previousOrParentTNode && previousOrParentTNode.parent;
7021 // Parents cannot cross component boundaries because components will be used in multiple places,
7022 // so it's only set if the view is the same.
7023 const parentInSameView = parent && parent !== tHostNode;
7024 const tParentNode = parentInSameView ? parent : null;
7025 const tNode = tView.data[adjustedIndex] =
7026 createTNode(tView, tParentNode, type, adjustedIndex, name, attrs);
7027 // Assign a pointer to the first child node of a given view. The first node is not always the one
7028 // at index 0, in case of i18n, index 0 can be the instruction `i18nStart` and the first node has
7029 // the index 1 or more, so we can't just check node index.
7030 if (tView.firstChild === null) {
7031 tView.firstChild = tNode;
7032 }
7033 if (previousOrParentTNode) {
7034 if (isParent && previousOrParentTNode.child == null &&
7035 (tNode.parent !== null || previousOrParentTNode.type === 2 /* View */)) {
7036 // We are in the same view, which means we are adding content node to the parent view.
7037 previousOrParentTNode.child = tNode;
7038 }
7039 else if (!isParent) {
7040 previousOrParentTNode.next = tNode;
7041 }
7042 }
7043 return tNode;
7044}
7045function assignTViewNodeToLView(tView, tParentNode, index, lView) {
7046 // View nodes are not stored in data because they can be added / removed at runtime (which
7047 // would cause indices to change). Their TNodes are instead stored in tView.node.
7048 let tNode = tView.node;
7049 if (tNode == null) {
7050 ngDevMode && tParentNode &&
7051 assertNodeOfPossibleTypes(tParentNode, [3 /* Element */, 0 /* Container */]);
7052 tView.node = tNode = createTNode(tView, tParentNode, //
7053 2 /* View */, index, null, null);
7054 }
7055 lView[T_HOST] = tNode;
7056}
7057/**
7058 * When elements are created dynamically after a view blueprint is created (e.g. through
7059 * i18nApply() or ComponentFactory.create), we need to adjust the blueprint for future
7060 * template passes.
7061 *
7062 * @param tView `TView` associated with `LView`
7063 * @param view The `LView` containing the blueprint to adjust
7064 * @param numSlotsToAlloc The number of slots to alloc in the LView, should be >0
7065 */
7066function allocExpando(tView, lView, numSlotsToAlloc) {
7067 ngDevMode &&
7068 assertGreaterThan(numSlotsToAlloc, 0, 'The number of slots to alloc should be greater than 0');
7069 if (numSlotsToAlloc > 0) {
7070 if (tView.firstCreatePass) {
7071 for (let i = 0; i < numSlotsToAlloc; i++) {
7072 tView.blueprint.push(null);
7073 tView.data.push(null);
7074 lView.push(null);
7075 }
7076 // We should only increment the expando start index if there aren't already directives
7077 // and injectors saved in the "expando" section
7078 if (!tView.expandoInstructions) {
7079 tView.expandoStartIndex += numSlotsToAlloc;
7080 }
7081 else {
7082 // Since we're adding the dynamic nodes into the expando section, we need to let the host
7083 // bindings know that they should skip x slots
7084 tView.expandoInstructions.push(numSlotsToAlloc);
7085 }
7086 }
7087 }
7088}
7089//////////////////////////
7090//// Render
7091//////////////////////////
7092/**
7093 * Processes a view in the creation mode. This includes a number of steps in a specific order:
7094 * - creating view query functions (if any);
7095 * - executing a template function in the creation mode;
7096 * - updating static queries (if any);
7097 * - creating child components defined in a given view.
7098 */
7099function renderView(tView, lView, context) {
7100 ngDevMode && assertEqual(isCreationMode(lView), true, 'Should be run in creation mode');
7101 enterView(lView, lView[T_HOST]);
7102 try {
7103 const viewQuery = tView.viewQuery;
7104 if (viewQuery !== null) {
7105 executeViewQueryFn(1 /* Create */, viewQuery, context);
7106 }
7107 // Execute a template associated with this view, if it exists. A template function might not be
7108 // defined for the root component views.
7109 const templateFn = tView.template;
7110 if (templateFn !== null) {
7111 executeTemplate(tView, lView, templateFn, 1 /* Create */, context);
7112 }
7113 // This needs to be set before children are processed to support recursive components.
7114 // This must be set to false immediately after the first creation run because in an
7115 // ngFor loop, all the views will be created together before update mode runs and turns
7116 // off firstCreatePass. If we don't set it here, instances will perform directive
7117 // matching, etc again and again.
7118 if (tView.firstCreatePass) {
7119 tView.firstCreatePass = false;
7120 }
7121 // We resolve content queries specifically marked as `static` in creation mode. Dynamic
7122 // content queries are resolved during change detection (i.e. update mode), after embedded
7123 // views are refreshed (see block above).
7124 if (tView.staticContentQueries) {
7125 refreshContentQueries(tView, lView);
7126 }
7127 // We must materialize query results before child components are processed
7128 // in case a child component has projected a container. The LContainer needs
7129 // to exist so the embedded views are properly attached by the container.
7130 if (tView.staticViewQueries) {
7131 executeViewQueryFn(2 /* Update */, tView.viewQuery, context);
7132 }
7133 // Render child component views.
7134 const components = tView.components;
7135 if (components !== null) {
7136 renderChildComponents(lView, components);
7137 }
7138 }
7139 catch (error) {
7140 // If we didn't manage to get past the first template pass due to
7141 // an error, mark the view as corrupted so we can try to recover.
7142 if (tView.firstCreatePass) {
7143 tView.incompleteFirstPass = true;
7144 }
7145 throw error;
7146 }
7147 finally {
7148 lView[FLAGS] &= ~4 /* CreationMode */;
7149 leaveView();
7150 }
7151}
7152/**
7153 * Processes a view in update mode. This includes a number of steps in a specific order:
7154 * - executing a template function in update mode;
7155 * - executing hooks;
7156 * - refreshing queries;
7157 * - setting host bindings;
7158 * - refreshing child (embedded and component) views.
7159 */
7160function refreshView(tView, lView, templateFn, context) {
7161 ngDevMode && assertEqual(isCreationMode(lView), false, 'Should be run in update mode');
7162 const flags = lView[FLAGS];
7163 if ((flags & 256 /* Destroyed */) === 256 /* Destroyed */)
7164 return;
7165 enterView(lView, lView[T_HOST]);
7166 const checkNoChangesMode = getCheckNoChangesMode();
7167 try {
7168 resetPreOrderHookFlags(lView);
7169 setBindingIndex(tView.bindingStartIndex);
7170 if (templateFn !== null) {
7171 executeTemplate(tView, lView, templateFn, 2 /* Update */, context);
7172 }
7173 const hooksInitPhaseCompleted = (flags & 3 /* InitPhaseStateMask */) === 3 /* InitPhaseCompleted */;
7174 // execute pre-order hooks (OnInit, OnChanges, DoCheck)
7175 // PERF WARNING: do NOT extract this to a separate function without running benchmarks
7176 if (!checkNoChangesMode) {
7177 if (hooksInitPhaseCompleted) {
7178 const preOrderCheckHooks = tView.preOrderCheckHooks;
7179 if (preOrderCheckHooks !== null) {
7180 executeCheckHooks(lView, preOrderCheckHooks, null);
7181 }
7182 }
7183 else {
7184 const preOrderHooks = tView.preOrderHooks;
7185 if (preOrderHooks !== null) {
7186 executeInitAndCheckHooks(lView, preOrderHooks, 0 /* OnInitHooksToBeRun */, null);
7187 }
7188 incrementInitPhaseFlags(lView, 0 /* OnInitHooksToBeRun */);
7189 }
7190 }
7191 // First mark transplanted views that are declared in this lView as needing a refresh at their
7192 // insertion points. This is needed to avoid the situation where the template is defined in this
7193 // `LView` but its declaration appears after the insertion component.
7194 markTransplantedViewsForRefresh(lView);
7195 refreshEmbeddedViews(lView);
7196 // Content query results must be refreshed before content hooks are called.
7197 if (tView.contentQueries !== null) {
7198 refreshContentQueries(tView, lView);
7199 }
7200 // execute content hooks (AfterContentInit, AfterContentChecked)
7201 // PERF WARNING: do NOT extract this to a separate function without running benchmarks
7202 if (!checkNoChangesMode) {
7203 if (hooksInitPhaseCompleted) {
7204 const contentCheckHooks = tView.contentCheckHooks;
7205 if (contentCheckHooks !== null) {
7206 executeCheckHooks(lView, contentCheckHooks);
7207 }
7208 }
7209 else {
7210 const contentHooks = tView.contentHooks;
7211 if (contentHooks !== null) {
7212 executeInitAndCheckHooks(lView, contentHooks, 1 /* AfterContentInitHooksToBeRun */);
7213 }
7214 incrementInitPhaseFlags(lView, 1 /* AfterContentInitHooksToBeRun */);
7215 }
7216 }
7217 setHostBindingsByExecutingExpandoInstructions(tView, lView);
7218 // Refresh child component views.
7219 const components = tView.components;
7220 if (components !== null) {
7221 refreshChildComponents(lView, components);
7222 }
7223 // View queries must execute after refreshing child components because a template in this view
7224 // could be inserted in a child component. If the view query executes before child component
7225 // refresh, the template might not yet be inserted.
7226 const viewQuery = tView.viewQuery;
7227 if (viewQuery !== null) {
7228 executeViewQueryFn(2 /* Update */, viewQuery, context);
7229 }
7230 // execute view hooks (AfterViewInit, AfterViewChecked)
7231 // PERF WARNING: do NOT extract this to a separate function without running benchmarks
7232 if (!checkNoChangesMode) {
7233 if (hooksInitPhaseCompleted) {
7234 const viewCheckHooks = tView.viewCheckHooks;
7235 if (viewCheckHooks !== null) {
7236 executeCheckHooks(lView, viewCheckHooks);
7237 }
7238 }
7239 else {
7240 const viewHooks = tView.viewHooks;
7241 if (viewHooks !== null) {
7242 executeInitAndCheckHooks(lView, viewHooks, 2 /* AfterViewInitHooksToBeRun */);
7243 }
7244 incrementInitPhaseFlags(lView, 2 /* AfterViewInitHooksToBeRun */);
7245 }
7246 }
7247 if (tView.firstUpdatePass === true) {
7248 // We need to make sure that we only flip the flag on successful `refreshView` only
7249 // Don't do this in `finally` block.
7250 // If we did this in `finally` block then an exception could block the execution of styling
7251 // instructions which in turn would be unable to insert themselves into the styling linked
7252 // list. The result of this would be that if the exception would not be throw on subsequent CD
7253 // the styling would be unable to process it data and reflect to the DOM.
7254 tView.firstUpdatePass = false;
7255 }
7256 // Do not reset the dirty state when running in check no changes mode. We don't want components
7257 // to behave differently depending on whether check no changes is enabled or not. For example:
7258 // Marking an OnPush component as dirty from within the `ngAfterViewInit` hook in order to
7259 // refresh a `NgClass` binding should work. If we would reset the dirty state in the check
7260 // no changes cycle, the component would be not be dirty for the next update pass. This would
7261 // be different in production mode where the component dirty state is not reset.
7262 if (!checkNoChangesMode) {
7263 lView[FLAGS] &= ~(64 /* Dirty */ | 8 /* FirstLViewPass */);
7264 }
7265 if (lView[FLAGS] & 1024 /* RefreshTransplantedView */) {
7266 lView[FLAGS] &= ~1024 /* RefreshTransplantedView */;
7267 updateTransplantedViewCount(lView[PARENT], -1);
7268 }
7269 }
7270 finally {
7271 leaveView();
7272 }
7273}
7274function renderComponentOrTemplate(tView, lView, templateFn, context) {
7275 const rendererFactory = lView[RENDERER_FACTORY];
7276 const normalExecutionPath = !getCheckNoChangesMode();
7277 const creationModeIsActive = isCreationMode(lView);
7278 try {
7279 if (normalExecutionPath && !creationModeIsActive && rendererFactory.begin) {
7280 rendererFactory.begin();
7281 }
7282 if (creationModeIsActive) {
7283 renderView(tView, lView, context);
7284 }
7285 refreshView(tView, lView, templateFn, context);
7286 }
7287 finally {
7288 if (normalExecutionPath && !creationModeIsActive && rendererFactory.end) {
7289 rendererFactory.end();
7290 }
7291 }
7292}
7293function executeTemplate(tView, lView, templateFn, rf, context) {
7294 const prevSelectedIndex = getSelectedIndex();
7295 try {
7296 setSelectedIndex(-1);
7297 if (rf & 2 /* Update */ && lView.length > HEADER_OFFSET) {
7298 // When we're updating, inherently select 0 so we don't
7299 // have to generate that instruction for most update blocks.
7300 selectIndexInternal(tView, lView, 0, getCheckNoChangesMode());
7301 }
7302 templateFn(rf, context);
7303 }
7304 finally {
7305 setSelectedIndex(prevSelectedIndex);
7306 }
7307}
7308//////////////////////////
7309//// Element
7310//////////////////////////
7311function executeContentQueries(tView, tNode, lView) {
7312 if (isContentQueryHost(tNode)) {
7313 const start = tNode.directiveStart;
7314 const end = tNode.directiveEnd;
7315 for (let directiveIndex = start; directiveIndex < end; directiveIndex++) {
7316 const def = tView.data[directiveIndex];
7317 if (def.contentQueries) {
7318 def.contentQueries(1 /* Create */, lView[directiveIndex], directiveIndex);
7319 }
7320 }
7321 }
7322}
7323/**
7324 * Creates directive instances.
7325 */
7326function createDirectivesInstances(tView, lView, tNode) {
7327 if (!getBindingsEnabled())
7328 return;
7329 instantiateAllDirectives(tView, lView, tNode, getNativeByTNode(tNode, lView));
7330 if ((tNode.flags & 128 /* hasHostBindings */) === 128 /* hasHostBindings */) {
7331 invokeDirectivesHostBindings(tView, lView, tNode);
7332 }
7333}
7334/**
7335 * Takes a list of local names and indices and pushes the resolved local variable values
7336 * to LView in the same order as they are loaded in the template with load().
7337 */
7338function saveResolvedLocalsInData(viewData, tNode, localRefExtractor = getNativeByTNode) {
7339 const localNames = tNode.localNames;
7340 if (localNames !== null) {
7341 let localIndex = tNode.index + 1;
7342 for (let i = 0; i < localNames.length; i += 2) {
7343 const index = localNames[i + 1];
7344 const value = index === -1 ?
7345 localRefExtractor(tNode, viewData) :
7346 viewData[index];
7347 viewData[localIndex++] = value;
7348 }
7349 }
7350}
7351/**
7352 * Gets TView from a template function or creates a new TView
7353 * if it doesn't already exist.
7354 *
7355 * @param def ComponentDef
7356 * @returns TView
7357 */
7358function getOrCreateTComponentView(def) {
7359 const tView = def.tView;
7360 // Create a TView if there isn't one, or recreate it if the first create pass didn't
7361 // complete successfuly since we can't know for sure whether it's in a usable shape.
7362 if (tView === null || tView.incompleteFirstPass) {
7363 return def.tView = createTView(1 /* Component */, -1, def.template, def.decls, def.vars, def.directiveDefs, def.pipeDefs, def.viewQuery, def.schemas, def.consts);
7364 }
7365 return tView;
7366}
7367/**
7368 * Creates a TView instance
7369 *
7370 * @param viewIndex The viewBlockId for inline views, or -1 if it's a component/dynamic
7371 * @param templateFn Template function
7372 * @param decls The number of nodes, local refs, and pipes in this template
7373 * @param directives Registry of directives for this view
7374 * @param pipes Registry of pipes for this view
7375 * @param viewQuery View queries for this view
7376 * @param schemas Schemas for this view
7377 * @param consts Constants for this view
7378 */
7379function createTView(type, viewIndex, templateFn, decls, vars, directives, pipes, viewQuery, schemas, consts) {
7380 ngDevMode && ngDevMode.tView++;
7381 const bindingStartIndex = HEADER_OFFSET + decls;
7382 // This length does not yet contain host bindings from child directives because at this point,
7383 // we don't know which directives are active on this template. As soon as a directive is matched
7384 // that has a host binding, we will update the blueprint with that def's hostVars count.
7385 const initialViewLength = bindingStartIndex + vars;
7386 const blueprint = createViewBlueprint(bindingStartIndex, initialViewLength);
7387 const tView = blueprint[TVIEW] = ngDevMode ?
7388 new TViewConstructor(type, viewIndex, // id: number,
7389 blueprint, // blueprint: LView,
7390 templateFn, // template: ComponentTemplate<{}>|null,
7391 null, // queries: TQueries|null
7392 viewQuery, // viewQuery: ViewQueriesFunction<{}>|null,
7393 null, // node: TViewNode|TElementNode|null,
7394 cloneToTViewData(blueprint).fill(null, bindingStartIndex), // data: TData,
7395 bindingStartIndex, // bindingStartIndex: number,
7396 initialViewLength, // expandoStartIndex: number,
7397 null, // expandoInstructions: ExpandoInstructions|null,
7398 true, // firstCreatePass: boolean,
7399 true, // firstUpdatePass: boolean,
7400 false, // staticViewQueries: boolean,
7401 false, // staticContentQueries: boolean,
7402 null, // preOrderHooks: HookData|null,
7403 null, // preOrderCheckHooks: HookData|null,
7404 null, // contentHooks: HookData|null,
7405 null, // contentCheckHooks: HookData|null,
7406 null, // viewHooks: HookData|null,
7407 null, // viewCheckHooks: HookData|null,
7408 null, // destroyHooks: DestroyHookData|null,
7409 null, // cleanup: any[]|null,
7410 null, // contentQueries: number[]|null,
7411 null, // components: number[]|null,
7412 typeof directives === 'function' ?
7413 directives() :
7414 directives, // directiveRegistry: DirectiveDefList|null,
7415 typeof pipes === 'function' ? pipes() : pipes, // pipeRegistry: PipeDefList|null,
7416 null, // firstChild: TNode|null,
7417 schemas, // schemas: SchemaMetadata[]|null,
7418 consts, // consts: TConstants|null
7419 false, // incompleteFirstPass: boolean
7420 decls, // ngDevMode only: decls
7421 vars) :
7422 {
7423 type: type,
7424 id: viewIndex,
7425 blueprint: blueprint,
7426 template: templateFn,
7427 queries: null,
7428 viewQuery: viewQuery,
7429 node: null,
7430 data: blueprint.slice().fill(null, bindingStartIndex),
7431 bindingStartIndex: bindingStartIndex,
7432 expandoStartIndex: initialViewLength,
7433 expandoInstructions: null,
7434 firstCreatePass: true,
7435 firstUpdatePass: true,
7436 staticViewQueries: false,
7437 staticContentQueries: false,
7438 preOrderHooks: null,
7439 preOrderCheckHooks: null,
7440 contentHooks: null,
7441 contentCheckHooks: null,
7442 viewHooks: null,
7443 viewCheckHooks: null,
7444 destroyHooks: null,
7445 cleanup: null,
7446 contentQueries: null,
7447 components: null,
7448 directiveRegistry: typeof directives === 'function' ? directives() : directives,
7449 pipeRegistry: typeof pipes === 'function' ? pipes() : pipes,
7450 firstChild: null,
7451 schemas: schemas,
7452 consts: consts,
7453 incompleteFirstPass: false
7454 };
7455 if (ngDevMode) {
7456 // For performance reasons it is important that the tView retains the same shape during runtime.
7457 // (To make sure that all of the code is monomorphic.) For this reason we seal the object to
7458 // prevent class transitions.
7459 Object.seal(tView);
7460 }
7461 return tView;
7462}
7463function createViewBlueprint(bindingStartIndex, initialViewLength) {
7464 const blueprint = ngDevMode ? new LViewBlueprint() : [];
7465 for (let i = 0; i < initialViewLength; i++) {
7466 blueprint.push(i < bindingStartIndex ? null : NO_CHANGE);
7467 }
7468 return blueprint;
7469}
7470function createError(text, token) {
7471 return new Error(`Renderer: ${text} [${stringifyForError(token)}]`);
7472}
7473function assertHostNodeExists(rElement, elementOrSelector) {
7474 if (!rElement) {
7475 if (typeof elementOrSelector === 'string') {
7476 throw createError('Host node with selector not found:', elementOrSelector);
7477 }
7478 else {
7479 throw createError('Host node is required:', elementOrSelector);
7480 }
7481 }
7482}
7483/**
7484 * Locates the host native element, used for bootstrapping existing nodes into rendering pipeline.
7485 *
7486 * @param rendererFactory Factory function to create renderer instance.
7487 * @param elementOrSelector Render element or CSS selector to locate the element.
7488 * @param encapsulation View Encapsulation defined for component that requests host element.
7489 */
7490function locateHostElement(renderer, elementOrSelector, encapsulation) {
7491 if (isProceduralRenderer(renderer)) {
7492 // When using native Shadow DOM, do not clear host element to allow native slot projection
7493 const preserveContent = encapsulation === ViewEncapsulation$1.ShadowDom;
7494 return renderer.selectRootElement(elementOrSelector, preserveContent);
7495 }
7496 let rElement = typeof elementOrSelector === 'string' ?
7497 renderer.querySelector(elementOrSelector) :
7498 elementOrSelector;
7499 ngDevMode && assertHostNodeExists(rElement, elementOrSelector);
7500 // Always clear host element's content when Renderer3 is in use. For procedural renderer case we
7501 // make it depend on whether ShadowDom encapsulation is used (in which case the content should be
7502 // preserved to allow native slot projection). ShadowDom encapsulation requires procedural
7503 // renderer, and procedural renderer case is handled above.
7504 rElement.textContent = '';
7505 return rElement;
7506}
7507/**
7508 * Saves context for this cleanup function in LView.cleanupInstances.
7509 *
7510 * On the first template pass, saves in TView:
7511 * - Cleanup function
7512 * - Index of context we just saved in LView.cleanupInstances
7513 */
7514function storeCleanupWithContext(tView, lView, context, cleanupFn) {
7515 const lCleanup = getLCleanup(lView);
7516 lCleanup.push(context);
7517 if (tView.firstCreatePass) {
7518 getTViewCleanup(tView).push(cleanupFn, lCleanup.length - 1);
7519 }
7520}
7521/**
7522 * Constructs a TNode object from the arguments.
7523 *
7524 * @param tView `TView` to which this `TNode` belongs (used only in `ngDevMode`)
7525 * @param type The type of the node
7526 * @param adjustedIndex The index of the TNode in TView.data, adjusted for HEADER_OFFSET
7527 * @param tagName The tag name of the node
7528 * @param attrs The attributes defined on this node
7529 * @param tViews Any TViews attached to this node
7530 * @returns the TNode object
7531 */
7532function createTNode(tView, tParent, type, adjustedIndex, tagName, attrs) {
7533 ngDevMode && ngDevMode.tNode++;
7534 let injectorIndex = tParent ? tParent.injectorIndex : -1;
7535 const tNode = ngDevMode ?
7536 new TNodeDebug(tView, // tView_: TView
7537 type, // type: TNodeType
7538 adjustedIndex, // index: number
7539 injectorIndex, // injectorIndex: number
7540 -1, // directiveStart: number
7541 -1, // directiveEnd: number
7542 -1, // directiveStylingLast: number
7543 null, // propertyBindings: number[]|null
7544 0, // flags: TNodeFlags
7545 0, // providerIndexes: TNodeProviderIndexes
7546 tagName, // tagName: string|null
7547 attrs, // attrs: (string|AttributeMarker|(string|SelectorFlags)[])[]|null
7548 null, // mergedAttrs
7549 null, // localNames: (string|number)[]|null
7550 undefined, // initialInputs: (string[]|null)[]|null|undefined
7551 null, // inputs: PropertyAliases|null
7552 null, // outputs: PropertyAliases|null
7553 null, // tViews: ITView|ITView[]|null
7554 null, // next: ITNode|null
7555 null, // projectionNext: ITNode|null
7556 null, // child: ITNode|null
7557 tParent, // parent: TElementNode|TContainerNode|null
7558 null, // projection: number|(ITNode|RNode[])[]|null
7559 null, // styles: string|null
7560 null, // stylesWithoutHost: string|null
7561 undefined, // residualStyles: string|null
7562 null, // classes: string|null
7563 null, // classesWithoutHost: string|null
7564 undefined, // residualClasses: string|null
7565 0, // classBindings: TStylingRange;
7566 0) :
7567 {
7568 type: type,
7569 index: adjustedIndex,
7570 injectorIndex: injectorIndex,
7571 directiveStart: -1,
7572 directiveEnd: -1,
7573 directiveStylingLast: -1,
7574 propertyBindings: null,
7575 flags: 0,
7576 providerIndexes: 0,
7577 tagName: tagName,
7578 attrs: attrs,
7579 mergedAttrs: null,
7580 localNames: null,
7581 initialInputs: undefined,
7582 inputs: null,
7583 outputs: null,
7584 tViews: null,
7585 next: null,
7586 projectionNext: null,
7587 child: null,
7588 parent: tParent,
7589 projection: null,
7590 styles: null,
7591 stylesWithoutHost: null,
7592 residualStyles: undefined,
7593 classes: null,
7594 classesWithoutHost: null,
7595 residualClasses: undefined,
7596 classBindings: 0,
7597 styleBindings: 0,
7598 };
7599 if (ngDevMode) {
7600 // For performance reasons it is important that the tNode retains the same shape during runtime.
7601 // (To make sure that all of the code is monomorphic.) For this reason we seal the object to
7602 // prevent class transitions.
7603 Object.seal(tNode);
7604 }
7605 return tNode;
7606}
7607function generatePropertyAliases(inputAliasMap, directiveDefIdx, propStore) {
7608 for (let publicName in inputAliasMap) {
7609 if (inputAliasMap.hasOwnProperty(publicName)) {
7610 propStore = propStore === null ? {} : propStore;
7611 const internalName = inputAliasMap[publicName];
7612 if (propStore.hasOwnProperty(publicName)) {
7613 propStore[publicName].push(directiveDefIdx, internalName);
7614 }
7615 else {
7616 (propStore[publicName] = [directiveDefIdx, internalName]);
7617 }
7618 }
7619 }
7620 return propStore;
7621}
7622/**
7623 * Initializes data structures required to work with directive outputs and outputs.
7624 * Initialization is done for all directives matched on a given TNode.
7625 */
7626function initializeInputAndOutputAliases(tView, tNode) {
7627 ngDevMode && assertFirstCreatePass(tView);
7628 const start = tNode.directiveStart;
7629 const end = tNode.directiveEnd;
7630 const defs = tView.data;
7631 const tNodeAttrs = tNode.attrs;
7632 const inputsFromAttrs = ngDevMode ? new TNodeInitialInputs() : [];
7633 let inputsStore = null;
7634 let outputsStore = null;
7635 for (let i = start; i < end; i++) {
7636 const directiveDef = defs[i];
7637 const directiveInputs = directiveDef.inputs;
7638 // Do not use unbound attributes as inputs to structural directives, since structural
7639 // directive inputs can only be set using microsyntax (e.g. `<div *dir="exp">`).
7640 // TODO(FW-1930): microsyntax expressions may also contain unbound/static attributes, which
7641 // should be set for inline templates.
7642 const initialInputs = (tNodeAttrs !== null && !isInlineTemplate(tNode)) ?
7643 generateInitialInputs(directiveInputs, tNodeAttrs) :
7644 null;
7645 inputsFromAttrs.push(initialInputs);
7646 inputsStore = generatePropertyAliases(directiveInputs, i, inputsStore);
7647 outputsStore = generatePropertyAliases(directiveDef.outputs, i, outputsStore);
7648 }
7649 if (inputsStore !== null) {
7650 if (inputsStore.hasOwnProperty('class')) {
7651 tNode.flags |= 16 /* hasClassInput */;
7652 }
7653 if (inputsStore.hasOwnProperty('style')) {
7654 tNode.flags |= 32 /* hasStyleInput */;
7655 }
7656 }
7657 tNode.initialInputs = inputsFromAttrs;
7658 tNode.inputs = inputsStore;
7659 tNode.outputs = outputsStore;
7660}
7661/**
7662 * Mapping between attributes names that don't correspond to their element property names.
7663 *
7664 * Performance note: this function is written as a series of if checks (instead of, say, a property
7665 * object lookup) for performance reasons - the series of `if` checks seems to be the fastest way of
7666 * mapping property names. Do NOT change without benchmarking.
7667 *
7668 * Note: this mapping has to be kept in sync with the equally named mapping in the template
7669 * type-checking machinery of ngtsc.
7670 */
7671function mapPropName(name) {
7672 if (name === 'class')
7673 return 'className';
7674 if (name === 'for')
7675 return 'htmlFor';
7676 if (name === 'formaction')
7677 return 'formAction';
7678 if (name === 'innerHtml')
7679 return 'innerHTML';
7680 if (name === 'readonly')
7681 return 'readOnly';
7682 if (name === 'tabindex')
7683 return 'tabIndex';
7684 return name;
7685}
7686function elementPropertyInternal(tView, tNode, lView, propName, value, renderer, sanitizer, nativeOnly) {
7687 ngDevMode && assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
7688 const element = getNativeByTNode(tNode, lView);
7689 let inputData = tNode.inputs;
7690 let dataValue;
7691 if (!nativeOnly && inputData != null && (dataValue = inputData[propName])) {
7692 setInputsForProperty(tView, lView, dataValue, propName, value);
7693 if (isComponentHost(tNode))
7694 markDirtyIfOnPush(lView, tNode.index);
7695 if (ngDevMode) {
7696 setNgReflectProperties(lView, element, tNode.type, dataValue, value);
7697 }
7698 }
7699 else if (tNode.type === 3 /* Element */) {
7700 propName = mapPropName(propName);
7701 if (ngDevMode) {
7702 validateAgainstEventProperties(propName);
7703 if (!validateProperty(tView, element, propName, tNode)) {
7704 // Return here since we only log warnings for unknown properties.
7705 logUnknownPropertyError(propName, tNode);
7706 return;
7707 }
7708 ngDevMode.rendererSetProperty++;
7709 }
7710 // It is assumed that the sanitizer is only added when the compiler determines that the
7711 // property is risky, so sanitization can be done without further checks.
7712 value = sanitizer != null ? sanitizer(value, tNode.tagName || '', propName) : value;
7713 if (isProceduralRenderer(renderer)) {
7714 renderer.setProperty(element, propName, value);
7715 }
7716 else if (!isAnimationProp(propName)) {
7717 element.setProperty ? element.setProperty(propName, value) :
7718 element[propName] = value;
7719 }
7720 }
7721 else if (tNode.type === 0 /* Container */ || tNode.type === 4 /* ElementContainer */) {
7722 // If the node is a container and the property didn't
7723 // match any of the inputs or schemas we should throw.
7724 if (ngDevMode && !matchingSchemas(tView, tNode.tagName)) {
7725 logUnknownPropertyError(propName, tNode);
7726 }
7727 }
7728}
7729/** If node is an OnPush component, marks its LView dirty. */
7730function markDirtyIfOnPush(lView, viewIndex) {
7731 ngDevMode && assertLView(lView);
7732 const childComponentLView = getComponentLViewByIndex(viewIndex, lView);
7733 if (!(childComponentLView[FLAGS] & 16 /* CheckAlways */)) {
7734 childComponentLView[FLAGS] |= 64 /* Dirty */;
7735 }
7736}
7737function setNgReflectProperty(lView, element, type, attrName, value) {
7738 const renderer = lView[RENDERER];
7739 attrName = normalizeDebugBindingName(attrName);
7740 const debugValue = normalizeDebugBindingValue(value);
7741 if (type === 3 /* Element */) {
7742 if (value == null) {
7743 isProceduralRenderer(renderer) ? renderer.removeAttribute(element, attrName) :
7744 element.removeAttribute(attrName);
7745 }
7746 else {
7747 isProceduralRenderer(renderer) ?
7748 renderer.setAttribute(element, attrName, debugValue) :
7749 element.setAttribute(attrName, debugValue);
7750 }
7751 }
7752 else {
7753 const textContent = `bindings=${JSON.stringify({ [attrName]: debugValue }, null, 2)}`;
7754 if (isProceduralRenderer(renderer)) {
7755 renderer.setValue(element, textContent);
7756 }
7757 else {
7758 element.textContent = textContent;
7759 }
7760 }
7761}
7762function setNgReflectProperties(lView, element, type, dataValue, value) {
7763 if (type === 3 /* Element */ || type === 0 /* Container */) {
7764 /**
7765 * dataValue is an array containing runtime input or output names for the directives:
7766 * i+0: directive instance index
7767 * i+1: privateName
7768 *
7769 * e.g. [0, 'change', 'change-minified']
7770 * we want to set the reflected property with the privateName: dataValue[i+1]
7771 */
7772 for (let i = 0; i < dataValue.length; i += 2) {
7773 setNgReflectProperty(lView, element, type, dataValue[i + 1], value);
7774 }
7775 }
7776}
7777function validateProperty(tView, element, propName, tNode) {
7778 // If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
7779 // mode where this check happens at compile time. In JIT mode, `schemas` is always present and
7780 // defined as an array (as an empty array in case `schemas` field is not defined) and we should
7781 // execute the check below.
7782 if (tView.schemas === null)
7783 return true;
7784 // The property is considered valid if the element matches the schema, it exists on the element
7785 // or it is synthetic, and we are in a browser context (web worker nodes should be skipped).
7786 if (matchingSchemas(tView, tNode.tagName) || propName in element || isAnimationProp(propName)) {
7787 return true;
7788 }
7789 // Note: `typeof Node` returns 'function' in most browsers, but on IE it is 'object' so we
7790 // need to account for both here, while being careful for `typeof null` also returning 'object'.
7791 return typeof Node === 'undefined' || Node === null || !(element instanceof Node);
7792}
7793function matchingSchemas(tView, tagName) {
7794 const schemas = tView.schemas;
7795 if (schemas !== null) {
7796 for (let i = 0; i < schemas.length; i++) {
7797 const schema = schemas[i];
7798 if (schema === NO_ERRORS_SCHEMA ||
7799 schema === CUSTOM_ELEMENTS_SCHEMA && tagName && tagName.indexOf('-') > -1) {
7800 return true;
7801 }
7802 }
7803 }
7804 return false;
7805}
7806/**
7807 * Logs an error that a property is not supported on an element.
7808 * @param propName Name of the invalid property.
7809 * @param tNode Node on which we encountered the property.
7810 */
7811function logUnknownPropertyError(propName, tNode) {
7812 console.error(`Can't bind to '${propName}' since it isn't a known property of '${tNode.tagName}'.`);
7813}
7814/**
7815 * Instantiate a root component.
7816 */
7817function instantiateRootComponent(tView, lView, def) {
7818 const rootTNode = getPreviousOrParentTNode();
7819 if (tView.firstCreatePass) {
7820 if (def.providersResolver)
7821 def.providersResolver(def);
7822 generateExpandoInstructionBlock(tView, rootTNode, 1);
7823 baseResolveDirective(tView, lView, def);
7824 }
7825 const directive = getNodeInjectable(lView, tView, lView.length - 1, rootTNode);
7826 attachPatchData(directive, lView);
7827 const native = getNativeByTNode(rootTNode, lView);
7828 if (native) {
7829 attachPatchData(native, lView);
7830 }
7831 return directive;
7832}
7833/**
7834 * Resolve the matched directives on a node.
7835 */
7836function resolveDirectives(tView, lView, tNode, localRefs) {
7837 // Please make sure to have explicit type for `exportsMap`. Inferred type triggers bug in
7838 // tsickle.
7839 ngDevMode && assertFirstCreatePass(tView);
7840 let hasDirectives = false;
7841 if (getBindingsEnabled()) {
7842 const directiveDefs = findDirectiveDefMatches(tView, lView, tNode);
7843 const exportsMap = localRefs === null ? null : { '': -1 };
7844 if (directiveDefs !== null) {
7845 let totalDirectiveHostVars = 0;
7846 hasDirectives = true;
7847 initTNodeFlags(tNode, tView.data.length, directiveDefs.length);
7848 // When the same token is provided by several directives on the same node, some rules apply in
7849 // the viewEngine:
7850 // - viewProviders have priority over providers
7851 // - the last directive in NgModule.declarations has priority over the previous one
7852 // So to match these rules, the order in which providers are added in the arrays is very
7853 // important.
7854 for (let i = 0; i < directiveDefs.length; i++) {
7855 const def = directiveDefs[i];
7856 if (def.providersResolver)
7857 def.providersResolver(def);
7858 }
7859 generateExpandoInstructionBlock(tView, tNode, directiveDefs.length);
7860 let preOrderHooksFound = false;
7861 let preOrderCheckHooksFound = false;
7862 for (let i = 0; i < directiveDefs.length; i++) {
7863 const def = directiveDefs[i];
7864 // Merge the attrs in the order of matches. This assumes that the first directive is the
7865 // component itself, so that the component has the least priority.
7866 tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, def.hostAttrs);
7867 baseResolveDirective(tView, lView, def);
7868 saveNameToExportMap(tView.data.length - 1, def, exportsMap);
7869 if (def.contentQueries !== null)
7870 tNode.flags |= 8 /* hasContentQuery */;
7871 if (def.hostBindings !== null || def.hostAttrs !== null || def.hostVars !== 0)
7872 tNode.flags |= 128 /* hasHostBindings */;
7873 const lifeCycleHooks = def.type.prototype;
7874 // Only push a node index into the preOrderHooks array if this is the first
7875 // pre-order hook found on this node.
7876 if (!preOrderHooksFound &&
7877 (lifeCycleHooks.ngOnChanges || lifeCycleHooks.ngOnInit || lifeCycleHooks.ngDoCheck)) {
7878 // We will push the actual hook function into this array later during dir instantiation.
7879 // We cannot do it now because we must ensure hooks are registered in the same
7880 // order that directives are created (i.e. injection order).
7881 (tView.preOrderHooks || (tView.preOrderHooks = [])).push(tNode.index - HEADER_OFFSET);
7882 preOrderHooksFound = true;
7883 }
7884 if (!preOrderCheckHooksFound && (lifeCycleHooks.ngOnChanges || lifeCycleHooks.ngDoCheck)) {
7885 (tView.preOrderCheckHooks || (tView.preOrderCheckHooks = []))
7886 .push(tNode.index - HEADER_OFFSET);
7887 preOrderCheckHooksFound = true;
7888 }
7889 addHostBindingsToExpandoInstructions(tView, def);
7890 totalDirectiveHostVars += def.hostVars;
7891 }
7892 initializeInputAndOutputAliases(tView, tNode);
7893 growHostVarsSpace(tView, lView, totalDirectiveHostVars);
7894 }
7895 if (exportsMap)
7896 cacheMatchingLocalNames(tNode, localRefs, exportsMap);
7897 }
7898 // Merge the template attrs last so that they have the highest priority.
7899 tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, tNode.attrs);
7900 return hasDirectives;
7901}
7902/**
7903 * Add `hostBindings` to the `TView.expandoInstructions`.
7904 *
7905 * @param tView `TView` to which the `hostBindings` should be added.
7906 * @param def `ComponentDef`/`DirectiveDef`, which contains the `hostVars`/`hostBindings` to add.
7907 */
7908function addHostBindingsToExpandoInstructions(tView, def) {
7909 ngDevMode && assertFirstCreatePass(tView);
7910 const expando = tView.expandoInstructions;
7911 // TODO(misko): PERF we are adding `hostBindings` even if there is nothing to add! This is
7912 // suboptimal for performance. `def.hostBindings` may be null,
7913 // but we still need to push null to the array as a placeholder
7914 // to ensure the directive counter is incremented (so host
7915 // binding functions always line up with the corrective directive).
7916 // This is suboptimal for performance. See `currentDirectiveIndex`
7917 // comment in `setHostBindingsByExecutingExpandoInstructions` for more
7918 // details. expando.push(def.hostBindings);
7919 expando.push(def.hostBindings);
7920 const hostVars = def.hostVars;
7921 if (hostVars !== 0) {
7922 expando.push(def.hostVars);
7923 }
7924}
7925/**
7926 * Grow the `LView`, blueprint and `TView.data` to accommodate the `hostBindings`.
7927 *
7928 * To support locality we don't know ahead of time how many `hostVars` of the containing directives
7929 * we need to allocate. For this reason we allow growing these data structures as we discover more
7930 * directives to accommodate them.
7931 *
7932 * @param tView `TView` which needs to be grown.
7933 * @param lView `LView` which needs to be grown.
7934 * @param count Size by which we need to grow the data structures.
7935 */
7936function growHostVarsSpace(tView, lView, count) {
7937 ngDevMode && assertFirstCreatePass(tView);
7938 ngDevMode && assertSame(tView, lView[TVIEW], '`LView` must be associated with `TView`!');
7939 for (let i = 0; i < count; i++) {
7940 lView.push(NO_CHANGE);
7941 tView.blueprint.push(NO_CHANGE);
7942 tView.data.push(null);
7943 }
7944}
7945/**
7946 * Instantiate all the directives that were previously resolved on the current node.
7947 */
7948function instantiateAllDirectives(tView, lView, tNode, native) {
7949 const start = tNode.directiveStart;
7950 const end = tNode.directiveEnd;
7951 if (!tView.firstCreatePass) {
7952 getOrCreateNodeInjectorForNode(tNode, lView);
7953 }
7954 attachPatchData(native, lView);
7955 const initialInputs = tNode.initialInputs;
7956 for (let i = start; i < end; i++) {
7957 const def = tView.data[i];
7958 const isComponent = isComponentDef(def);
7959 if (isComponent) {
7960 ngDevMode && assertNodeOfPossibleTypes(tNode, [3 /* Element */]);
7961 addComponentLogic(lView, tNode, def);
7962 }
7963 const directive = getNodeInjectable(lView, tView, i, tNode);
7964 attachPatchData(directive, lView);
7965 if (initialInputs !== null) {
7966 setInputsFromAttrs(lView, i - start, directive, def, tNode, initialInputs);
7967 }
7968 if (isComponent) {
7969 const componentView = getComponentLViewByIndex(tNode.index, lView);
7970 componentView[CONTEXT] = directive;
7971 }
7972 }
7973}
7974function invokeDirectivesHostBindings(tView, lView, tNode) {
7975 const start = tNode.directiveStart;
7976 const end = tNode.directiveEnd;
7977 const expando = tView.expandoInstructions;
7978 const firstCreatePass = tView.firstCreatePass;
7979 const elementIndex = tNode.index - HEADER_OFFSET;
7980 const currentDirectiveIndex = getCurrentDirectiveIndex();
7981 try {
7982 setSelectedIndex(elementIndex);
7983 for (let dirIndex = start; dirIndex < end; dirIndex++) {
7984 const def = tView.data[dirIndex];
7985 const directive = lView[dirIndex];
7986 setCurrentDirectiveIndex(dirIndex);
7987 if (def.hostBindings !== null || def.hostVars !== 0 || def.hostAttrs !== null) {
7988 invokeHostBindingsInCreationMode(def, directive);
7989 }
7990 else if (firstCreatePass) {
7991 expando.push(null);
7992 }
7993 }
7994 }
7995 finally {
7996 setSelectedIndex(-1);
7997 setCurrentDirectiveIndex(currentDirectiveIndex);
7998 }
7999}
8000/**
8001 * Invoke the host bindings in creation mode.
8002 *
8003 * @param def `DirectiveDef` which may contain the `hostBindings` function.
8004 * @param directive Instance of directive.
8005 */
8006function invokeHostBindingsInCreationMode(def, directive) {
8007 if (def.hostBindings !== null) {
8008 def.hostBindings(1 /* Create */, directive);
8009 }
8010}
8011/**
8012 * Generates a new block in TView.expandoInstructions for this node.
8013 *
8014 * Each expando block starts with the element index (turned negative so we can distinguish
8015 * it from the hostVar count) and the directive count. See more in VIEW_DATA.md.
8016 */
8017function generateExpandoInstructionBlock(tView, tNode, directiveCount) {
8018 ngDevMode &&
8019 assertEqual(tView.firstCreatePass, true, 'Expando block should only be generated on first create pass.');
8020 // Important: In JS `-x` and `0-x` is not the same! If `x===0` then `-x` will produce `-0` which
8021 // requires non standard math arithmetic and it can prevent VM optimizations.
8022 // `0-0` will always produce `0` and will not cause a potential deoptimization in VM.
8023 const elementIndex = HEADER_OFFSET - tNode.index;
8024 const providerStartIndex = tNode.providerIndexes & 1048575 /* ProvidersStartIndexMask */;
8025 const providerCount = tView.data.length - providerStartIndex;
8026 (tView.expandoInstructions || (tView.expandoInstructions = []))
8027 .push(elementIndex, providerCount, directiveCount);
8028}
8029/**
8030 * Matches the current node against all available selectors.
8031 * If a component is matched (at most one), it is returned in first position in the array.
8032 */
8033function findDirectiveDefMatches(tView, viewData, tNode) {
8034 ngDevMode && assertFirstCreatePass(tView);
8035 ngDevMode &&
8036 assertNodeOfPossibleTypes(tNode, [3 /* Element */, 4 /* ElementContainer */, 0 /* Container */]);
8037 const registry = tView.directiveRegistry;
8038 let matches = null;
8039 if (registry) {
8040 for (let i = 0; i < registry.length; i++) {
8041 const def = registry[i];
8042 if (isNodeMatchingSelectorList(tNode, def.selectors, /* isProjectionMode */ false)) {
8043 matches || (matches = ngDevMode ? new MatchesArray() : []);
8044 diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, viewData), tView, def.type);
8045 if (isComponentDef(def)) {
8046 ngDevMode &&
8047 assertNodeOfPossibleTypes(tNode, [3 /* Element */], `"${tNode.tagName}" tags cannot be used as component hosts. ` +
8048 `Please use a different tag to activate the ${stringify(def.type)} component.`);
8049 if (tNode.flags & 2 /* isComponentHost */)
8050 throwMultipleComponentError(tNode);
8051 markAsComponentHost(tView, tNode);
8052 // The component is always stored first with directives after.
8053 matches.unshift(def);
8054 }
8055 else {
8056 matches.push(def);
8057 }
8058 }
8059 }
8060 }
8061 return matches;
8062}
8063/**
8064 * Marks a given TNode as a component's host. This consists of:
8065 * - setting appropriate TNode flags;
8066 * - storing index of component's host element so it will be queued for view refresh during CD.
8067 */
8068function markAsComponentHost(tView, hostTNode) {
8069 ngDevMode && assertFirstCreatePass(tView);
8070 hostTNode.flags |= 2 /* isComponentHost */;
8071 (tView.components || (tView.components = ngDevMode ? new TViewComponents() : []))
8072 .push(hostTNode.index);
8073}
8074/** Caches local names and their matching directive indices for query and template lookups. */
8075function cacheMatchingLocalNames(tNode, localRefs, exportsMap) {
8076 if (localRefs) {
8077 const localNames = tNode.localNames = ngDevMode ? new TNodeLocalNames() : [];
8078 // Local names must be stored in tNode in the same order that localRefs are defined
8079 // in the template to ensure the data is loaded in the same slots as their refs
8080 // in the template (for template queries).
8081 for (let i = 0; i < localRefs.length; i += 2) {
8082 const index = exportsMap[localRefs[i + 1]];
8083 if (index == null)
8084 throw new Error(`Export of name '${localRefs[i + 1]}' not found!`);
8085 localNames.push(localRefs[i], index);
8086 }
8087 }
8088}
8089/**
8090 * Builds up an export map as directives are created, so local refs can be quickly mapped
8091 * to their directive instances.
8092 */
8093function saveNameToExportMap(index, def, exportsMap) {
8094 if (exportsMap) {
8095 if (def.exportAs) {
8096 for (let i = 0; i < def.exportAs.length; i++) {
8097 exportsMap[def.exportAs[i]] = index;
8098 }
8099 }
8100 if (isComponentDef(def))
8101 exportsMap[''] = index;
8102 }
8103}
8104/**
8105 * Initializes the flags on the current node, setting all indices to the initial index,
8106 * the directive count to 0, and adding the isComponent flag.
8107 * @param index the initial index
8108 */
8109function initTNodeFlags(tNode, index, numberOfDirectives) {
8110 ngDevMode &&
8111 assertNotEqual(numberOfDirectives, tNode.directiveEnd - tNode.directiveStart, 'Reached the max number of directives');
8112 tNode.flags |= 1 /* isDirectiveHost */;
8113 // When the first directive is created on a node, save the index
8114 tNode.directiveStart = index;
8115 tNode.directiveEnd = index + numberOfDirectives;
8116 tNode.providerIndexes = index;
8117}
8118function baseResolveDirective(tView, viewData, def) {
8119 tView.data.push(def);
8120 const directiveFactory = def.factory || (def.factory = getFactoryDef(def.type, true));
8121 const nodeInjectorFactory = new NodeInjectorFactory(directiveFactory, isComponentDef(def), null);
8122 tView.blueprint.push(nodeInjectorFactory);
8123 viewData.push(nodeInjectorFactory);
8124}
8125function addComponentLogic(lView, hostTNode, def) {
8126 const native = getNativeByTNode(hostTNode, lView);
8127 const tView = getOrCreateTComponentView(def);
8128 // Only component views should be added to the view tree directly. Embedded views are
8129 // accessed through their containers because they may be removed / re-added later.
8130 const rendererFactory = lView[RENDERER_FACTORY];
8131 const componentView = addToViewTree(lView, createLView(lView, tView, null, def.onPush ? 64 /* Dirty */ : 16 /* CheckAlways */, native, hostTNode, rendererFactory, rendererFactory.createRenderer(native, def)));
8132 // Component view will always be created before any injected LContainers,
8133 // so this is a regular element, wrap it with the component view
8134 lView[hostTNode.index] = componentView;
8135}
8136function elementAttributeInternal(tNode, lView, name, value, sanitizer, namespace) {
8137 if (ngDevMode) {
8138 assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
8139 validateAgainstEventAttributes(name);
8140 assertNodeNotOfTypes(tNode, [0 /* Container */, 4 /* ElementContainer */], `Attempted to set attribute \`${name}\` on a container node. ` +
8141 `Host bindings are not valid on ng-container or ng-template.`);
8142 }
8143 const element = getNativeByTNode(tNode, lView);
8144 const renderer = lView[RENDERER];
8145 if (value == null) {
8146 ngDevMode && ngDevMode.rendererRemoveAttribute++;
8147 isProceduralRenderer(renderer) ? renderer.removeAttribute(element, name, namespace) :
8148 element.removeAttribute(name);
8149 }
8150 else {
8151 ngDevMode && ngDevMode.rendererSetAttribute++;
8152 const strValue = sanitizer == null ? renderStringify(value) : sanitizer(value, tNode.tagName || '', name);
8153 if (isProceduralRenderer(renderer)) {
8154 renderer.setAttribute(element, name, strValue, namespace);
8155 }
8156 else {
8157 namespace ? element.setAttributeNS(namespace, name, strValue) :
8158 element.setAttribute(name, strValue);
8159 }
8160 }
8161}
8162/**
8163 * Sets initial input properties on directive instances from attribute data
8164 *
8165 * @param lView Current LView that is being processed.
8166 * @param directiveIndex Index of the directive in directives array
8167 * @param instance Instance of the directive on which to set the initial inputs
8168 * @param def The directive def that contains the list of inputs
8169 * @param tNode The static data for this node
8170 */
8171function setInputsFromAttrs(lView, directiveIndex, instance, def, tNode, initialInputData) {
8172 const initialInputs = initialInputData[directiveIndex];
8173 if (initialInputs !== null) {
8174 const setInput = def.setInput;
8175 for (let i = 0; i < initialInputs.length;) {
8176 const publicName = initialInputs[i++];
8177 const privateName = initialInputs[i++];
8178 const value = initialInputs[i++];
8179 if (setInput !== null) {
8180 def.setInput(instance, value, publicName, privateName);
8181 }
8182 else {
8183 instance[privateName] = value;
8184 }
8185 if (ngDevMode) {
8186 const nativeElement = getNativeByTNode(tNode, lView);
8187 setNgReflectProperty(lView, nativeElement, tNode.type, privateName, value);
8188 }
8189 }
8190 }
8191}
8192/**
8193 * Generates initialInputData for a node and stores it in the template's static storage
8194 * so subsequent template invocations don't have to recalculate it.
8195 *
8196 * initialInputData is an array containing values that need to be set as input properties
8197 * for directives on this node, but only once on creation. We need this array to support
8198 * the case where you set an @Input property of a directive using attribute-like syntax.
8199 * e.g. if you have a `name` @Input, you can set it once like this:
8200 *
8201 * <my-component name="Bess"></my-component>
8202 *
8203 * @param inputs The list of inputs from the directive def
8204 * @param attrs The static attrs on this node
8205 */
8206function generateInitialInputs(inputs, attrs) {
8207 let inputsToStore = null;
8208 let i = 0;
8209 while (i < attrs.length) {
8210 const attrName = attrs[i];
8211 if (attrName === 0 /* NamespaceURI */) {
8212 // We do not allow inputs on namespaced attributes.
8213 i += 4;
8214 continue;
8215 }
8216 else if (attrName === 5 /* ProjectAs */) {
8217 // Skip over the `ngProjectAs` value.
8218 i += 2;
8219 continue;
8220 }
8221 // If we hit any other attribute markers, we're done anyway. None of those are valid inputs.
8222 if (typeof attrName === 'number')
8223 break;
8224 if (inputs.hasOwnProperty(attrName)) {
8225 if (inputsToStore === null)
8226 inputsToStore = [];
8227 inputsToStore.push(attrName, inputs[attrName], attrs[i + 1]);
8228 }
8229 i += 2;
8230 }
8231 return inputsToStore;
8232}
8233//////////////////////////
8234//// ViewContainer & View
8235//////////////////////////
8236// Not sure why I need to do `any` here but TS complains later.
8237const LContainerArray = ((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode()) &&
8238 createNamedArrayType('LContainer');
8239/**
8240 * Creates a LContainer, either from a container instruction, or for a ViewContainerRef.
8241 *
8242 * @param hostNative The host element for the LContainer
8243 * @param hostTNode The host TNode for the LContainer
8244 * @param currentView The parent view of the LContainer
8245 * @param native The native comment element
8246 * @param isForViewContainerRef Optional a flag indicating the ViewContainerRef case
8247 * @returns LContainer
8248 */
8249function createLContainer(hostNative, currentView, native, tNode) {
8250 ngDevMode && assertLView(currentView);
8251 ngDevMode && !isProceduralRenderer(currentView[RENDERER]) && assertDomNode(native);
8252 // https://jsperf.com/array-literal-vs-new-array-really
8253 const lContainer = new (ngDevMode ? LContainerArray : Array)(hostNative, // host native
8254 true, // Boolean `true` in this position signifies that this is an `LContainer`
8255 false, // has transplanted views
8256 currentView, // parent
8257 null, // next
8258 0, // transplanted views to refresh count
8259 tNode, // t_host
8260 native, // native,
8261 null, // view refs
8262 null);
8263 ngDevMode &&
8264 assertEqual(lContainer.length, CONTAINER_HEADER_OFFSET, 'Should allocate correct number of slots for LContainer header.');
8265 ngDevMode && attachLContainerDebug(lContainer);
8266 return lContainer;
8267}
8268/**
8269 * Goes over embedded views (ones created through ViewContainerRef APIs) and refreshes
8270 * them by executing an associated template function.
8271 */
8272function refreshEmbeddedViews(lView) {
8273 for (let lContainer = getFirstLContainer(lView); lContainer !== null; lContainer = getNextLContainer(lContainer)) {
8274 for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
8275 const embeddedLView = lContainer[i];
8276 const embeddedTView = embeddedLView[TVIEW];
8277 ngDevMode && assertDefined(embeddedTView, 'TView must be allocated');
8278 if (viewAttachedToChangeDetector(embeddedLView)) {
8279 refreshView(embeddedTView, embeddedLView, embeddedTView.template, embeddedLView[CONTEXT]);
8280 }
8281 }
8282 }
8283}
8284/**
8285 * Mark transplanted views as needing to be refreshed at their insertion points.
8286 *
8287 * @param lView The `LView` that may have transplanted views.
8288 */
8289function markTransplantedViewsForRefresh(lView) {
8290 for (let lContainer = getFirstLContainer(lView); lContainer !== null; lContainer = getNextLContainer(lContainer)) {
8291 if (!lContainer[HAS_TRANSPLANTED_VIEWS])
8292 continue;
8293 const movedViews = lContainer[MOVED_VIEWS];
8294 ngDevMode && assertDefined(movedViews, 'Transplanted View flags set but missing MOVED_VIEWS');
8295 for (let i = 0; i < movedViews.length; i++) {
8296 const movedLView = movedViews[i];
8297 const insertionLContainer = movedLView[PARENT];
8298 ngDevMode && assertLContainer(insertionLContainer);
8299 // We don't want to increment the counter if the moved LView was already marked for
8300 // refresh.
8301 if ((movedLView[FLAGS] & 1024 /* RefreshTransplantedView */) === 0) {
8302 updateTransplantedViewCount(insertionLContainer, 1);
8303 }
8304 // Note, it is possible that the `movedViews` is tracking views that are transplanted *and*
8305 // those that aren't (declaration component === insertion component). In the latter case,
8306 // it's fine to add the flag, as we will clear it immediately in
8307 // `refreshEmbeddedViews` for the view currently being refreshed.
8308 movedLView[FLAGS] |= 1024 /* RefreshTransplantedView */;
8309 }
8310 }
8311}
8312/////////////
8313/**
8314 * Refreshes components by entering the component view and processing its bindings, queries, etc.
8315 *
8316 * @param componentHostIdx Element index in LView[] (adjusted for HEADER_OFFSET)
8317 */
8318function refreshComponent(hostLView, componentHostIdx) {
8319 ngDevMode && assertEqual(isCreationMode(hostLView), false, 'Should be run in update mode');
8320 const componentView = getComponentLViewByIndex(componentHostIdx, hostLView);
8321 // Only attached components that are CheckAlways or OnPush and dirty should be refreshed
8322 if (viewAttachedToChangeDetector(componentView)) {
8323 const tView = componentView[TVIEW];
8324 if (componentView[FLAGS] & (16 /* CheckAlways */ | 64 /* Dirty */)) {
8325 refreshView(tView, componentView, tView.template, componentView[CONTEXT]);
8326 }
8327 else if (componentView[TRANSPLANTED_VIEWS_TO_REFRESH] > 0) {
8328 // Only attached components that are CheckAlways or OnPush and dirty should be refreshed
8329 refreshContainsDirtyView(componentView);
8330 }
8331 }
8332}
8333/**
8334 * Refreshes all transplanted views marked with `LViewFlags.RefreshTransplantedView` that are
8335 * children or descendants of the given lView.
8336 *
8337 * @param lView The lView which contains descendant transplanted views that need to be refreshed.
8338 */
8339function refreshContainsDirtyView(lView) {
8340 for (let lContainer = getFirstLContainer(lView); lContainer !== null; lContainer = getNextLContainer(lContainer)) {
8341 for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
8342 const embeddedLView = lContainer[i];
8343 if (embeddedLView[FLAGS] & 1024 /* RefreshTransplantedView */) {
8344 const embeddedTView = embeddedLView[TVIEW];
8345 ngDevMode && assertDefined(embeddedTView, 'TView must be allocated');
8346 refreshView(embeddedTView, embeddedLView, embeddedTView.template, embeddedLView[CONTEXT]);
8347 }
8348 else if (embeddedLView[TRANSPLANTED_VIEWS_TO_REFRESH] > 0) {
8349 refreshContainsDirtyView(embeddedLView);
8350 }
8351 }
8352 }
8353 const tView = lView[TVIEW];
8354 // Refresh child component views.
8355 const components = tView.components;
8356 if (components !== null) {
8357 for (let i = 0; i < components.length; i++) {
8358 const componentView = getComponentLViewByIndex(components[i], lView);
8359 // Only attached components that are CheckAlways or OnPush and dirty should be refreshed
8360 if (viewAttachedToChangeDetector(componentView) &&
8361 componentView[TRANSPLANTED_VIEWS_TO_REFRESH] > 0) {
8362 refreshContainsDirtyView(componentView);
8363 }
8364 }
8365 }
8366}
8367function renderComponent(hostLView, componentHostIdx) {
8368 ngDevMode && assertEqual(isCreationMode(hostLView), true, 'Should be run in creation mode');
8369 const componentView = getComponentLViewByIndex(componentHostIdx, hostLView);
8370 const componentTView = componentView[TVIEW];
8371 syncViewWithBlueprint(componentTView, componentView);
8372 renderView(componentTView, componentView, componentView[CONTEXT]);
8373}
8374/**
8375 * Syncs an LView instance with its blueprint if they have gotten out of sync.
8376 *
8377 * Typically, blueprints and their view instances should always be in sync, so the loop here
8378 * will be skipped. However, consider this case of two components side-by-side:
8379 *
8380 * App template:
8381 * ```
8382 * <comp></comp>
8383 * <comp></comp>
8384 * ```
8385 *
8386 * The following will happen:
8387 * 1. App template begins processing.
8388 * 2. First <comp> is matched as a component and its LView is created.
8389 * 3. Second <comp> is matched as a component and its LView is created.
8390 * 4. App template completes processing, so it's time to check child templates.
8391 * 5. First <comp> template is checked. It has a directive, so its def is pushed to blueprint.
8392 * 6. Second <comp> template is checked. Its blueprint has been updated by the first
8393 * <comp> template, but its LView was created before this update, so it is out of sync.
8394 *
8395 * Note that embedded views inside ngFor loops will never be out of sync because these views
8396 * are processed as soon as they are created.
8397 *
8398 * @param tView The `TView` that contains the blueprint for syncing
8399 * @param lView The view to sync
8400 */
8401function syncViewWithBlueprint(tView, lView) {
8402 for (let i = lView.length; i < tView.blueprint.length; i++) {
8403 lView.push(tView.blueprint[i]);
8404 }
8405}
8406/**
8407 * Adds LView or LContainer to the end of the current view tree.
8408 *
8409 * This structure will be used to traverse through nested views to remove listeners
8410 * and call onDestroy callbacks.
8411 *
8412 * @param lView The view where LView or LContainer should be added
8413 * @param adjustedHostIndex Index of the view's host node in LView[], adjusted for header
8414 * @param lViewOrLContainer The LView or LContainer to add to the view tree
8415 * @returns The state passed in
8416 */
8417function addToViewTree(lView, lViewOrLContainer) {
8418 // TODO(benlesh/misko): This implementation is incorrect, because it always adds the LContainer
8419 // to the end of the queue, which means if the developer retrieves the LContainers from RNodes out
8420 // of order, the change detection will run out of order, as the act of retrieving the the
8421 // LContainer from the RNode is what adds it to the queue.
8422 if (lView[CHILD_HEAD]) {
8423 lView[CHILD_TAIL][NEXT] = lViewOrLContainer;
8424 }
8425 else {
8426 lView[CHILD_HEAD] = lViewOrLContainer;
8427 }
8428 lView[CHILD_TAIL] = lViewOrLContainer;
8429 return lViewOrLContainer;
8430}
8431///////////////////////////////
8432//// Change detection
8433///////////////////////////////
8434/**
8435 * Marks current view and all ancestors dirty.
8436 *
8437 * Returns the root view because it is found as a byproduct of marking the view tree
8438 * dirty, and can be used by methods that consume markViewDirty() to easily schedule
8439 * change detection. Otherwise, such methods would need to traverse up the view tree
8440 * an additional time to get the root view and schedule a tick on it.
8441 *
8442 * @param lView The starting LView to mark dirty
8443 * @returns the root LView
8444 */
8445function markViewDirty(lView) {
8446 while (lView) {
8447 lView[FLAGS] |= 64 /* Dirty */;
8448 const parent = getLViewParent(lView);
8449 // Stop traversing up as soon as you find a root view that wasn't attached to any container
8450 if (isRootView(lView) && !parent) {
8451 return lView;
8452 }
8453 // continue otherwise
8454 lView = parent;
8455 }
8456 return null;
8457}
8458/**
8459 * Used to schedule change detection on the whole application.
8460 *
8461 * Unlike `tick`, `scheduleTick` coalesces multiple calls into one change detection run.
8462 * It is usually called indirectly by calling `markDirty` when the view needs to be
8463 * re-rendered.
8464 *
8465 * Typically `scheduleTick` uses `requestAnimationFrame` to coalesce multiple
8466 * `scheduleTick` requests. The scheduling function can be overridden in
8467 * `renderComponent`'s `scheduler` option.
8468 */
8469function scheduleTick(rootContext, flags) {
8470 const nothingScheduled = rootContext.flags === 0 /* Empty */;
8471 rootContext.flags |= flags;
8472 if (nothingScheduled && rootContext.clean == _CLEAN_PROMISE) {
8473 let res;
8474 rootContext.clean = new Promise((r) => res = r);
8475 rootContext.scheduler(() => {
8476 if (rootContext.flags & 1 /* DetectChanges */) {
8477 rootContext.flags &= ~1 /* DetectChanges */;
8478 tickRootContext(rootContext);
8479 }
8480 if (rootContext.flags & 2 /* FlushPlayers */) {
8481 rootContext.flags &= ~2 /* FlushPlayers */;
8482 const playerHandler = rootContext.playerHandler;
8483 if (playerHandler) {
8484 playerHandler.flushPlayers();
8485 }
8486 }
8487 rootContext.clean = _CLEAN_PROMISE;
8488 res(null);
8489 });
8490 }
8491}
8492function tickRootContext(rootContext) {
8493 for (let i = 0; i < rootContext.components.length; i++) {
8494 const rootComponent = rootContext.components[i];
8495 const lView = readPatchedLView(rootComponent);
8496 const tView = lView[TVIEW];
8497 renderComponentOrTemplate(tView, lView, tView.template, rootComponent);
8498 }
8499}
8500function detectChangesInternal(tView, lView, context) {
8501 const rendererFactory = lView[RENDERER_FACTORY];
8502 if (rendererFactory.begin)
8503 rendererFactory.begin();
8504 try {
8505 refreshView(tView, lView, tView.template, context);
8506 }
8507 catch (error) {
8508 handleError(lView, error);
8509 throw error;
8510 }
8511 finally {
8512 if (rendererFactory.end)
8513 rendererFactory.end();
8514 }
8515}
8516/**
8517 * Synchronously perform change detection on a root view and its components.
8518 *
8519 * @param lView The view which the change detection should be performed on.
8520 */
8521function detectChangesInRootView(lView) {
8522 tickRootContext(lView[CONTEXT]);
8523}
8524function checkNoChangesInternal(tView, view, context) {
8525 setCheckNoChangesMode(true);
8526 try {
8527 detectChangesInternal(tView, view, context);
8528 }
8529 finally {
8530 setCheckNoChangesMode(false);
8531 }
8532}
8533/**
8534 * Checks the change detector on a root view and its components, and throws if any changes are
8535 * detected.
8536 *
8537 * This is used in development mode to verify that running change detection doesn't
8538 * introduce other changes.
8539 *
8540 * @param lView The view which the change detection should be checked on.
8541 */
8542function checkNoChangesInRootView(lView) {
8543 setCheckNoChangesMode(true);
8544 try {
8545 detectChangesInRootView(lView);
8546 }
8547 finally {
8548 setCheckNoChangesMode(false);
8549 }
8550}
8551function executeViewQueryFn(flags, viewQueryFn, component) {
8552 ngDevMode && assertDefined(viewQueryFn, 'View queries function to execute must be defined.');
8553 setCurrentQueryIndex(0);
8554 viewQueryFn(flags, component);
8555}
8556///////////////////////////////
8557//// Bindings & interpolations
8558///////////////////////////////
8559/**
8560 * Stores meta-data for a property binding to be used by TestBed's `DebugElement.properties`.
8561 *
8562 * In order to support TestBed's `DebugElement.properties` we need to save, for each binding:
8563 * - a bound property name;
8564 * - a static parts of interpolated strings;
8565 *
8566 * A given property metadata is saved at the binding's index in the `TView.data` (in other words, a
8567 * property binding metadata will be stored in `TView.data` at the same index as a bound value in
8568 * `LView`). Metadata are represented as `INTERPOLATION_DELIMITER`-delimited string with the
8569 * following format:
8570 * - `propertyName` for bound properties;
8571 * - `propertyName�prefix�interpolation_static_part1�..interpolation_static_partN�suffix` for
8572 * interpolated properties.
8573 *
8574 * @param tData `TData` where meta-data will be saved;
8575 * @param tNode `TNode` that is a target of the binding;
8576 * @param propertyName bound property name;
8577 * @param bindingIndex binding index in `LView`
8578 * @param interpolationParts static interpolation parts (for property interpolations)
8579 */
8580function storePropertyBindingMetadata(tData, tNode, propertyName, bindingIndex, ...interpolationParts) {
8581 // Binding meta-data are stored only the first time a given property instruction is processed.
8582 // Since we don't have a concept of the "first update pass" we need to check for presence of the
8583 // binding meta-data to decide if one should be stored (or if was stored already).
8584 if (tData[bindingIndex] === null) {
8585 if (tNode.inputs == null || !tNode.inputs[propertyName]) {
8586 const propBindingIdxs = tNode.propertyBindings || (tNode.propertyBindings = []);
8587 propBindingIdxs.push(bindingIndex);
8588 let bindingMetadata = propertyName;
8589 if (interpolationParts.length > 0) {
8590 bindingMetadata +=
8591 INTERPOLATION_DELIMITER + interpolationParts.join(INTERPOLATION_DELIMITER);
8592 }
8593 tData[bindingIndex] = bindingMetadata;
8594 }
8595 }
8596}
8597const CLEAN_PROMISE = _CLEAN_PROMISE;
8598function getLCleanup(view) {
8599 // top level variables should not be exported for performance reasons (PERF_NOTES.md)
8600 return view[CLEANUP] || (view[CLEANUP] = ngDevMode ? new LCleanup() : []);
8601}
8602function getTViewCleanup(tView) {
8603 return tView.cleanup || (tView.cleanup = ngDevMode ? new TCleanup() : []);
8604}
8605/**
8606 * There are cases where the sub component's renderer needs to be included
8607 * instead of the current renderer (see the componentSyntheticHost* instructions).
8608 */
8609function loadComponentRenderer(currentDef, tNode, lView) {
8610 // TODO(FW-2043): the `currentDef` is null when host bindings are invoked while creating root
8611 // component (see packages/core/src/render3/component.ts). This is not consistent with the process
8612 // of creating inner components, when current directive index is available in the state. In order
8613 // to avoid relying on current def being `null` (thus special-casing root component creation), the
8614 // process of creating root component should be unified with the process of creating inner
8615 // components.
8616 if (currentDef === null || isComponentDef(currentDef)) {
8617 lView = unwrapLView(lView[tNode.index]);
8618 }
8619 return lView[RENDERER];
8620}
8621/** Handles an error thrown in an LView. */
8622function handleError(lView, error) {
8623 const injector = lView[INJECTOR$1];
8624 const errorHandler = injector ? injector.get(ErrorHandler, null) : null;
8625 errorHandler && errorHandler.handleError(error);
8626}
8627/**
8628 * Set the inputs of directives at the current node to corresponding value.
8629 *
8630 * @param tView The current TView
8631 * @param lView the `LView` which contains the directives.
8632 * @param inputs mapping between the public "input" name and privately-known,
8633 * possibly minified, property names to write to.
8634 * @param value Value to set.
8635 */
8636function setInputsForProperty(tView, lView, inputs, publicName, value) {
8637 for (let i = 0; i < inputs.length;) {
8638 const index = inputs[i++];
8639 const privateName = inputs[i++];
8640 const instance = lView[index];
8641 ngDevMode && assertIndexInRange(lView, index);
8642 const def = tView.data[index];
8643 if (def.setInput !== null) {
8644 def.setInput(instance, value, publicName, privateName);
8645 }
8646 else {
8647 instance[privateName] = value;
8648 }
8649 }
8650}
8651/**
8652 * Updates a text binding at a given index in a given LView.
8653 */
8654function textBindingInternal(lView, index, value) {
8655 ngDevMode && assertNotSame(value, NO_CHANGE, 'value should not be NO_CHANGE');
8656 ngDevMode && assertIndexInRange(lView, index + HEADER_OFFSET);
8657 const element = getNativeByIndex(index, lView);
8658 ngDevMode && assertDefined(element, 'native element should exist');
8659 ngDevMode && ngDevMode.rendererSetText++;
8660 const renderer = lView[RENDERER];
8661 isProceduralRenderer(renderer) ? renderer.setValue(element, value) : element.textContent = value;
8662}
8663
8664/**
8665 * @license
8666 * Copyright Google LLC All Rights Reserved.
8667 *
8668 * Use of this source code is governed by an MIT-style license that can be
8669 * found in the LICENSE file at https://angular.io/license
8670 */
8671const unusedValueToPlacateAjd$1 = unusedValueExportToPlacateAjd$1 + unusedValueExportToPlacateAjd$4 + unusedValueExportToPlacateAjd$5 + unusedValueExportToPlacateAjd$2 + unusedValueExportToPlacateAjd;
8672function getLContainer(tNode, embeddedView) {
8673 ngDevMode && assertLView(embeddedView);
8674 const container = embeddedView[PARENT];
8675 if (tNode.index === -1) {
8676 // This is a dynamically created view inside a dynamic container.
8677 // The parent isn't an LContainer if the embedded view hasn't been attached yet.
8678 return isLContainer(container) ? container : null;
8679 }
8680 else {
8681 ngDevMode && assertLContainer(container);
8682 // This is a inline view node (e.g. embeddedViewStart)
8683 return container;
8684 }
8685}
8686/**
8687 * Retrieves render parent for a given view.
8688 * Might be null if a view is not yet attached to any container.
8689 */
8690function getContainerRenderParent(tViewNode, view) {
8691 const container = getLContainer(tViewNode, view);
8692 return container ? nativeParentNode(view[RENDERER], container[NATIVE]) : null;
8693}
8694/**
8695 * NOTE: for performance reasons, the possible actions are inlined within the function instead of
8696 * being passed as an argument.
8697 */
8698function applyToElementOrContainer(action, renderer, parent, lNodeToHandle, beforeNode) {
8699 // If this slot was allocated for a text node dynamically created by i18n, the text node itself
8700 // won't be created until i18nApply() in the update block, so this node should be skipped.
8701 // For more info, see "ICU expressions should work inside an ngTemplateOutlet inside an ngFor"
8702 // in `i18n_spec.ts`.
8703 if (lNodeToHandle != null) {
8704 let lContainer;
8705 let isComponent = false;
8706 // We are expecting an RNode, but in the case of a component or LContainer the `RNode` is
8707 // wrapped in an array which needs to be unwrapped. We need to know if it is a component and if
8708 // it has LContainer so that we can process all of those cases appropriately.
8709 if (isLContainer(lNodeToHandle)) {
8710 lContainer = lNodeToHandle;
8711 }
8712 else if (isLView(lNodeToHandle)) {
8713 isComponent = true;
8714 ngDevMode && assertDefined(lNodeToHandle[HOST], 'HOST must be defined for a component LView');
8715 lNodeToHandle = lNodeToHandle[HOST];
8716 }
8717 const rNode = unwrapRNode(lNodeToHandle);
8718 ngDevMode && !isProceduralRenderer(renderer) && assertDomNode(rNode);
8719 if (action === 0 /* Create */ && parent !== null) {
8720 if (beforeNode == null) {
8721 nativeAppendChild(renderer, parent, rNode);
8722 }
8723 else {
8724 nativeInsertBefore(renderer, parent, rNode, beforeNode || null);
8725 }
8726 }
8727 else if (action === 1 /* Insert */ && parent !== null) {
8728 nativeInsertBefore(renderer, parent, rNode, beforeNode || null);
8729 }
8730 else if (action === 2 /* Detach */) {
8731 nativeRemoveNode(renderer, rNode, isComponent);
8732 }
8733 else if (action === 3 /* Destroy */) {
8734 ngDevMode && ngDevMode.rendererDestroyNode++;
8735 renderer.destroyNode(rNode);
8736 }
8737 if (lContainer != null) {
8738 applyContainer(renderer, action, lContainer, parent, beforeNode);
8739 }
8740 }
8741}
8742function createTextNode(value, renderer) {
8743 ngDevMode && ngDevMode.rendererCreateTextNode++;
8744 ngDevMode && ngDevMode.rendererSetText++;
8745 return isProceduralRenderer(renderer) ? renderer.createText(value) :
8746 renderer.createTextNode(value);
8747}
8748function addRemoveViewFromContainer(tView, lView, insertMode, beforeNode) {
8749 const renderParent = getContainerRenderParent(tView.node, lView);
8750 ngDevMode && assertNodeType(tView.node, 2 /* View */);
8751 if (renderParent) {
8752 const renderer = lView[RENDERER];
8753 const action = insertMode ? 1 /* Insert */ : 2 /* Detach */;
8754 applyView(tView, lView, renderer, action, renderParent, beforeNode);
8755 }
8756}
8757/**
8758 * Detach a `LView` from the DOM by detaching its nodes.
8759 *
8760 * @param tView The `TView' of the `LView` to be detached
8761 * @param lView the `LView` to be detached.
8762 */
8763function renderDetachView(tView, lView) {
8764 applyView(tView, lView, lView[RENDERER], 2 /* Detach */, null, null);
8765}
8766/**
8767 * Traverses down and up the tree of views and containers to remove listeners and
8768 * call onDestroy callbacks.
8769 *
8770 * Notes:
8771 * - Because it's used for onDestroy calls, it needs to be bottom-up.
8772 * - Must process containers instead of their views to avoid splicing
8773 * when views are destroyed and re-added.
8774 * - Using a while loop because it's faster than recursion
8775 * - Destroy only called on movement to sibling or movement to parent (laterally or up)
8776 *
8777 * @param rootView The view to destroy
8778 */
8779function destroyViewTree(rootView) {
8780 // If the view has no children, we can clean it up and return early.
8781 let lViewOrLContainer = rootView[CHILD_HEAD];
8782 if (!lViewOrLContainer) {
8783 return cleanUpView(rootView[TVIEW], rootView);
8784 }
8785 while (lViewOrLContainer) {
8786 let next = null;
8787 if (isLView(lViewOrLContainer)) {
8788 // If LView, traverse down to child.
8789 next = lViewOrLContainer[CHILD_HEAD];
8790 }
8791 else {
8792 ngDevMode && assertLContainer(lViewOrLContainer);
8793 // If container, traverse down to its first LView.
8794 const firstView = lViewOrLContainer[CONTAINER_HEADER_OFFSET];
8795 if (firstView)
8796 next = firstView;
8797 }
8798 if (!next) {
8799 // Only clean up view when moving to the side or up, as destroy hooks
8800 // should be called in order from the bottom up.
8801 while (lViewOrLContainer && !lViewOrLContainer[NEXT] && lViewOrLContainer !== rootView) {
8802 isLView(lViewOrLContainer) && cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer);
8803 lViewOrLContainer = getParentState(lViewOrLContainer, rootView);
8804 }
8805 if (lViewOrLContainer === null)
8806 lViewOrLContainer = rootView;
8807 isLView(lViewOrLContainer) && cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer);
8808 next = lViewOrLContainer && lViewOrLContainer[NEXT];
8809 }
8810 lViewOrLContainer = next;
8811 }
8812}
8813/**
8814 * Inserts a view into a container.
8815 *
8816 * This adds the view to the container's array of active views in the correct
8817 * position. It also adds the view's elements to the DOM if the container isn't a
8818 * root node of another view (in that case, the view's elements will be added when
8819 * the container's parent view is added later).
8820 *
8821 * @param tView The `TView' of the `LView` to insert
8822 * @param lView The view to insert
8823 * @param lContainer The container into which the view should be inserted
8824 * @param index Which index in the container to insert the child view into
8825 */
8826function insertView(tView, lView, lContainer, index) {
8827 ngDevMode && assertLView(lView);
8828 ngDevMode && assertLContainer(lContainer);
8829 const indexInContainer = CONTAINER_HEADER_OFFSET + index;
8830 const containerLength = lContainer.length;
8831 if (index > 0) {
8832 // This is a new view, we need to add it to the children.
8833 lContainer[indexInContainer - 1][NEXT] = lView;
8834 }
8835 if (index < containerLength - CONTAINER_HEADER_OFFSET) {
8836 lView[NEXT] = lContainer[indexInContainer];
8837 addToArray(lContainer, CONTAINER_HEADER_OFFSET + index, lView);
8838 }
8839 else {
8840 lContainer.push(lView);
8841 lView[NEXT] = null;
8842 }
8843 lView[PARENT] = lContainer;
8844 // track views where declaration and insertion points are different
8845 const declarationLContainer = lView[DECLARATION_LCONTAINER];
8846 if (declarationLContainer !== null && lContainer !== declarationLContainer) {
8847 trackMovedView(declarationLContainer, lView);
8848 }
8849 // notify query that a new view has been added
8850 const lQueries = lView[QUERIES];
8851 if (lQueries !== null) {
8852 lQueries.insertView(tView);
8853 }
8854 // Sets the attached flag
8855 lView[FLAGS] |= 128 /* Attached */;
8856}
8857/**
8858 * Track views created from the declaration container (TemplateRef) and inserted into a
8859 * different LContainer.
8860 */
8861function trackMovedView(declarationContainer, lView) {
8862 ngDevMode && assertDefined(lView, 'LView required');
8863 ngDevMode && assertLContainer(declarationContainer);
8864 const movedViews = declarationContainer[MOVED_VIEWS];
8865 const insertedLContainer = lView[PARENT];
8866 ngDevMode && assertLContainer(insertedLContainer);
8867 const insertedComponentLView = insertedLContainer[PARENT][DECLARATION_COMPONENT_VIEW];
8868 ngDevMode && assertDefined(insertedComponentLView, 'Missing insertedComponentLView');
8869 const declaredComponentLView = lView[DECLARATION_COMPONENT_VIEW];
8870 ngDevMode && assertDefined(declaredComponentLView, 'Missing declaredComponentLView');
8871 if (declaredComponentLView !== insertedComponentLView) {
8872 // At this point the declaration-component is not same as insertion-component; this means that
8873 // this is a transplanted view. Mark the declared lView as having transplanted views so that
8874 // those views can participate in CD.
8875 declarationContainer[HAS_TRANSPLANTED_VIEWS] = true;
8876 }
8877 if (movedViews === null) {
8878 declarationContainer[MOVED_VIEWS] = [lView];
8879 }
8880 else {
8881 movedViews.push(lView);
8882 }
8883}
8884function detachMovedView(declarationContainer, lView) {
8885 ngDevMode && assertLContainer(declarationContainer);
8886 ngDevMode &&
8887 assertDefined(declarationContainer[MOVED_VIEWS], 'A projected view should belong to a non-empty projected views collection');
8888 const movedViews = declarationContainer[MOVED_VIEWS];
8889 const declarationViewIndex = movedViews.indexOf(lView);
8890 const insertionLContainer = lView[PARENT];
8891 ngDevMode && assertLContainer(insertionLContainer);
8892 // If the view was marked for refresh but then detached before it was checked (where the flag
8893 // would be cleared and the counter decremented), we need to decrement the view counter here
8894 // instead.
8895 if (lView[FLAGS] & 1024 /* RefreshTransplantedView */) {
8896 updateTransplantedViewCount(insertionLContainer, -1);
8897 }
8898 movedViews.splice(declarationViewIndex, 1);
8899}
8900/**
8901 * Detaches a view from a container.
8902 *
8903 * This method removes the view from the container's array of active views. It also
8904 * removes the view's elements from the DOM.
8905 *
8906 * @param lContainer The container from which to detach a view
8907 * @param removeIndex The index of the view to detach
8908 * @returns Detached LView instance.
8909 */
8910function detachView(lContainer, removeIndex) {
8911 if (lContainer.length <= CONTAINER_HEADER_OFFSET)
8912 return;
8913 const indexInContainer = CONTAINER_HEADER_OFFSET + removeIndex;
8914 const viewToDetach = lContainer[indexInContainer];
8915 if (viewToDetach) {
8916 const declarationLContainer = viewToDetach[DECLARATION_LCONTAINER];
8917 if (declarationLContainer !== null && declarationLContainer !== lContainer) {
8918 detachMovedView(declarationLContainer, viewToDetach);
8919 }
8920 if (removeIndex > 0) {
8921 lContainer[indexInContainer - 1][NEXT] = viewToDetach[NEXT];
8922 }
8923 const removedLView = removeFromArray(lContainer, CONTAINER_HEADER_OFFSET + removeIndex);
8924 addRemoveViewFromContainer(viewToDetach[TVIEW], viewToDetach, false, null);
8925 // notify query that a view has been removed
8926 const lQueries = removedLView[QUERIES];
8927 if (lQueries !== null) {
8928 lQueries.detachView(removedLView[TVIEW]);
8929 }
8930 viewToDetach[PARENT] = null;
8931 viewToDetach[NEXT] = null;
8932 // Unsets the attached flag
8933 viewToDetach[FLAGS] &= ~128 /* Attached */;
8934 }
8935 return viewToDetach;
8936}
8937/**
8938 * A standalone function which destroys an LView,
8939 * conducting clean up (e.g. removing listeners, calling onDestroys).
8940 *
8941 * @param tView The `TView' of the `LView` to be destroyed
8942 * @param lView The view to be destroyed.
8943 */
8944function destroyLView(tView, lView) {
8945 if (!(lView[FLAGS] & 256 /* Destroyed */)) {
8946 const renderer = lView[RENDERER];
8947 if (isProceduralRenderer(renderer) && renderer.destroyNode) {
8948 applyView(tView, lView, renderer, 3 /* Destroy */, null, null);
8949 }
8950 destroyViewTree(lView);
8951 }
8952}
8953/**
8954 * Determines which LViewOrLContainer to jump to when traversing back up the
8955 * tree in destroyViewTree.
8956 *
8957 * Normally, the view's parent LView should be checked, but in the case of
8958 * embedded views, the container (which is the view node's parent, but not the
8959 * LView's parent) needs to be checked for a possible next property.
8960 *
8961 * @param lViewOrLContainer The LViewOrLContainer for which we need a parent state
8962 * @param rootView The rootView, so we don't propagate too far up the view tree
8963 * @returns The correct parent LViewOrLContainer
8964 */
8965function getParentState(lViewOrLContainer, rootView) {
8966 let tNode;
8967 if (isLView(lViewOrLContainer) && (tNode = lViewOrLContainer[T_HOST]) &&
8968 tNode.type === 2 /* View */) {
8969 // if it's an embedded view, the state needs to go up to the container, in case the
8970 // container has a next
8971 return getLContainer(tNode, lViewOrLContainer);
8972 }
8973 else {
8974 // otherwise, use parent view for containers or component views
8975 return lViewOrLContainer[PARENT] === rootView ? null : lViewOrLContainer[PARENT];
8976 }
8977}
8978/**
8979 * Calls onDestroys hooks for all directives and pipes in a given view and then removes all
8980 * listeners. Listeners are removed as the last step so events delivered in the onDestroys hooks
8981 * can be propagated to @Output listeners.
8982 *
8983 * @param tView `TView` for the `LView` to clean up.
8984 * @param lView The LView to clean up
8985 */
8986function cleanUpView(tView, lView) {
8987 if (!(lView[FLAGS] & 256 /* Destroyed */)) {
8988 // Usually the Attached flag is removed when the view is detached from its parent, however
8989 // if it's a root view, the flag won't be unset hence why we're also removing on destroy.
8990 lView[FLAGS] &= ~128 /* Attached */;
8991 // Mark the LView as destroyed *before* executing the onDestroy hooks. An onDestroy hook
8992 // runs arbitrary user code, which could include its own `viewRef.destroy()` (or similar). If
8993 // We don't flag the view as destroyed before the hooks, this could lead to an infinite loop.
8994 // This also aligns with the ViewEngine behavior. It also means that the onDestroy hook is
8995 // really more of an "afterDestroy" hook if you think about it.
8996 lView[FLAGS] |= 256 /* Destroyed */;
8997 executeOnDestroys(tView, lView);
8998 removeListeners(tView, lView);
8999 const hostTNode = lView[T_HOST];
9000 // For component views only, the local renderer is destroyed as clean up time.
9001 if (hostTNode && hostTNode.type === 3 /* Element */ &&
9002 isProceduralRenderer(lView[RENDERER])) {
9003 ngDevMode && ngDevMode.rendererDestroy++;
9004 lView[RENDERER].destroy();
9005 }
9006 const declarationContainer = lView[DECLARATION_LCONTAINER];
9007 // we are dealing with an embedded view that is still inserted into a container
9008 if (declarationContainer !== null && isLContainer(lView[PARENT])) {
9009 // and this is a projected view
9010 if (declarationContainer !== lView[PARENT]) {
9011 detachMovedView(declarationContainer, lView);
9012 }
9013 // For embedded views still attached to a container: remove query result from this view.
9014 const lQueries = lView[QUERIES];
9015 if (lQueries !== null) {
9016 lQueries.detachView(tView);
9017 }
9018 }
9019 }
9020}
9021/** Removes listeners and unsubscribes from output subscriptions */
9022function removeListeners(tView, lView) {
9023 const tCleanup = tView.cleanup;
9024 if (tCleanup !== null) {
9025 const lCleanup = lView[CLEANUP];
9026 for (let i = 0; i < tCleanup.length - 1; i += 2) {
9027 if (typeof tCleanup[i] === 'string') {
9028 // This is a native DOM listener
9029 const idxOrTargetGetter = tCleanup[i + 1];
9030 const target = typeof idxOrTargetGetter === 'function' ?
9031 idxOrTargetGetter(lView) :
9032 unwrapRNode(lView[idxOrTargetGetter]);
9033 const listener = lCleanup[tCleanup[i + 2]];
9034 const useCaptureOrSubIdx = tCleanup[i + 3];
9035 if (typeof useCaptureOrSubIdx === 'boolean') {
9036 // native DOM listener registered with Renderer3
9037 target.removeEventListener(tCleanup[i], listener, useCaptureOrSubIdx);
9038 }
9039 else {
9040 if (useCaptureOrSubIdx >= 0) {
9041 // unregister
9042 lCleanup[useCaptureOrSubIdx]();
9043 }
9044 else {
9045 // Subscription
9046 lCleanup[-useCaptureOrSubIdx].unsubscribe();
9047 }
9048 }
9049 i += 2;
9050 }
9051 else {
9052 // This is a cleanup function that is grouped with the index of its context
9053 const context = lCleanup[tCleanup[i + 1]];
9054 tCleanup[i].call(context);
9055 }
9056 }
9057 lView[CLEANUP] = null;
9058 }
9059}
9060/** Calls onDestroy hooks for this view */
9061function executeOnDestroys(tView, lView) {
9062 let destroyHooks;
9063 if (tView != null && (destroyHooks = tView.destroyHooks) != null) {
9064 for (let i = 0; i < destroyHooks.length; i += 2) {
9065 const context = lView[destroyHooks[i]];
9066 // Only call the destroy hook if the context has been requested.
9067 if (!(context instanceof NodeInjectorFactory)) {
9068 const toCall = destroyHooks[i + 1];
9069 if (Array.isArray(toCall)) {
9070 for (let j = 0; j < toCall.length; j += 2) {
9071 toCall[j + 1].call(context[toCall[j]]);
9072 }
9073 }
9074 else {
9075 toCall.call(context);
9076 }
9077 }
9078 }
9079 }
9080}
9081/**
9082 * Returns a native element if a node can be inserted into the given parent.
9083 *
9084 * There are two reasons why we may not be able to insert a element immediately.
9085 * - Projection: When creating a child content element of a component, we have to skip the
9086 * insertion because the content of a component will be projected.
9087 * `<component><content>delayed due to projection</content></component>`
9088 * - Parent container is disconnected: This can happen when we are inserting a view into
9089 * parent container, which itself is disconnected. For example the parent container is part
9090 * of a View which has not be inserted or is made for projection but has not been inserted
9091 * into destination.
9092 */
9093function getRenderParent(tView, tNode, currentView) {
9094 // Skip over element and ICU containers as those are represented by a comment node and
9095 // can't be used as a render parent.
9096 let parentTNode = tNode.parent;
9097 while (parentTNode != null &&
9098 (parentTNode.type === 4 /* ElementContainer */ ||
9099 parentTNode.type === 5 /* IcuContainer */)) {
9100 tNode = parentTNode;
9101 parentTNode = tNode.parent;
9102 }
9103 // If the parent tNode is null, then we are inserting across views: either into an embedded view
9104 // or a component view.
9105 if (parentTNode == null) {
9106 const hostTNode = currentView[T_HOST];
9107 if (hostTNode.type === 2 /* View */) {
9108 // We are inserting a root element of an embedded view We might delay insertion of children
9109 // for a given view if it is disconnected. This might happen for 2 main reasons:
9110 // - view is not inserted into any container(view was created but not inserted yet)
9111 // - view is inserted into a container but the container itself is not inserted into the DOM
9112 // (container might be part of projection or child of a view that is not inserted yet).
9113 // In other words we can insert children of a given view if this view was inserted into a
9114 // container and the container itself has its render parent determined.
9115 return getContainerRenderParent(hostTNode, currentView);
9116 }
9117 else {
9118 // We are inserting a root element of the component view into the component host element and
9119 // it should always be eager.
9120 ngDevMode && assertNodeOfPossibleTypes(hostTNode, [3 /* Element */]);
9121 return currentView[HOST];
9122 }
9123 }
9124 else {
9125 const isIcuCase = tNode && tNode.type === 5 /* IcuContainer */;
9126 // If the parent of this node is an ICU container, then it is represented by comment node and we
9127 // need to use it as an anchor. If it is projected then it's direct parent node is the renderer.
9128 if (isIcuCase && tNode.flags & 4 /* isProjected */) {
9129 return getNativeByTNode(tNode, currentView).parentNode;
9130 }
9131 ngDevMode && assertNodeType(parentTNode, 3 /* Element */);
9132 if (parentTNode.flags & 2 /* isComponentHost */) {
9133 const tData = tView.data;
9134 const tNode = tData[parentTNode.index];
9135 const encapsulation = tData[tNode.directiveStart].encapsulation;
9136 // We've got a parent which is an element in the current view. We just need to verify if the
9137 // parent element is not a component. Component's content nodes are not inserted immediately
9138 // because they will be projected, and so doing insert at this point would be wasteful.
9139 // Since the projection would then move it to its final destination. Note that we can't
9140 // make this assumption when using the Shadow DOM, because the native projection placeholders
9141 // (<content> or <slot>) have to be in place as elements are being inserted.
9142 if (encapsulation !== ViewEncapsulation$1.ShadowDom &&
9143 encapsulation !== ViewEncapsulation$1.Native) {
9144 return null;
9145 }
9146 }
9147 return getNativeByTNode(parentTNode, currentView);
9148 }
9149}
9150/**
9151 * Inserts a native node before another native node for a given parent using {@link Renderer3}.
9152 * This is a utility function that can be used when native nodes were determined - it abstracts an
9153 * actual renderer being used.
9154 */
9155function nativeInsertBefore(renderer, parent, child, beforeNode) {
9156 ngDevMode && ngDevMode.rendererInsertBefore++;
9157 if (isProceduralRenderer(renderer)) {
9158 renderer.insertBefore(parent, child, beforeNode);
9159 }
9160 else {
9161 parent.insertBefore(child, beforeNode, true);
9162 }
9163}
9164function nativeAppendChild(renderer, parent, child) {
9165 ngDevMode && ngDevMode.rendererAppendChild++;
9166 ngDevMode && assertDefined(parent, 'parent node must be defined');
9167 if (isProceduralRenderer(renderer)) {
9168 renderer.appendChild(parent, child);
9169 }
9170 else {
9171 parent.appendChild(child);
9172 }
9173}
9174function nativeAppendOrInsertBefore(renderer, parent, child, beforeNode) {
9175 if (beforeNode !== null) {
9176 nativeInsertBefore(renderer, parent, child, beforeNode);
9177 }
9178 else {
9179 nativeAppendChild(renderer, parent, child);
9180 }
9181}
9182/** Removes a node from the DOM given its native parent. */
9183function nativeRemoveChild(renderer, parent, child, isHostElement) {
9184 if (isProceduralRenderer(renderer)) {
9185 renderer.removeChild(parent, child, isHostElement);
9186 }
9187 else {
9188 parent.removeChild(child);
9189 }
9190}
9191/**
9192 * Returns a native parent of a given native node.
9193 */
9194function nativeParentNode(renderer, node) {
9195 return (isProceduralRenderer(renderer) ? renderer.parentNode(node) : node.parentNode);
9196}
9197/**
9198 * Returns a native sibling of a given native node.
9199 */
9200function nativeNextSibling(renderer, node) {
9201 return isProceduralRenderer(renderer) ? renderer.nextSibling(node) : node.nextSibling;
9202}
9203/**
9204 * Finds a native "anchor" node for cases where we can't append a native child directly
9205 * (`appendChild`) and need to use a reference (anchor) node for the `insertBefore` operation.
9206 * @param parentTNode
9207 * @param lView
9208 */
9209function getNativeAnchorNode(parentTNode, lView) {
9210 if (parentTNode.type === 2 /* View */) {
9211 const lContainer = getLContainer(parentTNode, lView);
9212 if (lContainer === null)
9213 return null;
9214 const index = lContainer.indexOf(lView, CONTAINER_HEADER_OFFSET) - CONTAINER_HEADER_OFFSET;
9215 return getBeforeNodeForView(index, lContainer);
9216 }
9217 else if (parentTNode.type === 4 /* ElementContainer */ ||
9218 parentTNode.type === 5 /* IcuContainer */) {
9219 return getNativeByTNode(parentTNode, lView);
9220 }
9221 return null;
9222}
9223/**
9224 * Appends the `child` native node (or a collection of nodes) to the `parent`.
9225 *
9226 * The element insertion might be delayed {@link canInsertNativeNode}.
9227 *
9228 * @param tView The `TView' to be appended
9229 * @param lView The current LView
9230 * @param childEl The native child (or children) that should be appended
9231 * @param childTNode The TNode of the child element
9232 * @returns Whether or not the child was appended
9233 */
9234function appendChild(tView, lView, childEl, childTNode) {
9235 const renderParent = getRenderParent(tView, childTNode, lView);
9236 if (renderParent != null) {
9237 const renderer = lView[RENDERER];
9238 const parentTNode = childTNode.parent || lView[T_HOST];
9239 const anchorNode = getNativeAnchorNode(parentTNode, lView);
9240 if (Array.isArray(childEl)) {
9241 for (let i = 0; i < childEl.length; i++) {
9242 nativeAppendOrInsertBefore(renderer, renderParent, childEl[i], anchorNode);
9243 }
9244 }
9245 else {
9246 nativeAppendOrInsertBefore(renderer, renderParent, childEl, anchorNode);
9247 }
9248 }
9249}
9250/**
9251 * Returns the first native node for a given LView, starting from the provided TNode.
9252 *
9253 * Native nodes are returned in the order in which those appear in the native tree (DOM).
9254 */
9255function getFirstNativeNode(lView, tNode) {
9256 if (tNode !== null) {
9257 ngDevMode && assertNodeOfPossibleTypes(tNode, [
9258 3 /* Element */, 0 /* Container */, 4 /* ElementContainer */, 5 /* IcuContainer */,
9259 1 /* Projection */
9260 ]);
9261 const tNodeType = tNode.type;
9262 if (tNodeType === 3 /* Element */) {
9263 return getNativeByTNode(tNode, lView);
9264 }
9265 else if (tNodeType === 0 /* Container */) {
9266 return getBeforeNodeForView(-1, lView[tNode.index]);
9267 }
9268 else if (tNodeType === 4 /* ElementContainer */ || tNodeType === 5 /* IcuContainer */) {
9269 const elIcuContainerChild = tNode.child;
9270 if (elIcuContainerChild !== null) {
9271 return getFirstNativeNode(lView, elIcuContainerChild);
9272 }
9273 else {
9274 const rNodeOrLContainer = lView[tNode.index];
9275 if (isLContainer(rNodeOrLContainer)) {
9276 return getBeforeNodeForView(-1, rNodeOrLContainer);
9277 }
9278 else {
9279 return unwrapRNode(rNodeOrLContainer);
9280 }
9281 }
9282 }
9283 else {
9284 const componentView = lView[DECLARATION_COMPONENT_VIEW];
9285 const componentHost = componentView[T_HOST];
9286 const parentView = getLViewParent(componentView);
9287 const firstProjectedTNode = componentHost.projection[tNode.projection];
9288 if (firstProjectedTNode != null) {
9289 return getFirstNativeNode(parentView, firstProjectedTNode);
9290 }
9291 else {
9292 return getFirstNativeNode(lView, tNode.next);
9293 }
9294 }
9295 }
9296 return null;
9297}
9298function getBeforeNodeForView(viewIndexInContainer, lContainer) {
9299 const nextViewIndex = CONTAINER_HEADER_OFFSET + viewIndexInContainer + 1;
9300 if (nextViewIndex < lContainer.length) {
9301 const lView = lContainer[nextViewIndex];
9302 const firstTNodeOfView = lView[TVIEW].firstChild;
9303 if (firstTNodeOfView !== null) {
9304 return getFirstNativeNode(lView, firstTNodeOfView);
9305 }
9306 }
9307 return lContainer[NATIVE];
9308}
9309/**
9310 * Removes a native node itself using a given renderer. To remove the node we are looking up its
9311 * parent from the native tree as not all platforms / browsers support the equivalent of
9312 * node.remove().
9313 *
9314 * @param renderer A renderer to be used
9315 * @param rNode The native node that should be removed
9316 * @param isHostElement A flag indicating if a node to be removed is a host of a component.
9317 */
9318function nativeRemoveNode(renderer, rNode, isHostElement) {
9319 const nativeParent = nativeParentNode(renderer, rNode);
9320 if (nativeParent) {
9321 nativeRemoveChild(renderer, nativeParent, rNode, isHostElement);
9322 }
9323}
9324/**
9325 * Performs the operation of `action` on the node. Typically this involves inserting or removing
9326 * nodes on the LView or projection boundary.
9327 */
9328function applyNodes(renderer, action, tNode, lView, renderParent, beforeNode, isProjection) {
9329 while (tNode != null) {
9330 ngDevMode && assertTNodeForLView(tNode, lView);
9331 ngDevMode && assertNodeOfPossibleTypes(tNode, [
9332 0 /* Container */, 3 /* Element */, 4 /* ElementContainer */, 1 /* Projection */,
9333 5 /* IcuContainer */
9334 ]);
9335 const rawSlotValue = lView[tNode.index];
9336 const tNodeType = tNode.type;
9337 if (isProjection) {
9338 if (action === 0 /* Create */) {
9339 rawSlotValue && attachPatchData(unwrapRNode(rawSlotValue), lView);
9340 tNode.flags |= 4 /* isProjected */;
9341 }
9342 }
9343 if ((tNode.flags & 64 /* isDetached */) !== 64 /* isDetached */) {
9344 if (tNodeType === 4 /* ElementContainer */ || tNodeType === 5 /* IcuContainer */) {
9345 applyNodes(renderer, action, tNode.child, lView, renderParent, beforeNode, false);
9346 applyToElementOrContainer(action, renderer, renderParent, rawSlotValue, beforeNode);
9347 }
9348 else if (tNodeType === 1 /* Projection */) {
9349 applyProjectionRecursive(renderer, action, lView, tNode, renderParent, beforeNode);
9350 }
9351 else {
9352 ngDevMode && assertNodeOfPossibleTypes(tNode, [3 /* Element */, 0 /* Container */]);
9353 applyToElementOrContainer(action, renderer, renderParent, rawSlotValue, beforeNode);
9354 }
9355 }
9356 tNode = isProjection ? tNode.projectionNext : tNode.next;
9357 }
9358}
9359/**
9360 * `applyView` performs operation on the view as specified in `action` (insert, detach, destroy)
9361 *
9362 * Inserting a view without projection or containers at top level is simple. Just iterate over the
9363 * root nodes of the View, and for each node perform the `action`.
9364 *
9365 * Things get more complicated with containers and projections. That is because coming across:
9366 * - Container: implies that we have to insert/remove/destroy the views of that container as well
9367 * which in turn can have their own Containers at the View roots.
9368 * - Projection: implies that we have to insert/remove/destroy the nodes of the projection. The
9369 * complication is that the nodes we are projecting can themselves have Containers
9370 * or other Projections.
9371 *
9372 * As you can see this is a very recursive problem. Yes recursion is not most efficient but the
9373 * code is complicated enough that trying to implemented with recursion becomes unmaintainable.
9374 *
9375 * @param tView The `TView' which needs to be inserted, detached, destroyed
9376 * @param lView The LView which needs to be inserted, detached, destroyed.
9377 * @param renderer Renderer to use
9378 * @param action action to perform (insert, detach, destroy)
9379 * @param renderParent parent DOM element for insertion/removal.
9380 * @param beforeNode Before which node the insertions should happen.
9381 */
9382function applyView(tView, lView, renderer, action, renderParent, beforeNode) {
9383 ngDevMode && assertNodeType(tView.node, 2 /* View */);
9384 const viewRootTNode = tView.node.child;
9385 applyNodes(renderer, action, viewRootTNode, lView, renderParent, beforeNode, false);
9386}
9387/**
9388 * `applyProjection` performs operation on the projection.
9389 *
9390 * Inserting a projection requires us to locate the projected nodes from the parent component. The
9391 * complication is that those nodes themselves could be re-projected from their parent component.
9392 *
9393 * @param tView The `TView` of `LView` which needs to be inserted, detached, destroyed
9394 * @param lView The `LView` which needs to be inserted, detached, destroyed.
9395 * @param tProjectionNode node to project
9396 */
9397function applyProjection(tView, lView, tProjectionNode) {
9398 const renderer = lView[RENDERER];
9399 const renderParent = getRenderParent(tView, tProjectionNode, lView);
9400 const parentTNode = tProjectionNode.parent || lView[T_HOST];
9401 let beforeNode = getNativeAnchorNode(parentTNode, lView);
9402 applyProjectionRecursive(renderer, 0 /* Create */, lView, tProjectionNode, renderParent, beforeNode);
9403}
9404/**
9405 * `applyProjectionRecursive` performs operation on the projection specified by `action` (insert,
9406 * detach, destroy)
9407 *
9408 * Inserting a projection requires us to locate the projected nodes from the parent component. The
9409 * complication is that those nodes themselves could be re-projected from their parent component.
9410 *
9411 * @param renderer Render to use
9412 * @param action action to perform (insert, detach, destroy)
9413 * @param lView The LView which needs to be inserted, detached, destroyed.
9414 * @param tProjectionNode node to project
9415 * @param renderParent parent DOM element for insertion/removal.
9416 * @param beforeNode Before which node the insertions should happen.
9417 */
9418function applyProjectionRecursive(renderer, action, lView, tProjectionNode, renderParent, beforeNode) {
9419 const componentLView = lView[DECLARATION_COMPONENT_VIEW];
9420 const componentNode = componentLView[T_HOST];
9421 ngDevMode &&
9422 assertEqual(typeof tProjectionNode.projection, 'number', 'expecting projection index');
9423 const nodeToProjectOrRNodes = componentNode.projection[tProjectionNode.projection];
9424 if (Array.isArray(nodeToProjectOrRNodes)) {
9425 // This should not exist, it is a bit of a hack. When we bootstrap a top level node and we
9426 // need to support passing projectable nodes, so we cheat and put them in the TNode
9427 // of the Host TView. (Yes we put instance info at the T Level). We can get away with it
9428 // because we know that that TView is not shared and therefore it will not be a problem.
9429 // This should be refactored and cleaned up.
9430 for (let i = 0; i < nodeToProjectOrRNodes.length; i++) {
9431 const rNode = nodeToProjectOrRNodes[i];
9432 applyToElementOrContainer(action, renderer, renderParent, rNode, beforeNode);
9433 }
9434 }
9435 else {
9436 let nodeToProject = nodeToProjectOrRNodes;
9437 const projectedComponentLView = componentLView[PARENT];
9438 applyNodes(renderer, action, nodeToProject, projectedComponentLView, renderParent, beforeNode, true);
9439 }
9440}
9441/**
9442 * `applyContainer` performs an operation on the container and its views as specified by
9443 * `action` (insert, detach, destroy)
9444 *
9445 * Inserting a Container is complicated by the fact that the container may have Views which
9446 * themselves have containers or projections.
9447 *
9448 * @param renderer Renderer to use
9449 * @param action action to perform (insert, detach, destroy)
9450 * @param lContainer The LContainer which needs to be inserted, detached, destroyed.
9451 * @param renderParent parent DOM element for insertion/removal.
9452 * @param beforeNode Before which node the insertions should happen.
9453 */
9454function applyContainer(renderer, action, lContainer, renderParent, beforeNode) {
9455 ngDevMode && assertLContainer(lContainer);
9456 const anchor = lContainer[NATIVE]; // LContainer has its own before node.
9457 const native = unwrapRNode(lContainer);
9458 // An LContainer can be created dynamically on any node by injecting ViewContainerRef.
9459 // Asking for a ViewContainerRef on an element will result in a creation of a separate anchor node
9460 // (comment in the DOM) that will be different from the LContainer's host node. In this particular
9461 // case we need to execute action on 2 nodes:
9462 // - container's host node (this is done in the executeActionOnElementOrContainer)
9463 // - container's host node (this is done here)
9464 if (anchor !== native) {
9465 // This is very strange to me (Misko). I would expect that the native is same as anchor. I don't
9466 // see a reason why they should be different, but they are.
9467 //
9468 // If they are we need to process the second anchor as well.
9469 applyToElementOrContainer(action, renderer, renderParent, anchor, beforeNode);
9470 }
9471 for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
9472 const lView = lContainer[i];
9473 applyView(lView[TVIEW], lView, renderer, action, renderParent, anchor);
9474 }
9475}
9476/**
9477 * Writes class/style to element.
9478 *
9479 * @param renderer Renderer to use.
9480 * @param isClassBased `true` if it should be written to `class` (`false` to write to `style`)
9481 * @param rNode The Node to write to.
9482 * @param prop Property to write to. This would be the class/style name.
9483 * @param value Value to write. If `null`/`undefined`/`false` this is considered a remove (set/add
9484 * otherwise).
9485 */
9486function applyStyling(renderer, isClassBased, rNode, prop, value) {
9487 const isProcedural = isProceduralRenderer(renderer);
9488 if (isClassBased) {
9489 // We actually want JS true/false here because any truthy value should add the class
9490 if (!value) {
9491 ngDevMode && ngDevMode.rendererRemoveClass++;
9492 if (isProcedural) {
9493 renderer.removeClass(rNode, prop);
9494 }
9495 else {
9496 rNode.classList.remove(prop);
9497 }
9498 }
9499 else {
9500 ngDevMode && ngDevMode.rendererAddClass++;
9501 if (isProcedural) {
9502 renderer.addClass(rNode, prop);
9503 }
9504 else {
9505 ngDevMode && assertDefined(rNode.classList, 'HTMLElement expected');
9506 rNode.classList.add(prop);
9507 }
9508 }
9509 }
9510 else {
9511 // TODO(misko): Can't import RendererStyleFlags2.DashCase as it causes imports to be resolved in
9512 // different order which causes failures. Using direct constant as workaround for now.
9513 const flags = prop.indexOf('-') == -1 ? undefined : 2 /* RendererStyleFlags2.DashCase */;
9514 if (value == null /** || value === undefined */) {
9515 ngDevMode && ngDevMode.rendererRemoveStyle++;
9516 if (isProcedural) {
9517 renderer.removeStyle(rNode, prop, flags);
9518 }
9519 else {
9520 rNode.style.removeProperty(prop);
9521 }
9522 }
9523 else {
9524 ngDevMode && ngDevMode.rendererSetStyle++;
9525 if (isProcedural) {
9526 renderer.setStyle(rNode, prop, value, flags);
9527 }
9528 else {
9529 ngDevMode && assertDefined(rNode.style, 'HTMLElement expected');
9530 rNode.style.setProperty(prop, value);
9531 }
9532 }
9533 }
9534}
9535/**
9536 * Write `cssText` to `RElement`.
9537 *
9538 * This function does direct write without any reconciliation. Used for writing initial values, so
9539 * that static styling values do not pull in the style parser.
9540 *
9541 * @param renderer Renderer to use
9542 * @param element The element which needs to be updated.
9543 * @param newValue The new class list to write.
9544 */
9545function writeDirectStyle(renderer, element, newValue) {
9546 ngDevMode && assertString(newValue, '\'newValue\' should be a string');
9547 if (isProceduralRenderer(renderer)) {
9548 renderer.setAttribute(element, 'style', newValue);
9549 }
9550 else {
9551 element.style.cssText = newValue;
9552 }
9553 ngDevMode && ngDevMode.rendererSetStyle++;
9554}
9555/**
9556 * Write `className` to `RElement`.
9557 *
9558 * This function does direct write without any reconciliation. Used for writing initial values, so
9559 * that static styling values do not pull in the style parser.
9560 *
9561 * @param renderer Renderer to use
9562 * @param element The element which needs to be updated.
9563 * @param newValue The new class list to write.
9564 */
9565function writeDirectClass(renderer, element, newValue) {
9566 ngDevMode && assertString(newValue, '\'newValue\' should be a string');
9567 if (isProceduralRenderer(renderer)) {
9568 if (newValue === '') {
9569 // There are tests in `google3` which expect `element.getAttribute('class')` to be `null`.
9570 renderer.removeAttribute(element, 'class');
9571 }
9572 else {
9573 renderer.setAttribute(element, 'class', newValue);
9574 }
9575 }
9576 else {
9577 element.className = newValue;
9578 }
9579 ngDevMode && ngDevMode.rendererSetClassName++;
9580}
9581
9582/**
9583 * @license
9584 * Copyright Google LLC All Rights Reserved.
9585 *
9586 * Use of this source code is governed by an MIT-style license that can be
9587 * found in the LICENSE file at https://angular.io/license
9588 */
9589/**
9590 * If `startTNode.parent` exists and has an injector, returns TNode for that injector.
9591 * Otherwise, unwraps a parent injector location number to find the view offset from the current
9592 * injector, then walks up the declaration view tree until the TNode of the parent injector is
9593 * found.
9594 *
9595 * @param location The location of the parent injector, which contains the view offset
9596 * @param startView The LView instance from which to start walking up the view tree
9597 * @param startTNode The TNode instance of the starting element
9598 * @returns The TNode of the parent injector
9599 */
9600function getParentInjectorTNode(location, startView, startTNode) {
9601 // If there is an injector on the parent TNode, retrieve the TNode for that injector.
9602 if (startTNode.parent && startTNode.parent.injectorIndex !== -1) {
9603 // view offset is 0
9604 const injectorIndex = startTNode.parent.injectorIndex;
9605 let tNode = startTNode.parent;
9606 // If tNode.injectorIndex === tNode.parent.injectorIndex, then the index belongs to a parent
9607 // injector.
9608 while (tNode.parent != null && injectorIndex == tNode.parent.injectorIndex) {
9609 tNode = tNode.parent;
9610 }
9611 return tNode;
9612 }
9613 let viewOffset = getParentInjectorViewOffset(location);
9614 // view offset is 1
9615 let parentView = startView;
9616 let parentTNode = startView[T_HOST];
9617 // view offset is superior to 1
9618 while (viewOffset > 1) {
9619 parentView = parentView[DECLARATION_VIEW];
9620 parentTNode = parentView[T_HOST];
9621 viewOffset--;
9622 }
9623 return parentTNode;
9624}
9625
9626/**
9627 * @license
9628 * Copyright Google LLC All Rights Reserved.
9629 *
9630 * Use of this source code is governed by an MIT-style license that can be
9631 * found in the LICENSE file at https://angular.io/license
9632 */
9633class ViewRef {
9634 constructor(
9635 /**
9636 * This represents `LView` associated with the component when ViewRef is a ChangeDetectorRef.
9637 *
9638 * When ViewRef is created for a dynamic component, this also represents the `LView` for the
9639 * component.
9640 *
9641 * For a "regular" ViewRef created for an embedded view, this is the `LView` for the embedded
9642 * view.
9643 *
9644 * @internal
9645 */
9646 _lView,
9647 /**
9648 * This represents the `LView` associated with the point where `ChangeDetectorRef` was
9649 * requested.
9650 *
9651 * This may be different from `_lView` if the `_cdRefInjectingView` is an embedded view.
9652 */
9653 _cdRefInjectingView) {
9654 this._lView = _lView;
9655 this._cdRefInjectingView = _cdRefInjectingView;
9656 this._appRef = null;
9657 this._viewContainerRef = null;
9658 }
9659 get rootNodes() {
9660 const lView = this._lView;
9661 if (lView[HOST] == null) {
9662 const hostTView = lView[T_HOST];
9663 return collectNativeNodes(lView[TVIEW], lView, hostTView.child, []);
9664 }
9665 return [];
9666 }
9667 get context() {
9668 return this._lView[CONTEXT];
9669 }
9670 get destroyed() {
9671 return (this._lView[FLAGS] & 256 /* Destroyed */) === 256 /* Destroyed */;
9672 }
9673 destroy() {
9674 if (this._appRef) {
9675 this._appRef.detachView(this);
9676 }
9677 else if (this._viewContainerRef) {
9678 const index = this._viewContainerRef.indexOf(this);
9679 if (index > -1) {
9680 this._viewContainerRef.detach(index);
9681 }
9682 this._viewContainerRef = null;
9683 }
9684 destroyLView(this._lView[TVIEW], this._lView);
9685 }
9686 onDestroy(callback) {
9687 storeCleanupWithContext(this._lView[TVIEW], this._lView, null, callback);
9688 }
9689 /**
9690 * Marks a view and all of its ancestors dirty.
9691 *
9692 * It also triggers change detection by calling `scheduleTick` internally, which coalesces
9693 * multiple `markForCheck` calls to into one change detection run.
9694 *
9695 * This can be used to ensure an {@link ChangeDetectionStrategy#OnPush OnPush} component is
9696 * checked when it needs to be re-rendered but the two normal triggers haven't marked it
9697 * dirty (i.e. inputs haven't changed and events haven't fired in the view).
9698 *
9699 * <!-- TODO: Add a link to a chapter on OnPush components -->
9700 *
9701 * @usageNotes
9702 * ### Example
9703 *
9704 * ```typescript
9705 * @Component({
9706 * selector: 'my-app',
9707 * template: `Number of ticks: {{numberOfTicks}}`
9708 * changeDetection: ChangeDetectionStrategy.OnPush,
9709 * })
9710 * class AppComponent {
9711 * numberOfTicks = 0;
9712 *
9713 * constructor(private ref: ChangeDetectorRef) {
9714 * setInterval(() => {
9715 * this.numberOfTicks++;
9716 * // the following is required, otherwise the view will not be updated
9717 * this.ref.markForCheck();
9718 * }, 1000);
9719 * }
9720 * }
9721 * ```
9722 */
9723 markForCheck() {
9724 markViewDirty(this._cdRefInjectingView || this._lView);
9725 }
9726 /**
9727 * Detaches the view from the change detection tree.
9728 *
9729 * Detached views will not be checked during change detection runs until they are
9730 * re-attached, even if they are dirty. `detach` can be used in combination with
9731 * {@link ChangeDetectorRef#detectChanges detectChanges} to implement local change
9732 * detection checks.
9733 *
9734 * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
9735 * <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
9736 *
9737 * @usageNotes
9738 * ### Example
9739 *
9740 * The following example defines a component with a large list of readonly data.
9741 * Imagine the data changes constantly, many times per second. For performance reasons,
9742 * we want to check and update the list every five seconds. We can do that by detaching
9743 * the component's change detector and doing a local check every five seconds.
9744 *
9745 * ```typescript
9746 * class DataProvider {
9747 * // in a real application the returned data will be different every time
9748 * get data() {
9749 * return [1,2,3,4,5];
9750 * }
9751 * }
9752 *
9753 * @Component({
9754 * selector: 'giant-list',
9755 * template: `
9756 * <li *ngFor="let d of dataProvider.data">Data {{d}}</li>
9757 * `,
9758 * })
9759 * class GiantList {
9760 * constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {
9761 * ref.detach();
9762 * setInterval(() => {
9763 * this.ref.detectChanges();
9764 * }, 5000);
9765 * }
9766 * }
9767 *
9768 * @Component({
9769 * selector: 'app',
9770 * providers: [DataProvider],
9771 * template: `
9772 * <giant-list><giant-list>
9773 * `,
9774 * })
9775 * class App {
9776 * }
9777 * ```
9778 */
9779 detach() {
9780 this._lView[FLAGS] &= ~128 /* Attached */;
9781 }
9782 /**
9783 * Re-attaches a view to the change detection tree.
9784 *
9785 * This can be used to re-attach views that were previously detached from the tree
9786 * using {@link ChangeDetectorRef#detach detach}. Views are attached to the tree by default.
9787 *
9788 * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
9789 *
9790 * @usageNotes
9791 * ### Example
9792 *
9793 * The following example creates a component displaying `live` data. The component will detach
9794 * its change detector from the main change detector tree when the component's live property
9795 * is set to false.
9796 *
9797 * ```typescript
9798 * class DataProvider {
9799 * data = 1;
9800 *
9801 * constructor() {
9802 * setInterval(() => {
9803 * this.data = this.data * 2;
9804 * }, 500);
9805 * }
9806 * }
9807 *
9808 * @Component({
9809 * selector: 'live-data',
9810 * inputs: ['live'],
9811 * template: 'Data: {{dataProvider.data}}'
9812 * })
9813 * class LiveData {
9814 * constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {}
9815 *
9816 * set live(value) {
9817 * if (value) {
9818 * this.ref.reattach();
9819 * } else {
9820 * this.ref.detach();
9821 * }
9822 * }
9823 * }
9824 *
9825 * @Component({
9826 * selector: 'my-app',
9827 * providers: [DataProvider],
9828 * template: `
9829 * Live Update: <input type="checkbox" [(ngModel)]="live">
9830 * <live-data [live]="live"><live-data>
9831 * `,
9832 * })
9833 * class AppComponent {
9834 * live = true;
9835 * }
9836 * ```
9837 */
9838 reattach() {
9839 this._lView[FLAGS] |= 128 /* Attached */;
9840 }
9841 /**
9842 * Checks the view and its children.
9843 *
9844 * This can also be used in combination with {@link ChangeDetectorRef#detach detach} to implement
9845 * local change detection checks.
9846 *
9847 * <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
9848 * <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
9849 *
9850 * @usageNotes
9851 * ### Example
9852 *
9853 * The following example defines a component with a large list of readonly data.
9854 * Imagine, the data changes constantly, many times per second. For performance reasons,
9855 * we want to check and update the list every five seconds.
9856 *
9857 * We can do that by detaching the component's change detector and doing a local change detection
9858 * check every five seconds.
9859 *
9860 * See {@link ChangeDetectorRef#detach detach} for more information.
9861 */
9862 detectChanges() {
9863 detectChangesInternal(this._lView[TVIEW], this._lView, this.context);
9864 }
9865 /**
9866 * Checks the change detector and its children, and throws if any changes are detected.
9867 *
9868 * This is used in development mode to verify that running change detection doesn't
9869 * introduce other changes.
9870 */
9871 checkNoChanges() {
9872 checkNoChangesInternal(this._lView[TVIEW], this._lView, this.context);
9873 }
9874 attachToViewContainerRef(vcRef) {
9875 if (this._appRef) {
9876 throw new Error('This view is already attached directly to the ApplicationRef!');
9877 }
9878 this._viewContainerRef = vcRef;
9879 }
9880 detachFromAppRef() {
9881 this._appRef = null;
9882 renderDetachView(this._lView[TVIEW], this._lView);
9883 }
9884 attachToAppRef(appRef) {
9885 if (this._viewContainerRef) {
9886 throw new Error('This view is already attached to a ViewContainer!');
9887 }
9888 this._appRef = appRef;
9889 }
9890}
9891/** @internal */
9892class RootViewRef extends ViewRef {
9893 constructor(_view) {
9894 super(_view);
9895 this._view = _view;
9896 }
9897 detectChanges() {
9898 detectChangesInRootView(this._view);
9899 }
9900 checkNoChanges() {
9901 checkNoChangesInRootView(this._view);
9902 }
9903 get context() {
9904 return null;
9905 }
9906}
9907function collectNativeNodes(tView, lView, tNode, result, isProjection = false) {
9908 while (tNode !== null) {
9909 ngDevMode && assertNodeOfPossibleTypes(tNode, [
9910 3 /* Element */, 0 /* Container */, 1 /* Projection */, 4 /* ElementContainer */,
9911 5 /* IcuContainer */
9912 ]);
9913 const lNode = lView[tNode.index];
9914 if (lNode !== null) {
9915 result.push(unwrapRNode(lNode));
9916 }
9917 // A given lNode can represent either a native node or a LContainer (when it is a host of a
9918 // ViewContainerRef). When we find a LContainer we need to descend into it to collect root nodes
9919 // from the views in this container.
9920 if (isLContainer(lNode)) {
9921 for (let i = CONTAINER_HEADER_OFFSET; i < lNode.length; i++) {
9922 const lViewInAContainer = lNode[i];
9923 const lViewFirstChildTNode = lViewInAContainer[TVIEW].firstChild;
9924 if (lViewFirstChildTNode !== null) {
9925 collectNativeNodes(lViewInAContainer[TVIEW], lViewInAContainer, lViewFirstChildTNode, result);
9926 }
9927 }
9928 }
9929 const tNodeType = tNode.type;
9930 if (tNodeType === 4 /* ElementContainer */ || tNodeType === 5 /* IcuContainer */) {
9931 collectNativeNodes(tView, lView, tNode.child, result);
9932 }
9933 else if (tNodeType === 1 /* Projection */) {
9934 const componentView = lView[DECLARATION_COMPONENT_VIEW];
9935 const componentHost = componentView[T_HOST];
9936 const slotIdx = tNode.projection;
9937 ngDevMode &&
9938 assertDefined(componentHost.projection, 'Components with projection nodes (<ng-content>) must have projection slots defined.');
9939 const nodesInSlot = componentHost.projection[slotIdx];
9940 if (Array.isArray(nodesInSlot)) {
9941 result.push(...nodesInSlot);
9942 }
9943 else {
9944 const parentView = getLViewParent(componentView);
9945 ngDevMode &&
9946 assertDefined(parentView, 'Component views should always have a parent view (component\'s host view)');
9947 collectNativeNodes(parentView[TVIEW], parentView, nodesInSlot, result, true);
9948 }
9949 }
9950 tNode = isProjection ? tNode.projectionNext : tNode.next;
9951 }
9952 return result;
9953}
9954
9955/**
9956 * @license
9957 * Copyright Google LLC All Rights Reserved.
9958 *
9959 * Use of this source code is governed by an MIT-style license that can be
9960 * found in the LICENSE file at https://angular.io/license
9961 */
9962/**
9963 * Creates an ElementRef from the most recent node.
9964 *
9965 * @returns The ElementRef instance to use
9966 */
9967function injectElementRef(ElementRefToken) {
9968 return createElementRef(ElementRefToken, getPreviousOrParentTNode(), getLView());
9969}
9970let R3ElementRef;
9971/**
9972 * Creates an ElementRef given a node.
9973 *
9974 * @param ElementRefToken The ElementRef type
9975 * @param tNode The node for which you'd like an ElementRef
9976 * @param view The view to which the node belongs
9977 * @returns The ElementRef instance to use
9978 */
9979function createElementRef(ElementRefToken, tNode, view) {
9980 if (!R3ElementRef) {
9981 R3ElementRef = class ElementRef extends ElementRefToken {
9982 };
9983 }
9984 return new R3ElementRef(getNativeByTNode(tNode, view));
9985}
9986let R3TemplateRef;
9987/**
9988 * Creates a TemplateRef given a node.
9989 *
9990 * @returns The TemplateRef instance to use
9991 */
9992function injectTemplateRef(TemplateRefToken, ElementRefToken) {
9993 return createTemplateRef(TemplateRefToken, ElementRefToken, getPreviousOrParentTNode(), getLView());
9994}
9995/**
9996 * Creates a TemplateRef and stores it on the injector.
9997 *
9998 * @param TemplateRefToken The TemplateRef type
9999 * @param ElementRefToken The ElementRef type
10000 * @param hostTNode The node on which a TemplateRef is requested
10001 * @param hostView The view to which the node belongs
10002 * @returns The TemplateRef instance or null if we can't create a TemplateRef on a given node type
10003 */
10004function createTemplateRef(TemplateRefToken, ElementRefToken, hostTNode, hostView) {
10005 if (!R3TemplateRef) {
10006 R3TemplateRef = class TemplateRef extends TemplateRefToken {
10007 constructor(_declarationView, _declarationTContainer, elementRef) {
10008 super();
10009 this._declarationView = _declarationView;
10010 this._declarationTContainer = _declarationTContainer;
10011 this.elementRef = elementRef;
10012 }
10013 createEmbeddedView(context) {
10014 const embeddedTView = this._declarationTContainer.tViews;
10015 const embeddedLView = createLView(this._declarationView, embeddedTView, context, 16 /* CheckAlways */, null, embeddedTView.node);
10016 const declarationLContainer = this._declarationView[this._declarationTContainer.index];
10017 ngDevMode && assertLContainer(declarationLContainer);
10018 embeddedLView[DECLARATION_LCONTAINER] = declarationLContainer;
10019 const declarationViewLQueries = this._declarationView[QUERIES];
10020 if (declarationViewLQueries !== null) {
10021 embeddedLView[QUERIES] = declarationViewLQueries.createEmbeddedView(embeddedTView);
10022 }
10023 renderView(embeddedTView, embeddedLView, context);
10024 return new ViewRef(embeddedLView);
10025 }
10026 };
10027 }
10028 if (hostTNode.type === 0 /* Container */) {
10029 ngDevMode && assertDefined(hostTNode.tViews, 'TView must be allocated');
10030 return new R3TemplateRef(hostView, hostTNode, createElementRef(ElementRefToken, hostTNode, hostView));
10031 }
10032 else {
10033 return null;
10034 }
10035}
10036let R3ViewContainerRef;
10037/**
10038 * Creates a ViewContainerRef and stores it on the injector. Or, if the ViewContainerRef
10039 * already exists, retrieves the existing ViewContainerRef.
10040 *
10041 * @returns The ViewContainerRef instance to use
10042 */
10043function injectViewContainerRef(ViewContainerRefToken, ElementRefToken) {
10044 const previousTNode = getPreviousOrParentTNode();
10045 return createContainerRef(ViewContainerRefToken, ElementRefToken, previousTNode, getLView());
10046}
10047/**
10048 * Creates a ViewContainerRef and stores it on the injector.
10049 *
10050 * @param ViewContainerRefToken The ViewContainerRef type
10051 * @param ElementRefToken The ElementRef type
10052 * @param hostTNode The node that is requesting a ViewContainerRef
10053 * @param hostView The view to which the node belongs
10054 * @returns The ViewContainerRef instance to use
10055 */
10056function createContainerRef(ViewContainerRefToken, ElementRefToken, hostTNode, hostView) {
10057 if (!R3ViewContainerRef) {
10058 R3ViewContainerRef = class ViewContainerRef extends ViewContainerRefToken {
10059 constructor(_lContainer, _hostTNode, _hostView) {
10060 super();
10061 this._lContainer = _lContainer;
10062 this._hostTNode = _hostTNode;
10063 this._hostView = _hostView;
10064 }
10065 get element() {
10066 return createElementRef(ElementRefToken, this._hostTNode, this._hostView);
10067 }
10068 get injector() {
10069 return new NodeInjector(this._hostTNode, this._hostView);
10070 }
10071 /** @deprecated No replacement */
10072 get parentInjector() {
10073 const parentLocation = getParentInjectorLocation(this._hostTNode, this._hostView);
10074 const parentView = getParentInjectorView(parentLocation, this._hostView);
10075 const parentTNode = getParentInjectorTNode(parentLocation, this._hostView, this._hostTNode);
10076 return !hasParentInjector(parentLocation) || parentTNode == null ?
10077 new NodeInjector(null, this._hostView) :
10078 new NodeInjector(parentTNode, parentView);
10079 }
10080 clear() {
10081 while (this.length > 0) {
10082 this.remove(this.length - 1);
10083 }
10084 }
10085 get(index) {
10086 return this._lContainer[VIEW_REFS] !== null && this._lContainer[VIEW_REFS][index] || null;
10087 }
10088 get length() {
10089 return this._lContainer.length - CONTAINER_HEADER_OFFSET;
10090 }
10091 createEmbeddedView(templateRef, context, index) {
10092 const viewRef = templateRef.createEmbeddedView(context || {});
10093 this.insert(viewRef, index);
10094 return viewRef;
10095 }
10096 createComponent(componentFactory, index, injector, projectableNodes, ngModuleRef) {
10097 const contextInjector = injector || this.parentInjector;
10098 if (!ngModuleRef && componentFactory.ngModule == null && contextInjector) {
10099 // DO NOT REFACTOR. The code here used to have a `value || undefined` expression
10100 // which seems to cause internal google apps to fail. This is documented in the
10101 // following internal bug issue: go/b/142967802
10102 const result = contextInjector.get(NgModuleRef, null);
10103 if (result) {
10104 ngModuleRef = result;
10105 }
10106 }
10107 const componentRef = componentFactory.create(contextInjector, projectableNodes, undefined, ngModuleRef);
10108 this.insert(componentRef.hostView, index);
10109 return componentRef;
10110 }
10111 insert(viewRef, index) {
10112 const lView = viewRef._lView;
10113 const tView = lView[TVIEW];
10114 if (viewRef.destroyed) {
10115 throw new Error('Cannot insert a destroyed View in a ViewContainer!');
10116 }
10117 this.allocateContainerIfNeeded();
10118 if (viewAttachedToContainer(lView)) {
10119 // If view is already attached, detach it first so we clean up references appropriately.
10120 const prevIdx = this.indexOf(viewRef);
10121 // A view might be attached either to this or a different container. The `prevIdx` for
10122 // those cases will be:
10123 // equal to -1 for views attached to this ViewContainerRef
10124 // >= 0 for views attached to a different ViewContainerRef
10125 if (prevIdx !== -1) {
10126 this.detach(prevIdx);
10127 }
10128 else {
10129 const prevLContainer = lView[PARENT];
10130 ngDevMode &&
10131 assertEqual(isLContainer(prevLContainer), true, 'An attached view should have its PARENT point to a container.');
10132 // We need to re-create a R3ViewContainerRef instance since those are not stored on
10133 // LView (nor anywhere else).
10134 const prevVCRef = new R3ViewContainerRef(prevLContainer, prevLContainer[T_HOST], prevLContainer[PARENT]);
10135 prevVCRef.detach(prevVCRef.indexOf(viewRef));
10136 }
10137 }
10138 const adjustedIdx = this._adjustIndex(index);
10139 insertView(tView, lView, this._lContainer, adjustedIdx);
10140 const beforeNode = getBeforeNodeForView(adjustedIdx, this._lContainer);
10141 addRemoveViewFromContainer(tView, lView, true, beforeNode);
10142 viewRef.attachToViewContainerRef(this);
10143 addToArray(this._lContainer[VIEW_REFS], adjustedIdx, viewRef);
10144 return viewRef;
10145 }
10146 move(viewRef, newIndex) {
10147 if (viewRef.destroyed) {
10148 throw new Error('Cannot move a destroyed View in a ViewContainer!');
10149 }
10150 return this.insert(viewRef, newIndex);
10151 }
10152 indexOf(viewRef) {
10153 const viewRefsArr = this._lContainer[VIEW_REFS];
10154 return viewRefsArr !== null ? viewRefsArr.indexOf(viewRef) : -1;
10155 }
10156 remove(index) {
10157 this.allocateContainerIfNeeded();
10158 const adjustedIdx = this._adjustIndex(index, -1);
10159 const detachedView = detachView(this._lContainer, adjustedIdx);
10160 if (detachedView) {
10161 // Before destroying the view, remove it from the container's array of `ViewRef`s.
10162 // This ensures the view container length is updated before calling
10163 // `destroyLView`, which could recursively call view container methods that
10164 // rely on an accurate container length.
10165 // (e.g. a method on this view container being called by a child directive's OnDestroy
10166 // lifecycle hook)
10167 removeFromArray(this._lContainer[VIEW_REFS], adjustedIdx);
10168 destroyLView(detachedView[TVIEW], detachedView);
10169 }
10170 }
10171 detach(index) {
10172 this.allocateContainerIfNeeded();
10173 const adjustedIdx = this._adjustIndex(index, -1);
10174 const view = detachView(this._lContainer, adjustedIdx);
10175 const wasDetached = view && removeFromArray(this._lContainer[VIEW_REFS], adjustedIdx) != null;
10176 return wasDetached ? new ViewRef(view) : null;
10177 }
10178 _adjustIndex(index, shift = 0) {
10179 if (index == null) {
10180 return this.length + shift;
10181 }
10182 if (ngDevMode) {
10183 assertGreaterThan(index, -1, `ViewRef index must be positive, got ${index}`);
10184 // +1 because it's legal to insert at the end.
10185 assertLessThan(index, this.length + 1 + shift, 'index');
10186 }
10187 return index;
10188 }
10189 allocateContainerIfNeeded() {
10190 if (this._lContainer[VIEW_REFS] === null) {
10191 this._lContainer[VIEW_REFS] = [];
10192 }
10193 }
10194 };
10195 }
10196 ngDevMode &&
10197 assertNodeOfPossibleTypes(hostTNode, [0 /* Container */, 3 /* Element */, 4 /* ElementContainer */]);
10198 let lContainer;
10199 const slotValue = hostView[hostTNode.index];
10200 if (isLContainer(slotValue)) {
10201 // If the host is a container, we don't need to create a new LContainer
10202 lContainer = slotValue;
10203 }
10204 else {
10205 let commentNode;
10206 // If the host is an element container, the native host element is guaranteed to be a
10207 // comment and we can reuse that comment as anchor element for the new LContainer.
10208 // The comment node in question is already part of the DOM structure so we don't need to append
10209 // it again.
10210 if (hostTNode.type === 4 /* ElementContainer */) {
10211 commentNode = unwrapRNode(slotValue);
10212 }
10213 else {
10214 ngDevMode && ngDevMode.rendererCreateComment++;
10215 commentNode = hostView[RENDERER].createComment(ngDevMode ? 'container' : '');
10216 // A `ViewContainerRef` can be injected by the root (topmost / bootstrapped) component. In
10217 // this case we can't use TView / TNode data structures to insert container's marker node
10218 // (both a parent of a comment node and the comment node itself are not part of any view). In
10219 // this specific case we use low-level DOM manipulation to insert container's marker (comment)
10220 // node.
10221 if (isRootView(hostView)) {
10222 const renderer = hostView[RENDERER];
10223 const hostNative = getNativeByTNode(hostTNode, hostView);
10224 const parentOfHostNative = nativeParentNode(renderer, hostNative);
10225 nativeInsertBefore(renderer, parentOfHostNative, commentNode, nativeNextSibling(renderer, hostNative));
10226 }
10227 else {
10228 appendChild(hostView[TVIEW], hostView, commentNode, hostTNode);
10229 }
10230 }
10231 hostView[hostTNode.index] = lContainer =
10232 createLContainer(slotValue, hostView, commentNode, hostTNode);
10233 addToViewTree(hostView, lContainer);
10234 }
10235 return new R3ViewContainerRef(lContainer, hostTNode, hostView);
10236}
10237/** Returns a ChangeDetectorRef (a.k.a. a ViewRef) */
10238function injectChangeDetectorRef(isPipe = false) {
10239 return createViewRef(getPreviousOrParentTNode(), getLView(), isPipe);
10240}
10241/**
10242 * Creates a ViewRef and stores it on the injector as ChangeDetectorRef (public alias).
10243 *
10244 * @param tNode The node that is requesting a ChangeDetectorRef
10245 * @param lView The view to which the node belongs
10246 * @param isPipe Whether the view is being injected into a pipe.
10247 * @returns The ChangeDetectorRef to use
10248 */
10249function createViewRef(tNode, lView, isPipe) {
10250 // `isComponentView` will be true for Component and Directives (but not for Pipes).
10251 // See https://github.com/angular/angular/pull/33072 for proper fix
10252 const isComponentView = !isPipe && isComponentHost(tNode);
10253 if (isComponentView) {
10254 // The LView represents the location where the component is declared.
10255 // Instead we want the LView for the component View and so we need to look it up.
10256 const componentView = getComponentLViewByIndex(tNode.index, lView); // look down
10257 return new ViewRef(componentView, componentView);
10258 }
10259 else if (tNode.type === 3 /* Element */ || tNode.type === 0 /* Container */ ||
10260 tNode.type === 4 /* ElementContainer */ || tNode.type === 5 /* IcuContainer */) {
10261 // The LView represents the location where the injection is requested from.
10262 // We need to locate the containing LView (in case where the `lView` is an embedded view)
10263 const hostComponentView = lView[DECLARATION_COMPONENT_VIEW]; // look up
10264 return new ViewRef(hostComponentView, lView);
10265 }
10266 return null;
10267}
10268/** Returns a Renderer2 (or throws when application was bootstrapped with Renderer3) */
10269function getOrCreateRenderer2(view) {
10270 const renderer = view[RENDERER];
10271 if (isProceduralRenderer(renderer)) {
10272 return renderer;
10273 }
10274 else {
10275 throw new Error('Cannot inject Renderer2 when the application uses Renderer3!');
10276 }
10277}
10278/** Injects a Renderer2 for the current component. */
10279function injectRenderer2() {
10280 // We need the Renderer to be based on the component that it's being injected into, however since
10281 // DI happens before we've entered its view, `getLView` will return the parent view instead.
10282 const lView = getLView();
10283 const tNode = getPreviousOrParentTNode();
10284 const nodeAtIndex = getComponentLViewByIndex(tNode.index, lView);
10285 return getOrCreateRenderer2(isLView(nodeAtIndex) ? nodeAtIndex : lView);
10286}
10287
10288/**
10289 * @license
10290 * Copyright Google LLC All Rights Reserved.
10291 *
10292 * Use of this source code is governed by an MIT-style license that can be
10293 * found in the LICENSE file at https://angular.io/license
10294 */
10295/**
10296 * Base class that provides change detection functionality.
10297 * A change-detection tree collects all views that are to be checked for changes.
10298 * Use the methods to add and remove views from the tree, initiate change-detection,
10299 * and explicitly mark views as _dirty_, meaning that they have changed and need to be re-rendered.
10300 *
10301 * @see [Using change detection hooks](guide/lifecycle-hooks#using-change-detection-hooks)
10302 * @see [Defining custom change detection](guide/lifecycle-hooks#defining-custom-change-detection)
10303 *
10304 * @usageNotes
10305 *
10306 * The following examples demonstrate how to modify default change-detection behavior
10307 * to perform explicit detection when needed.
10308 *
10309 * ### Use `markForCheck()` with `CheckOnce` strategy
10310 *
10311 * The following example sets the `OnPush` change-detection strategy for a component
10312 * (`CheckOnce`, rather than the default `CheckAlways`), then forces a second check
10313 * after an interval. See [live demo](http://plnkr.co/edit/GC512b?p=preview).
10314 *
10315 * <code-example path="core/ts/change_detect/change-detection.ts"
10316 * region="mark-for-check"></code-example>
10317 *
10318 * ### Detach change detector to limit how often check occurs
10319 *
10320 * The following example defines a component with a large list of read-only data
10321 * that is expected to change constantly, many times per second.
10322 * To improve performance, we want to check and update the list
10323 * less often than the changes actually occur. To do that, we detach
10324 * the component's change detector and perform an explicit local check every five seconds.
10325 *
10326 * <code-example path="core/ts/change_detect/change-detection.ts" region="detach"></code-example>
10327 *
10328 *
10329 * ### Reattaching a detached component
10330 *
10331 * The following example creates a component displaying live data.
10332 * The component detaches its change detector from the main change detector tree
10333 * when the `live` property is set to false, and reattaches it when the property
10334 * becomes true.
10335 *
10336 * <code-example path="core/ts/change_detect/change-detection.ts" region="reattach"></code-example>
10337 *
10338 * @publicApi
10339 */
10340class ChangeDetectorRef {
10341}
10342/**
10343 * @internal
10344 * @nocollapse
10345 */
10346ChangeDetectorRef.__NG_ELEMENT_ID__ = () => SWITCH_CHANGE_DETECTOR_REF_FACTORY();
10347const SWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__ = injectChangeDetectorRef;
10348const SWITCH_CHANGE_DETECTOR_REF_FACTORY__PRE_R3__ = (...args) => { };
10349const ɵ0$5 = SWITCH_CHANGE_DETECTOR_REF_FACTORY__PRE_R3__;
10350const SWITCH_CHANGE_DETECTOR_REF_FACTORY = SWITCH_CHANGE_DETECTOR_REF_FACTORY__PRE_R3__;
10351
10352/**
10353 * @license
10354 * Copyright Google LLC All Rights Reserved.
10355 *
10356 * Use of this source code is governed by an MIT-style license that can be
10357 * found in the LICENSE file at https://angular.io/license
10358 */
10359/**
10360 * @description
10361 *
10362 * Represents a type that a Component or other object is instances of.
10363 *
10364 * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is represented by
10365 * the `MyCustomComponent` constructor function.
10366 *
10367 * @publicApi
10368 */
10369const Type = Function;
10370function isType(v) {
10371 return typeof v === 'function';
10372}
10373
10374/**
10375 * @license
10376 * Copyright Google LLC All Rights Reserved.
10377 *
10378 * Use of this source code is governed by an MIT-style license that can be
10379 * found in the LICENSE file at https://angular.io/license
10380 */
10381/*
10382 * #########################
10383 * Attention: These Regular expressions have to hold even if the code is minified!
10384 * ##########################
10385 */
10386/**
10387 * Regular expression that detects pass-through constructors for ES5 output. This Regex
10388 * intends to capture the common delegation pattern emitted by TypeScript and Babel. Also
10389 * it intends to capture the pattern where existing constructors have been downleveled from
10390 * ES2015 to ES5 using TypeScript w/ downlevel iteration. e.g.
10391 *
10392 * ```
10393 * function MyClass() {
10394 * var _this = _super.apply(this, arguments) || this;
10395 * ```
10396 *
10397 * ```
10398 * function MyClass() {
10399 * var _this = _super.apply(this, __spread(arguments)) || this;
10400 * ```
10401 *
10402 * More details can be found in: https://github.com/angular/angular/issues/38453.
10403 */
10404const ES5_DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*(arguments|[^()]+\(arguments\))\)/;
10405/** Regular expression that detects ES2015 classes which extend from other classes. */
10406const ES2015_INHERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/;
10407/**
10408 * Regular expression that detects ES2015 classes which extend from other classes and
10409 * have an explicit constructor defined.
10410 */
10411const ES2015_INHERITED_CLASS_WITH_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(/;
10412/**
10413 * Regular expression that detects ES2015 classes which extend from other classes
10414 * and inherit a constructor.
10415 */
10416const ES2015_INHERITED_CLASS_WITH_DELEGATE_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(\)\s*{\s*super\(\.\.\.arguments\)/;
10417/**
10418 * Determine whether a stringified type is a class which delegates its constructor
10419 * to its parent.
10420 *
10421 * This is not trivial since compiled code can actually contain a constructor function
10422 * even if the original source code did not. For instance, when the child class contains
10423 * an initialized instance property.
10424 */
10425function isDelegateCtor(typeStr) {
10426 return ES5_DELEGATE_CTOR.test(typeStr) ||
10427 ES2015_INHERITED_CLASS_WITH_DELEGATE_CTOR.test(typeStr) ||
10428 (ES2015_INHERITED_CLASS.test(typeStr) && !ES2015_INHERITED_CLASS_WITH_CTOR.test(typeStr));
10429}
10430class ReflectionCapabilities {
10431 constructor(reflect) {
10432 this._reflect = reflect || _global['Reflect'];
10433 }
10434 isReflectionEnabled() {
10435 return true;
10436 }
10437 factory(t) {
10438 return (...args) => new t(...args);
10439 }
10440 /** @internal */
10441 _zipTypesAndAnnotations(paramTypes, paramAnnotations) {
10442 let result;
10443 if (typeof paramTypes === 'undefined') {
10444 result = newArray(paramAnnotations.length);
10445 }
10446 else {
10447 result = newArray(paramTypes.length);
10448 }
10449 for (let i = 0; i < result.length; i++) {
10450 // TS outputs Object for parameters without types, while Traceur omits
10451 // the annotations. For now we preserve the Traceur behavior to aid
10452 // migration, but this can be revisited.
10453 if (typeof paramTypes === 'undefined') {
10454 result[i] = [];
10455 }
10456 else if (paramTypes[i] && paramTypes[i] != Object) {
10457 result[i] = [paramTypes[i]];
10458 }
10459 else {
10460 result[i] = [];
10461 }
10462 if (paramAnnotations && paramAnnotations[i] != null) {
10463 result[i] = result[i].concat(paramAnnotations[i]);
10464 }
10465 }
10466 return result;
10467 }
10468 _ownParameters(type, parentCtor) {
10469 const typeStr = type.toString();
10470 // If we have no decorators, we only have function.length as metadata.
10471 // In that case, to detect whether a child class declared an own constructor or not,
10472 // we need to look inside of that constructor to check whether it is
10473 // just calling the parent.
10474 // This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439
10475 // that sets 'design:paramtypes' to []
10476 // if a class inherits from another class but has no ctor declared itself.
10477 if (isDelegateCtor(typeStr)) {
10478 return null;
10479 }
10480 // Prefer the direct API.
10481 if (type.parameters && type.parameters !== parentCtor.parameters) {
10482 return type.parameters;
10483 }
10484 // API of tsickle for lowering decorators to properties on the class.
10485 const tsickleCtorParams = type.ctorParameters;
10486 if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {
10487 // Newer tsickle uses a function closure
10488 // Retain the non-function case for compatibility with older tsickle
10489 const ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;
10490 const paramTypes = ctorParameters.map((ctorParam) => ctorParam && ctorParam.type);
10491 const paramAnnotations = ctorParameters.map((ctorParam) => ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators));
10492 return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
10493 }
10494 // API for metadata created by invoking the decorators.
10495 const paramAnnotations = type.hasOwnProperty(PARAMETERS) && type[PARAMETERS];
10496 const paramTypes = this._reflect && this._reflect.getOwnMetadata &&
10497 this._reflect.getOwnMetadata('design:paramtypes', type);
10498 if (paramTypes || paramAnnotations) {
10499 return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
10500 }
10501 // If a class has no decorators, at least create metadata
10502 // based on function.length.
10503 // Note: We know that this is a real constructor as we checked
10504 // the content of the constructor above.
10505 return newArray(type.length);
10506 }
10507 parameters(type) {
10508 // Note: only report metadata if we have at least one class decorator
10509 // to stay in sync with the static reflector.
10510 if (!isType(type)) {
10511 return [];
10512 }
10513 const parentCtor = getParentCtor(type);
10514 let parameters = this._ownParameters(type, parentCtor);
10515 if (!parameters && parentCtor !== Object) {
10516 parameters = this.parameters(parentCtor);
10517 }
10518 return parameters || [];
10519 }
10520 _ownAnnotations(typeOrFunc, parentCtor) {
10521 // Prefer the direct API.
10522 if (typeOrFunc.annotations && typeOrFunc.annotations !== parentCtor.annotations) {
10523 let annotations = typeOrFunc.annotations;
10524 if (typeof annotations === 'function' && annotations.annotations) {
10525 annotations = annotations.annotations;
10526 }
10527 return annotations;
10528 }
10529 // API of tsickle for lowering decorators to properties on the class.
10530 if (typeOrFunc.decorators && typeOrFunc.decorators !== parentCtor.decorators) {
10531 return convertTsickleDecoratorIntoMetadata(typeOrFunc.decorators);
10532 }
10533 // API for metadata created by invoking the decorators.
10534 if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) {
10535 return typeOrFunc[ANNOTATIONS];
10536 }
10537 return null;
10538 }
10539 annotations(typeOrFunc) {
10540 if (!isType(typeOrFunc)) {
10541 return [];
10542 }
10543 const parentCtor = getParentCtor(typeOrFunc);
10544 const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];
10545 const parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];
10546 return parentAnnotations.concat(ownAnnotations);
10547 }
10548 _ownPropMetadata(typeOrFunc, parentCtor) {
10549 // Prefer the direct API.
10550 if (typeOrFunc.propMetadata &&
10551 typeOrFunc.propMetadata !== parentCtor.propMetadata) {
10552 let propMetadata = typeOrFunc.propMetadata;
10553 if (typeof propMetadata === 'function' && propMetadata.propMetadata) {
10554 propMetadata = propMetadata.propMetadata;
10555 }
10556 return propMetadata;
10557 }
10558 // API of tsickle for lowering decorators to properties on the class.
10559 if (typeOrFunc.propDecorators &&
10560 typeOrFunc.propDecorators !== parentCtor.propDecorators) {
10561 const propDecorators = typeOrFunc.propDecorators;
10562 const propMetadata = {};
10563 Object.keys(propDecorators).forEach(prop => {
10564 propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]);
10565 });
10566 return propMetadata;
10567 }
10568 // API for metadata created by invoking the decorators.
10569 if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {
10570 return typeOrFunc[PROP_METADATA];
10571 }
10572 return null;
10573 }
10574 propMetadata(typeOrFunc) {
10575 if (!isType(typeOrFunc)) {
10576 return {};
10577 }
10578 const parentCtor = getParentCtor(typeOrFunc);
10579 const propMetadata = {};
10580 if (parentCtor !== Object) {
10581 const parentPropMetadata = this.propMetadata(parentCtor);
10582 Object.keys(parentPropMetadata).forEach((propName) => {
10583 propMetadata[propName] = parentPropMetadata[propName];
10584 });
10585 }
10586 const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);
10587 if (ownPropMetadata) {
10588 Object.keys(ownPropMetadata).forEach((propName) => {
10589 const decorators = [];
10590 if (propMetadata.hasOwnProperty(propName)) {
10591 decorators.push(...propMetadata[propName]);
10592 }
10593 decorators.push(...ownPropMetadata[propName]);
10594 propMetadata[propName] = decorators;
10595 });
10596 }
10597 return propMetadata;
10598 }
10599 ownPropMetadata(typeOrFunc) {
10600 if (!isType(typeOrFunc)) {
10601 return {};
10602 }
10603 return this._ownPropMetadata(typeOrFunc, getParentCtor(typeOrFunc)) || {};
10604 }
10605 hasLifecycleHook(type, lcProperty) {
10606 return type instanceof Type && lcProperty in type.prototype;
10607 }
10608 guards(type) {
10609 return {};
10610 }
10611 getter(name) {
10612 return new Function('o', 'return o.' + name + ';');
10613 }
10614 setter(name) {
10615 return new Function('o', 'v', 'return o.' + name + ' = v;');
10616 }
10617 method(name) {
10618 const functionBody = `if (!o.${name}) throw new Error('"${name}" is undefined');
10619 return o.${name}.apply(o, args);`;
10620 return new Function('o', 'args', functionBody);
10621 }
10622 // There is not a concept of import uri in Js, but this is useful in developing Dart applications.
10623 importUri(type) {
10624 // StaticSymbol
10625 if (typeof type === 'object' && type['filePath']) {
10626 return type['filePath'];
10627 }
10628 // Runtime type
10629 return `./${stringify(type)}`;
10630 }
10631 resourceUri(type) {
10632 return `./${stringify(type)}`;
10633 }
10634 resolveIdentifier(name, moduleUrl, members, runtime) {
10635 return runtime;
10636 }
10637 resolveEnum(enumIdentifier, name) {
10638 return enumIdentifier[name];
10639 }
10640}
10641function convertTsickleDecoratorIntoMetadata(decoratorInvocations) {
10642 if (!decoratorInvocations) {
10643 return [];
10644 }
10645 return decoratorInvocations.map(decoratorInvocation => {
10646 const decoratorType = decoratorInvocation.type;
10647 const annotationCls = decoratorType.annotationCls;
10648 const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];
10649 return new annotationCls(...annotationArgs);
10650 });
10651}
10652function getParentCtor(ctor) {
10653 const parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;
10654 const parentCtor = parentProto ? parentProto.constructor : null;
10655 // Note: We always use `Object` as the null value
10656 // to simplify checking later on.
10657 return parentCtor || Object;
10658}
10659
10660/**
10661 * @license
10662 * Copyright Google LLC All Rights Reserved.
10663 *
10664 * Use of this source code is governed by an MIT-style license that can be
10665 * found in the LICENSE file at https://angular.io/license
10666 */
10667let _reflect = null;
10668function getReflect() {
10669 return (_reflect = _reflect || new ReflectionCapabilities());
10670}
10671function reflectDependencies(type) {
10672 return convertDependencies(getReflect().parameters(type));
10673}
10674function convertDependencies(deps) {
10675 const compiler = getCompilerFacade();
10676 return deps.map(dep => reflectDependency(compiler, dep));
10677}
10678function reflectDependency(compiler, dep) {
10679 const meta = {
10680 token: null,
10681 host: false,
10682 optional: false,
10683 resolved: compiler.R3ResolvedDependencyType.Token,
10684 self: false,
10685 skipSelf: false,
10686 };
10687 function setTokenAndResolvedType(token) {
10688 meta.resolved = compiler.R3ResolvedDependencyType.Token;
10689 meta.token = token;
10690 }
10691 if (Array.isArray(dep) && dep.length > 0) {
10692 for (let j = 0; j < dep.length; j++) {
10693 const param = dep[j];
10694 if (param === undefined) {
10695 // param may be undefined if type of dep is not set by ngtsc
10696 continue;
10697 }
10698 const proto = Object.getPrototypeOf(param);
10699 if (param instanceof Optional || proto.ngMetadataName === 'Optional') {
10700 meta.optional = true;
10701 }
10702 else if (param instanceof SkipSelf || proto.ngMetadataName === 'SkipSelf') {
10703 meta.skipSelf = true;
10704 }
10705 else if (param instanceof Self || proto.ngMetadataName === 'Self') {
10706 meta.self = true;
10707 }
10708 else if (param instanceof Host || proto.ngMetadataName === 'Host') {
10709 meta.host = true;
10710 }
10711 else if (param instanceof Inject) {
10712 meta.token = param.token;
10713 }
10714 else if (param instanceof Attribute) {
10715 if (param.attributeName === undefined) {
10716 throw new Error(`Attribute name must be defined.`);
10717 }
10718 meta.token = param.attributeName;
10719 meta.resolved = compiler.R3ResolvedDependencyType.Attribute;
10720 }
10721 else if (param === ChangeDetectorRef) {
10722 meta.token = param;
10723 meta.resolved = compiler.R3ResolvedDependencyType.ChangeDetectorRef;
10724 }
10725 else {
10726 setTokenAndResolvedType(param);
10727 }
10728 }
10729 }
10730 else if (dep === undefined || (Array.isArray(dep) && dep.length === 0)) {
10731 meta.token = undefined;
10732 meta.resolved = R3ResolvedDependencyType.Invalid;
10733 }
10734 else {
10735 setTokenAndResolvedType(dep);
10736 }
10737 return meta;
10738}
10739
10740/**
10741 * @license
10742 * Copyright Google LLC All Rights Reserved.
10743 *
10744 * Use of this source code is governed by an MIT-style license that can be
10745 * found in the LICENSE file at https://angular.io/license
10746 */
10747/**
10748 * Compile an Angular injectable according to its `Injectable` metadata, and patch the resulting
10749 * injectable def (`ɵprov`) onto the injectable type.
10750 */
10751function compileInjectable(type, srcMeta) {
10752 let ngInjectableDef = null;
10753 let ngFactoryDef = null;
10754 // if NG_PROV_DEF is already defined on this class then don't overwrite it
10755 if (!type.hasOwnProperty(NG_PROV_DEF)) {
10756 Object.defineProperty(type, NG_PROV_DEF, {
10757 get: () => {
10758 if (ngInjectableDef === null) {
10759 ngInjectableDef = getCompilerFacade().compileInjectable(angularCoreDiEnv, `ng:///${type.name}/ɵprov.js`, getInjectableMetadata(type, srcMeta));
10760 }
10761 return ngInjectableDef;
10762 },
10763 });
10764 // On IE10 properties defined via `defineProperty` won't be inherited by child classes,
10765 // which will break inheriting the injectable definition from a grandparent through an
10766 // undecorated parent class. We work around it by defining a method which should be used
10767 // as a fallback. This should only be a problem in JIT mode, because in AOT TypeScript
10768 // seems to have a workaround for static properties. When inheriting from an undecorated
10769 // parent is no longer supported (v11 or later), this can safely be removed.
10770 if (!type.hasOwnProperty(NG_PROV_DEF_FALLBACK)) {
10771 type[NG_PROV_DEF_FALLBACK] = () => type[NG_PROV_DEF];
10772 }
10773 }
10774 // if NG_FACTORY_DEF is already defined on this class then don't overwrite it
10775 if (!type.hasOwnProperty(NG_FACTORY_DEF)) {
10776 Object.defineProperty(type, NG_FACTORY_DEF, {
10777 get: () => {
10778 if (ngFactoryDef === null) {
10779 const metadata = getInjectableMetadata(type, srcMeta);
10780 const compiler = getCompilerFacade();
10781 ngFactoryDef = compiler.compileFactory(angularCoreDiEnv, `ng:///${type.name}/ɵfac.js`, {
10782 name: metadata.name,
10783 type: metadata.type,
10784 typeArgumentCount: metadata.typeArgumentCount,
10785 deps: reflectDependencies(type),
10786 injectFn: 'inject',
10787 target: compiler.R3FactoryTarget.Injectable
10788 });
10789 }
10790 return ngFactoryDef;
10791 },
10792 // Leave this configurable so that the factories from directives or pipes can take precedence.
10793 configurable: true
10794 });
10795 }
10796}
10797const ɵ0$6 = getClosureSafeProperty;
10798const USE_VALUE$1 = getClosureSafeProperty({ provide: String, useValue: ɵ0$6 });
10799function isUseClassProvider(meta) {
10800 return meta.useClass !== undefined;
10801}
10802function isUseValueProvider(meta) {
10803 return USE_VALUE$1 in meta;
10804}
10805function isUseFactoryProvider(meta) {
10806 return meta.useFactory !== undefined;
10807}
10808function isUseExistingProvider(meta) {
10809 return meta.useExisting !== undefined;
10810}
10811function getInjectableMetadata(type, srcMeta) {
10812 // Allow the compilation of a class with a `@Injectable()` decorator without parameters
10813 const meta = srcMeta || { providedIn: null };
10814 const compilerMeta = {
10815 name: type.name,
10816 type: type,
10817 typeArgumentCount: 0,
10818 providedIn: meta.providedIn,
10819 userDeps: undefined,
10820 };
10821 if ((isUseClassProvider(meta) || isUseFactoryProvider(meta)) && meta.deps !== undefined) {
10822 compilerMeta.userDeps = convertDependencies(meta.deps);
10823 }
10824 if (isUseClassProvider(meta)) {
10825 // The user explicitly specified useClass, and may or may not have provided deps.
10826 compilerMeta.useClass = resolveForwardRef(meta.useClass);
10827 }
10828 else if (isUseValueProvider(meta)) {
10829 // The user explicitly specified useValue.
10830 compilerMeta.useValue = resolveForwardRef(meta.useValue);
10831 }
10832 else if (isUseFactoryProvider(meta)) {
10833 // The user explicitly specified useFactory.
10834 compilerMeta.useFactory = meta.useFactory;
10835 }
10836 else if (isUseExistingProvider(meta)) {
10837 // The user explicitly specified useExisting.
10838 compilerMeta.useExisting = resolveForwardRef(meta.useExisting);
10839 }
10840 return compilerMeta;
10841}
10842
10843/**
10844 * @license
10845 * Copyright Google LLC All Rights Reserved.
10846 *
10847 * Use of this source code is governed by an MIT-style license that can be
10848 * found in the LICENSE file at https://angular.io/license
10849 */
10850const ɵ0$7 = getClosureSafeProperty;
10851const USE_VALUE$2 = getClosureSafeProperty({ provide: String, useValue: ɵ0$7 });
10852const EMPTY_ARRAY$1 = [];
10853function convertInjectableProviderToFactory(type, provider) {
10854 if (!provider) {
10855 const reflectionCapabilities = new ReflectionCapabilities();
10856 const deps = reflectionCapabilities.parameters(type);
10857 // TODO - convert to flags.
10858 return () => new type(...injectArgs(deps));
10859 }
10860 if (USE_VALUE$2 in provider) {
10861 const valueProvider = provider;
10862 return () => valueProvider.useValue;
10863 }
10864 else if (provider.useExisting) {
10865 const existingProvider = provider;
10866 return () => ɵɵinject(resolveForwardRef(existingProvider.useExisting));
10867 }
10868 else if (provider.useFactory) {
10869 const factoryProvider = provider;
10870 return () => factoryProvider.useFactory(...injectArgs(factoryProvider.deps || EMPTY_ARRAY$1));
10871 }
10872 else if (provider.useClass) {
10873 const classProvider = provider;
10874 let deps = provider.deps;
10875 if (!deps) {
10876 const reflectionCapabilities = new ReflectionCapabilities();
10877 deps = reflectionCapabilities.parameters(type);
10878 }
10879 return () => new (resolveForwardRef(classProvider.useClass))(...injectArgs(deps));
10880 }
10881 else {
10882 let deps = provider.deps;
10883 if (!deps) {
10884 const reflectionCapabilities = new ReflectionCapabilities();
10885 deps = reflectionCapabilities.parameters(type);
10886 }
10887 return () => new type(...injectArgs(deps));
10888 }
10889}
10890
10891/**
10892 * @license
10893 * Copyright Google LLC All Rights Reserved.
10894 *
10895 * Use of this source code is governed by an MIT-style license that can be
10896 * found in the LICENSE file at https://angular.io/license
10897 */
10898const ɵ0$8 = (type, meta) => SWITCH_COMPILE_INJECTABLE(type, meta);
10899/**
10900 * Injectable decorator and metadata.
10901 *
10902 * @Annotation
10903 * @publicApi
10904 */
10905const Injectable = makeDecorator('Injectable', undefined, undefined, undefined, ɵ0$8);
10906/**
10907 * Supports @Injectable() in JIT mode for Render2.
10908 */
10909function render2CompileInjectable(injectableType, options) {
10910 if (options && options.providedIn !== undefined && !getInjectableDef(injectableType)) {
10911 injectableType.ɵprov = ɵɵdefineInjectable({
10912 token: injectableType,
10913 providedIn: options.providedIn,
10914 factory: convertInjectableProviderToFactory(injectableType, options),
10915 });
10916 }
10917}
10918const SWITCH_COMPILE_INJECTABLE__POST_R3__ = compileInjectable;
10919const SWITCH_COMPILE_INJECTABLE__PRE_R3__ = render2CompileInjectable;
10920const SWITCH_COMPILE_INJECTABLE = SWITCH_COMPILE_INJECTABLE__PRE_R3__;
10921
10922/**
10923 * @license
10924 * Copyright Google LLC All Rights Reserved.
10925 *
10926 * Use of this source code is governed by an MIT-style license that can be
10927 * found in the LICENSE file at https://angular.io/license
10928 */
10929/**
10930 * An internal token whose presence in an injector indicates that the injector should treat itself
10931 * as a root scoped injector when processing requests for unknown tokens which may indicate
10932 * they are provided in the root scope.
10933 */
10934const INJECTOR_SCOPE = new InjectionToken('Set Injector scope.');
10935
10936/**
10937 * @license
10938 * Copyright Google LLC All Rights Reserved.
10939 *
10940 * Use of this source code is governed by an MIT-style license that can be
10941 * found in the LICENSE file at https://angular.io/license
10942 */
10943/**
10944 * Marker which indicates that a value has not yet been created from the factory function.
10945 */
10946const NOT_YET = {};
10947/**
10948 * Marker which indicates that the factory function for a token is in the process of being called.
10949 *
10950 * If the injector is asked to inject a token with its value set to CIRCULAR, that indicates
10951 * injection of a dependency has recursively attempted to inject the original token, and there is
10952 * a circular dependency among the providers.
10953 */
10954const CIRCULAR = {};
10955const EMPTY_ARRAY$2 = [];
10956/**
10957 * A lazily initialized NullInjector.
10958 */
10959let NULL_INJECTOR = undefined;
10960function getNullInjector() {
10961 if (NULL_INJECTOR === undefined) {
10962 NULL_INJECTOR = new NullInjector();
10963 }
10964 return NULL_INJECTOR;
10965}
10966/**
10967 * Create a new `Injector` which is configured using a `defType` of `InjectorType<any>`s.
10968 *
10969 * @publicApi
10970 */
10971function createInjector(defType, parent = null, additionalProviders = null, name) {
10972 const injector = createInjectorWithoutInjectorInstances(defType, parent, additionalProviders, name);
10973 injector._resolveInjectorDefTypes();
10974 return injector;
10975}
10976/**
10977 * Creates a new injector without eagerly resolving its injector types. Can be used in places
10978 * where resolving the injector types immediately can lead to an infinite loop. The injector types
10979 * should be resolved at a later point by calling `_resolveInjectorDefTypes`.
10980 */
10981function createInjectorWithoutInjectorInstances(defType, parent = null, additionalProviders = null, name) {
10982 return new R3Injector(defType, additionalProviders, parent || getNullInjector(), name);
10983}
10984class R3Injector {
10985 constructor(def, additionalProviders, parent, source = null) {
10986 this.parent = parent;
10987 /**
10988 * Map of tokens to records which contain the instances of those tokens.
10989 * - `null` value implies that we don't have the record. Used by tree-shakable injectors
10990 * to prevent further searches.
10991 */
10992 this.records = new Map();
10993 /**
10994 * The transitive set of `InjectorType`s which define this injector.
10995 */
10996 this.injectorDefTypes = new Set();
10997 /**
10998 * Set of values instantiated by this injector which contain `ngOnDestroy` lifecycle hooks.
10999 */
11000 this.onDestroy = new Set();
11001 this._destroyed = false;
11002 const dedupStack = [];
11003 // Start off by creating Records for every provider declared in every InjectorType
11004 // included transitively in additional providers then do the same for `def`. This order is
11005 // important because `def` may include providers that override ones in additionalProviders.
11006 additionalProviders &&
11007 deepForEach(additionalProviders, provider => this.processProvider(provider, def, additionalProviders));
11008 deepForEach([def], injectorDef => this.processInjectorType(injectorDef, [], dedupStack));
11009 // Make sure the INJECTOR token provides this injector.
11010 this.records.set(INJECTOR, makeRecord(undefined, this));
11011 // Detect whether this injector has the APP_ROOT_SCOPE token and thus should provide
11012 // any injectable scoped to APP_ROOT_SCOPE.
11013 const record = this.records.get(INJECTOR_SCOPE);
11014 this.scope = record != null ? record.value : null;
11015 // Source name, used for debugging
11016 this.source = source || (typeof def === 'object' ? null : stringify(def));
11017 }
11018 /**
11019 * Flag indicating that this injector was previously destroyed.
11020 */
11021 get destroyed() {
11022 return this._destroyed;
11023 }
11024 /**
11025 * Destroy the injector and release references to every instance or provider associated with it.
11026 *
11027 * Also calls the `OnDestroy` lifecycle hooks of every instance that was created for which a
11028 * hook was found.
11029 */
11030 destroy() {
11031 this.assertNotDestroyed();
11032 // Set destroyed = true first, in case lifecycle hooks re-enter destroy().
11033 this._destroyed = true;
11034 try {
11035 // Call all the lifecycle hooks.
11036 this.onDestroy.forEach(service => service.ngOnDestroy());
11037 }
11038 finally {
11039 // Release all references.
11040 this.records.clear();
11041 this.onDestroy.clear();
11042 this.injectorDefTypes.clear();
11043 }
11044 }
11045 get(token, notFoundValue = THROW_IF_NOT_FOUND, flags = InjectFlags.Default) {
11046 this.assertNotDestroyed();
11047 // Set the injection context.
11048 const previousInjector = setCurrentInjector(this);
11049 try {
11050 // Check for the SkipSelf flag.
11051 if (!(flags & InjectFlags.SkipSelf)) {
11052 // SkipSelf isn't set, check if the record belongs to this injector.
11053 let record = this.records.get(token);
11054 if (record === undefined) {
11055 // No record, but maybe the token is scoped to this injector. Look for an injectable
11056 // def with a scope matching this injector.
11057 const def = couldBeInjectableType(token) && getInjectableDef(token);
11058 if (def && this.injectableDefInScope(def)) {
11059 // Found an injectable def and it's scoped to this injector. Pretend as if it was here
11060 // all along.
11061 record = makeRecord(injectableDefOrInjectorDefFactory(token), NOT_YET);
11062 }
11063 else {
11064 record = null;
11065 }
11066 this.records.set(token, record);
11067 }
11068 // If a record was found, get the instance for it and return it.
11069 if (record != null /* NOT null || undefined */) {
11070 return this.hydrate(token, record);
11071 }
11072 }
11073 // Select the next injector based on the Self flag - if self is set, the next injector is
11074 // the NullInjector, otherwise it's the parent.
11075 const nextInjector = !(flags & InjectFlags.Self) ? this.parent : getNullInjector();
11076 // Set the notFoundValue based on the Optional flag - if optional is set and notFoundValue
11077 // is undefined, the value is null, otherwise it's the notFoundValue.
11078 notFoundValue = (flags & InjectFlags.Optional) && notFoundValue === THROW_IF_NOT_FOUND ?
11079 null :
11080 notFoundValue;
11081 return nextInjector.get(token, notFoundValue);
11082 }
11083 catch (e) {
11084 if (e.name === 'NullInjectorError') {
11085 const path = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || [];
11086 path.unshift(stringify(token));
11087 if (previousInjector) {
11088 // We still have a parent injector, keep throwing
11089 throw e;
11090 }
11091 else {
11092 // Format & throw the final error message when we don't have any previous injector
11093 return catchInjectorError(e, token, 'R3InjectorError', this.source);
11094 }
11095 }
11096 else {
11097 throw e;
11098 }
11099 }
11100 finally {
11101 // Lastly, clean up the state by restoring the previous injector.
11102 setCurrentInjector(previousInjector);
11103 }
11104 }
11105 /** @internal */
11106 _resolveInjectorDefTypes() {
11107 this.injectorDefTypes.forEach(defType => this.get(defType));
11108 }
11109 toString() {
11110 const tokens = [], records = this.records;
11111 records.forEach((v, token) => tokens.push(stringify(token)));
11112 return `R3Injector[${tokens.join(', ')}]`;
11113 }
11114 assertNotDestroyed() {
11115 if (this._destroyed) {
11116 throw new Error('Injector has already been destroyed.');
11117 }
11118 }
11119 /**
11120 * Add an `InjectorType` or `InjectorTypeWithProviders` and all of its transitive providers
11121 * to this injector.
11122 *
11123 * If an `InjectorTypeWithProviders` that declares providers besides the type is specified,
11124 * the function will return "true" to indicate that the providers of the type definition need
11125 * to be processed. This allows us to process providers of injector types after all imports of
11126 * an injector definition are processed. (following View Engine semantics: see FW-1349)
11127 */
11128 processInjectorType(defOrWrappedDef, parents, dedupStack) {
11129 defOrWrappedDef = resolveForwardRef(defOrWrappedDef);
11130 if (!defOrWrappedDef)
11131 return false;
11132 // Either the defOrWrappedDef is an InjectorType (with injector def) or an
11133 // InjectorDefTypeWithProviders (aka ModuleWithProviders). Detecting either is a megamorphic
11134 // read, so care is taken to only do the read once.
11135 // First attempt to read the injector def (`ɵinj`).
11136 let def = getInjectorDef(defOrWrappedDef);
11137 // If that's not present, then attempt to read ngModule from the InjectorDefTypeWithProviders.
11138 const ngModule = (def == null) && defOrWrappedDef.ngModule || undefined;
11139 // Determine the InjectorType. In the case where `defOrWrappedDef` is an `InjectorType`,
11140 // then this is easy. In the case of an InjectorDefTypeWithProviders, then the definition type
11141 // is the `ngModule`.
11142 const defType = (ngModule === undefined) ? defOrWrappedDef : ngModule;
11143 // Check for circular dependencies.
11144 if (ngDevMode && parents.indexOf(defType) !== -1) {
11145 const defName = stringify(defType);
11146 throw new Error(`Circular dependency in DI detected for type ${defName}. Dependency path: ${parents.map(defType => stringify(defType)).join(' > ')} > ${defName}.`);
11147 }
11148 // Check for multiple imports of the same module
11149 const isDuplicate = dedupStack.indexOf(defType) !== -1;
11150 // Finally, if defOrWrappedType was an `InjectorDefTypeWithProviders`, then the actual
11151 // `InjectorDef` is on its `ngModule`.
11152 if (ngModule !== undefined) {
11153 def = getInjectorDef(ngModule);
11154 }
11155 // If no definition was found, it might be from exports. Remove it.
11156 if (def == null) {
11157 return false;
11158 }
11159 // Add providers in the same way that @NgModule resolution did:
11160 // First, include providers from any imports.
11161 if (def.imports != null && !isDuplicate) {
11162 // Before processing defType's imports, add it to the set of parents. This way, if it ends
11163 // up deeply importing itself, this can be detected.
11164 ngDevMode && parents.push(defType);
11165 // Add it to the set of dedups. This way we can detect multiple imports of the same module
11166 dedupStack.push(defType);
11167 let importTypesWithProviders;
11168 try {
11169 deepForEach(def.imports, imported => {
11170 if (this.processInjectorType(imported, parents, dedupStack)) {
11171 if (importTypesWithProviders === undefined)
11172 importTypesWithProviders = [];
11173 // If the processed import is an injector type with providers, we store it in the
11174 // list of import types with providers, so that we can process those afterwards.
11175 importTypesWithProviders.push(imported);
11176 }
11177 });
11178 }
11179 finally {
11180 // Remove it from the parents set when finished.
11181 ngDevMode && parents.pop();
11182 }
11183 // Imports which are declared with providers (TypeWithProviders) need to be processed
11184 // after all imported modules are processed. This is similar to how View Engine
11185 // processes/merges module imports in the metadata resolver. See: FW-1349.
11186 if (importTypesWithProviders !== undefined) {
11187 for (let i = 0; i < importTypesWithProviders.length; i++) {
11188 const { ngModule, providers } = importTypesWithProviders[i];
11189 deepForEach(providers, provider => this.processProvider(provider, ngModule, providers || EMPTY_ARRAY$2));
11190 }
11191 }
11192 }
11193 // Track the InjectorType and add a provider for it. It's important that this is done after the
11194 // def's imports.
11195 this.injectorDefTypes.add(defType);
11196 this.records.set(defType, makeRecord(def.factory, NOT_YET));
11197 // Next, include providers listed on the definition itself.
11198 const defProviders = def.providers;
11199 if (defProviders != null && !isDuplicate) {
11200 const injectorType = defOrWrappedDef;
11201 deepForEach(defProviders, provider => this.processProvider(provider, injectorType, defProviders));
11202 }
11203 return (ngModule !== undefined &&
11204 defOrWrappedDef.providers !== undefined);
11205 }
11206 /**
11207 * Process a `SingleProvider` and add it.
11208 */
11209 processProvider(provider, ngModuleType, providers) {
11210 // Determine the token from the provider. Either it's its own token, or has a {provide: ...}
11211 // property.
11212 provider = resolveForwardRef(provider);
11213 let token = isTypeProvider(provider) ? provider : resolveForwardRef(provider && provider.provide);
11214 // Construct a `Record` for the provider.
11215 const record = providerToRecord(provider, ngModuleType, providers);
11216 if (!isTypeProvider(provider) && provider.multi === true) {
11217 // If the provider indicates that it's a multi-provider, process it specially.
11218 // First check whether it's been defined already.
11219 let multiRecord = this.records.get(token);
11220 if (multiRecord) {
11221 // It has. Throw a nice error if
11222 if (multiRecord.multi === undefined) {
11223 throwMixedMultiProviderError();
11224 }
11225 }
11226 else {
11227 multiRecord = makeRecord(undefined, NOT_YET, true);
11228 multiRecord.factory = () => injectArgs(multiRecord.multi);
11229 this.records.set(token, multiRecord);
11230 }
11231 token = provider;
11232 multiRecord.multi.push(provider);
11233 }
11234 else {
11235 const existing = this.records.get(token);
11236 if (existing && existing.multi !== undefined) {
11237 throwMixedMultiProviderError();
11238 }
11239 }
11240 this.records.set(token, record);
11241 }
11242 hydrate(token, record) {
11243 if (record.value === CIRCULAR) {
11244 throwCyclicDependencyError(stringify(token));
11245 }
11246 else if (record.value === NOT_YET) {
11247 record.value = CIRCULAR;
11248 record.value = record.factory();
11249 }
11250 if (typeof record.value === 'object' && record.value && hasOnDestroy(record.value)) {
11251 this.onDestroy.add(record.value);
11252 }
11253 return record.value;
11254 }
11255 injectableDefInScope(def) {
11256 if (!def.providedIn) {
11257 return false;
11258 }
11259 else if (typeof def.providedIn === 'string') {
11260 return def.providedIn === 'any' || (def.providedIn === this.scope);
11261 }
11262 else {
11263 return this.injectorDefTypes.has(def.providedIn);
11264 }
11265 }
11266}
11267function injectableDefOrInjectorDefFactory(token) {
11268 // Most tokens will have an injectable def directly on them, which specifies a factory directly.
11269 const injectableDef = getInjectableDef(token);
11270 const factory = injectableDef !== null ? injectableDef.factory : getFactoryDef(token);
11271 if (factory !== null) {
11272 return factory;
11273 }
11274 // If the token is an NgModule, it's also injectable but the factory is on its injector def
11275 // (`ɵinj`)
11276 const injectorDef = getInjectorDef(token);
11277 if (injectorDef !== null) {
11278 return injectorDef.factory;
11279 }
11280 // InjectionTokens should have an injectable def (ɵprov) and thus should be handled above.
11281 // If it's missing that, it's an error.
11282 if (token instanceof InjectionToken) {
11283 throw new Error(`Token ${stringify(token)} is missing a ɵprov definition.`);
11284 }
11285 // Undecorated types can sometimes be created if they have no constructor arguments.
11286 if (token instanceof Function) {
11287 return getUndecoratedInjectableFactory(token);
11288 }
11289 // There was no way to resolve a factory for this token.
11290 throw new Error('unreachable');
11291}
11292function getUndecoratedInjectableFactory(token) {
11293 // If the token has parameters then it has dependencies that we cannot resolve implicitly.
11294 const paramLength = token.length;
11295 if (paramLength > 0) {
11296 const args = newArray(paramLength, '?');
11297 throw new Error(`Can't resolve all parameters for ${stringify(token)}: (${args.join(', ')}).`);
11298 }
11299 // The constructor function appears to have no parameters.
11300 // This might be because it inherits from a super-class. In which case, use an injectable
11301 // def from an ancestor if there is one.
11302 // Otherwise this really is a simple class with no dependencies, so return a factory that
11303 // just instantiates the zero-arg constructor.
11304 const inheritedInjectableDef = getInheritedInjectableDef(token);
11305 if (inheritedInjectableDef !== null) {
11306 return () => inheritedInjectableDef.factory(token);
11307 }
11308 else {
11309 return () => new token();
11310 }
11311}
11312function providerToRecord(provider, ngModuleType, providers) {
11313 if (isValueProvider(provider)) {
11314 return makeRecord(undefined, provider.useValue);
11315 }
11316 else {
11317 const factory = providerToFactory(provider, ngModuleType, providers);
11318 return makeRecord(factory, NOT_YET);
11319 }
11320}
11321/**
11322 * Converts a `SingleProvider` into a factory function.
11323 *
11324 * @param provider provider to convert to factory
11325 */
11326function providerToFactory(provider, ngModuleType, providers) {
11327 let factory = undefined;
11328 if (isTypeProvider(provider)) {
11329 const unwrappedProvider = resolveForwardRef(provider);
11330 return getFactoryDef(unwrappedProvider) || injectableDefOrInjectorDefFactory(unwrappedProvider);
11331 }
11332 else {
11333 if (isValueProvider(provider)) {
11334 factory = () => resolveForwardRef(provider.useValue);
11335 }
11336 else if (isFactoryProvider(provider)) {
11337 factory = () => provider.useFactory(...injectArgs(provider.deps || []));
11338 }
11339 else if (isExistingProvider(provider)) {
11340 factory = () => ɵɵinject(resolveForwardRef(provider.useExisting));
11341 }
11342 else {
11343 const classRef = resolveForwardRef(provider &&
11344 (provider.useClass || provider.provide));
11345 if (!classRef) {
11346 throwInvalidProviderError(ngModuleType, providers, provider);
11347 }
11348 if (hasDeps(provider)) {
11349 factory = () => new (classRef)(...injectArgs(provider.deps));
11350 }
11351 else {
11352 return getFactoryDef(classRef) || injectableDefOrInjectorDefFactory(classRef);
11353 }
11354 }
11355 }
11356 return factory;
11357}
11358function makeRecord(factory, value, multi = false) {
11359 return {
11360 factory: factory,
11361 value: value,
11362 multi: multi ? [] : undefined,
11363 };
11364}
11365function isValueProvider(value) {
11366 return value !== null && typeof value == 'object' && USE_VALUE in value;
11367}
11368function isExistingProvider(value) {
11369 return !!(value && value.useExisting);
11370}
11371function isFactoryProvider(value) {
11372 return !!(value && value.useFactory);
11373}
11374function isTypeProvider(value) {
11375 return typeof value === 'function';
11376}
11377function isClassProvider(value) {
11378 return !!value.useClass;
11379}
11380function hasDeps(value) {
11381 return !!value.deps;
11382}
11383function hasOnDestroy(value) {
11384 return value !== null && typeof value === 'object' &&
11385 typeof value.ngOnDestroy === 'function';
11386}
11387function couldBeInjectableType(value) {
11388 return (typeof value === 'function') ||
11389 (typeof value === 'object' && value instanceof InjectionToken);
11390}
11391
11392/**
11393 * @license
11394 * Copyright Google LLC All Rights Reserved.
11395 *
11396 * Use of this source code is governed by an MIT-style license that can be
11397 * found in the LICENSE file at https://angular.io/license
11398 */
11399function INJECTOR_IMPL__PRE_R3__(providers, parent, name) {
11400 return new StaticInjector(providers, parent, name);
11401}
11402function INJECTOR_IMPL__POST_R3__(providers, parent, name) {
11403 return createInjector({ name: name }, parent, providers, name);
11404}
11405const INJECTOR_IMPL = INJECTOR_IMPL__PRE_R3__;
11406/**
11407 * Concrete injectors implement this interface. Injectors are configured
11408 * with [providers](guide/glossary#provider) that associate
11409 * dependencies of various types with [injection tokens](guide/glossary#di-token).
11410 *
11411 * @see ["DI Providers"](guide/dependency-injection-providers).
11412 * @see `StaticProvider`
11413 *
11414 * @usageNotes
11415 *
11416 * The following example creates a service injector instance.
11417 *
11418 * {@example core/di/ts/provider_spec.ts region='ConstructorProvider'}
11419 *
11420 * ### Usage example
11421 *
11422 * {@example core/di/ts/injector_spec.ts region='Injector'}
11423 *
11424 * `Injector` returns itself when given `Injector` as a token:
11425 *
11426 * {@example core/di/ts/injector_spec.ts region='injectInjector'}
11427 *
11428 * @publicApi
11429 */
11430class Injector {
11431 static create(options, parent) {
11432 if (Array.isArray(options)) {
11433 return INJECTOR_IMPL(options, parent, '');
11434 }
11435 else {
11436 return INJECTOR_IMPL(options.providers, options.parent, options.name || '');
11437 }
11438 }
11439}
11440Injector.THROW_IF_NOT_FOUND = THROW_IF_NOT_FOUND;
11441Injector.NULL = new NullInjector();
11442/** @nocollapse */
11443Injector.ɵprov = ɵɵdefineInjectable({
11444 token: Injector,
11445 providedIn: 'any',
11446 factory: () => ɵɵinject(INJECTOR),
11447});
11448/**
11449 * @internal
11450 * @nocollapse
11451 */
11452Injector.__NG_ELEMENT_ID__ = -1;
11453const IDENT = function (value) {
11454 return value;
11455};
11456const ɵ0$9 = IDENT;
11457const EMPTY = [];
11458const CIRCULAR$1 = IDENT;
11459const MULTI_PROVIDER_FN = function () {
11460 return Array.prototype.slice.call(arguments);
11461};
11462const ɵ1$1 = MULTI_PROVIDER_FN;
11463const NO_NEW_LINE$1 = 'ɵ';
11464class StaticInjector {
11465 constructor(providers, parent = Injector.NULL, source = null) {
11466 this.parent = parent;
11467 this.source = source;
11468 const records = this._records = new Map();
11469 records.set(Injector, { token: Injector, fn: IDENT, deps: EMPTY, value: this, useNew: false });
11470 records.set(INJECTOR, { token: INJECTOR, fn: IDENT, deps: EMPTY, value: this, useNew: false });
11471 this.scope = recursivelyProcessProviders(records, providers);
11472 }
11473 get(token, notFoundValue, flags = InjectFlags.Default) {
11474 const records = this._records;
11475 let record = records.get(token);
11476 if (record === undefined) {
11477 // This means we have never seen this record, see if it is tree shakable provider.
11478 const injectableDef = getInjectableDef(token);
11479 if (injectableDef) {
11480 const providedIn = injectableDef && injectableDef.providedIn;
11481 if (providedIn === 'any' || providedIn != null && providedIn === this.scope) {
11482 records.set(token, record = resolveProvider({ provide: token, useFactory: injectableDef.factory, deps: EMPTY }));
11483 }
11484 }
11485 if (record === undefined) {
11486 // Set record to null to make sure that we don't go through expensive lookup above again.
11487 records.set(token, null);
11488 }
11489 }
11490 let lastInjector = setCurrentInjector(this);
11491 try {
11492 return tryResolveToken(token, record, records, this.parent, notFoundValue, flags);
11493 }
11494 catch (e) {
11495 return catchInjectorError(e, token, 'StaticInjectorError', this.source);
11496 }
11497 finally {
11498 setCurrentInjector(lastInjector);
11499 }
11500 }
11501 toString() {
11502 const tokens = [], records = this._records;
11503 records.forEach((v, token) => tokens.push(stringify(token)));
11504 return `StaticInjector[${tokens.join(', ')}]`;
11505 }
11506}
11507function resolveProvider(provider) {
11508 const deps = computeDeps(provider);
11509 let fn = IDENT;
11510 let value = EMPTY;
11511 let useNew = false;
11512 let provide = resolveForwardRef(provider.provide);
11513 if (USE_VALUE in provider) {
11514 // We need to use USE_VALUE in provider since provider.useValue could be defined as undefined.
11515 value = provider.useValue;
11516 }
11517 else if (provider.useFactory) {
11518 fn = provider.useFactory;
11519 }
11520 else if (provider.useExisting) {
11521 // Just use IDENT
11522 }
11523 else if (provider.useClass) {
11524 useNew = true;
11525 fn = resolveForwardRef(provider.useClass);
11526 }
11527 else if (typeof provide == 'function') {
11528 useNew = true;
11529 fn = provide;
11530 }
11531 else {
11532 throw staticError('StaticProvider does not have [useValue|useFactory|useExisting|useClass] or [provide] is not newable', provider);
11533 }
11534 return { deps, fn, useNew, value };
11535}
11536function multiProviderMixError(token) {
11537 return staticError('Cannot mix multi providers and regular providers', token);
11538}
11539function recursivelyProcessProviders(records, provider) {
11540 let scope = null;
11541 if (provider) {
11542 provider = resolveForwardRef(provider);
11543 if (Array.isArray(provider)) {
11544 // if we have an array recurse into the array
11545 for (let i = 0; i < provider.length; i++) {
11546 scope = recursivelyProcessProviders(records, provider[i]) || scope;
11547 }
11548 }
11549 else if (typeof provider === 'function') {
11550 // Functions were supported in ReflectiveInjector, but are not here. For safety give useful
11551 // error messages
11552 throw staticError('Function/Class not supported', provider);
11553 }
11554 else if (provider && typeof provider === 'object' && provider.provide) {
11555 // At this point we have what looks like a provider: {provide: ?, ....}
11556 let token = resolveForwardRef(provider.provide);
11557 const resolvedProvider = resolveProvider(provider);
11558 if (provider.multi === true) {
11559 // This is a multi provider.
11560 let multiProvider = records.get(token);
11561 if (multiProvider) {
11562 if (multiProvider.fn !== MULTI_PROVIDER_FN) {
11563 throw multiProviderMixError(token);
11564 }
11565 }
11566 else {
11567 // Create a placeholder factory which will look up the constituents of the multi provider.
11568 records.set(token, multiProvider = {
11569 token: provider.provide,
11570 deps: [],
11571 useNew: false,
11572 fn: MULTI_PROVIDER_FN,
11573 value: EMPTY
11574 });
11575 }
11576 // Treat the provider as the token.
11577 token = provider;
11578 multiProvider.deps.push({ token, options: 6 /* Default */ });
11579 }
11580 const record = records.get(token);
11581 if (record && record.fn == MULTI_PROVIDER_FN) {
11582 throw multiProviderMixError(token);
11583 }
11584 if (token === INJECTOR_SCOPE) {
11585 scope = resolvedProvider.value;
11586 }
11587 records.set(token, resolvedProvider);
11588 }
11589 else {
11590 throw staticError('Unexpected provider', provider);
11591 }
11592 }
11593 return scope;
11594}
11595function tryResolveToken(token, record, records, parent, notFoundValue, flags) {
11596 try {
11597 return resolveToken(token, record, records, parent, notFoundValue, flags);
11598 }
11599 catch (e) {
11600 // ensure that 'e' is of type Error.
11601 if (!(e instanceof Error)) {
11602 e = new Error(e);
11603 }
11604 const path = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || [];
11605 path.unshift(token);
11606 if (record && record.value == CIRCULAR$1) {
11607 // Reset the Circular flag.
11608 record.value = EMPTY;
11609 }
11610 throw e;
11611 }
11612}
11613function resolveToken(token, record, records, parent, notFoundValue, flags) {
11614 let value;
11615 if (record && !(flags & InjectFlags.SkipSelf)) {
11616 // If we don't have a record, this implies that we don't own the provider hence don't know how
11617 // to resolve it.
11618 value = record.value;
11619 if (value == CIRCULAR$1) {
11620 throw Error(NO_NEW_LINE$1 + 'Circular dependency');
11621 }
11622 else if (value === EMPTY) {
11623 record.value = CIRCULAR$1;
11624 let obj = undefined;
11625 let useNew = record.useNew;
11626 let fn = record.fn;
11627 let depRecords = record.deps;
11628 let deps = EMPTY;
11629 if (depRecords.length) {
11630 deps = [];
11631 for (let i = 0; i < depRecords.length; i++) {
11632 const depRecord = depRecords[i];
11633 const options = depRecord.options;
11634 const childRecord = options & 2 /* CheckSelf */ ? records.get(depRecord.token) : undefined;
11635 deps.push(tryResolveToken(
11636 // Current Token to resolve
11637 depRecord.token,
11638 // A record which describes how to resolve the token.
11639 // If undefined, this means we don't have such a record
11640 childRecord,
11641 // Other records we know about.
11642 records,
11643 // If we don't know how to resolve dependency and we should not check parent for it,
11644 // than pass in Null injector.
11645 !childRecord && !(options & 4 /* CheckParent */) ? Injector.NULL : parent, options & 1 /* Optional */ ? null : Injector.THROW_IF_NOT_FOUND, InjectFlags.Default));
11646 }
11647 }
11648 record.value = value = useNew ? new fn(...deps) : fn.apply(obj, deps);
11649 }
11650 }
11651 else if (!(flags & InjectFlags.Self)) {
11652 value = parent.get(token, notFoundValue, InjectFlags.Default);
11653 }
11654 else if (!(flags & InjectFlags.Optional)) {
11655 value = Injector.NULL.get(token, notFoundValue);
11656 }
11657 else {
11658 value = Injector.NULL.get(token, typeof notFoundValue !== 'undefined' ? notFoundValue : null);
11659 }
11660 return value;
11661}
11662function computeDeps(provider) {
11663 let deps = EMPTY;
11664 const providerDeps = provider.deps;
11665 if (providerDeps && providerDeps.length) {
11666 deps = [];
11667 for (let i = 0; i < providerDeps.length; i++) {
11668 let options = 6 /* Default */;
11669 let token = resolveForwardRef(providerDeps[i]);
11670 if (Array.isArray(token)) {
11671 for (let j = 0, annotations = token; j < annotations.length; j++) {
11672 const annotation = annotations[j];
11673 if (annotation instanceof Optional || annotation == Optional) {
11674 options = options | 1 /* Optional */;
11675 }
11676 else if (annotation instanceof SkipSelf || annotation == SkipSelf) {
11677 options = options & ~2 /* CheckSelf */;
11678 }
11679 else if (annotation instanceof Self || annotation == Self) {
11680 options = options & ~4 /* CheckParent */;
11681 }
11682 else if (annotation instanceof Inject) {
11683 token = annotation.token;
11684 }
11685 else {
11686 token = resolveForwardRef(annotation);
11687 }
11688 }
11689 }
11690 deps.push({ token, options });
11691 }
11692 }
11693 else if (provider.useExisting) {
11694 const token = resolveForwardRef(provider.useExisting);
11695 deps = [{ token, options: 6 /* Default */ }];
11696 }
11697 else if (!providerDeps && !(USE_VALUE in provider)) {
11698 // useValue & useExisting are the only ones which are exempt from deps all others need it.
11699 throw staticError('\'deps\' required', provider);
11700 }
11701 return deps;
11702}
11703function staticError(text, obj) {
11704 return new Error(formatError(text, obj, 'StaticInjectorError'));
11705}
11706
11707/**
11708 * @license
11709 * Copyright Google LLC All Rights Reserved.
11710 *
11711 * Use of this source code is governed by an MIT-style license that can be
11712 * found in the LICENSE file at https://angular.io/license
11713 */
11714function findFirstClosedCycle(keys) {
11715 const res = [];
11716 for (let i = 0; i < keys.length; ++i) {
11717 if (res.indexOf(keys[i]) > -1) {
11718 res.push(keys[i]);
11719 return res;
11720 }
11721 res.push(keys[i]);
11722 }
11723 return res;
11724}
11725function constructResolvingPath(keys) {
11726 if (keys.length > 1) {
11727 const reversed = findFirstClosedCycle(keys.slice().reverse());
11728 const tokenStrs = reversed.map(k => stringify(k.token));
11729 return ' (' + tokenStrs.join(' -> ') + ')';
11730 }
11731 return '';
11732}
11733function injectionError(injector, key, constructResolvingMessage, originalError) {
11734 const keys = [key];
11735 const errMsg = constructResolvingMessage(keys);
11736 const error = (originalError ? wrappedError(errMsg, originalError) : Error(errMsg));
11737 error.addKey = addKey;
11738 error.keys = keys;
11739 error.injectors = [injector];
11740 error.constructResolvingMessage = constructResolvingMessage;
11741 error[ERROR_ORIGINAL_ERROR] = originalError;
11742 return error;
11743}
11744function addKey(injector, key) {
11745 this.injectors.push(injector);
11746 this.keys.push(key);
11747 // Note: This updated message won't be reflected in the `.stack` property
11748 this.message = this.constructResolvingMessage(this.keys);
11749}
11750/**
11751 * Thrown when trying to retrieve a dependency by key from {@link Injector}, but the
11752 * {@link Injector} does not have a {@link Provider} for the given key.
11753 *
11754 * @usageNotes
11755 * ### Example
11756 *
11757 * ```typescript
11758 * class A {
11759 * constructor(b:B) {}
11760 * }
11761 *
11762 * expect(() => Injector.resolveAndCreate([A])).toThrowError();
11763 * ```
11764 */
11765function noProviderError(injector, key) {
11766 return injectionError(injector, key, function (keys) {
11767 const first = stringify(keys[0].token);
11768 return `No provider for ${first}!${constructResolvingPath(keys)}`;
11769 });
11770}
11771/**
11772 * Thrown when dependencies form a cycle.
11773 *
11774 * @usageNotes
11775 * ### Example
11776 *
11777 * ```typescript
11778 * var injector = Injector.resolveAndCreate([
11779 * {provide: "one", useFactory: (two) => "two", deps: [[new Inject("two")]]},
11780 * {provide: "two", useFactory: (one) => "one", deps: [[new Inject("one")]]}
11781 * ]);
11782 *
11783 * expect(() => injector.get("one")).toThrowError();
11784 * ```
11785 *
11786 * Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
11787 */
11788function cyclicDependencyError(injector, key) {
11789 return injectionError(injector, key, function (keys) {
11790 return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`;
11791 });
11792}
11793/**
11794 * Thrown when a constructing type returns with an Error.
11795 *
11796 * The `InstantiationError` class contains the original error plus the dependency graph which caused
11797 * this object to be instantiated.
11798 *
11799 * @usageNotes
11800 * ### Example
11801 *
11802 * ```typescript
11803 * class A {
11804 * constructor() {
11805 * throw new Error('message');
11806 * }
11807 * }
11808 *
11809 * var injector = Injector.resolveAndCreate([A]);
11810
11811 * try {
11812 * injector.get(A);
11813 * } catch (e) {
11814 * expect(e instanceof InstantiationError).toBe(true);
11815 * expect(e.originalException.message).toEqual("message");
11816 * expect(e.originalStack).toBeDefined();
11817 * }
11818 * ```
11819 */
11820function instantiationError(injector, originalException, originalStack, key) {
11821 return injectionError(injector, key, function (keys) {
11822 const first = stringify(keys[0].token);
11823 return `${originalException.message}: Error during instantiation of ${first}!${constructResolvingPath(keys)}.`;
11824 }, originalException);
11825}
11826/**
11827 * Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector}
11828 * creation.
11829 *
11830 * @usageNotes
11831 * ### Example
11832 *
11833 * ```typescript
11834 * expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
11835 * ```
11836 */
11837function invalidProviderError(provider) {
11838 return Error(`Invalid provider - only instances of Provider and Type are allowed, got: ${provider}`);
11839}
11840/**
11841 * Thrown when the class has no annotation information.
11842 *
11843 * Lack of annotation information prevents the {@link Injector} from determining which dependencies
11844 * need to be injected into the constructor.
11845 *
11846 * @usageNotes
11847 * ### Example
11848 *
11849 * ```typescript
11850 * class A {
11851 * constructor(b) {}
11852 * }
11853 *
11854 * expect(() => Injector.resolveAndCreate([A])).toThrowError();
11855 * ```
11856 *
11857 * This error is also thrown when the class not marked with {@link Injectable} has parameter types.
11858 *
11859 * ```typescript
11860 * class B {}
11861 *
11862 * class A {
11863 * constructor(b:B) {} // no information about the parameter types of A is available at runtime.
11864 * }
11865 *
11866 * expect(() => Injector.resolveAndCreate([A,B])).toThrowError();
11867 * ```
11868 *
11869 */
11870function noAnnotationError(typeOrFunc, params) {
11871 const signature = [];
11872 for (let i = 0, ii = params.length; i < ii; i++) {
11873 const parameter = params[i];
11874 if (!parameter || parameter.length == 0) {
11875 signature.push('?');
11876 }
11877 else {
11878 signature.push(parameter.map(stringify).join(' '));
11879 }
11880 }
11881 return Error('Cannot resolve all parameters for \'' + stringify(typeOrFunc) + '\'(' +
11882 signature.join(', ') + '). ' +
11883 'Make sure that all the parameters are decorated with Inject or have valid type annotations and that \'' +
11884 stringify(typeOrFunc) + '\' is decorated with Injectable.');
11885}
11886/**
11887 * Thrown when getting an object by index.
11888 *
11889 * @usageNotes
11890 * ### Example
11891 *
11892 * ```typescript
11893 * class A {}
11894 *
11895 * var injector = Injector.resolveAndCreate([A]);
11896 *
11897 * expect(() => injector.getAt(100)).toThrowError();
11898 * ```
11899 *
11900 */
11901function outOfBoundsError(index) {
11902 return Error(`Index ${index} is out-of-bounds.`);
11903}
11904// TODO: add a working example after alpha38 is released
11905/**
11906 * Thrown when a multi provider and a regular provider are bound to the same token.
11907 *
11908 * @usageNotes
11909 * ### Example
11910 *
11911 * ```typescript
11912 * expect(() => Injector.resolveAndCreate([
11913 * { provide: "Strings", useValue: "string1", multi: true},
11914 * { provide: "Strings", useValue: "string2", multi: false}
11915 * ])).toThrowError();
11916 * ```
11917 */
11918function mixingMultiProvidersWithRegularProvidersError(provider1, provider2) {
11919 return Error(`Cannot mix multi providers and regular providers, got: ${provider1} ${provider2}`);
11920}
11921
11922/**
11923 * @license
11924 * Copyright Google LLC All Rights Reserved.
11925 *
11926 * Use of this source code is governed by an MIT-style license that can be
11927 * found in the LICENSE file at https://angular.io/license
11928 */
11929/**
11930 * A unique object used for retrieving items from the {@link ReflectiveInjector}.
11931 *
11932 * Keys have:
11933 * - a system-wide unique `id`.
11934 * - a `token`.
11935 *
11936 * `Key` is used internally by {@link ReflectiveInjector} because its system-wide unique `id` allows
11937 * the
11938 * injector to store created objects in a more efficient way.
11939 *
11940 * `Key` should not be created directly. {@link ReflectiveInjector} creates keys automatically when
11941 * resolving
11942 * providers.
11943 *
11944 * @deprecated No replacement
11945 * @publicApi
11946 */
11947class ReflectiveKey {
11948 /**
11949 * Private
11950 */
11951 constructor(token, id) {
11952 this.token = token;
11953 this.id = id;
11954 if (!token) {
11955 throw new Error('Token must be defined!');
11956 }
11957 this.displayName = stringify(this.token);
11958 }
11959 /**
11960 * Retrieves a `Key` for a token.
11961 */
11962 static get(token) {
11963 return _globalKeyRegistry.get(resolveForwardRef(token));
11964 }
11965 /**
11966 * @returns the number of keys registered in the system.
11967 */
11968 static get numberOfKeys() {
11969 return _globalKeyRegistry.numberOfKeys;
11970 }
11971}
11972class KeyRegistry {
11973 constructor() {
11974 this._allKeys = new Map();
11975 }
11976 get(token) {
11977 if (token instanceof ReflectiveKey)
11978 return token;
11979 if (this._allKeys.has(token)) {
11980 return this._allKeys.get(token);
11981 }
11982 const newKey = new ReflectiveKey(token, ReflectiveKey.numberOfKeys);
11983 this._allKeys.set(token, newKey);
11984 return newKey;
11985 }
11986 get numberOfKeys() {
11987 return this._allKeys.size;
11988 }
11989}
11990const _globalKeyRegistry = new KeyRegistry();
11991
11992/**
11993 * @license
11994 * Copyright Google LLC All Rights Reserved.
11995 *
11996 * Use of this source code is governed by an MIT-style license that can be
11997 * found in the LICENSE file at https://angular.io/license
11998 */
11999/**
12000 * Provides access to reflection data about symbols. Used internally by Angular
12001 * to power dependency injection and compilation.
12002 */
12003class Reflector {
12004 constructor(reflectionCapabilities) {
12005 this.reflectionCapabilities = reflectionCapabilities;
12006 }
12007 updateCapabilities(caps) {
12008 this.reflectionCapabilities = caps;
12009 }
12010 factory(type) {
12011 return this.reflectionCapabilities.factory(type);
12012 }
12013 parameters(typeOrFunc) {
12014 return this.reflectionCapabilities.parameters(typeOrFunc);
12015 }
12016 annotations(typeOrFunc) {
12017 return this.reflectionCapabilities.annotations(typeOrFunc);
12018 }
12019 propMetadata(typeOrFunc) {
12020 return this.reflectionCapabilities.propMetadata(typeOrFunc);
12021 }
12022 hasLifecycleHook(type, lcProperty) {
12023 return this.reflectionCapabilities.hasLifecycleHook(type, lcProperty);
12024 }
12025 getter(name) {
12026 return this.reflectionCapabilities.getter(name);
12027 }
12028 setter(name) {
12029 return this.reflectionCapabilities.setter(name);
12030 }
12031 method(name) {
12032 return this.reflectionCapabilities.method(name);
12033 }
12034 importUri(type) {
12035 return this.reflectionCapabilities.importUri(type);
12036 }
12037 resourceUri(type) {
12038 return this.reflectionCapabilities.resourceUri(type);
12039 }
12040 resolveIdentifier(name, moduleUrl, members, runtime) {
12041 return this.reflectionCapabilities.resolveIdentifier(name, moduleUrl, members, runtime);
12042 }
12043 resolveEnum(identifier, name) {
12044 return this.reflectionCapabilities.resolveEnum(identifier, name);
12045 }
12046}
12047
12048/**
12049 * @license
12050 * Copyright Google LLC All Rights Reserved.
12051 *
12052 * Use of this source code is governed by an MIT-style license that can be
12053 * found in the LICENSE file at https://angular.io/license
12054 */
12055/**
12056 * The {@link Reflector} used internally in Angular to access metadata
12057 * about symbols.
12058 */
12059const reflector = new Reflector(new ReflectionCapabilities());
12060
12061/**
12062 * @license
12063 * Copyright Google LLC All Rights Reserved.
12064 *
12065 * Use of this source code is governed by an MIT-style license that can be
12066 * found in the LICENSE file at https://angular.io/license
12067 */
12068/**
12069 * `Dependency` is used by the framework to extend DI.
12070 * This is internal to Angular and should not be used directly.
12071 */
12072class ReflectiveDependency {
12073 constructor(key, optional, visibility) {
12074 this.key = key;
12075 this.optional = optional;
12076 this.visibility = visibility;
12077 }
12078 static fromKey(key) {
12079 return new ReflectiveDependency(key, false, null);
12080 }
12081}
12082const _EMPTY_LIST = [];
12083class ResolvedReflectiveProvider_ {
12084 constructor(key, resolvedFactories, multiProvider) {
12085 this.key = key;
12086 this.resolvedFactories = resolvedFactories;
12087 this.multiProvider = multiProvider;
12088 this.resolvedFactory = this.resolvedFactories[0];
12089 }
12090}
12091/**
12092 * An internal resolved representation of a factory function created by resolving `Provider`.
12093 * @publicApi
12094 */
12095class ResolvedReflectiveFactory {
12096 constructor(
12097 /**
12098 * Factory function which can return an instance of an object represented by a key.
12099 */
12100 factory,
12101 /**
12102 * Arguments (dependencies) to the `factory` function.
12103 */
12104 dependencies) {
12105 this.factory = factory;
12106 this.dependencies = dependencies;
12107 }
12108}
12109/**
12110 * Resolve a single provider.
12111 */
12112function resolveReflectiveFactory(provider) {
12113 let factoryFn;
12114 let resolvedDeps;
12115 if (provider.useClass) {
12116 const useClass = resolveForwardRef(provider.useClass);
12117 factoryFn = reflector.factory(useClass);
12118 resolvedDeps = _dependenciesFor(useClass);
12119 }
12120 else if (provider.useExisting) {
12121 factoryFn = (aliasInstance) => aliasInstance;
12122 resolvedDeps = [ReflectiveDependency.fromKey(ReflectiveKey.get(provider.useExisting))];
12123 }
12124 else if (provider.useFactory) {
12125 factoryFn = provider.useFactory;
12126 resolvedDeps = constructDependencies(provider.useFactory, provider.deps);
12127 }
12128 else {
12129 factoryFn = () => provider.useValue;
12130 resolvedDeps = _EMPTY_LIST;
12131 }
12132 return new ResolvedReflectiveFactory(factoryFn, resolvedDeps);
12133}
12134/**
12135 * Converts the `Provider` into `ResolvedProvider`.
12136 *
12137 * `Injector` internally only uses `ResolvedProvider`, `Provider` contains convenience provider
12138 * syntax.
12139 */
12140function resolveReflectiveProvider(provider) {
12141 return new ResolvedReflectiveProvider_(ReflectiveKey.get(provider.provide), [resolveReflectiveFactory(provider)], provider.multi || false);
12142}
12143/**
12144 * Resolve a list of Providers.
12145 */
12146function resolveReflectiveProviders(providers) {
12147 const normalized = _normalizeProviders(providers, []);
12148 const resolved = normalized.map(resolveReflectiveProvider);
12149 const resolvedProviderMap = mergeResolvedReflectiveProviders(resolved, new Map());
12150 return Array.from(resolvedProviderMap.values());
12151}
12152/**
12153 * Merges a list of ResolvedProviders into a list where each key is contained exactly once and
12154 * multi providers have been merged.
12155 */
12156function mergeResolvedReflectiveProviders(providers, normalizedProvidersMap) {
12157 for (let i = 0; i < providers.length; i++) {
12158 const provider = providers[i];
12159 const existing = normalizedProvidersMap.get(provider.key.id);
12160 if (existing) {
12161 if (provider.multiProvider !== existing.multiProvider) {
12162 throw mixingMultiProvidersWithRegularProvidersError(existing, provider);
12163 }
12164 if (provider.multiProvider) {
12165 for (let j = 0; j < provider.resolvedFactories.length; j++) {
12166 existing.resolvedFactories.push(provider.resolvedFactories[j]);
12167 }
12168 }
12169 else {
12170 normalizedProvidersMap.set(provider.key.id, provider);
12171 }
12172 }
12173 else {
12174 let resolvedProvider;
12175 if (provider.multiProvider) {
12176 resolvedProvider = new ResolvedReflectiveProvider_(provider.key, provider.resolvedFactories.slice(), provider.multiProvider);
12177 }
12178 else {
12179 resolvedProvider = provider;
12180 }
12181 normalizedProvidersMap.set(provider.key.id, resolvedProvider);
12182 }
12183 }
12184 return normalizedProvidersMap;
12185}
12186function _normalizeProviders(providers, res) {
12187 providers.forEach(b => {
12188 if (b instanceof Type) {
12189 res.push({ provide: b, useClass: b });
12190 }
12191 else if (b && typeof b == 'object' && b.provide !== undefined) {
12192 res.push(b);
12193 }
12194 else if (Array.isArray(b)) {
12195 _normalizeProviders(b, res);
12196 }
12197 else {
12198 throw invalidProviderError(b);
12199 }
12200 });
12201 return res;
12202}
12203function constructDependencies(typeOrFunc, dependencies) {
12204 if (!dependencies) {
12205 return _dependenciesFor(typeOrFunc);
12206 }
12207 else {
12208 const params = dependencies.map(t => [t]);
12209 return dependencies.map(t => _extractToken(typeOrFunc, t, params));
12210 }
12211}
12212function _dependenciesFor(typeOrFunc) {
12213 const params = reflector.parameters(typeOrFunc);
12214 if (!params)
12215 return [];
12216 if (params.some(p => p == null)) {
12217 throw noAnnotationError(typeOrFunc, params);
12218 }
12219 return params.map(p => _extractToken(typeOrFunc, p, params));
12220}
12221function _extractToken(typeOrFunc, metadata, params) {
12222 let token = null;
12223 let optional = false;
12224 if (!Array.isArray(metadata)) {
12225 if (metadata instanceof Inject) {
12226 return _createDependency(metadata.token, optional, null);
12227 }
12228 else {
12229 return _createDependency(metadata, optional, null);
12230 }
12231 }
12232 let visibility = null;
12233 for (let i = 0; i < metadata.length; ++i) {
12234 const paramMetadata = metadata[i];
12235 if (paramMetadata instanceof Type) {
12236 token = paramMetadata;
12237 }
12238 else if (paramMetadata instanceof Inject) {
12239 token = paramMetadata.token;
12240 }
12241 else if (paramMetadata instanceof Optional) {
12242 optional = true;
12243 }
12244 else if (paramMetadata instanceof Self || paramMetadata instanceof SkipSelf) {
12245 visibility = paramMetadata;
12246 }
12247 else if (paramMetadata instanceof InjectionToken) {
12248 token = paramMetadata;
12249 }
12250 }
12251 token = resolveForwardRef(token);
12252 if (token != null) {
12253 return _createDependency(token, optional, visibility);
12254 }
12255 else {
12256 throw noAnnotationError(typeOrFunc, params);
12257 }
12258}
12259function _createDependency(token, optional, visibility) {
12260 return new ReflectiveDependency(ReflectiveKey.get(token), optional, visibility);
12261}
12262
12263/**
12264 * @license
12265 * Copyright Google LLC All Rights Reserved.
12266 *
12267 * Use of this source code is governed by an MIT-style license that can be
12268 * found in the LICENSE file at https://angular.io/license
12269 */
12270// Threshold for the dynamic version
12271const UNDEFINED = {};
12272/**
12273 * A ReflectiveDependency injection container used for instantiating objects and resolving
12274 * dependencies.
12275 *
12276 * An `Injector` is a replacement for a `new` operator, which can automatically resolve the
12277 * constructor dependencies.
12278 *
12279 * In typical use, application code asks for the dependencies in the constructor and they are
12280 * resolved by the `Injector`.
12281 *
12282 * @usageNotes
12283 * ### Example
12284 *
12285 * The following example creates an `Injector` configured to create `Engine` and `Car`.
12286 *
12287 * ```typescript
12288 * @Injectable()
12289 * class Engine {
12290 * }
12291 *
12292 * @Injectable()
12293 * class Car {
12294 * constructor(public engine:Engine) {}
12295 * }
12296 *
12297 * var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
12298 * var car = injector.get(Car);
12299 * expect(car instanceof Car).toBe(true);
12300 * expect(car.engine instanceof Engine).toBe(true);
12301 * ```
12302 *
12303 * Notice, we don't use the `new` operator because we explicitly want to have the `Injector`
12304 * resolve all of the object's dependencies automatically.
12305 *
12306 * @deprecated from v5 - slow and brings in a lot of code, Use `Injector.create` instead.
12307 * @publicApi
12308 */
12309class ReflectiveInjector {
12310 /**
12311 * Turns an array of provider definitions into an array of resolved providers.
12312 *
12313 * A resolution is a process of flattening multiple nested arrays and converting individual
12314 * providers into an array of `ResolvedReflectiveProvider`s.
12315 *
12316 * @usageNotes
12317 * ### Example
12318 *
12319 * ```typescript
12320 * @Injectable()
12321 * class Engine {
12322 * }
12323 *
12324 * @Injectable()
12325 * class Car {
12326 * constructor(public engine:Engine) {}
12327 * }
12328 *
12329 * var providers = ReflectiveInjector.resolve([Car, [[Engine]]]);
12330 *
12331 * expect(providers.length).toEqual(2);
12332 *
12333 * expect(providers[0] instanceof ResolvedReflectiveProvider).toBe(true);
12334 * expect(providers[0].key.displayName).toBe("Car");
12335 * expect(providers[0].dependencies.length).toEqual(1);
12336 * expect(providers[0].factory).toBeDefined();
12337 *
12338 * expect(providers[1].key.displayName).toBe("Engine");
12339 * });
12340 * ```
12341 *
12342 */
12343 static resolve(providers) {
12344 return resolveReflectiveProviders(providers);
12345 }
12346 /**
12347 * Resolves an array of providers and creates an injector from those providers.
12348 *
12349 * The passed-in providers can be an array of `Type`, `Provider`,
12350 * or a recursive array of more providers.
12351 *
12352 * @usageNotes
12353 * ### Example
12354 *
12355 * ```typescript
12356 * @Injectable()
12357 * class Engine {
12358 * }
12359 *
12360 * @Injectable()
12361 * class Car {
12362 * constructor(public engine:Engine) {}
12363 * }
12364 *
12365 * var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
12366 * expect(injector.get(Car) instanceof Car).toBe(true);
12367 * ```
12368 */
12369 static resolveAndCreate(providers, parent) {
12370 const ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
12371 return ReflectiveInjector.fromResolvedProviders(ResolvedReflectiveProviders, parent);
12372 }
12373 /**
12374 * Creates an injector from previously resolved providers.
12375 *
12376 * This API is the recommended way to construct injectors in performance-sensitive parts.
12377 *
12378 * @usageNotes
12379 * ### Example
12380 *
12381 * ```typescript
12382 * @Injectable()
12383 * class Engine {
12384 * }
12385 *
12386 * @Injectable()
12387 * class Car {
12388 * constructor(public engine:Engine) {}
12389 * }
12390 *
12391 * var providers = ReflectiveInjector.resolve([Car, Engine]);
12392 * var injector = ReflectiveInjector.fromResolvedProviders(providers);
12393 * expect(injector.get(Car) instanceof Car).toBe(true);
12394 * ```
12395 */
12396 static fromResolvedProviders(providers, parent) {
12397 return new ReflectiveInjector_(providers, parent);
12398 }
12399}
12400class ReflectiveInjector_ {
12401 /**
12402 * Private
12403 */
12404 constructor(_providers, _parent) {
12405 /** @internal */
12406 this._constructionCounter = 0;
12407 this._providers = _providers;
12408 this.parent = _parent || null;
12409 const len = _providers.length;
12410 this.keyIds = [];
12411 this.objs = [];
12412 for (let i = 0; i < len; i++) {
12413 this.keyIds[i] = _providers[i].key.id;
12414 this.objs[i] = UNDEFINED;
12415 }
12416 }
12417 get(token, notFoundValue = THROW_IF_NOT_FOUND) {
12418 return this._getByKey(ReflectiveKey.get(token), null, notFoundValue);
12419 }
12420 resolveAndCreateChild(providers) {
12421 const ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
12422 return this.createChildFromResolved(ResolvedReflectiveProviders);
12423 }
12424 createChildFromResolved(providers) {
12425 const inj = new ReflectiveInjector_(providers);
12426 inj.parent = this;
12427 return inj;
12428 }
12429 resolveAndInstantiate(provider) {
12430 return this.instantiateResolved(ReflectiveInjector.resolve([provider])[0]);
12431 }
12432 instantiateResolved(provider) {
12433 return this._instantiateProvider(provider);
12434 }
12435 getProviderAtIndex(index) {
12436 if (index < 0 || index >= this._providers.length) {
12437 throw outOfBoundsError(index);
12438 }
12439 return this._providers[index];
12440 }
12441 /** @internal */
12442 _new(provider) {
12443 if (this._constructionCounter++ > this._getMaxNumberOfObjects()) {
12444 throw cyclicDependencyError(this, provider.key);
12445 }
12446 return this._instantiateProvider(provider);
12447 }
12448 _getMaxNumberOfObjects() {
12449 return this.objs.length;
12450 }
12451 _instantiateProvider(provider) {
12452 if (provider.multiProvider) {
12453 const res = [];
12454 for (let i = 0; i < provider.resolvedFactories.length; ++i) {
12455 res[i] = this._instantiate(provider, provider.resolvedFactories[i]);
12456 }
12457 return res;
12458 }
12459 else {
12460 return this._instantiate(provider, provider.resolvedFactories[0]);
12461 }
12462 }
12463 _instantiate(provider, ResolvedReflectiveFactory) {
12464 const factory = ResolvedReflectiveFactory.factory;
12465 let deps;
12466 try {
12467 deps =
12468 ResolvedReflectiveFactory.dependencies.map(dep => this._getByReflectiveDependency(dep));
12469 }
12470 catch (e) {
12471 if (e.addKey) {
12472 e.addKey(this, provider.key);
12473 }
12474 throw e;
12475 }
12476 let obj;
12477 try {
12478 obj = factory(...deps);
12479 }
12480 catch (e) {
12481 throw instantiationError(this, e, e.stack, provider.key);
12482 }
12483 return obj;
12484 }
12485 _getByReflectiveDependency(dep) {
12486 return this._getByKey(dep.key, dep.visibility, dep.optional ? null : THROW_IF_NOT_FOUND);
12487 }
12488 _getByKey(key, visibility, notFoundValue) {
12489 if (key === ReflectiveInjector_.INJECTOR_KEY) {
12490 return this;
12491 }
12492 if (visibility instanceof Self) {
12493 return this._getByKeySelf(key, notFoundValue);
12494 }
12495 else {
12496 return this._getByKeyDefault(key, notFoundValue, visibility);
12497 }
12498 }
12499 _getObjByKeyId(keyId) {
12500 for (let i = 0; i < this.keyIds.length; i++) {
12501 if (this.keyIds[i] === keyId) {
12502 if (this.objs[i] === UNDEFINED) {
12503 this.objs[i] = this._new(this._providers[i]);
12504 }
12505 return this.objs[i];
12506 }
12507 }
12508 return UNDEFINED;
12509 }
12510 /** @internal */
12511 _throwOrNull(key, notFoundValue) {
12512 if (notFoundValue !== THROW_IF_NOT_FOUND) {
12513 return notFoundValue;
12514 }
12515 else {
12516 throw noProviderError(this, key);
12517 }
12518 }
12519 /** @internal */
12520 _getByKeySelf(key, notFoundValue) {
12521 const obj = this._getObjByKeyId(key.id);
12522 return (obj !== UNDEFINED) ? obj : this._throwOrNull(key, notFoundValue);
12523 }
12524 /** @internal */
12525 _getByKeyDefault(key, notFoundValue, visibility) {
12526 let inj;
12527 if (visibility instanceof SkipSelf) {
12528 inj = this.parent;
12529 }
12530 else {
12531 inj = this;
12532 }
12533 while (inj instanceof ReflectiveInjector_) {
12534 const inj_ = inj;
12535 const obj = inj_._getObjByKeyId(key.id);
12536 if (obj !== UNDEFINED)
12537 return obj;
12538 inj = inj_.parent;
12539 }
12540 if (inj !== null) {
12541 return inj.get(key.token, notFoundValue);
12542 }
12543 else {
12544 return this._throwOrNull(key, notFoundValue);
12545 }
12546 }
12547 get displayName() {
12548 const providers = _mapProviders(this, (b) => ' "' + b.key.displayName + '" ')
12549 .join(', ');
12550 return `ReflectiveInjector(providers: [${providers}])`;
12551 }
12552 toString() {
12553 return this.displayName;
12554 }
12555}
12556ReflectiveInjector_.INJECTOR_KEY = ReflectiveKey.get(Injector);
12557function _mapProviders(injector, fn) {
12558 const res = [];
12559 for (let i = 0; i < injector._providers.length; ++i) {
12560 res[i] = fn(injector.getProviderAtIndex(i));
12561 }
12562 return res;
12563}
12564
12565/**
12566 * @license
12567 * Copyright Google LLC All Rights Reserved.
12568 *
12569 * Use of this source code is governed by an MIT-style license that can be
12570 * found in the LICENSE file at https://angular.io/license
12571 */
12572
12573/**
12574 * @license
12575 * Copyright Google LLC All Rights Reserved.
12576 *
12577 * Use of this source code is governed by an MIT-style license that can be
12578 * found in the LICENSE file at https://angular.io/license
12579 */
12580
12581/**
12582 * @license
12583 * Copyright Google LLC All Rights Reserved.
12584 *
12585 * Use of this source code is governed by an MIT-style license that can be
12586 * found in the LICENSE file at https://angular.io/license
12587 */
12588/**
12589 * A DI token that you can use to create a virtual [provider](guide/glossary#provider)
12590 * that will populate the `entryComponents` field of components and NgModules
12591 * based on its `useValue` property value.
12592 * All components that are referenced in the `useValue` value (either directly
12593 * or in a nested array or map) are added to the `entryComponents` property.
12594 *
12595 * @usageNotes
12596 *
12597 * The following example shows how the router can populate the `entryComponents`
12598 * field of an NgModule based on a router configuration that refers
12599 * to components.
12600 *
12601 * ```typescript
12602 * // helper function inside the router
12603 * function provideRoutes(routes) {
12604 * return [
12605 * {provide: ROUTES, useValue: routes},
12606 * {provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: routes, multi: true}
12607 * ];
12608 * }
12609 *
12610 * // user code
12611 * let routes = [
12612 * {path: '/root', component: RootComp},
12613 * {path: '/teams', component: TeamsComp}
12614 * ];
12615 *
12616 * @NgModule({
12617 * providers: [provideRoutes(routes)]
12618 * })
12619 * class ModuleWithRoutes {}
12620 * ```
12621 *
12622 * @publicApi
12623 * @deprecated Since 9.0.0. With Ivy, this property is no longer necessary.
12624 */
12625const ANALYZE_FOR_ENTRY_COMPONENTS = new InjectionToken('AnalyzeForEntryComponents');
12626/**
12627 * Base class for query metadata.
12628 *
12629 * @see `ContentChildren`.
12630 * @see `ContentChild`.
12631 * @see `ViewChildren`.
12632 * @see `ViewChild`.
12633 *
12634 * @publicApi
12635 */
12636class Query {
12637}
12638const ɵ0$a = (selector, data = {}) => (Object.assign({ selector, first: false, isViewQuery: false, descendants: false }, data));
12639/**
12640 * ContentChildren decorator and metadata.
12641 *
12642 *
12643 * @Annotation
12644 * @publicApi
12645 */
12646const ContentChildren = makePropDecorator('ContentChildren', ɵ0$a, Query);
12647const ɵ1$2 = (selector, data = {}) => (Object.assign({ selector, first: true, isViewQuery: false, descendants: true }, data));
12648/**
12649 * ContentChild decorator and metadata.
12650 *
12651 *
12652 * @Annotation
12653 *
12654 * @publicApi
12655 */
12656const ContentChild = makePropDecorator('ContentChild', ɵ1$2, Query);
12657const ɵ2 = (selector, data = {}) => (Object.assign({ selector, first: false, isViewQuery: true, descendants: true }, data));
12658/**
12659 * ViewChildren decorator and metadata.
12660 *
12661 * @Annotation
12662 * @publicApi
12663 */
12664const ViewChildren = makePropDecorator('ViewChildren', ɵ2, Query);
12665const ɵ3 = (selector, data) => (Object.assign({ selector, first: true, isViewQuery: true, descendants: true }, data));
12666/**
12667 * ViewChild decorator and metadata.
12668 *
12669 * @Annotation
12670 * @publicApi
12671 */
12672const ViewChild = makePropDecorator('ViewChild', ɵ3, Query);
12673
12674/**
12675 * @license
12676 * Copyright Google LLC All Rights Reserved.
12677 *
12678 * Use of this source code is governed by an MIT-style license that can be
12679 * found in the LICENSE file at https://angular.io/license
12680 */
12681/**
12682 * Used to resolve resource URLs on `@Component` when used with JIT compilation.
12683 *
12684 * Example:
12685 * ```
12686 * @Component({
12687 * selector: 'my-comp',
12688 * templateUrl: 'my-comp.html', // This requires asynchronous resolution
12689 * })
12690 * class MyComponent{
12691 * }
12692 *
12693 * // Calling `renderComponent` will fail because `renderComponent` is a synchronous process
12694 * // and `MyComponent`'s `@Component.templateUrl` needs to be resolved asynchronously.
12695 *
12696 * // Calling `resolveComponentResources()` will resolve `@Component.templateUrl` into
12697 * // `@Component.template`, which allows `renderComponent` to proceed in a synchronous manner.
12698 *
12699 * // Use browser's `fetch()` function as the default resource resolution strategy.
12700 * resolveComponentResources(fetch).then(() => {
12701 * // After resolution all URLs have been converted into `template` strings.
12702 * renderComponent(MyComponent);
12703 * });
12704 *
12705 * ```
12706 *
12707 * NOTE: In AOT the resolution happens during compilation, and so there should be no need
12708 * to call this method outside JIT mode.
12709 *
12710 * @param resourceResolver a function which is responsible for returning a `Promise` to the
12711 * contents of the resolved URL. Browser's `fetch()` method is a good default implementation.
12712 */
12713function resolveComponentResources(resourceResolver) {
12714 // Store all promises which are fetching the resources.
12715 const componentResolved = [];
12716 // Cache so that we don't fetch the same resource more than once.
12717 const urlMap = new Map();
12718 function cachedResourceResolve(url) {
12719 let promise = urlMap.get(url);
12720 if (!promise) {
12721 const resp = resourceResolver(url);
12722 urlMap.set(url, promise = resp.then(unwrapResponse));
12723 }
12724 return promise;
12725 }
12726 componentResourceResolutionQueue.forEach((component, type) => {
12727 const promises = [];
12728 if (component.templateUrl) {
12729 promises.push(cachedResourceResolve(component.templateUrl).then((template) => {
12730 component.template = template;
12731 }));
12732 }
12733 const styleUrls = component.styleUrls;
12734 const styles = component.styles || (component.styles = []);
12735 const styleOffset = component.styles.length;
12736 styleUrls && styleUrls.forEach((styleUrl, index) => {
12737 styles.push(''); // pre-allocate array.
12738 promises.push(cachedResourceResolve(styleUrl).then((style) => {
12739 styles[styleOffset + index] = style;
12740 styleUrls.splice(styleUrls.indexOf(styleUrl), 1);
12741 if (styleUrls.length == 0) {
12742 component.styleUrls = undefined;
12743 }
12744 }));
12745 });
12746 const fullyResolved = Promise.all(promises).then(() => componentDefResolved(type));
12747 componentResolved.push(fullyResolved);
12748 });
12749 clearResolutionOfComponentResourcesQueue();
12750 return Promise.all(componentResolved).then(() => undefined);
12751}
12752let componentResourceResolutionQueue = new Map();
12753// Track when existing ɵcmp for a Type is waiting on resources.
12754const componentDefPendingResolution = new Set();
12755function maybeQueueResolutionOfComponentResources(type, metadata) {
12756 if (componentNeedsResolution(metadata)) {
12757 componentResourceResolutionQueue.set(type, metadata);
12758 componentDefPendingResolution.add(type);
12759 }
12760}
12761function isComponentDefPendingResolution(type) {
12762 return componentDefPendingResolution.has(type);
12763}
12764function componentNeedsResolution(component) {
12765 return !!((component.templateUrl && !component.hasOwnProperty('template')) ||
12766 component.styleUrls && component.styleUrls.length);
12767}
12768function clearResolutionOfComponentResourcesQueue() {
12769 const old = componentResourceResolutionQueue;
12770 componentResourceResolutionQueue = new Map();
12771 return old;
12772}
12773function restoreComponentResolutionQueue(queue) {
12774 componentDefPendingResolution.clear();
12775 queue.forEach((_, type) => componentDefPendingResolution.add(type));
12776 componentResourceResolutionQueue = queue;
12777}
12778function isComponentResourceResolutionQueueEmpty() {
12779 return componentResourceResolutionQueue.size === 0;
12780}
12781function unwrapResponse(response) {
12782 return typeof response == 'string' ? response : response.text();
12783}
12784function componentDefResolved(type) {
12785 componentDefPendingResolution.delete(type);
12786}
12787
12788/**
12789 * @license
12790 * Copyright Google LLC All Rights Reserved.
12791 *
12792 * Use of this source code is governed by an MIT-style license that can be
12793 * found in the LICENSE file at https://angular.io/license
12794 */
12795/**
12796 * Compute the static styling (class/style) from `TAttributes`.
12797 *
12798 * This function should be called during `firstCreatePass` only.
12799 *
12800 * @param tNode The `TNode` into which the styling information should be loaded.
12801 * @param attrs `TAttributes` containing the styling information.
12802 * @param writeToHost Where should the resulting static styles be written?
12803 * - `false` Write to `TNode.stylesWithoutHost` / `TNode.classesWithoutHost`
12804 * - `true` Write to `TNode.styles` / `TNode.classes`
12805 */
12806function computeStaticStyling(tNode, attrs, writeToHost) {
12807 ngDevMode &&
12808 assertFirstCreatePass(getTView(), 'Expecting to be called in first template pass only');
12809 let styles = writeToHost ? tNode.styles : null;
12810 let classes = writeToHost ? tNode.classes : null;
12811 let mode = 0;
12812 if (attrs !== null) {
12813 for (let i = 0; i < attrs.length; i++) {
12814 const value = attrs[i];
12815 if (typeof value === 'number') {
12816 mode = value;
12817 }
12818 else if (mode == 1 /* Classes */) {
12819 classes = concatStringsWithSpace(classes, value);
12820 }
12821 else if (mode == 2 /* Styles */) {
12822 const style = value;
12823 const styleValue = attrs[++i];
12824 styles = concatStringsWithSpace(styles, style + ': ' + styleValue + ';');
12825 }
12826 }
12827 }
12828 writeToHost ? tNode.styles = styles : tNode.stylesWithoutHost = styles;
12829 writeToHost ? tNode.classes = classes : tNode.classesWithoutHost = classes;
12830}
12831
12832/**
12833 * @license
12834 * Copyright Google LLC All Rights Reserved.
12835 *
12836 * Use of this source code is governed by an MIT-style license that can be
12837 * found in the LICENSE file at https://angular.io/license
12838 */
12839let _symbolIterator = null;
12840function getSymbolIterator() {
12841 if (!_symbolIterator) {
12842 const Symbol = _global['Symbol'];
12843 if (Symbol && Symbol.iterator) {
12844 _symbolIterator = Symbol.iterator;
12845 }
12846 else {
12847 // es6-shim specific logic
12848 const keys = Object.getOwnPropertyNames(Map.prototype);
12849 for (let i = 0; i < keys.length; ++i) {
12850 const key = keys[i];
12851 if (key !== 'entries' && key !== 'size' &&
12852 Map.prototype[key] === Map.prototype['entries']) {
12853 _symbolIterator = key;
12854 }
12855 }
12856 }
12857 }
12858 return _symbolIterator;
12859}
12860
12861/**
12862 * @license
12863 * Copyright Google LLC All Rights Reserved.
12864 *
12865 * Use of this source code is governed by an MIT-style license that can be
12866 * found in the LICENSE file at https://angular.io/license
12867 */
12868function devModeEqual(a, b) {
12869 const isListLikeIterableA = isListLikeIterable(a);
12870 const isListLikeIterableB = isListLikeIterable(b);
12871 if (isListLikeIterableA && isListLikeIterableB) {
12872 return areIterablesEqual(a, b, devModeEqual);
12873 }
12874 else {
12875 const isAObject = a && (typeof a === 'object' || typeof a === 'function');
12876 const isBObject = b && (typeof b === 'object' || typeof b === 'function');
12877 if (!isListLikeIterableA && isAObject && !isListLikeIterableB && isBObject) {
12878 return true;
12879 }
12880 else {
12881 return Object.is(a, b);
12882 }
12883 }
12884}
12885/**
12886 * Indicates that the result of a {@link Pipe} transformation has changed even though the
12887 * reference has not changed.
12888 *
12889 * Wrapped values are unwrapped automatically during the change detection, and the unwrapped value
12890 * is stored.
12891 *
12892 * Example:
12893 *
12894 * ```
12895 * if (this._latestValue === this._latestReturnedValue) {
12896 * return this._latestReturnedValue;
12897 * } else {
12898 * this._latestReturnedValue = this._latestValue;
12899 * return WrappedValue.wrap(this._latestValue); // this will force update
12900 * }
12901 * ```
12902 *
12903 * @publicApi
12904 * @deprecated from v10 stop using. (No replacement, deemed unnecessary.)
12905 */
12906class WrappedValue {
12907 constructor(value) {
12908 this.wrapped = value;
12909 }
12910 /** Creates a wrapped value. */
12911 static wrap(value) {
12912 return new WrappedValue(value);
12913 }
12914 /**
12915 * Returns the underlying value of a wrapped value.
12916 * Returns the given `value` when it is not wrapped.
12917 **/
12918 static unwrap(value) {
12919 return WrappedValue.isWrapped(value) ? value.wrapped : value;
12920 }
12921 /** Returns true if `value` is a wrapped value. */
12922 static isWrapped(value) {
12923 return value instanceof WrappedValue;
12924 }
12925}
12926function isListLikeIterable(obj) {
12927 if (!isJsObject(obj))
12928 return false;
12929 return Array.isArray(obj) ||
12930 (!(obj instanceof Map) && // JS Map are iterables but return entries as [k, v]
12931 getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop
12932}
12933function areIterablesEqual(a, b, comparator) {
12934 const iterator1 = a[getSymbolIterator()]();
12935 const iterator2 = b[getSymbolIterator()]();
12936 while (true) {
12937 const item1 = iterator1.next();
12938 const item2 = iterator2.next();
12939 if (item1.done && item2.done)
12940 return true;
12941 if (item1.done || item2.done)
12942 return false;
12943 if (!comparator(item1.value, item2.value))
12944 return false;
12945 }
12946}
12947function iterateListLike(obj, fn) {
12948 if (Array.isArray(obj)) {
12949 for (let i = 0; i < obj.length; i++) {
12950 fn(obj[i]);
12951 }
12952 }
12953 else {
12954 const iterator = obj[getSymbolIterator()]();
12955 let item;
12956 while (!((item = iterator.next()).done)) {
12957 fn(item.value);
12958 }
12959 }
12960}
12961function isJsObject(o) {
12962 return o !== null && (typeof o === 'function' || typeof o === 'object');
12963}
12964
12965/**
12966 * @license
12967 * Copyright Google LLC All Rights Reserved.
12968 *
12969 * Use of this source code is governed by an MIT-style license that can be
12970 * found in the LICENSE file at https://angular.io/license
12971 */
12972// TODO(misko): consider inlining
12973/** Updates binding and returns the value. */
12974function updateBinding(lView, bindingIndex, value) {
12975 return lView[bindingIndex] = value;
12976}
12977/** Gets the current binding value. */
12978function getBinding(lView, bindingIndex) {
12979 ngDevMode && assertIndexInRange(lView, bindingIndex);
12980 ngDevMode &&
12981 assertNotSame(lView[bindingIndex], NO_CHANGE, 'Stored value should never be NO_CHANGE.');
12982 return lView[bindingIndex];
12983}
12984/**
12985 * Updates binding if changed, then returns whether it was updated.
12986 *
12987 * This function also checks the `CheckNoChangesMode` and throws if changes are made.
12988 * Some changes (Objects/iterables) during `CheckNoChangesMode` are exempt to comply with VE
12989 * behavior.
12990 *
12991 * @param lView current `LView`
12992 * @param bindingIndex The binding in the `LView` to check
12993 * @param value New value to check against `lView[bindingIndex]`
12994 * @returns `true` if the bindings has changed. (Throws if binding has changed during
12995 * `CheckNoChangesMode`)
12996 */
12997function bindingUpdated(lView, bindingIndex, value) {
12998 ngDevMode && assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.');
12999 ngDevMode &&
13000 assertLessThan(bindingIndex, lView.length, `Slot should have been initialized to NO_CHANGE`);
13001 const oldValue = lView[bindingIndex];
13002 if (Object.is(oldValue, value)) {
13003 return false;
13004 }
13005 else {
13006 if (ngDevMode && getCheckNoChangesMode()) {
13007 // View engine didn't report undefined values as changed on the first checkNoChanges pass
13008 // (before the change detection was run).
13009 const oldValueToCompare = oldValue !== NO_CHANGE ? oldValue : undefined;
13010 if (!devModeEqual(oldValueToCompare, value)) {
13011 const details = getExpressionChangedErrorDetails(lView, bindingIndex, oldValueToCompare, value);
13012 throwErrorIfNoChangesMode(oldValue === NO_CHANGE, details.oldValue, details.newValue, details.propName);
13013 }
13014 // There was a change, but the `devModeEqual` decided that the change is exempt from an error.
13015 // For this reason we exit as if no change. The early exit is needed to prevent the changed
13016 // value to be written into `LView` (If we would write the new value that we would not see it
13017 // as change on next CD.)
13018 return false;
13019 }
13020 lView[bindingIndex] = value;
13021 return true;
13022 }
13023}
13024/** Updates 2 bindings if changed, then returns whether either was updated. */
13025function bindingUpdated2(lView, bindingIndex, exp1, exp2) {
13026 const different = bindingUpdated(lView, bindingIndex, exp1);
13027 return bindingUpdated(lView, bindingIndex + 1, exp2) || different;
13028}
13029/** Updates 3 bindings if changed, then returns whether any was updated. */
13030function bindingUpdated3(lView, bindingIndex, exp1, exp2, exp3) {
13031 const different = bindingUpdated2(lView, bindingIndex, exp1, exp2);
13032 return bindingUpdated(lView, bindingIndex + 2, exp3) || different;
13033}
13034/** Updates 4 bindings if changed, then returns whether any was updated. */
13035function bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4) {
13036 const different = bindingUpdated2(lView, bindingIndex, exp1, exp2);
13037 return bindingUpdated2(lView, bindingIndex + 2, exp3, exp4) || different;
13038}
13039
13040/**
13041 * @license
13042 * Copyright Google LLC All Rights Reserved.
13043 *
13044 * Use of this source code is governed by an MIT-style license that can be
13045 * found in the LICENSE file at https://angular.io/license
13046 */
13047/**
13048 * Updates the value of or removes a bound attribute on an Element.
13049 *
13050 * Used in the case of `[attr.title]="value"`
13051 *
13052 * @param name name The name of the attribute.
13053 * @param value value The attribute is removed when value is `null` or `undefined`.
13054 * Otherwise the attribute value is set to the stringified value.
13055 * @param sanitizer An optional function used to sanitize the value.
13056 * @param namespace Optional namespace to use when setting the attribute.
13057 *
13058 * @codeGenApi
13059 */
13060function ɵɵattribute(name, value, sanitizer, namespace) {
13061 const lView = getLView();
13062 const bindingIndex = nextBindingIndex();
13063 if (bindingUpdated(lView, bindingIndex, value)) {
13064 const tView = getTView();
13065 const tNode = getSelectedTNode();
13066 elementAttributeInternal(tNode, lView, name, value, sanitizer, namespace);
13067 ngDevMode && storePropertyBindingMetadata(tView.data, tNode, 'attr.' + name, bindingIndex);
13068 }
13069 return ɵɵattribute;
13070}
13071
13072/**
13073 * @license
13074 * Copyright Google LLC All Rights Reserved.
13075 *
13076 * Use of this source code is governed by an MIT-style license that can be
13077 * found in the LICENSE file at https://angular.io/license
13078 */
13079/**
13080 * Create interpolation bindings with a variable number of expressions.
13081 *
13082 * If there are 1 to 8 expressions `interpolation1()` to `interpolation8()` should be used instead.
13083 * Those are faster because there is no need to create an array of expressions and iterate over it.
13084 *
13085 * `values`:
13086 * - has static text at even indexes,
13087 * - has evaluated expressions at odd indexes.
13088 *
13089 * Returns the concatenated string when any of the arguments changes, `NO_CHANGE` otherwise.
13090 */
13091function interpolationV(lView, values) {
13092 ngDevMode && assertLessThan(2, values.length, 'should have at least 3 values');
13093 ngDevMode && assertEqual(values.length % 2, 1, 'should have an odd number of values');
13094 let isBindingUpdated = false;
13095 let bindingIndex = getBindingIndex();
13096 for (let i = 1; i < values.length; i += 2) {
13097 // Check if bindings (odd indexes) have changed
13098 isBindingUpdated = bindingUpdated(lView, bindingIndex++, values[i]) || isBindingUpdated;
13099 }
13100 setBindingIndex(bindingIndex);
13101 if (!isBindingUpdated) {
13102 return NO_CHANGE;
13103 }
13104 // Build the updated content
13105 let content = values[0];
13106 for (let i = 1; i < values.length; i += 2) {
13107 content += renderStringify(values[i]) + values[i + 1];
13108 }
13109 return content;
13110}
13111/**
13112 * Creates an interpolation binding with 1 expression.
13113 *
13114 * @param prefix static value used for concatenation only.
13115 * @param v0 value checked for change.
13116 * @param suffix static value used for concatenation only.
13117 */
13118function interpolation1(lView, prefix, v0, suffix) {
13119 const different = bindingUpdated(lView, nextBindingIndex(), v0);
13120 return different ? prefix + renderStringify(v0) + suffix : NO_CHANGE;
13121}
13122/**
13123 * Creates an interpolation binding with 2 expressions.
13124 */
13125function interpolation2(lView, prefix, v0, i0, v1, suffix) {
13126 const bindingIndex = getBindingIndex();
13127 const different = bindingUpdated2(lView, bindingIndex, v0, v1);
13128 incrementBindingIndex(2);
13129 return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + suffix : NO_CHANGE;
13130}
13131/**
13132 * Creates an interpolation binding with 3 expressions.
13133 */
13134function interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix) {
13135 const bindingIndex = getBindingIndex();
13136 const different = bindingUpdated3(lView, bindingIndex, v0, v1, v2);
13137 incrementBindingIndex(3);
13138 return different ?
13139 prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + suffix :
13140 NO_CHANGE;
13141}
13142/**
13143 * Create an interpolation binding with 4 expressions.
13144 */
13145function interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
13146 const bindingIndex = getBindingIndex();
13147 const different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
13148 incrementBindingIndex(4);
13149 return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 +
13150 renderStringify(v2) + i2 + renderStringify(v3) + suffix :
13151 NO_CHANGE;
13152}
13153/**
13154 * Creates an interpolation binding with 5 expressions.
13155 */
13156function interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
13157 const bindingIndex = getBindingIndex();
13158 let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
13159 different = bindingUpdated(lView, bindingIndex + 4, v4) || different;
13160 incrementBindingIndex(5);
13161 return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 +
13162 renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + suffix :
13163 NO_CHANGE;
13164}
13165/**
13166 * Creates an interpolation binding with 6 expressions.
13167 */
13168function interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
13169 const bindingIndex = getBindingIndex();
13170 let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
13171 different = bindingUpdated2(lView, bindingIndex + 4, v4, v5) || different;
13172 incrementBindingIndex(6);
13173 return different ?
13174 prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + i2 +
13175 renderStringify(v3) + i3 + renderStringify(v4) + i4 + renderStringify(v5) + suffix :
13176 NO_CHANGE;
13177}
13178/**
13179 * Creates an interpolation binding with 7 expressions.
13180 */
13181function interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
13182 const bindingIndex = getBindingIndex();
13183 let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
13184 different = bindingUpdated3(lView, bindingIndex + 4, v4, v5, v6) || different;
13185 incrementBindingIndex(7);
13186 return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 +
13187 renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + i4 +
13188 renderStringify(v5) + i5 + renderStringify(v6) + suffix :
13189 NO_CHANGE;
13190}
13191/**
13192 * Creates an interpolation binding with 8 expressions.
13193 */
13194function interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
13195 const bindingIndex = getBindingIndex();
13196 let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
13197 different = bindingUpdated4(lView, bindingIndex + 4, v4, v5, v6, v7) || different;
13198 incrementBindingIndex(8);
13199 return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 +
13200 renderStringify(v2) + i2 + renderStringify(v3) + i3 + renderStringify(v4) + i4 +
13201 renderStringify(v5) + i5 + renderStringify(v6) + i6 + renderStringify(v7) + suffix :
13202 NO_CHANGE;
13203}
13204
13205/**
13206 *
13207 * Update an interpolated attribute on an element with single bound value surrounded by text.
13208 *
13209 * Used when the value passed to a property has 1 interpolated value in it:
13210 *
13211 * ```html
13212 * <div attr.title="prefix{{v0}}suffix"></div>
13213 * ```
13214 *
13215 * Its compiled representation is::
13216 *
13217 * ```ts
13218 * ɵɵattributeInterpolate1('title', 'prefix', v0, 'suffix');
13219 * ```
13220 *
13221 * @param attrName The name of the attribute to update
13222 * @param prefix Static value used for concatenation only.
13223 * @param v0 Value checked for change.
13224 * @param suffix Static value used for concatenation only.
13225 * @param sanitizer An optional sanitizer function
13226 * @returns itself, so that it may be chained.
13227 * @codeGenApi
13228 */
13229function ɵɵattributeInterpolate1(attrName, prefix, v0, suffix, sanitizer, namespace) {
13230 const lView = getLView();
13231 const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
13232 if (interpolatedValue !== NO_CHANGE) {
13233 const tNode = getSelectedTNode();
13234 elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
13235 ngDevMode &&
13236 storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 1, prefix, suffix);
13237 }
13238 return ɵɵattributeInterpolate1;
13239}
13240/**
13241 *
13242 * Update an interpolated attribute on an element with 2 bound values surrounded by text.
13243 *
13244 * Used when the value passed to a property has 2 interpolated values in it:
13245 *
13246 * ```html
13247 * <div attr.title="prefix{{v0}}-{{v1}}suffix"></div>
13248 * ```
13249 *
13250 * Its compiled representation is::
13251 *
13252 * ```ts
13253 * ɵɵattributeInterpolate2('title', 'prefix', v0, '-', v1, 'suffix');
13254 * ```
13255 *
13256 * @param attrName The name of the attribute to update
13257 * @param prefix Static value used for concatenation only.
13258 * @param v0 Value checked for change.
13259 * @param i0 Static value used for concatenation only.
13260 * @param v1 Value checked for change.
13261 * @param suffix Static value used for concatenation only.
13262 * @param sanitizer An optional sanitizer function
13263 * @returns itself, so that it may be chained.
13264 * @codeGenApi
13265 */
13266function ɵɵattributeInterpolate2(attrName, prefix, v0, i0, v1, suffix, sanitizer, namespace) {
13267 const lView = getLView();
13268 const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
13269 if (interpolatedValue !== NO_CHANGE) {
13270 const tNode = getSelectedTNode();
13271 elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
13272 ngDevMode &&
13273 storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 2, prefix, i0, suffix);
13274 }
13275 return ɵɵattributeInterpolate2;
13276}
13277/**
13278 *
13279 * Update an interpolated attribute on an element with 3 bound values surrounded by text.
13280 *
13281 * Used when the value passed to a property has 3 interpolated values in it:
13282 *
13283 * ```html
13284 * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
13285 * ```
13286 *
13287 * Its compiled representation is::
13288 *
13289 * ```ts
13290 * ɵɵattributeInterpolate3(
13291 * 'title', 'prefix', v0, '-', v1, '-', v2, 'suffix');
13292 * ```
13293 *
13294 * @param attrName The name of the attribute to update
13295 * @param prefix Static value used for concatenation only.
13296 * @param v0 Value checked for change.
13297 * @param i0 Static value used for concatenation only.
13298 * @param v1 Value checked for change.
13299 * @param i1 Static value used for concatenation only.
13300 * @param v2 Value checked for change.
13301 * @param suffix Static value used for concatenation only.
13302 * @param sanitizer An optional sanitizer function
13303 * @returns itself, so that it may be chained.
13304 * @codeGenApi
13305 */
13306function ɵɵattributeInterpolate3(attrName, prefix, v0, i0, v1, i1, v2, suffix, sanitizer, namespace) {
13307 const lView = getLView();
13308 const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
13309 if (interpolatedValue !== NO_CHANGE) {
13310 const tNode = getSelectedTNode();
13311 elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
13312 ngDevMode &&
13313 storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 3, prefix, i0, i1, suffix);
13314 }
13315 return ɵɵattributeInterpolate3;
13316}
13317/**
13318 *
13319 * Update an interpolated attribute on an element with 4 bound values surrounded by text.
13320 *
13321 * Used when the value passed to a property has 4 interpolated values in it:
13322 *
13323 * ```html
13324 * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
13325 * ```
13326 *
13327 * Its compiled representation is::
13328 *
13329 * ```ts
13330 * ɵɵattributeInterpolate4(
13331 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
13332 * ```
13333 *
13334 * @param attrName The name of the attribute to update
13335 * @param prefix Static value used for concatenation only.
13336 * @param v0 Value checked for change.
13337 * @param i0 Static value used for concatenation only.
13338 * @param v1 Value checked for change.
13339 * @param i1 Static value used for concatenation only.
13340 * @param v2 Value checked for change.
13341 * @param i2 Static value used for concatenation only.
13342 * @param v3 Value checked for change.
13343 * @param suffix Static value used for concatenation only.
13344 * @param sanitizer An optional sanitizer function
13345 * @returns itself, so that it may be chained.
13346 * @codeGenApi
13347 */
13348function ɵɵattributeInterpolate4(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, sanitizer, namespace) {
13349 const lView = getLView();
13350 const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
13351 if (interpolatedValue !== NO_CHANGE) {
13352 const tNode = getSelectedTNode();
13353 elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
13354 ngDevMode &&
13355 storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 4, prefix, i0, i1, i2, suffix);
13356 }
13357 return ɵɵattributeInterpolate4;
13358}
13359/**
13360 *
13361 * Update an interpolated attribute on an element with 5 bound values surrounded by text.
13362 *
13363 * Used when the value passed to a property has 5 interpolated values in it:
13364 *
13365 * ```html
13366 * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
13367 * ```
13368 *
13369 * Its compiled representation is::
13370 *
13371 * ```ts
13372 * ɵɵattributeInterpolate5(
13373 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
13374 * ```
13375 *
13376 * @param attrName The name of the attribute to update
13377 * @param prefix Static value used for concatenation only.
13378 * @param v0 Value checked for change.
13379 * @param i0 Static value used for concatenation only.
13380 * @param v1 Value checked for change.
13381 * @param i1 Static value used for concatenation only.
13382 * @param v2 Value checked for change.
13383 * @param i2 Static value used for concatenation only.
13384 * @param v3 Value checked for change.
13385 * @param i3 Static value used for concatenation only.
13386 * @param v4 Value checked for change.
13387 * @param suffix Static value used for concatenation only.
13388 * @param sanitizer An optional sanitizer function
13389 * @returns itself, so that it may be chained.
13390 * @codeGenApi
13391 */
13392function ɵɵattributeInterpolate5(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, sanitizer, namespace) {
13393 const lView = getLView();
13394 const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
13395 if (interpolatedValue !== NO_CHANGE) {
13396 const tNode = getSelectedTNode();
13397 elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
13398 ngDevMode &&
13399 storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 5, prefix, i0, i1, i2, i3, suffix);
13400 }
13401 return ɵɵattributeInterpolate5;
13402}
13403/**
13404 *
13405 * Update an interpolated attribute on an element with 6 bound values surrounded by text.
13406 *
13407 * Used when the value passed to a property has 6 interpolated values in it:
13408 *
13409 * ```html
13410 * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
13411 * ```
13412 *
13413 * Its compiled representation is::
13414 *
13415 * ```ts
13416 * ɵɵattributeInterpolate6(
13417 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
13418 * ```
13419 *
13420 * @param attrName The name of the attribute to update
13421 * @param prefix Static value used for concatenation only.
13422 * @param v0 Value checked for change.
13423 * @param i0 Static value used for concatenation only.
13424 * @param v1 Value checked for change.
13425 * @param i1 Static value used for concatenation only.
13426 * @param v2 Value checked for change.
13427 * @param i2 Static value used for concatenation only.
13428 * @param v3 Value checked for change.
13429 * @param i3 Static value used for concatenation only.
13430 * @param v4 Value checked for change.
13431 * @param i4 Static value used for concatenation only.
13432 * @param v5 Value checked for change.
13433 * @param suffix Static value used for concatenation only.
13434 * @param sanitizer An optional sanitizer function
13435 * @returns itself, so that it may be chained.
13436 * @codeGenApi
13437 */
13438function ɵɵattributeInterpolate6(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, sanitizer, namespace) {
13439 const lView = getLView();
13440 const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
13441 if (interpolatedValue !== NO_CHANGE) {
13442 const tNode = getSelectedTNode();
13443 elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
13444 ngDevMode &&
13445 storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 6, prefix, i0, i1, i2, i3, i4, suffix);
13446 }
13447 return ɵɵattributeInterpolate6;
13448}
13449/**
13450 *
13451 * Update an interpolated attribute on an element with 7 bound values surrounded by text.
13452 *
13453 * Used when the value passed to a property has 7 interpolated values in it:
13454 *
13455 * ```html
13456 * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
13457 * ```
13458 *
13459 * Its compiled representation is::
13460 *
13461 * ```ts
13462 * ɵɵattributeInterpolate7(
13463 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
13464 * ```
13465 *
13466 * @param attrName The name of the attribute to update
13467 * @param prefix Static value used for concatenation only.
13468 * @param v0 Value checked for change.
13469 * @param i0 Static value used for concatenation only.
13470 * @param v1 Value checked for change.
13471 * @param i1 Static value used for concatenation only.
13472 * @param v2 Value checked for change.
13473 * @param i2 Static value used for concatenation only.
13474 * @param v3 Value checked for change.
13475 * @param i3 Static value used for concatenation only.
13476 * @param v4 Value checked for change.
13477 * @param i4 Static value used for concatenation only.
13478 * @param v5 Value checked for change.
13479 * @param i5 Static value used for concatenation only.
13480 * @param v6 Value checked for change.
13481 * @param suffix Static value used for concatenation only.
13482 * @param sanitizer An optional sanitizer function
13483 * @returns itself, so that it may be chained.
13484 * @codeGenApi
13485 */
13486function ɵɵattributeInterpolate7(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, sanitizer, namespace) {
13487 const lView = getLView();
13488 const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
13489 if (interpolatedValue !== NO_CHANGE) {
13490 const tNode = getSelectedTNode();
13491 elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
13492 ngDevMode &&
13493 storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, i5, suffix);
13494 }
13495 return ɵɵattributeInterpolate7;
13496}
13497/**
13498 *
13499 * Update an interpolated attribute on an element with 8 bound values surrounded by text.
13500 *
13501 * Used when the value passed to a property has 8 interpolated values in it:
13502 *
13503 * ```html
13504 * <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
13505 * ```
13506 *
13507 * Its compiled representation is::
13508 *
13509 * ```ts
13510 * ɵɵattributeInterpolate8(
13511 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
13512 * ```
13513 *
13514 * @param attrName The name of the attribute to update
13515 * @param prefix Static value used for concatenation only.
13516 * @param v0 Value checked for change.
13517 * @param i0 Static value used for concatenation only.
13518 * @param v1 Value checked for change.
13519 * @param i1 Static value used for concatenation only.
13520 * @param v2 Value checked for change.
13521 * @param i2 Static value used for concatenation only.
13522 * @param v3 Value checked for change.
13523 * @param i3 Static value used for concatenation only.
13524 * @param v4 Value checked for change.
13525 * @param i4 Static value used for concatenation only.
13526 * @param v5 Value checked for change.
13527 * @param i5 Static value used for concatenation only.
13528 * @param v6 Value checked for change.
13529 * @param i6 Static value used for concatenation only.
13530 * @param v7 Value checked for change.
13531 * @param suffix Static value used for concatenation only.
13532 * @param sanitizer An optional sanitizer function
13533 * @returns itself, so that it may be chained.
13534 * @codeGenApi
13535 */
13536function ɵɵattributeInterpolate8(attrName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, sanitizer, namespace) {
13537 const lView = getLView();
13538 const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
13539 if (interpolatedValue !== NO_CHANGE) {
13540 const tNode = getSelectedTNode();
13541 elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
13542 ngDevMode &&
13543 storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, i5, i6, suffix);
13544 }
13545 return ɵɵattributeInterpolate8;
13546}
13547/**
13548 * Update an interpolated attribute on an element with 9 or more bound values surrounded by text.
13549 *
13550 * Used when the number of interpolated values exceeds 8.
13551 *
13552 * ```html
13553 * <div
13554 * title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
13555 * ```
13556 *
13557 * Its compiled representation is::
13558 *
13559 * ```ts
13560 * ɵɵattributeInterpolateV(
13561 * 'title', ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
13562 * 'suffix']);
13563 * ```
13564 *
13565 * @param attrName The name of the attribute to update.
13566 * @param values The collection of values and the strings in-between those values, beginning with
13567 * a string prefix and ending with a string suffix.
13568 * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
13569 * @param sanitizer An optional sanitizer function
13570 * @returns itself, so that it may be chained.
13571 * @codeGenApi
13572 */
13573function ɵɵattributeInterpolateV(attrName, values, sanitizer, namespace) {
13574 const lView = getLView();
13575 const interpolated = interpolationV(lView, values);
13576 if (interpolated !== NO_CHANGE) {
13577 const tNode = getSelectedTNode();
13578 elementAttributeInternal(tNode, lView, attrName, interpolated, sanitizer, namespace);
13579 if (ngDevMode) {
13580 const interpolationInBetween = [values[0]]; // prefix
13581 for (let i = 2; i < values.length; i += 2) {
13582 interpolationInBetween.push(values[i]);
13583 }
13584 storePropertyBindingMetadata(getTView().data, tNode, 'attr.' + attrName, getBindingIndex() - interpolationInBetween.length + 1, ...interpolationInBetween);
13585 }
13586 }
13587 return ɵɵattributeInterpolateV;
13588}
13589
13590/**
13591 * @license
13592 * Copyright Google LLC All Rights Reserved.
13593 *
13594 * Use of this source code is governed by an MIT-style license that can be
13595 * found in the LICENSE file at https://angular.io/license
13596 */
13597/**
13598 * Synchronously perform change detection on a component (and possibly its sub-components).
13599 *
13600 * This function triggers change detection in a synchronous way on a component.
13601 *
13602 * @param component The component which the change detection should be performed on.
13603 */
13604function detectChanges(component) {
13605 const view = getComponentViewByInstance(component);
13606 detectChangesInternal(view[TVIEW], view, component);
13607}
13608/**
13609 * Marks the component as dirty (needing change detection). Marking a component dirty will
13610 * schedule a change detection on it at some point in the future.
13611 *
13612 * Marking an already dirty component as dirty won't do anything. Only one outstanding change
13613 * detection can be scheduled per component tree.
13614 *
13615 * @param component Component to mark as dirty.
13616 */
13617function markDirty(component) {
13618 ngDevMode && assertDefined(component, 'component');
13619 const rootView = markViewDirty(getComponentViewByInstance(component));
13620 ngDevMode && assertDefined(rootView[CONTEXT], 'rootContext should be defined');
13621 scheduleTick(rootView[CONTEXT], 1 /* DetectChanges */);
13622}
13623/**
13624 * Used to perform change detection on the whole application.
13625 *
13626 * This is equivalent to `detectChanges`, but invoked on root component. Additionally, `tick`
13627 * executes lifecycle hooks and conditionally checks components based on their
13628 * `ChangeDetectionStrategy` and dirtiness.
13629 *
13630 * The preferred way to trigger change detection is to call `markDirty`. `markDirty` internally
13631 * schedules `tick` using a scheduler in order to coalesce multiple `markDirty` calls into a
13632 * single change detection run. By default, the scheduler is `requestAnimationFrame`, but can
13633 * be changed when calling `renderComponent` and providing the `scheduler` option.
13634 */
13635function tick(component) {
13636 const rootView = getRootView(component);
13637 const rootContext = rootView[CONTEXT];
13638 tickRootContext(rootContext);
13639}
13640
13641/**
13642 * @license
13643 * Copyright Google LLC All Rights Reserved.
13644 *
13645 * Use of this source code is governed by an MIT-style license that can be
13646 * found in the LICENSE file at https://angular.io/license
13647 */
13648function templateFirstCreatePass(index, tView, lView, templateFn, decls, vars, tagName, attrsIndex, localRefsIndex) {
13649 ngDevMode && assertFirstCreatePass(tView);
13650 ngDevMode && ngDevMode.firstCreatePass++;
13651 const tViewConsts = tView.consts;
13652 // TODO(pk): refactor getOrCreateTNode to have the "create" only version
13653 const tNode = getOrCreateTNode(tView, lView[T_HOST], index, 0 /* Container */, tagName || null, getConstant(tViewConsts, attrsIndex));
13654 resolveDirectives(tView, lView, tNode, getConstant(tViewConsts, localRefsIndex));
13655 registerPostOrderHooks(tView, tNode);
13656 const embeddedTView = tNode.tViews = createTView(2 /* Embedded */, -1, templateFn, decls, vars, tView.directiveRegistry, tView.pipeRegistry, null, tView.schemas, tViewConsts);
13657 const embeddedTViewNode = createTNode(tView, null, 2 /* View */, -1, null, null);
13658 embeddedTViewNode.injectorIndex = tNode.injectorIndex;
13659 embeddedTView.node = embeddedTViewNode;
13660 if (tView.queries !== null) {
13661 tView.queries.template(tView, tNode);
13662 embeddedTView.queries = tView.queries.embeddedTView(tNode);
13663 }
13664 return tNode;
13665}
13666/**
13667 * Creates an LContainer for an ng-template (dynamically-inserted view), e.g.
13668 *
13669 * <ng-template #foo>
13670 * <div></div>
13671 * </ng-template>
13672 *
13673 * @param index The index of the container in the data array
13674 * @param templateFn Inline template
13675 * @param decls The number of nodes, local refs, and pipes for this template
13676 * @param vars The number of bindings for this template
13677 * @param tagName The name of the container element, if applicable
13678 * @param attrsIndex Index of template attributes in the `consts` array.
13679 * @param localRefs Index of the local references in the `consts` array.
13680 * @param localRefExtractor A function which extracts local-refs values from the template.
13681 * Defaults to the current element associated with the local-ref.
13682 *
13683 * @codeGenApi
13684 */
13685function ɵɵtemplate(index, templateFn, decls, vars, tagName, attrsIndex, localRefsIndex, localRefExtractor) {
13686 const lView = getLView();
13687 const tView = getTView();
13688 const adjustedIndex = index + HEADER_OFFSET;
13689 const tNode = tView.firstCreatePass ?
13690 templateFirstCreatePass(index, tView, lView, templateFn, decls, vars, tagName, attrsIndex, localRefsIndex) :
13691 tView.data[adjustedIndex];
13692 setPreviousOrParentTNode(tNode, false);
13693 const comment = lView[RENDERER].createComment(ngDevMode ? 'container' : '');
13694 appendChild(tView, lView, comment, tNode);
13695 attachPatchData(comment, lView);
13696 addToViewTree(lView, lView[adjustedIndex] = createLContainer(comment, lView, comment, tNode));
13697 if (isDirectiveHost(tNode)) {
13698 createDirectivesInstances(tView, lView, tNode);
13699 }
13700 if (localRefsIndex != null) {
13701 saveResolvedLocalsInData(lView, tNode, localRefExtractor);
13702 }
13703}
13704
13705/**
13706 * @license
13707 * Copyright Google LLC All Rights Reserved.
13708 *
13709 * Use of this source code is governed by an MIT-style license that can be
13710 * found in the LICENSE file at https://angular.io/license
13711 */
13712/** Store a value in the `data` at a given `index`. */
13713function store(tView, lView, index, value) {
13714 // We don't store any static data for local variables, so the first time
13715 // we see the template, we should store as null to avoid a sparse array
13716 const adjustedIndex = index + HEADER_OFFSET;
13717 if (adjustedIndex >= tView.data.length) {
13718 tView.data[adjustedIndex] = null;
13719 tView.blueprint[adjustedIndex] = null;
13720 }
13721 lView[adjustedIndex] = value;
13722}
13723/**
13724 * Retrieves a local reference from the current contextViewData.
13725 *
13726 * If the reference to retrieve is in a parent view, this instruction is used in conjunction
13727 * with a nextContext() call, which walks up the tree and updates the contextViewData instance.
13728 *
13729 * @param index The index of the local ref in contextViewData.
13730 *
13731 * @codeGenApi
13732 */
13733function ɵɵreference(index) {
13734 const contextLView = getContextLView();
13735 return load(contextLView, index);
13736}
13737
13738/**
13739 * @license
13740 * Copyright Google LLC All Rights Reserved.
13741 *
13742 * Use of this source code is governed by an MIT-style license that can be
13743 * found in the LICENSE file at https://angular.io/license
13744 */
13745function ɵɵdirectiveInject(token, flags = InjectFlags.Default) {
13746 const lView = getLView();
13747 // Fall back to inject() if view hasn't been created. This situation can happen in tests
13748 // if inject utilities are used before bootstrapping.
13749 if (lView == null)
13750 return ɵɵinject(token, flags);
13751 const tNode = getPreviousOrParentTNode();
13752 return getOrCreateInjectable(tNode, lView, resolveForwardRef(token), flags);
13753}
13754/**
13755 * Facade for the attribute injection from DI.
13756 *
13757 * @codeGenApi
13758 */
13759function ɵɵinjectAttribute(attrNameToInject) {
13760 return injectAttributeImpl(getPreviousOrParentTNode(), attrNameToInject);
13761}
13762/**
13763 * Throws an error indicating that a factory function could not be generated by the compiler for a
13764 * particular class.
13765 *
13766 * This instruction allows the actual error message to be optimized away when ngDevMode is turned
13767 * off, saving bytes of generated code while still providing a good experience in dev mode.
13768 *
13769 * The name of the class is not mentioned here, but will be in the generated factory function name
13770 * and thus in the stack trace.
13771 *
13772 * @codeGenApi
13773 */
13774function ɵɵinvalidFactory() {
13775 const msg = ngDevMode ? `This constructor was not compatible with Dependency Injection.` : 'invalid';
13776 throw new Error(msg);
13777}
13778
13779/**
13780 * @license
13781 * Copyright Google LLC All Rights Reserved.
13782 *
13783 * Use of this source code is governed by an MIT-style license that can be
13784 * found in the LICENSE file at https://angular.io/license
13785 */
13786/**
13787 * Update a property on a selected element.
13788 *
13789 * Operates on the element selected by index via the {@link select} instruction.
13790 *
13791 * If the property name also exists as an input property on one of the element's directives,
13792 * the component property will be set instead of the element property. This check must
13793 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled
13794 *
13795 * @param propName Name of property. Because it is going to DOM, this is not subject to
13796 * renaming as part of minification.
13797 * @param value New value to write.
13798 * @param sanitizer An optional function used to sanitize the value.
13799 * @returns This function returns itself so that it may be chained
13800 * (e.g. `property('name', ctx.name)('title', ctx.title)`)
13801 *
13802 * @codeGenApi
13803 */
13804function ɵɵproperty(propName, value, sanitizer) {
13805 const lView = getLView();
13806 const bindingIndex = nextBindingIndex();
13807 if (bindingUpdated(lView, bindingIndex, value)) {
13808 const tView = getTView();
13809 const tNode = getSelectedTNode();
13810 elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, false);
13811 ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
13812 }
13813 return ɵɵproperty;
13814}
13815/**
13816 * Given `<div style="..." my-dir>` and `MyDir` with `@Input('style')` we need to write to
13817 * directive input.
13818 */
13819function setDirectiveInputsWhichShadowsStyling(tView, tNode, lView, value, isClassBased) {
13820 const inputs = tNode.inputs;
13821 const property = isClassBased ? 'class' : 'style';
13822 // We support both 'class' and `className` hence the fallback.
13823 setInputsForProperty(tView, lView, inputs[property], property, value);
13824}
13825
13826/**
13827 * @license
13828 * Copyright Google LLC All Rights Reserved.
13829 *
13830 * Use of this source code is governed by an MIT-style license that can be
13831 * found in the LICENSE file at https://angular.io/license
13832 */
13833function elementStartFirstCreatePass(index, tView, lView, native, name, attrsIndex, localRefsIndex) {
13834 ngDevMode && assertFirstCreatePass(tView);
13835 ngDevMode && ngDevMode.firstCreatePass++;
13836 const tViewConsts = tView.consts;
13837 const attrs = getConstant(tViewConsts, attrsIndex);
13838 const tNode = getOrCreateTNode(tView, lView[T_HOST], index, 3 /* Element */, name, attrs);
13839 const hasDirectives = resolveDirectives(tView, lView, tNode, getConstant(tViewConsts, localRefsIndex));
13840 ngDevMode && logUnknownElementError(tView, native, tNode, hasDirectives);
13841 if (tNode.attrs !== null) {
13842 computeStaticStyling(tNode, tNode.attrs, false);
13843 }
13844 if (tNode.mergedAttrs !== null) {
13845 computeStaticStyling(tNode, tNode.mergedAttrs, true);
13846 }
13847 if (tView.queries !== null) {
13848 tView.queries.elementStart(tView, tNode);
13849 }
13850 return tNode;
13851}
13852/**
13853 * Create DOM element. The instruction must later be followed by `elementEnd()` call.
13854 *
13855 * @param index Index of the element in the LView array
13856 * @param name Name of the DOM Node
13857 * @param attrsIndex Index of the element's attributes in the `consts` array.
13858 * @param localRefsIndex Index of the element's local references in the `consts` array.
13859 *
13860 * Attributes and localRefs are passed as an array of strings where elements with an even index
13861 * hold an attribute name and elements with an odd index hold an attribute value, ex.:
13862 * ['id', 'warning5', 'class', 'alert']
13863 *
13864 * @codeGenApi
13865 */
13866function ɵɵelementStart(index, name, attrsIndex, localRefsIndex) {
13867 const lView = getLView();
13868 const tView = getTView();
13869 const adjustedIndex = HEADER_OFFSET + index;
13870 ngDevMode &&
13871 assertEqual(getBindingIndex(), tView.bindingStartIndex, 'elements should be created before any bindings');
13872 ngDevMode && ngDevMode.rendererCreateElement++;
13873 ngDevMode && assertIndexInRange(lView, adjustedIndex);
13874 const renderer = lView[RENDERER];
13875 const native = lView[adjustedIndex] = elementCreate(name, renderer, getNamespace());
13876 const tNode = tView.firstCreatePass ?
13877 elementStartFirstCreatePass(index, tView, lView, native, name, attrsIndex, localRefsIndex) :
13878 tView.data[adjustedIndex];
13879 setPreviousOrParentTNode(tNode, true);
13880 const mergedAttrs = tNode.mergedAttrs;
13881 if (mergedAttrs !== null) {
13882 setUpAttributes(renderer, native, mergedAttrs);
13883 }
13884 const classes = tNode.classes;
13885 if (classes !== null) {
13886 writeDirectClass(renderer, native, classes);
13887 }
13888 const styles = tNode.styles;
13889 if (styles !== null) {
13890 writeDirectStyle(renderer, native, styles);
13891 }
13892 appendChild(tView, lView, native, tNode);
13893 // any immediate children of a component or template container must be pre-emptively
13894 // monkey-patched with the component view data so that the element can be inspected
13895 // later on using any element discovery utility methods (see `element_discovery.ts`)
13896 if (getElementDepthCount() === 0) {
13897 attachPatchData(native, lView);
13898 }
13899 increaseElementDepthCount();
13900 if (isDirectiveHost(tNode)) {
13901 createDirectivesInstances(tView, lView, tNode);
13902 executeContentQueries(tView, tNode, lView);
13903 }
13904 if (localRefsIndex !== null) {
13905 saveResolvedLocalsInData(lView, tNode);
13906 }
13907}
13908/**
13909 * Mark the end of the element.
13910 *
13911 * @codeGenApi
13912 */
13913function ɵɵelementEnd() {
13914 let previousOrParentTNode = getPreviousOrParentTNode();
13915 ngDevMode && assertDefined(previousOrParentTNode, 'No parent node to close.');
13916 if (getIsParent()) {
13917 setIsNotParent();
13918 }
13919 else {
13920 ngDevMode && assertHasParent(getPreviousOrParentTNode());
13921 previousOrParentTNode = previousOrParentTNode.parent;
13922 setPreviousOrParentTNode(previousOrParentTNode, false);
13923 }
13924 const tNode = previousOrParentTNode;
13925 ngDevMode && assertNodeType(tNode, 3 /* Element */);
13926 decreaseElementDepthCount();
13927 const tView = getTView();
13928 if (tView.firstCreatePass) {
13929 registerPostOrderHooks(tView, previousOrParentTNode);
13930 if (isContentQueryHost(previousOrParentTNode)) {
13931 tView.queries.elementEnd(previousOrParentTNode);
13932 }
13933 }
13934 if (tNode.classesWithoutHost != null && hasClassInput(tNode)) {
13935 setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.classesWithoutHost, true);
13936 }
13937 if (tNode.stylesWithoutHost != null && hasStyleInput(tNode)) {
13938 setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.stylesWithoutHost, false);
13939 }
13940}
13941/**
13942 * Creates an empty element using {@link elementStart} and {@link elementEnd}
13943 *
13944 * @param index Index of the element in the data array
13945 * @param name Name of the DOM Node
13946 * @param attrsIndex Index of the element's attributes in the `consts` array.
13947 * @param localRefsIndex Index of the element's local references in the `consts` array.
13948 *
13949 * @codeGenApi
13950 */
13951function ɵɵelement(index, name, attrsIndex, localRefsIndex) {
13952 ɵɵelementStart(index, name, attrsIndex, localRefsIndex);
13953 ɵɵelementEnd();
13954}
13955function logUnknownElementError(tView, element, tNode, hasDirectives) {
13956 const schemas = tView.schemas;
13957 // If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
13958 // mode where this check happens at compile time. In JIT mode, `schemas` is always present and
13959 // defined as an array (as an empty array in case `schemas` field is not defined) and we should
13960 // execute the check below.
13961 if (schemas === null)
13962 return;
13963 const tagName = tNode.tagName;
13964 // If the element matches any directive, it's considered as valid.
13965 if (!hasDirectives && tagName !== null) {
13966 // The element is unknown if it's an instance of HTMLUnknownElement or it isn't registered
13967 // as a custom element. Note that unknown elements with a dash in their name won't be instances
13968 // of HTMLUnknownElement in browsers that support web components.
13969 const isUnknown =
13970 // Note that we can't check for `typeof HTMLUnknownElement === 'function'`,
13971 // because while most browsers return 'function', IE returns 'object'.
13972 (typeof HTMLUnknownElement !== 'undefined' && HTMLUnknownElement &&
13973 element instanceof HTMLUnknownElement) ||
13974 (typeof customElements !== 'undefined' && tagName.indexOf('-') > -1 &&
13975 !customElements.get(tagName));
13976 if (isUnknown && !matchingSchemas(tView, tagName)) {
13977 let message = `'${tagName}' is not a known element:\n`;
13978 message += `1. If '${tagName}' is an Angular component, then verify that it is part of this module.\n`;
13979 if (tagName && tagName.indexOf('-') > -1) {
13980 message += `2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`;
13981 }
13982 else {
13983 message +=
13984 `2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;
13985 }
13986 console.error(message);
13987 }
13988 }
13989}
13990
13991/**
13992 * @license
13993 * Copyright Google LLC All Rights Reserved.
13994 *
13995 * Use of this source code is governed by an MIT-style license that can be
13996 * found in the LICENSE file at https://angular.io/license
13997 */
13998function elementContainerStartFirstCreatePass(index, tView, lView, attrsIndex, localRefsIndex) {
13999 ngDevMode && ngDevMode.firstCreatePass++;
14000 const tViewConsts = tView.consts;
14001 const attrs = getConstant(tViewConsts, attrsIndex);
14002 const tNode = getOrCreateTNode(tView, lView[T_HOST], index, 4 /* ElementContainer */, 'ng-container', attrs);
14003 // While ng-container doesn't necessarily support styling, we use the style context to identify
14004 // and execute directives on the ng-container.
14005 if (attrs !== null) {
14006 computeStaticStyling(tNode, attrs, true);
14007 }
14008 const localRefs = getConstant(tViewConsts, localRefsIndex);
14009 resolveDirectives(tView, lView, tNode, localRefs);
14010 if (tView.queries !== null) {
14011 tView.queries.elementStart(tView, tNode);
14012 }
14013 return tNode;
14014}
14015/**
14016 * Creates a logical container for other nodes (<ng-container>) backed by a comment node in the DOM.
14017 * The instruction must later be followed by `elementContainerEnd()` call.
14018 *
14019 * @param index Index of the element in the LView array
14020 * @param attrsIndex Index of the container attributes in the `consts` array.
14021 * @param localRefsIndex Index of the container's local references in the `consts` array.
14022 *
14023 * Even if this instruction accepts a set of attributes no actual attribute values are propagated to
14024 * the DOM (as a comment node can't have attributes). Attributes are here only for directive
14025 * matching purposes and setting initial inputs of directives.
14026 *
14027 * @codeGenApi
14028 */
14029function ɵɵelementContainerStart(index, attrsIndex, localRefsIndex) {
14030 const lView = getLView();
14031 const tView = getTView();
14032 const adjustedIndex = index + HEADER_OFFSET;
14033 ngDevMode && assertIndexInRange(lView, adjustedIndex);
14034 ngDevMode &&
14035 assertEqual(getBindingIndex(), tView.bindingStartIndex, 'element containers should be created before any bindings');
14036 const tNode = tView.firstCreatePass ?
14037 elementContainerStartFirstCreatePass(index, tView, lView, attrsIndex, localRefsIndex) :
14038 tView.data[adjustedIndex];
14039 setPreviousOrParentTNode(tNode, true);
14040 ngDevMode && ngDevMode.rendererCreateComment++;
14041 const native = lView[adjustedIndex] =
14042 lView[RENDERER].createComment(ngDevMode ? 'ng-container' : '');
14043 appendChild(tView, lView, native, tNode);
14044 attachPatchData(native, lView);
14045 if (isDirectiveHost(tNode)) {
14046 createDirectivesInstances(tView, lView, tNode);
14047 executeContentQueries(tView, tNode, lView);
14048 }
14049 if (localRefsIndex != null) {
14050 saveResolvedLocalsInData(lView, tNode);
14051 }
14052}
14053/**
14054 * Mark the end of the <ng-container>.
14055 *
14056 * @codeGenApi
14057 */
14058function ɵɵelementContainerEnd() {
14059 let previousOrParentTNode = getPreviousOrParentTNode();
14060 const tView = getTView();
14061 if (getIsParent()) {
14062 setIsNotParent();
14063 }
14064 else {
14065 ngDevMode && assertHasParent(previousOrParentTNode);
14066 previousOrParentTNode = previousOrParentTNode.parent;
14067 setPreviousOrParentTNode(previousOrParentTNode, false);
14068 }
14069 ngDevMode && assertNodeType(previousOrParentTNode, 4 /* ElementContainer */);
14070 if (tView.firstCreatePass) {
14071 registerPostOrderHooks(tView, previousOrParentTNode);
14072 if (isContentQueryHost(previousOrParentTNode)) {
14073 tView.queries.elementEnd(previousOrParentTNode);
14074 }
14075 }
14076}
14077/**
14078 * Creates an empty logical container using {@link elementContainerStart}
14079 * and {@link elementContainerEnd}
14080 *
14081 * @param index Index of the element in the LView array
14082 * @param attrsIndex Index of the container attributes in the `consts` array.
14083 * @param localRefsIndex Index of the container's local references in the `consts` array.
14084 *
14085 * @codeGenApi
14086 */
14087function ɵɵelementContainer(index, attrsIndex, localRefsIndex) {
14088 ɵɵelementContainerStart(index, attrsIndex, localRefsIndex);
14089 ɵɵelementContainerEnd();
14090}
14091
14092/**
14093 * Returns the current OpaqueViewState instance.
14094 *
14095 * Used in conjunction with the restoreView() instruction to save a snapshot
14096 * of the current view and restore it when listeners are invoked. This allows
14097 * walking the declaration view tree in listeners to get vars from parent views.
14098 *
14099 * @codeGenApi
14100 */
14101function ɵɵgetCurrentView() {
14102 return getLView();
14103}
14104
14105/**
14106 * @license
14107 * Copyright Google LLC All Rights Reserved.
14108 *
14109 * Use of this source code is governed by an MIT-style license that can be
14110 * found in the LICENSE file at https://angular.io/license
14111 */
14112/**
14113 * Determine if the argument is shaped like a Promise
14114 */
14115function isPromise(obj) {
14116 // allow any Promise/A+ compliant thenable.
14117 // It's up to the caller to ensure that obj.then conforms to the spec
14118 return !!obj && typeof obj.then === 'function';
14119}
14120/**
14121 * Determine if the argument is an Observable
14122 */
14123function isObservable(obj) {
14124 // TODO: use isObservable once we update pass rxjs 6.1
14125 // https://github.com/ReactiveX/rxjs/blob/master/CHANGELOG.md#610-2018-05-03
14126 return !!obj && typeof obj.subscribe === 'function';
14127}
14128
14129/**
14130 * @license
14131 * Copyright Google LLC All Rights Reserved.
14132 *
14133 * Use of this source code is governed by an MIT-style license that can be
14134 * found in the LICENSE file at https://angular.io/license
14135 */
14136/**
14137 * Adds an event listener to the current node.
14138 *
14139 * If an output exists on one of the node's directives, it also subscribes to the output
14140 * and saves the subscription for later cleanup.
14141 *
14142 * @param eventName Name of the event
14143 * @param listenerFn The function to be called when event emits
14144 * @param useCapture Whether or not to use capture in event listener
14145 * @param eventTargetResolver Function that returns global target information in case this listener
14146 * should be attached to a global object like window, document or body
14147 *
14148 * @codeGenApi
14149 */
14150function ɵɵlistener(eventName, listenerFn, useCapture = false, eventTargetResolver) {
14151 const lView = getLView();
14152 const tView = getTView();
14153 const tNode = getPreviousOrParentTNode();
14154 listenerInternal(tView, lView, lView[RENDERER], tNode, eventName, listenerFn, useCapture, eventTargetResolver);
14155 return ɵɵlistener;
14156}
14157/**
14158 * Registers a synthetic host listener (e.g. `(@foo.start)`) on a component or directive.
14159 *
14160 * This instruction is for compatibility purposes and is designed to ensure that a
14161 * synthetic host listener (e.g. `@HostListener('@foo.start')`) properly gets rendered
14162 * in the component's renderer. Normally all host listeners are evaluated with the
14163 * parent component's renderer, but, in the case of animation @triggers, they need
14164 * to be evaluated with the sub component's renderer (because that's where the
14165 * animation triggers are defined).
14166 *
14167 * Do not use this instruction as a replacement for `listener`. This instruction
14168 * only exists to ensure compatibility with the ViewEngine's host binding behavior.
14169 *
14170 * @param eventName Name of the event
14171 * @param listenerFn The function to be called when event emits
14172 * @param useCapture Whether or not to use capture in event listener
14173 * @param eventTargetResolver Function that returns global target information in case this listener
14174 * should be attached to a global object like window, document or body
14175 *
14176 * @codeGenApi
14177 */
14178function ɵɵsyntheticHostListener(eventName, listenerFn, useCapture = false, eventTargetResolver) {
14179 const tNode = getPreviousOrParentTNode();
14180 const lView = getLView();
14181 const tView = getTView();
14182 const currentDef = getCurrentDirectiveDef(tView.data);
14183 const renderer = loadComponentRenderer(currentDef, tNode, lView);
14184 listenerInternal(tView, lView, renderer, tNode, eventName, listenerFn, useCapture, eventTargetResolver);
14185 return ɵɵsyntheticHostListener;
14186}
14187/**
14188 * A utility function that checks if a given element has already an event handler registered for an
14189 * event with a specified name. The TView.cleanup data structure is used to find out which events
14190 * are registered for a given element.
14191 */
14192function findExistingListener(tView, lView, eventName, tNodeIdx) {
14193 const tCleanup = tView.cleanup;
14194 if (tCleanup != null) {
14195 for (let i = 0; i < tCleanup.length - 1; i += 2) {
14196 const cleanupEventName = tCleanup[i];
14197 if (cleanupEventName === eventName && tCleanup[i + 1] === tNodeIdx) {
14198 // We have found a matching event name on the same node but it might not have been
14199 // registered yet, so we must explicitly verify entries in the LView cleanup data
14200 // structures.
14201 const lCleanup = lView[CLEANUP];
14202 const listenerIdxInLCleanup = tCleanup[i + 2];
14203 return lCleanup.length > listenerIdxInLCleanup ? lCleanup[listenerIdxInLCleanup] : null;
14204 }
14205 // TView.cleanup can have a mix of 4-elements entries (for event handler cleanups) or
14206 // 2-element entries (for directive and queries destroy hooks). As such we can encounter
14207 // blocks of 4 or 2 items in the tView.cleanup and this is why we iterate over 2 elements
14208 // first and jump another 2 elements if we detect listeners cleanup (4 elements). Also check
14209 // documentation of TView.cleanup for more details of this data structure layout.
14210 if (typeof cleanupEventName === 'string') {
14211 i += 2;
14212 }
14213 }
14214 }
14215 return null;
14216}
14217function listenerInternal(tView, lView, renderer, tNode, eventName, listenerFn, useCapture = false, eventTargetResolver) {
14218 const isTNodeDirectiveHost = isDirectiveHost(tNode);
14219 const firstCreatePass = tView.firstCreatePass;
14220 const tCleanup = firstCreatePass && (tView.cleanup || (tView.cleanup = []));
14221 // When the ɵɵlistener instruction was generated and is executed we know that there is either a
14222 // native listener or a directive output on this element. As such we we know that we will have to
14223 // register a listener and store its cleanup function on LView.
14224 const lCleanup = getLCleanup(lView);
14225 ngDevMode &&
14226 assertNodeOfPossibleTypes(tNode, [3 /* Element */, 0 /* Container */, 4 /* ElementContainer */]);
14227 let processOutputs = true;
14228 // add native event listener - applicable to elements only
14229 if (tNode.type === 3 /* Element */) {
14230 const native = getNativeByTNode(tNode, lView);
14231 const resolved = eventTargetResolver ? eventTargetResolver(native) : EMPTY_OBJ;
14232 const target = resolved.target || native;
14233 const lCleanupIndex = lCleanup.length;
14234 const idxOrTargetGetter = eventTargetResolver ?
14235 (_lView) => eventTargetResolver(unwrapRNode(_lView[tNode.index])).target :
14236 tNode.index;
14237 // In order to match current behavior, native DOM event listeners must be added for all
14238 // events (including outputs).
14239 if (isProceduralRenderer(renderer)) {
14240 // There might be cases where multiple directives on the same element try to register an event
14241 // handler function for the same event. In this situation we want to avoid registration of
14242 // several native listeners as each registration would be intercepted by NgZone and
14243 // trigger change detection. This would mean that a single user action would result in several
14244 // change detections being invoked. To avoid this situation we want to have only one call to
14245 // native handler registration (for the same element and same type of event).
14246 //
14247 // In order to have just one native event handler in presence of multiple handler functions,
14248 // we just register a first handler function as a native event listener and then chain
14249 // (coalesce) other handler functions on top of the first native handler function.
14250 let existingListener = null;
14251 // Please note that the coalescing described here doesn't happen for events specifying an
14252 // alternative target (ex. (document:click)) - this is to keep backward compatibility with the
14253 // view engine.
14254 // Also, we don't have to search for existing listeners is there are no directives
14255 // matching on a given node as we can't register multiple event handlers for the same event in
14256 // a template (this would mean having duplicate attributes).
14257 if (!eventTargetResolver && isTNodeDirectiveHost) {
14258 existingListener = findExistingListener(tView, lView, eventName, tNode.index);
14259 }
14260 if (existingListener !== null) {
14261 // Attach a new listener to coalesced listeners list, maintaining the order in which
14262 // listeners are registered. For performance reasons, we keep a reference to the last
14263 // listener in that list (in `__ngLastListenerFn__` field), so we can avoid going through
14264 // the entire set each time we need to add a new listener.
14265 const lastListenerFn = existingListener.__ngLastListenerFn__ || existingListener;
14266 lastListenerFn.__ngNextListenerFn__ = listenerFn;
14267 existingListener.__ngLastListenerFn__ = listenerFn;
14268 processOutputs = false;
14269 }
14270 else {
14271 // The first argument of `listen` function in Procedural Renderer is:
14272 // - either a target name (as a string) in case of global target (window, document, body)
14273 // - or element reference (in all other cases)
14274 listenerFn = wrapListener(tNode, lView, listenerFn, false /** preventDefault */);
14275 const cleanupFn = renderer.listen(resolved.name || target, eventName, listenerFn);
14276 ngDevMode && ngDevMode.rendererAddEventListener++;
14277 lCleanup.push(listenerFn, cleanupFn);
14278 tCleanup && tCleanup.push(eventName, idxOrTargetGetter, lCleanupIndex, lCleanupIndex + 1);
14279 }
14280 }
14281 else {
14282 listenerFn = wrapListener(tNode, lView, listenerFn, true /** preventDefault */);
14283 target.addEventListener(eventName, listenerFn, useCapture);
14284 ngDevMode && ngDevMode.rendererAddEventListener++;
14285 lCleanup.push(listenerFn);
14286 tCleanup && tCleanup.push(eventName, idxOrTargetGetter, lCleanupIndex, useCapture);
14287 }
14288 }
14289 // subscribe to directive outputs
14290 const outputs = tNode.outputs;
14291 let props;
14292 if (processOutputs && outputs !== null && (props = outputs[eventName])) {
14293 const propsLength = props.length;
14294 if (propsLength) {
14295 for (let i = 0; i < propsLength; i += 2) {
14296 const index = props[i];
14297 ngDevMode && assertIndexInRange(lView, index);
14298 const minifiedName = props[i + 1];
14299 const directiveInstance = lView[index];
14300 const output = directiveInstance[minifiedName];
14301 if (ngDevMode && !isObservable(output)) {
14302 throw new Error(`@Output ${minifiedName} not initialized in '${directiveInstance.constructor.name}'.`);
14303 }
14304 const subscription = output.subscribe(listenerFn);
14305 const idx = lCleanup.length;
14306 lCleanup.push(listenerFn, subscription);
14307 tCleanup && tCleanup.push(eventName, tNode.index, idx, -(idx + 1));
14308 }
14309 }
14310 }
14311}
14312function executeListenerWithErrorHandling(lView, listenerFn, e) {
14313 try {
14314 // Only explicitly returning false from a listener should preventDefault
14315 return listenerFn(e) !== false;
14316 }
14317 catch (error) {
14318 handleError(lView, error);
14319 return false;
14320 }
14321}
14322/**
14323 * Wraps an event listener with a function that marks ancestors dirty and prevents default behavior,
14324 * if applicable.
14325 *
14326 * @param tNode The TNode associated with this listener
14327 * @param lView The LView that contains this listener
14328 * @param listenerFn The listener function to call
14329 * @param wrapWithPreventDefault Whether or not to prevent default behavior
14330 * (the procedural renderer does this already, so in those cases, we should skip)
14331 */
14332function wrapListener(tNode, lView, listenerFn, wrapWithPreventDefault) {
14333 // Note: we are performing most of the work in the listener function itself
14334 // to optimize listener registration.
14335 return function wrapListenerIn_markDirtyAndPreventDefault(e) {
14336 // Ivy uses `Function` as a special token that allows us to unwrap the function
14337 // so that it can be invoked programmatically by `DebugNode.triggerEventHandler`.
14338 if (e === Function) {
14339 return listenerFn;
14340 }
14341 // In order to be backwards compatible with View Engine, events on component host nodes
14342 // must also mark the component view itself dirty (i.e. the view that it owns).
14343 const startView = tNode.flags & 2 /* isComponentHost */ ?
14344 getComponentLViewByIndex(tNode.index, lView) :
14345 lView;
14346 // See interfaces/view.ts for more on LViewFlags.ManualOnPush
14347 if ((lView[FLAGS] & 32 /* ManualOnPush */) === 0) {
14348 markViewDirty(startView);
14349 }
14350 let result = executeListenerWithErrorHandling(lView, listenerFn, e);
14351 // A just-invoked listener function might have coalesced listeners so we need to check for
14352 // their presence and invoke as needed.
14353 let nextListenerFn = wrapListenerIn_markDirtyAndPreventDefault.__ngNextListenerFn__;
14354 while (nextListenerFn) {
14355 // We should prevent default if any of the listeners explicitly return false
14356 result = executeListenerWithErrorHandling(lView, nextListenerFn, e) && result;
14357 nextListenerFn = nextListenerFn.__ngNextListenerFn__;
14358 }
14359 if (wrapWithPreventDefault && result === false) {
14360 e.preventDefault();
14361 // Necessary for legacy browsers that don't support preventDefault (e.g. IE)
14362 e.returnValue = false;
14363 }
14364 return result;
14365 };
14366}
14367
14368/**
14369 * @license
14370 * Copyright Google LLC All Rights Reserved.
14371 *
14372 * Use of this source code is governed by an MIT-style license that can be
14373 * found in the LICENSE file at https://angular.io/license
14374 */
14375
14376/**
14377 * @license
14378 * Copyright Google LLC All Rights Reserved.
14379 *
14380 * Use of this source code is governed by an MIT-style license that can be
14381 * found in the LICENSE file at https://angular.io/license
14382 */
14383/**
14384 * Retrieves a context at the level specified and saves it as the global, contextViewData.
14385 * Will get the next level up if level is not specified.
14386 *
14387 * This is used to save contexts of parent views so they can be bound in embedded views, or
14388 * in conjunction with reference() to bind a ref from a parent view.
14389 *
14390 * @param level The relative level of the view from which to grab context compared to contextVewData
14391 * @returns context
14392 *
14393 * @codeGenApi
14394 */
14395function ɵɵnextContext(level = 1) {
14396 return nextContextImpl(level);
14397}
14398
14399/**
14400 * @license
14401 * Copyright Google LLC All Rights Reserved.
14402 *
14403 * Use of this source code is governed by an MIT-style license that can be
14404 * found in the LICENSE file at https://angular.io/license
14405 */
14406/**
14407 * Checks a given node against matching projection slots and returns the
14408 * determined slot index. Returns "null" if no slot matched the given node.
14409 *
14410 * This function takes into account the parsed ngProjectAs selector from the
14411 * node's attributes. If present, it will check whether the ngProjectAs selector
14412 * matches any of the projection slot selectors.
14413 */
14414function matchingProjectionSlotIndex(tNode, projectionSlots) {
14415 let wildcardNgContentIndex = null;
14416 const ngProjectAsAttrVal = getProjectAsAttrValue(tNode);
14417 for (let i = 0; i < projectionSlots.length; i++) {
14418 const slotValue = projectionSlots[i];
14419 // The last wildcard projection slot should match all nodes which aren't matching
14420 // any selector. This is necessary to be backwards compatible with view engine.
14421 if (slotValue === '*') {
14422 wildcardNgContentIndex = i;
14423 continue;
14424 }
14425 // If we ran into an `ngProjectAs` attribute, we should match its parsed selector
14426 // to the list of selectors, otherwise we fall back to matching against the node.
14427 if (ngProjectAsAttrVal === null ?
14428 isNodeMatchingSelectorList(tNode, slotValue, /* isProjectionMode */ true) :
14429 isSelectorInSelectorList(ngProjectAsAttrVal, slotValue)) {
14430 return i; // first matching selector "captures" a given node
14431 }
14432 }
14433 return wildcardNgContentIndex;
14434}
14435/**
14436 * Instruction to distribute projectable nodes among <ng-content> occurrences in a given template.
14437 * It takes all the selectors from the entire component's template and decides where
14438 * each projected node belongs (it re-distributes nodes among "buckets" where each "bucket" is
14439 * backed by a selector).
14440 *
14441 * This function requires CSS selectors to be provided in 2 forms: parsed (by a compiler) and text,
14442 * un-parsed form.
14443 *
14444 * The parsed form is needed for efficient matching of a node against a given CSS selector.
14445 * The un-parsed, textual form is needed for support of the ngProjectAs attribute.
14446 *
14447 * Having a CSS selector in 2 different formats is not ideal, but alternatives have even more
14448 * drawbacks:
14449 * - having only a textual form would require runtime parsing of CSS selectors;
14450 * - we can't have only a parsed as we can't re-construct textual form from it (as entered by a
14451 * template author).
14452 *
14453 * @param projectionSlots? A collection of projection slots. A projection slot can be based
14454 * on a parsed CSS selectors or set to the wildcard selector ("*") in order to match
14455 * all nodes which do not match any selector. If not specified, a single wildcard
14456 * selector projection slot will be defined.
14457 *
14458 * @codeGenApi
14459 */
14460function ɵɵprojectionDef(projectionSlots) {
14461 const componentNode = getLView()[DECLARATION_COMPONENT_VIEW][T_HOST];
14462 if (!componentNode.projection) {
14463 // If no explicit projection slots are defined, fall back to a single
14464 // projection slot with the wildcard selector.
14465 const numProjectionSlots = projectionSlots ? projectionSlots.length : 1;
14466 const projectionHeads = componentNode.projection =
14467 newArray(numProjectionSlots, null);
14468 const tails = projectionHeads.slice();
14469 let componentChild = componentNode.child;
14470 while (componentChild !== null) {
14471 const slotIndex = projectionSlots ? matchingProjectionSlotIndex(componentChild, projectionSlots) : 0;
14472 if (slotIndex !== null) {
14473 if (tails[slotIndex]) {
14474 tails[slotIndex].projectionNext = componentChild;
14475 }
14476 else {
14477 projectionHeads[slotIndex] = componentChild;
14478 }
14479 tails[slotIndex] = componentChild;
14480 }
14481 componentChild = componentChild.next;
14482 }
14483 }
14484}
14485let delayProjection = false;
14486function setDelayProjection(value) {
14487 delayProjection = value;
14488}
14489/**
14490 * Inserts previously re-distributed projected nodes. This instruction must be preceded by a call
14491 * to the projectionDef instruction.
14492 *
14493 * @param nodeIndex
14494 * @param selectorIndex:
14495 * - 0 when the selector is `*` (or unspecified as this is the default value),
14496 * - 1 based index of the selector from the {@link projectionDef}
14497 *
14498 * @codeGenApi
14499 */
14500function ɵɵprojection(nodeIndex, selectorIndex = 0, attrs) {
14501 const lView = getLView();
14502 const tView = getTView();
14503 const tProjectionNode = getOrCreateTNode(tView, lView[T_HOST], nodeIndex, 1 /* Projection */, null, attrs || null);
14504 // We can't use viewData[HOST_NODE] because projection nodes can be nested in embedded views.
14505 if (tProjectionNode.projection === null)
14506 tProjectionNode.projection = selectorIndex;
14507 // `<ng-content>` has no content
14508 setIsNotParent();
14509 // We might need to delay the projection of nodes if they are in the middle of an i18n block
14510 if (!delayProjection) {
14511 // re-distribution of projectable nodes is stored on a component's view level
14512 applyProjection(tView, lView, tProjectionNode);
14513 }
14514}
14515
14516/**
14517 *
14518 * Update an interpolated property on an element with a lone bound value
14519 *
14520 * Used when the value passed to a property has 1 interpolated value in it, an no additional text
14521 * surrounds that interpolated value:
14522 *
14523 * ```html
14524 * <div title="{{v0}}"></div>
14525 * ```
14526 *
14527 * Its compiled representation is::
14528 *
14529 * ```ts
14530 * ɵɵpropertyInterpolate('title', v0);
14531 * ```
14532 *
14533 * If the property name also exists as an input property on one of the element's directives,
14534 * the component property will be set instead of the element property. This check must
14535 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
14536 *
14537 * @param propName The name of the property to update
14538 * @param prefix Static value used for concatenation only.
14539 * @param v0 Value checked for change.
14540 * @param suffix Static value used for concatenation only.
14541 * @param sanitizer An optional sanitizer function
14542 * @returns itself, so that it may be chained.
14543 * @codeGenApi
14544 */
14545function ɵɵpropertyInterpolate(propName, v0, sanitizer) {
14546 ɵɵpropertyInterpolate1(propName, '', v0, '', sanitizer);
14547 return ɵɵpropertyInterpolate;
14548}
14549/**
14550 *
14551 * Update an interpolated property on an element with single bound value surrounded by text.
14552 *
14553 * Used when the value passed to a property has 1 interpolated value in it:
14554 *
14555 * ```html
14556 * <div title="prefix{{v0}}suffix"></div>
14557 * ```
14558 *
14559 * Its compiled representation is::
14560 *
14561 * ```ts
14562 * ɵɵpropertyInterpolate1('title', 'prefix', v0, 'suffix');
14563 * ```
14564 *
14565 * If the property name also exists as an input property on one of the element's directives,
14566 * the component property will be set instead of the element property. This check must
14567 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
14568 *
14569 * @param propName The name of the property to update
14570 * @param prefix Static value used for concatenation only.
14571 * @param v0 Value checked for change.
14572 * @param suffix Static value used for concatenation only.
14573 * @param sanitizer An optional sanitizer function
14574 * @returns itself, so that it may be chained.
14575 * @codeGenApi
14576 */
14577function ɵɵpropertyInterpolate1(propName, prefix, v0, suffix, sanitizer) {
14578 const lView = getLView();
14579 const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
14580 if (interpolatedValue !== NO_CHANGE) {
14581 const tView = getTView();
14582 const tNode = getSelectedTNode();
14583 elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
14584 ngDevMode &&
14585 storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 1, prefix, suffix);
14586 }
14587 return ɵɵpropertyInterpolate1;
14588}
14589/**
14590 *
14591 * Update an interpolated property on an element with 2 bound values surrounded by text.
14592 *
14593 * Used when the value passed to a property has 2 interpolated values in it:
14594 *
14595 * ```html
14596 * <div title="prefix{{v0}}-{{v1}}suffix"></div>
14597 * ```
14598 *
14599 * Its compiled representation is::
14600 *
14601 * ```ts
14602 * ɵɵpropertyInterpolate2('title', 'prefix', v0, '-', v1, 'suffix');
14603 * ```
14604 *
14605 * If the property name also exists as an input property on one of the element's directives,
14606 * the component property will be set instead of the element property. This check must
14607 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
14608 *
14609 * @param propName The name of the property to update
14610 * @param prefix Static value used for concatenation only.
14611 * @param v0 Value checked for change.
14612 * @param i0 Static value used for concatenation only.
14613 * @param v1 Value checked for change.
14614 * @param suffix Static value used for concatenation only.
14615 * @param sanitizer An optional sanitizer function
14616 * @returns itself, so that it may be chained.
14617 * @codeGenApi
14618 */
14619function ɵɵpropertyInterpolate2(propName, prefix, v0, i0, v1, suffix, sanitizer) {
14620 const lView = getLView();
14621 const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
14622 if (interpolatedValue !== NO_CHANGE) {
14623 const tView = getTView();
14624 const tNode = getSelectedTNode();
14625 elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
14626 ngDevMode &&
14627 storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 2, prefix, i0, suffix);
14628 }
14629 return ɵɵpropertyInterpolate2;
14630}
14631/**
14632 *
14633 * Update an interpolated property on an element with 3 bound values surrounded by text.
14634 *
14635 * Used when the value passed to a property has 3 interpolated values in it:
14636 *
14637 * ```html
14638 * <div title="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
14639 * ```
14640 *
14641 * Its compiled representation is::
14642 *
14643 * ```ts
14644 * ɵɵpropertyInterpolate3(
14645 * 'title', 'prefix', v0, '-', v1, '-', v2, 'suffix');
14646 * ```
14647 *
14648 * If the property name also exists as an input property on one of the element's directives,
14649 * the component property will be set instead of the element property. This check must
14650 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
14651 *
14652 * @param propName The name of the property to update
14653 * @param prefix Static value used for concatenation only.
14654 * @param v0 Value checked for change.
14655 * @param i0 Static value used for concatenation only.
14656 * @param v1 Value checked for change.
14657 * @param i1 Static value used for concatenation only.
14658 * @param v2 Value checked for change.
14659 * @param suffix Static value used for concatenation only.
14660 * @param sanitizer An optional sanitizer function
14661 * @returns itself, so that it may be chained.
14662 * @codeGenApi
14663 */
14664function ɵɵpropertyInterpolate3(propName, prefix, v0, i0, v1, i1, v2, suffix, sanitizer) {
14665 const lView = getLView();
14666 const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
14667 if (interpolatedValue !== NO_CHANGE) {
14668 const tView = getTView();
14669 const tNode = getSelectedTNode();
14670 elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
14671 ngDevMode &&
14672 storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 3, prefix, i0, i1, suffix);
14673 }
14674 return ɵɵpropertyInterpolate3;
14675}
14676/**
14677 *
14678 * Update an interpolated property on an element with 4 bound values surrounded by text.
14679 *
14680 * Used when the value passed to a property has 4 interpolated values in it:
14681 *
14682 * ```html
14683 * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
14684 * ```
14685 *
14686 * Its compiled representation is::
14687 *
14688 * ```ts
14689 * ɵɵpropertyInterpolate4(
14690 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
14691 * ```
14692 *
14693 * If the property name also exists as an input property on one of the element's directives,
14694 * the component property will be set instead of the element property. This check must
14695 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
14696 *
14697 * @param propName The name of the property to update
14698 * @param prefix Static value used for concatenation only.
14699 * @param v0 Value checked for change.
14700 * @param i0 Static value used for concatenation only.
14701 * @param v1 Value checked for change.
14702 * @param i1 Static value used for concatenation only.
14703 * @param v2 Value checked for change.
14704 * @param i2 Static value used for concatenation only.
14705 * @param v3 Value checked for change.
14706 * @param suffix Static value used for concatenation only.
14707 * @param sanitizer An optional sanitizer function
14708 * @returns itself, so that it may be chained.
14709 * @codeGenApi
14710 */
14711function ɵɵpropertyInterpolate4(propName, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, sanitizer) {
14712 const lView = getLView();
14713 const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
14714 if (interpolatedValue !== NO_CHANGE) {
14715 const tView = getTView();
14716 const tNode = getSelectedTNode();
14717 elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
14718 ngDevMode &&
14719 storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 4, prefix, i0, i1, i2, suffix);
14720 }
14721 return ɵɵpropertyInterpolate4;
14722}
14723/**
14724 *
14725 * Update an interpolated property on an element with 5 bound values surrounded by text.
14726 *
14727 * Used when the value passed to a property has 5 interpolated values in it:
14728 *
14729 * ```html
14730 * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
14731 * ```
14732 *
14733 * Its compiled representation is::
14734 *
14735 * ```ts
14736 * ɵɵpropertyInterpolate5(
14737 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
14738 * ```
14739 *
14740 * If the property name also exists as an input property on one of the element's directives,
14741 * the component property will be set instead of the element property. This check must
14742 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
14743 *
14744 * @param propName The name of the property to update
14745 * @param prefix Static value used for concatenation only.
14746 * @param v0 Value checked for change.
14747 * @param i0 Static value used for concatenation only.
14748 * @param v1 Value checked for change.
14749 * @param i1 Static value used for concatenation only.
14750 * @param v2 Value checked for change.
14751 * @param i2 Static value used for concatenation only.
14752 * @param v3 Value checked for change.
14753 * @param i3 Static value used for concatenation only.
14754 * @param v4 Value checked for change.
14755 * @param suffix Static value used for concatenation only.
14756 * @param sanitizer An optional sanitizer function
14757 * @returns itself, so that it may be chained.
14758 * @codeGenApi
14759 */
14760function ɵɵpropertyInterpolate5(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, sanitizer) {
14761 const lView = getLView();
14762 const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
14763 if (interpolatedValue !== NO_CHANGE) {
14764 const tView = getTView();
14765 const tNode = getSelectedTNode();
14766 elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
14767 ngDevMode &&
14768 storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 5, prefix, i0, i1, i2, i3, suffix);
14769 }
14770 return ɵɵpropertyInterpolate5;
14771}
14772/**
14773 *
14774 * Update an interpolated property on an element with 6 bound values surrounded by text.
14775 *
14776 * Used when the value passed to a property has 6 interpolated values in it:
14777 *
14778 * ```html
14779 * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
14780 * ```
14781 *
14782 * Its compiled representation is::
14783 *
14784 * ```ts
14785 * ɵɵpropertyInterpolate6(
14786 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
14787 * ```
14788 *
14789 * If the property name also exists as an input property on one of the element's directives,
14790 * the component property will be set instead of the element property. This check must
14791 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
14792 *
14793 * @param propName The name of the property to update
14794 * @param prefix Static value used for concatenation only.
14795 * @param v0 Value checked for change.
14796 * @param i0 Static value used for concatenation only.
14797 * @param v1 Value checked for change.
14798 * @param i1 Static value used for concatenation only.
14799 * @param v2 Value checked for change.
14800 * @param i2 Static value used for concatenation only.
14801 * @param v3 Value checked for change.
14802 * @param i3 Static value used for concatenation only.
14803 * @param v4 Value checked for change.
14804 * @param i4 Static value used for concatenation only.
14805 * @param v5 Value checked for change.
14806 * @param suffix Static value used for concatenation only.
14807 * @param sanitizer An optional sanitizer function
14808 * @returns itself, so that it may be chained.
14809 * @codeGenApi
14810 */
14811function ɵɵpropertyInterpolate6(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, sanitizer) {
14812 const lView = getLView();
14813 const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
14814 if (interpolatedValue !== NO_CHANGE) {
14815 const tView = getTView();
14816 const tNode = getSelectedTNode();
14817 elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
14818 ngDevMode &&
14819 storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 6, prefix, i0, i1, i2, i3, i4, suffix);
14820 }
14821 return ɵɵpropertyInterpolate6;
14822}
14823/**
14824 *
14825 * Update an interpolated property on an element with 7 bound values surrounded by text.
14826 *
14827 * Used when the value passed to a property has 7 interpolated values in it:
14828 *
14829 * ```html
14830 * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
14831 * ```
14832 *
14833 * Its compiled representation is::
14834 *
14835 * ```ts
14836 * ɵɵpropertyInterpolate7(
14837 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
14838 * ```
14839 *
14840 * If the property name also exists as an input property on one of the element's directives,
14841 * the component property will be set instead of the element property. This check must
14842 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
14843 *
14844 * @param propName The name of the property to update
14845 * @param prefix Static value used for concatenation only.
14846 * @param v0 Value checked for change.
14847 * @param i0 Static value used for concatenation only.
14848 * @param v1 Value checked for change.
14849 * @param i1 Static value used for concatenation only.
14850 * @param v2 Value checked for change.
14851 * @param i2 Static value used for concatenation only.
14852 * @param v3 Value checked for change.
14853 * @param i3 Static value used for concatenation only.
14854 * @param v4 Value checked for change.
14855 * @param i4 Static value used for concatenation only.
14856 * @param v5 Value checked for change.
14857 * @param i5 Static value used for concatenation only.
14858 * @param v6 Value checked for change.
14859 * @param suffix Static value used for concatenation only.
14860 * @param sanitizer An optional sanitizer function
14861 * @returns itself, so that it may be chained.
14862 * @codeGenApi
14863 */
14864function ɵɵpropertyInterpolate7(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, sanitizer) {
14865 const lView = getLView();
14866 const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
14867 if (interpolatedValue !== NO_CHANGE) {
14868 const tView = getTView();
14869 const tNode = getSelectedTNode();
14870 elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
14871 ngDevMode &&
14872 storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, i5, suffix);
14873 }
14874 return ɵɵpropertyInterpolate7;
14875}
14876/**
14877 *
14878 * Update an interpolated property on an element with 8 bound values surrounded by text.
14879 *
14880 * Used when the value passed to a property has 8 interpolated values in it:
14881 *
14882 * ```html
14883 * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
14884 * ```
14885 *
14886 * Its compiled representation is::
14887 *
14888 * ```ts
14889 * ɵɵpropertyInterpolate8(
14890 * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
14891 * ```
14892 *
14893 * If the property name also exists as an input property on one of the element's directives,
14894 * the component property will be set instead of the element property. This check must
14895 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
14896 *
14897 * @param propName The name of the property to update
14898 * @param prefix Static value used for concatenation only.
14899 * @param v0 Value checked for change.
14900 * @param i0 Static value used for concatenation only.
14901 * @param v1 Value checked for change.
14902 * @param i1 Static value used for concatenation only.
14903 * @param v2 Value checked for change.
14904 * @param i2 Static value used for concatenation only.
14905 * @param v3 Value checked for change.
14906 * @param i3 Static value used for concatenation only.
14907 * @param v4 Value checked for change.
14908 * @param i4 Static value used for concatenation only.
14909 * @param v5 Value checked for change.
14910 * @param i5 Static value used for concatenation only.
14911 * @param v6 Value checked for change.
14912 * @param i6 Static value used for concatenation only.
14913 * @param v7 Value checked for change.
14914 * @param suffix Static value used for concatenation only.
14915 * @param sanitizer An optional sanitizer function
14916 * @returns itself, so that it may be chained.
14917 * @codeGenApi
14918 */
14919function ɵɵpropertyInterpolate8(propName, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, sanitizer) {
14920 const lView = getLView();
14921 const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
14922 if (interpolatedValue !== NO_CHANGE) {
14923 const tView = getTView();
14924 const tNode = getSelectedTNode();
14925 elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
14926 ngDevMode &&
14927 storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, i5, i6, suffix);
14928 }
14929 return ɵɵpropertyInterpolate8;
14930}
14931/**
14932 * Update an interpolated property on an element with 9 or more bound values surrounded by text.
14933 *
14934 * Used when the number of interpolated values exceeds 8.
14935 *
14936 * ```html
14937 * <div
14938 * title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
14939 * ```
14940 *
14941 * Its compiled representation is::
14942 *
14943 * ```ts
14944 * ɵɵpropertyInterpolateV(
14945 * 'title', ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
14946 * 'suffix']);
14947 * ```
14948 *
14949 * If the property name also exists as an input property on one of the element's directives,
14950 * the component property will be set instead of the element property. This check must
14951 * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled.
14952 *
14953 * @param propName The name of the property to update.
14954 * @param values The collection of values and the strings inbetween those values, beginning with a
14955 * string prefix and ending with a string suffix.
14956 * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
14957 * @param sanitizer An optional sanitizer function
14958 * @returns itself, so that it may be chained.
14959 * @codeGenApi
14960 */
14961function ɵɵpropertyInterpolateV(propName, values, sanitizer) {
14962 const lView = getLView();
14963 const interpolatedValue = interpolationV(lView, values);
14964 if (interpolatedValue !== NO_CHANGE) {
14965 const tView = getTView();
14966 const tNode = getSelectedTNode();
14967 elementPropertyInternal(tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false);
14968 if (ngDevMode) {
14969 const interpolationInBetween = [values[0]]; // prefix
14970 for (let i = 2; i < values.length; i += 2) {
14971 interpolationInBetween.push(values[i]);
14972 }
14973 storePropertyBindingMetadata(tView.data, tNode, propName, getBindingIndex() - interpolationInBetween.length + 1, ...interpolationInBetween);
14974 }
14975 }
14976 return ɵɵpropertyInterpolateV;
14977}
14978
14979/**
14980 * @license
14981 * Copyright Google LLC All Rights Reserved.
14982 *
14983 * Use of this source code is governed by an MIT-style license that can be
14984 * found in the LICENSE file at https://angular.io/license
14985 */
14986/**
14987 * This file contains reuseable "empty" symbols that can be used as default return values
14988 * in different parts of the rendering code. Because the same symbols are returned, this
14989 * allows for identity checks against these values to be consistently used by the framework
14990 * code.
14991 */
14992const EMPTY_OBJ$1 = {};
14993const EMPTY_ARRAY$3 = [];
14994// freezing the values prevents any code from accidentally inserting new values in
14995if ((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode()) {
14996 // These property accesses can be ignored because ngDevMode will be set to false
14997 // when optimizing code and the whole if statement will be dropped.
14998 // tslint:disable-next-line:no-toplevel-property-access
14999 Object.freeze(EMPTY_OBJ$1);
15000 // tslint:disable-next-line:no-toplevel-property-access
15001 Object.freeze(EMPTY_ARRAY$3);
15002}
15003
15004/**
15005 * @license
15006 * Copyright Google LLC All Rights Reserved.
15007 *
15008 * Use of this source code is governed by an MIT-style license that can be
15009 * found in the LICENSE file at https://angular.io/license
15010 */
15011/**
15012 * NOTE: The word `styling` is used interchangeably as style or class styling.
15013 *
15014 * This file contains code to link styling instructions together so that they can be replayed in
15015 * priority order. The file exists because Ivy styling instruction execution order does not match
15016 * that of the priority order. The purpose of this code is to create a linked list so that the
15017 * instructions can be traversed in priority order when computing the styles.
15018 *
15019 * Assume we are dealing with the following code:
15020 * ```
15021 * @Component({
15022 * template: `
15023 * <my-cmp [style]=" {color: '#001'} "
15024 * [style.color]=" #002 "
15025 * dir-style-color-1
15026 * dir-style-color-2> `
15027 * })
15028 * class ExampleComponent {
15029 * static ngComp = ... {
15030 * ...
15031 * // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
15032 * ɵɵstyleMap({color: '#001'});
15033 * ɵɵstyleProp('color', '#002');
15034 * ...
15035 * }
15036 * }
15037 *
15038 * @Directive({
15039 * selector: `[dir-style-color-1]',
15040 * })
15041 * class Style1Directive {
15042 * @HostBinding('style') style = {color: '#005'};
15043 * @HostBinding('style.color') color = '#006';
15044 *
15045 * static ngDir = ... {
15046 * ...
15047 * // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
15048 * ɵɵstyleMap({color: '#005'});
15049 * ɵɵstyleProp('color', '#006');
15050 * ...
15051 * }
15052 * }
15053 *
15054 * @Directive({
15055 * selector: `[dir-style-color-2]',
15056 * })
15057 * class Style2Directive {
15058 * @HostBinding('style') style = {color: '#007'};
15059 * @HostBinding('style.color') color = '#008';
15060 *
15061 * static ngDir = ... {
15062 * ...
15063 * // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
15064 * ɵɵstyleMap({color: '#007'});
15065 * ɵɵstyleProp('color', '#008');
15066 * ...
15067 * }
15068 * }
15069 *
15070 * @Directive({
15071 * selector: `my-cmp',
15072 * })
15073 * class MyComponent {
15074 * @HostBinding('style') style = {color: '#003'};
15075 * @HostBinding('style.color') color = '#004';
15076 *
15077 * static ngComp = ... {
15078 * ...
15079 * // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
15080 * ɵɵstyleMap({color: '#003'});
15081 * ɵɵstyleProp('color', '#004');
15082 * ...
15083 * }
15084 * }
15085 * ```
15086 *
15087 * The Order of instruction execution is:
15088 *
15089 * NOTE: the comment binding location is for illustrative purposes only.
15090 *
15091 * ```
15092 * // Template: (ExampleComponent)
15093 * ɵɵstyleMap({color: '#001'}); // Binding index: 10
15094 * ɵɵstyleProp('color', '#002'); // Binding index: 12
15095 * // MyComponent
15096 * ɵɵstyleMap({color: '#003'}); // Binding index: 20
15097 * ɵɵstyleProp('color', '#004'); // Binding index: 22
15098 * // Style1Directive
15099 * ɵɵstyleMap({color: '#005'}); // Binding index: 24
15100 * ɵɵstyleProp('color', '#006'); // Binding index: 26
15101 * // Style2Directive
15102 * ɵɵstyleMap({color: '#007'}); // Binding index: 28
15103 * ɵɵstyleProp('color', '#008'); // Binding index: 30
15104 * ```
15105 *
15106 * The correct priority order of concatenation is:
15107 *
15108 * ```
15109 * // MyComponent
15110 * ɵɵstyleMap({color: '#003'}); // Binding index: 20
15111 * ɵɵstyleProp('color', '#004'); // Binding index: 22
15112 * // Style1Directive
15113 * ɵɵstyleMap({color: '#005'}); // Binding index: 24
15114 * ɵɵstyleProp('color', '#006'); // Binding index: 26
15115 * // Style2Directive
15116 * ɵɵstyleMap({color: '#007'}); // Binding index: 28
15117 * ɵɵstyleProp('color', '#008'); // Binding index: 30
15118 * // Template: (ExampleComponent)
15119 * ɵɵstyleMap({color: '#001'}); // Binding index: 10
15120 * ɵɵstyleProp('color', '#002'); // Binding index: 12
15121 * ```
15122 *
15123 * What color should be rendered?
15124 *
15125 * Once the items are correctly sorted in the list, the answer is simply the last item in the
15126 * concatenation list which is `#002`.
15127 *
15128 * To do so we keep a linked list of all of the bindings which pertain to this element.
15129 * Notice that the bindings are inserted in the order of execution, but the `TView.data` allows
15130 * us to traverse them in the order of priority.
15131 *
15132 * |Idx|`TView.data`|`LView` | Notes
15133 * |---|------------|-----------------|--------------
15134 * |...| | |
15135 * |10 |`null` |`{color: '#001'}`| `ɵɵstyleMap('color', {color: '#001'})`
15136 * |11 |`30 | 12` | ... |
15137 * |12 |`color` |`'#002'` | `ɵɵstyleProp('color', '#002')`
15138 * |13 |`10 | 0` | ... |
15139 * |...| | |
15140 * |20 |`null` |`{color: '#003'}`| `ɵɵstyleMap('color', {color: '#003'})`
15141 * |21 |`0 | 22` | ... |
15142 * |22 |`color` |`'#004'` | `ɵɵstyleProp('color', '#004')`
15143 * |23 |`20 | 24` | ... |
15144 * |24 |`null` |`{color: '#005'}`| `ɵɵstyleMap('color', {color: '#005'})`
15145 * |25 |`22 | 26` | ... |
15146 * |26 |`color` |`'#006'` | `ɵɵstyleProp('color', '#006')`
15147 * |27 |`24 | 28` | ... |
15148 * |28 |`null` |`{color: '#007'}`| `ɵɵstyleMap('color', {color: '#007'})`
15149 * |29 |`26 | 30` | ... |
15150 * |30 |`color` |`'#008'` | `ɵɵstyleProp('color', '#008')`
15151 * |31 |`28 | 10` | ... |
15152 *
15153 * The above data structure allows us to re-concatenate the styling no matter which data binding
15154 * changes.
15155 *
15156 * NOTE: in addition to keeping track of next/previous index the `TView.data` also stores prev/next
15157 * duplicate bit. The duplicate bit if true says there either is a binding with the same name or
15158 * there is a map (which may contain the name). This information is useful in knowing if other
15159 * styles with higher priority need to be searched for overwrites.
15160 *
15161 * NOTE: See `should support example in 'tnode_linked_list.ts' documentation` in
15162 * `tnode_linked_list_spec.ts` for working example.
15163 */
15164let __unused_const_as_closure_does_not_like_standalone_comment_blocks__;
15165/**
15166 * Insert new `tStyleValue` at `TData` and link existing style bindings such that we maintain linked
15167 * list of styles and compute the duplicate flag.
15168 *
15169 * Note: this function is executed during `firstUpdatePass` only to populate the `TView.data`.
15170 *
15171 * The function works by keeping track of `tStylingRange` which contains two pointers pointing to
15172 * the head/tail of the template portion of the styles.
15173 * - if `isHost === false` (we are template) then insertion is at tail of `TStylingRange`
15174 * - if `isHost === true` (we are host binding) then insertion is at head of `TStylingRange`
15175 *
15176 * @param tData The `TData` to insert into.
15177 * @param tNode `TNode` associated with the styling element.
15178 * @param tStylingKey See `TStylingKey`.
15179 * @param index location of where `tStyleValue` should be stored (and linked into list.)
15180 * @param isHostBinding `true` if the insertion is for a `hostBinding`. (insertion is in front of
15181 * template.)
15182 * @param isClassBinding True if the associated `tStylingKey` as a `class` styling.
15183 * `tNode.classBindings` should be used (or `tNode.styleBindings` otherwise.)
15184 */
15185function insertTStylingBinding(tData, tNode, tStylingKeyWithStatic, index, isHostBinding, isClassBinding) {
15186 ngDevMode && assertFirstUpdatePass(getTView());
15187 let tBindings = isClassBinding ? tNode.classBindings : tNode.styleBindings;
15188 let tmplHead = getTStylingRangePrev(tBindings);
15189 let tmplTail = getTStylingRangeNext(tBindings);
15190 tData[index] = tStylingKeyWithStatic;
15191 let isKeyDuplicateOfStatic = false;
15192 let tStylingKey;
15193 if (Array.isArray(tStylingKeyWithStatic)) {
15194 // We are case when the `TStylingKey` contains static fields as well.
15195 const staticKeyValueArray = tStylingKeyWithStatic;
15196 tStylingKey = staticKeyValueArray[1]; // unwrap.
15197 // We need to check if our key is present in the static so that we can mark it as duplicate.
15198 if (tStylingKey === null ||
15199 keyValueArrayIndexOf(staticKeyValueArray, tStylingKey) > 0) {
15200 // tStylingKey is present in the statics, need to mark it as duplicate.
15201 isKeyDuplicateOfStatic = true;
15202 }
15203 }
15204 else {
15205 tStylingKey = tStylingKeyWithStatic;
15206 }
15207 if (isHostBinding) {
15208 // We are inserting host bindings
15209 // If we don't have template bindings then `tail` is 0.
15210 const hasTemplateBindings = tmplTail !== 0;
15211 // This is important to know because that means that the `head` can't point to the first
15212 // template bindings (there are none.) Instead the head points to the tail of the template.
15213 if (hasTemplateBindings) {
15214 // template head's "prev" will point to last host binding or to 0 if no host bindings yet
15215 const previousNode = getTStylingRangePrev(tData[tmplHead + 1]);
15216 tData[index + 1] = toTStylingRange(previousNode, tmplHead);
15217 // if a host binding has already been registered, we need to update the next of that host
15218 // binding to point to this one
15219 if (previousNode !== 0) {
15220 // We need to update the template-tail value to point to us.
15221 tData[previousNode + 1] =
15222 setTStylingRangeNext(tData[previousNode + 1], index);
15223 }
15224 // The "previous" of the template binding head should point to this host binding
15225 tData[tmplHead + 1] = setTStylingRangePrev(tData[tmplHead + 1], index);
15226 }
15227 else {
15228 tData[index + 1] = toTStylingRange(tmplHead, 0);
15229 // if a host binding has already been registered, we need to update the next of that host
15230 // binding to point to this one
15231 if (tmplHead !== 0) {
15232 // We need to update the template-tail value to point to us.
15233 tData[tmplHead + 1] = setTStylingRangeNext(tData[tmplHead + 1], index);
15234 }
15235 // if we don't have template, the head points to template-tail, and needs to be advanced.
15236 tmplHead = index;
15237 }
15238 }
15239 else {
15240 // We are inserting in template section.
15241 // We need to set this binding's "previous" to the current template tail
15242 tData[index + 1] = toTStylingRange(tmplTail, 0);
15243 ngDevMode &&
15244 assertEqual(tmplHead !== 0 && tmplTail === 0, false, 'Adding template bindings after hostBindings is not allowed.');
15245 if (tmplHead === 0) {
15246 tmplHead = index;
15247 }
15248 else {
15249 // We need to update the previous value "next" to point to this binding
15250 tData[tmplTail + 1] = setTStylingRangeNext(tData[tmplTail + 1], index);
15251 }
15252 tmplTail = index;
15253 }
15254 // Now we need to update / compute the duplicates.
15255 // Starting with our location search towards head (least priority)
15256 if (isKeyDuplicateOfStatic) {
15257 tData[index + 1] = setTStylingRangePrevDuplicate(tData[index + 1]);
15258 }
15259 markDuplicates(tData, tStylingKey, index, true, isClassBinding);
15260 markDuplicates(tData, tStylingKey, index, false, isClassBinding);
15261 markDuplicateOfResidualStyling(tNode, tStylingKey, tData, index, isClassBinding);
15262 tBindings = toTStylingRange(tmplHead, tmplTail);
15263 if (isClassBinding) {
15264 tNode.classBindings = tBindings;
15265 }
15266 else {
15267 tNode.styleBindings = tBindings;
15268 }
15269}
15270/**
15271 * Look into the residual styling to see if the current `tStylingKey` is duplicate of residual.
15272 *
15273 * @param tNode `TNode` where the residual is stored.
15274 * @param tStylingKey `TStylingKey` to store.
15275 * @param tData `TData` associated with the current `LView`.
15276 * @param index location of where `tStyleValue` should be stored (and linked into list.)
15277 * @param isClassBinding True if the associated `tStylingKey` as a `class` styling.
15278 * `tNode.classBindings` should be used (or `tNode.styleBindings` otherwise.)
15279 */
15280function markDuplicateOfResidualStyling(tNode, tStylingKey, tData, index, isClassBinding) {
15281 const residual = isClassBinding ? tNode.residualClasses : tNode.residualStyles;
15282 if (residual != null /* or undefined */ && typeof tStylingKey == 'string' &&
15283 keyValueArrayIndexOf(residual, tStylingKey) >= 0) {
15284 // We have duplicate in the residual so mark ourselves as duplicate.
15285 tData[index + 1] = setTStylingRangeNextDuplicate(tData[index + 1]);
15286 }
15287}
15288/**
15289 * Marks `TStyleValue`s as duplicates if another style binding in the list has the same
15290 * `TStyleValue`.
15291 *
15292 * NOTE: this function is intended to be called twice once with `isPrevDir` set to `true` and once
15293 * with it set to `false` to search both the previous as well as next items in the list.
15294 *
15295 * No duplicate case
15296 * ```
15297 * [style.color]
15298 * [style.width.px] <<- index
15299 * [style.height.px]
15300 * ```
15301 *
15302 * In the above case adding `[style.width.px]` to the existing `[style.color]` produces no
15303 * duplicates because `width` is not found in any other part of the linked list.
15304 *
15305 * Duplicate case
15306 * ```
15307 * [style.color]
15308 * [style.width.em]
15309 * [style.width.px] <<- index
15310 * ```
15311 * In the above case adding `[style.width.px]` will produce a duplicate with `[style.width.em]`
15312 * because `width` is found in the chain.
15313 *
15314 * Map case 1
15315 * ```
15316 * [style.width.px]
15317 * [style.color]
15318 * [style] <<- index
15319 * ```
15320 * In the above case adding `[style]` will produce a duplicate with any other bindings because
15321 * `[style]` is a Map and as such is fully dynamic and could produce `color` or `width`.
15322 *
15323 * Map case 2
15324 * ```
15325 * [style]
15326 * [style.width.px]
15327 * [style.color] <<- index
15328 * ```
15329 * In the above case adding `[style.color]` will produce a duplicate because there is already a
15330 * `[style]` binding which is a Map and as such is fully dynamic and could produce `color` or
15331 * `width`.
15332 *
15333 * NOTE: Once `[style]` (Map) is added into the system all things are mapped as duplicates.
15334 * NOTE: We use `style` as example, but same logic is applied to `class`es as well.
15335 *
15336 * @param tData `TData` where the linked list is stored.
15337 * @param tStylingKey `TStylingKeyPrimitive` which contains the value to compare to other keys in
15338 * the linked list.
15339 * @param index Starting location in the linked list to search from
15340 * @param isPrevDir Direction.
15341 * - `true` for previous (lower priority);
15342 * - `false` for next (higher priority).
15343 */
15344function markDuplicates(tData, tStylingKey, index, isPrevDir, isClassBinding) {
15345 const tStylingAtIndex = tData[index + 1];
15346 const isMap = tStylingKey === null;
15347 let cursor = isPrevDir ? getTStylingRangePrev(tStylingAtIndex) : getTStylingRangeNext(tStylingAtIndex);
15348 let foundDuplicate = false;
15349 // We keep iterating as long as we have a cursor
15350 // AND either:
15351 // - we found what we are looking for, OR
15352 // - we are a map in which case we have to continue searching even after we find what we were
15353 // looking for since we are a wild card and everything needs to be flipped to duplicate.
15354 while (cursor !== 0 && (foundDuplicate === false || isMap)) {
15355 ngDevMode && assertIndexInRange(tData, cursor);
15356 const tStylingValueAtCursor = tData[cursor];
15357 const tStyleRangeAtCursor = tData[cursor + 1];
15358 if (isStylingMatch(tStylingValueAtCursor, tStylingKey)) {
15359 foundDuplicate = true;
15360 tData[cursor + 1] = isPrevDir ? setTStylingRangeNextDuplicate(tStyleRangeAtCursor) :
15361 setTStylingRangePrevDuplicate(tStyleRangeAtCursor);
15362 }
15363 cursor = isPrevDir ? getTStylingRangePrev(tStyleRangeAtCursor) :
15364 getTStylingRangeNext(tStyleRangeAtCursor);
15365 }
15366 if (foundDuplicate) {
15367 // if we found a duplicate, than mark ourselves.
15368 tData[index + 1] = isPrevDir ? setTStylingRangePrevDuplicate(tStylingAtIndex) :
15369 setTStylingRangeNextDuplicate(tStylingAtIndex);
15370 }
15371}
15372/**
15373 * Determines if two `TStylingKey`s are a match.
15374 *
15375 * When computing weather a binding contains a duplicate, we need to compare if the instruction
15376 * `TStylingKey` has a match.
15377 *
15378 * Here are examples of `TStylingKey`s which match given `tStylingKeyCursor` is:
15379 * - `color`
15380 * - `color` // Match another color
15381 * - `null` // That means that `tStylingKey` is a `classMap`/`styleMap` instruction
15382 * - `['', 'color', 'other', true]` // wrapped `color` so match
15383 * - `['', null, 'other', true]` // wrapped `null` so match
15384 * - `['', 'width', 'color', 'value']` // wrapped static value contains a match on `'color'`
15385 * - `null` // `tStylingKeyCursor` always match as it is `classMap`/`styleMap` instruction
15386 *
15387 * @param tStylingKeyCursor
15388 * @param tStylingKey
15389 */
15390function isStylingMatch(tStylingKeyCursor, tStylingKey) {
15391 ngDevMode &&
15392 assertNotEqual(Array.isArray(tStylingKey), true, 'Expected that \'tStylingKey\' has been unwrapped');
15393 if (tStylingKeyCursor === null || // If the cursor is `null` it means that we have map at that
15394 // location so we must assume that we have a match.
15395 tStylingKey == null || // If `tStylingKey` is `null` then it is a map therefor assume that it
15396 // contains a match.
15397 (Array.isArray(tStylingKeyCursor) ? tStylingKeyCursor[1] : tStylingKeyCursor) ===
15398 tStylingKey // If the keys match explicitly than we are a match.
15399 ) {
15400 return true;
15401 }
15402 else if (Array.isArray(tStylingKeyCursor) && typeof tStylingKey === 'string') {
15403 // if we did not find a match, but `tStylingKeyCursor` is `KeyValueArray` that means cursor has
15404 // statics and we need to check those as well.
15405 return keyValueArrayIndexOf(tStylingKeyCursor, tStylingKey) >=
15406 0; // see if we are matching the key
15407 }
15408 return false;
15409}
15410
15411/**
15412 * @license
15413 * Copyright Google LLC All Rights Reserved.
15414 *
15415 * Use of this source code is governed by an MIT-style license that can be
15416 * found in the LICENSE file at https://angular.io/license
15417 */
15418// Global state of the parser. (This makes parser non-reentrant, but that is not an issue)
15419const parserState = {
15420 textEnd: 0,
15421 key: 0,
15422 keyEnd: 0,
15423 value: 0,
15424 valueEnd: 0,
15425};
15426/**
15427 * Retrieves the last parsed `key` of style.
15428 * @param text the text to substring the key from.
15429 */
15430function getLastParsedKey(text) {
15431 return text.substring(parserState.key, parserState.keyEnd);
15432}
15433/**
15434 * Retrieves the last parsed `value` of style.
15435 * @param text the text to substring the key from.
15436 */
15437function getLastParsedValue(text) {
15438 return text.substring(parserState.value, parserState.valueEnd);
15439}
15440/**
15441 * Initializes `className` string for parsing and parses the first token.
15442 *
15443 * This function is intended to be used in this format:
15444 * ```
15445 * for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
15446 * const key = getLastParsedKey();
15447 * ...
15448 * }
15449 * ```
15450 * @param text `className` to parse
15451 * @returns index where the next invocation of `parseClassNameNext` should resume.
15452 */
15453function parseClassName(text) {
15454 resetParserState(text);
15455 return parseClassNameNext(text, consumeWhitespace(text, 0, parserState.textEnd));
15456}
15457/**
15458 * Parses next `className` token.
15459 *
15460 * This function is intended to be used in this format:
15461 * ```
15462 * for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
15463 * const key = getLastParsedKey();
15464 * ...
15465 * }
15466 * ```
15467 *
15468 * @param text `className` to parse
15469 * @param index where the parsing should resume.
15470 * @returns index where the next invocation of `parseClassNameNext` should resume.
15471 */
15472function parseClassNameNext(text, index) {
15473 const end = parserState.textEnd;
15474 if (end === index) {
15475 return -1;
15476 }
15477 index = parserState.keyEnd = consumeClassToken(text, parserState.key = index, end);
15478 return consumeWhitespace(text, index, end);
15479}
15480/**
15481 * Initializes `cssText` string for parsing and parses the first key/values.
15482 *
15483 * This function is intended to be used in this format:
15484 * ```
15485 * for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
15486 * const key = getLastParsedKey();
15487 * const value = getLastParsedValue();
15488 * ...
15489 * }
15490 * ```
15491 * @param text `cssText` to parse
15492 * @returns index where the next invocation of `parseStyleNext` should resume.
15493 */
15494function parseStyle(text) {
15495 resetParserState(text);
15496 return parseStyleNext(text, consumeWhitespace(text, 0, parserState.textEnd));
15497}
15498/**
15499 * Parses the next `cssText` key/values.
15500 *
15501 * This function is intended to be used in this format:
15502 * ```
15503 * for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
15504 * const key = getLastParsedKey();
15505 * const value = getLastParsedValue();
15506 * ...
15507 * }
15508 *
15509 * @param text `cssText` to parse
15510 * @param index where the parsing should resume.
15511 * @returns index where the next invocation of `parseStyleNext` should resume.
15512 */
15513function parseStyleNext(text, startIndex) {
15514 const end = parserState.textEnd;
15515 let index = parserState.key = consumeWhitespace(text, startIndex, end);
15516 if (end === index) {
15517 // we reached an end so just quit
15518 return -1;
15519 }
15520 index = parserState.keyEnd = consumeStyleKey(text, index, end);
15521 index = consumeSeparator(text, index, end, 58 /* COLON */);
15522 index = parserState.value = consumeWhitespace(text, index, end);
15523 index = parserState.valueEnd = consumeStyleValue(text, index, end);
15524 return consumeSeparator(text, index, end, 59 /* SEMI_COLON */);
15525}
15526/**
15527 * Reset the global state of the styling parser.
15528 * @param text The styling text to parse.
15529 */
15530function resetParserState(text) {
15531 parserState.key = 0;
15532 parserState.keyEnd = 0;
15533 parserState.value = 0;
15534 parserState.valueEnd = 0;
15535 parserState.textEnd = text.length;
15536}
15537/**
15538 * Returns index of next non-whitespace character.
15539 *
15540 * @param text Text to scan
15541 * @param startIndex Starting index of character where the scan should start.
15542 * @param endIndex Ending index of character where the scan should end.
15543 * @returns Index of next non-whitespace character (May be the same as `start` if no whitespace at
15544 * that location.)
15545 */
15546function consumeWhitespace(text, startIndex, endIndex) {
15547 while (startIndex < endIndex && text.charCodeAt(startIndex) <= 32 /* SPACE */) {
15548 startIndex++;
15549 }
15550 return startIndex;
15551}
15552/**
15553 * Returns index of last char in class token.
15554 *
15555 * @param text Text to scan
15556 * @param startIndex Starting index of character where the scan should start.
15557 * @param endIndex Ending index of character where the scan should end.
15558 * @returns Index after last char in class token.
15559 */
15560function consumeClassToken(text, startIndex, endIndex) {
15561 while (startIndex < endIndex && text.charCodeAt(startIndex) > 32 /* SPACE */) {
15562 startIndex++;
15563 }
15564 return startIndex;
15565}
15566/**
15567 * Consumes all of the characters belonging to style key and token.
15568 *
15569 * @param text Text to scan
15570 * @param startIndex Starting index of character where the scan should start.
15571 * @param endIndex Ending index of character where the scan should end.
15572 * @returns Index after last style key character.
15573 */
15574function consumeStyleKey(text, startIndex, endIndex) {
15575 let ch;
15576 while (startIndex < endIndex &&
15577 ((ch = text.charCodeAt(startIndex)) === 45 /* DASH */ || ch === 95 /* UNDERSCORE */ ||
15578 ((ch & -33 /* UPPER_CASE */) >= 65 /* A */ && (ch & -33 /* UPPER_CASE */) <= 90 /* Z */) ||
15579 (ch >= 48 /* ZERO */ && ch <= 57 /* NINE */))) {
15580 startIndex++;
15581 }
15582 return startIndex;
15583}
15584/**
15585 * Consumes all whitespace and the separator `:` after the style key.
15586 *
15587 * @param text Text to scan
15588 * @param startIndex Starting index of character where the scan should start.
15589 * @param endIndex Ending index of character where the scan should end.
15590 * @returns Index after separator and surrounding whitespace.
15591 */
15592function consumeSeparator(text, startIndex, endIndex, separator) {
15593 startIndex = consumeWhitespace(text, startIndex, endIndex);
15594 if (startIndex < endIndex) {
15595 if (ngDevMode && text.charCodeAt(startIndex) !== separator) {
15596 malformedStyleError(text, String.fromCharCode(separator), startIndex);
15597 }
15598 startIndex++;
15599 }
15600 return startIndex;
15601}
15602/**
15603 * Consumes style value honoring `url()` and `""` text.
15604 *
15605 * @param text Text to scan
15606 * @param startIndex Starting index of character where the scan should start.
15607 * @param endIndex Ending index of character where the scan should end.
15608 * @returns Index after last style value character.
15609 */
15610function consumeStyleValue(text, startIndex, endIndex) {
15611 let ch1 = -1; // 1st previous character
15612 let ch2 = -1; // 2nd previous character
15613 let ch3 = -1; // 3rd previous character
15614 let i = startIndex;
15615 let lastChIndex = i;
15616 while (i < endIndex) {
15617 const ch = text.charCodeAt(i++);
15618 if (ch === 59 /* SEMI_COLON */) {
15619 return lastChIndex;
15620 }
15621 else if (ch === 34 /* DOUBLE_QUOTE */ || ch === 39 /* SINGLE_QUOTE */) {
15622 lastChIndex = i = consumeQuotedText(text, ch, i, endIndex);
15623 }
15624 else if (startIndex ===
15625 i - 4 && // We have seen only 4 characters so far "URL(" (Ignore "foo_URL()")
15626 ch3 === 85 /* U */ &&
15627 ch2 === 82 /* R */ && ch1 === 76 /* L */ && ch === 40 /* OPEN_PAREN */) {
15628 lastChIndex = i = consumeQuotedText(text, 41 /* CLOSE_PAREN */, i, endIndex);
15629 }
15630 else if (ch > 32 /* SPACE */) {
15631 // if we have a non-whitespace character then capture its location
15632 lastChIndex = i;
15633 }
15634 ch3 = ch2;
15635 ch2 = ch1;
15636 ch1 = ch & -33 /* UPPER_CASE */;
15637 }
15638 return lastChIndex;
15639}
15640/**
15641 * Consumes all of the quoted characters.
15642 *
15643 * @param text Text to scan
15644 * @param quoteCharCode CharCode of either `"` or `'` quote or `)` for `url(...)`.
15645 * @param startIndex Starting index of character where the scan should start.
15646 * @param endIndex Ending index of character where the scan should end.
15647 * @returns Index after quoted characters.
15648 */
15649function consumeQuotedText(text, quoteCharCode, startIndex, endIndex) {
15650 let ch1 = -1; // 1st previous character
15651 let index = startIndex;
15652 while (index < endIndex) {
15653 const ch = text.charCodeAt(index++);
15654 if (ch == quoteCharCode && ch1 !== 92 /* BACK_SLASH */) {
15655 return index;
15656 }
15657 if (ch == 92 /* BACK_SLASH */ && ch1 === 92 /* BACK_SLASH */) {
15658 // two back slashes cancel each other out. For example `"\\"` should properly end the
15659 // quotation. (It should not assume that the last `"` is escaped.)
15660 ch1 = 0;
15661 }
15662 else {
15663 ch1 = ch;
15664 }
15665 }
15666 throw ngDevMode ? malformedStyleError(text, String.fromCharCode(quoteCharCode), endIndex) :
15667 new Error();
15668}
15669function malformedStyleError(text, expecting, index) {
15670 ngDevMode && assertEqual(typeof text === 'string', true, 'String expected here');
15671 throw throwError(`Malformed style at location ${index} in string '` + text.substring(0, index) + '[>>' +
15672 text.substring(index, index + 1) + '<<]' + text.substr(index + 1) +
15673 `'. Expecting '${expecting}'.`);
15674}
15675
15676/**
15677 * @license
15678 * Copyright Google LLC All Rights Reserved.
15679 *
15680 * Use of this source code is governed by an MIT-style license that can be
15681 * found in the LICENSE file at https://angular.io/license
15682 */
15683/**
15684 * Update a style binding on an element with the provided value.
15685 *
15686 * If the style value is falsy then it will be removed from the element
15687 * (or assigned a different value depending if there are any styles placed
15688 * on the element with `styleMap` or any static styles that are
15689 * present from when the element was created with `styling`).
15690 *
15691 * Note that the styling element is updated as part of `stylingApply`.
15692 *
15693 * @param prop A valid CSS property.
15694 * @param value New value to write (`null` or an empty string to remove).
15695 * @param suffix Optional suffix. Used with scalar values to add unit such as `px`.
15696 *
15697 * Note that this will apply the provided style value to the host element if this function is called
15698 * within a host binding function.
15699 *
15700 * @codeGenApi
15701 */
15702function ɵɵstyleProp(prop, value, suffix) {
15703 checkStylingProperty(prop, value, suffix, false);
15704 return ɵɵstyleProp;
15705}
15706/**
15707 * Update a class binding on an element with the provided value.
15708 *
15709 * This instruction is meant to handle the `[class.foo]="exp"` case and,
15710 * therefore, the class binding itself must already be allocated using
15711 * `styling` within the creation block.
15712 *
15713 * @param prop A valid CSS class (only one).
15714 * @param value A true/false value which will turn the class on or off.
15715 *
15716 * Note that this will apply the provided class value to the host element if this function
15717 * is called within a host binding function.
15718 *
15719 * @codeGenApi
15720 */
15721function ɵɵclassProp(className, value) {
15722 checkStylingProperty(className, value, null, true);
15723 return ɵɵclassProp;
15724}
15725/**
15726 * Update style bindings using an object literal on an element.
15727 *
15728 * This instruction is meant to apply styling via the `[style]="exp"` template bindings.
15729 * When styles are applied to the element they will then be updated with respect to
15730 * any styles/classes set via `styleProp`. If any styles are set to falsy
15731 * then they will be removed from the element.
15732 *
15733 * Note that the styling instruction will not be applied until `stylingApply` is called.
15734 *
15735 * @param styles A key/value style map of the styles that will be applied to the given element.
15736 * Any missing styles (that have already been applied to the element beforehand) will be
15737 * removed (unset) from the element's styling.
15738 *
15739 * Note that this will apply the provided styleMap value to the host element if this function
15740 * is called within a host binding.
15741 *
15742 * @codeGenApi
15743 */
15744function ɵɵstyleMap(styles) {
15745 checkStylingMap(styleKeyValueArraySet, styleStringParser, styles, false);
15746}
15747/**
15748 * Parse text as style and add values to KeyValueArray.
15749 *
15750 * This code is pulled out to a separate function so that it can be tree shaken away if it is not
15751 * needed. It is only referenced from `ɵɵstyleMap`.
15752 *
15753 * @param keyValueArray KeyValueArray to add parsed values to.
15754 * @param text text to parse.
15755 */
15756function styleStringParser(keyValueArray, text) {
15757 for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i)) {
15758 styleKeyValueArraySet(keyValueArray, getLastParsedKey(text), getLastParsedValue(text));
15759 }
15760}
15761/**
15762 * Update class bindings using an object literal or class-string on an element.
15763 *
15764 * This instruction is meant to apply styling via the `[class]="exp"` template bindings.
15765 * When classes are applied to the element they will then be updated with
15766 * respect to any styles/classes set via `classProp`. If any
15767 * classes are set to falsy then they will be removed from the element.
15768 *
15769 * Note that the styling instruction will not be applied until `stylingApply` is called.
15770 * Note that this will the provided classMap value to the host element if this function is called
15771 * within a host binding.
15772 *
15773 * @param classes A key/value map or string of CSS classes that will be added to the
15774 * given element. Any missing classes (that have already been applied to the element
15775 * beforehand) will be removed (unset) from the element's list of CSS classes.
15776 *
15777 * @codeGenApi
15778 */
15779function ɵɵclassMap(classes) {
15780 checkStylingMap(keyValueArraySet, classStringParser, classes, true);
15781}
15782/**
15783 * Parse text as class and add values to KeyValueArray.
15784 *
15785 * This code is pulled out to a separate function so that it can be tree shaken away if it is not
15786 * needed. It is only referenced from `ɵɵclassMap`.
15787 *
15788 * @param keyValueArray KeyValueArray to add parsed values to.
15789 * @param text text to parse.
15790 */
15791function classStringParser(keyValueArray, text) {
15792 for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
15793 keyValueArraySet(keyValueArray, getLastParsedKey(text), true);
15794 }
15795}
15796/**
15797 * Common code between `ɵɵclassProp` and `ɵɵstyleProp`.
15798 *
15799 * @param prop property name.
15800 * @param value binding value.
15801 * @param suffix suffix for the property (e.g. `em` or `px`)
15802 * @param isClassBased `true` if `class` change (`false` if `style`)
15803 */
15804function checkStylingProperty(prop, value, suffix, isClassBased) {
15805 const lView = getLView();
15806 const tView = getTView();
15807 // Styling instructions use 2 slots per binding.
15808 // 1. one for the value / TStylingKey
15809 // 2. one for the intermittent-value / TStylingRange
15810 const bindingIndex = incrementBindingIndex(2);
15811 if (tView.firstUpdatePass) {
15812 stylingFirstUpdatePass(tView, prop, bindingIndex, isClassBased);
15813 }
15814 if (value !== NO_CHANGE && bindingUpdated(lView, bindingIndex, value)) {
15815 const tNode = tView.data[getSelectedIndex() + HEADER_OFFSET];
15816 updateStyling(tView, tNode, lView, lView[RENDERER], prop, lView[bindingIndex + 1] = normalizeSuffix(value, suffix), isClassBased, bindingIndex);
15817 }
15818}
15819/**
15820 * Common code between `ɵɵclassMap` and `ɵɵstyleMap`.
15821 *
15822 * @param keyValueArraySet (See `keyValueArraySet` in "util/array_utils") Gets passed in as a
15823 * function so that `style` can be processed. This is done for tree shaking purposes.
15824 * @param stringParser Parser used to parse `value` if `string`. (Passed in as `style` and `class`
15825 * have different parsers.)
15826 * @param value bound value from application
15827 * @param isClassBased `true` if `class` change (`false` if `style`)
15828 */
15829function checkStylingMap(keyValueArraySet, stringParser, value, isClassBased) {
15830 const tView = getTView();
15831 const bindingIndex = incrementBindingIndex(2);
15832 if (tView.firstUpdatePass) {
15833 stylingFirstUpdatePass(tView, null, bindingIndex, isClassBased);
15834 }
15835 const lView = getLView();
15836 if (value !== NO_CHANGE && bindingUpdated(lView, bindingIndex, value)) {
15837 // `getSelectedIndex()` should be here (rather than in instruction) so that it is guarded by the
15838 // if so as not to read unnecessarily.
15839 const tNode = tView.data[getSelectedIndex() + HEADER_OFFSET];
15840 if (hasStylingInputShadow(tNode, isClassBased) && !isInHostBindings(tView, bindingIndex)) {
15841 if (ngDevMode) {
15842 // verify that if we are shadowing then `TData` is appropriately marked so that we skip
15843 // processing this binding in styling resolution.
15844 const tStylingKey = tView.data[bindingIndex];
15845 assertEqual(Array.isArray(tStylingKey) ? tStylingKey[1] : tStylingKey, false, 'Styling linked list shadow input should be marked as \'false\'');
15846 }
15847 // VE does not concatenate the static portion like we are doing here.
15848 // Instead VE just ignores the static completely if dynamic binding is present.
15849 // Because of locality we have already set the static portion because we don't know if there
15850 // is a dynamic portion until later. If we would ignore the static portion it would look like
15851 // the binding has removed it. This would confuse `[ngStyle]`/`[ngClass]` to do the wrong
15852 // thing as it would think that the static portion was removed. For this reason we
15853 // concatenate it so that `[ngStyle]`/`[ngClass]` can continue to work on changed.
15854 let staticPrefix = isClassBased ? tNode.classesWithoutHost : tNode.stylesWithoutHost;
15855 ngDevMode && isClassBased === false && staticPrefix !== null &&
15856 assertEqual(staticPrefix.endsWith(';'), true, 'Expecting static portion to end with \';\'');
15857 if (staticPrefix !== null) {
15858 // We want to make sure that falsy values of `value` become empty strings.
15859 value = concatStringsWithSpace(staticPrefix, value ? value : '');
15860 }
15861 // Given `<div [style] my-dir>` such that `my-dir` has `@Input('style')`.
15862 // This takes over the `[style]` binding. (Same for `[class]`)
15863 setDirectiveInputsWhichShadowsStyling(tView, tNode, lView, value, isClassBased);
15864 }
15865 else {
15866 updateStylingMap(tView, tNode, lView, lView[RENDERER], lView[bindingIndex + 1], lView[bindingIndex + 1] = toStylingKeyValueArray(keyValueArraySet, stringParser, value), isClassBased, bindingIndex);
15867 }
15868 }
15869}
15870/**
15871 * Determines when the binding is in `hostBindings` section
15872 *
15873 * @param tView Current `TView`
15874 * @param bindingIndex index of binding which we would like if it is in `hostBindings`
15875 */
15876function isInHostBindings(tView, bindingIndex) {
15877 // All host bindings are placed after the expando section.
15878 return bindingIndex >= tView.expandoStartIndex;
15879}
15880/**
15881 * Collects the necessary information to insert the binding into a linked list of style bindings
15882 * using `insertTStylingBinding`.
15883 *
15884 * @param tView `TView` where the binding linked list will be stored.
15885 * @param tStylingKey Property/key of the binding.
15886 * @param bindingIndex Index of binding associated with the `prop`
15887 * @param isClassBased `true` if `class` change (`false` if `style`)
15888 */
15889function stylingFirstUpdatePass(tView, tStylingKey, bindingIndex, isClassBased) {
15890 ngDevMode && assertFirstUpdatePass(tView);
15891 const tData = tView.data;
15892 if (tData[bindingIndex + 1] === null) {
15893 // The above check is necessary because we don't clear first update pass until first successful
15894 // (no exception) template execution. This prevents the styling instruction from double adding
15895 // itself to the list.
15896 // `getSelectedIndex()` should be here (rather than in instruction) so that it is guarded by the
15897 // if so as not to read unnecessarily.
15898 const tNode = tData[getSelectedIndex() + HEADER_OFFSET];
15899 const isHostBindings = isInHostBindings(tView, bindingIndex);
15900 if (hasStylingInputShadow(tNode, isClassBased) && tStylingKey === null && !isHostBindings) {
15901 // `tStylingKey === null` implies that we are either `[style]` or `[class]` binding.
15902 // If there is a directive which uses `@Input('style')` or `@Input('class')` than
15903 // we need to neutralize this binding since that directive is shadowing it.
15904 // We turn this into a noop by setting the key to `false`
15905 tStylingKey = false;
15906 }
15907 tStylingKey = wrapInStaticStylingKey(tData, tNode, tStylingKey, isClassBased);
15908 insertTStylingBinding(tData, tNode, tStylingKey, bindingIndex, isHostBindings, isClassBased);
15909 }
15910}
15911/**
15912 * Adds static styling information to the binding if applicable.
15913 *
15914 * The linked list of styles not only stores the list and keys, but also stores static styling
15915 * information on some of the keys. This function determines if the key should contain the styling
15916 * information and computes it.
15917 *
15918 * See `TStylingStatic` for more details.
15919 *
15920 * @param tData `TData` where the linked list is stored.
15921 * @param tNode `TNode` for which the styling is being computed.
15922 * @param stylingKey `TStylingKeyPrimitive` which may need to be wrapped into `TStylingKey`
15923 * @param isClassBased `true` if `class` (`false` if `style`)
15924 */
15925function wrapInStaticStylingKey(tData, tNode, stylingKey, isClassBased) {
15926 const hostDirectiveDef = getCurrentDirectiveDef(tData);
15927 let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles;
15928 if (hostDirectiveDef === null) {
15929 // We are in template node.
15930 // If template node already had styling instruction then it has already collected the static
15931 // styling and there is no need to collect them again. We know that we are the first styling
15932 // instruction because the `TNode.*Bindings` points to 0 (nothing has been inserted yet).
15933 const isFirstStylingInstructionInTemplate = (isClassBased ? tNode.classBindings : tNode.styleBindings) === 0;
15934 if (isFirstStylingInstructionInTemplate) {
15935 // It would be nice to be able to get the statics from `mergeAttrs`, however, at this point
15936 // they are already merged and it would not be possible to figure which property belongs where
15937 // in the priority.
15938 stylingKey = collectStylingFromDirectives(null, tData, tNode, stylingKey, isClassBased);
15939 stylingKey = collectStylingFromTAttrs(stylingKey, tNode.attrs, isClassBased);
15940 // We know that if we have styling binding in template we can't have residual.
15941 residual = null;
15942 }
15943 }
15944 else {
15945 // We are in host binding node and there was no binding instruction in template node.
15946 // This means that we need to compute the residual.
15947 const directiveStylingLast = tNode.directiveStylingLast;
15948 const isFirstStylingInstructionInHostBinding = directiveStylingLast === -1 || tData[directiveStylingLast] !== hostDirectiveDef;
15949 if (isFirstStylingInstructionInHostBinding) {
15950 stylingKey =
15951 collectStylingFromDirectives(hostDirectiveDef, tData, tNode, stylingKey, isClassBased);
15952 if (residual === null) {
15953 // - If `null` than either:
15954 // - Template styling instruction already ran and it has consumed the static
15955 // styling into its `TStylingKey` and so there is no need to update residual. Instead
15956 // we need to update the `TStylingKey` associated with the first template node
15957 // instruction. OR
15958 // - Some other styling instruction ran and determined that there are no residuals
15959 let templateStylingKey = getTemplateHeadTStylingKey(tData, tNode, isClassBased);
15960 if (templateStylingKey !== undefined && Array.isArray(templateStylingKey)) {
15961 // Only recompute if `templateStylingKey` had static values. (If no static value found
15962 // then there is nothing to do since this operation can only produce less static keys, not
15963 // more.)
15964 templateStylingKey = collectStylingFromDirectives(null, tData, tNode, templateStylingKey[1] /* unwrap previous statics */, isClassBased);
15965 templateStylingKey =
15966 collectStylingFromTAttrs(templateStylingKey, tNode.attrs, isClassBased);
15967 setTemplateHeadTStylingKey(tData, tNode, isClassBased, templateStylingKey);
15968 }
15969 }
15970 else {
15971 // We only need to recompute residual if it is not `null`.
15972 // - If existing residual (implies there was no template styling). This means that some of
15973 // the statics may have moved from the residual to the `stylingKey` and so we have to
15974 // recompute.
15975 // - If `undefined` this is the first time we are running.
15976 residual = collectResidual(tData, tNode, isClassBased);
15977 }
15978 }
15979 }
15980 if (residual !== undefined) {
15981 isClassBased ? (tNode.residualClasses = residual) : (tNode.residualStyles = residual);
15982 }
15983 return stylingKey;
15984}
15985/**
15986 * Retrieve the `TStylingKey` for the template styling instruction.
15987 *
15988 * This is needed since `hostBinding` styling instructions are inserted after the template
15989 * instruction. While the template instruction needs to update the residual in `TNode` the
15990 * `hostBinding` instructions need to update the `TStylingKey` of the template instruction because
15991 * the template instruction is downstream from the `hostBindings` instructions.
15992 *
15993 * @param tData `TData` where the linked list is stored.
15994 * @param tNode `TNode` for which the styling is being computed.
15995 * @param isClassBased `true` if `class` (`false` if `style`)
15996 * @return `TStylingKey` if found or `undefined` if not found.
15997 */
15998function getTemplateHeadTStylingKey(tData, tNode, isClassBased) {
15999 const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings;
16000 if (getTStylingRangeNext(bindings) === 0) {
16001 // There does not seem to be a styling instruction in the `template`.
16002 return undefined;
16003 }
16004 return tData[getTStylingRangePrev(bindings)];
16005}
16006/**
16007 * Update the `TStylingKey` of the first template instruction in `TNode`.
16008 *
16009 * Logically `hostBindings` styling instructions are of lower priority than that of the template.
16010 * However, they execute after the template styling instructions. This means that they get inserted
16011 * in front of the template styling instructions.
16012 *
16013 * If we have a template styling instruction and a new `hostBindings` styling instruction is
16014 * executed it means that it may need to steal static fields from the template instruction. This
16015 * method allows us to update the first template instruction `TStylingKey` with a new value.
16016 *
16017 * Assume:
16018 * ```
16019 * <div my-dir style="color: red" [style.color]="tmplExp"></div>
16020 *
16021 * @Directive({
16022 * host: {
16023 * 'style': 'width: 100px',
16024 * '[style.color]': 'dirExp',
16025 * }
16026 * })
16027 * class MyDir {}
16028 * ```
16029 *
16030 * when `[style.color]="tmplExp"` executes it creates this data structure.
16031 * ```
16032 * ['', 'color', 'color', 'red', 'width', '100px'],
16033 * ```
16034 *
16035 * The reason for this is that the template instruction does not know if there are styling
16036 * instructions and must assume that there are none and must collect all of the static styling.
16037 * (both
16038 * `color' and 'width`)
16039 *
16040 * When `'[style.color]': 'dirExp',` executes we need to insert a new data into the linked list.
16041 * ```
16042 * ['', 'color', 'width', '100px'], // newly inserted
16043 * ['', 'color', 'color', 'red', 'width', '100px'], // this is wrong
16044 * ```
16045 *
16046 * Notice that the template statics is now wrong as it incorrectly contains `width` so we need to
16047 * update it like so:
16048 * ```
16049 * ['', 'color', 'width', '100px'],
16050 * ['', 'color', 'color', 'red'], // UPDATE
16051 * ```
16052 *
16053 * @param tData `TData` where the linked list is stored.
16054 * @param tNode `TNode` for which the styling is being computed.
16055 * @param isClassBased `true` if `class` (`false` if `style`)
16056 * @param tStylingKey New `TStylingKey` which is replacing the old one.
16057 */
16058function setTemplateHeadTStylingKey(tData, tNode, isClassBased, tStylingKey) {
16059 const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings;
16060 ngDevMode &&
16061 assertNotEqual(getTStylingRangeNext(bindings), 0, 'Expecting to have at least one template styling binding.');
16062 tData[getTStylingRangePrev(bindings)] = tStylingKey;
16063}
16064/**
16065 * Collect all static values after the current `TNode.directiveStylingLast` index.
16066 *
16067 * Collect the remaining styling information which has not yet been collected by an existing
16068 * styling instruction.
16069 *
16070 * @param tData `TData` where the `DirectiveDefs` are stored.
16071 * @param tNode `TNode` which contains the directive range.
16072 * @param isClassBased `true` if `class` (`false` if `style`)
16073 */
16074function collectResidual(tData, tNode, isClassBased) {
16075 let residual = undefined;
16076 const directiveEnd = tNode.directiveEnd;
16077 ngDevMode &&
16078 assertNotEqual(tNode.directiveStylingLast, -1, 'By the time this function gets called at least one hostBindings-node styling instruction must have executed.');
16079 // We add `1 + tNode.directiveStart` because we need to skip the current directive (as we are
16080 // collecting things after the last `hostBindings` directive which had a styling instruction.)
16081 for (let i = 1 + tNode.directiveStylingLast; i < directiveEnd; i++) {
16082 const attrs = tData[i].hostAttrs;
16083 residual = collectStylingFromTAttrs(residual, attrs, isClassBased);
16084 }
16085 return collectStylingFromTAttrs(residual, tNode.attrs, isClassBased);
16086}
16087/**
16088 * Collect the static styling information with lower priority than `hostDirectiveDef`.
16089 *
16090 * (This is opposite of residual styling.)
16091 *
16092 * @param hostDirectiveDef `DirectiveDef` for which we want to collect lower priority static
16093 * styling. (Or `null` if template styling)
16094 * @param tData `TData` where the linked list is stored.
16095 * @param tNode `TNode` for which the styling is being computed.
16096 * @param stylingKey Existing `TStylingKey` to update or wrap.
16097 * @param isClassBased `true` if `class` (`false` if `style`)
16098 */
16099function collectStylingFromDirectives(hostDirectiveDef, tData, tNode, stylingKey, isClassBased) {
16100 // We need to loop because there can be directives which have `hostAttrs` but don't have
16101 // `hostBindings` so this loop catches up to the current directive..
16102 let currentDirective = null;
16103 const directiveEnd = tNode.directiveEnd;
16104 let directiveStylingLast = tNode.directiveStylingLast;
16105 if (directiveStylingLast === -1) {
16106 directiveStylingLast = tNode.directiveStart;
16107 }
16108 else {
16109 directiveStylingLast++;
16110 }
16111 while (directiveStylingLast < directiveEnd) {
16112 currentDirective = tData[directiveStylingLast];
16113 ngDevMode && assertDefined(currentDirective, 'expected to be defined');
16114 stylingKey = collectStylingFromTAttrs(stylingKey, currentDirective.hostAttrs, isClassBased);
16115 if (currentDirective === hostDirectiveDef)
16116 break;
16117 directiveStylingLast++;
16118 }
16119 if (hostDirectiveDef !== null) {
16120 // we only advance the styling cursor if we are collecting data from host bindings.
16121 // Template executes before host bindings and so if we would update the index,
16122 // host bindings would not get their statics.
16123 tNode.directiveStylingLast = directiveStylingLast;
16124 }
16125 return stylingKey;
16126}
16127/**
16128 * Convert `TAttrs` into `TStylingStatic`.
16129 *
16130 * @param stylingKey existing `TStylingKey` to update or wrap.
16131 * @param attrs `TAttributes` to process.
16132 * @param isClassBased `true` if `class` (`false` if `style`)
16133 */
16134function collectStylingFromTAttrs(stylingKey, attrs, isClassBased) {
16135 const desiredMarker = isClassBased ? 1 /* Classes */ : 2 /* Styles */;
16136 let currentMarker = -1 /* ImplicitAttributes */;
16137 if (attrs !== null) {
16138 for (let i = 0; i < attrs.length; i++) {
16139 const item = attrs[i];
16140 if (typeof item === 'number') {
16141 currentMarker = item;
16142 }
16143 else {
16144 if (currentMarker === desiredMarker) {
16145 if (!Array.isArray(stylingKey)) {
16146 stylingKey = stylingKey === undefined ? [] : ['', stylingKey];
16147 }
16148 keyValueArraySet(stylingKey, item, isClassBased ? true : attrs[++i]);
16149 }
16150 }
16151 }
16152 }
16153 return stylingKey === undefined ? null : stylingKey;
16154}
16155/**
16156 * Convert user input to `KeyValueArray`.
16157 *
16158 * This function takes user input which could be `string`, Object literal, or iterable and converts
16159 * it into a consistent representation. The output of this is `KeyValueArray` (which is an array
16160 * where
16161 * even indexes contain keys and odd indexes contain values for those keys).
16162 *
16163 * The advantage of converting to `KeyValueArray` is that we can perform diff in an input
16164 * independent
16165 * way.
16166 * (ie we can compare `foo bar` to `['bar', 'baz'] and determine a set of changes which need to be
16167 * applied)
16168 *
16169 * The fact that `KeyValueArray` is sorted is very important because it allows us to compute the
16170 * difference in linear fashion without the need to allocate any additional data.
16171 *
16172 * For example if we kept this as a `Map` we would have to iterate over previous `Map` to determine
16173 * which values need to be deleted, over the new `Map` to determine additions, and we would have to
16174 * keep additional `Map` to keep track of duplicates or items which have not yet been visited.
16175 *
16176 * @param keyValueArraySet (See `keyValueArraySet` in "util/array_utils") Gets passed in as a
16177 * function so that `style` can be processed. This is done
16178 * for tree shaking purposes.
16179 * @param stringParser The parser is passed in so that it will be tree shakable. See
16180 * `styleStringParser` and `classStringParser`
16181 * @param value The value to parse/convert to `KeyValueArray`
16182 */
16183function toStylingKeyValueArray(keyValueArraySet, stringParser, value) {
16184 if (value == null /*|| value === undefined */ || value === '')
16185 return EMPTY_ARRAY$3;
16186 const styleKeyValueArray = [];
16187 const unwrappedValue = unwrapSafeValue(value);
16188 if (Array.isArray(unwrappedValue)) {
16189 for (let i = 0; i < unwrappedValue.length; i++) {
16190 keyValueArraySet(styleKeyValueArray, unwrappedValue[i], true);
16191 }
16192 }
16193 else if (typeof unwrappedValue === 'object') {
16194 for (const key in unwrappedValue) {
16195 if (unwrappedValue.hasOwnProperty(key)) {
16196 keyValueArraySet(styleKeyValueArray, key, unwrappedValue[key]);
16197 }
16198 }
16199 }
16200 else if (typeof unwrappedValue === 'string') {
16201 stringParser(styleKeyValueArray, unwrappedValue);
16202 }
16203 else {
16204 ngDevMode &&
16205 throwError('Unsupported styling type ' + typeof unwrappedValue + ': ' + unwrappedValue);
16206 }
16207 return styleKeyValueArray;
16208}
16209/**
16210 * Set a `value` for a `key`.
16211 *
16212 * See: `keyValueArraySet` for details
16213 *
16214 * @param keyValueArray KeyValueArray to add to.
16215 * @param key Style key to add.
16216 * @param value The value to set.
16217 */
16218function styleKeyValueArraySet(keyValueArray, key, value) {
16219 keyValueArraySet(keyValueArray, key, unwrapSafeValue(value));
16220}
16221/**
16222 * Update map based styling.
16223 *
16224 * Map based styling could be anything which contains more than one binding. For example `string`,
16225 * or object literal. Dealing with all of these types would complicate the logic so
16226 * instead this function expects that the complex input is first converted into normalized
16227 * `KeyValueArray`. The advantage of normalization is that we get the values sorted, which makes it
16228 * very cheap to compute deltas between the previous and current value.
16229 *
16230 * @param tView Associated `TView.data` contains the linked list of binding priorities.
16231 * @param tNode `TNode` where the binding is located.
16232 * @param lView `LView` contains the values associated with other styling binding at this `TNode`.
16233 * @param renderer Renderer to use if any updates.
16234 * @param oldKeyValueArray Previous value represented as `KeyValueArray`
16235 * @param newKeyValueArray Current value represented as `KeyValueArray`
16236 * @param isClassBased `true` if `class` (`false` if `style`)
16237 * @param bindingIndex Binding index of the binding.
16238 */
16239function updateStylingMap(tView, tNode, lView, renderer, oldKeyValueArray, newKeyValueArray, isClassBased, bindingIndex) {
16240 if (oldKeyValueArray === NO_CHANGE) {
16241 // On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.
16242 oldKeyValueArray = EMPTY_ARRAY$3;
16243 }
16244 let oldIndex = 0;
16245 let newIndex = 0;
16246 let oldKey = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;
16247 let newKey = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;
16248 while (oldKey !== null || newKey !== null) {
16249 ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');
16250 ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');
16251 const oldValue = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;
16252 const newValue = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;
16253 let setKey = null;
16254 let setValue = undefined;
16255 if (oldKey === newKey) {
16256 // UPDATE: Keys are equal => new value is overwriting old value.
16257 oldIndex += 2;
16258 newIndex += 2;
16259 if (oldValue !== newValue) {
16260 setKey = newKey;
16261 setValue = newValue;
16262 }
16263 }
16264 else if (newKey === null || oldKey !== null && oldKey < newKey) {
16265 // DELETE: oldKey key is missing or we did not find the oldKey in the newValue
16266 // (because the keyValueArray is sorted and `newKey` is found later alphabetically).
16267 // `"background" < "color"` so we need to delete `"background"` because it is not found in the
16268 // new array.
16269 oldIndex += 2;
16270 setKey = oldKey;
16271 }
16272 else {
16273 // CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.
16274 // `"color" > "background"` so we need to add `color` because it is in new array but not in
16275 // old array.
16276 ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');
16277 newIndex += 2;
16278 setKey = newKey;
16279 setValue = newValue;
16280 }
16281 if (setKey !== null) {
16282 updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);
16283 }
16284 oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;
16285 newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;
16286 }
16287}
16288/**
16289 * Update a simple (property name) styling.
16290 *
16291 * This function takes `prop` and updates the DOM to that value. The function takes the binding
16292 * value as well as binding priority into consideration to determine which value should be written
16293 * to DOM. (For example it may be determined that there is a higher priority overwrite which blocks
16294 * the DOM write, or if the value goes to `undefined` a lower priority overwrite may be consulted.)
16295 *
16296 * @param tView Associated `TView.data` contains the linked list of binding priorities.
16297 * @param tNode `TNode` where the binding is located.
16298 * @param lView `LView` contains the values associated with other styling binding at this `TNode`.
16299 * @param renderer Renderer to use if any updates.
16300 * @param prop Either style property name or a class name.
16301 * @param value Either style value for `prop` or `true`/`false` if `prop` is class.
16302 * @param isClassBased `true` if `class` (`false` if `style`)
16303 * @param bindingIndex Binding index of the binding.
16304 */
16305function updateStyling(tView, tNode, lView, renderer, prop, value, isClassBased, bindingIndex) {
16306 if (tNode.type !== 3 /* Element */) {
16307 // It is possible to have styling on non-elements (such as ng-container).
16308 // This is rare, but it does happen. In such a case, just ignore the binding.
16309 return;
16310 }
16311 const tData = tView.data;
16312 const tRange = tData[bindingIndex + 1];
16313 const higherPriorityValue = getTStylingRangeNextDuplicate(tRange) ?
16314 findStylingValue(tData, tNode, lView, prop, getTStylingRangeNext(tRange), isClassBased) :
16315 undefined;
16316 if (!isStylingValuePresent(higherPriorityValue)) {
16317 // We don't have a next duplicate, or we did not find a duplicate value.
16318 if (!isStylingValuePresent(value)) {
16319 // We should delete current value or restore to lower priority value.
16320 if (getTStylingRangePrevDuplicate(tRange)) {
16321 // We have a possible prev duplicate, let's retrieve it.
16322 value = findStylingValue(tData, null, lView, prop, bindingIndex, isClassBased);
16323 }
16324 }
16325 const rNode = getNativeByIndex(getSelectedIndex(), lView);
16326 applyStyling(renderer, isClassBased, rNode, prop, value);
16327 }
16328}
16329/**
16330 * Search for styling value with higher priority which is overwriting current value, or a
16331 * value of lower priority to which we should fall back if the value is `undefined`.
16332 *
16333 * When value is being applied at a location, related values need to be consulted.
16334 * - If there is a higher priority binding, we should be using that one instead.
16335 * For example `<div [style]="{color:exp1}" [style.color]="exp2">` change to `exp1`
16336 * requires that we check `exp2` to see if it is set to value other than `undefined`.
16337 * - If there is a lower priority binding and we are changing to `undefined`
16338 * For example `<div [style]="{color:exp1}" [style.color]="exp2">` change to `exp2` to
16339 * `undefined` requires that we check `exp1` (and static values) and use that as new value.
16340 *
16341 * NOTE: The styling stores two values.
16342 * 1. The raw value which came from the application is stored at `index + 0` location. (This value
16343 * is used for dirty checking).
16344 * 2. The normalized value is stored at `index + 1`.
16345 *
16346 * @param tData `TData` used for traversing the priority.
16347 * @param tNode `TNode` to use for resolving static styling. Also controls search direction.
16348 * - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true.
16349 * If no value found consult `tNode.residualStyle`/`tNode.residualClass` for default value.
16350 * - `null` search prev and go all the way to end. Return last value where
16351 * `isStylingValuePresent(value)` is true.
16352 * @param lView `LView` used for retrieving the actual values.
16353 * @param prop Property which we are interested in.
16354 * @param index Starting index in the linked list of styling bindings where the search should start.
16355 * @param isClassBased `true` if `class` (`false` if `style`)
16356 */
16357function findStylingValue(tData, tNode, lView, prop, index, isClassBased) {
16358 // `TNode` to use for resolving static styling. Also controls search direction.
16359 // - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true.
16360 // If no value found consult `tNode.residualStyle`/`tNode.residualClass` for default value.
16361 // - `null` search prev and go all the way to end. Return last value where
16362 // `isStylingValuePresent(value)` is true.
16363 const isPrevDirection = tNode === null;
16364 let value = undefined;
16365 while (index > 0) {
16366 const rawKey = tData[index];
16367 const containsStatics = Array.isArray(rawKey);
16368 // Unwrap the key if we contain static values.
16369 const key = containsStatics ? rawKey[1] : rawKey;
16370 const isStylingMap = key === null;
16371 let valueAtLViewIndex = lView[index + 1];
16372 if (valueAtLViewIndex === NO_CHANGE) {
16373 // In firstUpdatePass the styling instructions create a linked list of styling.
16374 // On subsequent passes it is possible for a styling instruction to try to read a binding
16375 // which
16376 // has not yet executed. In that case we will find `NO_CHANGE` and we should assume that
16377 // we have `undefined` (or empty array in case of styling-map instruction) instead. This
16378 // allows the resolution to apply the value (which may later be overwritten when the
16379 // binding actually executes.)
16380 valueAtLViewIndex = isStylingMap ? EMPTY_ARRAY$3 : undefined;
16381 }
16382 let currentValue = isStylingMap ? keyValueArrayGet(valueAtLViewIndex, prop) :
16383 key === prop ? valueAtLViewIndex : undefined;
16384 if (containsStatics && !isStylingValuePresent(currentValue)) {
16385 currentValue = keyValueArrayGet(rawKey, prop);
16386 }
16387 if (isStylingValuePresent(currentValue)) {
16388 value = currentValue;
16389 if (isPrevDirection) {
16390 return value;
16391 }
16392 }
16393 const tRange = tData[index + 1];
16394 index = isPrevDirection ? getTStylingRangePrev(tRange) : getTStylingRangeNext(tRange);
16395 }
16396 if (tNode !== null) {
16397 // in case where we are going in next direction AND we did not find anything, we need to
16398 // consult residual styling
16399 let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles;
16400 if (residual != null /** OR residual !=== undefined */) {
16401 value = keyValueArrayGet(residual, prop);
16402 }
16403 }
16404 return value;
16405}
16406/**
16407 * Determines if the binding value should be used (or if the value is 'undefined' and hence priority
16408 * resolution should be used.)
16409 *
16410 * @param value Binding style value.
16411 */
16412function isStylingValuePresent(value) {
16413 // Currently only `undefined` value is considered non-binding. That is `undefined` says I don't
16414 // have an opinion as to what this binding should be and you should consult other bindings by
16415 // priority to determine the valid value.
16416 // This is extracted into a single function so that we have a single place to control this.
16417 return value !== undefined;
16418}
16419/**
16420 * Normalizes and/or adds a suffix to the value.
16421 *
16422 * If value is `null`/`undefined` no suffix is added
16423 * @param value
16424 * @param suffix
16425 */
16426function normalizeSuffix(value, suffix) {
16427 if (value == null /** || value === undefined */) {
16428 // do nothing
16429 }
16430 else if (typeof suffix === 'string') {
16431 value = value + suffix;
16432 }
16433 else if (typeof value === 'object') {
16434 value = stringify(unwrapSafeValue(value));
16435 }
16436 return value;
16437}
16438/**
16439 * Tests if the `TNode` has input shadow.
16440 *
16441 * An input shadow is when a directive steals (shadows) the input by using `@Input('style')` or
16442 * `@Input('class')` as input.
16443 *
16444 * @param tNode `TNode` which we would like to see if it has shadow.
16445 * @param isClassBased `true` if `class` (`false` if `style`)
16446 */
16447function hasStylingInputShadow(tNode, isClassBased) {
16448 return (tNode.flags & (isClassBased ? 16 /* hasClassInput */ : 32 /* hasStyleInput */)) !== 0;
16449}
16450
16451/**
16452 * @license
16453 * Copyright Google LLC All Rights Reserved.
16454 *
16455 * Use of this source code is governed by an MIT-style license that can be
16456 * found in the LICENSE file at https://angular.io/license
16457 */
16458/**
16459 * Create static text node
16460 *
16461 * @param index Index of the node in the data array
16462 * @param value Static string value to write.
16463 *
16464 * @codeGenApi
16465 */
16466function ɵɵtext(index, value = '') {
16467 const lView = getLView();
16468 const tView = getTView();
16469 const adjustedIndex = index + HEADER_OFFSET;
16470 ngDevMode &&
16471 assertEqual(getBindingIndex(), tView.bindingStartIndex, 'text nodes should be created before any bindings');
16472 ngDevMode && assertIndexInRange(lView, adjustedIndex);
16473 const tNode = tView.firstCreatePass ?
16474 getOrCreateTNode(tView, lView[T_HOST], index, 3 /* Element */, null, null) :
16475 tView.data[adjustedIndex];
16476 const textNative = lView[adjustedIndex] = createTextNode(value, lView[RENDERER]);
16477 appendChild(tView, lView, textNative, tNode);
16478 // Text nodes are self closing.
16479 setPreviousOrParentTNode(tNode, false);
16480}
16481
16482/**
16483 * @license
16484 * Copyright Google LLC All Rights Reserved.
16485 *
16486 * Use of this source code is governed by an MIT-style license that can be
16487 * found in the LICENSE file at https://angular.io/license
16488 */
16489/**
16490 *
16491 * Update text content with a lone bound value
16492 *
16493 * Used when a text node has 1 interpolated value in it, an no additional text
16494 * surrounds that interpolated value:
16495 *
16496 * ```html
16497 * <div>{{v0}}</div>
16498 * ```
16499 *
16500 * Its compiled representation is:
16501 *
16502 * ```ts
16503 * ɵɵtextInterpolate(v0);
16504 * ```
16505 * @returns itself, so that it may be chained.
16506 * @see textInterpolateV
16507 * @codeGenApi
16508 */
16509function ɵɵtextInterpolate(v0) {
16510 ɵɵtextInterpolate1('', v0, '');
16511 return ɵɵtextInterpolate;
16512}
16513/**
16514 *
16515 * Update text content with single bound value surrounded by other text.
16516 *
16517 * Used when a text node has 1 interpolated value in it:
16518 *
16519 * ```html
16520 * <div>prefix{{v0}}suffix</div>
16521 * ```
16522 *
16523 * Its compiled representation is:
16524 *
16525 * ```ts
16526 * ɵɵtextInterpolate1('prefix', v0, 'suffix');
16527 * ```
16528 * @returns itself, so that it may be chained.
16529 * @see textInterpolateV
16530 * @codeGenApi
16531 */
16532function ɵɵtextInterpolate1(prefix, v0, suffix) {
16533 const lView = getLView();
16534 const interpolated = interpolation1(lView, prefix, v0, suffix);
16535 if (interpolated !== NO_CHANGE) {
16536 textBindingInternal(lView, getSelectedIndex(), interpolated);
16537 }
16538 return ɵɵtextInterpolate1;
16539}
16540/**
16541 *
16542 * Update text content with 2 bound values surrounded by other text.
16543 *
16544 * Used when a text node has 2 interpolated values in it:
16545 *
16546 * ```html
16547 * <div>prefix{{v0}}-{{v1}}suffix</div>
16548 * ```
16549 *
16550 * Its compiled representation is:
16551 *
16552 * ```ts
16553 * ɵɵtextInterpolate2('prefix', v0, '-', v1, 'suffix');
16554 * ```
16555 * @returns itself, so that it may be chained.
16556 * @see textInterpolateV
16557 * @codeGenApi
16558 */
16559function ɵɵtextInterpolate2(prefix, v0, i0, v1, suffix) {
16560 const lView = getLView();
16561 const interpolated = interpolation2(lView, prefix, v0, i0, v1, suffix);
16562 if (interpolated !== NO_CHANGE) {
16563 textBindingInternal(lView, getSelectedIndex(), interpolated);
16564 }
16565 return ɵɵtextInterpolate2;
16566}
16567/**
16568 *
16569 * Update text content with 3 bound values surrounded by other text.
16570 *
16571 * Used when a text node has 3 interpolated values in it:
16572 *
16573 * ```html
16574 * <div>prefix{{v0}}-{{v1}}-{{v2}}suffix</div>
16575 * ```
16576 *
16577 * Its compiled representation is:
16578 *
16579 * ```ts
16580 * ɵɵtextInterpolate3(
16581 * 'prefix', v0, '-', v1, '-', v2, 'suffix');
16582 * ```
16583 * @returns itself, so that it may be chained.
16584 * @see textInterpolateV
16585 * @codeGenApi
16586 */
16587function ɵɵtextInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
16588 const lView = getLView();
16589 const interpolated = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
16590 if (interpolated !== NO_CHANGE) {
16591 textBindingInternal(lView, getSelectedIndex(), interpolated);
16592 }
16593 return ɵɵtextInterpolate3;
16594}
16595/**
16596 *
16597 * Update text content with 4 bound values surrounded by other text.
16598 *
16599 * Used when a text node has 4 interpolated values in it:
16600 *
16601 * ```html
16602 * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix</div>
16603 * ```
16604 *
16605 * Its compiled representation is:
16606 *
16607 * ```ts
16608 * ɵɵtextInterpolate4(
16609 * 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
16610 * ```
16611 * @returns itself, so that it may be chained.
16612 * @see ɵɵtextInterpolateV
16613 * @codeGenApi
16614 */
16615function ɵɵtextInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
16616 const lView = getLView();
16617 const interpolated = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
16618 if (interpolated !== NO_CHANGE) {
16619 textBindingInternal(lView, getSelectedIndex(), interpolated);
16620 }
16621 return ɵɵtextInterpolate4;
16622}
16623/**
16624 *
16625 * Update text content with 5 bound values surrounded by other text.
16626 *
16627 * Used when a text node has 5 interpolated values in it:
16628 *
16629 * ```html
16630 * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix</div>
16631 * ```
16632 *
16633 * Its compiled representation is:
16634 *
16635 * ```ts
16636 * ɵɵtextInterpolate5(
16637 * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
16638 * ```
16639 * @returns itself, so that it may be chained.
16640 * @see textInterpolateV
16641 * @codeGenApi
16642 */
16643function ɵɵtextInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
16644 const lView = getLView();
16645 const interpolated = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
16646 if (interpolated !== NO_CHANGE) {
16647 textBindingInternal(lView, getSelectedIndex(), interpolated);
16648 }
16649 return ɵɵtextInterpolate5;
16650}
16651/**
16652 *
16653 * Update text content with 6 bound values surrounded by other text.
16654 *
16655 * Used when a text node has 6 interpolated values in it:
16656 *
16657 * ```html
16658 * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix</div>
16659 * ```
16660 *
16661 * Its compiled representation is:
16662 *
16663 * ```ts
16664 * ɵɵtextInterpolate6(
16665 * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
16666 * ```
16667 *
16668 * @param i4 Static value used for concatenation only.
16669 * @param v5 Value checked for change. @returns itself, so that it may be chained.
16670 * @see textInterpolateV
16671 * @codeGenApi
16672 */
16673function ɵɵtextInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
16674 const lView = getLView();
16675 const interpolated = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
16676 if (interpolated !== NO_CHANGE) {
16677 textBindingInternal(lView, getSelectedIndex(), interpolated);
16678 }
16679 return ɵɵtextInterpolate6;
16680}
16681/**
16682 *
16683 * Update text content with 7 bound values surrounded by other text.
16684 *
16685 * Used when a text node has 7 interpolated values in it:
16686 *
16687 * ```html
16688 * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix</div>
16689 * ```
16690 *
16691 * Its compiled representation is:
16692 *
16693 * ```ts
16694 * ɵɵtextInterpolate7(
16695 * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
16696 * ```
16697 * @returns itself, so that it may be chained.
16698 * @see textInterpolateV
16699 * @codeGenApi
16700 */
16701function ɵɵtextInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
16702 const lView = getLView();
16703 const interpolated = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
16704 if (interpolated !== NO_CHANGE) {
16705 textBindingInternal(lView, getSelectedIndex(), interpolated);
16706 }
16707 return ɵɵtextInterpolate7;
16708}
16709/**
16710 *
16711 * Update text content with 8 bound values surrounded by other text.
16712 *
16713 * Used when a text node has 8 interpolated values in it:
16714 *
16715 * ```html
16716 * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix</div>
16717 * ```
16718 *
16719 * Its compiled representation is:
16720 *
16721 * ```ts
16722 * ɵɵtextInterpolate8(
16723 * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
16724 * ```
16725 * @returns itself, so that it may be chained.
16726 * @see textInterpolateV
16727 * @codeGenApi
16728 */
16729function ɵɵtextInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
16730 const lView = getLView();
16731 const interpolated = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
16732 if (interpolated !== NO_CHANGE) {
16733 textBindingInternal(lView, getSelectedIndex(), interpolated);
16734 }
16735 return ɵɵtextInterpolate8;
16736}
16737/**
16738 * Update text content with 9 or more bound values other surrounded by text.
16739 *
16740 * Used when the number of interpolated values exceeds 8.
16741 *
16742 * ```html
16743 * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix</div>
16744 * ```
16745 *
16746 * Its compiled representation is:
16747 *
16748 * ```ts
16749 * ɵɵtextInterpolateV(
16750 * ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
16751 * 'suffix']);
16752 * ```
16753 *.
16754 * @param values The collection of values and the strings in between those values, beginning with
16755 * a string prefix and ending with a string suffix.
16756 * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
16757 *
16758 * @returns itself, so that it may be chained.
16759 * @codeGenApi
16760 */
16761function ɵɵtextInterpolateV(values) {
16762 const lView = getLView();
16763 const interpolated = interpolationV(lView, values);
16764 if (interpolated !== NO_CHANGE) {
16765 textBindingInternal(lView, getSelectedIndex(), interpolated);
16766 }
16767 return ɵɵtextInterpolateV;
16768}
16769
16770/**
16771 * @license
16772 * Copyright Google LLC All Rights Reserved.
16773 *
16774 * Use of this source code is governed by an MIT-style license that can be
16775 * found in the LICENSE file at https://angular.io/license
16776 */
16777/**
16778 *
16779 * Update an interpolated class on an element with single bound value surrounded by text.
16780 *
16781 * Used when the value passed to a property has 1 interpolated value in it:
16782 *
16783 * ```html
16784 * <div class="prefix{{v0}}suffix"></div>
16785 * ```
16786 *
16787 * Its compiled representation is:
16788 *
16789 * ```ts
16790 * ɵɵclassMapInterpolate1('prefix', v0, 'suffix');
16791 * ```
16792 *
16793 * @param prefix Static value used for concatenation only.
16794 * @param v0 Value checked for change.
16795 * @param suffix Static value used for concatenation only.
16796 * @codeGenApi
16797 */
16798function ɵɵclassMapInterpolate1(prefix, v0, suffix) {
16799 const lView = getLView();
16800 const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
16801 checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
16802}
16803/**
16804 *
16805 * Update an interpolated class on an element with 2 bound values surrounded by text.
16806 *
16807 * Used when the value passed to a property has 2 interpolated values in it:
16808 *
16809 * ```html
16810 * <div class="prefix{{v0}}-{{v1}}suffix"></div>
16811 * ```
16812 *
16813 * Its compiled representation is:
16814 *
16815 * ```ts
16816 * ɵɵclassMapInterpolate2('prefix', v0, '-', v1, 'suffix');
16817 * ```
16818 *
16819 * @param prefix Static value used for concatenation only.
16820 * @param v0 Value checked for change.
16821 * @param i0 Static value used for concatenation only.
16822 * @param v1 Value checked for change.
16823 * @param suffix Static value used for concatenation only.
16824 * @codeGenApi
16825 */
16826function ɵɵclassMapInterpolate2(prefix, v0, i0, v1, suffix) {
16827 const lView = getLView();
16828 const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
16829 checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
16830}
16831/**
16832 *
16833 * Update an interpolated class on an element with 3 bound values surrounded by text.
16834 *
16835 * Used when the value passed to a property has 3 interpolated values in it:
16836 *
16837 * ```html
16838 * <div class="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
16839 * ```
16840 *
16841 * Its compiled representation is:
16842 *
16843 * ```ts
16844 * ɵɵclassMapInterpolate3(
16845 * 'prefix', v0, '-', v1, '-', v2, 'suffix');
16846 * ```
16847 *
16848 * @param prefix Static value used for concatenation only.
16849 * @param v0 Value checked for change.
16850 * @param i0 Static value used for concatenation only.
16851 * @param v1 Value checked for change.
16852 * @param i1 Static value used for concatenation only.
16853 * @param v2 Value checked for change.
16854 * @param suffix Static value used for concatenation only.
16855 * @codeGenApi
16856 */
16857function ɵɵclassMapInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
16858 const lView = getLView();
16859 const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
16860 checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
16861}
16862/**
16863 *
16864 * Update an interpolated class on an element with 4 bound values surrounded by text.
16865 *
16866 * Used when the value passed to a property has 4 interpolated values in it:
16867 *
16868 * ```html
16869 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
16870 * ```
16871 *
16872 * Its compiled representation is:
16873 *
16874 * ```ts
16875 * ɵɵclassMapInterpolate4(
16876 * 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
16877 * ```
16878 *
16879 * @param prefix Static value used for concatenation only.
16880 * @param v0 Value checked for change.
16881 * @param i0 Static value used for concatenation only.
16882 * @param v1 Value checked for change.
16883 * @param i1 Static value used for concatenation only.
16884 * @param v2 Value checked for change.
16885 * @param i2 Static value used for concatenation only.
16886 * @param v3 Value checked for change.
16887 * @param suffix Static value used for concatenation only.
16888 * @codeGenApi
16889 */
16890function ɵɵclassMapInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
16891 const lView = getLView();
16892 const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
16893 checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
16894}
16895/**
16896 *
16897 * Update an interpolated class on an element with 5 bound values surrounded by text.
16898 *
16899 * Used when the value passed to a property has 5 interpolated values in it:
16900 *
16901 * ```html
16902 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
16903 * ```
16904 *
16905 * Its compiled representation is:
16906 *
16907 * ```ts
16908 * ɵɵclassMapInterpolate5(
16909 * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
16910 * ```
16911 *
16912 * @param prefix Static value used for concatenation only.
16913 * @param v0 Value checked for change.
16914 * @param i0 Static value used for concatenation only.
16915 * @param v1 Value checked for change.
16916 * @param i1 Static value used for concatenation only.
16917 * @param v2 Value checked for change.
16918 * @param i2 Static value used for concatenation only.
16919 * @param v3 Value checked for change.
16920 * @param i3 Static value used for concatenation only.
16921 * @param v4 Value checked for change.
16922 * @param suffix Static value used for concatenation only.
16923 * @codeGenApi
16924 */
16925function ɵɵclassMapInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
16926 const lView = getLView();
16927 const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
16928 checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
16929}
16930/**
16931 *
16932 * Update an interpolated class on an element with 6 bound values surrounded by text.
16933 *
16934 * Used when the value passed to a property has 6 interpolated values in it:
16935 *
16936 * ```html
16937 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
16938 * ```
16939 *
16940 * Its compiled representation is:
16941 *
16942 * ```ts
16943 * ɵɵclassMapInterpolate6(
16944 * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
16945 * ```
16946 *
16947 * @param prefix Static value used for concatenation only.
16948 * @param v0 Value checked for change.
16949 * @param i0 Static value used for concatenation only.
16950 * @param v1 Value checked for change.
16951 * @param i1 Static value used for concatenation only.
16952 * @param v2 Value checked for change.
16953 * @param i2 Static value used for concatenation only.
16954 * @param v3 Value checked for change.
16955 * @param i3 Static value used for concatenation only.
16956 * @param v4 Value checked for change.
16957 * @param i4 Static value used for concatenation only.
16958 * @param v5 Value checked for change.
16959 * @param suffix Static value used for concatenation only.
16960 * @codeGenApi
16961 */
16962function ɵɵclassMapInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
16963 const lView = getLView();
16964 const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
16965 checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
16966}
16967/**
16968 *
16969 * Update an interpolated class on an element with 7 bound values surrounded by text.
16970 *
16971 * Used when the value passed to a property has 7 interpolated values in it:
16972 *
16973 * ```html
16974 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
16975 * ```
16976 *
16977 * Its compiled representation is:
16978 *
16979 * ```ts
16980 * ɵɵclassMapInterpolate7(
16981 * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
16982 * ```
16983 *
16984 * @param prefix Static value used for concatenation only.
16985 * @param v0 Value checked for change.
16986 * @param i0 Static value used for concatenation only.
16987 * @param v1 Value checked for change.
16988 * @param i1 Static value used for concatenation only.
16989 * @param v2 Value checked for change.
16990 * @param i2 Static value used for concatenation only.
16991 * @param v3 Value checked for change.
16992 * @param i3 Static value used for concatenation only.
16993 * @param v4 Value checked for change.
16994 * @param i4 Static value used for concatenation only.
16995 * @param v5 Value checked for change.
16996 * @param i5 Static value used for concatenation only.
16997 * @param v6 Value checked for change.
16998 * @param suffix Static value used for concatenation only.
16999 * @codeGenApi
17000 */
17001function ɵɵclassMapInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
17002 const lView = getLView();
17003 const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
17004 checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
17005}
17006/**
17007 *
17008 * Update an interpolated class on an element with 8 bound values surrounded by text.
17009 *
17010 * Used when the value passed to a property has 8 interpolated values in it:
17011 *
17012 * ```html
17013 * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
17014 * ```
17015 *
17016 * Its compiled representation is:
17017 *
17018 * ```ts
17019 * ɵɵclassMapInterpolate8(
17020 * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
17021 * ```
17022 *
17023 * @param prefix Static value used for concatenation only.
17024 * @param v0 Value checked for change.
17025 * @param i0 Static value used for concatenation only.
17026 * @param v1 Value checked for change.
17027 * @param i1 Static value used for concatenation only.
17028 * @param v2 Value checked for change.
17029 * @param i2 Static value used for concatenation only.
17030 * @param v3 Value checked for change.
17031 * @param i3 Static value used for concatenation only.
17032 * @param v4 Value checked for change.
17033 * @param i4 Static value used for concatenation only.
17034 * @param v5 Value checked for change.
17035 * @param i5 Static value used for concatenation only.
17036 * @param v6 Value checked for change.
17037 * @param i6 Static value used for concatenation only.
17038 * @param v7 Value checked for change.
17039 * @param suffix Static value used for concatenation only.
17040 * @codeGenApi
17041 */
17042function ɵɵclassMapInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
17043 const lView = getLView();
17044 const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
17045 checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
17046}
17047/**
17048 * Update an interpolated class on an element with 9 or more bound values surrounded by text.
17049 *
17050 * Used when the number of interpolated values exceeds 8.
17051 *
17052 * ```html
17053 * <div
17054 * class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div>
17055 * ```
17056 *
17057 * Its compiled representation is:
17058 *
17059 * ```ts
17060 * ɵɵclassMapInterpolateV(
17061 * ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
17062 * 'suffix']);
17063 * ```
17064 *.
17065 * @param values The collection of values and the strings in-between those values, beginning with
17066 * a string prefix and ending with a string suffix.
17067 * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
17068 * @codeGenApi
17069 */
17070function ɵɵclassMapInterpolateV(values) {
17071 const lView = getLView();
17072 const interpolatedValue = interpolationV(lView, values);
17073 checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true);
17074}
17075
17076/**
17077 * @license
17078 * Copyright Google LLC All Rights Reserved.
17079 *
17080 * Use of this source code is governed by an MIT-style license that can be
17081 * found in the LICENSE file at https://angular.io/license
17082 */
17083/**
17084 *
17085 * Update an interpolated style on an element with single bound value surrounded by text.
17086 *
17087 * Used when the value passed to a property has 1 interpolated value in it:
17088 *
17089 * ```html
17090 * <div style="key: {{v0}}suffix"></div>
17091 * ```
17092 *
17093 * Its compiled representation is:
17094 *
17095 * ```ts
17096 * ɵɵstyleMapInterpolate1('key: ', v0, 'suffix');
17097 * ```
17098 *
17099 * @param prefix Static value used for concatenation only.
17100 * @param v0 Value checked for change.
17101 * @param suffix Static value used for concatenation only.
17102 * @codeGenApi
17103 */
17104function ɵɵstyleMapInterpolate1(prefix, v0, suffix) {
17105 const lView = getLView();
17106 const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
17107 ɵɵstyleMap(interpolatedValue);
17108}
17109/**
17110 *
17111 * Update an interpolated style on an element with 2 bound values surrounded by text.
17112 *
17113 * Used when the value passed to a property has 2 interpolated values in it:
17114 *
17115 * ```html
17116 * <div style="key: {{v0}}; key1: {{v1}}suffix"></div>
17117 * ```
17118 *
17119 * Its compiled representation is:
17120 *
17121 * ```ts
17122 * ɵɵstyleMapInterpolate2('key: ', v0, '; key1: ', v1, 'suffix');
17123 * ```
17124 *
17125 * @param prefix Static value used for concatenation only.
17126 * @param v0 Value checked for change.
17127 * @param i0 Static value used for concatenation only.
17128 * @param v1 Value checked for change.
17129 * @param suffix Static value used for concatenation only.
17130 * @codeGenApi
17131 */
17132function ɵɵstyleMapInterpolate2(prefix, v0, i0, v1, suffix) {
17133 const lView = getLView();
17134 const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
17135 ɵɵstyleMap(interpolatedValue);
17136}
17137/**
17138 *
17139 * Update an interpolated style on an element with 3 bound values surrounded by text.
17140 *
17141 * Used when the value passed to a property has 3 interpolated values in it:
17142 *
17143 * ```html
17144 * <div style="key: {{v0}}; key2: {{v1}}; key2: {{v2}}suffix"></div>
17145 * ```
17146 *
17147 * Its compiled representation is:
17148 *
17149 * ```ts
17150 * ɵɵstyleMapInterpolate3(
17151 * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, 'suffix');
17152 * ```
17153 *
17154 * @param prefix Static value used for concatenation only.
17155 * @param v0 Value checked for change.
17156 * @param i0 Static value used for concatenation only.
17157 * @param v1 Value checked for change.
17158 * @param i1 Static value used for concatenation only.
17159 * @param v2 Value checked for change.
17160 * @param suffix Static value used for concatenation only.
17161 * @codeGenApi
17162 */
17163function ɵɵstyleMapInterpolate3(prefix, v0, i0, v1, i1, v2, suffix) {
17164 const lView = getLView();
17165 const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
17166 ɵɵstyleMap(interpolatedValue);
17167}
17168/**
17169 *
17170 * Update an interpolated style on an element with 4 bound values surrounded by text.
17171 *
17172 * Used when the value passed to a property has 4 interpolated values in it:
17173 *
17174 * ```html
17175 * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}suffix"></div>
17176 * ```
17177 *
17178 * Its compiled representation is:
17179 *
17180 * ```ts
17181 * ɵɵstyleMapInterpolate4(
17182 * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, 'suffix');
17183 * ```
17184 *
17185 * @param prefix Static value used for concatenation only.
17186 * @param v0 Value checked for change.
17187 * @param i0 Static value used for concatenation only.
17188 * @param v1 Value checked for change.
17189 * @param i1 Static value used for concatenation only.
17190 * @param v2 Value checked for change.
17191 * @param i2 Static value used for concatenation only.
17192 * @param v3 Value checked for change.
17193 * @param suffix Static value used for concatenation only.
17194 * @codeGenApi
17195 */
17196function ɵɵstyleMapInterpolate4(prefix, v0, i0, v1, i1, v2, i2, v3, suffix) {
17197 const lView = getLView();
17198 const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
17199 ɵɵstyleMap(interpolatedValue);
17200}
17201/**
17202 *
17203 * Update an interpolated style on an element with 5 bound values surrounded by text.
17204 *
17205 * Used when the value passed to a property has 5 interpolated values in it:
17206 *
17207 * ```html
17208 * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}suffix"></div>
17209 * ```
17210 *
17211 * Its compiled representation is:
17212 *
17213 * ```ts
17214 * ɵɵstyleMapInterpolate5(
17215 * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, 'suffix');
17216 * ```
17217 *
17218 * @param prefix Static value used for concatenation only.
17219 * @param v0 Value checked for change.
17220 * @param i0 Static value used for concatenation only.
17221 * @param v1 Value checked for change.
17222 * @param i1 Static value used for concatenation only.
17223 * @param v2 Value checked for change.
17224 * @param i2 Static value used for concatenation only.
17225 * @param v3 Value checked for change.
17226 * @param i3 Static value used for concatenation only.
17227 * @param v4 Value checked for change.
17228 * @param suffix Static value used for concatenation only.
17229 * @codeGenApi
17230 */
17231function ɵɵstyleMapInterpolate5(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix) {
17232 const lView = getLView();
17233 const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
17234 ɵɵstyleMap(interpolatedValue);
17235}
17236/**
17237 *
17238 * Update an interpolated style on an element with 6 bound values surrounded by text.
17239 *
17240 * Used when the value passed to a property has 6 interpolated values in it:
17241 *
17242 * ```html
17243 * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}};
17244 * key5: {{v5}}suffix"></div>
17245 * ```
17246 *
17247 * Its compiled representation is:
17248 *
17249 * ```ts
17250 * ɵɵstyleMapInterpolate6(
17251 * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
17252 * 'suffix');
17253 * ```
17254 *
17255 * @param prefix Static value used for concatenation only.
17256 * @param v0 Value checked for change.
17257 * @param i0 Static value used for concatenation only.
17258 * @param v1 Value checked for change.
17259 * @param i1 Static value used for concatenation only.
17260 * @param v2 Value checked for change.
17261 * @param i2 Static value used for concatenation only.
17262 * @param v3 Value checked for change.
17263 * @param i3 Static value used for concatenation only.
17264 * @param v4 Value checked for change.
17265 * @param i4 Static value used for concatenation only.
17266 * @param v5 Value checked for change.
17267 * @param suffix Static value used for concatenation only.
17268 * @codeGenApi
17269 */
17270function ɵɵstyleMapInterpolate6(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix) {
17271 const lView = getLView();
17272 const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
17273 ɵɵstyleMap(interpolatedValue);
17274}
17275/**
17276 *
17277 * Update an interpolated style on an element with 7 bound values surrounded by text.
17278 *
17279 * Used when the value passed to a property has 7 interpolated values in it:
17280 *
17281 * ```html
17282 * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
17283 * key6: {{v6}}suffix"></div>
17284 * ```
17285 *
17286 * Its compiled representation is:
17287 *
17288 * ```ts
17289 * ɵɵstyleMapInterpolate7(
17290 * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
17291 * '; key6: ', v6, 'suffix');
17292 * ```
17293 *
17294 * @param prefix Static value used for concatenation only.
17295 * @param v0 Value checked for change.
17296 * @param i0 Static value used for concatenation only.
17297 * @param v1 Value checked for change.
17298 * @param i1 Static value used for concatenation only.
17299 * @param v2 Value checked for change.
17300 * @param i2 Static value used for concatenation only.
17301 * @param v3 Value checked for change.
17302 * @param i3 Static value used for concatenation only.
17303 * @param v4 Value checked for change.
17304 * @param i4 Static value used for concatenation only.
17305 * @param v5 Value checked for change.
17306 * @param i5 Static value used for concatenation only.
17307 * @param v6 Value checked for change.
17308 * @param suffix Static value used for concatenation only.
17309 * @codeGenApi
17310 */
17311function ɵɵstyleMapInterpolate7(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix) {
17312 const lView = getLView();
17313 const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
17314 ɵɵstyleMap(interpolatedValue);
17315}
17316/**
17317 *
17318 * Update an interpolated style on an element with 8 bound values surrounded by text.
17319 *
17320 * Used when the value passed to a property has 8 interpolated values in it:
17321 *
17322 * ```html
17323 * <div style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
17324 * key6: {{v6}}; key7: {{v7}}suffix"></div>
17325 * ```
17326 *
17327 * Its compiled representation is:
17328 *
17329 * ```ts
17330 * ɵɵstyleMapInterpolate8(
17331 * 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
17332 * '; key6: ', v6, '; key7: ', v7, 'suffix');
17333 * ```
17334 *
17335 * @param prefix Static value used for concatenation only.
17336 * @param v0 Value checked for change.
17337 * @param i0 Static value used for concatenation only.
17338 * @param v1 Value checked for change.
17339 * @param i1 Static value used for concatenation only.
17340 * @param v2 Value checked for change.
17341 * @param i2 Static value used for concatenation only.
17342 * @param v3 Value checked for change.
17343 * @param i3 Static value used for concatenation only.
17344 * @param v4 Value checked for change.
17345 * @param i4 Static value used for concatenation only.
17346 * @param v5 Value checked for change.
17347 * @param i5 Static value used for concatenation only.
17348 * @param v6 Value checked for change.
17349 * @param i6 Static value used for concatenation only.
17350 * @param v7 Value checked for change.
17351 * @param suffix Static value used for concatenation only.
17352 * @codeGenApi
17353 */
17354function ɵɵstyleMapInterpolate8(prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix) {
17355 const lView = getLView();
17356 const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
17357 ɵɵstyleMap(interpolatedValue);
17358}
17359/**
17360 * Update an interpolated style on an element with 9 or more bound values surrounded by text.
17361 *
17362 * Used when the number of interpolated values exceeds 8.
17363 *
17364 * ```html
17365 * <div
17366 * class="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
17367 * key6: {{v6}}; key7: {{v7}}; key8: {{v8}}; key9: {{v9}}suffix"></div>
17368 * ```
17369 *
17370 * Its compiled representation is:
17371 *
17372 * ```ts
17373 * ɵɵstyleMapInterpolateV(
17374 * ['key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
17375 * '; key6: ', v6, '; key7: ', v7, '; key8: ', v8, '; key9: ', v9, 'suffix']);
17376 * ```
17377 *.
17378 * @param values The collection of values and the strings in-between those values, beginning with
17379 * a string prefix and ending with a string suffix.
17380 * (e.g. `['prefix', value0, '; key2: ', value1, '; key2: ', value2, ..., value99, 'suffix']`)
17381 * @codeGenApi
17382 */
17383function ɵɵstyleMapInterpolateV(values) {
17384 const lView = getLView();
17385 const interpolatedValue = interpolationV(lView, values);
17386 ɵɵstyleMap(interpolatedValue);
17387}
17388
17389/**
17390 * @license
17391 * Copyright Google LLC All Rights Reserved.
17392 *
17393 * Use of this source code is governed by an MIT-style license that can be
17394 * found in the LICENSE file at https://angular.io/license
17395 */
17396/**
17397 *
17398 * Update an interpolated style property on an element with single bound value surrounded by text.
17399 *
17400 * Used when the value passed to a property has 1 interpolated value in it:
17401 *
17402 * ```html
17403 * <div style.color="prefix{{v0}}suffix"></div>
17404 * ```
17405 *
17406 * Its compiled representation is:
17407 *
17408 * ```ts
17409 * ɵɵstylePropInterpolate1(0, 'prefix', v0, 'suffix');
17410 * ```
17411 *
17412 * @param styleIndex Index of style to update. This index value refers to the
17413 * index of the style in the style bindings array that was passed into
17414 * `styling`.
17415 * @param prefix Static value used for concatenation only.
17416 * @param v0 Value checked for change.
17417 * @param suffix Static value used for concatenation only.
17418 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
17419 * @returns itself, so that it may be chained.
17420 * @codeGenApi
17421 */
17422function ɵɵstylePropInterpolate1(prop, prefix, v0, suffix, valueSuffix) {
17423 const lView = getLView();
17424 const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
17425 checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
17426 return ɵɵstylePropInterpolate1;
17427}
17428/**
17429 *
17430 * Update an interpolated style property on an element with 2 bound values surrounded by text.
17431 *
17432 * Used when the value passed to a property has 2 interpolated values in it:
17433 *
17434 * ```html
17435 * <div style.color="prefix{{v0}}-{{v1}}suffix"></div>
17436 * ```
17437 *
17438 * Its compiled representation is:
17439 *
17440 * ```ts
17441 * ɵɵstylePropInterpolate2(0, 'prefix', v0, '-', v1, 'suffix');
17442 * ```
17443 *
17444 * @param styleIndex Index of style to update. This index value refers to the
17445 * index of the style in the style bindings array that was passed into
17446 * `styling`.
17447 * @param prefix Static value used for concatenation only.
17448 * @param v0 Value checked for change.
17449 * @param i0 Static value used for concatenation only.
17450 * @param v1 Value checked for change.
17451 * @param suffix Static value used for concatenation only.
17452 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
17453 * @returns itself, so that it may be chained.
17454 * @codeGenApi
17455 */
17456function ɵɵstylePropInterpolate2(prop, prefix, v0, i0, v1, suffix, valueSuffix) {
17457 const lView = getLView();
17458 const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
17459 checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
17460 return ɵɵstylePropInterpolate2;
17461}
17462/**
17463 *
17464 * Update an interpolated style property on an element with 3 bound values surrounded by text.
17465 *
17466 * Used when the value passed to a property has 3 interpolated values in it:
17467 *
17468 * ```html
17469 * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
17470 * ```
17471 *
17472 * Its compiled representation is:
17473 *
17474 * ```ts
17475 * ɵɵstylePropInterpolate3(0, 'prefix', v0, '-', v1, '-', v2, 'suffix');
17476 * ```
17477 *
17478 * @param styleIndex Index of style to update. This index value refers to the
17479 * index of the style in the style bindings array that was passed into
17480 * `styling`.
17481 * @param prefix Static value used for concatenation only.
17482 * @param v0 Value checked for change.
17483 * @param i0 Static value used for concatenation only.
17484 * @param v1 Value checked for change.
17485 * @param i1 Static value used for concatenation only.
17486 * @param v2 Value checked for change.
17487 * @param suffix Static value used for concatenation only.
17488 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
17489 * @returns itself, so that it may be chained.
17490 * @codeGenApi
17491 */
17492function ɵɵstylePropInterpolate3(prop, prefix, v0, i0, v1, i1, v2, suffix, valueSuffix) {
17493 const lView = getLView();
17494 const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
17495 checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
17496 return ɵɵstylePropInterpolate3;
17497}
17498/**
17499 *
17500 * Update an interpolated style property on an element with 4 bound values surrounded by text.
17501 *
17502 * Used when the value passed to a property has 4 interpolated values in it:
17503 *
17504 * ```html
17505 * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
17506 * ```
17507 *
17508 * Its compiled representation is:
17509 *
17510 * ```ts
17511 * ɵɵstylePropInterpolate4(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
17512 * ```
17513 *
17514 * @param styleIndex Index of style to update. This index value refers to the
17515 * index of the style in the style bindings array that was passed into
17516 * `styling`.
17517 * @param prefix Static value used for concatenation only.
17518 * @param v0 Value checked for change.
17519 * @param i0 Static value used for concatenation only.
17520 * @param v1 Value checked for change.
17521 * @param i1 Static value used for concatenation only.
17522 * @param v2 Value checked for change.
17523 * @param i2 Static value used for concatenation only.
17524 * @param v3 Value checked for change.
17525 * @param suffix Static value used for concatenation only.
17526 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
17527 * @returns itself, so that it may be chained.
17528 * @codeGenApi
17529 */
17530function ɵɵstylePropInterpolate4(prop, prefix, v0, i0, v1, i1, v2, i2, v3, suffix, valueSuffix) {
17531 const lView = getLView();
17532 const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
17533 checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
17534 return ɵɵstylePropInterpolate4;
17535}
17536/**
17537 *
17538 * Update an interpolated style property on an element with 5 bound values surrounded by text.
17539 *
17540 * Used when the value passed to a property has 5 interpolated values in it:
17541 *
17542 * ```html
17543 * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
17544 * ```
17545 *
17546 * Its compiled representation is:
17547 *
17548 * ```ts
17549 * ɵɵstylePropInterpolate5(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
17550 * ```
17551 *
17552 * @param styleIndex Index of style to update. This index value refers to the
17553 * index of the style in the style bindings array that was passed into
17554 * `styling`.
17555 * @param prefix Static value used for concatenation only.
17556 * @param v0 Value checked for change.
17557 * @param i0 Static value used for concatenation only.
17558 * @param v1 Value checked for change.
17559 * @param i1 Static value used for concatenation only.
17560 * @param v2 Value checked for change.
17561 * @param i2 Static value used for concatenation only.
17562 * @param v3 Value checked for change.
17563 * @param i3 Static value used for concatenation only.
17564 * @param v4 Value checked for change.
17565 * @param suffix Static value used for concatenation only.
17566 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
17567 * @returns itself, so that it may be chained.
17568 * @codeGenApi
17569 */
17570function ɵɵstylePropInterpolate5(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, valueSuffix) {
17571 const lView = getLView();
17572 const interpolatedValue = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix);
17573 checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
17574 return ɵɵstylePropInterpolate5;
17575}
17576/**
17577 *
17578 * Update an interpolated style property on an element with 6 bound values surrounded by text.
17579 *
17580 * Used when the value passed to a property has 6 interpolated values in it:
17581 *
17582 * ```html
17583 * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
17584 * ```
17585 *
17586 * Its compiled representation is:
17587 *
17588 * ```ts
17589 * ɵɵstylePropInterpolate6(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
17590 * ```
17591 *
17592 * @param styleIndex Index of style to update. This index value refers to the
17593 * index of the style in the style bindings array that was passed into
17594 * `styling`.
17595 * @param prefix Static value used for concatenation only.
17596 * @param v0 Value checked for change.
17597 * @param i0 Static value used for concatenation only.
17598 * @param v1 Value checked for change.
17599 * @param i1 Static value used for concatenation only.
17600 * @param v2 Value checked for change.
17601 * @param i2 Static value used for concatenation only.
17602 * @param v3 Value checked for change.
17603 * @param i3 Static value used for concatenation only.
17604 * @param v4 Value checked for change.
17605 * @param i4 Static value used for concatenation only.
17606 * @param v5 Value checked for change.
17607 * @param suffix Static value used for concatenation only.
17608 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
17609 * @returns itself, so that it may be chained.
17610 * @codeGenApi
17611 */
17612function ɵɵstylePropInterpolate6(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, valueSuffix) {
17613 const lView = getLView();
17614 const interpolatedValue = interpolation6(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix);
17615 checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
17616 return ɵɵstylePropInterpolate6;
17617}
17618/**
17619 *
17620 * Update an interpolated style property on an element with 7 bound values surrounded by text.
17621 *
17622 * Used when the value passed to a property has 7 interpolated values in it:
17623 *
17624 * ```html
17625 * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
17626 * ```
17627 *
17628 * Its compiled representation is:
17629 *
17630 * ```ts
17631 * ɵɵstylePropInterpolate7(
17632 * 0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
17633 * ```
17634 *
17635 * @param styleIndex Index of style to update. This index value refers to the
17636 * index of the style in the style bindings array that was passed into
17637 * `styling`.
17638 * @param prefix Static value used for concatenation only.
17639 * @param v0 Value checked for change.
17640 * @param i0 Static value used for concatenation only.
17641 * @param v1 Value checked for change.
17642 * @param i1 Static value used for concatenation only.
17643 * @param v2 Value checked for change.
17644 * @param i2 Static value used for concatenation only.
17645 * @param v3 Value checked for change.
17646 * @param i3 Static value used for concatenation only.
17647 * @param v4 Value checked for change.
17648 * @param i4 Static value used for concatenation only.
17649 * @param v5 Value checked for change.
17650 * @param i5 Static value used for concatenation only.
17651 * @param v6 Value checked for change.
17652 * @param suffix Static value used for concatenation only.
17653 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
17654 * @returns itself, so that it may be chained.
17655 * @codeGenApi
17656 */
17657function ɵɵstylePropInterpolate7(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, valueSuffix) {
17658 const lView = getLView();
17659 const interpolatedValue = interpolation7(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix);
17660 checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
17661 return ɵɵstylePropInterpolate7;
17662}
17663/**
17664 *
17665 * Update an interpolated style property on an element with 8 bound values surrounded by text.
17666 *
17667 * Used when the value passed to a property has 8 interpolated values in it:
17668 *
17669 * ```html
17670 * <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
17671 * ```
17672 *
17673 * Its compiled representation is:
17674 *
17675 * ```ts
17676 * ɵɵstylePropInterpolate8(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6,
17677 * '-', v7, 'suffix');
17678 * ```
17679 *
17680 * @param styleIndex Index of style to update. This index value refers to the
17681 * index of the style in the style bindings array that was passed into
17682 * `styling`.
17683 * @param prefix Static value used for concatenation only.
17684 * @param v0 Value checked for change.
17685 * @param i0 Static value used for concatenation only.
17686 * @param v1 Value checked for change.
17687 * @param i1 Static value used for concatenation only.
17688 * @param v2 Value checked for change.
17689 * @param i2 Static value used for concatenation only.
17690 * @param v3 Value checked for change.
17691 * @param i3 Static value used for concatenation only.
17692 * @param v4 Value checked for change.
17693 * @param i4 Static value used for concatenation only.
17694 * @param v5 Value checked for change.
17695 * @param i5 Static value used for concatenation only.
17696 * @param v6 Value checked for change.
17697 * @param i6 Static value used for concatenation only.
17698 * @param v7 Value checked for change.
17699 * @param suffix Static value used for concatenation only.
17700 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
17701 * @returns itself, so that it may be chained.
17702 * @codeGenApi
17703 */
17704function ɵɵstylePropInterpolate8(prop, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, valueSuffix) {
17705 const lView = getLView();
17706 const interpolatedValue = interpolation8(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix);
17707 checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
17708 return ɵɵstylePropInterpolate8;
17709}
17710/**
17711 * Update an interpolated style property on an element with 9 or more bound values surrounded by
17712 * text.
17713 *
17714 * Used when the number of interpolated values exceeds 8.
17715 *
17716 * ```html
17717 * <div
17718 * style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix">
17719 * </div>
17720 * ```
17721 *
17722 * Its compiled representation is:
17723 *
17724 * ```ts
17725 * ɵɵstylePropInterpolateV(
17726 * 0, ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
17727 * 'suffix']);
17728 * ```
17729 *
17730 * @param styleIndex Index of style to update. This index value refers to the
17731 * index of the style in the style bindings array that was passed into
17732 * `styling`..
17733 * @param values The collection of values and the strings in-between those values, beginning with
17734 * a string prefix and ending with a string suffix.
17735 * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`)
17736 * @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
17737 * @returns itself, so that it may be chained.
17738 * @codeGenApi
17739 */
17740function ɵɵstylePropInterpolateV(prop, values, valueSuffix) {
17741 const lView = getLView();
17742 const interpolatedValue = interpolationV(lView, values);
17743 checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
17744 return ɵɵstylePropInterpolateV;
17745}
17746
17747/**
17748 * @license
17749 * Copyright Google LLC All Rights Reserved.
17750 *
17751 * Use of this source code is governed by an MIT-style license that can be
17752 * found in the LICENSE file at https://angular.io/license
17753 */
17754/**
17755 * Update a property on a host element. Only applies to native node properties, not inputs.
17756 *
17757 * Operates on the element selected by index via the {@link select} instruction.
17758 *
17759 * @param propName Name of property. Because it is going to DOM, this is not subject to
17760 * renaming as part of minification.
17761 * @param value New value to write.
17762 * @param sanitizer An optional function used to sanitize the value.
17763 * @returns This function returns itself so that it may be chained
17764 * (e.g. `property('name', ctx.name)('title', ctx.title)`)
17765 *
17766 * @codeGenApi
17767 */
17768function ɵɵhostProperty(propName, value, sanitizer) {
17769 const lView = getLView();
17770 const bindingIndex = nextBindingIndex();
17771 if (bindingUpdated(lView, bindingIndex, value)) {
17772 const tView = getTView();
17773 const tNode = getSelectedTNode();
17774 elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, true);
17775 ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
17776 }
17777 return ɵɵhostProperty;
17778}
17779/**
17780 * Updates a synthetic host binding (e.g. `[@foo]`) on a component or directive.
17781 *
17782 * This instruction is for compatibility purposes and is designed to ensure that a
17783 * synthetic host binding (e.g. `@HostBinding('@foo')`) properly gets rendered in
17784 * the component's renderer. Normally all host bindings are evaluated with the parent
17785 * component's renderer, but, in the case of animation @triggers, they need to be
17786 * evaluated with the sub component's renderer (because that's where the animation
17787 * triggers are defined).
17788 *
17789 * Do not use this instruction as a replacement for `elementProperty`. This instruction
17790 * only exists to ensure compatibility with the ViewEngine's host binding behavior.
17791 *
17792 * @param index The index of the element to update in the data array
17793 * @param propName Name of property. Because it is going to DOM, this is not subject to
17794 * renaming as part of minification.
17795 * @param value New value to write.
17796 * @param sanitizer An optional function used to sanitize the value.
17797 *
17798 * @codeGenApi
17799 */
17800function ɵɵsyntheticHostProperty(propName, value, sanitizer) {
17801 const lView = getLView();
17802 const bindingIndex = nextBindingIndex();
17803 if (bindingUpdated(lView, bindingIndex, value)) {
17804 const tView = getTView();
17805 const tNode = getSelectedTNode();
17806 const currentDef = getCurrentDirectiveDef(tView.data);
17807 const renderer = loadComponentRenderer(currentDef, tNode, lView);
17808 elementPropertyInternal(tView, tNode, lView, propName, value, renderer, sanitizer, true);
17809 ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex);
17810 }
17811 return ɵɵsyntheticHostProperty;
17812}
17813
17814/**
17815 * @license
17816 * Copyright Google LLC All Rights Reserved.
17817 *
17818 * Use of this source code is governed by an MIT-style license that can be
17819 * found in the LICENSE file at https://angular.io/license
17820 */
17821
17822/**
17823 * @license
17824 * Copyright Google LLC All Rights Reserved.
17825 *
17826 * Use of this source code is governed by an MIT-style license that can be
17827 * found in the LICENSE file at https://angular.io/license
17828 */
17829/**
17830 * Retrieves the component instance associated with a given DOM element.
17831 *
17832 * @usageNotes
17833 * Given the following DOM structure:
17834 * ```html
17835 * <my-app>
17836 * <div>
17837 * <child-comp></child-comp>
17838 * </div>
17839 * </my-app>
17840 * ```
17841 * Calling `getComponent` on `<child-comp>` will return the instance of `ChildComponent`
17842 * associated with this DOM element.
17843 *
17844 * Calling the function on `<my-app>` will return the `MyApp` instance.
17845 *
17846 *
17847 * @param element DOM element from which the component should be retrieved.
17848 * @returns Component instance associated with the element or `null` if there
17849 * is no component associated with it.
17850 *
17851 * @publicApi
17852 * @globalApi ng
17853 */
17854function getComponent(element) {
17855 assertDomElement(element);
17856 const context = loadLContext(element, false);
17857 if (context === null)
17858 return null;
17859 if (context.component === undefined) {
17860 context.component = getComponentAtNodeIndex(context.nodeIndex, context.lView);
17861 }
17862 return context.component;
17863}
17864/**
17865 * If inside an embedded view (e.g. `*ngIf` or `*ngFor`), retrieves the context of the embedded
17866 * view that the element is part of. Otherwise retrieves the instance of the component whose view
17867 * owns the element (in this case, the result is the same as calling `getOwningComponent`).
17868 *
17869 * @param element Element for which to get the surrounding component instance.
17870 * @returns Instance of the component that is around the element or null if the element isn't
17871 * inside any component.
17872 *
17873 * @publicApi
17874 * @globalApi ng
17875 */
17876function getContext(element) {
17877 assertDomElement(element);
17878 const context = loadLContext(element, false);
17879 return context === null ? null : context.lView[CONTEXT];
17880}
17881/**
17882 * Retrieves the component instance whose view contains the DOM element.
17883 *
17884 * For example, if `<child-comp>` is used in the template of `<app-comp>`
17885 * (i.e. a `ViewChild` of `<app-comp>`), calling `getOwningComponent` on `<child-comp>`
17886 * would return `<app-comp>`.
17887 *
17888 * @param elementOrDir DOM element, component or directive instance
17889 * for which to retrieve the root components.
17890 * @returns Component instance whose view owns the DOM element or null if the element is not
17891 * part of a component view.
17892 *
17893 * @publicApi
17894 * @globalApi ng
17895 */
17896function getOwningComponent(elementOrDir) {
17897 const context = loadLContext(elementOrDir, false);
17898 if (context === null)
17899 return null;
17900 let lView = context.lView;
17901 let parent;
17902 ngDevMode && assertLView(lView);
17903 while (lView[HOST] === null && (parent = getLViewParent(lView))) {
17904 // As long as lView[HOST] is null we know we are part of sub-template such as `*ngIf`
17905 lView = parent;
17906 }
17907 return lView[FLAGS] & 512 /* IsRoot */ ? null : lView[CONTEXT];
17908}
17909/**
17910 * Retrieves all root components associated with a DOM element, directive or component instance.
17911 * Root components are those which have been bootstrapped by Angular.
17912 *
17913 * @param elementOrDir DOM element, component or directive instance
17914 * for which to retrieve the root components.
17915 * @returns Root components associated with the target object.
17916 *
17917 * @publicApi
17918 * @globalApi ng
17919 */
17920function getRootComponents(elementOrDir) {
17921 return [...getRootContext(elementOrDir).components];
17922}
17923/**
17924 * Retrieves an `Injector` associated with an element, component or directive instance.
17925 *
17926 * @param elementOrDir DOM element, component or directive instance for which to
17927 * retrieve the injector.
17928 * @returns Injector associated with the element, component or directive instance.
17929 *
17930 * @publicApi
17931 * @globalApi ng
17932 */
17933function getInjector(elementOrDir) {
17934 const context = loadLContext(elementOrDir, false);
17935 if (context === null)
17936 return Injector.NULL;
17937 const tNode = context.lView[TVIEW].data[context.nodeIndex];
17938 return new NodeInjector(tNode, context.lView);
17939}
17940/**
17941 * Retrieve a set of injection tokens at a given DOM node.
17942 *
17943 * @param element Element for which the injection tokens should be retrieved.
17944 */
17945function getInjectionTokens(element) {
17946 const context = loadLContext(element, false);
17947 if (context === null)
17948 return [];
17949 const lView = context.lView;
17950 const tView = lView[TVIEW];
17951 const tNode = tView.data[context.nodeIndex];
17952 const providerTokens = [];
17953 const startIndex = tNode.providerIndexes & 1048575 /* ProvidersStartIndexMask */;
17954 const endIndex = tNode.directiveEnd;
17955 for (let i = startIndex; i < endIndex; i++) {
17956 let value = tView.data[i];
17957 if (isDirectiveDefHack(value)) {
17958 // The fact that we sometimes store Type and sometimes DirectiveDef in this location is a
17959 // design flaw. We should always store same type so that we can be monomorphic. The issue
17960 // is that for Components/Directives we store the def instead the type. The correct behavior
17961 // is that we should always be storing injectable type in this location.
17962 value = value.type;
17963 }
17964 providerTokens.push(value);
17965 }
17966 return providerTokens;
17967}
17968/**
17969 * Retrieves directive instances associated with a given DOM element. Does not include
17970 * component instances.
17971 *
17972 * @usageNotes
17973 * Given the following DOM structure:
17974 * ```
17975 * <my-app>
17976 * <button my-button></button>
17977 * <my-comp></my-comp>
17978 * </my-app>
17979 * ```
17980 * Calling `getDirectives` on `<button>` will return an array with an instance of the `MyButton`
17981 * directive that is associated with the DOM element.
17982 *
17983 * Calling `getDirectives` on `<my-comp>` will return an empty array.
17984 *
17985 * @param element DOM element for which to get the directives.
17986 * @returns Array of directives associated with the element.
17987 *
17988 * @publicApi
17989 * @globalApi ng
17990 */
17991function getDirectives(element) {
17992 const context = loadLContext(element);
17993 if (context.directives === undefined) {
17994 context.directives = getDirectivesAtNodeIndex(context.nodeIndex, context.lView, false);
17995 }
17996 // The `directives` in this case are a named array called `LComponentView`. Clone the
17997 // result so we don't expose an internal data structure in the user's console.
17998 return context.directives === null ? [] : [...context.directives];
17999}
18000function loadLContext(target, throwOnNotFound = true) {
18001 const context = getLContext(target);
18002 if (!context && throwOnNotFound) {
18003 throw new Error(ngDevMode ? `Unable to find context associated with ${stringifyForError(target)}` :
18004 'Invalid ng target');
18005 }
18006 return context;
18007}
18008/**
18009 * Retrieve map of local references.
18010 *
18011 * The references are retrieved as a map of local reference name to element or directive instance.
18012 *
18013 * @param target DOM element, component or directive instance for which to retrieve
18014 * the local references.
18015 */
18016function getLocalRefs(target) {
18017 const context = loadLContext(target, false);
18018 if (context === null)
18019 return {};
18020 if (context.localRefs === undefined) {
18021 context.localRefs = discoverLocalRefs(context.lView, context.nodeIndex);
18022 }
18023 return context.localRefs || {};
18024}
18025/**
18026 * Retrieves the host element of a component or directive instance.
18027 * The host element is the DOM element that matched the selector of the directive.
18028 *
18029 * @param componentOrDirective Component or directive instance for which the host
18030 * element should be retrieved.
18031 * @returns Host element of the target.
18032 *
18033 * @publicApi
18034 * @globalApi ng
18035 */
18036function getHostElement(componentOrDirective) {
18037 return getLContext(componentOrDirective).native;
18038}
18039/**
18040 * Retrieves the rendered text for a given component.
18041 *
18042 * This function retrieves the host element of a component and
18043 * and then returns the `textContent` for that element. This implies
18044 * that the text returned will include re-projected content of
18045 * the component as well.
18046 *
18047 * @param component The component to return the content text for.
18048 */
18049function getRenderedText(component) {
18050 const hostElement = getHostElement(component);
18051 return hostElement.textContent || '';
18052}
18053function loadLContextFromNode(node) {
18054 if (!(node instanceof Node))
18055 throw new Error('Expecting instance of DOM Element');
18056 return loadLContext(node);
18057}
18058/**
18059 * Retrieves a list of event listeners associated with a DOM element. The list does include host
18060 * listeners, but it does not include event listeners defined outside of the Angular context
18061 * (e.g. through `addEventListener`).
18062 *
18063 * @usageNotes
18064 * Given the following DOM structure:
18065 * ```
18066 * <my-app>
18067 * <div (click)="doSomething()"></div>
18068 * </my-app>
18069 *
18070 * ```
18071 * Calling `getListeners` on `<div>` will return an object that looks as follows:
18072 * ```
18073 * {
18074 * name: 'click',
18075 * element: <div>,
18076 * callback: () => doSomething(),
18077 * useCapture: false
18078 * }
18079 * ```
18080 *
18081 * @param element Element for which the DOM listeners should be retrieved.
18082 * @returns Array of event listeners on the DOM element.
18083 *
18084 * @publicApi
18085 * @globalApi ng
18086 */
18087function getListeners(element) {
18088 assertDomElement(element);
18089 const lContext = loadLContext(element, false);
18090 if (lContext === null)
18091 return [];
18092 const lView = lContext.lView;
18093 const tView = lView[TVIEW];
18094 const lCleanup = lView[CLEANUP];
18095 const tCleanup = tView.cleanup;
18096 const listeners = [];
18097 if (tCleanup && lCleanup) {
18098 for (let i = 0; i < tCleanup.length;) {
18099 const firstParam = tCleanup[i++];
18100 const secondParam = tCleanup[i++];
18101 if (typeof firstParam === 'string') {
18102 const name = firstParam;
18103 const listenerElement = unwrapRNode(lView[secondParam]);
18104 const callback = lCleanup[tCleanup[i++]];
18105 const useCaptureOrIndx = tCleanup[i++];
18106 // if useCaptureOrIndx is boolean then report it as is.
18107 // if useCaptureOrIndx is positive number then it in unsubscribe method
18108 // if useCaptureOrIndx is negative number then it is a Subscription
18109 const type = (typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0) ? 'dom' : 'output';
18110 const useCapture = typeof useCaptureOrIndx === 'boolean' ? useCaptureOrIndx : false;
18111 if (element == listenerElement) {
18112 listeners.push({ element, name, callback, useCapture, type });
18113 }
18114 }
18115 }
18116 }
18117 listeners.sort(sortListeners);
18118 return listeners;
18119}
18120function sortListeners(a, b) {
18121 if (a.name == b.name)
18122 return 0;
18123 return a.name < b.name ? -1 : 1;
18124}
18125/**
18126 * This function should not exist because it is megamorphic and only mostly correct.
18127 *
18128 * See call site for more info.
18129 */
18130function isDirectiveDefHack(obj) {
18131 return obj.type !== undefined && obj.template !== undefined && obj.declaredInputs !== undefined;
18132}
18133/**
18134 * Returns the attached `DebugNode` instance for an element in the DOM.
18135 *
18136 * @param element DOM element which is owned by an existing component's view.
18137 */
18138function getDebugNode(element) {
18139 let debugNode = null;
18140 const lContext = loadLContextFromNode(element);
18141 const lView = lContext.lView;
18142 const nodeIndex = lContext.nodeIndex;
18143 if (nodeIndex !== -1) {
18144 const valueInLView = lView[nodeIndex];
18145 // this means that value in the lView is a component with its own
18146 // data. In this situation the TNode is not accessed at the same spot.
18147 const tNode = isLView(valueInLView) ? valueInLView[T_HOST] :
18148 getTNode(lView[TVIEW], nodeIndex - HEADER_OFFSET);
18149 debugNode = buildDebugNode(tNode, lView, nodeIndex);
18150 }
18151 return debugNode;
18152}
18153/**
18154 * Retrieve the component `LView` from component/element.
18155 *
18156 * NOTE: `LView` is a private and should not be leaked outside.
18157 * Don't export this method to `ng.*` on window.
18158 *
18159 * @param target DOM element or component instance for which to retrieve the LView.
18160 */
18161function getComponentLView(target) {
18162 const lContext = loadLContext(target);
18163 const nodeIndx = lContext.nodeIndex;
18164 const lView = lContext.lView;
18165 const componentLView = lView[nodeIndx];
18166 ngDevMode && assertLView(componentLView);
18167 return componentLView;
18168}
18169/** Asserts that a value is a DOM Element. */
18170function assertDomElement(value) {
18171 if (typeof Element !== 'undefined' && !(value instanceof Element)) {
18172 throw new Error('Expecting instance of DOM Element');
18173 }
18174}
18175
18176/**
18177 * @license
18178 * Copyright Google LLC All Rights Reserved.
18179 *
18180 * Use of this source code is governed by an MIT-style license that can be
18181 * found in the LICENSE file at https://angular.io/license
18182 */
18183/**
18184 * Marks a component for check (in case of OnPush components) and synchronously
18185 * performs change detection on the application this component belongs to.
18186 *
18187 * @param component Component to {@link ChangeDetectorRef#markForCheck mark for check}.
18188 *
18189 * @publicApi
18190 * @globalApi ng
18191 */
18192function applyChanges(component) {
18193 markDirty(component);
18194 getRootComponents(component).forEach(rootComponent => detectChanges(rootComponent));
18195}
18196
18197/**
18198 * @license
18199 * Copyright Google LLC All Rights Reserved.
18200 *
18201 * Use of this source code is governed by an MIT-style license that can be
18202 * found in the LICENSE file at https://angular.io/license
18203 */
18204/**
18205 * This file introduces series of globally accessible debug tools
18206 * to allow for the Angular debugging story to function.
18207 *
18208 * To see this in action run the following command:
18209 *
18210 * bazel run --config=ivy
18211 * //packages/core/test/bundling/todo:devserver
18212 *
18213 * Then load `localhost:5432` and start using the console tools.
18214 */
18215/**
18216 * This value reflects the property on the window where the dev
18217 * tools are patched (window.ng).
18218 * */
18219const GLOBAL_PUBLISH_EXPANDO_KEY = 'ng';
18220let _published = false;
18221/**
18222 * Publishes a collection of default debug tools onto`window.ng`.
18223 *
18224 * These functions are available globally when Angular is in development
18225 * mode and are automatically stripped away from prod mode is on.
18226 */
18227function publishDefaultGlobalUtils() {
18228 if (!_published) {
18229 _published = true;
18230 publishGlobalUtil('getComponent', getComponent);
18231 publishGlobalUtil('getContext', getContext);
18232 publishGlobalUtil('getListeners', getListeners);
18233 publishGlobalUtil('getOwningComponent', getOwningComponent);
18234 publishGlobalUtil('getHostElement', getHostElement);
18235 publishGlobalUtil('getInjector', getInjector);
18236 publishGlobalUtil('getRootComponents', getRootComponents);
18237 publishGlobalUtil('getDirectives', getDirectives);
18238 publishGlobalUtil('applyChanges', applyChanges);
18239 }
18240}
18241/**
18242 * Publishes the given function to `window.ng` so that it can be
18243 * used from the browser console when an application is not in production.
18244 */
18245function publishGlobalUtil(name, fn) {
18246 if (typeof COMPILED === 'undefined' || !COMPILED) {
18247 // Note: we can't export `ng` when using closure enhanced optimization as:
18248 // - closure declares globals itself for minified names, which sometimes clobber our `ng` global
18249 // - we can't declare a closure extern as the namespace `ng` is already used within Google
18250 // for typings for AngularJS (via `goog.provide('ng....')`).
18251 const w = _global;
18252 ngDevMode && assertDefined(fn, 'function not defined');
18253 if (w) {
18254 let container = w[GLOBAL_PUBLISH_EXPANDO_KEY];
18255 if (!container) {
18256 container = w[GLOBAL_PUBLISH_EXPANDO_KEY] = {};
18257 }
18258 container[name] = fn;
18259 }
18260 }
18261}
18262
18263/**
18264 * @license
18265 * Copyright Google LLC All Rights Reserved.
18266 *
18267 * Use of this source code is governed by an MIT-style license that can be
18268 * found in the LICENSE file at https://angular.io/license
18269 */
18270const ɵ0$b = (token, notFoundValue) => {
18271 throw new Error('NullInjector: Not found: ' + stringifyForError(token));
18272};
18273// TODO: A hack to not pull in the NullInjector from @angular/core.
18274const NULL_INJECTOR$1 = {
18275 get: ɵ0$b
18276};
18277/**
18278 * Bootstraps a Component into an existing host element and returns an instance
18279 * of the component.
18280 *
18281 * Use this function to bootstrap a component into the DOM tree. Each invocation
18282 * of this function will create a separate tree of components, injectors and
18283 * change detection cycles and lifetimes. To dynamically insert a new component
18284 * into an existing tree such that it shares the same injection, change detection
18285 * and object lifetime, use {@link ViewContainer#createComponent}.
18286 *
18287 * @param componentType Component to bootstrap
18288 * @param options Optional parameters which control bootstrapping
18289 */
18290function renderComponent$1(componentType /* Type as workaround for: Microsoft/TypeScript/issues/4881 */, opts = {}) {
18291 ngDevMode && publishDefaultGlobalUtils();
18292 ngDevMode && assertComponentType(componentType);
18293 const rendererFactory = opts.rendererFactory || domRendererFactory3;
18294 const sanitizer = opts.sanitizer || null;
18295 const componentDef = getComponentDef(componentType);
18296 if (componentDef.type != componentType)
18297 componentDef.type = componentType;
18298 // The first index of the first selector is the tag name.
18299 const componentTag = componentDef.selectors[0][0];
18300 const hostRenderer = rendererFactory.createRenderer(null, null);
18301 const hostRNode = locateHostElement(hostRenderer, opts.host || componentTag, componentDef.encapsulation);
18302 const rootFlags = componentDef.onPush ? 64 /* Dirty */ | 512 /* IsRoot */ :
18303 16 /* CheckAlways */ | 512 /* IsRoot */;
18304 const rootContext = createRootContext(opts.scheduler, opts.playerHandler);
18305 const renderer = rendererFactory.createRenderer(hostRNode, componentDef);
18306 const rootTView = createTView(0 /* Root */, -1, null, 1, 0, null, null, null, null, null);
18307 const rootView = createLView(null, rootTView, rootContext, rootFlags, null, null, rendererFactory, renderer, undefined, opts.injector || null);
18308 enterView(rootView, null);
18309 let component;
18310 try {
18311 if (rendererFactory.begin)
18312 rendererFactory.begin();
18313 const componentView = createRootComponentView(hostRNode, componentDef, rootView, rendererFactory, renderer, sanitizer);
18314 component = createRootComponent(componentView, componentDef, rootView, rootContext, opts.hostFeatures || null);
18315 // create mode pass
18316 renderView(rootTView, rootView, null);
18317 // update mode pass
18318 refreshView(rootTView, rootView, null, null);
18319 }
18320 finally {
18321 leaveView();
18322 if (rendererFactory.end)
18323 rendererFactory.end();
18324 }
18325 return component;
18326}
18327/**
18328 * Creates the root component view and the root component node.
18329 *
18330 * @param rNode Render host element.
18331 * @param def ComponentDef
18332 * @param rootView The parent view where the host node is stored
18333 * @param hostRenderer The current renderer
18334 * @param sanitizer The sanitizer, if provided
18335 *
18336 * @returns Component view created
18337 */
18338function createRootComponentView(rNode, def, rootView, rendererFactory, hostRenderer, sanitizer) {
18339 const tView = rootView[TVIEW];
18340 ngDevMode && assertIndexInRange(rootView, 0 + HEADER_OFFSET);
18341 rootView[0 + HEADER_OFFSET] = rNode;
18342 const tNode = getOrCreateTNode(tView, null, 0, 3 /* Element */, null, null);
18343 const mergedAttrs = tNode.mergedAttrs = def.hostAttrs;
18344 if (mergedAttrs !== null) {
18345 computeStaticStyling(tNode, mergedAttrs, true);
18346 if (rNode !== null) {
18347 setUpAttributes(hostRenderer, rNode, mergedAttrs);
18348 if (tNode.classes !== null) {
18349 writeDirectClass(hostRenderer, rNode, tNode.classes);
18350 }
18351 if (tNode.styles !== null) {
18352 writeDirectStyle(hostRenderer, rNode, tNode.styles);
18353 }
18354 }
18355 }
18356 const viewRenderer = rendererFactory.createRenderer(rNode, def);
18357 const componentView = createLView(rootView, getOrCreateTComponentView(def), null, def.onPush ? 64 /* Dirty */ : 16 /* CheckAlways */, rootView[HEADER_OFFSET], tNode, rendererFactory, viewRenderer, sanitizer);
18358 if (tView.firstCreatePass) {
18359 diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, rootView), tView, def.type);
18360 markAsComponentHost(tView, tNode);
18361 initTNodeFlags(tNode, rootView.length, 1);
18362 }
18363 addToViewTree(rootView, componentView);
18364 // Store component view at node index, with node as the HOST
18365 return rootView[HEADER_OFFSET] = componentView;
18366}
18367/**
18368 * Creates a root component and sets it up with features and host bindings. Shared by
18369 * renderComponent() and ViewContainerRef.createComponent().
18370 */
18371function createRootComponent(componentView, componentDef, rootLView, rootContext, hostFeatures) {
18372 const tView = rootLView[TVIEW];
18373 // Create directive instance with factory() and store at next index in viewData
18374 const component = instantiateRootComponent(tView, rootLView, componentDef);
18375 rootContext.components.push(component);
18376 componentView[CONTEXT] = component;
18377 hostFeatures && hostFeatures.forEach((feature) => feature(component, componentDef));
18378 // We want to generate an empty QueryList for root content queries for backwards
18379 // compatibility with ViewEngine.
18380 if (componentDef.contentQueries) {
18381 componentDef.contentQueries(1 /* Create */, component, rootLView.length - 1);
18382 }
18383 const rootTNode = getPreviousOrParentTNode();
18384 if (tView.firstCreatePass &&
18385 (componentDef.hostBindings !== null || componentDef.hostAttrs !== null)) {
18386 const elementIndex = rootTNode.index - HEADER_OFFSET;
18387 setSelectedIndex(elementIndex);
18388 const rootTView = rootLView[TVIEW];
18389 addHostBindingsToExpandoInstructions(rootTView, componentDef);
18390 growHostVarsSpace(rootTView, rootLView, componentDef.hostVars);
18391 invokeHostBindingsInCreationMode(componentDef, component);
18392 }
18393 return component;
18394}
18395function createRootContext(scheduler, playerHandler) {
18396 return {
18397 components: [],
18398 scheduler: scheduler || defaultScheduler,
18399 clean: CLEAN_PROMISE,
18400 playerHandler: playerHandler || null,
18401 flags: 0 /* Empty */
18402 };
18403}
18404/**
18405 * Used to enable lifecycle hooks on the root component.
18406 *
18407 * Include this feature when calling `renderComponent` if the root component
18408 * you are rendering has lifecycle hooks defined. Otherwise, the hooks won't
18409 * be called properly.
18410 *
18411 * Example:
18412 *
18413 * ```
18414 * renderComponent(AppComponent, {hostFeatures: [LifecycleHooksFeature]});
18415 * ```
18416 */
18417function LifecycleHooksFeature(component, def) {
18418 const rootTView = readPatchedLView(component)[TVIEW];
18419 const dirIndex = rootTView.data.length - 1;
18420 // TODO(misko): replace `as TNode` with createTNode call. (needs refactoring to lose dep on
18421 // LNode).
18422 registerPostOrderHooks(rootTView, { directiveStart: dirIndex, directiveEnd: dirIndex + 1 });
18423}
18424/**
18425 * Wait on component until it is rendered.
18426 *
18427 * This function returns a `Promise` which is resolved when the component's
18428 * change detection is executed. This is determined by finding the scheduler
18429 * associated with the `component`'s render tree and waiting until the scheduler
18430 * flushes. If nothing is scheduled, the function returns a resolved promise.
18431 *
18432 * Example:
18433 * ```
18434 * await whenRendered(myComponent);
18435 * ```
18436 *
18437 * @param component Component to wait upon
18438 * @returns Promise which resolves when the component is rendered.
18439 */
18440function whenRendered(component) {
18441 return getRootContext(component).clean;
18442}
18443
18444/**
18445 * @license
18446 * Copyright Google LLC All Rights Reserved.
18447 *
18448 * Use of this source code is governed by an MIT-style license that can be
18449 * found in the LICENSE file at https://angular.io/license
18450 */
18451function getSuperType(type) {
18452 return Object.getPrototypeOf(type.prototype).constructor;
18453}
18454/**
18455 * Merges the definition from a super class to a sub class.
18456 * @param definition The definition that is a SubClass of another directive of component
18457 *
18458 * @codeGenApi
18459 */
18460function ɵɵInheritDefinitionFeature(definition) {
18461 let superType = getSuperType(definition.type);
18462 let shouldInheritFields = true;
18463 const inheritanceChain = [definition];
18464 while (superType) {
18465 let superDef = undefined;
18466 if (isComponentDef(definition)) {
18467 // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
18468 superDef = superType.ɵcmp || superType.ɵdir;
18469 }
18470 else {
18471 if (superType.ɵcmp) {
18472 throw new Error('Directives cannot inherit Components');
18473 }
18474 // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
18475 superDef = superType.ɵdir;
18476 }
18477 if (superDef) {
18478 if (shouldInheritFields) {
18479 inheritanceChain.push(superDef);
18480 // Some fields in the definition may be empty, if there were no values to put in them that
18481 // would've justified object creation. Unwrap them if necessary.
18482 const writeableDef = definition;
18483 writeableDef.inputs = maybeUnwrapEmpty(definition.inputs);
18484 writeableDef.declaredInputs = maybeUnwrapEmpty(definition.declaredInputs);
18485 writeableDef.outputs = maybeUnwrapEmpty(definition.outputs);
18486 // Merge hostBindings
18487 const superHostBindings = superDef.hostBindings;
18488 superHostBindings && inheritHostBindings(definition, superHostBindings);
18489 // Merge queries
18490 const superViewQuery = superDef.viewQuery;
18491 const superContentQueries = superDef.contentQueries;
18492 superViewQuery && inheritViewQuery(definition, superViewQuery);
18493 superContentQueries && inheritContentQueries(definition, superContentQueries);
18494 // Merge inputs and outputs
18495 fillProperties(definition.inputs, superDef.inputs);
18496 fillProperties(definition.declaredInputs, superDef.declaredInputs);
18497 fillProperties(definition.outputs, superDef.outputs);
18498 // Merge animations metadata.
18499 // If `superDef` is a Component, the `data` field is present (defaults to an empty object).
18500 if (isComponentDef(superDef) && superDef.data.animation) {
18501 // If super def is a Component, the `definition` is also a Component, since Directives can
18502 // not inherit Components (we throw an error above and cannot reach this code).
18503 const defData = definition.data;
18504 defData.animation = (defData.animation || []).concat(superDef.data.animation);
18505 }
18506 }
18507 // Run parent features
18508 const features = superDef.features;
18509 if (features) {
18510 for (let i = 0; i < features.length; i++) {
18511 const feature = features[i];
18512 if (feature && feature.ngInherit) {
18513 feature(definition);
18514 }
18515 // If `InheritDefinitionFeature` is a part of the current `superDef`, it means that this
18516 // def already has all the necessary information inherited from its super class(es), so we
18517 // can stop merging fields from super classes. However we need to iterate through the
18518 // prototype chain to look for classes that might contain other "features" (like
18519 // NgOnChanges), which we should invoke for the original `definition`. We set the
18520 // `shouldInheritFields` flag to indicate that, essentially skipping fields inheritance
18521 // logic and only invoking functions from the "features" list.
18522 if (feature === ɵɵInheritDefinitionFeature) {
18523 shouldInheritFields = false;
18524 }
18525 }
18526 }
18527 }
18528 superType = Object.getPrototypeOf(superType);
18529 }
18530 mergeHostAttrsAcrossInheritance(inheritanceChain);
18531}
18532/**
18533 * Merge the `hostAttrs` and `hostVars` from the inherited parent to the base class.
18534 *
18535 * @param inheritanceChain A list of `WritableDefs` starting at the top most type and listing
18536 * sub-types in order. For each type take the `hostAttrs` and `hostVars` and merge it with the child
18537 * type.
18538 */
18539function mergeHostAttrsAcrossInheritance(inheritanceChain) {
18540 let hostVars = 0;
18541 let hostAttrs = null;
18542 // We process the inheritance order from the base to the leaves here.
18543 for (let i = inheritanceChain.length - 1; i >= 0; i--) {
18544 const def = inheritanceChain[i];
18545 // For each `hostVars`, we need to add the superclass amount.
18546 def.hostVars = (hostVars += def.hostVars);
18547 // for each `hostAttrs` we need to merge it with superclass.
18548 def.hostAttrs =
18549 mergeHostAttrs(def.hostAttrs, hostAttrs = mergeHostAttrs(hostAttrs, def.hostAttrs));
18550 }
18551}
18552function maybeUnwrapEmpty(value) {
18553 if (value === EMPTY_OBJ) {
18554 return {};
18555 }
18556 else if (value === EMPTY_ARRAY) {
18557 return [];
18558 }
18559 else {
18560 return value;
18561 }
18562}
18563function inheritViewQuery(definition, superViewQuery) {
18564 const prevViewQuery = definition.viewQuery;
18565 if (prevViewQuery) {
18566 definition.viewQuery = (rf, ctx) => {
18567 superViewQuery(rf, ctx);
18568 prevViewQuery(rf, ctx);
18569 };
18570 }
18571 else {
18572 definition.viewQuery = superViewQuery;
18573 }
18574}
18575function inheritContentQueries(definition, superContentQueries) {
18576 const prevContentQueries = definition.contentQueries;
18577 if (prevContentQueries) {
18578 definition.contentQueries = (rf, ctx, directiveIndex) => {
18579 superContentQueries(rf, ctx, directiveIndex);
18580 prevContentQueries(rf, ctx, directiveIndex);
18581 };
18582 }
18583 else {
18584 definition.contentQueries = superContentQueries;
18585 }
18586}
18587function inheritHostBindings(definition, superHostBindings) {
18588 const prevHostBindings = definition.hostBindings;
18589 if (prevHostBindings) {
18590 definition.hostBindings = (rf, ctx) => {
18591 superHostBindings(rf, ctx);
18592 prevHostBindings(rf, ctx);
18593 };
18594 }
18595 else {
18596 definition.hostBindings = superHostBindings;
18597 }
18598}
18599
18600/**
18601 * @license
18602 * Copyright Google LLC All Rights Reserved.
18603 *
18604 * Use of this source code is governed by an MIT-style license that can be
18605 * found in the LICENSE file at https://angular.io/license
18606 */
18607/**
18608 * Fields which exist on either directive or component definitions, and need to be copied from
18609 * parent to child classes by the `ɵɵCopyDefinitionFeature`.
18610 */
18611const COPY_DIRECTIVE_FIELDS = [
18612 // The child class should use the providers of its parent.
18613 'providersResolver',
18614];
18615/**
18616 * Fields which exist only on component definitions, and need to be copied from parent to child
18617 * classes by the `ɵɵCopyDefinitionFeature`.
18618 *
18619 * The type here allows any field of `ComponentDef` which is not also a property of `DirectiveDef`,
18620 * since those should go in `COPY_DIRECTIVE_FIELDS` above.
18621 */
18622const COPY_COMPONENT_FIELDS = [
18623 // The child class should use the template function of its parent, including all template
18624 // semantics.
18625 'template',
18626 'decls',
18627 'consts',
18628 'vars',
18629 'onPush',
18630 'ngContentSelectors',
18631 // The child class should use the CSS styles of its parent, including all styling semantics.
18632 'styles',
18633 'encapsulation',
18634 // The child class should be checked by the runtime in the same way as its parent.
18635 'schemas',
18636];
18637/**
18638 * Copies the fields not handled by the `ɵɵInheritDefinitionFeature` from the supertype of a
18639 * definition.
18640 *
18641 * This exists primarily to support ngcc migration of an existing View Engine pattern, where an
18642 * entire decorator is inherited from a parent to a child class. When ngcc detects this case, it
18643 * generates a skeleton definition on the child class, and applies this feature.
18644 *
18645 * The `ɵɵCopyDefinitionFeature` then copies any needed fields from the parent class' definition,
18646 * including things like the component template function.
18647 *
18648 * @param definition The definition of a child class which inherits from a parent class with its
18649 * own definition.
18650 *
18651 * @codeGenApi
18652 */
18653function ɵɵCopyDefinitionFeature(definition) {
18654 let superType = getSuperType(definition.type);
18655 let superDef = undefined;
18656 if (isComponentDef(definition)) {
18657 // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
18658 superDef = superType.ɵcmp;
18659 }
18660 else {
18661 // Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
18662 superDef = superType.ɵdir;
18663 }
18664 // Needed because `definition` fields are readonly.
18665 const defAny = definition;
18666 // Copy over any fields that apply to either directives or components.
18667 for (const field of COPY_DIRECTIVE_FIELDS) {
18668 defAny[field] = superDef[field];
18669 }
18670 if (isComponentDef(superDef)) {
18671 // Copy over any component-specific fields.
18672 for (const field of COPY_COMPONENT_FIELDS) {
18673 defAny[field] = superDef[field];
18674 }
18675 }
18676}
18677
18678/**
18679 * @license
18680 * Copyright Google LLC All Rights Reserved.
18681 *
18682 * Use of this source code is governed by an MIT-style license that can be
18683 * found in the LICENSE file at https://angular.io/license
18684 */
18685/**
18686 * Resolves the providers which are defined in the DirectiveDef.
18687 *
18688 * When inserting the tokens and the factories in their respective arrays, we can assume that
18689 * this method is called first for the component (if any), and then for other directives on the same
18690 * node.
18691 * As a consequence,the providers are always processed in that order:
18692 * 1) The view providers of the component
18693 * 2) The providers of the component
18694 * 3) The providers of the other directives
18695 * This matches the structure of the injectables arrays of a view (for each node).
18696 * So the tokens and the factories can be pushed at the end of the arrays, except
18697 * in one case for multi providers.
18698 *
18699 * @param def the directive definition
18700 * @param providers: Array of `providers`.
18701 * @param viewProviders: Array of `viewProviders`.
18702 */
18703function providersResolver(def, providers, viewProviders) {
18704 const tView = getTView();
18705 if (tView.firstCreatePass) {
18706 const isComponent = isComponentDef(def);
18707 // The list of view providers is processed first, and the flags are updated
18708 resolveProvider$1(viewProviders, tView.data, tView.blueprint, isComponent, true);
18709 // Then, the list of providers is processed, and the flags are updated
18710 resolveProvider$1(providers, tView.data, tView.blueprint, isComponent, false);
18711 }
18712}
18713/**
18714 * Resolves a provider and publishes it to the DI system.
18715 */
18716function resolveProvider$1(provider, tInjectables, lInjectablesBlueprint, isComponent, isViewProvider) {
18717 provider = resolveForwardRef(provider);
18718 if (Array.isArray(provider)) {
18719 // Recursively call `resolveProvider`
18720 // Recursion is OK in this case because this code will not be in hot-path once we implement
18721 // cloning of the initial state.
18722 for (let i = 0; i < provider.length; i++) {
18723 resolveProvider$1(provider[i], tInjectables, lInjectablesBlueprint, isComponent, isViewProvider);
18724 }
18725 }
18726 else {
18727 const tView = getTView();
18728 const lView = getLView();
18729 let token = isTypeProvider(provider) ? provider : resolveForwardRef(provider.provide);
18730 let providerFactory = providerToFactory(provider);
18731 const tNode = getPreviousOrParentTNode();
18732 const beginIndex = tNode.providerIndexes & 1048575 /* ProvidersStartIndexMask */;
18733 const endIndex = tNode.directiveStart;
18734 const cptViewProvidersCount = tNode.providerIndexes >> 20 /* CptViewProvidersCountShift */;
18735 if (isTypeProvider(provider) || !provider.multi) {
18736 // Single provider case: the factory is created and pushed immediately
18737 const factory = new NodeInjectorFactory(providerFactory, isViewProvider, ɵɵdirectiveInject);
18738 const existingFactoryIndex = indexOf(token, tInjectables, isViewProvider ? beginIndex : beginIndex + cptViewProvidersCount, endIndex);
18739 if (existingFactoryIndex === -1) {
18740 diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, lView), tView, token);
18741 registerDestroyHooksIfSupported(tView, provider, tInjectables.length);
18742 tInjectables.push(token);
18743 tNode.directiveStart++;
18744 tNode.directiveEnd++;
18745 if (isViewProvider) {
18746 tNode.providerIndexes += 1048576 /* CptViewProvidersCountShifter */;
18747 }
18748 lInjectablesBlueprint.push(factory);
18749 lView.push(factory);
18750 }
18751 else {
18752 lInjectablesBlueprint[existingFactoryIndex] = factory;
18753 lView[existingFactoryIndex] = factory;
18754 }
18755 }
18756 else {
18757 // Multi provider case:
18758 // We create a multi factory which is going to aggregate all the values.
18759 // Since the output of such a factory depends on content or view injection,
18760 // we create two of them, which are linked together.
18761 //
18762 // The first one (for view providers) is always in the first block of the injectables array,
18763 // and the second one (for providers) is always in the second block.
18764 // This is important because view providers have higher priority. When a multi token
18765 // is being looked up, the view providers should be found first.
18766 // Note that it is not possible to have a multi factory in the third block (directive block).
18767 //
18768 // The algorithm to process multi providers is as follows:
18769 // 1) If the multi provider comes from the `viewProviders` of the component:
18770 // a) If the special view providers factory doesn't exist, it is created and pushed.
18771 // b) Else, the multi provider is added to the existing multi factory.
18772 // 2) If the multi provider comes from the `providers` of the component or of another
18773 // directive:
18774 // a) If the multi factory doesn't exist, it is created and provider pushed into it.
18775 // It is also linked to the multi factory for view providers, if it exists.
18776 // b) Else, the multi provider is added to the existing multi factory.
18777 const existingProvidersFactoryIndex = indexOf(token, tInjectables, beginIndex + cptViewProvidersCount, endIndex);
18778 const existingViewProvidersFactoryIndex = indexOf(token, tInjectables, beginIndex, beginIndex + cptViewProvidersCount);
18779 const doesProvidersFactoryExist = existingProvidersFactoryIndex >= 0 &&
18780 lInjectablesBlueprint[existingProvidersFactoryIndex];
18781 const doesViewProvidersFactoryExist = existingViewProvidersFactoryIndex >= 0 &&
18782 lInjectablesBlueprint[existingViewProvidersFactoryIndex];
18783 if (isViewProvider && !doesViewProvidersFactoryExist ||
18784 !isViewProvider && !doesProvidersFactoryExist) {
18785 // Cases 1.a and 2.a
18786 diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, lView), tView, token);
18787 const factory = multiFactory(isViewProvider ? multiViewProvidersFactoryResolver : multiProvidersFactoryResolver, lInjectablesBlueprint.length, isViewProvider, isComponent, providerFactory);
18788 if (!isViewProvider && doesViewProvidersFactoryExist) {
18789 lInjectablesBlueprint[existingViewProvidersFactoryIndex].providerFactory = factory;
18790 }
18791 registerDestroyHooksIfSupported(tView, provider, tInjectables.length, 0);
18792 tInjectables.push(token);
18793 tNode.directiveStart++;
18794 tNode.directiveEnd++;
18795 if (isViewProvider) {
18796 tNode.providerIndexes += 1048576 /* CptViewProvidersCountShifter */;
18797 }
18798 lInjectablesBlueprint.push(factory);
18799 lView.push(factory);
18800 }
18801 else {
18802 // Cases 1.b and 2.b
18803 const indexInFactory = multiFactoryAdd(lInjectablesBlueprint[isViewProvider ? existingViewProvidersFactoryIndex :
18804 existingProvidersFactoryIndex], providerFactory, !isViewProvider && isComponent);
18805 registerDestroyHooksIfSupported(tView, provider, existingProvidersFactoryIndex > -1 ? existingProvidersFactoryIndex :
18806 existingViewProvidersFactoryIndex, indexInFactory);
18807 }
18808 if (!isViewProvider && isComponent && doesViewProvidersFactoryExist) {
18809 lInjectablesBlueprint[existingViewProvidersFactoryIndex].componentProviders++;
18810 }
18811 }
18812 }
18813}
18814/**
18815 * Registers the `ngOnDestroy` hook of a provider, if the provider supports destroy hooks.
18816 * @param tView `TView` in which to register the hook.
18817 * @param provider Provider whose hook should be registered.
18818 * @param contextIndex Index under which to find the context for the hook when it's being invoked.
18819 * @param indexInFactory Only required for `multi` providers. Index of the provider in the multi
18820 * provider factory.
18821 */
18822function registerDestroyHooksIfSupported(tView, provider, contextIndex, indexInFactory) {
18823 const providerIsTypeProvider = isTypeProvider(provider);
18824 if (providerIsTypeProvider || isClassProvider(provider)) {
18825 const prototype = (provider.useClass || provider).prototype;
18826 const ngOnDestroy = prototype.ngOnDestroy;
18827 if (ngOnDestroy) {
18828 const hooks = tView.destroyHooks || (tView.destroyHooks = []);
18829 if (!providerIsTypeProvider && provider.multi) {
18830 ngDevMode &&
18831 assertDefined(indexInFactory, 'indexInFactory when registering multi factory destroy hook');
18832 const existingCallbacksIndex = hooks.indexOf(contextIndex);
18833 if (existingCallbacksIndex === -1) {
18834 hooks.push(contextIndex, [indexInFactory, ngOnDestroy]);
18835 }
18836 else {
18837 hooks[existingCallbacksIndex + 1].push(indexInFactory, ngOnDestroy);
18838 }
18839 }
18840 else {
18841 hooks.push(contextIndex, ngOnDestroy);
18842 }
18843 }
18844 }
18845}
18846/**
18847 * Add a factory in a multi factory.
18848 * @returns Index at which the factory was inserted.
18849 */
18850function multiFactoryAdd(multiFactory, factory, isComponentProvider) {
18851 if (isComponentProvider) {
18852 multiFactory.componentProviders++;
18853 }
18854 return multiFactory.multi.push(factory) - 1;
18855}
18856/**
18857 * Returns the index of item in the array, but only in the begin to end range.
18858 */
18859function indexOf(item, arr, begin, end) {
18860 for (let i = begin; i < end; i++) {
18861 if (arr[i] === item)
18862 return i;
18863 }
18864 return -1;
18865}
18866/**
18867 * Use this with `multi` `providers`.
18868 */
18869function multiProvidersFactoryResolver(_, tData, lData, tNode) {
18870 return multiResolve(this.multi, []);
18871}
18872/**
18873 * Use this with `multi` `viewProviders`.
18874 *
18875 * This factory knows how to concatenate itself with the existing `multi` `providers`.
18876 */
18877function multiViewProvidersFactoryResolver(_, tData, lView, tNode) {
18878 const factories = this.multi;
18879 let result;
18880 if (this.providerFactory) {
18881 const componentCount = this.providerFactory.componentProviders;
18882 const multiProviders = getNodeInjectable(lView, lView[TVIEW], this.providerFactory.index, tNode);
18883 // Copy the section of the array which contains `multi` `providers` from the component
18884 result = multiProviders.slice(0, componentCount);
18885 // Insert the `viewProvider` instances.
18886 multiResolve(factories, result);
18887 // Copy the section of the array which contains `multi` `providers` from other directives
18888 for (let i = componentCount; i < multiProviders.length; i++) {
18889 result.push(multiProviders[i]);
18890 }
18891 }
18892 else {
18893 result = [];
18894 // Insert the `viewProvider` instances.
18895 multiResolve(factories, result);
18896 }
18897 return result;
18898}
18899/**
18900 * Maps an array of factories into an array of values.
18901 */
18902function multiResolve(factories, result) {
18903 for (let i = 0; i < factories.length; i++) {
18904 const factory = factories[i];
18905 result.push(factory());
18906 }
18907 return result;
18908}
18909/**
18910 * Creates a multi factory.
18911 */
18912function multiFactory(factoryFn, index, isViewProvider, isComponent, f) {
18913 const factory = new NodeInjectorFactory(factoryFn, isViewProvider, ɵɵdirectiveInject);
18914 factory.multi = [];
18915 factory.index = index;
18916 factory.componentProviders = 0;
18917 multiFactoryAdd(factory, f, isComponent && !isViewProvider);
18918 return factory;
18919}
18920
18921/**
18922 * This feature resolves the providers of a directive (or component),
18923 * and publish them into the DI system, making it visible to others for injection.
18924 *
18925 * For example:
18926 * ```ts
18927 * class ComponentWithProviders {
18928 * constructor(private greeter: GreeterDE) {}
18929 *
18930 * static ɵcmp = defineComponent({
18931 * type: ComponentWithProviders,
18932 * selectors: [['component-with-providers']],
18933 * factory: () => new ComponentWithProviders(directiveInject(GreeterDE as any)),
18934 * decls: 1,
18935 * vars: 1,
18936 * template: function(fs: RenderFlags, ctx: ComponentWithProviders) {
18937 * if (fs & RenderFlags.Create) {
18938 * ɵɵtext(0);
18939 * }
18940 * if (fs & RenderFlags.Update) {
18941 * ɵɵtextInterpolate(ctx.greeter.greet());
18942 * }
18943 * },
18944 * features: [ProvidersFeature([GreeterDE])]
18945 * });
18946 * }
18947 * ```
18948 *
18949 * @param definition
18950 *
18951 * @codeGenApi
18952 */
18953function ɵɵProvidersFeature(providers, viewProviders = []) {
18954 return (definition) => {
18955 definition.providersResolver =
18956 (def, processProvidersFn) => {
18957 return providersResolver(def, //
18958 processProvidersFn ? processProvidersFn(providers) : providers, //
18959 viewProviders);
18960 };
18961 };
18962}
18963
18964/**
18965 * @license
18966 * Copyright Google LLC All Rights Reserved.
18967 *
18968 * Use of this source code is governed by an MIT-style license that can be
18969 * found in the LICENSE file at https://angular.io/license
18970 */
18971/**
18972 * Represents a component created by a `ComponentFactory`.
18973 * Provides access to the component instance and related objects,
18974 * and provides the means of destroying the instance.
18975 *
18976 * @publicApi
18977 */
18978class ComponentRef {
18979}
18980/**
18981 * Base class for a factory that can create a component dynamically.
18982 * Instantiate a factory for a given type of component with `resolveComponentFactory()`.
18983 * Use the resulting `ComponentFactory.create()` method to create a component of that type.
18984 *
18985 * @see [Dynamic Components](guide/dynamic-component-loader)
18986 *
18987 * @publicApi
18988 */
18989class ComponentFactory {
18990}
18991
18992/**
18993 * @license
18994 * Copyright Google LLC All Rights Reserved.
18995 *
18996 * Use of this source code is governed by an MIT-style license that can be
18997 * found in the LICENSE file at https://angular.io/license
18998 */
18999function noComponentFactoryError(component) {
19000 const error = Error(`No component factory found for ${stringify(component)}. Did you add it to @NgModule.entryComponents?`);
19001 error[ERROR_COMPONENT] = component;
19002 return error;
19003}
19004const ERROR_COMPONENT = 'ngComponent';
19005function getComponent$1(error) {
19006 return error[ERROR_COMPONENT];
19007}
19008class _NullComponentFactoryResolver {
19009 resolveComponentFactory(component) {
19010 throw noComponentFactoryError(component);
19011 }
19012}
19013/**
19014 * A simple registry that maps `Components` to generated `ComponentFactory` classes
19015 * that can be used to create instances of components.
19016 * Use to obtain the factory for a given component type,
19017 * then use the factory's `create()` method to create a component of that type.
19018 *
19019 * @see [Dynamic Components](guide/dynamic-component-loader)
19020 * @publicApi
19021 */
19022class ComponentFactoryResolver {
19023}
19024ComponentFactoryResolver.NULL = new _NullComponentFactoryResolver();
19025class CodegenComponentFactoryResolver {
19026 constructor(factories, _parent, _ngModule) {
19027 this._parent = _parent;
19028 this._ngModule = _ngModule;
19029 this._factories = new Map();
19030 for (let i = 0; i < factories.length; i++) {
19031 const factory = factories[i];
19032 this._factories.set(factory.componentType, factory);
19033 }
19034 }
19035 resolveComponentFactory(component) {
19036 let factory = this._factories.get(component);
19037 if (!factory && this._parent) {
19038 factory = this._parent.resolveComponentFactory(component);
19039 }
19040 if (!factory) {
19041 throw noComponentFactoryError(component);
19042 }
19043 return new ComponentFactoryBoundToModule(factory, this._ngModule);
19044 }
19045}
19046class ComponentFactoryBoundToModule extends ComponentFactory {
19047 constructor(factory, ngModule) {
19048 super();
19049 this.factory = factory;
19050 this.ngModule = ngModule;
19051 this.selector = factory.selector;
19052 this.componentType = factory.componentType;
19053 this.ngContentSelectors = factory.ngContentSelectors;
19054 this.inputs = factory.inputs;
19055 this.outputs = factory.outputs;
19056 }
19057 create(injector, projectableNodes, rootSelectorOrNode, ngModule) {
19058 return this.factory.create(injector, projectableNodes, rootSelectorOrNode, ngModule || this.ngModule);
19059 }
19060}
19061
19062/**
19063 * @license
19064 * Copyright Google LLC All Rights Reserved.
19065 *
19066 * Use of this source code is governed by an MIT-style license that can be
19067 * found in the LICENSE file at https://angular.io/license
19068 */
19069function noop(...args) {
19070 // Do nothing.
19071}
19072
19073/**
19074 * @license
19075 * Copyright Google LLC All Rights Reserved.
19076 *
19077 * Use of this source code is governed by an MIT-style license that can be
19078 * found in the LICENSE file at https://angular.io/license
19079 */
19080/**
19081 * A wrapper around a native element inside of a View.
19082 *
19083 * An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM
19084 * element.
19085 *
19086 * @security Permitting direct access to the DOM can make your application more vulnerable to
19087 * XSS attacks. Carefully review any use of `ElementRef` in your code. For more detail, see the
19088 * [Security Guide](http://g.co/ng/security).
19089 *
19090 * @publicApi
19091 */
19092// Note: We don't expose things like `Injector`, `ViewContainer`, ... here,
19093// i.e. users have to ask for what they need. With that, we can build better analysis tools
19094// and could do better codegen in the future.
19095class ElementRef {
19096 constructor(nativeElement) {
19097 this.nativeElement = nativeElement;
19098 }
19099}
19100/**
19101 * @internal
19102 * @nocollapse
19103 */
19104ElementRef.__NG_ELEMENT_ID__ = () => SWITCH_ELEMENT_REF_FACTORY(ElementRef);
19105const SWITCH_ELEMENT_REF_FACTORY__POST_R3__ = injectElementRef;
19106const SWITCH_ELEMENT_REF_FACTORY__PRE_R3__ = noop;
19107const SWITCH_ELEMENT_REF_FACTORY = SWITCH_ELEMENT_REF_FACTORY__PRE_R3__;
19108
19109/**
19110 * @license
19111 * Copyright Google LLC All Rights Reserved.
19112 *
19113 * Use of this source code is governed by an MIT-style license that can be
19114 * found in the LICENSE file at https://angular.io/license
19115 */
19116const Renderer2Interceptor = new InjectionToken('Renderer2Interceptor');
19117/**
19118 * Creates and initializes a custom renderer that implements the `Renderer2` base class.
19119 *
19120 * @publicApi
19121 */
19122class RendererFactory2 {
19123}
19124/**
19125 * Flags for renderer-specific style modifiers.
19126 * @publicApi
19127 */
19128var RendererStyleFlags2;
19129(function (RendererStyleFlags2) {
19130 // TODO(misko): This needs to be refactored into a separate file so that it can be imported from
19131 // `node_manipulation.ts` Currently doing the import cause resolution order to change and fails
19132 // the tests. The work around is to have hard coded value in `node_manipulation.ts` for now.
19133 /**
19134 * Marks a style as important.
19135 */
19136 RendererStyleFlags2[RendererStyleFlags2["Important"] = 1] = "Important";
19137 /**
19138 * Marks a style as using dash case naming (this-is-dash-case).
19139 */
19140 RendererStyleFlags2[RendererStyleFlags2["DashCase"] = 2] = "DashCase";
19141})(RendererStyleFlags2 || (RendererStyleFlags2 = {}));
19142/**
19143 * Extend this base class to implement custom rendering. By default, Angular
19144 * renders a template into DOM. You can use custom rendering to intercept
19145 * rendering calls, or to render to something other than DOM.
19146 *
19147 * Create your custom renderer using `RendererFactory2`.
19148 *
19149 * Use a custom renderer to bypass Angular's templating and
19150 * make custom UI changes that can't be expressed declaratively.
19151 * For example if you need to set a property or an attribute whose name is
19152 * not statically known, use the `setProperty()` or
19153 * `setAttribute()` method.
19154 *
19155 * @publicApi
19156 */
19157class Renderer2 {
19158}
19159/**
19160 * @internal
19161 * @nocollapse
19162 */
19163Renderer2.__NG_ELEMENT_ID__ = () => SWITCH_RENDERER2_FACTORY();
19164const SWITCH_RENDERER2_FACTORY__POST_R3__ = injectRenderer2;
19165const SWITCH_RENDERER2_FACTORY__PRE_R3__ = noop;
19166const SWITCH_RENDERER2_FACTORY = SWITCH_RENDERER2_FACTORY__PRE_R3__;
19167
19168/**
19169 * @license
19170 * Copyright Google LLC All Rights Reserved.
19171 *
19172 * Use of this source code is governed by an MIT-style license that can be
19173 * found in the LICENSE file at https://angular.io/license
19174 */
19175/**
19176 * Sanitizer is used by the views to sanitize potentially dangerous values.
19177 *
19178 * @publicApi
19179 */
19180class Sanitizer {
19181}
19182/** @nocollapse */
19183Sanitizer.ɵprov = ɵɵdefineInjectable({
19184 token: Sanitizer,
19185 providedIn: 'root',
19186 factory: () => null,
19187});
19188
19189/**
19190 * @license
19191 * Copyright Google LLC All Rights Reserved.
19192 *
19193 * Use of this source code is governed by an MIT-style license that can be
19194 * found in the LICENSE file at https://angular.io/license
19195 */
19196/**
19197 * @description Represents the version of Angular
19198 *
19199 * @publicApi
19200 */
19201class Version {
19202 constructor(full) {
19203 this.full = full;
19204 this.major = full.split('.')[0];
19205 this.minor = full.split('.')[1];
19206 this.patch = full.split('.').slice(2).join('.');
19207 }
19208}
19209/**
19210 * @publicApi
19211 */
19212const VERSION = new Version('10.0.10');
19213
19214/**
19215 * @license
19216 * Copyright Google LLC All Rights Reserved.
19217 *
19218 * Use of this source code is governed by an MIT-style license that can be
19219 * found in the LICENSE file at https://angular.io/license
19220 */
19221class DefaultIterableDifferFactory {
19222 constructor() { }
19223 supports(obj) {
19224 return isListLikeIterable(obj);
19225 }
19226 create(trackByFn) {
19227 return new DefaultIterableDiffer(trackByFn);
19228 }
19229}
19230const trackByIdentity = (index, item) => item;
19231const ɵ0$c = trackByIdentity;
19232/**
19233 * @deprecated v4.0.0 - Should not be part of public API.
19234 * @publicApi
19235 */
19236class DefaultIterableDiffer {
19237 constructor(trackByFn) {
19238 this.length = 0;
19239 // Keeps track of the used records at any point in time (during & across `_check()` calls)
19240 this._linkedRecords = null;
19241 // Keeps track of the removed records at any point in time during `_check()` calls.
19242 this._unlinkedRecords = null;
19243 this._previousItHead = null;
19244 this._itHead = null;
19245 this._itTail = null;
19246 this._additionsHead = null;
19247 this._additionsTail = null;
19248 this._movesHead = null;
19249 this._movesTail = null;
19250 this._removalsHead = null;
19251 this._removalsTail = null;
19252 // Keeps track of records where custom track by is the same, but item identity has changed
19253 this._identityChangesHead = null;
19254 this._identityChangesTail = null;
19255 this._trackByFn = trackByFn || trackByIdentity;
19256 }
19257 forEachItem(fn) {
19258 let record;
19259 for (record = this._itHead; record !== null; record = record._next) {
19260 fn(record);
19261 }
19262 }
19263 forEachOperation(fn) {
19264 let nextIt = this._itHead;
19265 let nextRemove = this._removalsHead;
19266 let addRemoveOffset = 0;
19267 let moveOffsets = null;
19268 while (nextIt || nextRemove) {
19269 // Figure out which is the next record to process
19270 // Order: remove, add, move
19271 const record = !nextRemove ||
19272 nextIt &&
19273 nextIt.currentIndex <
19274 getPreviousIndex(nextRemove, addRemoveOffset, moveOffsets) ?
19275 nextIt :
19276 nextRemove;
19277 const adjPreviousIndex = getPreviousIndex(record, addRemoveOffset, moveOffsets);
19278 const currentIndex = record.currentIndex;
19279 // consume the item, and adjust the addRemoveOffset and update moveDistance if necessary
19280 if (record === nextRemove) {
19281 addRemoveOffset--;
19282 nextRemove = nextRemove._nextRemoved;
19283 }
19284 else {
19285 nextIt = nextIt._next;
19286 if (record.previousIndex == null) {
19287 addRemoveOffset++;
19288 }
19289 else {
19290 // INVARIANT: currentIndex < previousIndex
19291 if (!moveOffsets)
19292 moveOffsets = [];
19293 const localMovePreviousIndex = adjPreviousIndex - addRemoveOffset;
19294 const localCurrentIndex = currentIndex - addRemoveOffset;
19295 if (localMovePreviousIndex != localCurrentIndex) {
19296 for (let i = 0; i < localMovePreviousIndex; i++) {
19297 const offset = i < moveOffsets.length ? moveOffsets[i] : (moveOffsets[i] = 0);
19298 const index = offset + i;
19299 if (localCurrentIndex <= index && index < localMovePreviousIndex) {
19300 moveOffsets[i] = offset + 1;
19301 }
19302 }
19303 const previousIndex = record.previousIndex;
19304 moveOffsets[previousIndex] = localCurrentIndex - localMovePreviousIndex;
19305 }
19306 }
19307 }
19308 if (adjPreviousIndex !== currentIndex) {
19309 fn(record, adjPreviousIndex, currentIndex);
19310 }
19311 }
19312 }
19313 forEachPreviousItem(fn) {
19314 let record;
19315 for (record = this._previousItHead; record !== null; record = record._nextPrevious) {
19316 fn(record);
19317 }
19318 }
19319 forEachAddedItem(fn) {
19320 let record;
19321 for (record = this._additionsHead; record !== null; record = record._nextAdded) {
19322 fn(record);
19323 }
19324 }
19325 forEachMovedItem(fn) {
19326 let record;
19327 for (record = this._movesHead; record !== null; record = record._nextMoved) {
19328 fn(record);
19329 }
19330 }
19331 forEachRemovedItem(fn) {
19332 let record;
19333 for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
19334 fn(record);
19335 }
19336 }
19337 forEachIdentityChange(fn) {
19338 let record;
19339 for (record = this._identityChangesHead; record !== null; record = record._nextIdentityChange) {
19340 fn(record);
19341 }
19342 }
19343 diff(collection) {
19344 if (collection == null)
19345 collection = [];
19346 if (!isListLikeIterable(collection)) {
19347 throw new Error(`Error trying to diff '${stringify(collection)}'. Only arrays and iterables are allowed`);
19348 }
19349 if (this.check(collection)) {
19350 return this;
19351 }
19352 else {
19353 return null;
19354 }
19355 }
19356 onDestroy() { }
19357 check(collection) {
19358 this._reset();
19359 let record = this._itHead;
19360 let mayBeDirty = false;
19361 let index;
19362 let item;
19363 let itemTrackBy;
19364 if (Array.isArray(collection)) {
19365 this.length = collection.length;
19366 for (let index = 0; index < this.length; index++) {
19367 item = collection[index];
19368 itemTrackBy = this._trackByFn(index, item);
19369 if (record === null || !Object.is(record.trackById, itemTrackBy)) {
19370 record = this._mismatch(record, item, itemTrackBy, index);
19371 mayBeDirty = true;
19372 }
19373 else {
19374 if (mayBeDirty) {
19375 // TODO(misko): can we limit this to duplicates only?
19376 record = this._verifyReinsertion(record, item, itemTrackBy, index);
19377 }
19378 if (!Object.is(record.item, item))
19379 this._addIdentityChange(record, item);
19380 }
19381 record = record._next;
19382 }
19383 }
19384 else {
19385 index = 0;
19386 iterateListLike(collection, (item) => {
19387 itemTrackBy = this._trackByFn(index, item);
19388 if (record === null || !Object.is(record.trackById, itemTrackBy)) {
19389 record = this._mismatch(record, item, itemTrackBy, index);
19390 mayBeDirty = true;
19391 }
19392 else {
19393 if (mayBeDirty) {
19394 // TODO(misko): can we limit this to duplicates only?
19395 record = this._verifyReinsertion(record, item, itemTrackBy, index);
19396 }
19397 if (!Object.is(record.item, item))
19398 this._addIdentityChange(record, item);
19399 }
19400 record = record._next;
19401 index++;
19402 });
19403 this.length = index;
19404 }
19405 this._truncate(record);
19406 this.collection = collection;
19407 return this.isDirty;
19408 }
19409 /* CollectionChanges is considered dirty if it has any additions, moves, removals, or identity
19410 * changes.
19411 */
19412 get isDirty() {
19413 return this._additionsHead !== null || this._movesHead !== null ||
19414 this._removalsHead !== null || this._identityChangesHead !== null;
19415 }
19416 /**
19417 * Reset the state of the change objects to show no changes. This means set previousKey to
19418 * currentKey, and clear all of the queues (additions, moves, removals).
19419 * Set the previousIndexes of moved and added items to their currentIndexes
19420 * Reset the list of additions, moves and removals
19421 *
19422 * @internal
19423 */
19424 _reset() {
19425 if (this.isDirty) {
19426 let record;
19427 let nextRecord;
19428 for (record = this._previousItHead = this._itHead; record !== null; record = record._next) {
19429 record._nextPrevious = record._next;
19430 }
19431 for (record = this._additionsHead; record !== null; record = record._nextAdded) {
19432 record.previousIndex = record.currentIndex;
19433 }
19434 this._additionsHead = this._additionsTail = null;
19435 for (record = this._movesHead; record !== null; record = nextRecord) {
19436 record.previousIndex = record.currentIndex;
19437 nextRecord = record._nextMoved;
19438 }
19439 this._movesHead = this._movesTail = null;
19440 this._removalsHead = this._removalsTail = null;
19441 this._identityChangesHead = this._identityChangesTail = null;
19442 // TODO(vicb): when assert gets supported
19443 // assert(!this.isDirty);
19444 }
19445 }
19446 /**
19447 * This is the core function which handles differences between collections.
19448 *
19449 * - `record` is the record which we saw at this position last time. If null then it is a new
19450 * item.
19451 * - `item` is the current item in the collection
19452 * - `index` is the position of the item in the collection
19453 *
19454 * @internal
19455 */
19456 _mismatch(record, item, itemTrackBy, index) {
19457 // The previous record after which we will append the current one.
19458 let previousRecord;
19459 if (record === null) {
19460 previousRecord = this._itTail;
19461 }
19462 else {
19463 previousRecord = record._prev;
19464 // Remove the record from the collection since we know it does not match the item.
19465 this._remove(record);
19466 }
19467 // Attempt to see if we have seen the item before.
19468 record = this._linkedRecords === null ? null : this._linkedRecords.get(itemTrackBy, index);
19469 if (record !== null) {
19470 // We have seen this before, we need to move it forward in the collection.
19471 // But first we need to check if identity changed, so we can update in view if necessary
19472 if (!Object.is(record.item, item))
19473 this._addIdentityChange(record, item);
19474 this._moveAfter(record, previousRecord, index);
19475 }
19476 else {
19477 // Never seen it, check evicted list.
19478 record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
19479 if (record !== null) {
19480 // It is an item which we have evicted earlier: reinsert it back into the list.
19481 // But first we need to check if identity changed, so we can update in view if necessary
19482 if (!Object.is(record.item, item))
19483 this._addIdentityChange(record, item);
19484 this._reinsertAfter(record, previousRecord, index);
19485 }
19486 else {
19487 // It is a new item: add it.
19488 record =
19489 this._addAfter(new IterableChangeRecord_(item, itemTrackBy), previousRecord, index);
19490 }
19491 }
19492 return record;
19493 }
19494 /**
19495 * This check is only needed if an array contains duplicates. (Short circuit of nothing dirty)
19496 *
19497 * Use case: `[a, a]` => `[b, a, a]`
19498 *
19499 * If we did not have this check then the insertion of `b` would:
19500 * 1) evict first `a`
19501 * 2) insert `b` at `0` index.
19502 * 3) leave `a` at index `1` as is. <-- this is wrong!
19503 * 3) reinsert `a` at index 2. <-- this is wrong!
19504 *
19505 * The correct behavior is:
19506 * 1) evict first `a`
19507 * 2) insert `b` at `0` index.
19508 * 3) reinsert `a` at index 1.
19509 * 3) move `a` at from `1` to `2`.
19510 *
19511 *
19512 * Double check that we have not evicted a duplicate item. We need to check if the item type may
19513 * have already been removed:
19514 * The insertion of b will evict the first 'a'. If we don't reinsert it now it will be reinserted
19515 * at the end. Which will show up as the two 'a's switching position. This is incorrect, since a
19516 * better way to think of it is as insert of 'b' rather then switch 'a' with 'b' and then add 'a'
19517 * at the end.
19518 *
19519 * @internal
19520 */
19521 _verifyReinsertion(record, item, itemTrackBy, index) {
19522 let reinsertRecord = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null);
19523 if (reinsertRecord !== null) {
19524 record = this._reinsertAfter(reinsertRecord, record._prev, index);
19525 }
19526 else if (record.currentIndex != index) {
19527 record.currentIndex = index;
19528 this._addToMoves(record, index);
19529 }
19530 return record;
19531 }
19532 /**
19533 * Get rid of any excess {@link IterableChangeRecord_}s from the previous collection
19534 *
19535 * - `record` The first excess {@link IterableChangeRecord_}.
19536 *
19537 * @internal
19538 */
19539 _truncate(record) {
19540 // Anything after that needs to be removed;
19541 while (record !== null) {
19542 const nextRecord = record._next;
19543 this._addToRemovals(this._unlink(record));
19544 record = nextRecord;
19545 }
19546 if (this._unlinkedRecords !== null) {
19547 this._unlinkedRecords.clear();
19548 }
19549 if (this._additionsTail !== null) {
19550 this._additionsTail._nextAdded = null;
19551 }
19552 if (this._movesTail !== null) {
19553 this._movesTail._nextMoved = null;
19554 }
19555 if (this._itTail !== null) {
19556 this._itTail._next = null;
19557 }
19558 if (this._removalsTail !== null) {
19559 this._removalsTail._nextRemoved = null;
19560 }
19561 if (this._identityChangesTail !== null) {
19562 this._identityChangesTail._nextIdentityChange = null;
19563 }
19564 }
19565 /** @internal */
19566 _reinsertAfter(record, prevRecord, index) {
19567 if (this._unlinkedRecords !== null) {
19568 this._unlinkedRecords.remove(record);
19569 }
19570 const prev = record._prevRemoved;
19571 const next = record._nextRemoved;
19572 if (prev === null) {
19573 this._removalsHead = next;
19574 }
19575 else {
19576 prev._nextRemoved = next;
19577 }
19578 if (next === null) {
19579 this._removalsTail = prev;
19580 }
19581 else {
19582 next._prevRemoved = prev;
19583 }
19584 this._insertAfter(record, prevRecord, index);
19585 this._addToMoves(record, index);
19586 return record;
19587 }
19588 /** @internal */
19589 _moveAfter(record, prevRecord, index) {
19590 this._unlink(record);
19591 this._insertAfter(record, prevRecord, index);
19592 this._addToMoves(record, index);
19593 return record;
19594 }
19595 /** @internal */
19596 _addAfter(record, prevRecord, index) {
19597 this._insertAfter(record, prevRecord, index);
19598 if (this._additionsTail === null) {
19599 // TODO(vicb):
19600 // assert(this._additionsHead === null);
19601 this._additionsTail = this._additionsHead = record;
19602 }
19603 else {
19604 // TODO(vicb):
19605 // assert(_additionsTail._nextAdded === null);
19606 // assert(record._nextAdded === null);
19607 this._additionsTail = this._additionsTail._nextAdded = record;
19608 }
19609 return record;
19610 }
19611 /** @internal */
19612 _insertAfter(record, prevRecord, index) {
19613 // TODO(vicb):
19614 // assert(record != prevRecord);
19615 // assert(record._next === null);
19616 // assert(record._prev === null);
19617 const next = prevRecord === null ? this._itHead : prevRecord._next;
19618 // TODO(vicb):
19619 // assert(next != record);
19620 // assert(prevRecord != record);
19621 record._next = next;
19622 record._prev = prevRecord;
19623 if (next === null) {
19624 this._itTail = record;
19625 }
19626 else {
19627 next._prev = record;
19628 }
19629 if (prevRecord === null) {
19630 this._itHead = record;
19631 }
19632 else {
19633 prevRecord._next = record;
19634 }
19635 if (this._linkedRecords === null) {
19636 this._linkedRecords = new _DuplicateMap();
19637 }
19638 this._linkedRecords.put(record);
19639 record.currentIndex = index;
19640 return record;
19641 }
19642 /** @internal */
19643 _remove(record) {
19644 return this._addToRemovals(this._unlink(record));
19645 }
19646 /** @internal */
19647 _unlink(record) {
19648 if (this._linkedRecords !== null) {
19649 this._linkedRecords.remove(record);
19650 }
19651 const prev = record._prev;
19652 const next = record._next;
19653 // TODO(vicb):
19654 // assert((record._prev = null) === null);
19655 // assert((record._next = null) === null);
19656 if (prev === null) {
19657 this._itHead = next;
19658 }
19659 else {
19660 prev._next = next;
19661 }
19662 if (next === null) {
19663 this._itTail = prev;
19664 }
19665 else {
19666 next._prev = prev;
19667 }
19668 return record;
19669 }
19670 /** @internal */
19671 _addToMoves(record, toIndex) {
19672 // TODO(vicb):
19673 // assert(record._nextMoved === null);
19674 if (record.previousIndex === toIndex) {
19675 return record;
19676 }
19677 if (this._movesTail === null) {
19678 // TODO(vicb):
19679 // assert(_movesHead === null);
19680 this._movesTail = this._movesHead = record;
19681 }
19682 else {
19683 // TODO(vicb):
19684 // assert(_movesTail._nextMoved === null);
19685 this._movesTail = this._movesTail._nextMoved = record;
19686 }
19687 return record;
19688 }
19689 _addToRemovals(record) {
19690 if (this._unlinkedRecords === null) {
19691 this._unlinkedRecords = new _DuplicateMap();
19692 }
19693 this._unlinkedRecords.put(record);
19694 record.currentIndex = null;
19695 record._nextRemoved = null;
19696 if (this._removalsTail === null) {
19697 // TODO(vicb):
19698 // assert(_removalsHead === null);
19699 this._removalsTail = this._removalsHead = record;
19700 record._prevRemoved = null;
19701 }
19702 else {
19703 // TODO(vicb):
19704 // assert(_removalsTail._nextRemoved === null);
19705 // assert(record._nextRemoved === null);
19706 record._prevRemoved = this._removalsTail;
19707 this._removalsTail = this._removalsTail._nextRemoved = record;
19708 }
19709 return record;
19710 }
19711 /** @internal */
19712 _addIdentityChange(record, item) {
19713 record.item = item;
19714 if (this._identityChangesTail === null) {
19715 this._identityChangesTail = this._identityChangesHead = record;
19716 }
19717 else {
19718 this._identityChangesTail = this._identityChangesTail._nextIdentityChange = record;
19719 }
19720 return record;
19721 }
19722}
19723class IterableChangeRecord_ {
19724 constructor(item, trackById) {
19725 this.item = item;
19726 this.trackById = trackById;
19727 this.currentIndex = null;
19728 this.previousIndex = null;
19729 /** @internal */
19730 this._nextPrevious = null;
19731 /** @internal */
19732 this._prev = null;
19733 /** @internal */
19734 this._next = null;
19735 /** @internal */
19736 this._prevDup = null;
19737 /** @internal */
19738 this._nextDup = null;
19739 /** @internal */
19740 this._prevRemoved = null;
19741 /** @internal */
19742 this._nextRemoved = null;
19743 /** @internal */
19744 this._nextAdded = null;
19745 /** @internal */
19746 this._nextMoved = null;
19747 /** @internal */
19748 this._nextIdentityChange = null;
19749 }
19750}
19751// A linked list of CollectionChangeRecords with the same IterableChangeRecord_.item
19752class _DuplicateItemRecordList {
19753 constructor() {
19754 /** @internal */
19755 this._head = null;
19756 /** @internal */
19757 this._tail = null;
19758 }
19759 /**
19760 * Append the record to the list of duplicates.
19761 *
19762 * Note: by design all records in the list of duplicates hold the same value in record.item.
19763 */
19764 add(record) {
19765 if (this._head === null) {
19766 this._head = this._tail = record;
19767 record._nextDup = null;
19768 record._prevDup = null;
19769 }
19770 else {
19771 // TODO(vicb):
19772 // assert(record.item == _head.item ||
19773 // record.item is num && record.item.isNaN && _head.item is num && _head.item.isNaN);
19774 this._tail._nextDup = record;
19775 record._prevDup = this._tail;
19776 record._nextDup = null;
19777 this._tail = record;
19778 }
19779 }
19780 // Returns a IterableChangeRecord_ having IterableChangeRecord_.trackById == trackById and
19781 // IterableChangeRecord_.currentIndex >= atOrAfterIndex
19782 get(trackById, atOrAfterIndex) {
19783 let record;
19784 for (record = this._head; record !== null; record = record._nextDup) {
19785 if ((atOrAfterIndex === null || atOrAfterIndex <= record.currentIndex) &&
19786 Object.is(record.trackById, trackById)) {
19787 return record;
19788 }
19789 }
19790 return null;
19791 }
19792 /**
19793 * Remove one {@link IterableChangeRecord_} from the list of duplicates.
19794 *
19795 * Returns whether the list of duplicates is empty.
19796 */
19797 remove(record) {
19798 // TODO(vicb):
19799 // assert(() {
19800 // // verify that the record being removed is in the list.
19801 // for (IterableChangeRecord_ cursor = _head; cursor != null; cursor = cursor._nextDup) {
19802 // if (identical(cursor, record)) return true;
19803 // }
19804 // return false;
19805 //});
19806 const prev = record._prevDup;
19807 const next = record._nextDup;
19808 if (prev === null) {
19809 this._head = next;
19810 }
19811 else {
19812 prev._nextDup = next;
19813 }
19814 if (next === null) {
19815 this._tail = prev;
19816 }
19817 else {
19818 next._prevDup = prev;
19819 }
19820 return this._head === null;
19821 }
19822}
19823class _DuplicateMap {
19824 constructor() {
19825 this.map = new Map();
19826 }
19827 put(record) {
19828 const key = record.trackById;
19829 let duplicates = this.map.get(key);
19830 if (!duplicates) {
19831 duplicates = new _DuplicateItemRecordList();
19832 this.map.set(key, duplicates);
19833 }
19834 duplicates.add(record);
19835 }
19836 /**
19837 * Retrieve the `value` using key. Because the IterableChangeRecord_ value may be one which we
19838 * have already iterated over, we use the `atOrAfterIndex` to pretend it is not there.
19839 *
19840 * Use case: `[a, b, c, a, a]` if we are at index `3` which is the second `a` then asking if we
19841 * have any more `a`s needs to return the second `a`.
19842 */
19843 get(trackById, atOrAfterIndex) {
19844 const key = trackById;
19845 const recordList = this.map.get(key);
19846 return recordList ? recordList.get(trackById, atOrAfterIndex) : null;
19847 }
19848 /**
19849 * Removes a {@link IterableChangeRecord_} from the list of duplicates.
19850 *
19851 * The list of duplicates also is removed from the map if it gets empty.
19852 */
19853 remove(record) {
19854 const key = record.trackById;
19855 const recordList = this.map.get(key);
19856 // Remove the list of duplicates when it gets empty
19857 if (recordList.remove(record)) {
19858 this.map.delete(key);
19859 }
19860 return record;
19861 }
19862 get isEmpty() {
19863 return this.map.size === 0;
19864 }
19865 clear() {
19866 this.map.clear();
19867 }
19868}
19869function getPreviousIndex(item, addRemoveOffset, moveOffsets) {
19870 const previousIndex = item.previousIndex;
19871 if (previousIndex === null)
19872 return previousIndex;
19873 let moveOffset = 0;
19874 if (moveOffsets && previousIndex < moveOffsets.length) {
19875 moveOffset = moveOffsets[previousIndex];
19876 }
19877 return previousIndex + addRemoveOffset + moveOffset;
19878}
19879
19880/**
19881 * @license
19882 * Copyright Google LLC All Rights Reserved.
19883 *
19884 * Use of this source code is governed by an MIT-style license that can be
19885 * found in the LICENSE file at https://angular.io/license
19886 */
19887class DefaultKeyValueDifferFactory {
19888 constructor() { }
19889 supports(obj) {
19890 return obj instanceof Map || isJsObject(obj);
19891 }
19892 create() {
19893 return new DefaultKeyValueDiffer();
19894 }
19895}
19896class DefaultKeyValueDiffer {
19897 constructor() {
19898 this._records = new Map();
19899 this._mapHead = null;
19900 // _appendAfter is used in the check loop
19901 this._appendAfter = null;
19902 this._previousMapHead = null;
19903 this._changesHead = null;
19904 this._changesTail = null;
19905 this._additionsHead = null;
19906 this._additionsTail = null;
19907 this._removalsHead = null;
19908 this._removalsTail = null;
19909 }
19910 get isDirty() {
19911 return this._additionsHead !== null || this._changesHead !== null ||
19912 this._removalsHead !== null;
19913 }
19914 forEachItem(fn) {
19915 let record;
19916 for (record = this._mapHead; record !== null; record = record._next) {
19917 fn(record);
19918 }
19919 }
19920 forEachPreviousItem(fn) {
19921 let record;
19922 for (record = this._previousMapHead; record !== null; record = record._nextPrevious) {
19923 fn(record);
19924 }
19925 }
19926 forEachChangedItem(fn) {
19927 let record;
19928 for (record = this._changesHead; record !== null; record = record._nextChanged) {
19929 fn(record);
19930 }
19931 }
19932 forEachAddedItem(fn) {
19933 let record;
19934 for (record = this._additionsHead; record !== null; record = record._nextAdded) {
19935 fn(record);
19936 }
19937 }
19938 forEachRemovedItem(fn) {
19939 let record;
19940 for (record = this._removalsHead; record !== null; record = record._nextRemoved) {
19941 fn(record);
19942 }
19943 }
19944 diff(map) {
19945 if (!map) {
19946 map = new Map();
19947 }
19948 else if (!(map instanceof Map || isJsObject(map))) {
19949 throw new Error(`Error trying to diff '${stringify(map)}'. Only maps and objects are allowed`);
19950 }
19951 return this.check(map) ? this : null;
19952 }
19953 onDestroy() { }
19954 /**
19955 * Check the current state of the map vs the previous.
19956 * The algorithm is optimised for when the keys do no change.
19957 */
19958 check(map) {
19959 this._reset();
19960 let insertBefore = this._mapHead;
19961 this._appendAfter = null;
19962 this._forEach(map, (value, key) => {
19963 if (insertBefore && insertBefore.key === key) {
19964 this._maybeAddToChanges(insertBefore, value);
19965 this._appendAfter = insertBefore;
19966 insertBefore = insertBefore._next;
19967 }
19968 else {
19969 const record = this._getOrCreateRecordForKey(key, value);
19970 insertBefore = this._insertBeforeOrAppend(insertBefore, record);
19971 }
19972 });
19973 // Items remaining at the end of the list have been deleted
19974 if (insertBefore) {
19975 if (insertBefore._prev) {
19976 insertBefore._prev._next = null;
19977 }
19978 this._removalsHead = insertBefore;
19979 for (let record = insertBefore; record !== null; record = record._nextRemoved) {
19980 if (record === this._mapHead) {
19981 this._mapHead = null;
19982 }
19983 this._records.delete(record.key);
19984 record._nextRemoved = record._next;
19985 record.previousValue = record.currentValue;
19986 record.currentValue = null;
19987 record._prev = null;
19988 record._next = null;
19989 }
19990 }
19991 // Make sure tails have no next records from previous runs
19992 if (this._changesTail)
19993 this._changesTail._nextChanged = null;
19994 if (this._additionsTail)
19995 this._additionsTail._nextAdded = null;
19996 return this.isDirty;
19997 }
19998 /**
19999 * Inserts a record before `before` or append at the end of the list when `before` is null.
20000 *
20001 * Notes:
20002 * - This method appends at `this._appendAfter`,
20003 * - This method updates `this._appendAfter`,
20004 * - The return value is the new value for the insertion pointer.
20005 */
20006 _insertBeforeOrAppend(before, record) {
20007 if (before) {
20008 const prev = before._prev;
20009 record._next = before;
20010 record._prev = prev;
20011 before._prev = record;
20012 if (prev) {
20013 prev._next = record;
20014 }
20015 if (before === this._mapHead) {
20016 this._mapHead = record;
20017 }
20018 this._appendAfter = before;
20019 return before;
20020 }
20021 if (this._appendAfter) {
20022 this._appendAfter._next = record;
20023 record._prev = this._appendAfter;
20024 }
20025 else {
20026 this._mapHead = record;
20027 }
20028 this._appendAfter = record;
20029 return null;
20030 }
20031 _getOrCreateRecordForKey(key, value) {
20032 if (this._records.has(key)) {
20033 const record = this._records.get(key);
20034 this._maybeAddToChanges(record, value);
20035 const prev = record._prev;
20036 const next = record._next;
20037 if (prev) {
20038 prev._next = next;
20039 }
20040 if (next) {
20041 next._prev = prev;
20042 }
20043 record._next = null;
20044 record._prev = null;
20045 return record;
20046 }
20047 const record = new KeyValueChangeRecord_(key);
20048 this._records.set(key, record);
20049 record.currentValue = value;
20050 this._addToAdditions(record);
20051 return record;
20052 }
20053 /** @internal */
20054 _reset() {
20055 if (this.isDirty) {
20056 let record;
20057 // let `_previousMapHead` contain the state of the map before the changes
20058 this._previousMapHead = this._mapHead;
20059 for (record = this._previousMapHead; record !== null; record = record._next) {
20060 record._nextPrevious = record._next;
20061 }
20062 // Update `record.previousValue` with the value of the item before the changes
20063 // We need to update all changed items (that's those which have been added and changed)
20064 for (record = this._changesHead; record !== null; record = record._nextChanged) {
20065 record.previousValue = record.currentValue;
20066 }
20067 for (record = this._additionsHead; record != null; record = record._nextAdded) {
20068 record.previousValue = record.currentValue;
20069 }
20070 this._changesHead = this._changesTail = null;
20071 this._additionsHead = this._additionsTail = null;
20072 this._removalsHead = null;
20073 }
20074 }
20075 // Add the record or a given key to the list of changes only when the value has actually changed
20076 _maybeAddToChanges(record, newValue) {
20077 if (!Object.is(newValue, record.currentValue)) {
20078 record.previousValue = record.currentValue;
20079 record.currentValue = newValue;
20080 this._addToChanges(record);
20081 }
20082 }
20083 _addToAdditions(record) {
20084 if (this._additionsHead === null) {
20085 this._additionsHead = this._additionsTail = record;
20086 }
20087 else {
20088 this._additionsTail._nextAdded = record;
20089 this._additionsTail = record;
20090 }
20091 }
20092 _addToChanges(record) {
20093 if (this._changesHead === null) {
20094 this._changesHead = this._changesTail = record;
20095 }
20096 else {
20097 this._changesTail._nextChanged = record;
20098 this._changesTail = record;
20099 }
20100 }
20101 /** @internal */
20102 _forEach(obj, fn) {
20103 if (obj instanceof Map) {
20104 obj.forEach(fn);
20105 }
20106 else {
20107 Object.keys(obj).forEach(k => fn(obj[k], k));
20108 }
20109 }
20110}
20111class KeyValueChangeRecord_ {
20112 constructor(key) {
20113 this.key = key;
20114 this.previousValue = null;
20115 this.currentValue = null;
20116 /** @internal */
20117 this._nextPrevious = null;
20118 /** @internal */
20119 this._next = null;
20120 /** @internal */
20121 this._prev = null;
20122 /** @internal */
20123 this._nextAdded = null;
20124 /** @internal */
20125 this._nextRemoved = null;
20126 /** @internal */
20127 this._nextChanged = null;
20128 }
20129}
20130
20131/**
20132 * @license
20133 * Copyright Google LLC All Rights Reserved.
20134 *
20135 * Use of this source code is governed by an MIT-style license that can be
20136 * found in the LICENSE file at https://angular.io/license
20137 */
20138/**
20139 * A repository of different iterable diffing strategies used by NgFor, NgClass, and others.
20140 *
20141 * @publicApi
20142 */
20143class IterableDiffers {
20144 constructor(factories) {
20145 this.factories = factories;
20146 }
20147 static create(factories, parent) {
20148 if (parent != null) {
20149 const copied = parent.factories.slice();
20150 factories = factories.concat(copied);
20151 }
20152 return new IterableDiffers(factories);
20153 }
20154 /**
20155 * Takes an array of {@link IterableDifferFactory} and returns a provider used to extend the
20156 * inherited {@link IterableDiffers} instance with the provided factories and return a new
20157 * {@link IterableDiffers} instance.
20158 *
20159 * @usageNotes
20160 * ### Example
20161 *
20162 * The following example shows how to extend an existing list of factories,
20163 * which will only be applied to the injector for this component and its children.
20164 * This step is all that's required to make a new {@link IterableDiffer} available.
20165 *
20166 * ```
20167 * @Component({
20168 * viewProviders: [
20169 * IterableDiffers.extend([new ImmutableListDiffer()])
20170 * ]
20171 * })
20172 * ```
20173 */
20174 static extend(factories) {
20175 return {
20176 provide: IterableDiffers,
20177 useFactory: (parent) => {
20178 if (!parent) {
20179 // Typically would occur when calling IterableDiffers.extend inside of dependencies passed
20180 // to
20181 // bootstrap(), which would override default pipes instead of extending them.
20182 throw new Error('Cannot extend IterableDiffers without a parent injector');
20183 }
20184 return IterableDiffers.create(factories, parent);
20185 },
20186 // Dependency technically isn't optional, but we can provide a better error message this way.
20187 deps: [[IterableDiffers, new SkipSelf(), new Optional()]]
20188 };
20189 }
20190 find(iterable) {
20191 const factory = this.factories.find(f => f.supports(iterable));
20192 if (factory != null) {
20193 return factory;
20194 }
20195 else {
20196 throw new Error(`Cannot find a differ supporting object '${iterable}' of type '${getTypeNameForDebugging(iterable)}'`);
20197 }
20198 }
20199}
20200/** @nocollapse */
20201IterableDiffers.ɵprov = ɵɵdefineInjectable({
20202 token: IterableDiffers,
20203 providedIn: 'root',
20204 factory: () => new IterableDiffers([new DefaultIterableDifferFactory()])
20205});
20206function getTypeNameForDebugging(type) {
20207 return type['name'] || typeof type;
20208}
20209
20210/**
20211 * @license
20212 * Copyright Google LLC All Rights Reserved.
20213 *
20214 * Use of this source code is governed by an MIT-style license that can be
20215 * found in the LICENSE file at https://angular.io/license
20216 */
20217/**
20218 * A repository of different Map diffing strategies used by NgClass, NgStyle, and others.
20219 *
20220 * @publicApi
20221 */
20222class KeyValueDiffers {
20223 constructor(factories) {
20224 this.factories = factories;
20225 }
20226 static create(factories, parent) {
20227 if (parent) {
20228 const copied = parent.factories.slice();
20229 factories = factories.concat(copied);
20230 }
20231 return new KeyValueDiffers(factories);
20232 }
20233 /**
20234 * Takes an array of {@link KeyValueDifferFactory} and returns a provider used to extend the
20235 * inherited {@link KeyValueDiffers} instance with the provided factories and return a new
20236 * {@link KeyValueDiffers} instance.
20237 *
20238 * @usageNotes
20239 * ### Example
20240 *
20241 * The following example shows how to extend an existing list of factories,
20242 * which will only be applied to the injector for this component and its children.
20243 * This step is all that's required to make a new {@link KeyValueDiffer} available.
20244 *
20245 * ```
20246 * @Component({
20247 * viewProviders: [
20248 * KeyValueDiffers.extend([new ImmutableMapDiffer()])
20249 * ]
20250 * })
20251 * ```
20252 */
20253 static extend(factories) {
20254 return {
20255 provide: KeyValueDiffers,
20256 useFactory: (parent) => {
20257 if (!parent) {
20258 // Typically would occur when calling KeyValueDiffers.extend inside of dependencies passed
20259 // to bootstrap(), which would override default pipes instead of extending them.
20260 throw new Error('Cannot extend KeyValueDiffers without a parent injector');
20261 }
20262 return KeyValueDiffers.create(factories, parent);
20263 },
20264 // Dependency technically isn't optional, but we can provide a better error message this way.
20265 deps: [[KeyValueDiffers, new SkipSelf(), new Optional()]]
20266 };
20267 }
20268 find(kv) {
20269 const factory = this.factories.find(f => f.supports(kv));
20270 if (factory) {
20271 return factory;
20272 }
20273 throw new Error(`Cannot find a differ supporting object '${kv}'`);
20274 }
20275}
20276/** @nocollapse */
20277KeyValueDiffers.ɵprov = ɵɵdefineInjectable({
20278 token: KeyValueDiffers,
20279 providedIn: 'root',
20280 factory: () => new KeyValueDiffers([new DefaultKeyValueDifferFactory()])
20281});
20282
20283/**
20284 * @license
20285 * Copyright Google LLC All Rights Reserved.
20286 *
20287 * Use of this source code is governed by an MIT-style license that can be
20288 * found in the LICENSE file at https://angular.io/license
20289 */
20290/**
20291 * Structural diffing for `Object`s and `Map`s.
20292 */
20293const keyValDiff = [new DefaultKeyValueDifferFactory()];
20294/**
20295 * Structural diffing for `Iterable` types such as `Array`s.
20296 */
20297const iterableDiff = [new DefaultIterableDifferFactory()];
20298const defaultIterableDiffers = new IterableDiffers(iterableDiff);
20299const defaultKeyValueDiffers = new KeyValueDiffers(keyValDiff);
20300
20301/**
20302 * @license
20303 * Copyright Google LLC All Rights Reserved.
20304 *
20305 * Use of this source code is governed by an MIT-style license that can be
20306 * found in the LICENSE file at https://angular.io/license
20307 */
20308/**
20309 * Represents an embedded template that can be used to instantiate embedded views.
20310 * To instantiate embedded views based on a template, use the `ViewContainerRef`
20311 * method `createEmbeddedView()`.
20312 *
20313 * Access a `TemplateRef` instance by placing a directive on an `<ng-template>`
20314 * element (or directive prefixed with `*`). The `TemplateRef` for the embedded view
20315 * is injected into the constructor of the directive,
20316 * using the `TemplateRef` token.
20317 *
20318 * You can also use a `Query` to find a `TemplateRef` associated with
20319 * a component or a directive.
20320 *
20321 * @see `ViewContainerRef`
20322 * @see [Navigate the Component Tree with DI](guide/dependency-injection-navtree)
20323 *
20324 * @publicApi
20325 */
20326class TemplateRef {
20327}
20328/**
20329 * @internal
20330 * @nocollapse
20331 */
20332TemplateRef.__NG_ELEMENT_ID__ = () => SWITCH_TEMPLATE_REF_FACTORY(TemplateRef, ElementRef);
20333const SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ = injectTemplateRef;
20334const SWITCH_TEMPLATE_REF_FACTORY__PRE_R3__ = noop;
20335const SWITCH_TEMPLATE_REF_FACTORY = SWITCH_TEMPLATE_REF_FACTORY__PRE_R3__;
20336
20337/**
20338 * @license
20339 * Copyright Google LLC All Rights Reserved.
20340 *
20341 * Use of this source code is governed by an MIT-style license that can be
20342 * found in the LICENSE file at https://angular.io/license
20343 */
20344/**
20345 * Represents a container where one or more views can be attached to a component.
20346 *
20347 * Can contain *host views* (created by instantiating a
20348 * component with the `createComponent()` method), and *embedded views*
20349 * (created by instantiating a `TemplateRef` with the `createEmbeddedView()` method).
20350 *
20351 * A view container instance can contain other view containers,
20352 * creating a [view hierarchy](guide/glossary#view-tree).
20353 *
20354 * @see `ComponentRef`
20355 * @see `EmbeddedViewRef`
20356 *
20357 * @publicApi
20358 */
20359class ViewContainerRef {
20360}
20361/**
20362 * @internal
20363 * @nocollapse
20364 */
20365ViewContainerRef.__NG_ELEMENT_ID__ = () => SWITCH_VIEW_CONTAINER_REF_FACTORY(ViewContainerRef, ElementRef);
20366const SWITCH_VIEW_CONTAINER_REF_FACTORY__POST_R3__ = injectViewContainerRef;
20367const SWITCH_VIEW_CONTAINER_REF_FACTORY__PRE_R3__ = noop;
20368const SWITCH_VIEW_CONTAINER_REF_FACTORY = SWITCH_VIEW_CONTAINER_REF_FACTORY__PRE_R3__;
20369
20370/**
20371 * @license
20372 * Copyright Google LLC All Rights Reserved.
20373 *
20374 * Use of this source code is governed by an MIT-style license that can be
20375 * found in the LICENSE file at https://angular.io/license
20376 */
20377function expressionChangedAfterItHasBeenCheckedError(context, oldValue, currValue, isFirstCheck) {
20378 let msg = `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '${oldValue}'. Current value: '${currValue}'.`;
20379 if (isFirstCheck) {
20380 msg +=
20381 ` It seems like the view has been created after its parent and its children have been dirty checked.` +
20382 ` Has it been created in a change detection hook ?`;
20383 }
20384 return viewDebugError(msg, context);
20385}
20386function viewWrappedDebugError(err, context) {
20387 if (!(err instanceof Error)) {
20388 // errors that are not Error instances don't have a stack,
20389 // so it is ok to wrap them into a new Error object...
20390 err = new Error(err.toString());
20391 }
20392 _addDebugContext(err, context);
20393 return err;
20394}
20395function viewDebugError(msg, context) {
20396 const err = new Error(msg);
20397 _addDebugContext(err, context);
20398 return err;
20399}
20400function _addDebugContext(err, context) {
20401 err[ERROR_DEBUG_CONTEXT] = context;
20402 err[ERROR_LOGGER] = context.logError.bind(context);
20403}
20404function isViewDebugError(err) {
20405 return !!getDebugContext(err);
20406}
20407function viewDestroyedError(action) {
20408 return new Error(`ViewDestroyedError: Attempt to use a destroyed view: ${action}`);
20409}
20410
20411/**
20412 * @license
20413 * Copyright Google LLC All Rights Reserved.
20414 *
20415 * Use of this source code is governed by an MIT-style license that can be
20416 * found in the LICENSE file at https://angular.io/license
20417 */
20418// Called before each cycle of a view's check to detect whether this is in the
20419// initState for which we need to call ngOnInit, ngAfterContentInit or ngAfterViewInit
20420// lifecycle methods. Returns true if this check cycle should call lifecycle
20421// methods.
20422function shiftInitState(view, priorInitState, newInitState) {
20423 // Only update the InitState if we are currently in the prior state.
20424 // For example, only move into CallingInit if we are in BeforeInit. Only
20425 // move into CallingContentInit if we are in CallingInit. Normally this will
20426 // always be true because of how checkCycle is called in checkAndUpdateView.
20427 // However, if checkAndUpdateView is called recursively or if an exception is
20428 // thrown while checkAndUpdateView is running, checkAndUpdateView starts over
20429 // from the beginning. This ensures the state is monotonically increasing,
20430 // terminating in the AfterInit state, which ensures the Init methods are called
20431 // at least once and only once.
20432 const state = view.state;
20433 const initState = state & 1792 /* InitState_Mask */;
20434 if (initState === priorInitState) {
20435 view.state = (state & ~1792 /* InitState_Mask */) | newInitState;
20436 view.initIndex = -1;
20437 return true;
20438 }
20439 return initState === newInitState;
20440}
20441// Returns true if the lifecycle init method should be called for the node with
20442// the given init index.
20443function shouldCallLifecycleInitHook(view, initState, index) {
20444 if ((view.state & 1792 /* InitState_Mask */) === initState && view.initIndex <= index) {
20445 view.initIndex = index + 1;
20446 return true;
20447 }
20448 return false;
20449}
20450/**
20451 * Node instance data.
20452 *
20453 * We have a separate type per NodeType to save memory
20454 * (TextData | ElementData | ProviderData | PureExpressionData | QueryList<any>)
20455 *
20456 * To keep our code monomorphic,
20457 * we prohibit using `NodeData` directly but enforce the use of accessors (`asElementData`, ...).
20458 * This way, no usage site can get a `NodeData` from view.nodes and then use it for different
20459 * purposes.
20460 */
20461class NodeData {
20462}
20463/**
20464 * Accessor for view.nodes, enforcing that every usage site stays monomorphic.
20465 */
20466function asTextData(view, index) {
20467 return view.nodes[index];
20468}
20469/**
20470 * Accessor for view.nodes, enforcing that every usage site stays monomorphic.
20471 */
20472function asElementData(view, index) {
20473 return view.nodes[index];
20474}
20475/**
20476 * Accessor for view.nodes, enforcing that every usage site stays monomorphic.
20477 */
20478function asProviderData(view, index) {
20479 return view.nodes[index];
20480}
20481/**
20482 * Accessor for view.nodes, enforcing that every usage site stays monomorphic.
20483 */
20484function asPureExpressionData(view, index) {
20485 return view.nodes[index];
20486}
20487/**
20488 * Accessor for view.nodes, enforcing that every usage site stays monomorphic.
20489 */
20490function asQueryList(view, index) {
20491 return view.nodes[index];
20492}
20493class DebugContext {
20494}
20495/**
20496 * This object is used to prevent cycles in the source files and to have a place where
20497 * debug mode can hook it. It is lazily filled when `isDevMode` is known.
20498 */
20499const Services = {
20500 setCurrentNode: undefined,
20501 createRootView: undefined,
20502 createEmbeddedView: undefined,
20503 createComponentView: undefined,
20504 createNgModuleRef: undefined,
20505 overrideProvider: undefined,
20506 overrideComponentView: undefined,
20507 clearOverrides: undefined,
20508 checkAndUpdateView: undefined,
20509 checkNoChangesView: undefined,
20510 destroyView: undefined,
20511 resolveDep: undefined,
20512 createDebugContext: undefined,
20513 handleEvent: undefined,
20514 updateDirectives: undefined,
20515 updateRenderer: undefined,
20516 dirtyParentQueries: undefined,
20517};
20518
20519/**
20520 * @license
20521 * Copyright Google LLC All Rights Reserved.
20522 *
20523 * Use of this source code is governed by an MIT-style license that can be
20524 * found in the LICENSE file at https://angular.io/license
20525 */
20526const NOOP = () => { };
20527const _tokenKeyCache = new Map();
20528function tokenKey(token) {
20529 let key = _tokenKeyCache.get(token);
20530 if (!key) {
20531 key = stringify(token) + '_' + _tokenKeyCache.size;
20532 _tokenKeyCache.set(token, key);
20533 }
20534 return key;
20535}
20536function unwrapValue(view, nodeIdx, bindingIdx, value) {
20537 if (WrappedValue.isWrapped(value)) {
20538 value = WrappedValue.unwrap(value);
20539 const globalBindingIdx = view.def.nodes[nodeIdx].bindingIndex + bindingIdx;
20540 const oldValue = WrappedValue.unwrap(view.oldValues[globalBindingIdx]);
20541 view.oldValues[globalBindingIdx] = new WrappedValue(oldValue);
20542 }
20543 return value;
20544}
20545const UNDEFINED_RENDERER_TYPE_ID = '$$undefined';
20546const EMPTY_RENDERER_TYPE_ID = '$$empty';
20547// Attention: this function is called as top level function.
20548// Putting any logic in here will destroy closure tree shaking!
20549function createRendererType2(values) {
20550 return {
20551 id: UNDEFINED_RENDERER_TYPE_ID,
20552 styles: values.styles,
20553 encapsulation: values.encapsulation,
20554 data: values.data
20555 };
20556}
20557let _renderCompCount$1 = 0;
20558function resolveRendererType2(type) {
20559 if (type && type.id === UNDEFINED_RENDERER_TYPE_ID) {
20560 // first time we see this RendererType2. Initialize it...
20561 const isFilled = ((type.encapsulation != null && type.encapsulation !== ViewEncapsulation$1.None) ||
20562 type.styles.length || Object.keys(type.data).length);
20563 if (isFilled) {
20564 type.id = `c${_renderCompCount$1++}`;
20565 }
20566 else {
20567 type.id = EMPTY_RENDERER_TYPE_ID;
20568 }
20569 }
20570 if (type && type.id === EMPTY_RENDERER_TYPE_ID) {
20571 type = null;
20572 }
20573 return type || null;
20574}
20575function checkBinding(view, def, bindingIdx, value) {
20576 const oldValues = view.oldValues;
20577 if ((view.state & 2 /* FirstCheck */) ||
20578 !Object.is(oldValues[def.bindingIndex + bindingIdx], value)) {
20579 return true;
20580 }
20581 return false;
20582}
20583function checkAndUpdateBinding(view, def, bindingIdx, value) {
20584 if (checkBinding(view, def, bindingIdx, value)) {
20585 view.oldValues[def.bindingIndex + bindingIdx] = value;
20586 return true;
20587 }
20588 return false;
20589}
20590function checkBindingNoChanges(view, def, bindingIdx, value) {
20591 const oldValue = view.oldValues[def.bindingIndex + bindingIdx];
20592 if ((view.state & 1 /* BeforeFirstCheck */) || !devModeEqual(oldValue, value)) {
20593 const bindingName = def.bindings[bindingIdx].name;
20594 throw expressionChangedAfterItHasBeenCheckedError(Services.createDebugContext(view, def.nodeIndex), `${bindingName}: ${oldValue}`, `${bindingName}: ${value}`, (view.state & 1 /* BeforeFirstCheck */) !== 0);
20595 }
20596}
20597function markParentViewsForCheck(view) {
20598 let currView = view;
20599 while (currView) {
20600 if (currView.def.flags & 2 /* OnPush */) {
20601 currView.state |= 8 /* ChecksEnabled */;
20602 }
20603 currView = currView.viewContainerParent || currView.parent;
20604 }
20605}
20606function markParentViewsForCheckProjectedViews(view, endView) {
20607 let currView = view;
20608 while (currView && currView !== endView) {
20609 currView.state |= 64 /* CheckProjectedViews */;
20610 currView = currView.viewContainerParent || currView.parent;
20611 }
20612}
20613function dispatchEvent(view, nodeIndex, eventName, event) {
20614 try {
20615 const nodeDef = view.def.nodes[nodeIndex];
20616 const startView = nodeDef.flags & 33554432 /* ComponentView */ ?
20617 asElementData(view, nodeIndex).componentView :
20618 view;
20619 markParentViewsForCheck(startView);
20620 return Services.handleEvent(view, nodeIndex, eventName, event);
20621 }
20622 catch (e) {
20623 // Attention: Don't rethrow, as it would cancel Observable subscriptions!
20624 view.root.errorHandler.handleError(e);
20625 }
20626}
20627function declaredViewContainer(view) {
20628 if (view.parent) {
20629 const parentView = view.parent;
20630 return asElementData(parentView, view.parentNodeDef.nodeIndex);
20631 }
20632 return null;
20633}
20634/**
20635 * for component views, this is the host element.
20636 * for embedded views, this is the index of the parent node
20637 * that contains the view container.
20638 */
20639function viewParentEl(view) {
20640 const parentView = view.parent;
20641 if (parentView) {
20642 return view.parentNodeDef.parent;
20643 }
20644 else {
20645 return null;
20646 }
20647}
20648function renderNode(view, def) {
20649 switch (def.flags & 201347067 /* Types */) {
20650 case 1 /* TypeElement */:
20651 return asElementData(view, def.nodeIndex).renderElement;
20652 case 2 /* TypeText */:
20653 return asTextData(view, def.nodeIndex).renderText;
20654 }
20655}
20656function elementEventFullName(target, name) {
20657 return target ? `${target}:${name}` : name;
20658}
20659function isComponentView(view) {
20660 return !!view.parent && !!(view.parentNodeDef.flags & 32768 /* Component */);
20661}
20662function isEmbeddedView(view) {
20663 return !!view.parent && !(view.parentNodeDef.flags & 32768 /* Component */);
20664}
20665function filterQueryId(queryId) {
20666 return 1 << (queryId % 32);
20667}
20668function splitMatchedQueriesDsl(matchedQueriesDsl) {
20669 const matchedQueries = {};
20670 let matchedQueryIds = 0;
20671 const references = {};
20672 if (matchedQueriesDsl) {
20673 matchedQueriesDsl.forEach(([queryId, valueType]) => {
20674 if (typeof queryId === 'number') {
20675 matchedQueries[queryId] = valueType;
20676 matchedQueryIds |= filterQueryId(queryId);
20677 }
20678 else {
20679 references[queryId] = valueType;
20680 }
20681 });
20682 }
20683 return { matchedQueries, references, matchedQueryIds };
20684}
20685function splitDepsDsl(deps, sourceName) {
20686 return deps.map(value => {
20687 let token;
20688 let flags;
20689 if (Array.isArray(value)) {
20690 [flags, token] = value;
20691 }
20692 else {
20693 flags = 0 /* None */;
20694 token = value;
20695 }
20696 if (token && (typeof token === 'function' || typeof token === 'object') && sourceName) {
20697 Object.defineProperty(token, SOURCE, { value: sourceName, configurable: true });
20698 }
20699 return { flags, token, tokenKey: tokenKey(token) };
20700 });
20701}
20702function getParentRenderElement(view, renderHost, def) {
20703 let renderParent = def.renderParent;
20704 if (renderParent) {
20705 if ((renderParent.flags & 1 /* TypeElement */) === 0 ||
20706 (renderParent.flags & 33554432 /* ComponentView */) === 0 ||
20707 (renderParent.element.componentRendererType &&
20708 renderParent.element.componentRendererType.encapsulation === ViewEncapsulation$1.Native)) {
20709 // only children of non components, or children of components with native encapsulation should
20710 // be attached.
20711 return asElementData(view, def.renderParent.nodeIndex).renderElement;
20712 }
20713 }
20714 else {
20715 return renderHost;
20716 }
20717}
20718const DEFINITION_CACHE = new WeakMap();
20719function resolveDefinition(factory) {
20720 let value = DEFINITION_CACHE.get(factory);
20721 if (!value) {
20722 value = factory(() => NOOP);
20723 value.factory = factory;
20724 DEFINITION_CACHE.set(factory, value);
20725 }
20726 return value;
20727}
20728function rootRenderNodes(view) {
20729 const renderNodes = [];
20730 visitRootRenderNodes(view, 0 /* Collect */, undefined, undefined, renderNodes);
20731 return renderNodes;
20732}
20733function visitRootRenderNodes(view, action, parentNode, nextSibling, target) {
20734 // We need to re-compute the parent node in case the nodes have been moved around manually
20735 if (action === 3 /* RemoveChild */) {
20736 parentNode = view.renderer.parentNode(renderNode(view, view.def.lastRenderRootNode));
20737 }
20738 visitSiblingRenderNodes(view, action, 0, view.def.nodes.length - 1, parentNode, nextSibling, target);
20739}
20740function visitSiblingRenderNodes(view, action, startIndex, endIndex, parentNode, nextSibling, target) {
20741 for (let i = startIndex; i <= endIndex; i++) {
20742 const nodeDef = view.def.nodes[i];
20743 if (nodeDef.flags & (1 /* TypeElement */ | 2 /* TypeText */ | 8 /* TypeNgContent */)) {
20744 visitRenderNode(view, nodeDef, action, parentNode, nextSibling, target);
20745 }
20746 // jump to next sibling
20747 i += nodeDef.childCount;
20748 }
20749}
20750function visitProjectedRenderNodes(view, ngContentIndex, action, parentNode, nextSibling, target) {
20751 let compView = view;
20752 while (compView && !isComponentView(compView)) {
20753 compView = compView.parent;
20754 }
20755 const hostView = compView.parent;
20756 const hostElDef = viewParentEl(compView);
20757 const startIndex = hostElDef.nodeIndex + 1;
20758 const endIndex = hostElDef.nodeIndex + hostElDef.childCount;
20759 for (let i = startIndex; i <= endIndex; i++) {
20760 const nodeDef = hostView.def.nodes[i];
20761 if (nodeDef.ngContentIndex === ngContentIndex) {
20762 visitRenderNode(hostView, nodeDef, action, parentNode, nextSibling, target);
20763 }
20764 // jump to next sibling
20765 i += nodeDef.childCount;
20766 }
20767 if (!hostView.parent) {
20768 // a root view
20769 const projectedNodes = view.root.projectableNodes[ngContentIndex];
20770 if (projectedNodes) {
20771 for (let i = 0; i < projectedNodes.length; i++) {
20772 execRenderNodeAction(view, projectedNodes[i], action, parentNode, nextSibling, target);
20773 }
20774 }
20775 }
20776}
20777function visitRenderNode(view, nodeDef, action, parentNode, nextSibling, target) {
20778 if (nodeDef.flags & 8 /* TypeNgContent */) {
20779 visitProjectedRenderNodes(view, nodeDef.ngContent.index, action, parentNode, nextSibling, target);
20780 }
20781 else {
20782 const rn = renderNode(view, nodeDef);
20783 if (action === 3 /* RemoveChild */ && (nodeDef.flags & 33554432 /* ComponentView */) &&
20784 (nodeDef.bindingFlags & 48 /* CatSyntheticProperty */)) {
20785 // Note: we might need to do both actions.
20786 if (nodeDef.bindingFlags & (16 /* SyntheticProperty */)) {
20787 execRenderNodeAction(view, rn, action, parentNode, nextSibling, target);
20788 }
20789 if (nodeDef.bindingFlags & (32 /* SyntheticHostProperty */)) {
20790 const compView = asElementData(view, nodeDef.nodeIndex).componentView;
20791 execRenderNodeAction(compView, rn, action, parentNode, nextSibling, target);
20792 }
20793 }
20794 else {
20795 execRenderNodeAction(view, rn, action, parentNode, nextSibling, target);
20796 }
20797 if (nodeDef.flags & 16777216 /* EmbeddedViews */) {
20798 const embeddedViews = asElementData(view, nodeDef.nodeIndex).viewContainer._embeddedViews;
20799 for (let k = 0; k < embeddedViews.length; k++) {
20800 visitRootRenderNodes(embeddedViews[k], action, parentNode, nextSibling, target);
20801 }
20802 }
20803 if (nodeDef.flags & 1 /* TypeElement */ && !nodeDef.element.name) {
20804 visitSiblingRenderNodes(view, action, nodeDef.nodeIndex + 1, nodeDef.nodeIndex + nodeDef.childCount, parentNode, nextSibling, target);
20805 }
20806 }
20807}
20808function execRenderNodeAction(view, renderNode, action, parentNode, nextSibling, target) {
20809 const renderer = view.renderer;
20810 switch (action) {
20811 case 1 /* AppendChild */:
20812 renderer.appendChild(parentNode, renderNode);
20813 break;
20814 case 2 /* InsertBefore */:
20815 renderer.insertBefore(parentNode, renderNode, nextSibling);
20816 break;
20817 case 3 /* RemoveChild */:
20818 renderer.removeChild(parentNode, renderNode);
20819 break;
20820 case 0 /* Collect */:
20821 target.push(renderNode);
20822 break;
20823 }
20824}
20825const NS_PREFIX_RE = /^:([^:]+):(.+)$/;
20826function splitNamespace(name) {
20827 if (name[0] === ':') {
20828 const match = name.match(NS_PREFIX_RE);
20829 return [match[1], match[2]];
20830 }
20831 return ['', name];
20832}
20833function calcBindingFlags(bindings) {
20834 let flags = 0;
20835 for (let i = 0; i < bindings.length; i++) {
20836 flags |= bindings[i].flags;
20837 }
20838 return flags;
20839}
20840function interpolate(valueCount, constAndInterp) {
20841 let result = '';
20842 for (let i = 0; i < valueCount * 2; i = i + 2) {
20843 result = result + constAndInterp[i] + _toStringWithNull(constAndInterp[i + 1]);
20844 }
20845 return result + constAndInterp[valueCount * 2];
20846}
20847function inlineInterpolate(valueCount, c0, a1, c1, a2, c2, a3, c3, a4, c4, a5, c5, a6, c6, a7, c7, a8, c8, a9, c9) {
20848 switch (valueCount) {
20849 case 1:
20850 return c0 + _toStringWithNull(a1) + c1;
20851 case 2:
20852 return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2;
20853 case 3:
20854 return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
20855 c3;
20856 case 4:
20857 return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
20858 c3 + _toStringWithNull(a4) + c4;
20859 case 5:
20860 return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
20861 c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5;
20862 case 6:
20863 return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
20864 c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) + c6;
20865 case 7:
20866 return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
20867 c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) +
20868 c6 + _toStringWithNull(a7) + c7;
20869 case 8:
20870 return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
20871 c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) +
20872 c6 + _toStringWithNull(a7) + c7 + _toStringWithNull(a8) + c8;
20873 case 9:
20874 return c0 + _toStringWithNull(a1) + c1 + _toStringWithNull(a2) + c2 + _toStringWithNull(a3) +
20875 c3 + _toStringWithNull(a4) + c4 + _toStringWithNull(a5) + c5 + _toStringWithNull(a6) +
20876 c6 + _toStringWithNull(a7) + c7 + _toStringWithNull(a8) + c8 + _toStringWithNull(a9) + c9;
20877 default:
20878 throw new Error(`Does not support more than 9 expressions`);
20879 }
20880}
20881function _toStringWithNull(v) {
20882 return v != null ? v.toString() : '';
20883}
20884const EMPTY_ARRAY$4 = [];
20885const EMPTY_MAP = {};
20886
20887/**
20888 * @license
20889 * Copyright Google LLC All Rights Reserved.
20890 *
20891 * Use of this source code is governed by an MIT-style license that can be
20892 * found in the LICENSE file at https://angular.io/license
20893 */
20894const UNDEFINED_VALUE = {};
20895const InjectorRefTokenKey = tokenKey(Injector);
20896const INJECTORRefTokenKey = tokenKey(INJECTOR);
20897const NgModuleRefTokenKey = tokenKey(NgModuleRef);
20898function moduleProvideDef(flags, token, value, deps) {
20899 // Need to resolve forwardRefs as e.g. for `useValue` we
20900 // lowered the expression and then stopped evaluating it,
20901 // i.e. also didn't unwrap it.
20902 value = resolveForwardRef(value);
20903 const depDefs = splitDepsDsl(deps, stringify(token));
20904 return {
20905 // will bet set by the module definition
20906 index: -1,
20907 deps: depDefs,
20908 flags,
20909 token,
20910 value
20911 };
20912}
20913function moduleDef(providers) {
20914 const providersByKey = {};
20915 const modules = [];
20916 let scope = null;
20917 for (let i = 0; i < providers.length; i++) {
20918 const provider = providers[i];
20919 if (provider.token === INJECTOR_SCOPE) {
20920 scope = provider.value;
20921 }
20922 if (provider.flags & 1073741824 /* TypeNgModule */) {
20923 modules.push(provider.token);
20924 }
20925 provider.index = i;
20926 providersByKey[tokenKey(provider.token)] = provider;
20927 }
20928 return {
20929 // Will be filled later...
20930 factory: null,
20931 providersByKey,
20932 providers,
20933 modules,
20934 scope: scope,
20935 };
20936}
20937function initNgModule(data) {
20938 const def = data._def;
20939 const providers = data._providers = newArray(def.providers.length);
20940 for (let i = 0; i < def.providers.length; i++) {
20941 const provDef = def.providers[i];
20942 if (!(provDef.flags & 4096 /* LazyProvider */)) {
20943 // Make sure the provider has not been already initialized outside this loop.
20944 if (providers[i] === undefined) {
20945 providers[i] = _createProviderInstance(data, provDef);
20946 }
20947 }
20948 }
20949}
20950function resolveNgModuleDep(data, depDef, notFoundValue = Injector.THROW_IF_NOT_FOUND) {
20951 const former = setCurrentInjector(data);
20952 try {
20953 if (depDef.flags & 8 /* Value */) {
20954 return depDef.token;
20955 }
20956 if (depDef.flags & 2 /* Optional */) {
20957 notFoundValue = null;
20958 }
20959 if (depDef.flags & 1 /* SkipSelf */) {
20960 return data._parent.get(depDef.token, notFoundValue);
20961 }
20962 const tokenKey = depDef.tokenKey;
20963 switch (tokenKey) {
20964 case InjectorRefTokenKey:
20965 case INJECTORRefTokenKey:
20966 case NgModuleRefTokenKey:
20967 return data;
20968 }
20969 const providerDef = data._def.providersByKey[tokenKey];
20970 let injectableDef;
20971 if (providerDef) {
20972 let providerInstance = data._providers[providerDef.index];
20973 if (providerInstance === undefined) {
20974 providerInstance = data._providers[providerDef.index] =
20975 _createProviderInstance(data, providerDef);
20976 }
20977 return providerInstance === UNDEFINED_VALUE ? undefined : providerInstance;
20978 }
20979 else if ((injectableDef = getInjectableDef(depDef.token)) && targetsModule(data, injectableDef)) {
20980 const index = data._providers.length;
20981 data._def.providers[index] = data._def.providersByKey[depDef.tokenKey] = {
20982 flags: 1024 /* TypeFactoryProvider */ | 4096 /* LazyProvider */,
20983 value: injectableDef.factory,
20984 deps: [],
20985 index,
20986 token: depDef.token,
20987 };
20988 data._providers[index] = UNDEFINED_VALUE;
20989 return (data._providers[index] =
20990 _createProviderInstance(data, data._def.providersByKey[depDef.tokenKey]));
20991 }
20992 else if (depDef.flags & 4 /* Self */) {
20993 return notFoundValue;
20994 }
20995 return data._parent.get(depDef.token, notFoundValue);
20996 }
20997 finally {
20998 setCurrentInjector(former);
20999 }
21000}
21001function moduleTransitivelyPresent(ngModule, scope) {
21002 return ngModule._def.modules.indexOf(scope) > -1;
21003}
21004function targetsModule(ngModule, def) {
21005 const providedIn = def.providedIn;
21006 return providedIn != null &&
21007 (providedIn === 'any' || providedIn === ngModule._def.scope ||
21008 moduleTransitivelyPresent(ngModule, providedIn));
21009}
21010function _createProviderInstance(ngModule, providerDef) {
21011 let injectable;
21012 switch (providerDef.flags & 201347067 /* Types */) {
21013 case 512 /* TypeClassProvider */:
21014 injectable = _createClass(ngModule, providerDef.value, providerDef.deps);
21015 break;
21016 case 1024 /* TypeFactoryProvider */:
21017 injectable = _callFactory(ngModule, providerDef.value, providerDef.deps);
21018 break;
21019 case 2048 /* TypeUseExistingProvider */:
21020 injectable = resolveNgModuleDep(ngModule, providerDef.deps[0]);
21021 break;
21022 case 256 /* TypeValueProvider */:
21023 injectable = providerDef.value;
21024 break;
21025 }
21026 // The read of `ngOnDestroy` here is slightly expensive as it's megamorphic, so it should be
21027 // avoided if possible. The sequence of checks here determines whether ngOnDestroy needs to be
21028 // checked. It might not if the `injectable` isn't an object or if NodeFlags.OnDestroy is already
21029 // set (ngOnDestroy was detected statically).
21030 if (injectable !== UNDEFINED_VALUE && injectable !== null && typeof injectable === 'object' &&
21031 !(providerDef.flags & 131072 /* OnDestroy */) && typeof injectable.ngOnDestroy === 'function') {
21032 providerDef.flags |= 131072 /* OnDestroy */;
21033 }
21034 return injectable === undefined ? UNDEFINED_VALUE : injectable;
21035}
21036function _createClass(ngModule, ctor, deps) {
21037 const len = deps.length;
21038 switch (len) {
21039 case 0:
21040 return new ctor();
21041 case 1:
21042 return new ctor(resolveNgModuleDep(ngModule, deps[0]));
21043 case 2:
21044 return new ctor(resolveNgModuleDep(ngModule, deps[0]), resolveNgModuleDep(ngModule, deps[1]));
21045 case 3:
21046 return new ctor(resolveNgModuleDep(ngModule, deps[0]), resolveNgModuleDep(ngModule, deps[1]), resolveNgModuleDep(ngModule, deps[2]));
21047 default:
21048 const depValues = [];
21049 for (let i = 0; i < len; i++) {
21050 depValues[i] = resolveNgModuleDep(ngModule, deps[i]);
21051 }
21052 return new ctor(...depValues);
21053 }
21054}
21055function _callFactory(ngModule, factory, deps) {
21056 const len = deps.length;
21057 switch (len) {
21058 case 0:
21059 return factory();
21060 case 1:
21061 return factory(resolveNgModuleDep(ngModule, deps[0]));
21062 case 2:
21063 return factory(resolveNgModuleDep(ngModule, deps[0]), resolveNgModuleDep(ngModule, deps[1]));
21064 case 3:
21065 return factory(resolveNgModuleDep(ngModule, deps[0]), resolveNgModuleDep(ngModule, deps[1]), resolveNgModuleDep(ngModule, deps[2]));
21066 default:
21067 const depValues = [];
21068 for (let i = 0; i < len; i++) {
21069 depValues[i] = resolveNgModuleDep(ngModule, deps[i]);
21070 }
21071 return factory(...depValues);
21072 }
21073}
21074function callNgModuleLifecycle(ngModule, lifecycles) {
21075 const def = ngModule._def;
21076 const destroyed = new Set();
21077 for (let i = 0; i < def.providers.length; i++) {
21078 const provDef = def.providers[i];
21079 if (provDef.flags & 131072 /* OnDestroy */) {
21080 const instance = ngModule._providers[i];
21081 if (instance && instance !== UNDEFINED_VALUE) {
21082 const onDestroy = instance.ngOnDestroy;
21083 if (typeof onDestroy === 'function' && !destroyed.has(instance)) {
21084 onDestroy.apply(instance);
21085 destroyed.add(instance);
21086 }
21087 }
21088 }
21089 }
21090}
21091
21092/**
21093 * @license
21094 * Copyright Google LLC All Rights Reserved.
21095 *
21096 * Use of this source code is governed by an MIT-style license that can be
21097 * found in the LICENSE file at https://angular.io/license
21098 */
21099function attachEmbeddedView(parentView, elementData, viewIndex, view) {
21100 let embeddedViews = elementData.viewContainer._embeddedViews;
21101 if (viewIndex === null || viewIndex === undefined) {
21102 viewIndex = embeddedViews.length;
21103 }
21104 view.viewContainerParent = parentView;
21105 addToArray(embeddedViews, viewIndex, view);
21106 attachProjectedView(elementData, view);
21107 Services.dirtyParentQueries(view);
21108 const prevView = viewIndex > 0 ? embeddedViews[viewIndex - 1] : null;
21109 renderAttachEmbeddedView(elementData, prevView, view);
21110}
21111function attachProjectedView(vcElementData, view) {
21112 const dvcElementData = declaredViewContainer(view);
21113 if (!dvcElementData || dvcElementData === vcElementData ||
21114 view.state & 16 /* IsProjectedView */) {
21115 return;
21116 }
21117 // Note: For performance reasons, we
21118 // - add a view to template._projectedViews only 1x throughout its lifetime,
21119 // and remove it not until the view is destroyed.
21120 // (hard, as when a parent view is attached/detached we would need to attach/detach all
21121 // nested projected views as well, even across component boundaries).
21122 // - don't track the insertion order of views in the projected views array
21123 // (hard, as when the views of the same template are inserted different view containers)
21124 view.state |= 16 /* IsProjectedView */;
21125 let projectedViews = dvcElementData.template._projectedViews;
21126 if (!projectedViews) {
21127 projectedViews = dvcElementData.template._projectedViews = [];
21128 }
21129 projectedViews.push(view);
21130 // Note: we are changing the NodeDef here as we cannot calculate
21131 // the fact whether a template is used for projection during compilation.
21132 markNodeAsProjectedTemplate(view.parent.def, view.parentNodeDef);
21133}
21134function markNodeAsProjectedTemplate(viewDef, nodeDef) {
21135 if (nodeDef.flags & 4 /* ProjectedTemplate */) {
21136 return;
21137 }
21138 viewDef.nodeFlags |= 4 /* ProjectedTemplate */;
21139 nodeDef.flags |= 4 /* ProjectedTemplate */;
21140 let parentNodeDef = nodeDef.parent;
21141 while (parentNodeDef) {
21142 parentNodeDef.childFlags |= 4 /* ProjectedTemplate */;
21143 parentNodeDef = parentNodeDef.parent;
21144 }
21145}
21146function detachEmbeddedView(elementData, viewIndex) {
21147 const embeddedViews = elementData.viewContainer._embeddedViews;
21148 if (viewIndex == null || viewIndex >= embeddedViews.length) {
21149 viewIndex = embeddedViews.length - 1;
21150 }
21151 if (viewIndex < 0) {
21152 return null;
21153 }
21154 const view = embeddedViews[viewIndex];
21155 view.viewContainerParent = null;
21156 removeFromArray(embeddedViews, viewIndex);
21157 // See attachProjectedView for why we don't update projectedViews here.
21158 Services.dirtyParentQueries(view);
21159 renderDetachView$1(view);
21160 return view;
21161}
21162function detachProjectedView(view) {
21163 if (!(view.state & 16 /* IsProjectedView */)) {
21164 return;
21165 }
21166 const dvcElementData = declaredViewContainer(view);
21167 if (dvcElementData) {
21168 const projectedViews = dvcElementData.template._projectedViews;
21169 if (projectedViews) {
21170 removeFromArray(projectedViews, projectedViews.indexOf(view));
21171 Services.dirtyParentQueries(view);
21172 }
21173 }
21174}
21175function moveEmbeddedView(elementData, oldViewIndex, newViewIndex) {
21176 const embeddedViews = elementData.viewContainer._embeddedViews;
21177 const view = embeddedViews[oldViewIndex];
21178 removeFromArray(embeddedViews, oldViewIndex);
21179 if (newViewIndex == null) {
21180 newViewIndex = embeddedViews.length;
21181 }
21182 addToArray(embeddedViews, newViewIndex, view);
21183 // Note: Don't need to change projectedViews as the order in there
21184 // as always invalid...
21185 Services.dirtyParentQueries(view);
21186 renderDetachView$1(view);
21187 const prevView = newViewIndex > 0 ? embeddedViews[newViewIndex - 1] : null;
21188 renderAttachEmbeddedView(elementData, prevView, view);
21189 return view;
21190}
21191function renderAttachEmbeddedView(elementData, prevView, view) {
21192 const prevRenderNode = prevView ? renderNode(prevView, prevView.def.lastRenderRootNode) : elementData.renderElement;
21193 const parentNode = view.renderer.parentNode(prevRenderNode);
21194 const nextSibling = view.renderer.nextSibling(prevRenderNode);
21195 // Note: We can't check if `nextSibling` is present, as on WebWorkers it will always be!
21196 // However, browsers automatically do `appendChild` when there is no `nextSibling`.
21197 visitRootRenderNodes(view, 2 /* InsertBefore */, parentNode, nextSibling, undefined);
21198}
21199function renderDetachView$1(view) {
21200 visitRootRenderNodes(view, 3 /* RemoveChild */, null, null, undefined);
21201}
21202
21203/**
21204 * @license
21205 * Copyright Google LLC All Rights Reserved.
21206 *
21207 * Use of this source code is governed by an MIT-style license that can be
21208 * found in the LICENSE file at https://angular.io/license
21209 */
21210const EMPTY_CONTEXT = {};
21211// Attention: this function is called as top level function.
21212// Putting any logic in here will destroy closure tree shaking!
21213function createComponentFactory(selector, componentType, viewDefFactory, inputs, outputs, ngContentSelectors) {
21214 return new ComponentFactory_(selector, componentType, viewDefFactory, inputs, outputs, ngContentSelectors);
21215}
21216function getComponentViewDefinitionFactory(componentFactory) {
21217 return componentFactory.viewDefFactory;
21218}
21219class ComponentFactory_ extends ComponentFactory {
21220 constructor(selector, componentType, viewDefFactory, _inputs, _outputs, ngContentSelectors) {
21221 // Attention: this ctor is called as top level function.
21222 // Putting any logic in here will destroy closure tree shaking!
21223 super();
21224 this.selector = selector;
21225 this.componentType = componentType;
21226 this._inputs = _inputs;
21227 this._outputs = _outputs;
21228 this.ngContentSelectors = ngContentSelectors;
21229 this.viewDefFactory = viewDefFactory;
21230 }
21231 get inputs() {
21232 const inputsArr = [];
21233 const inputs = this._inputs;
21234 for (let propName in inputs) {
21235 const templateName = inputs[propName];
21236 inputsArr.push({ propName, templateName });
21237 }
21238 return inputsArr;
21239 }
21240 get outputs() {
21241 const outputsArr = [];
21242 for (let propName in this._outputs) {
21243 const templateName = this._outputs[propName];
21244 outputsArr.push({ propName, templateName });
21245 }
21246 return outputsArr;
21247 }
21248 /**
21249 * Creates a new component.
21250 */
21251 create(injector, projectableNodes, rootSelectorOrNode, ngModule) {
21252 if (!ngModule) {
21253 throw new Error('ngModule should be provided');
21254 }
21255 const viewDef = resolveDefinition(this.viewDefFactory);
21256 const componentNodeIndex = viewDef.nodes[0].element.componentProvider.nodeIndex;
21257 const view = Services.createRootView(injector, projectableNodes || [], rootSelectorOrNode, viewDef, ngModule, EMPTY_CONTEXT);
21258 const component = asProviderData(view, componentNodeIndex).instance;
21259 if (rootSelectorOrNode) {
21260 view.renderer.setAttribute(asElementData(view, 0).renderElement, 'ng-version', VERSION.full);
21261 }
21262 return new ComponentRef_(view, new ViewRef_(view), component);
21263 }
21264}
21265class ComponentRef_ extends ComponentRef {
21266 constructor(_view, _viewRef, _component) {
21267 super();
21268 this._view = _view;
21269 this._viewRef = _viewRef;
21270 this._component = _component;
21271 this._elDef = this._view.def.nodes[0];
21272 this.hostView = _viewRef;
21273 this.changeDetectorRef = _viewRef;
21274 this.instance = _component;
21275 }
21276 get location() {
21277 return new ElementRef(asElementData(this._view, this._elDef.nodeIndex).renderElement);
21278 }
21279 get injector() {
21280 return new Injector_(this._view, this._elDef);
21281 }
21282 get componentType() {
21283 return this._component.constructor;
21284 }
21285 destroy() {
21286 this._viewRef.destroy();
21287 }
21288 onDestroy(callback) {
21289 this._viewRef.onDestroy(callback);
21290 }
21291}
21292function createViewContainerData(view, elDef, elData) {
21293 return new ViewContainerRef_(view, elDef, elData);
21294}
21295class ViewContainerRef_ {
21296 constructor(_view, _elDef, _data) {
21297 this._view = _view;
21298 this._elDef = _elDef;
21299 this._data = _data;
21300 /**
21301 * @internal
21302 */
21303 this._embeddedViews = [];
21304 }
21305 get element() {
21306 return new ElementRef(this._data.renderElement);
21307 }
21308 get injector() {
21309 return new Injector_(this._view, this._elDef);
21310 }
21311 /** @deprecated No replacement */
21312 get parentInjector() {
21313 let view = this._view;
21314 let elDef = this._elDef.parent;
21315 while (!elDef && view) {
21316 elDef = viewParentEl(view);
21317 view = view.parent;
21318 }
21319 return view ? new Injector_(view, elDef) : new Injector_(this._view, null);
21320 }
21321 clear() {
21322 const len = this._embeddedViews.length;
21323 for (let i = len - 1; i >= 0; i--) {
21324 const view = detachEmbeddedView(this._data, i);
21325 Services.destroyView(view);
21326 }
21327 }
21328 get(index) {
21329 const view = this._embeddedViews[index];
21330 if (view) {
21331 const ref = new ViewRef_(view);
21332 ref.attachToViewContainerRef(this);
21333 return ref;
21334 }
21335 return null;
21336 }
21337 get length() {
21338 return this._embeddedViews.length;
21339 }
21340 createEmbeddedView(templateRef, context, index) {
21341 const viewRef = templateRef.createEmbeddedView(context || {});
21342 this.insert(viewRef, index);
21343 return viewRef;
21344 }
21345 createComponent(componentFactory, index, injector, projectableNodes, ngModuleRef) {
21346 const contextInjector = injector || this.parentInjector;
21347 if (!ngModuleRef && !(componentFactory instanceof ComponentFactoryBoundToModule)) {
21348 ngModuleRef = contextInjector.get(NgModuleRef);
21349 }
21350 const componentRef = componentFactory.create(contextInjector, projectableNodes, undefined, ngModuleRef);
21351 this.insert(componentRef.hostView, index);
21352 return componentRef;
21353 }
21354 insert(viewRef, index) {
21355 if (viewRef.destroyed) {
21356 throw new Error('Cannot insert a destroyed View in a ViewContainer!');
21357 }
21358 const viewRef_ = viewRef;
21359 const viewData = viewRef_._view;
21360 attachEmbeddedView(this._view, this._data, index, viewData);
21361 viewRef_.attachToViewContainerRef(this);
21362 return viewRef;
21363 }
21364 move(viewRef, currentIndex) {
21365 if (viewRef.destroyed) {
21366 throw new Error('Cannot move a destroyed View in a ViewContainer!');
21367 }
21368 const previousIndex = this._embeddedViews.indexOf(viewRef._view);
21369 moveEmbeddedView(this._data, previousIndex, currentIndex);
21370 return viewRef;
21371 }
21372 indexOf(viewRef) {
21373 return this._embeddedViews.indexOf(viewRef._view);
21374 }
21375 remove(index) {
21376 const viewData = detachEmbeddedView(this._data, index);
21377 if (viewData) {
21378 Services.destroyView(viewData);
21379 }
21380 }
21381 detach(index) {
21382 const view = detachEmbeddedView(this._data, index);
21383 return view ? new ViewRef_(view) : null;
21384 }
21385}
21386function createChangeDetectorRef(view) {
21387 return new ViewRef_(view);
21388}
21389class ViewRef_ {
21390 constructor(_view) {
21391 this._view = _view;
21392 this._viewContainerRef = null;
21393 this._appRef = null;
21394 }
21395 get rootNodes() {
21396 return rootRenderNodes(this._view);
21397 }
21398 get context() {
21399 return this._view.context;
21400 }
21401 get destroyed() {
21402 return (this._view.state & 128 /* Destroyed */) !== 0;
21403 }
21404 markForCheck() {
21405 markParentViewsForCheck(this._view);
21406 }
21407 detach() {
21408 this._view.state &= ~4 /* Attached */;
21409 }
21410 detectChanges() {
21411 const fs = this._view.root.rendererFactory;
21412 if (fs.begin) {
21413 fs.begin();
21414 }
21415 try {
21416 Services.checkAndUpdateView(this._view);
21417 }
21418 finally {
21419 if (fs.end) {
21420 fs.end();
21421 }
21422 }
21423 }
21424 checkNoChanges() {
21425 Services.checkNoChangesView(this._view);
21426 }
21427 reattach() {
21428 this._view.state |= 4 /* Attached */;
21429 }
21430 onDestroy(callback) {
21431 if (!this._view.disposables) {
21432 this._view.disposables = [];
21433 }
21434 this._view.disposables.push(callback);
21435 }
21436 destroy() {
21437 if (this._appRef) {
21438 this._appRef.detachView(this);
21439 }
21440 else if (this._viewContainerRef) {
21441 this._viewContainerRef.detach(this._viewContainerRef.indexOf(this));
21442 }
21443 Services.destroyView(this._view);
21444 }
21445 detachFromAppRef() {
21446 this._appRef = null;
21447 renderDetachView$1(this._view);
21448 Services.dirtyParentQueries(this._view);
21449 }
21450 attachToAppRef(appRef) {
21451 if (this._viewContainerRef) {
21452 throw new Error('This view is already attached to a ViewContainer!');
21453 }
21454 this._appRef = appRef;
21455 }
21456 attachToViewContainerRef(vcRef) {
21457 if (this._appRef) {
21458 throw new Error('This view is already attached directly to the ApplicationRef!');
21459 }
21460 this._viewContainerRef = vcRef;
21461 }
21462}
21463function createTemplateData(view, def) {
21464 return new TemplateRef_(view, def);
21465}
21466class TemplateRef_ extends TemplateRef {
21467 constructor(_parentView, _def) {
21468 super();
21469 this._parentView = _parentView;
21470 this._def = _def;
21471 }
21472 createEmbeddedView(context) {
21473 return new ViewRef_(Services.createEmbeddedView(this._parentView, this._def, this._def.element.template, context));
21474 }
21475 get elementRef() {
21476 return new ElementRef(asElementData(this._parentView, this._def.nodeIndex).renderElement);
21477 }
21478}
21479function createInjector$1(view, elDef) {
21480 return new Injector_(view, elDef);
21481}
21482class Injector_ {
21483 constructor(view, elDef) {
21484 this.view = view;
21485 this.elDef = elDef;
21486 }
21487 get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND) {
21488 const allowPrivateServices = this.elDef ? (this.elDef.flags & 33554432 /* ComponentView */) !== 0 : false;
21489 return Services.resolveDep(this.view, this.elDef, allowPrivateServices, { flags: 0 /* None */, token, tokenKey: tokenKey(token) }, notFoundValue);
21490 }
21491}
21492function nodeValue(view, index) {
21493 const def = view.def.nodes[index];
21494 if (def.flags & 1 /* TypeElement */) {
21495 const elData = asElementData(view, def.nodeIndex);
21496 return def.element.template ? elData.template : elData.renderElement;
21497 }
21498 else if (def.flags & 2 /* TypeText */) {
21499 return asTextData(view, def.nodeIndex).renderText;
21500 }
21501 else if (def.flags & (20224 /* CatProvider */ | 16 /* TypePipe */)) {
21502 return asProviderData(view, def.nodeIndex).instance;
21503 }
21504 throw new Error(`Illegal state: read nodeValue for node index ${index}`);
21505}
21506function createNgModuleRef(moduleType, parent, bootstrapComponents, def) {
21507 return new NgModuleRef_(moduleType, parent, bootstrapComponents, def);
21508}
21509class NgModuleRef_ {
21510 constructor(_moduleType, _parent, _bootstrapComponents, _def) {
21511 this._moduleType = _moduleType;
21512 this._parent = _parent;
21513 this._bootstrapComponents = _bootstrapComponents;
21514 this._def = _def;
21515 this._destroyListeners = [];
21516 this._destroyed = false;
21517 this.injector = this;
21518 initNgModule(this);
21519 }
21520 get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND, injectFlags = InjectFlags.Default) {
21521 let flags = 0 /* None */;
21522 if (injectFlags & InjectFlags.SkipSelf) {
21523 flags |= 1 /* SkipSelf */;
21524 }
21525 else if (injectFlags & InjectFlags.Self) {
21526 flags |= 4 /* Self */;
21527 }
21528 return resolveNgModuleDep(this, { token: token, tokenKey: tokenKey(token), flags: flags }, notFoundValue);
21529 }
21530 get instance() {
21531 return this.get(this._moduleType);
21532 }
21533 get componentFactoryResolver() {
21534 return this.get(ComponentFactoryResolver);
21535 }
21536 destroy() {
21537 if (this._destroyed) {
21538 throw new Error(`The ng module ${stringify(this.instance.constructor)} has already been destroyed.`);
21539 }
21540 this._destroyed = true;
21541 callNgModuleLifecycle(this, 131072 /* OnDestroy */);
21542 this._destroyListeners.forEach((listener) => listener());
21543 }
21544 onDestroy(callback) {
21545 this._destroyListeners.push(callback);
21546 }
21547}
21548
21549/**
21550 * @license
21551 * Copyright Google LLC All Rights Reserved.
21552 *
21553 * Use of this source code is governed by an MIT-style license that can be
21554 * found in the LICENSE file at https://angular.io/license
21555 */
21556const Renderer2TokenKey = tokenKey(Renderer2);
21557const ElementRefTokenKey = tokenKey(ElementRef);
21558const ViewContainerRefTokenKey = tokenKey(ViewContainerRef);
21559const TemplateRefTokenKey = tokenKey(TemplateRef);
21560const ChangeDetectorRefTokenKey = tokenKey(ChangeDetectorRef);
21561const InjectorRefTokenKey$1 = tokenKey(Injector);
21562const INJECTORRefTokenKey$1 = tokenKey(INJECTOR);
21563function directiveDef(checkIndex, flags, matchedQueries, childCount, ctor, deps, props, outputs) {
21564 const bindings = [];
21565 if (props) {
21566 for (let prop in props) {
21567 const [bindingIndex, nonMinifiedName] = props[prop];
21568 bindings[bindingIndex] = {
21569 flags: 8 /* TypeProperty */,
21570 name: prop,
21571 nonMinifiedName,
21572 ns: null,
21573 securityContext: null,
21574 suffix: null
21575 };
21576 }
21577 }
21578 const outputDefs = [];
21579 if (outputs) {
21580 for (let propName in outputs) {
21581 outputDefs.push({ type: 1 /* DirectiveOutput */, propName, target: null, eventName: outputs[propName] });
21582 }
21583 }
21584 flags |= 16384 /* TypeDirective */;
21585 return _def(checkIndex, flags, matchedQueries, childCount, ctor, ctor, deps, bindings, outputDefs);
21586}
21587function pipeDef(flags, ctor, deps) {
21588 flags |= 16 /* TypePipe */;
21589 return _def(-1, flags, null, 0, ctor, ctor, deps);
21590}
21591function providerDef(flags, matchedQueries, token, value, deps) {
21592 return _def(-1, flags, matchedQueries, 0, token, value, deps);
21593}
21594function _def(checkIndex, flags, matchedQueriesDsl, childCount, token, value, deps, bindings, outputs) {
21595 const { matchedQueries, references, matchedQueryIds } = splitMatchedQueriesDsl(matchedQueriesDsl);
21596 if (!outputs) {
21597 outputs = [];
21598 }
21599 if (!bindings) {
21600 bindings = [];
21601 }
21602 // Need to resolve forwardRefs as e.g. for `useValue` we
21603 // lowered the expression and then stopped evaluating it,
21604 // i.e. also didn't unwrap it.
21605 value = resolveForwardRef(value);
21606 const depDefs = splitDepsDsl(deps, stringify(token));
21607 return {
21608 // will bet set by the view definition
21609 nodeIndex: -1,
21610 parent: null,
21611 renderParent: null,
21612 bindingIndex: -1,
21613 outputIndex: -1,
21614 // regular values
21615 checkIndex,
21616 flags,
21617 childFlags: 0,
21618 directChildFlags: 0,
21619 childMatchedQueries: 0,
21620 matchedQueries,
21621 matchedQueryIds,
21622 references,
21623 ngContentIndex: -1,
21624 childCount,
21625 bindings,
21626 bindingFlags: calcBindingFlags(bindings),
21627 outputs,
21628 element: null,
21629 provider: { token, value, deps: depDefs },
21630 text: null,
21631 query: null,
21632 ngContent: null
21633 };
21634}
21635function createProviderInstance(view, def) {
21636 return _createProviderInstance$1(view, def);
21637}
21638function createPipeInstance(view, def) {
21639 // deps are looked up from component.
21640 let compView = view;
21641 while (compView.parent && !isComponentView(compView)) {
21642 compView = compView.parent;
21643 }
21644 // pipes can see the private services of the component
21645 const allowPrivateServices = true;
21646 // pipes are always eager and classes!
21647 return createClass(compView.parent, viewParentEl(compView), allowPrivateServices, def.provider.value, def.provider.deps);
21648}
21649function createDirectiveInstance(view, def) {
21650 // components can see other private services, other directives can't.
21651 const allowPrivateServices = (def.flags & 32768 /* Component */) > 0;
21652 // directives are always eager and classes!
21653 const instance = createClass(view, def.parent, allowPrivateServices, def.provider.value, def.provider.deps);
21654 if (def.outputs.length) {
21655 for (let i = 0; i < def.outputs.length; i++) {
21656 const output = def.outputs[i];
21657 const outputObservable = instance[output.propName];
21658 if (isObservable(outputObservable)) {
21659 const subscription = outputObservable.subscribe(eventHandlerClosure(view, def.parent.nodeIndex, output.eventName));
21660 view.disposables[def.outputIndex + i] = subscription.unsubscribe.bind(subscription);
21661 }
21662 else {
21663 throw new Error(`@Output ${output.propName} not initialized in '${instance.constructor.name}'.`);
21664 }
21665 }
21666 }
21667 return instance;
21668}
21669function eventHandlerClosure(view, index, eventName) {
21670 return (event) => dispatchEvent(view, index, eventName, event);
21671}
21672function checkAndUpdateDirectiveInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
21673 const providerData = asProviderData(view, def.nodeIndex);
21674 const directive = providerData.instance;
21675 let changed = false;
21676 let changes = undefined;
21677 const bindLen = def.bindings.length;
21678 if (bindLen > 0 && checkBinding(view, def, 0, v0)) {
21679 changed = true;
21680 changes = updateProp(view, providerData, def, 0, v0, changes);
21681 }
21682 if (bindLen > 1 && checkBinding(view, def, 1, v1)) {
21683 changed = true;
21684 changes = updateProp(view, providerData, def, 1, v1, changes);
21685 }
21686 if (bindLen > 2 && checkBinding(view, def, 2, v2)) {
21687 changed = true;
21688 changes = updateProp(view, providerData, def, 2, v2, changes);
21689 }
21690 if (bindLen > 3 && checkBinding(view, def, 3, v3)) {
21691 changed = true;
21692 changes = updateProp(view, providerData, def, 3, v3, changes);
21693 }
21694 if (bindLen > 4 && checkBinding(view, def, 4, v4)) {
21695 changed = true;
21696 changes = updateProp(view, providerData, def, 4, v4, changes);
21697 }
21698 if (bindLen > 5 && checkBinding(view, def, 5, v5)) {
21699 changed = true;
21700 changes = updateProp(view, providerData, def, 5, v5, changes);
21701 }
21702 if (bindLen > 6 && checkBinding(view, def, 6, v6)) {
21703 changed = true;
21704 changes = updateProp(view, providerData, def, 6, v6, changes);
21705 }
21706 if (bindLen > 7 && checkBinding(view, def, 7, v7)) {
21707 changed = true;
21708 changes = updateProp(view, providerData, def, 7, v7, changes);
21709 }
21710 if (bindLen > 8 && checkBinding(view, def, 8, v8)) {
21711 changed = true;
21712 changes = updateProp(view, providerData, def, 8, v8, changes);
21713 }
21714 if (bindLen > 9 && checkBinding(view, def, 9, v9)) {
21715 changed = true;
21716 changes = updateProp(view, providerData, def, 9, v9, changes);
21717 }
21718 if (changes) {
21719 directive.ngOnChanges(changes);
21720 }
21721 if ((def.flags & 65536 /* OnInit */) &&
21722 shouldCallLifecycleInitHook(view, 256 /* InitState_CallingOnInit */, def.nodeIndex)) {
21723 directive.ngOnInit();
21724 }
21725 if (def.flags & 262144 /* DoCheck */) {
21726 directive.ngDoCheck();
21727 }
21728 return changed;
21729}
21730function checkAndUpdateDirectiveDynamic(view, def, values) {
21731 const providerData = asProviderData(view, def.nodeIndex);
21732 const directive = providerData.instance;
21733 let changed = false;
21734 let changes = undefined;
21735 for (let i = 0; i < values.length; i++) {
21736 if (checkBinding(view, def, i, values[i])) {
21737 changed = true;
21738 changes = updateProp(view, providerData, def, i, values[i], changes);
21739 }
21740 }
21741 if (changes) {
21742 directive.ngOnChanges(changes);
21743 }
21744 if ((def.flags & 65536 /* OnInit */) &&
21745 shouldCallLifecycleInitHook(view, 256 /* InitState_CallingOnInit */, def.nodeIndex)) {
21746 directive.ngOnInit();
21747 }
21748 if (def.flags & 262144 /* DoCheck */) {
21749 directive.ngDoCheck();
21750 }
21751 return changed;
21752}
21753function _createProviderInstance$1(view, def) {
21754 // private services can see other private services
21755 const allowPrivateServices = (def.flags & 8192 /* PrivateProvider */) > 0;
21756 const providerDef = def.provider;
21757 switch (def.flags & 201347067 /* Types */) {
21758 case 512 /* TypeClassProvider */:
21759 return createClass(view, def.parent, allowPrivateServices, providerDef.value, providerDef.deps);
21760 case 1024 /* TypeFactoryProvider */:
21761 return callFactory(view, def.parent, allowPrivateServices, providerDef.value, providerDef.deps);
21762 case 2048 /* TypeUseExistingProvider */:
21763 return resolveDep(view, def.parent, allowPrivateServices, providerDef.deps[0]);
21764 case 256 /* TypeValueProvider */:
21765 return providerDef.value;
21766 }
21767}
21768function createClass(view, elDef, allowPrivateServices, ctor, deps) {
21769 const len = deps.length;
21770 switch (len) {
21771 case 0:
21772 return new ctor();
21773 case 1:
21774 return new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0]));
21775 case 2:
21776 return new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]));
21777 case 3:
21778 return new ctor(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]), resolveDep(view, elDef, allowPrivateServices, deps[2]));
21779 default:
21780 const depValues = [];
21781 for (let i = 0; i < len; i++) {
21782 depValues.push(resolveDep(view, elDef, allowPrivateServices, deps[i]));
21783 }
21784 return new ctor(...depValues);
21785 }
21786}
21787function callFactory(view, elDef, allowPrivateServices, factory, deps) {
21788 const len = deps.length;
21789 switch (len) {
21790 case 0:
21791 return factory();
21792 case 1:
21793 return factory(resolveDep(view, elDef, allowPrivateServices, deps[0]));
21794 case 2:
21795 return factory(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]));
21796 case 3:
21797 return factory(resolveDep(view, elDef, allowPrivateServices, deps[0]), resolveDep(view, elDef, allowPrivateServices, deps[1]), resolveDep(view, elDef, allowPrivateServices, deps[2]));
21798 default:
21799 const depValues = [];
21800 for (let i = 0; i < len; i++) {
21801 depValues.push(resolveDep(view, elDef, allowPrivateServices, deps[i]));
21802 }
21803 return factory(...depValues);
21804 }
21805}
21806// This default value is when checking the hierarchy for a token.
21807//
21808// It means both:
21809// - the token is not provided by the current injector,
21810// - only the element injectors should be checked (ie do not check module injectors
21811//
21812// mod1
21813// /
21814// el1 mod2
21815// \ /
21816// el2
21817//
21818// When requesting el2.injector.get(token), we should check in the following order and return the
21819// first found value:
21820// - el2.injector.get(token, default)
21821// - el1.injector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) -> do not check the module
21822// - mod2.injector.get(token, default)
21823const NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR = {};
21824function resolveDep(view, elDef, allowPrivateServices, depDef, notFoundValue = Injector.THROW_IF_NOT_FOUND) {
21825 if (depDef.flags & 8 /* Value */) {
21826 return depDef.token;
21827 }
21828 const startView = view;
21829 if (depDef.flags & 2 /* Optional */) {
21830 notFoundValue = null;
21831 }
21832 const tokenKey = depDef.tokenKey;
21833 if (tokenKey === ChangeDetectorRefTokenKey) {
21834 // directives on the same element as a component should be able to control the change detector
21835 // of that component as well.
21836 allowPrivateServices = !!(elDef && elDef.element.componentView);
21837 }
21838 if (elDef && (depDef.flags & 1 /* SkipSelf */)) {
21839 allowPrivateServices = false;
21840 elDef = elDef.parent;
21841 }
21842 let searchView = view;
21843 while (searchView) {
21844 if (elDef) {
21845 switch (tokenKey) {
21846 case Renderer2TokenKey: {
21847 const compView = findCompView(searchView, elDef, allowPrivateServices);
21848 return compView.renderer;
21849 }
21850 case ElementRefTokenKey:
21851 return new ElementRef(asElementData(searchView, elDef.nodeIndex).renderElement);
21852 case ViewContainerRefTokenKey:
21853 return asElementData(searchView, elDef.nodeIndex).viewContainer;
21854 case TemplateRefTokenKey: {
21855 if (elDef.element.template) {
21856 return asElementData(searchView, elDef.nodeIndex).template;
21857 }
21858 break;
21859 }
21860 case ChangeDetectorRefTokenKey: {
21861 let cdView = findCompView(searchView, elDef, allowPrivateServices);
21862 return createChangeDetectorRef(cdView);
21863 }
21864 case InjectorRefTokenKey$1:
21865 case INJECTORRefTokenKey$1:
21866 return createInjector$1(searchView, elDef);
21867 default:
21868 const providerDef = (allowPrivateServices ? elDef.element.allProviders :
21869 elDef.element.publicProviders)[tokenKey];
21870 if (providerDef) {
21871 let providerData = asProviderData(searchView, providerDef.nodeIndex);
21872 if (!providerData) {
21873 providerData = { instance: _createProviderInstance$1(searchView, providerDef) };
21874 searchView.nodes[providerDef.nodeIndex] = providerData;
21875 }
21876 return providerData.instance;
21877 }
21878 }
21879 }
21880 allowPrivateServices = isComponentView(searchView);
21881 elDef = viewParentEl(searchView);
21882 searchView = searchView.parent;
21883 if (depDef.flags & 4 /* Self */) {
21884 searchView = null;
21885 }
21886 }
21887 const value = startView.root.injector.get(depDef.token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR);
21888 if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR ||
21889 notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) {
21890 // Return the value from the root element injector when
21891 // - it provides it
21892 // (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
21893 // - the module injector should not be checked
21894 // (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
21895 return value;
21896 }
21897 return startView.root.ngModule.injector.get(depDef.token, notFoundValue);
21898}
21899function findCompView(view, elDef, allowPrivateServices) {
21900 let compView;
21901 if (allowPrivateServices) {
21902 compView = asElementData(view, elDef.nodeIndex).componentView;
21903 }
21904 else {
21905 compView = view;
21906 while (compView.parent && !isComponentView(compView)) {
21907 compView = compView.parent;
21908 }
21909 }
21910 return compView;
21911}
21912function updateProp(view, providerData, def, bindingIdx, value, changes) {
21913 if (def.flags & 32768 /* Component */) {
21914 const compView = asElementData(view, def.parent.nodeIndex).componentView;
21915 if (compView.def.flags & 2 /* OnPush */) {
21916 compView.state |= 8 /* ChecksEnabled */;
21917 }
21918 }
21919 const binding = def.bindings[bindingIdx];
21920 const propName = binding.name;
21921 // Note: This is still safe with Closure Compiler as
21922 // the user passed in the property name as an object has to `providerDef`,
21923 // so Closure Compiler will have renamed the property correctly already.
21924 providerData.instance[propName] = value;
21925 if (def.flags & 524288 /* OnChanges */) {
21926 changes = changes || {};
21927 const oldValue = WrappedValue.unwrap(view.oldValues[def.bindingIndex + bindingIdx]);
21928 const binding = def.bindings[bindingIdx];
21929 changes[binding.nonMinifiedName] =
21930 new SimpleChange(oldValue, value, (view.state & 2 /* FirstCheck */) !== 0);
21931 }
21932 view.oldValues[def.bindingIndex + bindingIdx] = value;
21933 return changes;
21934}
21935// This function calls the ngAfterContentCheck, ngAfterContentInit,
21936// ngAfterViewCheck, and ngAfterViewInit lifecycle hooks (depending on the node
21937// flags in lifecycle). Unlike ngDoCheck, ngOnChanges and ngOnInit, which are
21938// called during a pre-order traversal of the view tree (that is calling the
21939// parent hooks before the child hooks) these events are sent in using a
21940// post-order traversal of the tree (children before parents). This changes the
21941// meaning of initIndex in the view state. For ngOnInit, initIndex tracks the
21942// expected nodeIndex which a ngOnInit should be called. When sending
21943// ngAfterContentInit and ngAfterViewInit it is the expected count of
21944// ngAfterContentInit or ngAfterViewInit methods that have been called. This
21945// ensure that despite being called recursively or after picking up after an
21946// exception, the ngAfterContentInit or ngAfterViewInit will be called on the
21947// correct nodes. Consider for example, the following (where E is an element
21948// and D is a directive)
21949// Tree: pre-order index post-order index
21950// E1 0 6
21951// E2 1 1
21952// D3 2 0
21953// E4 3 5
21954// E5 4 4
21955// E6 5 2
21956// E7 6 3
21957// As can be seen, the post-order index has an unclear relationship to the
21958// pre-order index (postOrderIndex === preOrderIndex - parentCount +
21959// childCount). Since number of calls to ngAfterContentInit and ngAfterViewInit
21960// are stable (will be the same for the same view regardless of exceptions or
21961// recursion) we just need to count them which will roughly correspond to the
21962// post-order index (it skips elements and directives that do not have
21963// lifecycle hooks).
21964//
21965// For example, if an exception is raised in the E6.onAfterViewInit() the
21966// initIndex is left at 3 (by shouldCallLifecycleInitHook() which set it to
21967// initIndex + 1). When checkAndUpdateView() is called again D3, E2 and E6 will
21968// not have their ngAfterViewInit() called but, starting with E7, the rest of
21969// the view will begin getting ngAfterViewInit() called until a check and
21970// pass is complete.
21971//
21972// This algorthim also handles recursion. Consider if E4's ngAfterViewInit()
21973// indirectly calls E1's ChangeDetectorRef.detectChanges(). The expected
21974// initIndex is set to 6, the recusive checkAndUpdateView() starts walk again.
21975// D3, E2, E6, E7, E5 and E4 are skipped, ngAfterViewInit() is called on E1.
21976// When the recursion returns the initIndex will be 7 so E1 is skipped as it
21977// has already been called in the recursively called checkAnUpdateView().
21978function callLifecycleHooksChildrenFirst(view, lifecycles) {
21979 if (!(view.def.nodeFlags & lifecycles)) {
21980 return;
21981 }
21982 const nodes = view.def.nodes;
21983 let initIndex = 0;
21984 for (let i = 0; i < nodes.length; i++) {
21985 const nodeDef = nodes[i];
21986 let parent = nodeDef.parent;
21987 if (!parent && nodeDef.flags & lifecycles) {
21988 // matching root node (e.g. a pipe)
21989 callProviderLifecycles(view, i, nodeDef.flags & lifecycles, initIndex++);
21990 }
21991 if ((nodeDef.childFlags & lifecycles) === 0) {
21992 // no child matches one of the lifecycles
21993 i += nodeDef.childCount;
21994 }
21995 while (parent && (parent.flags & 1 /* TypeElement */) &&
21996 i === parent.nodeIndex + parent.childCount) {
21997 // last child of an element
21998 if (parent.directChildFlags & lifecycles) {
21999 initIndex = callElementProvidersLifecycles(view, parent, lifecycles, initIndex);
22000 }
22001 parent = parent.parent;
22002 }
22003 }
22004}
22005function callElementProvidersLifecycles(view, elDef, lifecycles, initIndex) {
22006 for (let i = elDef.nodeIndex + 1; i <= elDef.nodeIndex + elDef.childCount; i++) {
22007 const nodeDef = view.def.nodes[i];
22008 if (nodeDef.flags & lifecycles) {
22009 callProviderLifecycles(view, i, nodeDef.flags & lifecycles, initIndex++);
22010 }
22011 // only visit direct children
22012 i += nodeDef.childCount;
22013 }
22014 return initIndex;
22015}
22016function callProviderLifecycles(view, index, lifecycles, initIndex) {
22017 const providerData = asProviderData(view, index);
22018 if (!providerData) {
22019 return;
22020 }
22021 const provider = providerData.instance;
22022 if (!provider) {
22023 return;
22024 }
22025 Services.setCurrentNode(view, index);
22026 if (lifecycles & 1048576 /* AfterContentInit */ &&
22027 shouldCallLifecycleInitHook(view, 512 /* InitState_CallingAfterContentInit */, initIndex)) {
22028 provider.ngAfterContentInit();
22029 }
22030 if (lifecycles & 2097152 /* AfterContentChecked */) {
22031 provider.ngAfterContentChecked();
22032 }
22033 if (lifecycles & 4194304 /* AfterViewInit */ &&
22034 shouldCallLifecycleInitHook(view, 768 /* InitState_CallingAfterViewInit */, initIndex)) {
22035 provider.ngAfterViewInit();
22036 }
22037 if (lifecycles & 8388608 /* AfterViewChecked */) {
22038 provider.ngAfterViewChecked();
22039 }
22040 if (lifecycles & 131072 /* OnDestroy */) {
22041 provider.ngOnDestroy();
22042 }
22043}
22044
22045/**
22046 * @license
22047 * Copyright Google LLC All Rights Reserved.
22048 *
22049 * Use of this source code is governed by an MIT-style license that can be
22050 * found in the LICENSE file at https://angular.io/license
22051 */
22052class ComponentFactoryResolver$1 extends ComponentFactoryResolver {
22053 /**
22054 * @param ngModule The NgModuleRef to which all resolved factories are bound.
22055 */
22056 constructor(ngModule) {
22057 super();
22058 this.ngModule = ngModule;
22059 }
22060 resolveComponentFactory(component) {
22061 ngDevMode && assertComponentType(component);
22062 const componentDef = getComponentDef(component);
22063 return new ComponentFactory$1(componentDef, this.ngModule);
22064 }
22065}
22066function toRefArray(map) {
22067 const array = [];
22068 for (let nonMinified in map) {
22069 if (map.hasOwnProperty(nonMinified)) {
22070 const minified = map[nonMinified];
22071 array.push({ propName: minified, templateName: nonMinified });
22072 }
22073 }
22074 return array;
22075}
22076function getNamespace$1(elementName) {
22077 const name = elementName.toLowerCase();
22078 return name === 'svg' ? SVG_NAMESPACE : (name === 'math' ? MATH_ML_NAMESPACE : null);
22079}
22080/**
22081 * A change detection scheduler token for {@link RootContext}. This token is the default value used
22082 * for the default `RootContext` found in the {@link ROOT_CONTEXT} token.
22083 */
22084const SCHEDULER = new InjectionToken('SCHEDULER_TOKEN', {
22085 providedIn: 'root',
22086 factory: () => defaultScheduler,
22087});
22088function createChainedInjector(rootViewInjector, moduleInjector) {
22089 return {
22090 get: (token, notFoundValue, flags) => {
22091 const value = rootViewInjector.get(token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR, flags);
22092 if (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR ||
22093 notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) {
22094 // Return the value from the root element injector when
22095 // - it provides it
22096 // (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
22097 // - the module injector should not be checked
22098 // (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR)
22099 return value;
22100 }
22101 return moduleInjector.get(token, notFoundValue, flags);
22102 }
22103 };
22104}
22105/**
22106 * Render3 implementation of {@link viewEngine_ComponentFactory}.
22107 */
22108class ComponentFactory$1 extends ComponentFactory {
22109 /**
22110 * @param componentDef The component definition.
22111 * @param ngModule The NgModuleRef to which the factory is bound.
22112 */
22113 constructor(componentDef, ngModule) {
22114 super();
22115 this.componentDef = componentDef;
22116 this.ngModule = ngModule;
22117 this.componentType = componentDef.type;
22118 this.selector = stringifyCSSSelectorList(componentDef.selectors);
22119 this.ngContentSelectors =
22120 componentDef.ngContentSelectors ? componentDef.ngContentSelectors : [];
22121 this.isBoundToModule = !!ngModule;
22122 }
22123 get inputs() {
22124 return toRefArray(this.componentDef.inputs);
22125 }
22126 get outputs() {
22127 return toRefArray(this.componentDef.outputs);
22128 }
22129 create(injector, projectableNodes, rootSelectorOrNode, ngModule) {
22130 ngModule = ngModule || this.ngModule;
22131 const rootViewInjector = ngModule ? createChainedInjector(injector, ngModule.injector) : injector;
22132 const rendererFactory = rootViewInjector.get(RendererFactory2, domRendererFactory3);
22133 const sanitizer = rootViewInjector.get(Sanitizer, null);
22134 const hostRenderer = rendererFactory.createRenderer(null, this.componentDef);
22135 // Determine a tag name used for creating host elements when this component is created
22136 // dynamically. Default to 'div' if this component did not specify any tag name in its selector.
22137 const elementName = this.componentDef.selectors[0][0] || 'div';
22138 const hostRNode = rootSelectorOrNode ?
22139 locateHostElement(hostRenderer, rootSelectorOrNode, this.componentDef.encapsulation) :
22140 elementCreate(elementName, rendererFactory.createRenderer(null, this.componentDef), getNamespace$1(elementName));
22141 const rootFlags = this.componentDef.onPush ? 64 /* Dirty */ | 512 /* IsRoot */ :
22142 16 /* CheckAlways */ | 512 /* IsRoot */;
22143 const rootContext = createRootContext();
22144 // Create the root view. Uses empty TView and ContentTemplate.
22145 const rootTView = createTView(0 /* Root */, -1, null, 1, 0, null, null, null, null, null);
22146 const rootLView = createLView(null, rootTView, rootContext, rootFlags, null, null, rendererFactory, hostRenderer, sanitizer, rootViewInjector);
22147 // rootView is the parent when bootstrapping
22148 // TODO(misko): it looks like we are entering view here but we don't really need to as
22149 // `renderView` does that. However as the code is written it is needed because
22150 // `createRootComponentView` and `createRootComponent` both read global state. Fixing those
22151 // issues would allow us to drop this.
22152 enterView(rootLView, null);
22153 let component;
22154 let tElementNode;
22155 try {
22156 const componentView = createRootComponentView(hostRNode, this.componentDef, rootLView, rendererFactory, hostRenderer);
22157 if (hostRNode) {
22158 if (rootSelectorOrNode) {
22159 setUpAttributes(hostRenderer, hostRNode, ['ng-version', VERSION.full]);
22160 }
22161 else {
22162 // If host element is created as a part of this function call (i.e. `rootSelectorOrNode`
22163 // is not defined), also apply attributes and classes extracted from component selector.
22164 // Extract attributes and classes from the first selector only to match VE behavior.
22165 const { attrs, classes } = extractAttrsAndClassesFromSelector(this.componentDef.selectors[0]);
22166 if (attrs) {
22167 setUpAttributes(hostRenderer, hostRNode, attrs);
22168 }
22169 if (classes && classes.length > 0) {
22170 writeDirectClass(hostRenderer, hostRNode, classes.join(' '));
22171 }
22172 }
22173 }
22174 tElementNode = getTNode(rootTView, 0);
22175 if (projectableNodes !== undefined) {
22176 const projection = tElementNode.projection = [];
22177 for (let i = 0; i < this.ngContentSelectors.length; i++) {
22178 const nodesforSlot = projectableNodes[i];
22179 // Projectable nodes can be passed as array of arrays or an array of iterables (ngUpgrade
22180 // case). Here we do normalize passed data structure to be an array of arrays to avoid
22181 // complex checks down the line.
22182 // We also normalize the length of the passed in projectable nodes (to match the number of
22183 // <ng-container> slots defined by a component).
22184 projection.push(nodesforSlot != null ? Array.from(nodesforSlot) : null);
22185 }
22186 }
22187 // TODO: should LifecycleHooksFeature and other host features be generated by the compiler and
22188 // executed here?
22189 // Angular 5 reference: https://stackblitz.com/edit/lifecycle-hooks-vcref
22190 component = createRootComponent(componentView, this.componentDef, rootLView, rootContext, [LifecycleHooksFeature]);
22191 renderView(rootTView, rootLView, null);
22192 }
22193 finally {
22194 leaveView();
22195 }
22196 const componentRef = new ComponentRef$1(this.componentType, component, createElementRef(ElementRef, tElementNode, rootLView), rootLView, tElementNode);
22197 // The host element of the internal root view is attached to the component's host view node.
22198 ngDevMode && assertNodeOfPossibleTypes(rootTView.node, [2 /* View */]);
22199 rootTView.node.child = tElementNode;
22200 return componentRef;
22201 }
22202}
22203const componentFactoryResolver = new ComponentFactoryResolver$1();
22204/**
22205 * Creates a ComponentFactoryResolver and stores it on the injector. Or, if the
22206 * ComponentFactoryResolver
22207 * already exists, retrieves the existing ComponentFactoryResolver.
22208 *
22209 * @returns The ComponentFactoryResolver instance to use
22210 */
22211function injectComponentFactoryResolver() {
22212 return componentFactoryResolver;
22213}
22214/**
22215 * Represents an instance of a Component created via a {@link ComponentFactory}.
22216 *
22217 * `ComponentRef` provides access to the Component Instance as well other objects related to this
22218 * Component Instance and allows you to destroy the Component Instance via the {@link #destroy}
22219 * method.
22220 *
22221 */
22222class ComponentRef$1 extends ComponentRef {
22223 constructor(componentType, instance, location, _rootLView, _tNode) {
22224 super();
22225 this.location = location;
22226 this._rootLView = _rootLView;
22227 this._tNode = _tNode;
22228 this.destroyCbs = [];
22229 this.instance = instance;
22230 this.hostView = this.changeDetectorRef = new RootViewRef(_rootLView);
22231 assignTViewNodeToLView(_rootLView[TVIEW], null, -1, _rootLView);
22232 this.componentType = componentType;
22233 }
22234 get injector() {
22235 return new NodeInjector(this._tNode, this._rootLView);
22236 }
22237 destroy() {
22238 if (this.destroyCbs) {
22239 this.destroyCbs.forEach(fn => fn());
22240 this.destroyCbs = null;
22241 !this.hostView.destroyed && this.hostView.destroy();
22242 }
22243 }
22244 onDestroy(callback) {
22245 if (this.destroyCbs) {
22246 this.destroyCbs.push(callback);
22247 }
22248 }
22249}
22250
22251/**
22252 * @license
22253 * Copyright Google LLC All Rights Reserved.
22254 *
22255 * Use of this source code is governed by an MIT-style license that can be
22256 * found in the LICENSE file at https://angular.io/license
22257 */
22258// THIS CODE IS GENERATED - DO NOT MODIFY
22259// See angular/tools/gulp-tasks/cldr/extract.js
22260const u = undefined;
22261function plural(n) {
22262 let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
22263 if (i === 1 && v === 0)
22264 return 1;
22265 return 5;
22266}
22267var localeEn = [
22268 'en',
22269 [['a', 'p'], ['AM', 'PM'], u],
22270 [['AM', 'PM'], u, u],
22271 [
22272 ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
22273 ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
22274 ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
22275 ],
22276 u,
22277 [
22278 ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
22279 ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
22280 [
22281 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
22282 'October', 'November', 'December'
22283 ]
22284 ],
22285 u,
22286 [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']],
22287 0,
22288 [6, 0],
22289 ['M/d/yy', 'MMM d, y', 'MMMM d, y', 'EEEE, MMMM d, y'],
22290 ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
22291 ['{1}, {0}', u, '{1} \'at\' {0}', u],
22292 ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
22293 ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'],
22294 'USD',
22295 '$',
22296 'US Dollar',
22297 {},
22298 'ltr',
22299 plural
22300];
22301
22302/**
22303 * @license
22304 * Copyright Google LLC All Rights Reserved.
22305 *
22306 * Use of this source code is governed by an MIT-style license that can be
22307 * found in the LICENSE file at https://angular.io/license
22308 */
22309/**
22310 * This const is used to store the locale data registered with `registerLocaleData`
22311 */
22312let LOCALE_DATA = {};
22313/**
22314 * Register locale data to be used internally by Angular. See the
22315 * ["I18n guide"](guide/i18n#i18n-pipes) to know how to import additional locale data.
22316 *
22317 * The signature `registerLocaleData(data: any, extraData?: any)` is deprecated since v5.1
22318 */
22319function registerLocaleData(data, localeId, extraData) {
22320 if (typeof localeId !== 'string') {
22321 extraData = localeId;
22322 localeId = data[LocaleDataIndex.LocaleId];
22323 }
22324 localeId = localeId.toLowerCase().replace(/_/g, '-');
22325 LOCALE_DATA[localeId] = data;
22326 if (extraData) {
22327 LOCALE_DATA[localeId][LocaleDataIndex.ExtraData] = extraData;
22328 }
22329}
22330/**
22331 * Finds the locale data for a given locale.
22332 *
22333 * @param locale The locale code.
22334 * @returns The locale data.
22335 * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
22336 */
22337function findLocaleData(locale) {
22338 const normalizedLocale = normalizeLocale(locale);
22339 let match = getLocaleData(normalizedLocale);
22340 if (match) {
22341 return match;
22342 }
22343 // let's try to find a parent locale
22344 const parentLocale = normalizedLocale.split('-')[0];
22345 match = getLocaleData(parentLocale);
22346 if (match) {
22347 return match;
22348 }
22349 if (parentLocale === 'en') {
22350 return localeEn;
22351 }
22352 throw new Error(`Missing locale data for the locale "${locale}".`);
22353}
22354/**
22355 * Retrieves the default currency code for the given locale.
22356 *
22357 * The default is defined as the first currency which is still in use.
22358 *
22359 * @param locale The code of the locale whose currency code we want.
22360 * @returns The code of the default currency for the given locale.
22361 *
22362 */
22363function getLocaleCurrencyCode(locale) {
22364 const data = findLocaleData(locale);
22365 return data[LocaleDataIndex.CurrencyCode] || null;
22366}
22367/**
22368 * Retrieves the plural function used by ICU expressions to determine the plural case to use
22369 * for a given locale.
22370 * @param locale A locale code for the locale format rules to use.
22371 * @returns The plural function for the locale.
22372 * @see `NgPlural`
22373 * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
22374 */
22375function getLocalePluralCase(locale) {
22376 const data = findLocaleData(locale);
22377 return data[LocaleDataIndex.PluralCase];
22378}
22379/**
22380 * Helper function to get the given `normalizedLocale` from `LOCALE_DATA`
22381 * or from the global `ng.common.locale`.
22382 */
22383function getLocaleData(normalizedLocale) {
22384 if (!(normalizedLocale in LOCALE_DATA)) {
22385 LOCALE_DATA[normalizedLocale] = _global.ng && _global.ng.common && _global.ng.common.locales &&
22386 _global.ng.common.locales[normalizedLocale];
22387 }
22388 return LOCALE_DATA[normalizedLocale];
22389}
22390/**
22391 * Helper function to remove all the locale data from `LOCALE_DATA`.
22392 */
22393function unregisterAllLocaleData() {
22394 LOCALE_DATA = {};
22395}
22396/**
22397 * Index of each type of locale data from the locale data array
22398 */
22399var LocaleDataIndex;
22400(function (LocaleDataIndex) {
22401 LocaleDataIndex[LocaleDataIndex["LocaleId"] = 0] = "LocaleId";
22402 LocaleDataIndex[LocaleDataIndex["DayPeriodsFormat"] = 1] = "DayPeriodsFormat";
22403 LocaleDataIndex[LocaleDataIndex["DayPeriodsStandalone"] = 2] = "DayPeriodsStandalone";
22404 LocaleDataIndex[LocaleDataIndex["DaysFormat"] = 3] = "DaysFormat";
22405 LocaleDataIndex[LocaleDataIndex["DaysStandalone"] = 4] = "DaysStandalone";
22406 LocaleDataIndex[LocaleDataIndex["MonthsFormat"] = 5] = "MonthsFormat";
22407 LocaleDataIndex[LocaleDataIndex["MonthsStandalone"] = 6] = "MonthsStandalone";
22408 LocaleDataIndex[LocaleDataIndex["Eras"] = 7] = "Eras";
22409 LocaleDataIndex[LocaleDataIndex["FirstDayOfWeek"] = 8] = "FirstDayOfWeek";
22410 LocaleDataIndex[LocaleDataIndex["WeekendRange"] = 9] = "WeekendRange";
22411 LocaleDataIndex[LocaleDataIndex["DateFormat"] = 10] = "DateFormat";
22412 LocaleDataIndex[LocaleDataIndex["TimeFormat"] = 11] = "TimeFormat";
22413 LocaleDataIndex[LocaleDataIndex["DateTimeFormat"] = 12] = "DateTimeFormat";
22414 LocaleDataIndex[LocaleDataIndex["NumberSymbols"] = 13] = "NumberSymbols";
22415 LocaleDataIndex[LocaleDataIndex["NumberFormats"] = 14] = "NumberFormats";
22416 LocaleDataIndex[LocaleDataIndex["CurrencyCode"] = 15] = "CurrencyCode";
22417 LocaleDataIndex[LocaleDataIndex["CurrencySymbol"] = 16] = "CurrencySymbol";
22418 LocaleDataIndex[LocaleDataIndex["CurrencyName"] = 17] = "CurrencyName";
22419 LocaleDataIndex[LocaleDataIndex["Currencies"] = 18] = "Currencies";
22420 LocaleDataIndex[LocaleDataIndex["Directionality"] = 19] = "Directionality";
22421 LocaleDataIndex[LocaleDataIndex["PluralCase"] = 20] = "PluralCase";
22422 LocaleDataIndex[LocaleDataIndex["ExtraData"] = 21] = "ExtraData";
22423})(LocaleDataIndex || (LocaleDataIndex = {}));
22424/**
22425 * Returns the canonical form of a locale name - lowercase with `_` replaced with `-`.
22426 */
22427function normalizeLocale(locale) {
22428 return locale.toLowerCase().replace(/_/g, '-');
22429}
22430
22431/**
22432 * @license
22433 * Copyright Google LLC All Rights Reserved.
22434 *
22435 * Use of this source code is governed by an MIT-style license that can be
22436 * found in the LICENSE file at https://angular.io/license
22437 */
22438const pluralMapping = ['zero', 'one', 'two', 'few', 'many'];
22439/**
22440 * Returns the plural case based on the locale
22441 */
22442function getPluralCase(value, locale) {
22443 const plural = getLocalePluralCase(locale)(parseInt(value, 10));
22444 const result = pluralMapping[plural];
22445 return (result !== undefined) ? result : 'other';
22446}
22447/**
22448 * The locale id that the application is using by default (for translations and ICU expressions).
22449 */
22450const DEFAULT_LOCALE_ID = 'en-US';
22451/**
22452 * USD currency code that the application uses by default for CurrencyPipe when no
22453 * DEFAULT_CURRENCY_CODE is provided.
22454 */
22455const USD_CURRENCY_CODE = 'USD';
22456
22457/**
22458 * @license
22459 * Copyright Google LLC All Rights Reserved.
22460 *
22461 * Use of this source code is governed by an MIT-style license that can be
22462 * found in the LICENSE file at https://angular.io/license
22463 */
22464/**
22465 * The locale id that the application is currently using (for translations and ICU expressions).
22466 * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
22467 * but is now defined as a global value.
22468 */
22469let LOCALE_ID = DEFAULT_LOCALE_ID;
22470/**
22471 * Sets the locale id that will be used for translations and ICU expressions.
22472 * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
22473 * but is now defined as a global value.
22474 *
22475 * @param localeId
22476 */
22477function setLocaleId(localeId) {
22478 assertDefined(localeId, `Expected localeId to be defined`);
22479 if (typeof localeId === 'string') {
22480 LOCALE_ID = localeId.toLowerCase().replace(/_/g, '-');
22481 }
22482}
22483/**
22484 * Gets the locale id that will be used for translations and ICU expressions.
22485 * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
22486 * but is now defined as a global value.
22487 */
22488function getLocaleId() {
22489 return LOCALE_ID;
22490}
22491
22492/**
22493 * @license
22494 * Copyright Google LLC All Rights Reserved.
22495 *
22496 * Use of this source code is governed by an MIT-style license that can be
22497 * found in the LICENSE file at https://angular.io/license
22498 */
22499/**
22500 * NOTE: changes to the `ngI18nClosureMode` name must be synced with `compiler-cli/src/tooling.ts`.
22501 */
22502if (typeof ngI18nClosureMode === 'undefined') {
22503 // These property accesses can be ignored because ngI18nClosureMode will be set to false
22504 // when optimizing code and the whole if statement will be dropped.
22505 // Make sure to refer to ngI18nClosureMode as ['ngI18nClosureMode'] for closure.
22506 // NOTE: we need to have it in IIFE so that the tree-shaker is happy.
22507 (function () {
22508 // tslint:disable-next-line:no-toplevel-property-access
22509 _global['ngI18nClosureMode'] =
22510 // TODO(FW-1250): validate that this actually, you know, works.
22511 // tslint:disable-next-line:no-toplevel-property-access
22512 typeof goog !== 'undefined' && typeof goog.getMsg === 'function';
22513 })();
22514}
22515
22516/**
22517 * @license
22518 * Copyright Google LLC All Rights Reserved.
22519 *
22520 * Use of this source code is governed by an MIT-style license that can be
22521 * found in the LICENSE file at https://angular.io/license
22522 */
22523function getParentFromI18nMutateOpCode(mergedCode) {
22524 return mergedCode >>> 17 /* SHIFT_PARENT */;
22525}
22526function getRefFromI18nMutateOpCode(mergedCode) {
22527 return (mergedCode & 131064 /* MASK_REF */) >>> 3 /* SHIFT_REF */;
22528}
22529function getInstructionFromI18nMutateOpCode(mergedCode) {
22530 return mergedCode & 7 /* MASK_INSTRUCTION */;
22531}
22532/**
22533 * Marks that the next string is an element name.
22534 *
22535 * See `I18nMutateOpCodes` documentation.
22536 */
22537const ELEMENT_MARKER = {
22538 marker: 'element'
22539};
22540/**
22541 * Marks that the next string is comment text.
22542 *
22543 * See `I18nMutateOpCodes` documentation.
22544 */
22545const COMMENT_MARKER = {
22546 marker: 'comment'
22547};
22548// Note: This hack is necessary so we don't erroneously get a circular dependency
22549// failure based on types.
22550const unusedValueExportToPlacateAjd$6 = 1;
22551
22552/**
22553 * @license
22554 * Copyright Google LLC All Rights Reserved.
22555 *
22556 * Use of this source code is governed by an MIT-style license that can be
22557 * found in the LICENSE file at https://angular.io/license
22558 */
22559const i18nIndexStack = [];
22560let i18nIndexStackPointer = -1;
22561function popI18nIndex() {
22562 return i18nIndexStack[i18nIndexStackPointer--];
22563}
22564function pushI18nIndex(index) {
22565 i18nIndexStack[++i18nIndexStackPointer] = index;
22566}
22567let changeMask = 0b0;
22568let shiftsCounter = 0;
22569function setMaskBit(bit) {
22570 if (bit) {
22571 changeMask = changeMask | (1 << shiftsCounter);
22572 }
22573 shiftsCounter++;
22574}
22575function applyI18n(tView, lView, index) {
22576 if (shiftsCounter > 0) {
22577 ngDevMode && assertDefined(tView, `tView should be defined`);
22578 const tI18n = tView.data[index + HEADER_OFFSET];
22579 let updateOpCodes;
22580 let tIcus = null;
22581 if (Array.isArray(tI18n)) {
22582 updateOpCodes = tI18n;
22583 }
22584 else {
22585 updateOpCodes = tI18n.update;
22586 tIcus = tI18n.icus;
22587 }
22588 const bindingsStartIndex = getBindingIndex() - shiftsCounter - 1;
22589 applyUpdateOpCodes(tView, tIcus, lView, updateOpCodes, bindingsStartIndex, changeMask);
22590 // Reset changeMask & maskBit to default for the next update cycle
22591 changeMask = 0b0;
22592 shiftsCounter = 0;
22593 }
22594}
22595/**
22596 * Apply `I18nMutateOpCodes` OpCodes.
22597 *
22598 * @param tView Current `TView`
22599 * @param rootIndex Pointer to the root (parent) tNode for the i18n.
22600 * @param createOpCodes OpCodes to process
22601 * @param lView Current `LView`
22602 */
22603function applyCreateOpCodes(tView, rootindex, createOpCodes, lView) {
22604 const renderer = lView[RENDERER];
22605 let currentTNode = null;
22606 let previousTNode = null;
22607 const visitedNodes = [];
22608 for (let i = 0; i < createOpCodes.length; i++) {
22609 const opCode = createOpCodes[i];
22610 if (typeof opCode == 'string') {
22611 const textRNode = createTextNode(opCode, renderer);
22612 const textNodeIndex = createOpCodes[++i];
22613 ngDevMode && ngDevMode.rendererCreateTextNode++;
22614 previousTNode = currentTNode;
22615 currentTNode =
22616 createDynamicNodeAtIndex(tView, lView, textNodeIndex, 3 /* Element */, textRNode, null);
22617 visitedNodes.push(textNodeIndex);
22618 setIsNotParent();
22619 }
22620 else if (typeof opCode == 'number') {
22621 switch (opCode & 7 /* MASK_INSTRUCTION */) {
22622 case 1 /* AppendChild */:
22623 const destinationNodeIndex = opCode >>> 17 /* SHIFT_PARENT */;
22624 let destinationTNode;
22625 if (destinationNodeIndex === rootindex) {
22626 // If the destination node is `i18nStart`, we don't have a
22627 // top-level node and we should use the host node instead
22628 destinationTNode = lView[T_HOST];
22629 }
22630 else {
22631 destinationTNode = getTNode(tView, destinationNodeIndex);
22632 }
22633 ngDevMode &&
22634 assertDefined(currentTNode, `You need to create or select a node before you can insert it into the DOM`);
22635 previousTNode =
22636 appendI18nNode(tView, currentTNode, destinationTNode, previousTNode, lView);
22637 break;
22638 case 0 /* Select */:
22639 // Negative indices indicate that a given TNode is a sibling node, not a parent node
22640 // (see `i18nStartFirstPass` for additional information).
22641 const isParent = opCode >= 0;
22642 // FIXME(misko): This SHIFT_REF looks suspect as it does not have mask.
22643 const nodeIndex = (isParent ? opCode : ~opCode) >>> 3 /* SHIFT_REF */;
22644 visitedNodes.push(nodeIndex);
22645 previousTNode = currentTNode;
22646 currentTNode = getTNode(tView, nodeIndex);
22647 if (currentTNode) {
22648 setPreviousOrParentTNode(currentTNode, isParent);
22649 }
22650 break;
22651 case 5 /* ElementEnd */:
22652 const elementIndex = opCode >>> 3 /* SHIFT_REF */;
22653 previousTNode = currentTNode = getTNode(tView, elementIndex);
22654 setPreviousOrParentTNode(currentTNode, false);
22655 break;
22656 case 4 /* Attr */:
22657 const elementNodeIndex = opCode >>> 3 /* SHIFT_REF */;
22658 const attrName = createOpCodes[++i];
22659 const attrValue = createOpCodes[++i];
22660 // This code is used for ICU expressions only, since we don't support
22661 // directives/components in ICUs, we don't need to worry about inputs here
22662 elementAttributeInternal(getTNode(tView, elementNodeIndex), lView, attrName, attrValue, null, null);
22663 break;
22664 default:
22665 throw new Error(`Unable to determine the type of mutate operation for "${opCode}"`);
22666 }
22667 }
22668 else {
22669 switch (opCode) {
22670 case COMMENT_MARKER:
22671 const commentValue = createOpCodes[++i];
22672 const commentNodeIndex = createOpCodes[++i];
22673 ngDevMode &&
22674 assertEqual(typeof commentValue, 'string', `Expected "${commentValue}" to be a comment node value`);
22675 const commentRNode = renderer.createComment(commentValue);
22676 ngDevMode && ngDevMode.rendererCreateComment++;
22677 previousTNode = currentTNode;
22678 currentTNode = createDynamicNodeAtIndex(tView, lView, commentNodeIndex, 5 /* IcuContainer */, commentRNode, null);
22679 visitedNodes.push(commentNodeIndex);
22680 attachPatchData(commentRNode, lView);
22681 // We will add the case nodes later, during the update phase
22682 setIsNotParent();
22683 break;
22684 case ELEMENT_MARKER:
22685 const tagNameValue = createOpCodes[++i];
22686 const elementNodeIndex = createOpCodes[++i];
22687 ngDevMode &&
22688 assertEqual(typeof tagNameValue, 'string', `Expected "${tagNameValue}" to be an element node tag name`);
22689 const elementRNode = renderer.createElement(tagNameValue);
22690 ngDevMode && ngDevMode.rendererCreateElement++;
22691 previousTNode = currentTNode;
22692 currentTNode = createDynamicNodeAtIndex(tView, lView, elementNodeIndex, 3 /* Element */, elementRNode, tagNameValue);
22693 visitedNodes.push(elementNodeIndex);
22694 break;
22695 default:
22696 throw new Error(`Unable to determine the type of mutate operation for "${opCode}"`);
22697 }
22698 }
22699 }
22700 setIsNotParent();
22701 return visitedNodes;
22702}
22703/**
22704 * Apply `I18nUpdateOpCodes` OpCodes
22705 *
22706 * @param tView Current `TView`
22707 * @param tIcus If ICUs present than this contains them.
22708 * @param lView Current `LView`
22709 * @param updateOpCodes OpCodes to process
22710 * @param bindingsStartIndex Location of the first `ɵɵi18nApply`
22711 * @param changeMask Each bit corresponds to a `ɵɵi18nExp` (Counting backwards from
22712 * `bindingsStartIndex`)
22713 */
22714function applyUpdateOpCodes(tView, tIcus, lView, updateOpCodes, bindingsStartIndex, changeMask) {
22715 let caseCreated = false;
22716 for (let i = 0; i < updateOpCodes.length; i++) {
22717 // bit code to check if we should apply the next update
22718 const checkBit = updateOpCodes[i];
22719 // Number of opCodes to skip until next set of update codes
22720 const skipCodes = updateOpCodes[++i];
22721 if (checkBit & changeMask) {
22722 // The value has been updated since last checked
22723 let value = '';
22724 for (let j = i + 1; j <= (i + skipCodes); j++) {
22725 const opCode = updateOpCodes[j];
22726 if (typeof opCode == 'string') {
22727 value += opCode;
22728 }
22729 else if (typeof opCode == 'number') {
22730 if (opCode < 0) {
22731 // Negative opCode represent `i18nExp` values offset.
22732 value += renderStringify(lView[bindingsStartIndex - opCode]);
22733 }
22734 else {
22735 const nodeIndex = opCode >>> 2 /* SHIFT_REF */;
22736 switch (opCode & 3 /* MASK_OPCODE */) {
22737 case 1 /* Attr */:
22738 const propName = updateOpCodes[++j];
22739 const sanitizeFn = updateOpCodes[++j];
22740 elementPropertyInternal(tView, getTNode(tView, nodeIndex), lView, propName, value, lView[RENDERER], sanitizeFn, false);
22741 break;
22742 case 0 /* Text */:
22743 textBindingInternal(lView, nodeIndex, value);
22744 break;
22745 case 2 /* IcuSwitch */:
22746 caseCreated =
22747 applyIcuSwitchCase(tView, tIcus, updateOpCodes[++j], lView, value);
22748 break;
22749 case 3 /* IcuUpdate */:
22750 applyIcuUpdateCase(tView, tIcus, updateOpCodes[++j], bindingsStartIndex, lView, caseCreated);
22751 break;
22752 }
22753 }
22754 }
22755 }
22756 }
22757 i += skipCodes;
22758 }
22759}
22760/**
22761 * Apply OpCodes associated with updating an existing ICU.
22762 *
22763 * @param tView Current `TView`
22764 * @param tIcus ICUs active at this location.
22765 * @param tIcuIndex Index into `tIcus` to process.
22766 * @param bindingsStartIndex Location of the first `ɵɵi18nApply`
22767 * @param lView Current `LView`
22768 * @param changeMask Each bit corresponds to a `ɵɵi18nExp` (Counting backwards from
22769 * `bindingsStartIndex`)
22770 */
22771function applyIcuUpdateCase(tView, tIcus, tIcuIndex, bindingsStartIndex, lView, caseCreated) {
22772 ngDevMode && assertIndexInRange(tIcus, tIcuIndex);
22773 const tIcu = tIcus[tIcuIndex];
22774 ngDevMode && assertIndexInRange(lView, tIcu.currentCaseLViewIndex);
22775 const activeCaseIndex = lView[tIcu.currentCaseLViewIndex];
22776 if (activeCaseIndex !== null) {
22777 const mask = caseCreated ?
22778 -1 : // -1 is same as all bits on, which simulates creation since it marks all bits dirty
22779 changeMask;
22780 applyUpdateOpCodes(tView, tIcus, lView, tIcu.update[activeCaseIndex], bindingsStartIndex, mask);
22781 }
22782}
22783/**
22784 * Apply OpCodes associated with switching a case on ICU.
22785 *
22786 * This involves tearing down existing case and than building up a new case.
22787 *
22788 * @param tView Current `TView`
22789 * @param tIcus ICUs active at this location.
22790 * @param tICuIndex Index into `tIcus` to process.
22791 * @param lView Current `LView`
22792 * @param value Value of the case to update to.
22793 * @returns true if a new case was created (needed so that the update executes regardless of the
22794 * bitmask)
22795 */
22796function applyIcuSwitchCase(tView, tIcus, tICuIndex, lView, value) {
22797 applyIcuSwitchCaseRemove(tView, tIcus, tICuIndex, lView);
22798 // Rebuild a new case for this ICU
22799 let caseCreated = false;
22800 const tIcu = tIcus[tICuIndex];
22801 const caseIndex = getCaseIndex(tIcu, value);
22802 lView[tIcu.currentCaseLViewIndex] = caseIndex !== -1 ? caseIndex : null;
22803 if (caseIndex > -1) {
22804 // Add the nodes for the new case
22805 applyCreateOpCodes(tView, -1, // -1 means we don't have parent node
22806 tIcu.create[caseIndex], lView);
22807 caseCreated = true;
22808 }
22809 return caseCreated;
22810}
22811/**
22812 * Apply OpCodes associated with tearing down of DOM.
22813 *
22814 * This involves tearing down existing case and than building up a new case.
22815 *
22816 * @param tView Current `TView`
22817 * @param tIcus ICUs active at this location.
22818 * @param tIcuIndex Index into `tIcus` to process.
22819 * @param lView Current `LView`
22820 * @returns true if a new case was created (needed so that the update executes regardless of the
22821 * bitmask)
22822 */
22823function applyIcuSwitchCaseRemove(tView, tIcus, tIcuIndex, lView) {
22824 ngDevMode && assertIndexInRange(tIcus, tIcuIndex);
22825 const tIcu = tIcus[tIcuIndex];
22826 const activeCaseIndex = lView[tIcu.currentCaseLViewIndex];
22827 if (activeCaseIndex !== null) {
22828 const removeCodes = tIcu.remove[activeCaseIndex];
22829 for (let k = 0; k < removeCodes.length; k++) {
22830 const removeOpCode = removeCodes[k];
22831 const nodeOrIcuIndex = removeOpCode >>> 3 /* SHIFT_REF */;
22832 switch (removeOpCode & 7 /* MASK_INSTRUCTION */) {
22833 case 3 /* Remove */:
22834 // FIXME(misko): this comment is wrong!
22835 // Remove DOM element, but do *not* mark TNode as detached, since we are
22836 // just switching ICU cases (while keeping the same TNode), so a DOM element
22837 // representing a new ICU case will be re-created.
22838 removeNode(tView, lView, nodeOrIcuIndex, /* markAsDetached */ false);
22839 break;
22840 case 6 /* RemoveNestedIcu */:
22841 applyIcuSwitchCaseRemove(tView, tIcus, nodeOrIcuIndex, lView);
22842 break;
22843 }
22844 }
22845 }
22846}
22847function appendI18nNode(tView, tNode, parentTNode, previousTNode, lView) {
22848 ngDevMode && ngDevMode.rendererMoveNode++;
22849 const nextNode = tNode.next;
22850 if (!previousTNode) {
22851 previousTNode = parentTNode;
22852 }
22853 // Re-organize node tree to put this node in the correct position.
22854 if (previousTNode === parentTNode && tNode !== parentTNode.child) {
22855 tNode.next = parentTNode.child;
22856 parentTNode.child = tNode;
22857 }
22858 else if (previousTNode !== parentTNode && tNode !== previousTNode.next) {
22859 tNode.next = previousTNode.next;
22860 previousTNode.next = tNode;
22861 }
22862 else {
22863 tNode.next = null;
22864 }
22865 if (parentTNode !== lView[T_HOST]) {
22866 tNode.parent = parentTNode;
22867 }
22868 // If tNode was moved around, we might need to fix a broken link.
22869 let cursor = tNode.next;
22870 while (cursor) {
22871 if (cursor.next === tNode) {
22872 cursor.next = nextNode;
22873 }
22874 cursor = cursor.next;
22875 }
22876 // If the placeholder to append is a projection, we need to move the projected nodes instead
22877 if (tNode.type === 1 /* Projection */) {
22878 applyProjection(tView, lView, tNode);
22879 return tNode;
22880 }
22881 appendChild(tView, lView, getNativeByTNode(tNode, lView), tNode);
22882 const slotValue = lView[tNode.index];
22883 if (tNode.type !== 0 /* Container */ && isLContainer(slotValue)) {
22884 // Nodes that inject ViewContainerRef also have a comment node that should be moved
22885 appendChild(tView, lView, slotValue[NATIVE], tNode);
22886 }
22887 return tNode;
22888}
22889/**
22890 * See `i18nEnd` above.
22891 */
22892function i18nEndFirstPass(tView, lView) {
22893 ngDevMode &&
22894 assertEqual(getBindingIndex(), tView.bindingStartIndex, 'i18nEnd should be called before any binding');
22895 const rootIndex = popI18nIndex();
22896 const tI18n = tView.data[rootIndex + HEADER_OFFSET];
22897 ngDevMode && assertDefined(tI18n, `You should call i18nStart before i18nEnd`);
22898 // Find the last node that was added before `i18nEnd`
22899 const lastCreatedNode = getPreviousOrParentTNode();
22900 // Read the instructions to insert/move/remove DOM elements
22901 const visitedNodes = applyCreateOpCodes(tView, rootIndex, tI18n.create, lView);
22902 // Remove deleted nodes
22903 let index = rootIndex + 1;
22904 while (index <= lastCreatedNode.index - HEADER_OFFSET) {
22905 if (visitedNodes.indexOf(index) === -1) {
22906 removeNode(tView, lView, index, /* markAsDetached */ true);
22907 }
22908 // Check if an element has any local refs and skip them
22909 const tNode = getTNode(tView, index);
22910 if (tNode &&
22911 (tNode.type === 0 /* Container */ || tNode.type === 3 /* Element */ ||
22912 tNode.type === 4 /* ElementContainer */) &&
22913 tNode.localNames !== null) {
22914 // Divide by 2 to get the number of local refs,
22915 // since they are stored as an array that also includes directive indexes,
22916 // i.e. ["localRef", directiveIndex, ...]
22917 index += tNode.localNames.length >> 1;
22918 }
22919 index++;
22920 }
22921}
22922function removeNode(tView, lView, index, markAsDetached) {
22923 const removedPhTNode = getTNode(tView, index);
22924 const removedPhRNode = getNativeByIndex(index, lView);
22925 if (removedPhRNode) {
22926 nativeRemoveNode(lView[RENDERER], removedPhRNode);
22927 }
22928 const slotValue = load(lView, index);
22929 if (isLContainer(slotValue)) {
22930 const lContainer = slotValue;
22931 if (removedPhTNode.type !== 0 /* Container */) {
22932 nativeRemoveNode(lView[RENDERER], lContainer[NATIVE]);
22933 }
22934 }
22935 if (markAsDetached) {
22936 // Define this node as detached to avoid projecting it later
22937 removedPhTNode.flags |= 64 /* isDetached */;
22938 }
22939 ngDevMode && ngDevMode.rendererRemoveNode++;
22940}
22941/**
22942 * Creates and stores the dynamic TNode, and unhooks it from the tree for now.
22943 */
22944function createDynamicNodeAtIndex(tView, lView, index, type, native, name) {
22945 const previousOrParentTNode = getPreviousOrParentTNode();
22946 ngDevMode && assertIndexInRange(lView, index + HEADER_OFFSET);
22947 lView[index + HEADER_OFFSET] = native;
22948 // FIXME(misko): Why does this create A TNode??? I would not expect this to be here.
22949 const tNode = getOrCreateTNode(tView, lView[T_HOST], index, type, name, null);
22950 // We are creating a dynamic node, the previous tNode might not be pointing at this node.
22951 // We will link ourselves into the tree later with `appendI18nNode`.
22952 if (previousOrParentTNode && previousOrParentTNode.next === tNode) {
22953 previousOrParentTNode.next = null;
22954 }
22955 return tNode;
22956}
22957/**
22958 * Returns the index of the current case of an ICU expression depending on the main binding value
22959 *
22960 * @param icuExpression
22961 * @param bindingValue The value of the main binding used by this ICU expression
22962 */
22963function getCaseIndex(icuExpression, bindingValue) {
22964 let index = icuExpression.cases.indexOf(bindingValue);
22965 if (index === -1) {
22966 switch (icuExpression.type) {
22967 case 1 /* plural */: {
22968 const resolvedCase = getPluralCase(bindingValue, getLocaleId());
22969 index = icuExpression.cases.indexOf(resolvedCase);
22970 if (index === -1 && resolvedCase !== 'other') {
22971 index = icuExpression.cases.indexOf('other');
22972 }
22973 break;
22974 }
22975 case 0 /* select */: {
22976 index = icuExpression.cases.indexOf('other');
22977 break;
22978 }
22979 }
22980 }
22981 return index;
22982}
22983
22984/**
22985 * @license
22986 * Copyright Google LLC All Rights Reserved.
22987 *
22988 * Use of this source code is governed by an MIT-style license that can be
22989 * found in the LICENSE file at https://angular.io/license
22990 */
22991/**
22992 * Converts `I18nUpdateOpCodes` array into a human readable format.
22993 *
22994 * This function is attached to the `I18nUpdateOpCodes.debug` property if `ngDevMode` is enabled.
22995 * This function provides a human readable view of the opcodes. This is useful when debugging the
22996 * application as well as writing more readable tests.
22997 *
22998 * @param this `I18nUpdateOpCodes` if attached as a method.
22999 * @param opcodes `I18nUpdateOpCodes` if invoked as a function.
23000 */
23001function i18nUpdateOpCodesToString(opcodes) {
23002 const parser = new OpCodeParser(opcodes || (Array.isArray(this) ? this : []));
23003 let lines = [];
23004 function consumeOpCode(value) {
23005 const ref = value >>> 2 /* SHIFT_REF */;
23006 const opCode = value & 3 /* MASK_OPCODE */;
23007 switch (opCode) {
23008 case 0 /* Text */:
23009 return `(lView[${ref}] as Text).textContent = $$$`;
23010 case 1 /* Attr */:
23011 const attrName = parser.consumeString();
23012 const sanitizationFn = parser.consumeFunction();
23013 const value = sanitizationFn ? `(${sanitizationFn})($$$)` : '$$$';
23014 return `(lView[${ref}] as Element).setAttribute('${attrName}', ${value})`;
23015 case 2 /* IcuSwitch */:
23016 return `icuSwitchCase(lView[${ref}] as Comment, ${parser.consumeNumber()}, $$$)`;
23017 case 3 /* IcuUpdate */:
23018 return `icuUpdateCase(lView[${ref}] as Comment, ${parser.consumeNumber()})`;
23019 }
23020 throw new Error('unexpected OpCode');
23021 }
23022 while (parser.hasMore()) {
23023 let mask = parser.consumeNumber();
23024 let size = parser.consumeNumber();
23025 const end = parser.i + size;
23026 const statements = [];
23027 let statement = '';
23028 while (parser.i < end) {
23029 let value = parser.consumeNumberOrString();
23030 if (typeof value === 'string') {
23031 statement += value;
23032 }
23033 else if (value < 0) {
23034 // Negative numbers are ref indexes
23035 statement += '${lView[' + (0 - value) + ']}';
23036 }
23037 else {
23038 // Positive numbers are operations.
23039 const opCodeText = consumeOpCode(value);
23040 statements.push(opCodeText.replace('$$$', '`' + statement + '`') + ';');
23041 statement = '';
23042 }
23043 }
23044 lines.push(`if (mask & 0b${mask.toString(2)}) { ${statements.join(' ')} }`);
23045 }
23046 return lines;
23047}
23048/**
23049 * Converts `I18nMutableOpCodes` array into a human readable format.
23050 *
23051 * This function is attached to the `I18nMutableOpCodes.debug` if `ngDevMode` is enabled. This
23052 * function provides a human readable view of the opcodes. This is useful when debugging the
23053 * application as well as writing more readable tests.
23054 *
23055 * @param this `I18nMutableOpCodes` if attached as a method.
23056 * @param opcodes `I18nMutableOpCodes` if invoked as a function.
23057 */
23058function i18nMutateOpCodesToString(opcodes) {
23059 const parser = new OpCodeParser(opcodes || (Array.isArray(this) ? this : []));
23060 let lines = [];
23061 function consumeOpCode(opCode) {
23062 const parent = getParentFromI18nMutateOpCode(opCode);
23063 const ref = getRefFromI18nMutateOpCode(opCode);
23064 switch (getInstructionFromI18nMutateOpCode(opCode)) {
23065 case 0 /* Select */:
23066 lastRef = ref;
23067 return '';
23068 case 1 /* AppendChild */:
23069 return `(lView[${parent}] as Element).appendChild(lView[${lastRef}])`;
23070 case 3 /* Remove */:
23071 return `(lView[${parent}] as Element).remove(lView[${ref}])`;
23072 case 4 /* Attr */:
23073 return `(lView[${ref}] as Element).setAttribute("${parser.consumeString()}", "${parser.consumeString()}")`;
23074 case 5 /* ElementEnd */:
23075 return `setPreviousOrParentTNode(tView.data[${ref}] as TNode)`;
23076 case 6 /* RemoveNestedIcu */:
23077 return `removeNestedICU(${ref})`;
23078 }
23079 throw new Error('Unexpected OpCode');
23080 }
23081 let lastRef = -1;
23082 while (parser.hasMore()) {
23083 let value = parser.consumeNumberStringOrMarker();
23084 if (value === COMMENT_MARKER) {
23085 const text = parser.consumeString();
23086 lastRef = parser.consumeNumber();
23087 lines.push(`lView[${lastRef}] = document.createComment("${text}")`);
23088 }
23089 else if (value === ELEMENT_MARKER) {
23090 const text = parser.consumeString();
23091 lastRef = parser.consumeNumber();
23092 lines.push(`lView[${lastRef}] = document.createElement("${text}")`);
23093 }
23094 else if (typeof value === 'string') {
23095 lastRef = parser.consumeNumber();
23096 lines.push(`lView[${lastRef}] = document.createTextNode("${value}")`);
23097 }
23098 else if (typeof value === 'number') {
23099 const line = consumeOpCode(value);
23100 line && lines.push(line);
23101 }
23102 else {
23103 throw new Error('Unexpected value');
23104 }
23105 }
23106 return lines;
23107}
23108class OpCodeParser {
23109 constructor(codes) {
23110 this.i = 0;
23111 this.codes = codes;
23112 }
23113 hasMore() {
23114 return this.i < this.codes.length;
23115 }
23116 consumeNumber() {
23117 let value = this.codes[this.i++];
23118 assertNumber(value, 'expecting number in OpCode');
23119 return value;
23120 }
23121 consumeString() {
23122 let value = this.codes[this.i++];
23123 assertString(value, 'expecting string in OpCode');
23124 return value;
23125 }
23126 consumeFunction() {
23127 let value = this.codes[this.i++];
23128 if (value === null || typeof value === 'function') {
23129 return value;
23130 }
23131 throw new Error('expecting function in OpCode');
23132 }
23133 consumeNumberOrString() {
23134 let value = this.codes[this.i++];
23135 if (typeof value === 'string') {
23136 return value;
23137 }
23138 assertNumber(value, 'expecting number or string in OpCode');
23139 return value;
23140 }
23141 consumeNumberStringOrMarker() {
23142 let value = this.codes[this.i++];
23143 if (typeof value === 'string' || typeof value === 'number' || value == COMMENT_MARKER ||
23144 value == ELEMENT_MARKER) {
23145 return value;
23146 }
23147 assertNumber(value, 'expecting number, string, COMMENT_MARKER or ELEMENT_MARKER in OpCode');
23148 return value;
23149 }
23150}
23151
23152/**
23153 * @license
23154 * Copyright Google LLC All Rights Reserved.
23155 *
23156 * Use of this source code is governed by an MIT-style license that can be
23157 * found in the LICENSE file at https://angular.io/license
23158 */
23159const BINDING_REGEXP = /�(\d+):?\d*�/gi;
23160const ICU_REGEXP = /({\s*�\d+:?\d*�\s*,\s*\S{6}\s*,[\s\S]*})/gi;
23161const NESTED_ICU = /�(\d+)�/;
23162const ICU_BLOCK_REGEXP = /^\s*(�\d+:?\d*�)\s*,\s*(select|plural)\s*,/;
23163// Count for the number of vars that will be allocated for each i18n block.
23164// It is global because this is used in multiple functions that include loops and recursive calls.
23165// This is reset to 0 when `i18nStartFirstPass` is called.
23166let i18nVarsCount;
23167const parentIndexStack = [];
23168const MARKER = `�`;
23169const SUBTEMPLATE_REGEXP = /�\/?\*(\d+:\d+)�/gi;
23170const PH_REGEXP = /�(\/?[#*!]\d+):?\d*�/gi;
23171/**
23172 * Angular Dart introduced &ngsp; as a placeholder for non-removable space, see:
23173 * https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart#L25-L32
23174 * In Angular Dart &ngsp; is converted to the 0xE500 PUA (Private Use Areas) unicode character
23175 * and later on replaced by a space. We are re-implementing the same idea here, since translations
23176 * might contain this special character.
23177 */
23178const NGSP_UNICODE_REGEXP = /\uE500/g;
23179function replaceNgsp(value) {
23180 return value.replace(NGSP_UNICODE_REGEXP, ' ');
23181}
23182/**
23183 * See `i18nStart` above.
23184 */
23185function i18nStartFirstPass(lView, tView, index, message, subTemplateIndex) {
23186 const startIndex = tView.blueprint.length - HEADER_OFFSET;
23187 i18nVarsCount = 0;
23188 const previousOrParentTNode = getPreviousOrParentTNode();
23189 const parentTNode = getIsParent() ? previousOrParentTNode : previousOrParentTNode && previousOrParentTNode.parent;
23190 let parentIndex = parentTNode && parentTNode !== lView[T_HOST] ? parentTNode.index - HEADER_OFFSET : index;
23191 let parentIndexPointer = 0;
23192 parentIndexStack[parentIndexPointer] = parentIndex;
23193 const createOpCodes = [];
23194 if (ngDevMode) {
23195 attachDebugGetter(createOpCodes, i18nMutateOpCodesToString);
23196 }
23197 // If the previous node wasn't the direct parent then we have a translation without top level
23198 // element and we need to keep a reference of the previous element if there is one. We should also
23199 // keep track whether an element was a parent node or not, so that the logic that consumes
23200 // the generated `I18nMutateOpCode`s can leverage this information to properly set TNode state
23201 // (whether it's a parent or sibling).
23202 if (index > 0 && previousOrParentTNode !== parentTNode) {
23203 let previousTNodeIndex = previousOrParentTNode.index - HEADER_OFFSET;
23204 // If current TNode is a sibling node, encode it using a negative index. This information is
23205 // required when the `Select` action is processed (see the `readCreateOpCodes` function).
23206 if (!getIsParent()) {
23207 previousTNodeIndex = ~previousTNodeIndex;
23208 }
23209 // Create an OpCode to select the previous TNode
23210 createOpCodes.push(previousTNodeIndex << 3 /* SHIFT_REF */ | 0 /* Select */);
23211 }
23212 const updateOpCodes = [];
23213 if (ngDevMode) {
23214 attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString);
23215 }
23216 const icuExpressions = [];
23217 if (message === '' && isRootTemplateMessage(subTemplateIndex)) {
23218 // If top level translation is an empty string, do not invoke additional processing
23219 // and just create op codes for empty text node instead.
23220 createOpCodes.push(message, allocNodeIndex(startIndex), parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
23221 }
23222 else {
23223 const templateTranslation = getTranslationForTemplate(message, subTemplateIndex);
23224 const msgParts = replaceNgsp(templateTranslation).split(PH_REGEXP);
23225 for (let i = 0; i < msgParts.length; i++) {
23226 let value = msgParts[i];
23227 if (i & 1) {
23228 // Odd indexes are placeholders (elements and sub-templates)
23229 if (value.charAt(0) === '/') {
23230 // It is a closing tag
23231 if (value.charAt(1) === "#" /* ELEMENT */) {
23232 const phIndex = parseInt(value.substr(2), 10);
23233 parentIndex = parentIndexStack[--parentIndexPointer];
23234 createOpCodes.push(phIndex << 3 /* SHIFT_REF */ | 5 /* ElementEnd */);
23235 }
23236 }
23237 else {
23238 const phIndex = parseInt(value.substr(1), 10);
23239 const isElement = value.charAt(0) === "#" /* ELEMENT */;
23240 // The value represents a placeholder that we move to the designated index.
23241 // Note: positive indicies indicate that a TNode with a given index should also be marked
23242 // as parent while executing `Select` instruction.
23243 createOpCodes.push((isElement ? phIndex : ~phIndex) << 3 /* SHIFT_REF */ |
23244 0 /* Select */, parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
23245 if (isElement) {
23246 parentIndexStack[++parentIndexPointer] = parentIndex = phIndex;
23247 }
23248 }
23249 }
23250 else {
23251 // Even indexes are text (including bindings & ICU expressions)
23252 const parts = extractParts(value);
23253 for (let j = 0; j < parts.length; j++) {
23254 if (j & 1) {
23255 // Odd indexes are ICU expressions
23256 const icuExpression = parts[j];
23257 // Verify that ICU expression has the right shape. Translations might contain invalid
23258 // constructions (while original messages were correct), so ICU parsing at runtime may
23259 // not succeed (thus `icuExpression` remains a string).
23260 if (typeof icuExpression !== 'object') {
23261 throw new Error(`Unable to parse ICU expression in "${templateTranslation}" message.`);
23262 }
23263 // Create the comment node that will anchor the ICU expression
23264 const icuNodeIndex = allocNodeIndex(startIndex);
23265 createOpCodes.push(COMMENT_MARKER, ngDevMode ? `ICU ${icuNodeIndex}` : '', icuNodeIndex, parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
23266 // Update codes for the ICU expression
23267 const mask = getBindingMask(icuExpression);
23268 icuStart(icuExpressions, icuExpression, icuNodeIndex, icuNodeIndex);
23269 // Since this is recursive, the last TIcu that was pushed is the one we want
23270 const tIcuIndex = icuExpressions.length - 1;
23271 updateOpCodes.push(toMaskBit(icuExpression.mainBinding), // mask of the main binding
23272 3, // skip 3 opCodes if not changed
23273 -1 - icuExpression.mainBinding, icuNodeIndex << 2 /* SHIFT_REF */ | 2 /* IcuSwitch */, tIcuIndex, mask, // mask of all the bindings of this ICU expression
23274 2, // skip 2 opCodes if not changed
23275 icuNodeIndex << 2 /* SHIFT_REF */ | 3 /* IcuUpdate */, tIcuIndex);
23276 }
23277 else if (parts[j] !== '') {
23278 const text = parts[j];
23279 // Even indexes are text (including bindings)
23280 const hasBinding = text.match(BINDING_REGEXP);
23281 // Create text nodes
23282 const textNodeIndex = allocNodeIndex(startIndex);
23283 createOpCodes.push(
23284 // If there is a binding, the value will be set during update
23285 hasBinding ? '' : text, textNodeIndex, parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
23286 if (hasBinding) {
23287 addAllToArray(generateBindingUpdateOpCodes(text, textNodeIndex), updateOpCodes);
23288 }
23289 }
23290 }
23291 }
23292 }
23293 }
23294 if (i18nVarsCount > 0) {
23295 allocExpando(tView, lView, i18nVarsCount);
23296 }
23297 // NOTE: local var needed to properly assert the type of `TI18n`.
23298 const tI18n = {
23299 vars: i18nVarsCount,
23300 create: createOpCodes,
23301 update: updateOpCodes,
23302 icus: icuExpressions.length ? icuExpressions : null,
23303 };
23304 tView.data[index + HEADER_OFFSET] = tI18n;
23305}
23306/**
23307 * See `i18nAttributes` above.
23308 */
23309function i18nAttributesFirstPass(lView, tView, index, values) {
23310 const previousElement = getPreviousOrParentTNode();
23311 const previousElementIndex = previousElement.index - HEADER_OFFSET;
23312 const updateOpCodes = [];
23313 if (ngDevMode) {
23314 attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString);
23315 }
23316 for (let i = 0; i < values.length; i += 2) {
23317 const attrName = values[i];
23318 const message = values[i + 1];
23319 const parts = message.split(ICU_REGEXP);
23320 for (let j = 0; j < parts.length; j++) {
23321 const value = parts[j];
23322 if (j & 1) {
23323 // Odd indexes are ICU expressions
23324 // TODO(ocombe): support ICU expressions in attributes
23325 throw new Error('ICU expressions are not yet supported in attributes');
23326 }
23327 else if (value !== '') {
23328 // Even indexes are text (including bindings)
23329 const hasBinding = !!value.match(BINDING_REGEXP);
23330 if (hasBinding) {
23331 if (tView.firstCreatePass && tView.data[index + HEADER_OFFSET] === null) {
23332 addAllToArray(generateBindingUpdateOpCodes(value, previousElementIndex, attrName), updateOpCodes);
23333 }
23334 }
23335 else {
23336 const tNode = getTNode(tView, previousElementIndex);
23337 // Set attributes for Elements only, for other types (like ElementContainer),
23338 // only set inputs below
23339 if (tNode.type === 3 /* Element */) {
23340 elementAttributeInternal(tNode, lView, attrName, value, null, null);
23341 }
23342 // Check if that attribute is a directive input
23343 const dataValue = tNode.inputs !== null && tNode.inputs[attrName];
23344 if (dataValue) {
23345 setInputsForProperty(tView, lView, dataValue, attrName, value);
23346 if (ngDevMode) {
23347 const element = getNativeByIndex(previousElementIndex, lView);
23348 setNgReflectProperties(lView, element, tNode.type, dataValue, value);
23349 }
23350 }
23351 }
23352 }
23353 }
23354 }
23355 if (tView.firstCreatePass && tView.data[index + HEADER_OFFSET] === null) {
23356 tView.data[index + HEADER_OFFSET] = updateOpCodes;
23357 }
23358}
23359/**
23360 * Generate the OpCodes to update the bindings of a string.
23361 *
23362 * @param str The string containing the bindings.
23363 * @param destinationNode Index of the destination node which will receive the binding.
23364 * @param attrName Name of the attribute, if the string belongs to an attribute.
23365 * @param sanitizeFn Sanitization function used to sanitize the string after update, if necessary.
23366 */
23367function generateBindingUpdateOpCodes(str, destinationNode, attrName, sanitizeFn = null) {
23368 const updateOpCodes = [null, null]; // Alloc space for mask and size
23369 if (ngDevMode) {
23370 attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString);
23371 }
23372 const textParts = str.split(BINDING_REGEXP);
23373 let mask = 0;
23374 for (let j = 0; j < textParts.length; j++) {
23375 const textValue = textParts[j];
23376 if (j & 1) {
23377 // Odd indexes are bindings
23378 const bindingIndex = parseInt(textValue, 10);
23379 updateOpCodes.push(-1 - bindingIndex);
23380 mask = mask | toMaskBit(bindingIndex);
23381 }
23382 else if (textValue !== '') {
23383 // Even indexes are text
23384 updateOpCodes.push(textValue);
23385 }
23386 }
23387 updateOpCodes.push(destinationNode << 2 /* SHIFT_REF */ |
23388 (attrName ? 1 /* Attr */ : 0 /* Text */));
23389 if (attrName) {
23390 updateOpCodes.push(attrName, sanitizeFn);
23391 }
23392 updateOpCodes[0] = mask;
23393 updateOpCodes[1] = updateOpCodes.length - 2;
23394 return updateOpCodes;
23395}
23396function getBindingMask(icuExpression, mask = 0) {
23397 mask = mask | toMaskBit(icuExpression.mainBinding);
23398 let match;
23399 for (let i = 0; i < icuExpression.values.length; i++) {
23400 const valueArr = icuExpression.values[i];
23401 for (let j = 0; j < valueArr.length; j++) {
23402 const value = valueArr[j];
23403 if (typeof value === 'string') {
23404 while (match = BINDING_REGEXP.exec(value)) {
23405 mask = mask | toMaskBit(parseInt(match[1], 10));
23406 }
23407 }
23408 else {
23409 mask = getBindingMask(value, mask);
23410 }
23411 }
23412 }
23413 return mask;
23414}
23415function allocNodeIndex(startIndex) {
23416 return startIndex + i18nVarsCount++;
23417}
23418/**
23419 * Convert binding index to mask bit.
23420 *
23421 * Each index represents a single bit on the bit-mask. Because bit-mask only has 32 bits, we make
23422 * the 32nd bit share all masks for all bindings higher than 32. Since it is extremely rare to have
23423 * more than 32 bindings this will be hit very rarely. The downside of hitting this corner case is
23424 * that we will execute binding code more often than necessary. (penalty of performance)
23425 */
23426function toMaskBit(bindingIndex) {
23427 return 1 << Math.min(bindingIndex, 31);
23428}
23429function isRootTemplateMessage(subTemplateIndex) {
23430 return subTemplateIndex === undefined;
23431}
23432/**
23433 * Removes everything inside the sub-templates of a message.
23434 */
23435function removeInnerTemplateTranslation(message) {
23436 let match;
23437 let res = '';
23438 let index = 0;
23439 let inTemplate = false;
23440 let tagMatched;
23441 while ((match = SUBTEMPLATE_REGEXP.exec(message)) !== null) {
23442 if (!inTemplate) {
23443 res += message.substring(index, match.index + match[0].length);
23444 tagMatched = match[1];
23445 inTemplate = true;
23446 }
23447 else {
23448 if (match[0] === `${MARKER}/*${tagMatched}${MARKER}`) {
23449 index = match.index;
23450 inTemplate = false;
23451 }
23452 }
23453 }
23454 ngDevMode &&
23455 assertEqual(inTemplate, false, `Tag mismatch: unable to find the end of the sub-template in the translation "${message}"`);
23456 res += message.substr(index);
23457 return res;
23458}
23459/**
23460 * Extracts a part of a message and removes the rest.
23461 *
23462 * This method is used for extracting a part of the message associated with a template. A translated
23463 * message can span multiple templates.
23464 *
23465 * Example:
23466 * ```
23467 * <div i18n>Translate <span *ngIf>me</span>!</div>
23468 * ```
23469 *
23470 * @param message The message to crop
23471 * @param subTemplateIndex Index of the sub-template to extract. If undefined it returns the
23472 * external template and removes all sub-templates.
23473 */
23474function getTranslationForTemplate(message, subTemplateIndex) {
23475 if (isRootTemplateMessage(subTemplateIndex)) {
23476 // We want the root template message, ignore all sub-templates
23477 return removeInnerTemplateTranslation(message);
23478 }
23479 else {
23480 // We want a specific sub-template
23481 const start = message.indexOf(`:${subTemplateIndex}${MARKER}`) + 2 + subTemplateIndex.toString().length;
23482 const end = message.search(new RegExp(`${MARKER}\\/\\*\\d+:${subTemplateIndex}${MARKER}`));
23483 return removeInnerTemplateTranslation(message.substring(start, end));
23484 }
23485}
23486/**
23487 * Generate the OpCodes for ICU expressions.
23488 *
23489 * @param tIcus
23490 * @param icuExpression
23491 * @param startIndex
23492 * @param expandoStartIndex
23493 */
23494function icuStart(tIcus, icuExpression, startIndex, expandoStartIndex) {
23495 const createCodes = [];
23496 const removeCodes = [];
23497 const updateCodes = [];
23498 const vars = [];
23499 const childIcus = [];
23500 const values = icuExpression.values;
23501 for (let i = 0; i < values.length; i++) {
23502 // Each value is an array of strings & other ICU expressions
23503 const valueArr = values[i];
23504 const nestedIcus = [];
23505 for (let j = 0; j < valueArr.length; j++) {
23506 const value = valueArr[j];
23507 if (typeof value !== 'string') {
23508 // It is an nested ICU expression
23509 const icuIndex = nestedIcus.push(value) - 1;
23510 // Replace nested ICU expression by a comment node
23511 valueArr[j] = `<!--�${icuIndex}�-->`;
23512 }
23513 }
23514 const icuCase = parseIcuCase(valueArr.join(''), startIndex, nestedIcus, tIcus, expandoStartIndex);
23515 createCodes.push(icuCase.create);
23516 removeCodes.push(icuCase.remove);
23517 updateCodes.push(icuCase.update);
23518 vars.push(icuCase.vars);
23519 childIcus.push(icuCase.childIcus);
23520 }
23521 const tIcu = {
23522 type: icuExpression.type,
23523 vars,
23524 currentCaseLViewIndex: HEADER_OFFSET +
23525 expandoStartIndex // expandoStartIndex does not include the header so add it.
23526 + 1,
23527 childIcus,
23528 cases: icuExpression.cases,
23529 create: createCodes,
23530 remove: removeCodes,
23531 update: updateCodes
23532 };
23533 tIcus.push(tIcu);
23534 // Adding the maximum possible of vars needed (based on the cases with the most vars)
23535 i18nVarsCount += Math.max(...vars);
23536}
23537/**
23538 * Parses text containing an ICU expression and produces a JSON object for it.
23539 * Original code from closure library, modified for Angular.
23540 *
23541 * @param pattern Text containing an ICU expression that needs to be parsed.
23542 *
23543 */
23544function parseICUBlock(pattern) {
23545 const cases = [];
23546 const values = [];
23547 let icuType = 1 /* plural */;
23548 let mainBinding = 0;
23549 pattern = pattern.replace(ICU_BLOCK_REGEXP, function (str, binding, type) {
23550 if (type === 'select') {
23551 icuType = 0 /* select */;
23552 }
23553 else {
23554 icuType = 1 /* plural */;
23555 }
23556 mainBinding = parseInt(binding.substr(1), 10);
23557 return '';
23558 });
23559 const parts = extractParts(pattern);
23560 // Looking for (key block)+ sequence. One of the keys has to be "other".
23561 for (let pos = 0; pos < parts.length;) {
23562 let key = parts[pos++].trim();
23563 if (icuType === 1 /* plural */) {
23564 // Key can be "=x", we just want "x"
23565 key = key.replace(/\s*(?:=)?(\w+)\s*/, '$1');
23566 }
23567 if (key.length) {
23568 cases.push(key);
23569 }
23570 const blocks = extractParts(parts[pos++]);
23571 if (cases.length > values.length) {
23572 values.push(blocks);
23573 }
23574 }
23575 // TODO(ocombe): support ICU expressions in attributes, see #21615
23576 return { type: icuType, mainBinding: mainBinding, cases, values };
23577}
23578/**
23579 * Transforms a string template into an HTML template and a list of instructions used to update
23580 * attributes or nodes that contain bindings.
23581 *
23582 * @param unsafeHtml The string to parse
23583 * @param parentIndex
23584 * @param nestedIcus
23585 * @param tIcus
23586 * @param expandoStartIndex
23587 */
23588function parseIcuCase(unsafeHtml, parentIndex, nestedIcus, tIcus, expandoStartIndex) {
23589 const inertBodyHelper = getInertBodyHelper(getDocument());
23590 const inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
23591 if (!inertBodyElement) {
23592 throw new Error('Unable to generate inert body element');
23593 }
23594 const wrapper = getTemplateContent(inertBodyElement) || inertBodyElement;
23595 const opCodes = {
23596 vars: 1,
23597 childIcus: [],
23598 create: [],
23599 remove: [],
23600 update: []
23601 };
23602 if (ngDevMode) {
23603 attachDebugGetter(opCodes.create, i18nMutateOpCodesToString);
23604 attachDebugGetter(opCodes.remove, i18nMutateOpCodesToString);
23605 attachDebugGetter(opCodes.update, i18nUpdateOpCodesToString);
23606 }
23607 parseNodes(wrapper.firstChild, opCodes, parentIndex, nestedIcus, tIcus, expandoStartIndex);
23608 return opCodes;
23609}
23610/**
23611 * Breaks pattern into strings and top level {...} blocks.
23612 * Can be used to break a message into text and ICU expressions, or to break an ICU expression into
23613 * keys and cases.
23614 * Original code from closure library, modified for Angular.
23615 *
23616 * @param pattern (sub)Pattern to be broken.
23617 *
23618 */
23619function extractParts(pattern) {
23620 if (!pattern) {
23621 return [];
23622 }
23623 let prevPos = 0;
23624 const braceStack = [];
23625 const results = [];
23626 const braces = /[{}]/g;
23627 // lastIndex doesn't get set to 0 so we have to.
23628 braces.lastIndex = 0;
23629 let match;
23630 while (match = braces.exec(pattern)) {
23631 const pos = match.index;
23632 if (match[0] == '}') {
23633 braceStack.pop();
23634 if (braceStack.length == 0) {
23635 // End of the block.
23636 const block = pattern.substring(prevPos, pos);
23637 if (ICU_BLOCK_REGEXP.test(block)) {
23638 results.push(parseICUBlock(block));
23639 }
23640 else {
23641 results.push(block);
23642 }
23643 prevPos = pos + 1;
23644 }
23645 }
23646 else {
23647 if (braceStack.length == 0) {
23648 const substring = pattern.substring(prevPos, pos);
23649 results.push(substring);
23650 prevPos = pos + 1;
23651 }
23652 braceStack.push('{');
23653 }
23654 }
23655 const substring = pattern.substring(prevPos);
23656 results.push(substring);
23657 return results;
23658}
23659/**
23660 * Parses a node, its children and its siblings, and generates the mutate & update OpCodes.
23661 *
23662 * @param currentNode The first node to parse
23663 * @param icuCase The data for the ICU expression case that contains those nodes
23664 * @param parentIndex Index of the current node's parent
23665 * @param nestedIcus Data for the nested ICU expressions that this case contains
23666 * @param tIcus Data for all ICU expressions of the current message
23667 * @param expandoStartIndex Expando start index for the current ICU expression
23668 */
23669function parseNodes(currentNode, icuCase, parentIndex, nestedIcus, tIcus, expandoStartIndex) {
23670 if (currentNode) {
23671 const nestedIcusToCreate = [];
23672 while (currentNode) {
23673 const nextNode = currentNode.nextSibling;
23674 const newIndex = expandoStartIndex + ++icuCase.vars;
23675 switch (currentNode.nodeType) {
23676 case Node.ELEMENT_NODE:
23677 const element = currentNode;
23678 const tagName = element.tagName.toLowerCase();
23679 if (!VALID_ELEMENTS.hasOwnProperty(tagName)) {
23680 // This isn't a valid element, we won't create an element for it
23681 icuCase.vars--;
23682 }
23683 else {
23684 icuCase.create.push(ELEMENT_MARKER, tagName, newIndex, parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
23685 const elAttrs = element.attributes;
23686 for (let i = 0; i < elAttrs.length; i++) {
23687 const attr = elAttrs.item(i);
23688 const lowerAttrName = attr.name.toLowerCase();
23689 const hasBinding = !!attr.value.match(BINDING_REGEXP);
23690 // we assume the input string is safe, unless it's using a binding
23691 if (hasBinding) {
23692 if (VALID_ATTRS.hasOwnProperty(lowerAttrName)) {
23693 if (URI_ATTRS[lowerAttrName]) {
23694 addAllToArray(generateBindingUpdateOpCodes(attr.value, newIndex, attr.name, _sanitizeUrl), icuCase.update);
23695 }
23696 else if (SRCSET_ATTRS[lowerAttrName]) {
23697 addAllToArray(generateBindingUpdateOpCodes(attr.value, newIndex, attr.name, sanitizeSrcset), icuCase.update);
23698 }
23699 else {
23700 addAllToArray(generateBindingUpdateOpCodes(attr.value, newIndex, attr.name), icuCase.update);
23701 }
23702 }
23703 else {
23704 ngDevMode &&
23705 console.warn(`WARNING: ignoring unsafe attribute value ${lowerAttrName} on element ${tagName} (see http://g.co/ng/security#xss)`);
23706 }
23707 }
23708 else {
23709 icuCase.create.push(newIndex << 3 /* SHIFT_REF */ | 4 /* Attr */, attr.name, attr.value);
23710 }
23711 }
23712 // Parse the children of this node (if any)
23713 parseNodes(currentNode.firstChild, icuCase, newIndex, nestedIcus, tIcus, expandoStartIndex);
23714 // Remove the parent node after the children
23715 icuCase.remove.push(newIndex << 3 /* SHIFT_REF */ | 3 /* Remove */);
23716 }
23717 break;
23718 case Node.TEXT_NODE:
23719 const value = currentNode.textContent || '';
23720 const hasBinding = value.match(BINDING_REGEXP);
23721 icuCase.create.push(hasBinding ? '' : value, newIndex, parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
23722 icuCase.remove.push(newIndex << 3 /* SHIFT_REF */ | 3 /* Remove */);
23723 if (hasBinding) {
23724 addAllToArray(generateBindingUpdateOpCodes(value, newIndex), icuCase.update);
23725 }
23726 break;
23727 case Node.COMMENT_NODE:
23728 // Check if the comment node is a placeholder for a nested ICU
23729 const match = NESTED_ICU.exec(currentNode.textContent || '');
23730 if (match) {
23731 const nestedIcuIndex = parseInt(match[1], 10);
23732 const newLocal = ngDevMode ? `nested ICU ${nestedIcuIndex}` : '';
23733 // Create the comment node that will anchor the ICU expression
23734 icuCase.create.push(COMMENT_MARKER, newLocal, newIndex, parentIndex << 17 /* SHIFT_PARENT */ | 1 /* AppendChild */);
23735 const nestedIcu = nestedIcus[nestedIcuIndex];
23736 nestedIcusToCreate.push([nestedIcu, newIndex]);
23737 }
23738 else {
23739 // We do not handle any other type of comment
23740 icuCase.vars--;
23741 }
23742 break;
23743 default:
23744 // We do not handle any other type of element
23745 icuCase.vars--;
23746 }
23747 currentNode = nextNode;
23748 }
23749 for (let i = 0; i < nestedIcusToCreate.length; i++) {
23750 const nestedIcu = nestedIcusToCreate[i][0];
23751 const nestedIcuNodeIndex = nestedIcusToCreate[i][1];
23752 icuStart(tIcus, nestedIcu, nestedIcuNodeIndex, expandoStartIndex + icuCase.vars);
23753 // Since this is recursive, the last TIcu that was pushed is the one we want
23754 const nestTIcuIndex = tIcus.length - 1;
23755 icuCase.vars += Math.max(...tIcus[nestTIcuIndex].vars);
23756 icuCase.childIcus.push(nestTIcuIndex);
23757 const mask = getBindingMask(nestedIcu);
23758 icuCase.update.push(toMaskBit(nestedIcu.mainBinding), // mask of the main binding
23759 3, // skip 3 opCodes if not changed
23760 -1 - nestedIcu.mainBinding, nestedIcuNodeIndex << 2 /* SHIFT_REF */ | 2 /* IcuSwitch */,
23761 // FIXME(misko): Index should be part of the opcode
23762 nestTIcuIndex, mask, // mask of all the bindings of this ICU expression
23763 2, // skip 2 opCodes if not changed
23764 nestedIcuNodeIndex << 2 /* SHIFT_REF */ | 3 /* IcuUpdate */, nestTIcuIndex);
23765 icuCase.remove.push(nestTIcuIndex << 3 /* SHIFT_REF */ | 6 /* RemoveNestedIcu */,
23766 // FIXME(misko): Index should be part of the opcode
23767 nestedIcuNodeIndex << 3 /* SHIFT_REF */ | 3 /* Remove */);
23768 }
23769 }
23770}
23771
23772/**
23773 * @license
23774 * Copyright Google LLC All Rights Reserved.
23775 *
23776 * Use of this source code is governed by an MIT-style license that can be
23777 * found in the LICENSE file at https://angular.io/license
23778 */
23779// i18nPostprocess consts
23780const ROOT_TEMPLATE_ID = 0;
23781const PP_MULTI_VALUE_PLACEHOLDERS_REGEXP = /\[(�.+?�?)\]/;
23782const PP_PLACEHOLDERS_REGEXP = /\[(�.+?�?)\]|(�\/?\*\d+:\d+�)/g;
23783const PP_ICU_VARS_REGEXP = /({\s*)(VAR_(PLURAL|SELECT)(_\d+)?)(\s*,)/g;
23784const PP_ICU_PLACEHOLDERS_REGEXP = /{([A-Z0-9_]+)}/g;
23785const PP_ICUS_REGEXP = /�I18N_EXP_(ICU(_\d+)?)�/g;
23786const PP_CLOSE_TEMPLATE_REGEXP = /\/\*/;
23787const PP_TEMPLATE_ID_REGEXP = /\d+\:(\d+)/;
23788/**
23789 * Handles message string post-processing for internationalization.
23790 *
23791 * Handles message string post-processing by transforming it from intermediate
23792 * format (that might contain some markers that we need to replace) to the final
23793 * form, consumable by i18nStart instruction. Post processing steps include:
23794 *
23795 * 1. Resolve all multi-value cases (like [�*1:1��#2:1�|�#4:1�|�5�])
23796 * 2. Replace all ICU vars (like "VAR_PLURAL")
23797 * 3. Replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
23798 * 4. Replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�)
23799 * in case multiple ICUs have the same placeholder name
23800 *
23801 * @param message Raw translation string for post processing
23802 * @param replacements Set of replacements that should be applied
23803 *
23804 * @returns Transformed string that can be consumed by i18nStart instruction
23805 *
23806 * @codeGenApi
23807 */
23808function i18nPostprocess(message, replacements = {}) {
23809 /**
23810 * Step 1: resolve all multi-value placeholders like [�#5�|�*1:1��#2:1�|�#4:1�]
23811 *
23812 * Note: due to the way we process nested templates (BFS), multi-value placeholders are typically
23813 * grouped by templates, for example: [�#5�|�#6�|�#1:1�|�#3:2�] where �#5� and �#6� belong to root
23814 * template, �#1:1� belong to nested template with index 1 and �#1:2� - nested template with index
23815 * 3. However in real templates the order might be different: i.e. �#1:1� and/or �#3:2� may go in
23816 * front of �#6�. The post processing step restores the right order by keeping track of the
23817 * template id stack and looks for placeholders that belong to the currently active template.
23818 */
23819 let result = message;
23820 if (PP_MULTI_VALUE_PLACEHOLDERS_REGEXP.test(message)) {
23821 const matches = {};
23822 const templateIdsStack = [ROOT_TEMPLATE_ID];
23823 result = result.replace(PP_PLACEHOLDERS_REGEXP, (m, phs, tmpl) => {
23824 const content = phs || tmpl;
23825 const placeholders = matches[content] || [];
23826 if (!placeholders.length) {
23827 content.split('|').forEach((placeholder) => {
23828 const match = placeholder.match(PP_TEMPLATE_ID_REGEXP);
23829 const templateId = match ? parseInt(match[1], 10) : ROOT_TEMPLATE_ID;
23830 const isCloseTemplateTag = PP_CLOSE_TEMPLATE_REGEXP.test(placeholder);
23831 placeholders.push([templateId, isCloseTemplateTag, placeholder]);
23832 });
23833 matches[content] = placeholders;
23834 }
23835 if (!placeholders.length) {
23836 throw new Error(`i18n postprocess: unmatched placeholder - ${content}`);
23837 }
23838 const currentTemplateId = templateIdsStack[templateIdsStack.length - 1];
23839 let idx = 0;
23840 // find placeholder index that matches current template id
23841 for (let i = 0; i < placeholders.length; i++) {
23842 if (placeholders[i][0] === currentTemplateId) {
23843 idx = i;
23844 break;
23845 }
23846 }
23847 // update template id stack based on the current tag extracted
23848 const [templateId, isCloseTemplateTag, placeholder] = placeholders[idx];
23849 if (isCloseTemplateTag) {
23850 templateIdsStack.pop();
23851 }
23852 else if (currentTemplateId !== templateId) {
23853 templateIdsStack.push(templateId);
23854 }
23855 // remove processed tag from the list
23856 placeholders.splice(idx, 1);
23857 return placeholder;
23858 });
23859 }
23860 // return current result if no replacements specified
23861 if (!Object.keys(replacements).length) {
23862 return result;
23863 }
23864 /**
23865 * Step 2: replace all ICU vars (like "VAR_PLURAL")
23866 */
23867 result = result.replace(PP_ICU_VARS_REGEXP, (match, start, key, _type, _idx, end) => {
23868 return replacements.hasOwnProperty(key) ? `${start}${replacements[key]}${end}` : match;
23869 });
23870 /**
23871 * Step 3: replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
23872 */
23873 result = result.replace(PP_ICU_PLACEHOLDERS_REGEXP, (match, key) => {
23874 return replacements.hasOwnProperty(key) ? replacements[key] : match;
23875 });
23876 /**
23877 * Step 4: replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�) in case
23878 * multiple ICUs have the same placeholder name
23879 */
23880 result = result.replace(PP_ICUS_REGEXP, (match, key) => {
23881 if (replacements.hasOwnProperty(key)) {
23882 const list = replacements[key];
23883 if (!list.length) {
23884 throw new Error(`i18n postprocess: unmatched ICU - ${match} with key: ${key}`);
23885 }
23886 return list.shift();
23887 }
23888 return match;
23889 });
23890 return result;
23891}
23892
23893/**
23894 * @license
23895 * Copyright Google LLC All Rights Reserved.
23896 *
23897 * Use of this source code is governed by an MIT-style license that can be
23898 * found in the LICENSE file at https://angular.io/license
23899 */
23900/**
23901 * Marks a block of text as translatable.
23902 *
23903 * The instructions `i18nStart` and `i18nEnd` mark the translation block in the template.
23904 * The translation `message` is the value which is locale specific. The translation string may
23905 * contain placeholders which associate inner elements and sub-templates within the translation.
23906 *
23907 * The translation `message` placeholders are:
23908 * - `�{index}(:{block})�`: *Binding Placeholder*: Marks a location where an expression will be
23909 * interpolated into. The placeholder `index` points to the expression binding index. An optional
23910 * `block` that matches the sub-template in which it was declared.
23911 * - `�#{index}(:{block})�`/`�/#{index}(:{block})�`: *Element Placeholder*: Marks the beginning
23912 * and end of DOM element that were embedded in the original translation block. The placeholder
23913 * `index` points to the element index in the template instructions set. An optional `block` that
23914 * matches the sub-template in which it was declared.
23915 * - `�!{index}(:{block})�`/`�/!{index}(:{block})�`: *Projection Placeholder*: Marks the
23916 * beginning and end of <ng-content> that was embedded in the original translation block.
23917 * The placeholder `index` points to the element index in the template instructions set.
23918 * An optional `block` that matches the sub-template in which it was declared.
23919 * - `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template Placeholder*: Sub-templates must be
23920 * split up and translated separately in each angular template function. The `index` points to the
23921 * `template` instruction index. A `block` that matches the sub-template in which it was declared.
23922 *
23923 * @param index A unique index of the translation in the static block.
23924 * @param message The translation message.
23925 * @param subTemplateIndex Optional sub-template index in the `message`.
23926 *
23927 * @codeGenApi
23928 */
23929function ɵɵi18nStart(index, message, subTemplateIndex) {
23930 const tView = getTView();
23931 ngDevMode && assertDefined(tView, `tView should be defined`);
23932 pushI18nIndex(index);
23933 // We need to delay projections until `i18nEnd`
23934 setDelayProjection(true);
23935 if (tView.firstCreatePass && tView.data[index + HEADER_OFFSET] === null) {
23936 i18nStartFirstPass(getLView(), tView, index, message, subTemplateIndex);
23937 }
23938}
23939/**
23940 * Translates a translation block marked by `i18nStart` and `i18nEnd`. It inserts the text/ICU nodes
23941 * into the render tree, moves the placeholder nodes and removes the deleted nodes.
23942 *
23943 * @codeGenApi
23944 */
23945function ɵɵi18nEnd() {
23946 const lView = getLView();
23947 const tView = getTView();
23948 ngDevMode && assertDefined(tView, `tView should be defined`);
23949 i18nEndFirstPass(tView, lView);
23950 // Stop delaying projections
23951 setDelayProjection(false);
23952}
23953/**
23954 *
23955 * Use this instruction to create a translation block that doesn't contain any placeholder.
23956 * It calls both {@link i18nStart} and {@link i18nEnd} in one instruction.
23957 *
23958 * The translation `message` is the value which is locale specific. The translation string may
23959 * contain placeholders which associate inner elements and sub-templates within the translation.
23960 *
23961 * The translation `message` placeholders are:
23962 * - `�{index}(:{block})�`: *Binding Placeholder*: Marks a location where an expression will be
23963 * interpolated into. The placeholder `index` points to the expression binding index. An optional
23964 * `block` that matches the sub-template in which it was declared.
23965 * - `�#{index}(:{block})�`/`�/#{index}(:{block})�`: *Element Placeholder*: Marks the beginning
23966 * and end of DOM element that were embedded in the original translation block. The placeholder
23967 * `index` points to the element index in the template instructions set. An optional `block` that
23968 * matches the sub-template in which it was declared.
23969 * - `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template Placeholder*: Sub-templates must be
23970 * split up and translated separately in each angular template function. The `index` points to the
23971 * `template` instruction index. A `block` that matches the sub-template in which it was declared.
23972 *
23973 * @param index A unique index of the translation in the static block.
23974 * @param message The translation message.
23975 * @param subTemplateIndex Optional sub-template index in the `message`.
23976 *
23977 * @codeGenApi
23978 */
23979function ɵɵi18n(index, message, subTemplateIndex) {
23980 ɵɵi18nStart(index, message, subTemplateIndex);
23981 ɵɵi18nEnd();
23982}
23983/**
23984 * Marks a list of attributes as translatable.
23985 *
23986 * @param index A unique index in the static block
23987 * @param values
23988 *
23989 * @codeGenApi
23990 */
23991function ɵɵi18nAttributes(index, values) {
23992 const lView = getLView();
23993 const tView = getTView();
23994 ngDevMode && assertDefined(tView, `tView should be defined`);
23995 i18nAttributesFirstPass(lView, tView, index, values);
23996}
23997/**
23998 * Stores the values of the bindings during each update cycle in order to determine if we need to
23999 * update the translated nodes.
24000 *
24001 * @param value The binding's value
24002 * @returns This function returns itself so that it may be chained
24003 * (e.g. `i18nExp(ctx.name)(ctx.title)`)
24004 *
24005 * @codeGenApi
24006 */
24007function ɵɵi18nExp(value) {
24008 const lView = getLView();
24009 setMaskBit(bindingUpdated(lView, nextBindingIndex(), value));
24010 return ɵɵi18nExp;
24011}
24012/**
24013 * Updates a translation block or an i18n attribute when the bindings have changed.
24014 *
24015 * @param index Index of either {@link i18nStart} (translation block) or {@link i18nAttributes}
24016 * (i18n attribute) on which it should update the content.
24017 *
24018 * @codeGenApi
24019 */
24020function ɵɵi18nApply(index) {
24021 applyI18n(getTView(), getLView(), index);
24022}
24023/**
24024 * Handles message string post-processing for internationalization.
24025 *
24026 * Handles message string post-processing by transforming it from intermediate
24027 * format (that might contain some markers that we need to replace) to the final
24028 * form, consumable by i18nStart instruction. Post processing steps include:
24029 *
24030 * 1. Resolve all multi-value cases (like [�*1:1��#2:1�|�#4:1�|�5�])
24031 * 2. Replace all ICU vars (like "VAR_PLURAL")
24032 * 3. Replace all placeholders used inside ICUs in a form of {PLACEHOLDER}
24033 * 4. Replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�)
24034 * in case multiple ICUs have the same placeholder name
24035 *
24036 * @param message Raw translation string for post processing
24037 * @param replacements Set of replacements that should be applied
24038 *
24039 * @returns Transformed string that can be consumed by i18nStart instruction
24040 *
24041 * @codeGenApi
24042 */
24043function ɵɵi18nPostprocess(message, replacements = {}) {
24044 return i18nPostprocess(message, replacements);
24045}
24046
24047/**
24048 * @license
24049 * Copyright Google LLC All Rights Reserved.
24050 *
24051 * Use of this source code is governed by an MIT-style license that can be
24052 * found in the LICENSE file at https://angular.io/license
24053 */
24054/**
24055 * Adds decorator, constructor, and property metadata to a given type via static metadata fields
24056 * on the type.
24057 *
24058 * These metadata fields can later be read with Angular's `ReflectionCapabilities` API.
24059 *
24060 * Calls to `setClassMetadata` can be marked as pure, resulting in the metadata assignments being
24061 * tree-shaken away during production builds.
24062 */
24063function setClassMetadata(type, decorators, ctorParameters, propDecorators) {
24064 return noSideEffects(() => {
24065 const clazz = type;
24066 // We determine whether a class has its own metadata by taking the metadata from the
24067 // parent constructor and checking whether it's the same as the subclass metadata below.
24068 // We can't use `hasOwnProperty` here because it doesn't work correctly in IE10 for
24069 // static fields that are defined by TS. See
24070 // https://github.com/angular/angular/pull/28439#issuecomment-459349218.
24071 const parentPrototype = clazz.prototype ? Object.getPrototypeOf(clazz.prototype) : null;
24072 const parentConstructor = parentPrototype && parentPrototype.constructor;
24073 if (decorators !== null) {
24074 if (clazz.decorators !== undefined &&
24075 (!parentConstructor || parentConstructor.decorators !== clazz.decorators)) {
24076 clazz.decorators.push(...decorators);
24077 }
24078 else {
24079 clazz.decorators = decorators;
24080 }
24081 }
24082 if (ctorParameters !== null) {
24083 // Rather than merging, clobber the existing parameters. If other projects exist which
24084 // use tsickle-style annotations and reflect over them in the same way, this could
24085 // cause issues, but that is vanishingly unlikely.
24086 clazz.ctorParameters = ctorParameters;
24087 }
24088 if (propDecorators !== null) {
24089 // The property decorator objects are merged as it is possible different fields have
24090 // different decorator types. Decorators on individual fields are not merged, as it's
24091 // also incredibly unlikely that a field will be decorated both with an Angular
24092 // decorator and a non-Angular decorator that's also been downleveled.
24093 if (clazz.propDecorators !== undefined &&
24094 (!parentConstructor ||
24095 parentConstructor.propDecorators !== clazz.propDecorators)) {
24096 clazz.propDecorators = Object.assign(Object.assign({}, clazz.propDecorators), propDecorators);
24097 }
24098 else {
24099 clazz.propDecorators = propDecorators;
24100 }
24101 }
24102 });
24103}
24104
24105/**
24106 * @license
24107 * Copyright Google LLC All Rights Reserved.
24108 *
24109 * Use of this source code is governed by an MIT-style license that can be
24110 * found in the LICENSE file at https://angular.io/license
24111 */
24112/**
24113 * Map of module-id to the corresponding NgModule.
24114 * - In pre Ivy we track NgModuleFactory,
24115 * - In post Ivy we track the NgModuleType
24116 */
24117const modules = new Map();
24118/**
24119 * Registers a loaded module. Should only be called from generated NgModuleFactory code.
24120 * @publicApi
24121 */
24122function registerModuleFactory(id, factory) {
24123 const existing = modules.get(id);
24124 assertSameOrNotExisting(id, existing && existing.moduleType, factory.moduleType);
24125 modules.set(id, factory);
24126}
24127function assertSameOrNotExisting(id, type, incoming) {
24128 if (type && type !== incoming) {
24129 throw new Error(`Duplicate module registered for ${id} - ${stringify(type)} vs ${stringify(type.name)}`);
24130 }
24131}
24132function registerNgModuleType(ngModuleType) {
24133 if (ngModuleType.ɵmod.id !== null) {
24134 const id = ngModuleType.ɵmod.id;
24135 const existing = modules.get(id);
24136 assertSameOrNotExisting(id, existing, ngModuleType);
24137 modules.set(id, ngModuleType);
24138 }
24139 let imports = ngModuleType.ɵmod.imports;
24140 if (imports instanceof Function) {
24141 imports = imports();
24142 }
24143 if (imports) {
24144 imports.forEach(i => registerNgModuleType(i));
24145 }
24146}
24147function clearModulesForTest() {
24148 modules.clear();
24149}
24150function getRegisteredNgModuleType(id) {
24151 return modules.get(id) || autoRegisterModuleById[id];
24152}
24153
24154/**
24155 * @license
24156 * Copyright Google LLC All Rights Reserved.
24157 *
24158 * Use of this source code is governed by an MIT-style license that can be
24159 * found in the LICENSE file at https://angular.io/license
24160 */
24161class NgModuleRef$1 extends NgModuleRef {
24162 constructor(ngModuleType, _parent) {
24163 super();
24164 this._parent = _parent;
24165 // tslint:disable-next-line:require-internal-with-underscore
24166 this._bootstrapComponents = [];
24167 this.injector = this;
24168 this.destroyCbs = [];
24169 // When bootstrapping a module we have a dependency graph that looks like this:
24170 // ApplicationRef -> ComponentFactoryResolver -> NgModuleRef. The problem is that if the
24171 // module being resolved tries to inject the ComponentFactoryResolver, it'll create a
24172 // circular dependency which will result in a runtime error, because the injector doesn't
24173 // exist yet. We work around the issue by creating the ComponentFactoryResolver ourselves
24174 // and providing it, rather than letting the injector resolve it.
24175 this.componentFactoryResolver = new ComponentFactoryResolver$1(this);
24176 const ngModuleDef = getNgModuleDef(ngModuleType);
24177 ngDevMode &&
24178 assertDefined(ngModuleDef, `NgModule '${stringify(ngModuleType)}' is not a subtype of 'NgModuleType'.`);
24179 const ngLocaleIdDef = getNgLocaleIdDef(ngModuleType);
24180 ngLocaleIdDef && setLocaleId(ngLocaleIdDef);
24181 this._bootstrapComponents = maybeUnwrapFn(ngModuleDef.bootstrap);
24182 this._r3Injector = createInjectorWithoutInjectorInstances(ngModuleType, _parent, [
24183 { provide: NgModuleRef, useValue: this }, {
24184 provide: ComponentFactoryResolver,
24185 useValue: this.componentFactoryResolver
24186 }
24187 ], stringify(ngModuleType));
24188 // We need to resolve the injector types separately from the injector creation, because
24189 // the module might be trying to use this ref in its contructor for DI which will cause a
24190 // circular error that will eventually error out, because the injector isn't created yet.
24191 this._r3Injector._resolveInjectorDefTypes();
24192 this.instance = this.get(ngModuleType);
24193 }
24194 get(token, notFoundValue = Injector.THROW_IF_NOT_FOUND, injectFlags = InjectFlags.Default) {
24195 if (token === Injector || token === NgModuleRef || token === INJECTOR) {
24196 return this;
24197 }
24198 return this._r3Injector.get(token, notFoundValue, injectFlags);
24199 }
24200 destroy() {
24201 ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
24202 const injector = this._r3Injector;
24203 !injector.destroyed && injector.destroy();
24204 this.destroyCbs.forEach(fn => fn());
24205 this.destroyCbs = null;
24206 }
24207 onDestroy(callback) {
24208 ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed');
24209 this.destroyCbs.push(callback);
24210 }
24211}
24212class NgModuleFactory$1 extends NgModuleFactory {
24213 constructor(moduleType) {
24214 super();
24215 this.moduleType = moduleType;
24216 const ngModuleDef = getNgModuleDef(moduleType);
24217 if (ngModuleDef !== null) {
24218 // Register the NgModule with Angular's module registry. The location (and hence timing) of
24219 // this call is critical to ensure this works correctly (modules get registered when expected)
24220 // without bloating bundles (modules are registered when otherwise not referenced).
24221 //
24222 // In View Engine, registration occurs in the .ngfactory.js file as a side effect. This has
24223 // several practical consequences:
24224 //
24225 // - If an .ngfactory file is not imported from, the module won't be registered (and can be
24226 // tree shaken).
24227 // - If an .ngfactory file is imported from, the module will be registered even if an instance
24228 // is not actually created (via `create` below).
24229 // - Since an .ngfactory file in View Engine references the .ngfactory files of the NgModule's
24230 // imports,
24231 //
24232 // In Ivy, things are a bit different. .ngfactory files still exist for compatibility, but are
24233 // not a required API to use - there are other ways to obtain an NgModuleFactory for a given
24234 // NgModule. Thus, relying on a side effect in the .ngfactory file is not sufficient. Instead,
24235 // the side effect of registration is added here, in the constructor of NgModuleFactory,
24236 // ensuring no matter how a factory is created, the module is registered correctly.
24237 //
24238 // An alternative would be to include the registration side effect inline following the actual
24239 // NgModule definition. This also has the correct timing, but breaks tree-shaking - modules
24240 // will be registered and retained even if they're otherwise never referenced.
24241 registerNgModuleType(moduleType);
24242 }
24243 }
24244 create(parentInjector) {
24245 return new NgModuleRef$1(this.moduleType, parentInjector);
24246 }
24247}
24248
24249/**
24250 * @license
24251 * Copyright Google LLC All Rights Reserved.
24252 *
24253 * Use of this source code is governed by an MIT-style license that can be
24254 * found in the LICENSE file at https://angular.io/license
24255 */
24256/**
24257 * Bindings for pure functions are stored after regular bindings.
24258 *
24259 * |-------decls------|---------vars---------| |----- hostVars (dir1) ------|
24260 * ------------------------------------------------------------------------------------------
24261 * | nodes/refs/pipes | bindings | fn slots | injector | dir1 | host bindings | host slots |
24262 * ------------------------------------------------------------------------------------------
24263 * ^ ^
24264 * TView.bindingStartIndex TView.expandoStartIndex
24265 *
24266 * Pure function instructions are given an offset from the binding root. Adding the offset to the
24267 * binding root gives the first index where the bindings are stored. In component views, the binding
24268 * root is the bindingStartIndex. In host bindings, the binding root is the expandoStartIndex +
24269 * any directive instances + any hostVars in directives evaluated before it.
24270 *
24271 * See VIEW_DATA.md for more information about host binding resolution.
24272 */
24273/**
24274 * If the value hasn't been saved, calls the pure function to store and return the
24275 * value. If it has been saved, returns the saved value.
24276 *
24277 * @param slotOffset the offset from binding root to the reserved slot
24278 * @param pureFn Function that returns a value
24279 * @param thisArg Optional calling context of pureFn
24280 * @returns value
24281 *
24282 * @codeGenApi
24283 */
24284function ɵɵpureFunction0(slotOffset, pureFn, thisArg) {
24285 const bindingIndex = getBindingRoot() + slotOffset;
24286 const lView = getLView();
24287 return lView[bindingIndex] === NO_CHANGE ?
24288 updateBinding(lView, bindingIndex, thisArg ? pureFn.call(thisArg) : pureFn()) :
24289 getBinding(lView, bindingIndex);
24290}
24291/**
24292 * If the value of the provided exp has changed, calls the pure function to return
24293 * an updated value. Or if the value has not changed, returns cached value.
24294 *
24295 * @param slotOffset the offset from binding root to the reserved slot
24296 * @param pureFn Function that returns an updated value
24297 * @param exp Updated expression value
24298 * @param thisArg Optional calling context of pureFn
24299 * @returns Updated or cached value
24300 *
24301 * @codeGenApi
24302 */
24303function ɵɵpureFunction1(slotOffset, pureFn, exp, thisArg) {
24304 return pureFunction1Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp, thisArg);
24305}
24306/**
24307 * If the value of any provided exp has changed, calls the pure function to return
24308 * an updated value. Or if no values have changed, returns cached value.
24309 *
24310 * @param slotOffset the offset from binding root to the reserved slot
24311 * @param pureFn
24312 * @param exp1
24313 * @param exp2
24314 * @param thisArg Optional calling context of pureFn
24315 * @returns Updated or cached value
24316 *
24317 * @codeGenApi
24318 */
24319function ɵɵpureFunction2(slotOffset, pureFn, exp1, exp2, thisArg) {
24320 return pureFunction2Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, thisArg);
24321}
24322/**
24323 * If the value of any provided exp has changed, calls the pure function to return
24324 * an updated value. Or if no values have changed, returns cached value.
24325 *
24326 * @param slotOffset the offset from binding root to the reserved slot
24327 * @param pureFn
24328 * @param exp1
24329 * @param exp2
24330 * @param exp3
24331 * @param thisArg Optional calling context of pureFn
24332 * @returns Updated or cached value
24333 *
24334 * @codeGenApi
24335 */
24336function ɵɵpureFunction3(slotOffset, pureFn, exp1, exp2, exp3, thisArg) {
24337 return pureFunction3Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, exp3, thisArg);
24338}
24339/**
24340 * If the value of any provided exp has changed, calls the pure function to return
24341 * an updated value. Or if no values have changed, returns cached value.
24342 *
24343 * @param slotOffset the offset from binding root to the reserved slot
24344 * @param pureFn
24345 * @param exp1
24346 * @param exp2
24347 * @param exp3
24348 * @param exp4
24349 * @param thisArg Optional calling context of pureFn
24350 * @returns Updated or cached value
24351 *
24352 * @codeGenApi
24353 */
24354function ɵɵpureFunction4(slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg) {
24355 return pureFunction4Internal(getLView(), getBindingRoot(), slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg);
24356}
24357/**
24358 * If the value of any provided exp has changed, calls the pure function to return
24359 * an updated value. Or if no values have changed, returns cached value.
24360 *
24361 * @param slotOffset the offset from binding root to the reserved slot
24362 * @param pureFn
24363 * @param exp1
24364 * @param exp2
24365 * @param exp3
24366 * @param exp4
24367 * @param exp5
24368 * @param thisArg Optional calling context of pureFn
24369 * @returns Updated or cached value
24370 *
24371 * @codeGenApi
24372 */
24373function ɵɵpureFunction5(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, thisArg) {
24374 const bindingIndex = getBindingRoot() + slotOffset;
24375 const lView = getLView();
24376 const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
24377 return bindingUpdated(lView, bindingIndex + 4, exp5) || different ?
24378 updateBinding(lView, bindingIndex + 5, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5) :
24379 pureFn(exp1, exp2, exp3, exp4, exp5)) :
24380 getBinding(lView, bindingIndex + 5);
24381}
24382/**
24383 * If the value of any provided exp has changed, calls the pure function to return
24384 * an updated value. Or if no values have changed, returns cached value.
24385 *
24386 * @param slotOffset the offset from binding root to the reserved slot
24387 * @param pureFn
24388 * @param exp1
24389 * @param exp2
24390 * @param exp3
24391 * @param exp4
24392 * @param exp5
24393 * @param exp6
24394 * @param thisArg Optional calling context of pureFn
24395 * @returns Updated or cached value
24396 *
24397 * @codeGenApi
24398 */
24399function ɵɵpureFunction6(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, thisArg) {
24400 const bindingIndex = getBindingRoot() + slotOffset;
24401 const lView = getLView();
24402 const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
24403 return bindingUpdated2(lView, bindingIndex + 4, exp5, exp6) || different ?
24404 updateBinding(lView, bindingIndex + 6, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6) :
24405 pureFn(exp1, exp2, exp3, exp4, exp5, exp6)) :
24406 getBinding(lView, bindingIndex + 6);
24407}
24408/**
24409 * If the value of any provided exp has changed, calls the pure function to return
24410 * an updated value. Or if no values have changed, returns cached value.
24411 *
24412 * @param slotOffset the offset from binding root to the reserved slot
24413 * @param pureFn
24414 * @param exp1
24415 * @param exp2
24416 * @param exp3
24417 * @param exp4
24418 * @param exp5
24419 * @param exp6
24420 * @param exp7
24421 * @param thisArg Optional calling context of pureFn
24422 * @returns Updated or cached value
24423 *
24424 * @codeGenApi
24425 */
24426function ɵɵpureFunction7(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, exp7, thisArg) {
24427 const bindingIndex = getBindingRoot() + slotOffset;
24428 const lView = getLView();
24429 let different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
24430 return bindingUpdated3(lView, bindingIndex + 4, exp5, exp6, exp7) || different ?
24431 updateBinding(lView, bindingIndex + 7, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7) :
24432 pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7)) :
24433 getBinding(lView, bindingIndex + 7);
24434}
24435/**
24436 * If the value of any provided exp has changed, calls the pure function to return
24437 * an updated value. Or if no values have changed, returns cached value.
24438 *
24439 * @param slotOffset the offset from binding root to the reserved slot
24440 * @param pureFn
24441 * @param exp1
24442 * @param exp2
24443 * @param exp3
24444 * @param exp4
24445 * @param exp5
24446 * @param exp6
24447 * @param exp7
24448 * @param exp8
24449 * @param thisArg Optional calling context of pureFn
24450 * @returns Updated or cached value
24451 *
24452 * @codeGenApi
24453 */
24454function ɵɵpureFunction8(slotOffset, pureFn, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8, thisArg) {
24455 const bindingIndex = getBindingRoot() + slotOffset;
24456 const lView = getLView();
24457 const different = bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4);
24458 return bindingUpdated4(lView, bindingIndex + 4, exp5, exp6, exp7, exp8) || different ?
24459 updateBinding(lView, bindingIndex + 8, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8) :
24460 pureFn(exp1, exp2, exp3, exp4, exp5, exp6, exp7, exp8)) :
24461 getBinding(lView, bindingIndex + 8);
24462}
24463/**
24464 * pureFunction instruction that can support any number of bindings.
24465 *
24466 * If the value of any provided exp has changed, calls the pure function to return
24467 * an updated value. Or if no values have changed, returns cached value.
24468 *
24469 * @param slotOffset the offset from binding root to the reserved slot
24470 * @param pureFn A pure function that takes binding values and builds an object or array
24471 * containing those values.
24472 * @param exps An array of binding values
24473 * @param thisArg Optional calling context of pureFn
24474 * @returns Updated or cached value
24475 *
24476 * @codeGenApi
24477 */
24478function ɵɵpureFunctionV(slotOffset, pureFn, exps, thisArg) {
24479 return pureFunctionVInternal(getLView(), getBindingRoot(), slotOffset, pureFn, exps, thisArg);
24480}
24481/**
24482 * Results of a pure function invocation are stored in LView in a dedicated slot that is initialized
24483 * to NO_CHANGE. In rare situations a pure pipe might throw an exception on the very first
24484 * invocation and not produce any valid results. In this case LView would keep holding the NO_CHANGE
24485 * value. The NO_CHANGE is not something that we can use in expressions / bindings thus we convert
24486 * it to `undefined`.
24487 */
24488function getPureFunctionReturnValue(lView, returnValueIndex) {
24489 ngDevMode && assertIndexInRange(lView, returnValueIndex);
24490 const lastReturnValue = lView[returnValueIndex];
24491 return lastReturnValue === NO_CHANGE ? undefined : lastReturnValue;
24492}
24493/**
24494 * If the value of the provided exp has changed, calls the pure function to return
24495 * an updated value. Or if the value has not changed, returns cached value.
24496 *
24497 * @param lView LView in which the function is being executed.
24498 * @param bindingRoot Binding root index.
24499 * @param slotOffset the offset from binding root to the reserved slot
24500 * @param pureFn Function that returns an updated value
24501 * @param exp Updated expression value
24502 * @param thisArg Optional calling context of pureFn
24503 * @returns Updated or cached value
24504 */
24505function pureFunction1Internal(lView, bindingRoot, slotOffset, pureFn, exp, thisArg) {
24506 const bindingIndex = bindingRoot + slotOffset;
24507 return bindingUpdated(lView, bindingIndex, exp) ?
24508 updateBinding(lView, bindingIndex + 1, thisArg ? pureFn.call(thisArg, exp) : pureFn(exp)) :
24509 getPureFunctionReturnValue(lView, bindingIndex + 1);
24510}
24511/**
24512 * If the value of any provided exp has changed, calls the pure function to return
24513 * an updated value. Or if no values have changed, returns cached value.
24514 *
24515 * @param lView LView in which the function is being executed.
24516 * @param bindingRoot Binding root index.
24517 * @param slotOffset the offset from binding root to the reserved slot
24518 * @param pureFn
24519 * @param exp1
24520 * @param exp2
24521 * @param thisArg Optional calling context of pureFn
24522 * @returns Updated or cached value
24523 */
24524function pureFunction2Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, thisArg) {
24525 const bindingIndex = bindingRoot + slotOffset;
24526 return bindingUpdated2(lView, bindingIndex, exp1, exp2) ?
24527 updateBinding(lView, bindingIndex + 2, thisArg ? pureFn.call(thisArg, exp1, exp2) : pureFn(exp1, exp2)) :
24528 getPureFunctionReturnValue(lView, bindingIndex + 2);
24529}
24530/**
24531 * If the value of any provided exp has changed, calls the pure function to return
24532 * an updated value. Or if no values have changed, returns cached value.
24533 *
24534 * @param lView LView in which the function is being executed.
24535 * @param bindingRoot Binding root index.
24536 * @param slotOffset the offset from binding root to the reserved slot
24537 * @param pureFn
24538 * @param exp1
24539 * @param exp2
24540 * @param exp3
24541 * @param thisArg Optional calling context of pureFn
24542 * @returns Updated or cached value
24543 */
24544function pureFunction3Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, exp3, thisArg) {
24545 const bindingIndex = bindingRoot + slotOffset;
24546 return bindingUpdated3(lView, bindingIndex, exp1, exp2, exp3) ?
24547 updateBinding(lView, bindingIndex + 3, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3) : pureFn(exp1, exp2, exp3)) :
24548 getPureFunctionReturnValue(lView, bindingIndex + 3);
24549}
24550/**
24551 * If the value of any provided exp has changed, calls the pure function to return
24552 * an updated value. Or if no values have changed, returns cached value.
24553 *
24554 * @param lView LView in which the function is being executed.
24555 * @param bindingRoot Binding root index.
24556 * @param slotOffset the offset from binding root to the reserved slot
24557 * @param pureFn
24558 * @param exp1
24559 * @param exp2
24560 * @param exp3
24561 * @param exp4
24562 * @param thisArg Optional calling context of pureFn
24563 * @returns Updated or cached value
24564 *
24565 */
24566function pureFunction4Internal(lView, bindingRoot, slotOffset, pureFn, exp1, exp2, exp3, exp4, thisArg) {
24567 const bindingIndex = bindingRoot + slotOffset;
24568 return bindingUpdated4(lView, bindingIndex, exp1, exp2, exp3, exp4) ?
24569 updateBinding(lView, bindingIndex + 4, thisArg ? pureFn.call(thisArg, exp1, exp2, exp3, exp4) : pureFn(exp1, exp2, exp3, exp4)) :
24570 getPureFunctionReturnValue(lView, bindingIndex + 4);
24571}
24572/**
24573 * pureFunction instruction that can support any number of bindings.
24574 *
24575 * If the value of any provided exp has changed, calls the pure function to return
24576 * an updated value. Or if no values have changed, returns cached value.
24577 *
24578 * @param lView LView in which the function is being executed.
24579 * @param bindingRoot Binding root index.
24580 * @param slotOffset the offset from binding root to the reserved slot
24581 * @param pureFn A pure function that takes binding values and builds an object or array
24582 * containing those values.
24583 * @param exps An array of binding values
24584 * @param thisArg Optional calling context of pureFn
24585 * @returns Updated or cached value
24586 */
24587function pureFunctionVInternal(lView, bindingRoot, slotOffset, pureFn, exps, thisArg) {
24588 let bindingIndex = bindingRoot + slotOffset;
24589 let different = false;
24590 for (let i = 0; i < exps.length; i++) {
24591 bindingUpdated(lView, bindingIndex++, exps[i]) && (different = true);
24592 }
24593 return different ? updateBinding(lView, bindingIndex, pureFn.apply(thisArg, exps)) :
24594 getPureFunctionReturnValue(lView, bindingIndex);
24595}
24596
24597/**
24598 * @license
24599 * Copyright Google LLC All Rights Reserved.
24600 *
24601 * Use of this source code is governed by an MIT-style license that can be
24602 * found in the LICENSE file at https://angular.io/license
24603 */
24604/**
24605 * Create a pipe.
24606 *
24607 * @param index Pipe index where the pipe will be stored.
24608 * @param pipeName The name of the pipe
24609 * @returns T the instance of the pipe.
24610 *
24611 * @codeGenApi
24612 */
24613function ɵɵpipe(index, pipeName) {
24614 const tView = getTView();
24615 let pipeDef;
24616 const adjustedIndex = index + HEADER_OFFSET;
24617 if (tView.firstCreatePass) {
24618 pipeDef = getPipeDef$1(pipeName, tView.pipeRegistry);
24619 tView.data[adjustedIndex] = pipeDef;
24620 if (pipeDef.onDestroy) {
24621 (tView.destroyHooks || (tView.destroyHooks = [])).push(adjustedIndex, pipeDef.onDestroy);
24622 }
24623 }
24624 else {
24625 pipeDef = tView.data[adjustedIndex];
24626 }
24627 const pipeFactory = pipeDef.factory || (pipeDef.factory = getFactoryDef(pipeDef.type, true));
24628 const previousInjectImplementation = setInjectImplementation(ɵɵdirectiveInject);
24629 // DI for pipes is supposed to behave like directives when placed on a component
24630 // host node, which means that we have to disable access to `viewProviders`.
24631 const previousIncludeViewProviders = setIncludeViewProviders(false);
24632 const pipeInstance = pipeFactory();
24633 setIncludeViewProviders(previousIncludeViewProviders);
24634 setInjectImplementation(previousInjectImplementation);
24635 store(tView, getLView(), index, pipeInstance);
24636 return pipeInstance;
24637}
24638/**
24639 * Searches the pipe registry for a pipe with the given name. If one is found,
24640 * returns the pipe. Otherwise, an error is thrown because the pipe cannot be resolved.
24641 *
24642 * @param name Name of pipe to resolve
24643 * @param registry Full list of available pipes
24644 * @returns Matching PipeDef
24645 */
24646function getPipeDef$1(name, registry) {
24647 if (registry) {
24648 for (let i = registry.length - 1; i >= 0; i--) {
24649 const pipeDef = registry[i];
24650 if (name === pipeDef.name) {
24651 return pipeDef;
24652 }
24653 }
24654 }
24655 throw new Error(`The pipe '${name}' could not be found!`);
24656}
24657/**
24658 * Invokes a pipe with 1 arguments.
24659 *
24660 * This instruction acts as a guard to {@link PipeTransform#transform} invoking
24661 * the pipe only when an input to the pipe changes.
24662 *
24663 * @param index Pipe index where the pipe was stored on creation.
24664 * @param slotOffset the offset in the reserved slot space
24665 * @param v1 1st argument to {@link PipeTransform#transform}.
24666 *
24667 * @codeGenApi
24668 */
24669function ɵɵpipeBind1(index, slotOffset, v1) {
24670 const lView = getLView();
24671 const pipeInstance = load(lView, index);
24672 return unwrapValue$1(lView, isPure(lView, index) ?
24673 pureFunction1Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, pipeInstance) :
24674 pipeInstance.transform(v1));
24675}
24676/**
24677 * Invokes a pipe with 2 arguments.
24678 *
24679 * This instruction acts as a guard to {@link PipeTransform#transform} invoking
24680 * the pipe only when an input to the pipe changes.
24681 *
24682 * @param index Pipe index where the pipe was stored on creation.
24683 * @param slotOffset the offset in the reserved slot space
24684 * @param v1 1st argument to {@link PipeTransform#transform}.
24685 * @param v2 2nd argument to {@link PipeTransform#transform}.
24686 *
24687 * @codeGenApi
24688 */
24689function ɵɵpipeBind2(index, slotOffset, v1, v2) {
24690 const lView = getLView();
24691 const pipeInstance = load(lView, index);
24692 return unwrapValue$1(lView, isPure(lView, index) ?
24693 pureFunction2Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, pipeInstance) :
24694 pipeInstance.transform(v1, v2));
24695}
24696/**
24697 * Invokes a pipe with 3 arguments.
24698 *
24699 * This instruction acts as a guard to {@link PipeTransform#transform} invoking
24700 * the pipe only when an input to the pipe changes.
24701 *
24702 * @param index Pipe index where the pipe was stored on creation.
24703 * @param slotOffset the offset in the reserved slot space
24704 * @param v1 1st argument to {@link PipeTransform#transform}.
24705 * @param v2 2nd argument to {@link PipeTransform#transform}.
24706 * @param v3 4rd argument to {@link PipeTransform#transform}.
24707 *
24708 * @codeGenApi
24709 */
24710function ɵɵpipeBind3(index, slotOffset, v1, v2, v3) {
24711 const lView = getLView();
24712 const pipeInstance = load(lView, index);
24713 return unwrapValue$1(lView, isPure(lView, index) ? pureFunction3Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, v3, pipeInstance) :
24714 pipeInstance.transform(v1, v2, v3));
24715}
24716/**
24717 * Invokes a pipe with 4 arguments.
24718 *
24719 * This instruction acts as a guard to {@link PipeTransform#transform} invoking
24720 * the pipe only when an input to the pipe changes.
24721 *
24722 * @param index Pipe index where the pipe was stored on creation.
24723 * @param slotOffset the offset in the reserved slot space
24724 * @param v1 1st argument to {@link PipeTransform#transform}.
24725 * @param v2 2nd argument to {@link PipeTransform#transform}.
24726 * @param v3 3rd argument to {@link PipeTransform#transform}.
24727 * @param v4 4th argument to {@link PipeTransform#transform}.
24728 *
24729 * @codeGenApi
24730 */
24731function ɵɵpipeBind4(index, slotOffset, v1, v2, v3, v4) {
24732 const lView = getLView();
24733 const pipeInstance = load(lView, index);
24734 return unwrapValue$1(lView, isPure(lView, index) ? pureFunction4Internal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, v1, v2, v3, v4, pipeInstance) :
24735 pipeInstance.transform(v1, v2, v3, v4));
24736}
24737/**
24738 * Invokes a pipe with variable number of arguments.
24739 *
24740 * This instruction acts as a guard to {@link PipeTransform#transform} invoking
24741 * the pipe only when an input to the pipe changes.
24742 *
24743 * @param index Pipe index where the pipe was stored on creation.
24744 * @param slotOffset the offset in the reserved slot space
24745 * @param values Array of arguments to pass to {@link PipeTransform#transform} method.
24746 *
24747 * @codeGenApi
24748 */
24749function ɵɵpipeBindV(index, slotOffset, values) {
24750 const lView = getLView();
24751 const pipeInstance = load(lView, index);
24752 return unwrapValue$1(lView, isPure(lView, index) ?
24753 pureFunctionVInternal(lView, getBindingRoot(), slotOffset, pipeInstance.transform, values, pipeInstance) :
24754 pipeInstance.transform.apply(pipeInstance, values));
24755}
24756function isPure(lView, index) {
24757 return lView[TVIEW].data[index + HEADER_OFFSET].pure;
24758}
24759/**
24760 * Unwrap the output of a pipe transformation.
24761 * In order to trick change detection into considering that the new value is always different from
24762 * the old one, the old value is overwritten by NO_CHANGE.
24763 *
24764 * @param newValue the pipe transformation output.
24765 */
24766function unwrapValue$1(lView, newValue) {
24767 if (WrappedValue.isWrapped(newValue)) {
24768 newValue = WrappedValue.unwrap(newValue);
24769 // The NO_CHANGE value needs to be written at the index where the impacted binding value is
24770 // stored
24771 const bindingToInvalidateIdx = getBindingIndex();
24772 lView[bindingToInvalidateIdx] = NO_CHANGE;
24773 }
24774 return newValue;
24775}
24776
24777/**
24778 * @license
24779 * Copyright Google LLC All Rights Reserved.
24780 *
24781 * Use of this source code is governed by an MIT-style license that can be
24782 * found in the LICENSE file at https://angular.io/license
24783 */
24784class EventEmitter_ extends Subject {
24785 constructor(isAsync = false) {
24786 super();
24787 this.__isAsync = isAsync;
24788 }
24789 emit(value) {
24790 super.next(value);
24791 }
24792 subscribe(generatorOrNext, error, complete) {
24793 let schedulerFn;
24794 let errorFn = (err) => null;
24795 let completeFn = () => null;
24796 if (generatorOrNext && typeof generatorOrNext === 'object') {
24797 schedulerFn = this.__isAsync ? (value) => {
24798 setTimeout(() => generatorOrNext.next(value));
24799 } : (value) => {
24800 generatorOrNext.next(value);
24801 };
24802 if (generatorOrNext.error) {
24803 errorFn = this.__isAsync ? (err) => {
24804 setTimeout(() => generatorOrNext.error(err));
24805 } : (err) => {
24806 generatorOrNext.error(err);
24807 };
24808 }
24809 if (generatorOrNext.complete) {
24810 completeFn = this.__isAsync ? () => {
24811 setTimeout(() => generatorOrNext.complete());
24812 } : () => {
24813 generatorOrNext.complete();
24814 };
24815 }
24816 }
24817 else {
24818 schedulerFn = this.__isAsync ? (value) => {
24819 setTimeout(() => generatorOrNext(value));
24820 } : (value) => {
24821 generatorOrNext(value);
24822 };
24823 if (error) {
24824 errorFn = this.__isAsync ? (err) => {
24825 setTimeout(() => error(err));
24826 } : (err) => {
24827 error(err);
24828 };
24829 }
24830 if (complete) {
24831 completeFn = this.__isAsync ? () => {
24832 setTimeout(() => complete());
24833 } : () => {
24834 complete();
24835 };
24836 }
24837 }
24838 const sink = super.subscribe(schedulerFn, errorFn, completeFn);
24839 if (generatorOrNext instanceof Subscription) {
24840 generatorOrNext.add(sink);
24841 }
24842 return sink;
24843 }
24844}
24845/**
24846 * @publicApi
24847 */
24848const EventEmitter = EventEmitter_;
24849
24850/**
24851 * @license
24852 * Copyright Google LLC All Rights Reserved.
24853 *
24854 * Use of this source code is governed by an MIT-style license that can be
24855 * found in the LICENSE file at https://angular.io/license
24856 */
24857function symbolIterator() {
24858 return this._results[getSymbolIterator()]();
24859}
24860/**
24861 * An unmodifiable list of items that Angular keeps up to date when the state
24862 * of the application changes.
24863 *
24864 * The type of object that {@link ViewChildren}, {@link ContentChildren}, and {@link QueryList}
24865 * provide.
24866 *
24867 * Implements an iterable interface, therefore it can be used in both ES6
24868 * javascript `for (var i of items)` loops as well as in Angular templates with
24869 * `*ngFor="let i of myList"`.
24870 *
24871 * Changes can be observed by subscribing to the changes `Observable`.
24872 *
24873 * NOTE: In the future this class will implement an `Observable` interface.
24874 *
24875 * @usageNotes
24876 * ### Example
24877 * ```typescript
24878 * @Component({...})
24879 * class Container {
24880 * @ViewChildren(Item) items:QueryList<Item>;
24881 * }
24882 * ```
24883 *
24884 * @publicApi
24885 */
24886class QueryList {
24887 constructor() {
24888 this.dirty = true;
24889 this._results = [];
24890 this.changes = new EventEmitter();
24891 this.length = 0;
24892 // This function should be declared on the prototype, but doing so there will cause the class
24893 // declaration to have side-effects and become not tree-shakable. For this reason we do it in
24894 // the constructor.
24895 // [getSymbolIterator()](): Iterator<T> { ... }
24896 const symbol = getSymbolIterator();
24897 const proto = QueryList.prototype;
24898 if (!proto[symbol])
24899 proto[symbol] = symbolIterator;
24900 }
24901 /**
24902 * See
24903 * [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
24904 */
24905 map(fn) {
24906 return this._results.map(fn);
24907 }
24908 /**
24909 * See
24910 * [Array.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
24911 */
24912 filter(fn) {
24913 return this._results.filter(fn);
24914 }
24915 /**
24916 * See
24917 * [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
24918 */
24919 find(fn) {
24920 return this._results.find(fn);
24921 }
24922 /**
24923 * See
24924 * [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
24925 */
24926 reduce(fn, init) {
24927 return this._results.reduce(fn, init);
24928 }
24929 /**
24930 * See
24931 * [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
24932 */
24933 forEach(fn) {
24934 this._results.forEach(fn);
24935 }
24936 /**
24937 * See
24938 * [Array.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)
24939 */
24940 some(fn) {
24941 return this._results.some(fn);
24942 }
24943 /**
24944 * Returns a copy of the internal results list as an Array.
24945 */
24946 toArray() {
24947 return this._results.slice();
24948 }
24949 toString() {
24950 return this._results.toString();
24951 }
24952 /**
24953 * Updates the stored data of the query list, and resets the `dirty` flag to `false`, so that
24954 * on change detection, it will not notify of changes to the queries, unless a new change
24955 * occurs.
24956 *
24957 * @param resultsTree The query results to store
24958 */
24959 reset(resultsTree) {
24960 this._results = flatten(resultsTree);
24961 this.dirty = false;
24962 this.length = this._results.length;
24963 this.last = this._results[this.length - 1];
24964 this.first = this._results[0];
24965 }
24966 /**
24967 * Triggers a change event by emitting on the `changes` {@link EventEmitter}.
24968 */
24969 notifyOnChanges() {
24970 this.changes.emit(this);
24971 }
24972 /** internal */
24973 setDirty() {
24974 this.dirty = true;
24975 }
24976 /** internal */
24977 destroy() {
24978 this.changes.complete();
24979 this.changes.unsubscribe();
24980 }
24981}
24982
24983/**
24984 * @license
24985 * Copyright Google LLC All Rights Reserved.
24986 *
24987 * Use of this source code is governed by an MIT-style license that can be
24988 * found in the LICENSE file at https://angular.io/license
24989 */
24990// Note: This hack is necessary so we don't erroneously get a circular dependency
24991// failure based on types.
24992const unusedValueExportToPlacateAjd$7 = 1;
24993
24994/**
24995 * @license
24996 * Copyright Google LLC All Rights Reserved.
24997 *
24998 * Use of this source code is governed by an MIT-style license that can be
24999 * found in the LICENSE file at https://angular.io/license
25000 */
25001// Note: This hack is necessary so we don't erroneously get a circular dependency
25002// failure based on types.
25003const unusedValueExportToPlacateAjd$8 = 1;
25004
25005/**
25006 * @license
25007 * Copyright Google LLC All Rights Reserved.
25008 *
25009 * Use of this source code is governed by an MIT-style license that can be
25010 * found in the LICENSE file at https://angular.io/license
25011 */
25012const unusedValueToPlacateAjd$2 = unusedValueExportToPlacateAjd$7 + unusedValueExportToPlacateAjd$3 + unusedValueExportToPlacateAjd$4 + unusedValueExportToPlacateAjd$8;
25013class LQuery_ {
25014 constructor(queryList) {
25015 this.queryList = queryList;
25016 this.matches = null;
25017 }
25018 clone() {
25019 return new LQuery_(this.queryList);
25020 }
25021 setDirty() {
25022 this.queryList.setDirty();
25023 }
25024}
25025class LQueries_ {
25026 constructor(queries = []) {
25027 this.queries = queries;
25028 }
25029 createEmbeddedView(tView) {
25030 const tQueries = tView.queries;
25031 if (tQueries !== null) {
25032 const noOfInheritedQueries = tView.contentQueries !== null ? tView.contentQueries[0] : tQueries.length;
25033 const viewLQueries = [];
25034 // An embedded view has queries propagated from a declaration view at the beginning of the
25035 // TQueries collection and up until a first content query declared in the embedded view. Only
25036 // propagated LQueries are created at this point (LQuery corresponding to declared content
25037 // queries will be instantiated from the content query instructions for each directive).
25038 for (let i = 0; i < noOfInheritedQueries; i++) {
25039 const tQuery = tQueries.getByIndex(i);
25040 const parentLQuery = this.queries[tQuery.indexInDeclarationView];
25041 viewLQueries.push(parentLQuery.clone());
25042 }
25043 return new LQueries_(viewLQueries);
25044 }
25045 return null;
25046 }
25047 insertView(tView) {
25048 this.dirtyQueriesWithMatches(tView);
25049 }
25050 detachView(tView) {
25051 this.dirtyQueriesWithMatches(tView);
25052 }
25053 dirtyQueriesWithMatches(tView) {
25054 for (let i = 0; i < this.queries.length; i++) {
25055 if (getTQuery(tView, i).matches !== null) {
25056 this.queries[i].setDirty();
25057 }
25058 }
25059 }
25060}
25061class TQueryMetadata_ {
25062 constructor(predicate, descendants, isStatic, read = null) {
25063 this.predicate = predicate;
25064 this.descendants = descendants;
25065 this.isStatic = isStatic;
25066 this.read = read;
25067 }
25068}
25069class TQueries_ {
25070 constructor(queries = []) {
25071 this.queries = queries;
25072 }
25073 elementStart(tView, tNode) {
25074 ngDevMode &&
25075 assertFirstCreatePass(tView, 'Queries should collect results on the first template pass only');
25076 for (let i = 0; i < this.queries.length; i++) {
25077 this.queries[i].elementStart(tView, tNode);
25078 }
25079 }
25080 elementEnd(tNode) {
25081 for (let i = 0; i < this.queries.length; i++) {
25082 this.queries[i].elementEnd(tNode);
25083 }
25084 }
25085 embeddedTView(tNode) {
25086 let queriesForTemplateRef = null;
25087 for (let i = 0; i < this.length; i++) {
25088 const childQueryIndex = queriesForTemplateRef !== null ? queriesForTemplateRef.length : 0;
25089 const tqueryClone = this.getByIndex(i).embeddedTView(tNode, childQueryIndex);
25090 if (tqueryClone) {
25091 tqueryClone.indexInDeclarationView = i;
25092 if (queriesForTemplateRef !== null) {
25093 queriesForTemplateRef.push(tqueryClone);
25094 }
25095 else {
25096 queriesForTemplateRef = [tqueryClone];
25097 }
25098 }
25099 }
25100 return queriesForTemplateRef !== null ? new TQueries_(queriesForTemplateRef) : null;
25101 }
25102 template(tView, tNode) {
25103 ngDevMode &&
25104 assertFirstCreatePass(tView, 'Queries should collect results on the first template pass only');
25105 for (let i = 0; i < this.queries.length; i++) {
25106 this.queries[i].template(tView, tNode);
25107 }
25108 }
25109 getByIndex(index) {
25110 ngDevMode && assertIndexInRange(this.queries, index);
25111 return this.queries[index];
25112 }
25113 get length() {
25114 return this.queries.length;
25115 }
25116 track(tquery) {
25117 this.queries.push(tquery);
25118 }
25119}
25120class TQuery_ {
25121 constructor(metadata, nodeIndex = -1) {
25122 this.metadata = metadata;
25123 this.matches = null;
25124 this.indexInDeclarationView = -1;
25125 this.crossesNgTemplate = false;
25126 /**
25127 * A flag indicating if a given query still applies to nodes it is crossing. We use this flag
25128 * (alongside with _declarationNodeIndex) to know when to stop applying content queries to
25129 * elements in a template.
25130 */
25131 this._appliesToNextNode = true;
25132 this._declarationNodeIndex = nodeIndex;
25133 }
25134 elementStart(tView, tNode) {
25135 if (this.isApplyingToNode(tNode)) {
25136 this.matchTNode(tView, tNode);
25137 }
25138 }
25139 elementEnd(tNode) {
25140 if (this._declarationNodeIndex === tNode.index) {
25141 this._appliesToNextNode = false;
25142 }
25143 }
25144 template(tView, tNode) {
25145 this.elementStart(tView, tNode);
25146 }
25147 embeddedTView(tNode, childQueryIndex) {
25148 if (this.isApplyingToNode(tNode)) {
25149 this.crossesNgTemplate = true;
25150 // A marker indicating a `<ng-template>` element (a placeholder for query results from
25151 // embedded views created based on this `<ng-template>`).
25152 this.addMatch(-tNode.index, childQueryIndex);
25153 return new TQuery_(this.metadata);
25154 }
25155 return null;
25156 }
25157 isApplyingToNode(tNode) {
25158 if (this._appliesToNextNode && this.metadata.descendants === false) {
25159 const declarationNodeIdx = this._declarationNodeIndex;
25160 let parent = tNode.parent;
25161 // Determine if a given TNode is a "direct" child of a node on which a content query was
25162 // declared (only direct children of query's host node can match with the descendants: false
25163 // option). There are 3 main use-case / conditions to consider here:
25164 // - <needs-target><i #target></i></needs-target>: here <i #target> parent node is a query
25165 // host node;
25166 // - <needs-target><ng-template [ngIf]="true"><i #target></i></ng-template></needs-target>:
25167 // here <i #target> parent node is null;
25168 // - <needs-target><ng-container><i #target></i></ng-container></needs-target>: here we need
25169 // to go past `<ng-container>` to determine <i #target> parent node (but we shouldn't traverse
25170 // up past the query's host node!).
25171 while (parent !== null && parent.type === 4 /* ElementContainer */ &&
25172 parent.index !== declarationNodeIdx) {
25173 parent = parent.parent;
25174 }
25175 return declarationNodeIdx === (parent !== null ? parent.index : -1);
25176 }
25177 return this._appliesToNextNode;
25178 }
25179 matchTNode(tView, tNode) {
25180 const predicate = this.metadata.predicate;
25181 if (Array.isArray(predicate)) {
25182 for (let i = 0; i < predicate.length; i++) {
25183 const name = predicate[i];
25184 this.matchTNodeWithReadOption(tView, tNode, getIdxOfMatchingSelector(tNode, name));
25185 // Also try matching the name to a provider since strings can be used as DI tokens too.
25186 this.matchTNodeWithReadOption(tView, tNode, locateDirectiveOrProvider(tNode, tView, name, false, false));
25187 }
25188 }
25189 else {
25190 if (predicate === TemplateRef) {
25191 if (tNode.type === 0 /* Container */) {
25192 this.matchTNodeWithReadOption(tView, tNode, -1);
25193 }
25194 }
25195 else {
25196 this.matchTNodeWithReadOption(tView, tNode, locateDirectiveOrProvider(tNode, tView, predicate, false, false));
25197 }
25198 }
25199 }
25200 matchTNodeWithReadOption(tView, tNode, nodeMatchIdx) {
25201 if (nodeMatchIdx !== null) {
25202 const read = this.metadata.read;
25203 if (read !== null) {
25204 if (read === ElementRef || read === ViewContainerRef ||
25205 read === TemplateRef && tNode.type === 0 /* Container */) {
25206 this.addMatch(tNode.index, -2);
25207 }
25208 else {
25209 const directiveOrProviderIdx = locateDirectiveOrProvider(tNode, tView, read, false, false);
25210 if (directiveOrProviderIdx !== null) {
25211 this.addMatch(tNode.index, directiveOrProviderIdx);
25212 }
25213 }
25214 }
25215 else {
25216 this.addMatch(tNode.index, nodeMatchIdx);
25217 }
25218 }
25219 }
25220 addMatch(tNodeIdx, matchIdx) {
25221 if (this.matches === null) {
25222 this.matches = [tNodeIdx, matchIdx];
25223 }
25224 else {
25225 this.matches.push(tNodeIdx, matchIdx);
25226 }
25227 }
25228}
25229/**
25230 * Iterates over local names for a given node and returns directive index
25231 * (or -1 if a local name points to an element).
25232 *
25233 * @param tNode static data of a node to check
25234 * @param selector selector to match
25235 * @returns directive index, -1 or null if a selector didn't match any of the local names
25236 */
25237function getIdxOfMatchingSelector(tNode, selector) {
25238 const localNames = tNode.localNames;
25239 if (localNames !== null) {
25240 for (let i = 0; i < localNames.length; i += 2) {
25241 if (localNames[i] === selector) {
25242 return localNames[i + 1];
25243 }
25244 }
25245 }
25246 return null;
25247}
25248function createResultByTNodeType(tNode, currentView) {
25249 if (tNode.type === 3 /* Element */ || tNode.type === 4 /* ElementContainer */) {
25250 return createElementRef(ElementRef, tNode, currentView);
25251 }
25252 else if (tNode.type === 0 /* Container */) {
25253 return createTemplateRef(TemplateRef, ElementRef, tNode, currentView);
25254 }
25255 return null;
25256}
25257function createResultForNode(lView, tNode, matchingIdx, read) {
25258 if (matchingIdx === -1) {
25259 // if read token and / or strategy is not specified, detect it using appropriate tNode type
25260 return createResultByTNodeType(tNode, lView);
25261 }
25262 else if (matchingIdx === -2) {
25263 // read a special token from a node injector
25264 return createSpecialToken(lView, tNode, read);
25265 }
25266 else {
25267 // read a token
25268 return getNodeInjectable(lView, lView[TVIEW], matchingIdx, tNode);
25269 }
25270}
25271function createSpecialToken(lView, tNode, read) {
25272 if (read === ElementRef) {
25273 return createElementRef(ElementRef, tNode, lView);
25274 }
25275 else if (read === TemplateRef) {
25276 return createTemplateRef(TemplateRef, ElementRef, tNode, lView);
25277 }
25278 else if (read === ViewContainerRef) {
25279 ngDevMode &&
25280 assertNodeOfPossibleTypes(tNode, [3 /* Element */, 0 /* Container */, 4 /* ElementContainer */]);
25281 return createContainerRef(ViewContainerRef, ElementRef, tNode, lView);
25282 }
25283 else {
25284 ngDevMode &&
25285 throwError(`Special token to read should be one of ElementRef, TemplateRef or ViewContainerRef but got ${stringify(read)}.`);
25286 }
25287}
25288/**
25289 * A helper function that creates query results for a given view. This function is meant to do the
25290 * processing once and only once for a given view instance (a set of results for a given view
25291 * doesn't change).
25292 */
25293function materializeViewResults(tView, lView, tQuery, queryIndex) {
25294 const lQuery = lView[QUERIES].queries[queryIndex];
25295 if (lQuery.matches === null) {
25296 const tViewData = tView.data;
25297 const tQueryMatches = tQuery.matches;
25298 const result = [];
25299 for (let i = 0; i < tQueryMatches.length; i += 2) {
25300 const matchedNodeIdx = tQueryMatches[i];
25301 if (matchedNodeIdx < 0) {
25302 // we at the <ng-template> marker which might have results in views created based on this
25303 // <ng-template> - those results will be in separate views though, so here we just leave
25304 // null as a placeholder
25305 result.push(null);
25306 }
25307 else {
25308 ngDevMode && assertIndexInRange(tViewData, matchedNodeIdx);
25309 const tNode = tViewData[matchedNodeIdx];
25310 result.push(createResultForNode(lView, tNode, tQueryMatches[i + 1], tQuery.metadata.read));
25311 }
25312 }
25313 lQuery.matches = result;
25314 }
25315 return lQuery.matches;
25316}
25317/**
25318 * A helper function that collects (already materialized) query results from a tree of views,
25319 * starting with a provided LView.
25320 */
25321function collectQueryResults(tView, lView, queryIndex, result) {
25322 const tQuery = tView.queries.getByIndex(queryIndex);
25323 const tQueryMatches = tQuery.matches;
25324 if (tQueryMatches !== null) {
25325 const lViewResults = materializeViewResults(tView, lView, tQuery, queryIndex);
25326 for (let i = 0; i < tQueryMatches.length; i += 2) {
25327 const tNodeIdx = tQueryMatches[i];
25328 if (tNodeIdx > 0) {
25329 result.push(lViewResults[i / 2]);
25330 }
25331 else {
25332 const childQueryIndex = tQueryMatches[i + 1];
25333 const declarationLContainer = lView[-tNodeIdx];
25334 ngDevMode && assertLContainer(declarationLContainer);
25335 // collect matches for views inserted in this container
25336 for (let i = CONTAINER_HEADER_OFFSET; i < declarationLContainer.length; i++) {
25337 const embeddedLView = declarationLContainer[i];
25338 if (embeddedLView[DECLARATION_LCONTAINER] === embeddedLView[PARENT]) {
25339 collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result);
25340 }
25341 }
25342 // collect matches for views created from this declaration container and inserted into
25343 // different containers
25344 if (declarationLContainer[MOVED_VIEWS] !== null) {
25345 const embeddedLViews = declarationLContainer[MOVED_VIEWS];
25346 for (let i = 0; i < embeddedLViews.length; i++) {
25347 const embeddedLView = embeddedLViews[i];
25348 collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result);
25349 }
25350 }
25351 }
25352 }
25353 }
25354 return result;
25355}
25356/**
25357 * Refreshes a query by combining matches from all active views and removing matches from deleted
25358 * views.
25359 *
25360 * @returns `true` if a query got dirty during change detection or if this is a static query
25361 * resolving in creation mode, `false` otherwise.
25362 *
25363 * @codeGenApi
25364 */
25365function ɵɵqueryRefresh(queryList) {
25366 const lView = getLView();
25367 const tView = getTView();
25368 const queryIndex = getCurrentQueryIndex();
25369 setCurrentQueryIndex(queryIndex + 1);
25370 const tQuery = getTQuery(tView, queryIndex);
25371 if (queryList.dirty && (isCreationMode(lView) === tQuery.metadata.isStatic)) {
25372 if (tQuery.matches === null) {
25373 queryList.reset([]);
25374 }
25375 else {
25376 const result = tQuery.crossesNgTemplate ?
25377 collectQueryResults(tView, lView, queryIndex, []) :
25378 materializeViewResults(tView, lView, tQuery, queryIndex);
25379 queryList.reset(result);
25380 queryList.notifyOnChanges();
25381 }
25382 return true;
25383 }
25384 return false;
25385}
25386/**
25387 * Creates new QueryList for a static view query.
25388 *
25389 * @param predicate The type for which the query will search
25390 * @param descend Whether or not to descend into children
25391 * @param read What to save in the query
25392 *
25393 * @codeGenApi
25394 */
25395function ɵɵstaticViewQuery(predicate, descend, read) {
25396 viewQueryInternal(getTView(), getLView(), predicate, descend, read, true);
25397}
25398/**
25399 * Creates new QueryList, stores the reference in LView and returns QueryList.
25400 *
25401 * @param predicate The type for which the query will search
25402 * @param descend Whether or not to descend into children
25403 * @param read What to save in the query
25404 *
25405 * @codeGenApi
25406 */
25407function ɵɵviewQuery(predicate, descend, read) {
25408 viewQueryInternal(getTView(), getLView(), predicate, descend, read, false);
25409}
25410function viewQueryInternal(tView, lView, predicate, descend, read, isStatic) {
25411 if (tView.firstCreatePass) {
25412 createTQuery(tView, new TQueryMetadata_(predicate, descend, isStatic, read), -1);
25413 if (isStatic) {
25414 tView.staticViewQueries = true;
25415 }
25416 }
25417 createLQuery(tView, lView);
25418}
25419/**
25420 * Registers a QueryList, associated with a content query, for later refresh (part of a view
25421 * refresh).
25422 *
25423 * @param directiveIndex Current directive index
25424 * @param predicate The type for which the query will search
25425 * @param descend Whether or not to descend into children
25426 * @param read What to save in the query
25427 * @returns QueryList<T>
25428 *
25429 * @codeGenApi
25430 */
25431function ɵɵcontentQuery(directiveIndex, predicate, descend, read) {
25432 contentQueryInternal(getTView(), getLView(), predicate, descend, read, false, getPreviousOrParentTNode(), directiveIndex);
25433}
25434/**
25435 * Registers a QueryList, associated with a static content query, for later refresh
25436 * (part of a view refresh).
25437 *
25438 * @param directiveIndex Current directive index
25439 * @param predicate The type for which the query will search
25440 * @param descend Whether or not to descend into children
25441 * @param read What to save in the query
25442 * @returns QueryList<T>
25443 *
25444 * @codeGenApi
25445 */
25446function ɵɵstaticContentQuery(directiveIndex, predicate, descend, read) {
25447 contentQueryInternal(getTView(), getLView(), predicate, descend, read, true, getPreviousOrParentTNode(), directiveIndex);
25448}
25449function contentQueryInternal(tView, lView, predicate, descend, read, isStatic, tNode, directiveIndex) {
25450 if (tView.firstCreatePass) {
25451 createTQuery(tView, new TQueryMetadata_(predicate, descend, isStatic, read), tNode.index);
25452 saveContentQueryAndDirectiveIndex(tView, directiveIndex);
25453 if (isStatic) {
25454 tView.staticContentQueries = true;
25455 }
25456 }
25457 createLQuery(tView, lView);
25458}
25459/**
25460 * Loads a QueryList corresponding to the current view or content query.
25461 *
25462 * @codeGenApi
25463 */
25464function ɵɵloadQuery() {
25465 return loadQueryInternal(getLView(), getCurrentQueryIndex());
25466}
25467function loadQueryInternal(lView, queryIndex) {
25468 ngDevMode &&
25469 assertDefined(lView[QUERIES], 'LQueries should be defined when trying to load a query');
25470 ngDevMode && assertIndexInRange(lView[QUERIES].queries, queryIndex);
25471 return lView[QUERIES].queries[queryIndex].queryList;
25472}
25473function createLQuery(tView, lView) {
25474 const queryList = new QueryList();
25475 storeCleanupWithContext(tView, lView, queryList, queryList.destroy);
25476 if (lView[QUERIES] === null)
25477 lView[QUERIES] = new LQueries_();
25478 lView[QUERIES].queries.push(new LQuery_(queryList));
25479}
25480function createTQuery(tView, metadata, nodeIndex) {
25481 if (tView.queries === null)
25482 tView.queries = new TQueries_();
25483 tView.queries.track(new TQuery_(metadata, nodeIndex));
25484}
25485function saveContentQueryAndDirectiveIndex(tView, directiveIndex) {
25486 const tViewContentQueries = tView.contentQueries || (tView.contentQueries = []);
25487 const lastSavedDirectiveIndex = tView.contentQueries.length ? tViewContentQueries[tViewContentQueries.length - 1] : -1;
25488 if (directiveIndex !== lastSavedDirectiveIndex) {
25489 tViewContentQueries.push(tView.queries.length - 1, directiveIndex);
25490 }
25491}
25492function getTQuery(tView, index) {
25493 ngDevMode && assertDefined(tView.queries, 'TQueries must be defined to retrieve a TQuery');
25494 return tView.queries.getByIndex(index);
25495}
25496
25497/**
25498 * @license
25499 * Copyright Google LLC All Rights Reserved.
25500 *
25501 * Use of this source code is governed by an MIT-style license that can be
25502 * found in the LICENSE file at https://angular.io/license
25503 */
25504/**
25505 * Retrieves `TemplateRef` instance from `Injector` when a local reference is placed on the
25506 * `<ng-template>` element.
25507 *
25508 * @codeGenApi
25509 */
25510function ɵɵtemplateRefExtractor(tNode, currentView) {
25511 return createTemplateRef(TemplateRef, ElementRef, tNode, currentView);
25512}
25513/**
25514 * Returns the appropriate `ChangeDetectorRef` for a pipe.
25515 *
25516 * @codeGenApi
25517 */
25518function ɵɵinjectPipeChangeDetectorRef(flags = InjectFlags.Default) {
25519 const value = injectChangeDetectorRef(true);
25520 if (value == null && !(flags & InjectFlags.Optional)) {
25521 throw new Error(`No provider for ChangeDetectorRef!`);
25522 }
25523 else {
25524 return value;
25525 }
25526}
25527
25528/**
25529 * @license
25530 * Copyright Google LLC All Rights Reserved.
25531 *
25532 * Use of this source code is governed by an MIT-style license that can be
25533 * found in the LICENSE file at https://angular.io/license
25534 */
25535
25536/**
25537 * @license
25538 * Copyright Google LLC All Rights Reserved.
25539 *
25540 * Use of this source code is governed by an MIT-style license that can be
25541 * found in the LICENSE file at https://angular.io/license
25542 */
25543const ɵ0$d = () => ({
25544 'ɵɵattribute': ɵɵattribute,
25545 'ɵɵattributeInterpolate1': ɵɵattributeInterpolate1,
25546 'ɵɵattributeInterpolate2': ɵɵattributeInterpolate2,
25547 'ɵɵattributeInterpolate3': ɵɵattributeInterpolate3,
25548 'ɵɵattributeInterpolate4': ɵɵattributeInterpolate4,
25549 'ɵɵattributeInterpolate5': ɵɵattributeInterpolate5,
25550 'ɵɵattributeInterpolate6': ɵɵattributeInterpolate6,
25551 'ɵɵattributeInterpolate7': ɵɵattributeInterpolate7,
25552 'ɵɵattributeInterpolate8': ɵɵattributeInterpolate8,
25553 'ɵɵattributeInterpolateV': ɵɵattributeInterpolateV,
25554 'ɵɵdefineComponent': ɵɵdefineComponent,
25555 'ɵɵdefineDirective': ɵɵdefineDirective,
25556 'ɵɵdefineInjectable': ɵɵdefineInjectable,
25557 'ɵɵdefineInjector': ɵɵdefineInjector,
25558 'ɵɵdefineNgModule': ɵɵdefineNgModule,
25559 'ɵɵdefinePipe': ɵɵdefinePipe,
25560 'ɵɵdirectiveInject': ɵɵdirectiveInject,
25561 'ɵɵgetFactoryOf': ɵɵgetFactoryOf,
25562 'ɵɵgetInheritedFactory': ɵɵgetInheritedFactory,
25563 'ɵɵinject': ɵɵinject,
25564 'ɵɵinjectAttribute': ɵɵinjectAttribute,
25565 'ɵɵinvalidFactory': ɵɵinvalidFactory,
25566 'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
25567 'ɵɵinjectPipeChangeDetectorRef': ɵɵinjectPipeChangeDetectorRef,
25568 'ɵɵtemplateRefExtractor': ɵɵtemplateRefExtractor,
25569 'ɵɵNgOnChangesFeature': ɵɵNgOnChangesFeature,
25570 'ɵɵProvidersFeature': ɵɵProvidersFeature,
25571 'ɵɵCopyDefinitionFeature': ɵɵCopyDefinitionFeature,
25572 'ɵɵInheritDefinitionFeature': ɵɵInheritDefinitionFeature,
25573 'ɵɵnextContext': ɵɵnextContext,
25574 'ɵɵnamespaceHTML': ɵɵnamespaceHTML,
25575 'ɵɵnamespaceMathML': ɵɵnamespaceMathML,
25576 'ɵɵnamespaceSVG': ɵɵnamespaceSVG,
25577 'ɵɵenableBindings': ɵɵenableBindings,
25578 'ɵɵdisableBindings': ɵɵdisableBindings,
25579 'ɵɵelementStart': ɵɵelementStart,
25580 'ɵɵelementEnd': ɵɵelementEnd,
25581 'ɵɵelement': ɵɵelement,
25582 'ɵɵelementContainerStart': ɵɵelementContainerStart,
25583 'ɵɵelementContainerEnd': ɵɵelementContainerEnd,
25584 'ɵɵelementContainer': ɵɵelementContainer,
25585 'ɵɵpureFunction0': ɵɵpureFunction0,
25586 'ɵɵpureFunction1': ɵɵpureFunction1,
25587 'ɵɵpureFunction2': ɵɵpureFunction2,
25588 'ɵɵpureFunction3': ɵɵpureFunction3,
25589 'ɵɵpureFunction4': ɵɵpureFunction4,
25590 'ɵɵpureFunction5': ɵɵpureFunction5,
25591 'ɵɵpureFunction6': ɵɵpureFunction6,
25592 'ɵɵpureFunction7': ɵɵpureFunction7,
25593 'ɵɵpureFunction8': ɵɵpureFunction8,
25594 'ɵɵpureFunctionV': ɵɵpureFunctionV,
25595 'ɵɵgetCurrentView': ɵɵgetCurrentView,
25596 'ɵɵrestoreView': ɵɵrestoreView,
25597 'ɵɵlistener': ɵɵlistener,
25598 'ɵɵprojection': ɵɵprojection,
25599 'ɵɵsyntheticHostProperty': ɵɵsyntheticHostProperty,
25600 'ɵɵsyntheticHostListener': ɵɵsyntheticHostListener,
25601 'ɵɵpipeBind1': ɵɵpipeBind1,
25602 'ɵɵpipeBind2': ɵɵpipeBind2,
25603 'ɵɵpipeBind3': ɵɵpipeBind3,
25604 'ɵɵpipeBind4': ɵɵpipeBind4,
25605 'ɵɵpipeBindV': ɵɵpipeBindV,
25606 'ɵɵprojectionDef': ɵɵprojectionDef,
25607 'ɵɵhostProperty': ɵɵhostProperty,
25608 'ɵɵproperty': ɵɵproperty,
25609 'ɵɵpropertyInterpolate': ɵɵpropertyInterpolate,
25610 'ɵɵpropertyInterpolate1': ɵɵpropertyInterpolate1,
25611 'ɵɵpropertyInterpolate2': ɵɵpropertyInterpolate2,
25612 'ɵɵpropertyInterpolate3': ɵɵpropertyInterpolate3,
25613 'ɵɵpropertyInterpolate4': ɵɵpropertyInterpolate4,
25614 'ɵɵpropertyInterpolate5': ɵɵpropertyInterpolate5,
25615 'ɵɵpropertyInterpolate6': ɵɵpropertyInterpolate6,
25616 'ɵɵpropertyInterpolate7': ɵɵpropertyInterpolate7,
25617 'ɵɵpropertyInterpolate8': ɵɵpropertyInterpolate8,
25618 'ɵɵpropertyInterpolateV': ɵɵpropertyInterpolateV,
25619 'ɵɵpipe': ɵɵpipe,
25620 'ɵɵqueryRefresh': ɵɵqueryRefresh,
25621 'ɵɵviewQuery': ɵɵviewQuery,
25622 'ɵɵstaticViewQuery': ɵɵstaticViewQuery,
25623 'ɵɵstaticContentQuery': ɵɵstaticContentQuery,
25624 'ɵɵloadQuery': ɵɵloadQuery,
25625 'ɵɵcontentQuery': ɵɵcontentQuery,
25626 'ɵɵreference': ɵɵreference,
25627 'ɵɵclassMap': ɵɵclassMap,
25628 'ɵɵclassMapInterpolate1': ɵɵclassMapInterpolate1,
25629 'ɵɵclassMapInterpolate2': ɵɵclassMapInterpolate2,
25630 'ɵɵclassMapInterpolate3': ɵɵclassMapInterpolate3,
25631 'ɵɵclassMapInterpolate4': ɵɵclassMapInterpolate4,
25632 'ɵɵclassMapInterpolate5': ɵɵclassMapInterpolate5,
25633 'ɵɵclassMapInterpolate6': ɵɵclassMapInterpolate6,
25634 'ɵɵclassMapInterpolate7': ɵɵclassMapInterpolate7,
25635 'ɵɵclassMapInterpolate8': ɵɵclassMapInterpolate8,
25636 'ɵɵclassMapInterpolateV': ɵɵclassMapInterpolateV,
25637 'ɵɵstyleMap': ɵɵstyleMap,
25638 'ɵɵstyleMapInterpolate1': ɵɵstyleMapInterpolate1,
25639 'ɵɵstyleMapInterpolate2': ɵɵstyleMapInterpolate2,
25640 'ɵɵstyleMapInterpolate3': ɵɵstyleMapInterpolate3,
25641 'ɵɵstyleMapInterpolate4': ɵɵstyleMapInterpolate4,
25642 'ɵɵstyleMapInterpolate5': ɵɵstyleMapInterpolate5,
25643 'ɵɵstyleMapInterpolate6': ɵɵstyleMapInterpolate6,
25644 'ɵɵstyleMapInterpolate7': ɵɵstyleMapInterpolate7,
25645 'ɵɵstyleMapInterpolate8': ɵɵstyleMapInterpolate8,
25646 'ɵɵstyleMapInterpolateV': ɵɵstyleMapInterpolateV,
25647 'ɵɵstyleProp': ɵɵstyleProp,
25648 'ɵɵstylePropInterpolate1': ɵɵstylePropInterpolate1,
25649 'ɵɵstylePropInterpolate2': ɵɵstylePropInterpolate2,
25650 'ɵɵstylePropInterpolate3': ɵɵstylePropInterpolate3,
25651 'ɵɵstylePropInterpolate4': ɵɵstylePropInterpolate4,
25652 'ɵɵstylePropInterpolate5': ɵɵstylePropInterpolate5,
25653 'ɵɵstylePropInterpolate6': ɵɵstylePropInterpolate6,
25654 'ɵɵstylePropInterpolate7': ɵɵstylePropInterpolate7,
25655 'ɵɵstylePropInterpolate8': ɵɵstylePropInterpolate8,
25656 'ɵɵstylePropInterpolateV': ɵɵstylePropInterpolateV,
25657 'ɵɵclassProp': ɵɵclassProp,
25658 'ɵɵselect': ɵɵselect,
25659 'ɵɵadvance': ɵɵadvance,
25660 'ɵɵtemplate': ɵɵtemplate,
25661 'ɵɵtext': ɵɵtext,
25662 'ɵɵtextInterpolate': ɵɵtextInterpolate,
25663 'ɵɵtextInterpolate1': ɵɵtextInterpolate1,
25664 'ɵɵtextInterpolate2': ɵɵtextInterpolate2,
25665 'ɵɵtextInterpolate3': ɵɵtextInterpolate3,
25666 'ɵɵtextInterpolate4': ɵɵtextInterpolate4,
25667 'ɵɵtextInterpolate5': ɵɵtextInterpolate5,
25668 'ɵɵtextInterpolate6': ɵɵtextInterpolate6,
25669 'ɵɵtextInterpolate7': ɵɵtextInterpolate7,
25670 'ɵɵtextInterpolate8': ɵɵtextInterpolate8,
25671 'ɵɵtextInterpolateV': ɵɵtextInterpolateV,
25672 'ɵɵi18n': ɵɵi18n,
25673 'ɵɵi18nAttributes': ɵɵi18nAttributes,
25674 'ɵɵi18nExp': ɵɵi18nExp,
25675 'ɵɵi18nStart': ɵɵi18nStart,
25676 'ɵɵi18nEnd': ɵɵi18nEnd,
25677 'ɵɵi18nApply': ɵɵi18nApply,
25678 'ɵɵi18nPostprocess': ɵɵi18nPostprocess,
25679 'ɵɵresolveWindow': ɵɵresolveWindow,
25680 'ɵɵresolveDocument': ɵɵresolveDocument,
25681 'ɵɵresolveBody': ɵɵresolveBody,
25682 'ɵɵsetComponentScope': ɵɵsetComponentScope,
25683 'ɵɵsetNgModuleScope': ɵɵsetNgModuleScope,
25684 'ɵɵsanitizeHtml': ɵɵsanitizeHtml,
25685 'ɵɵsanitizeStyle': ɵɵsanitizeStyle,
25686 'ɵɵsanitizeResourceUrl': ɵɵsanitizeResourceUrl,
25687 'ɵɵsanitizeScript': ɵɵsanitizeScript,
25688 'ɵɵsanitizeUrl': ɵɵsanitizeUrl,
25689 'ɵɵsanitizeUrlOrResourceUrl': ɵɵsanitizeUrlOrResourceUrl,
25690});
25691/**
25692 * A mapping of the @angular/core API surface used in generated expressions to the actual symbols.
25693 *
25694 * This should be kept up to date with the public exports of @angular/core.
25695 */
25696const angularCoreEnv = (ɵ0$d)();
25697
25698let jitOptions = null;
25699function setJitOptions(options) {
25700 if (jitOptions !== null) {
25701 if (options.defaultEncapsulation !== jitOptions.defaultEncapsulation) {
25702 ngDevMode &&
25703 console.error('Provided value for `defaultEncapsulation` can not be changed once it has been set.');
25704 return;
25705 }
25706 if (options.preserveWhitespaces !== jitOptions.preserveWhitespaces) {
25707 ngDevMode &&
25708 console.error('Provided value for `preserveWhitespaces` can not be changed once it has been set.');
25709 return;
25710 }
25711 }
25712 jitOptions = options;
25713}
25714function getJitOptions() {
25715 return jitOptions;
25716}
25717function resetJitOptions() {
25718 jitOptions = null;
25719}
25720
25721/**
25722 * @license
25723 * Copyright Google LLC All Rights Reserved.
25724 *
25725 * Use of this source code is governed by an MIT-style license that can be
25726 * found in the LICENSE file at https://angular.io/license
25727 */
25728const EMPTY_ARRAY$5 = [];
25729const moduleQueue = [];
25730/**
25731 * Enqueues moduleDef to be checked later to see if scope can be set on its
25732 * component declarations.
25733 */
25734function enqueueModuleForDelayedScoping(moduleType, ngModule) {
25735 moduleQueue.push({ moduleType, ngModule });
25736}
25737let flushingModuleQueue = false;
25738/**
25739 * Loops over queued module definitions, if a given module definition has all of its
25740 * declarations resolved, it dequeues that module definition and sets the scope on
25741 * its declarations.
25742 */
25743function flushModuleScopingQueueAsMuchAsPossible() {
25744 if (!flushingModuleQueue) {
25745 flushingModuleQueue = true;
25746 try {
25747 for (let i = moduleQueue.length - 1; i >= 0; i--) {
25748 const { moduleType, ngModule } = moduleQueue[i];
25749 if (ngModule.declarations && ngModule.declarations.every(isResolvedDeclaration)) {
25750 // dequeue
25751 moduleQueue.splice(i, 1);
25752 setScopeOnDeclaredComponents(moduleType, ngModule);
25753 }
25754 }
25755 }
25756 finally {
25757 flushingModuleQueue = false;
25758 }
25759 }
25760}
25761/**
25762 * Returns truthy if a declaration has resolved. If the declaration happens to be
25763 * an array of declarations, it will recurse to check each declaration in that array
25764 * (which may also be arrays).
25765 */
25766function isResolvedDeclaration(declaration) {
25767 if (Array.isArray(declaration)) {
25768 return declaration.every(isResolvedDeclaration);
25769 }
25770 return !!resolveForwardRef(declaration);
25771}
25772/**
25773 * Compiles a module in JIT mode.
25774 *
25775 * This function automatically gets called when a class has a `@NgModule` decorator.
25776 */
25777function compileNgModule(moduleType, ngModule = {}) {
25778 compileNgModuleDefs(moduleType, ngModule);
25779 // Because we don't know if all declarations have resolved yet at the moment the
25780 // NgModule decorator is executing, we're enqueueing the setting of module scope
25781 // on its declarations to be run at a later time when all declarations for the module,
25782 // including forward refs, have resolved.
25783 enqueueModuleForDelayedScoping(moduleType, ngModule);
25784}
25785/**
25786 * Compiles and adds the `ɵmod` and `ɵinj` properties to the module class.
25787 *
25788 * It's possible to compile a module via this API which will allow duplicate declarations in its
25789 * root.
25790 */
25791function compileNgModuleDefs(moduleType, ngModule, allowDuplicateDeclarationsInRoot = false) {
25792 ngDevMode && assertDefined(moduleType, 'Required value moduleType');
25793 ngDevMode && assertDefined(ngModule, 'Required value ngModule');
25794 const declarations = flatten(ngModule.declarations || EMPTY_ARRAY$5);
25795 let ngModuleDef = null;
25796 Object.defineProperty(moduleType, NG_MOD_DEF, {
25797 configurable: true,
25798 get: () => {
25799 if (ngModuleDef === null) {
25800 if (ngDevMode && ngModule.imports && ngModule.imports.indexOf(moduleType) > -1) {
25801 // We need to assert this immediately, because allowing it to continue will cause it to
25802 // go into an infinite loop before we've reached the point where we throw all the errors.
25803 throw new Error(`'${stringifyForError(moduleType)}' module can't import itself`);
25804 }
25805 ngModuleDef = getCompilerFacade().compileNgModule(angularCoreEnv, `ng:///${moduleType.name}/ɵmod.js`, {
25806 type: moduleType,
25807 bootstrap: flatten(ngModule.bootstrap || EMPTY_ARRAY$5).map(resolveForwardRef),
25808 declarations: declarations.map(resolveForwardRef),
25809 imports: flatten(ngModule.imports || EMPTY_ARRAY$5)
25810 .map(resolveForwardRef)
25811 .map(expandModuleWithProviders),
25812 exports: flatten(ngModule.exports || EMPTY_ARRAY$5)
25813 .map(resolveForwardRef)
25814 .map(expandModuleWithProviders),
25815 schemas: ngModule.schemas ? flatten(ngModule.schemas) : null,
25816 id: ngModule.id || null,
25817 });
25818 // Set `schemas` on ngModuleDef to an empty array in JIT mode to indicate that runtime
25819 // should verify that there are no unknown elements in a template. In AOT mode, that check
25820 // happens at compile time and `schemas` information is not present on Component and Module
25821 // defs after compilation (so the check doesn't happen the second time at runtime).
25822 if (!ngModuleDef.schemas) {
25823 ngModuleDef.schemas = [];
25824 }
25825 }
25826 return ngModuleDef;
25827 }
25828 });
25829 let ngInjectorDef = null;
25830 Object.defineProperty(moduleType, NG_INJ_DEF, {
25831 get: () => {
25832 if (ngInjectorDef === null) {
25833 ngDevMode &&
25834 verifySemanticsOfNgModuleDef(moduleType, allowDuplicateDeclarationsInRoot);
25835 const meta = {
25836 name: moduleType.name,
25837 type: moduleType,
25838 deps: reflectDependencies(moduleType),
25839 providers: ngModule.providers || EMPTY_ARRAY$5,
25840 imports: [
25841 (ngModule.imports || EMPTY_ARRAY$5).map(resolveForwardRef),
25842 (ngModule.exports || EMPTY_ARRAY$5).map(resolveForwardRef),
25843 ],
25844 };
25845 ngInjectorDef = getCompilerFacade().compileInjector(angularCoreEnv, `ng:///${moduleType.name}/ɵinj.js`, meta);
25846 }
25847 return ngInjectorDef;
25848 },
25849 // Make the property configurable in dev mode to allow overriding in tests
25850 configurable: !!ngDevMode,
25851 });
25852}
25853function verifySemanticsOfNgModuleDef(moduleType, allowDuplicateDeclarationsInRoot, importingModule) {
25854 if (verifiedNgModule.get(moduleType))
25855 return;
25856 verifiedNgModule.set(moduleType, true);
25857 moduleType = resolveForwardRef(moduleType);
25858 let ngModuleDef;
25859 if (importingModule) {
25860 ngModuleDef = getNgModuleDef(moduleType);
25861 if (!ngModuleDef) {
25862 throw new Error(`Unexpected value '${moduleType.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
25863 }
25864 }
25865 else {
25866 ngModuleDef = getNgModuleDef(moduleType, true);
25867 }
25868 const errors = [];
25869 const declarations = maybeUnwrapFn(ngModuleDef.declarations);
25870 const imports = maybeUnwrapFn(ngModuleDef.imports);
25871 flatten(imports).map(unwrapModuleWithProvidersImports).forEach(mod => {
25872 verifySemanticsOfNgModuleImport(mod, moduleType);
25873 verifySemanticsOfNgModuleDef(mod, false, moduleType);
25874 });
25875 const exports = maybeUnwrapFn(ngModuleDef.exports);
25876 declarations.forEach(verifyDeclarationsHaveDefinitions);
25877 declarations.forEach(verifyDirectivesHaveSelector);
25878 const combinedDeclarations = [
25879 ...declarations.map(resolveForwardRef),
25880 ...flatten(imports.map(computeCombinedExports)).map(resolveForwardRef),
25881 ];
25882 exports.forEach(verifyExportsAreDeclaredOrReExported);
25883 declarations.forEach(decl => verifyDeclarationIsUnique(decl, allowDuplicateDeclarationsInRoot));
25884 declarations.forEach(verifyComponentEntryComponentsIsPartOfNgModule);
25885 const ngModule = getAnnotation(moduleType, 'NgModule');
25886 if (ngModule) {
25887 ngModule.imports &&
25888 flatten(ngModule.imports).map(unwrapModuleWithProvidersImports).forEach(mod => {
25889 verifySemanticsOfNgModuleImport(mod, moduleType);
25890 verifySemanticsOfNgModuleDef(mod, false, moduleType);
25891 });
25892 ngModule.bootstrap && deepForEach(ngModule.bootstrap, verifyCorrectBootstrapType);
25893 ngModule.bootstrap && deepForEach(ngModule.bootstrap, verifyComponentIsPartOfNgModule);
25894 ngModule.entryComponents &&
25895 deepForEach(ngModule.entryComponents, verifyComponentIsPartOfNgModule);
25896 }
25897 // Throw Error if any errors were detected.
25898 if (errors.length) {
25899 throw new Error(errors.join('\n'));
25900 }
25901 ////////////////////////////////////////////////////////////////////////////////////////////////
25902 function verifyDeclarationsHaveDefinitions(type) {
25903 type = resolveForwardRef(type);
25904 const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef(type);
25905 if (!def) {
25906 errors.push(`Unexpected value '${stringifyForError(type)}' declared by the module '${stringifyForError(moduleType)}'. Please add a @Pipe/@Directive/@Component annotation.`);
25907 }
25908 }
25909 function verifyDirectivesHaveSelector(type) {
25910 type = resolveForwardRef(type);
25911 const def = getDirectiveDef(type);
25912 if (!getComponentDef(type) && def && def.selectors.length == 0) {
25913 errors.push(`Directive ${stringifyForError(type)} has no selector, please add it!`);
25914 }
25915 }
25916 function verifyExportsAreDeclaredOrReExported(type) {
25917 type = resolveForwardRef(type);
25918 const kind = getComponentDef(type) && 'component' || getDirectiveDef(type) && 'directive' ||
25919 getPipeDef(type) && 'pipe';
25920 if (kind) {
25921 // only checked if we are declared as Component, Directive, or Pipe
25922 // Modules don't need to be declared or imported.
25923 if (combinedDeclarations.lastIndexOf(type) === -1) {
25924 // We are exporting something which we don't explicitly declare or import.
25925 errors.push(`Can't export ${kind} ${stringifyForError(type)} from ${stringifyForError(moduleType)} as it was neither declared nor imported!`);
25926 }
25927 }
25928 }
25929 function verifyDeclarationIsUnique(type, suppressErrors) {
25930 type = resolveForwardRef(type);
25931 const existingModule = ownerNgModule.get(type);
25932 if (existingModule && existingModule !== moduleType) {
25933 if (!suppressErrors) {
25934 const modules = [existingModule, moduleType].map(stringifyForError).sort();
25935 errors.push(`Type ${stringifyForError(type)} is part of the declarations of 2 modules: ${modules[0]} and ${modules[1]}! ` +
25936 `Please consider moving ${stringifyForError(type)} to a higher module that imports ${modules[0]} and ${modules[1]}. ` +
25937 `You can also create a new NgModule that exports and includes ${stringifyForError(type)} then import that NgModule in ${modules[0]} and ${modules[1]}.`);
25938 }
25939 }
25940 else {
25941 // Mark type as having owner.
25942 ownerNgModule.set(type, moduleType);
25943 }
25944 }
25945 function verifyComponentIsPartOfNgModule(type) {
25946 type = resolveForwardRef(type);
25947 const existingModule = ownerNgModule.get(type);
25948 if (!existingModule) {
25949 errors.push(`Component ${stringifyForError(type)} is not part of any NgModule or the module has not been imported into your module.`);
25950 }
25951 }
25952 function verifyCorrectBootstrapType(type) {
25953 type = resolveForwardRef(type);
25954 if (!getComponentDef(type)) {
25955 errors.push(`${stringifyForError(type)} cannot be used as an entry component.`);
25956 }
25957 }
25958 function verifyComponentEntryComponentsIsPartOfNgModule(type) {
25959 type = resolveForwardRef(type);
25960 if (getComponentDef(type)) {
25961 // We know we are component
25962 const component = getAnnotation(type, 'Component');
25963 if (component && component.entryComponents) {
25964 deepForEach(component.entryComponents, verifyComponentIsPartOfNgModule);
25965 }
25966 }
25967 }
25968 function verifySemanticsOfNgModuleImport(type, importingModule) {
25969 type = resolveForwardRef(type);
25970 if (getComponentDef(type) || getDirectiveDef(type)) {
25971 throw new Error(`Unexpected directive '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
25972 }
25973 if (getPipeDef(type)) {
25974 throw new Error(`Unexpected pipe '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`);
25975 }
25976 }
25977}
25978function unwrapModuleWithProvidersImports(typeOrWithProviders) {
25979 typeOrWithProviders = resolveForwardRef(typeOrWithProviders);
25980 return typeOrWithProviders.ngModule || typeOrWithProviders;
25981}
25982function getAnnotation(type, name) {
25983 let annotation = null;
25984 collect(type.__annotations__);
25985 collect(type.decorators);
25986 return annotation;
25987 function collect(annotations) {
25988 if (annotations) {
25989 annotations.forEach(readAnnotation);
25990 }
25991 }
25992 function readAnnotation(decorator) {
25993 if (!annotation) {
25994 const proto = Object.getPrototypeOf(decorator);
25995 if (proto.ngMetadataName == name) {
25996 annotation = decorator;
25997 }
25998 else if (decorator.type) {
25999 const proto = Object.getPrototypeOf(decorator.type);
26000 if (proto.ngMetadataName == name) {
26001 annotation = decorator.args[0];
26002 }
26003 }
26004 }
26005 }
26006}
26007/**
26008 * Keep track of compiled components. This is needed because in tests we often want to compile the
26009 * same component with more than one NgModule. This would cause an error unless we reset which
26010 * NgModule the component belongs to. We keep the list of compiled components here so that the
26011 * TestBed can reset it later.
26012 */
26013let ownerNgModule = new Map();
26014let verifiedNgModule = new Map();
26015function resetCompiledComponents() {
26016 ownerNgModule = new Map();
26017 verifiedNgModule = new Map();
26018 moduleQueue.length = 0;
26019}
26020/**
26021 * Computes the combined declarations of explicit declarations, as well as declarations inherited by
26022 * traversing the exports of imported modules.
26023 * @param type
26024 */
26025function computeCombinedExports(type) {
26026 type = resolveForwardRef(type);
26027 const ngModuleDef = getNgModuleDef(type, true);
26028 return [...flatten(maybeUnwrapFn(ngModuleDef.exports).map((type) => {
26029 const ngModuleDef = getNgModuleDef(type);
26030 if (ngModuleDef) {
26031 verifySemanticsOfNgModuleDef(type, false);
26032 return computeCombinedExports(type);
26033 }
26034 else {
26035 return type;
26036 }
26037 }))];
26038}
26039/**
26040 * Some declared components may be compiled asynchronously, and thus may not have their
26041 * ɵcmp set yet. If this is the case, then a reference to the module is written into
26042 * the `ngSelectorScope` property of the declared type.
26043 */
26044function setScopeOnDeclaredComponents(moduleType, ngModule) {
26045 const declarations = flatten(ngModule.declarations || EMPTY_ARRAY$5);
26046 const transitiveScopes = transitiveScopesFor(moduleType);
26047 declarations.forEach(declaration => {
26048 if (declaration.hasOwnProperty(NG_COMP_DEF)) {
26049 // A `ɵcmp` field exists - go ahead and patch the component directly.
26050 const component = declaration;
26051 const componentDef = getComponentDef(component);
26052 patchComponentDefWithScope(componentDef, transitiveScopes);
26053 }
26054 else if (!declaration.hasOwnProperty(NG_DIR_DEF) && !declaration.hasOwnProperty(NG_PIPE_DEF)) {
26055 // Set `ngSelectorScope` for future reference when the component compilation finishes.
26056 declaration.ngSelectorScope = moduleType;
26057 }
26058 });
26059}
26060/**
26061 * Patch the definition of a component with directives and pipes from the compilation scope of
26062 * a given module.
26063 */
26064function patchComponentDefWithScope(componentDef, transitiveScopes) {
26065 componentDef.directiveDefs = () => Array.from(transitiveScopes.compilation.directives)
26066 .map(dir => dir.hasOwnProperty(NG_COMP_DEF) ? getComponentDef(dir) : getDirectiveDef(dir))
26067 .filter(def => !!def);
26068 componentDef.pipeDefs = () => Array.from(transitiveScopes.compilation.pipes).map(pipe => getPipeDef(pipe));
26069 componentDef.schemas = transitiveScopes.schemas;
26070 // Since we avoid Components/Directives/Pipes recompiling in case there are no overrides, we
26071 // may face a problem where previously compiled defs available to a given Component/Directive
26072 // are cached in TView and may become stale (in case any of these defs gets recompiled). In
26073 // order to avoid this problem, we force fresh TView to be created.
26074 componentDef.tView = null;
26075}
26076/**
26077 * Compute the pair of transitive scopes (compilation scope and exported scope) for a given module.
26078 *
26079 * This operation is memoized and the result is cached on the module's definition. This function can
26080 * be called on modules with components that have not fully compiled yet, but the result should not
26081 * be used until they have.
26082 *
26083 * @param moduleType module that transitive scope should be calculated for.
26084 */
26085function transitiveScopesFor(moduleType) {
26086 if (!isNgModule(moduleType)) {
26087 throw new Error(`${moduleType.name} does not have a module def (ɵmod property)`);
26088 }
26089 const def = getNgModuleDef(moduleType);
26090 if (def.transitiveCompileScopes !== null) {
26091 return def.transitiveCompileScopes;
26092 }
26093 const scopes = {
26094 schemas: def.schemas || null,
26095 compilation: {
26096 directives: new Set(),
26097 pipes: new Set(),
26098 },
26099 exported: {
26100 directives: new Set(),
26101 pipes: new Set(),
26102 },
26103 };
26104 maybeUnwrapFn(def.imports).forEach((imported) => {
26105 const importedType = imported;
26106 if (!isNgModule(importedType)) {
26107 throw new Error(`Importing ${importedType.name} which does not have a ɵmod property`);
26108 }
26109 // When this module imports another, the imported module's exported directives and pipes are
26110 // added to the compilation scope of this module.
26111 const importedScope = transitiveScopesFor(importedType);
26112 importedScope.exported.directives.forEach(entry => scopes.compilation.directives.add(entry));
26113 importedScope.exported.pipes.forEach(entry => scopes.compilation.pipes.add(entry));
26114 });
26115 maybeUnwrapFn(def.declarations).forEach(declared => {
26116 const declaredWithDefs = declared;
26117 if (getPipeDef(declaredWithDefs)) {
26118 scopes.compilation.pipes.add(declared);
26119 }
26120 else {
26121 // Either declared has a ɵcmp or ɵdir, or it's a component which hasn't
26122 // had its template compiled yet. In either case, it gets added to the compilation's
26123 // directives.
26124 scopes.compilation.directives.add(declared);
26125 }
26126 });
26127 maybeUnwrapFn(def.exports).forEach((exported) => {
26128 const exportedType = exported;
26129 // Either the type is a module, a pipe, or a component/directive (which may not have a
26130 // ɵcmp as it might be compiled asynchronously).
26131 if (isNgModule(exportedType)) {
26132 // When this module exports another, the exported module's exported directives and pipes are
26133 // added to both the compilation and exported scopes of this module.
26134 const exportedScope = transitiveScopesFor(exportedType);
26135 exportedScope.exported.directives.forEach(entry => {
26136 scopes.compilation.directives.add(entry);
26137 scopes.exported.directives.add(entry);
26138 });
26139 exportedScope.exported.pipes.forEach(entry => {
26140 scopes.compilation.pipes.add(entry);
26141 scopes.exported.pipes.add(entry);
26142 });
26143 }
26144 else if (getPipeDef(exportedType)) {
26145 scopes.exported.pipes.add(exportedType);
26146 }
26147 else {
26148 scopes.exported.directives.add(exportedType);
26149 }
26150 });
26151 def.transitiveCompileScopes = scopes;
26152 return scopes;
26153}
26154function expandModuleWithProviders(value) {
26155 if (isModuleWithProviders(value)) {
26156 return value.ngModule;
26157 }
26158 return value;
26159}
26160function isModuleWithProviders(value) {
26161 return value.ngModule !== undefined;
26162}
26163function isNgModule(value) {
26164 return !!getNgModuleDef(value);
26165}
26166
26167/**
26168 * @license
26169 * Copyright Google LLC All Rights Reserved.
26170 *
26171 * Use of this source code is governed by an MIT-style license that can be
26172 * found in the LICENSE file at https://angular.io/license
26173 */
26174/**
26175 * Keep track of the compilation depth to avoid reentrancy issues during JIT compilation. This
26176 * matters in the following scenario:
26177 *
26178 * Consider a component 'A' that extends component 'B', both declared in module 'M'. During
26179 * the compilation of 'A' the definition of 'B' is requested to capture the inheritance chain,
26180 * potentially triggering compilation of 'B'. If this nested compilation were to trigger
26181 * `flushModuleScopingQueueAsMuchAsPossible` it may happen that module 'M' is still pending in the
26182 * queue, resulting in 'A' and 'B' to be patched with the NgModule scope. As the compilation of
26183 * 'A' is still in progress, this would introduce a circular dependency on its compilation. To avoid
26184 * this issue, the module scope queue is only flushed for compilations at the depth 0, to ensure
26185 * all compilations have finished.
26186 */
26187let compilationDepth = 0;
26188/**
26189 * Compile an Angular component according to its decorator metadata, and patch the resulting
26190 * component def (ɵcmp) onto the component type.
26191 *
26192 * Compilation may be asynchronous (due to the need to resolve URLs for the component template or
26193 * other resources, for example). In the event that compilation is not immediate, `compileComponent`
26194 * will enqueue resource resolution into a global queue and will fail to return the `ɵcmp`
26195 * until the global queue has been resolved with a call to `resolveComponentResources`.
26196 */
26197function compileComponent(type, metadata) {
26198 // Initialize ngDevMode. This must be the first statement in compileComponent.
26199 // See the `initNgDevMode` docstring for more information.
26200 (typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode();
26201 let ngComponentDef = null;
26202 // Metadata may have resources which need to be resolved.
26203 maybeQueueResolutionOfComponentResources(type, metadata);
26204 // Note that we're using the same function as `Directive`, because that's only subset of metadata
26205 // that we need to create the ngFactoryDef. We're avoiding using the component metadata
26206 // because we'd have to resolve the asynchronous templates.
26207 addDirectiveFactoryDef(type, metadata);
26208 Object.defineProperty(type, NG_COMP_DEF, {
26209 get: () => {
26210 if (ngComponentDef === null) {
26211 const compiler = getCompilerFacade();
26212 if (componentNeedsResolution(metadata)) {
26213 const error = [`Component '${type.name}' is not resolved:`];
26214 if (metadata.templateUrl) {
26215 error.push(` - templateUrl: ${metadata.templateUrl}`);
26216 }
26217 if (metadata.styleUrls && metadata.styleUrls.length) {
26218 error.push(` - styleUrls: ${JSON.stringify(metadata.styleUrls)}`);
26219 }
26220 error.push(`Did you run and wait for 'resolveComponentResources()'?`);
26221 throw new Error(error.join('\n'));
26222 }
26223 // This const was called `jitOptions` previously but had to be renamed to `options` because
26224 // of a bug with Terser that caused optimized JIT builds to throw a `ReferenceError`.
26225 // This bug was investigated in https://github.com/angular/angular-cli/issues/17264.
26226 // We should not rename it back until https://github.com/terser/terser/issues/615 is fixed.
26227 const options = getJitOptions();
26228 let preserveWhitespaces = metadata.preserveWhitespaces;
26229 if (preserveWhitespaces === undefined) {
26230 if (options !== null && options.preserveWhitespaces !== undefined) {
26231 preserveWhitespaces = options.preserveWhitespaces;
26232 }
26233 else {
26234 preserveWhitespaces = false;
26235 }
26236 }
26237 let encapsulation = metadata.encapsulation;
26238 if (encapsulation === undefined) {
26239 if (options !== null && options.defaultEncapsulation !== undefined) {
26240 encapsulation = options.defaultEncapsulation;
26241 }
26242 else {
26243 encapsulation = ViewEncapsulation$1.Emulated;
26244 }
26245 }
26246 const templateUrl = metadata.templateUrl || `ng:///${type.name}/template.html`;
26247 const meta = Object.assign(Object.assign({}, directiveMetadata(type, metadata)), { typeSourceSpan: compiler.createParseSourceSpan('Component', type.name, templateUrl), template: metadata.template || '', preserveWhitespaces, styles: metadata.styles || EMPTY_ARRAY, animations: metadata.animations, directives: [], changeDetection: metadata.changeDetection, pipes: new Map(), encapsulation, interpolation: metadata.interpolation, viewProviders: metadata.viewProviders || null });
26248 compilationDepth++;
26249 try {
26250 if (meta.usesInheritance) {
26251 addDirectiveDefToUndecoratedParents(type);
26252 }
26253 ngComponentDef = compiler.compileComponent(angularCoreEnv, templateUrl, meta);
26254 }
26255 finally {
26256 // Ensure that the compilation depth is decremented even when the compilation failed.
26257 compilationDepth--;
26258 }
26259 if (compilationDepth === 0) {
26260 // When NgModule decorator executed, we enqueued the module definition such that
26261 // it would only dequeue and add itself as module scope to all of its declarations,
26262 // but only if if all of its declarations had resolved. This call runs the check
26263 // to see if any modules that are in the queue can be dequeued and add scope to
26264 // their declarations.
26265 flushModuleScopingQueueAsMuchAsPossible();
26266 }
26267 // If component compilation is async, then the @NgModule annotation which declares the
26268 // component may execute and set an ngSelectorScope property on the component type. This
26269 // allows the component to patch itself with directiveDefs from the module after it
26270 // finishes compiling.
26271 if (hasSelectorScope(type)) {
26272 const scopes = transitiveScopesFor(type.ngSelectorScope);
26273 patchComponentDefWithScope(ngComponentDef, scopes);
26274 }
26275 }
26276 return ngComponentDef;
26277 },
26278 // Make the property configurable in dev mode to allow overriding in tests
26279 configurable: !!ngDevMode,
26280 });
26281}
26282function hasSelectorScope(component) {
26283 return component.ngSelectorScope !== undefined;
26284}
26285/**
26286 * Compile an Angular directive according to its decorator metadata, and patch the resulting
26287 * directive def onto the component type.
26288 *
26289 * In the event that compilation is not immediate, `compileDirective` will return a `Promise` which
26290 * will resolve when compilation completes and the directive becomes usable.
26291 */
26292function compileDirective(type, directive) {
26293 let ngDirectiveDef = null;
26294 addDirectiveFactoryDef(type, directive || {});
26295 Object.defineProperty(type, NG_DIR_DEF, {
26296 get: () => {
26297 if (ngDirectiveDef === null) {
26298 // `directive` can be null in the case of abstract directives as a base class
26299 // that use `@Directive()` with no selector. In that case, pass empty object to the
26300 // `directiveMetadata` function instead of null.
26301 const meta = getDirectiveMetadata(type, directive || {});
26302 ngDirectiveDef =
26303 getCompilerFacade().compileDirective(angularCoreEnv, meta.sourceMapUrl, meta.metadata);
26304 }
26305 return ngDirectiveDef;
26306 },
26307 // Make the property configurable in dev mode to allow overriding in tests
26308 configurable: !!ngDevMode,
26309 });
26310}
26311function getDirectiveMetadata(type, metadata) {
26312 const name = type && type.name;
26313 const sourceMapUrl = `ng:///${name}/ɵdir.js`;
26314 const compiler = getCompilerFacade();
26315 const facade = directiveMetadata(type, metadata);
26316 facade.typeSourceSpan = compiler.createParseSourceSpan('Directive', name, sourceMapUrl);
26317 if (facade.usesInheritance) {
26318 addDirectiveDefToUndecoratedParents(type);
26319 }
26320 return { metadata: facade, sourceMapUrl };
26321}
26322function addDirectiveFactoryDef(type, metadata) {
26323 let ngFactoryDef = null;
26324 Object.defineProperty(type, NG_FACTORY_DEF, {
26325 get: () => {
26326 if (ngFactoryDef === null) {
26327 const meta = getDirectiveMetadata(type, metadata);
26328 const compiler = getCompilerFacade();
26329 ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${type.name}/ɵfac.js`, Object.assign(Object.assign({}, meta.metadata), { injectFn: 'directiveInject', target: compiler.R3FactoryTarget.Directive }));
26330 }
26331 return ngFactoryDef;
26332 },
26333 // Make the property configurable in dev mode to allow overriding in tests
26334 configurable: !!ngDevMode,
26335 });
26336}
26337function extendsDirectlyFromObject(type) {
26338 return Object.getPrototypeOf(type.prototype) === Object.prototype;
26339}
26340/**
26341 * Extract the `R3DirectiveMetadata` for a particular directive (either a `Directive` or a
26342 * `Component`).
26343 */
26344function directiveMetadata(type, metadata) {
26345 // Reflect inputs and outputs.
26346 const reflect = getReflect();
26347 const propMetadata = reflect.ownPropMetadata(type);
26348 return {
26349 name: type.name,
26350 type: type,
26351 typeArgumentCount: 0,
26352 selector: metadata.selector !== undefined ? metadata.selector : null,
26353 deps: reflectDependencies(type),
26354 host: metadata.host || EMPTY_OBJ,
26355 propMetadata: propMetadata,
26356 inputs: metadata.inputs || EMPTY_ARRAY,
26357 outputs: metadata.outputs || EMPTY_ARRAY,
26358 queries: extractQueriesMetadata(type, propMetadata, isContentQuery),
26359 lifecycle: { usesOnChanges: reflect.hasLifecycleHook(type, 'ngOnChanges') },
26360 typeSourceSpan: null,
26361 usesInheritance: !extendsDirectlyFromObject(type),
26362 exportAs: extractExportAs(metadata.exportAs),
26363 providers: metadata.providers || null,
26364 viewQueries: extractQueriesMetadata(type, propMetadata, isViewQuery)
26365 };
26366}
26367/**
26368 * Adds a directive definition to all parent classes of a type that don't have an Angular decorator.
26369 */
26370function addDirectiveDefToUndecoratedParents(type) {
26371 const objPrototype = Object.prototype;
26372 let parent = Object.getPrototypeOf(type.prototype).constructor;
26373 // Go up the prototype until we hit `Object`.
26374 while (parent && parent !== objPrototype) {
26375 // Since inheritance works if the class was annotated already, we only need to add
26376 // the def if there are no annotations and the def hasn't been created already.
26377 if (!getDirectiveDef(parent) && !getComponentDef(parent) &&
26378 shouldAddAbstractDirective(parent)) {
26379 compileDirective(parent, null);
26380 }
26381 parent = Object.getPrototypeOf(parent);
26382 }
26383}
26384function convertToR3QueryPredicate(selector) {
26385 return typeof selector === 'string' ? splitByComma(selector) : resolveForwardRef(selector);
26386}
26387function convertToR3QueryMetadata(propertyName, ann) {
26388 return {
26389 propertyName: propertyName,
26390 predicate: convertToR3QueryPredicate(ann.selector),
26391 descendants: ann.descendants,
26392 first: ann.first,
26393 read: ann.read ? ann.read : null,
26394 static: !!ann.static
26395 };
26396}
26397function extractQueriesMetadata(type, propMetadata, isQueryAnn) {
26398 const queriesMeta = [];
26399 for (const field in propMetadata) {
26400 if (propMetadata.hasOwnProperty(field)) {
26401 const annotations = propMetadata[field];
26402 annotations.forEach(ann => {
26403 if (isQueryAnn(ann)) {
26404 if (!ann.selector) {
26405 throw new Error(`Can't construct a query for the property "${field}" of ` +
26406 `"${stringifyForError(type)}" since the query selector wasn't defined.`);
26407 }
26408 if (annotations.some(isInputAnnotation)) {
26409 throw new Error(`Cannot combine @Input decorators with query decorators`);
26410 }
26411 queriesMeta.push(convertToR3QueryMetadata(field, ann));
26412 }
26413 });
26414 }
26415 }
26416 return queriesMeta;
26417}
26418function extractExportAs(exportAs) {
26419 return exportAs === undefined ? null : splitByComma(exportAs);
26420}
26421function isContentQuery(value) {
26422 const name = value.ngMetadataName;
26423 return name === 'ContentChild' || name === 'ContentChildren';
26424}
26425function isViewQuery(value) {
26426 const name = value.ngMetadataName;
26427 return name === 'ViewChild' || name === 'ViewChildren';
26428}
26429function isInputAnnotation(value) {
26430 return value.ngMetadataName === 'Input';
26431}
26432function splitByComma(value) {
26433 return value.split(',').map(piece => piece.trim());
26434}
26435const LIFECYCLE_HOOKS = [
26436 'ngOnChanges', 'ngOnInit', 'ngOnDestroy', 'ngDoCheck', 'ngAfterViewInit', 'ngAfterViewChecked',
26437 'ngAfterContentInit', 'ngAfterContentChecked'
26438];
26439function shouldAddAbstractDirective(type) {
26440 const reflect = getReflect();
26441 if (LIFECYCLE_HOOKS.some(hookName => reflect.hasLifecycleHook(type, hookName))) {
26442 return true;
26443 }
26444 const propMetadata = reflect.propMetadata(type);
26445 for (const field in propMetadata) {
26446 const annotations = propMetadata[field];
26447 for (let i = 0; i < annotations.length; i++) {
26448 const current = annotations[i];
26449 const metadataName = current.ngMetadataName;
26450 if (isInputAnnotation(current) || isContentQuery(current) || isViewQuery(current) ||
26451 metadataName === 'Output' || metadataName === 'HostBinding' ||
26452 metadataName === 'HostListener') {
26453 return true;
26454 }
26455 }
26456 }
26457 return false;
26458}
26459
26460/**
26461 * @license
26462 * Copyright Google LLC All Rights Reserved.
26463 *
26464 * Use of this source code is governed by an MIT-style license that can be
26465 * found in the LICENSE file at https://angular.io/license
26466 */
26467function compilePipe(type, meta) {
26468 let ngPipeDef = null;
26469 let ngFactoryDef = null;
26470 Object.defineProperty(type, NG_FACTORY_DEF, {
26471 get: () => {
26472 if (ngFactoryDef === null) {
26473 const metadata = getPipeMetadata(type, meta);
26474 const compiler = getCompilerFacade();
26475 ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${metadata.name}/ɵfac.js`, Object.assign(Object.assign({}, metadata), { injectFn: 'directiveInject', target: compiler.R3FactoryTarget.Pipe }));
26476 }
26477 return ngFactoryDef;
26478 },
26479 // Make the property configurable in dev mode to allow overriding in tests
26480 configurable: !!ngDevMode,
26481 });
26482 Object.defineProperty(type, NG_PIPE_DEF, {
26483 get: () => {
26484 if (ngPipeDef === null) {
26485 const metadata = getPipeMetadata(type, meta);
26486 ngPipeDef = getCompilerFacade().compilePipe(angularCoreEnv, `ng:///${metadata.name}/ɵpipe.js`, metadata);
26487 }
26488 return ngPipeDef;
26489 },
26490 // Make the property configurable in dev mode to allow overriding in tests
26491 configurable: !!ngDevMode,
26492 });
26493}
26494function getPipeMetadata(type, meta) {
26495 return {
26496 type: type,
26497 typeArgumentCount: 0,
26498 name: type.name,
26499 deps: reflectDependencies(type),
26500 pipeName: meta.name,
26501 pure: meta.pure !== undefined ? meta.pure : true
26502 };
26503}
26504
26505/**
26506 * @license
26507 * Copyright Google LLC All Rights Reserved.
26508 *
26509 * Use of this source code is governed by an MIT-style license that can be
26510 * found in the LICENSE file at https://angular.io/license
26511 */
26512const ɵ0$e = (dir = {}) => dir, ɵ1$3 = (type, meta) => SWITCH_COMPILE_DIRECTIVE(type, meta);
26513/**
26514 * Type of the Directive metadata.
26515 *
26516 * @publicApi
26517 */
26518const Directive = makeDecorator('Directive', ɵ0$e, undefined, undefined, ɵ1$3);
26519const ɵ2$1 = (c = {}) => (Object.assign({ changeDetection: ChangeDetectionStrategy.Default }, c)), ɵ3$1 = (type, meta) => SWITCH_COMPILE_COMPONENT(type, meta);
26520/**
26521 * Component decorator and metadata.
26522 *
26523 * @Annotation
26524 * @publicApi
26525 */
26526const Component = makeDecorator('Component', ɵ2$1, Directive, undefined, ɵ3$1);
26527const ɵ4 = (p) => (Object.assign({ pure: true }, p)), ɵ5 = (type, meta) => SWITCH_COMPILE_PIPE(type, meta);
26528/**
26529 * @Annotation
26530 * @publicApi
26531 */
26532const Pipe = makeDecorator('Pipe', ɵ4, undefined, undefined, ɵ5);
26533const ɵ6 = (bindingPropertyName) => ({ bindingPropertyName });
26534/**
26535 * @Annotation
26536 * @publicApi
26537 */
26538const Input = makePropDecorator('Input', ɵ6);
26539const ɵ7 = (bindingPropertyName) => ({ bindingPropertyName });
26540/**
26541 * @Annotation
26542 * @publicApi
26543 */
26544const Output = makePropDecorator('Output', ɵ7);
26545const ɵ8 = (hostPropertyName) => ({ hostPropertyName });
26546/**
26547 * @Annotation
26548 * @publicApi
26549 */
26550const HostBinding = makePropDecorator('HostBinding', ɵ8);
26551const ɵ9 = (eventName, args) => ({ eventName, args });
26552/**
26553 * Decorator that binds a DOM event to a host listener and supplies configuration metadata.
26554 * Angular invokes the supplied handler method when the host element emits the specified event,
26555 * and updates the bound element with the result.
26556 *
26557 * If the handler method returns false, applies `preventDefault` on the bound element.
26558 *
26559 * @usageNotes
26560 *
26561 * The following example declares a directive
26562 * that attaches a click listener to a button and counts clicks.
26563 *
26564 * ```ts
26565 * @Directive({selector: 'button[counting]'})
26566 * class CountClicks {
26567 * numberOfClicks = 0;
26568 *
26569 * @HostListener('click', ['$event.target'])
26570 * onClick(btn) {
26571 * console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
26572 * }
26573 * }
26574 *
26575 * @Component({
26576 * selector: 'app',
26577 * template: '<button counting>Increment</button>',
26578 * })
26579 * class App {}
26580 *
26581 * ```
26582 *
26583 * The following example registers another DOM event handler that listens for key-press events.
26584 * ``` ts
26585 * import { HostListener, Component } from "@angular/core";
26586 *
26587 * @Component({
26588 * selector: 'app',
26589 * template: `<h1>Hello, you have pressed keys {{counter}} number of times!</h1> Press any key to
26590 * increment the counter.
26591 * <button (click)="resetCounter()">Reset Counter</button>`
26592 * })
26593 * class AppComponent {
26594 * counter = 0;
26595 * @HostListener('window:keydown', ['$event'])
26596 * handleKeyDown(event: KeyboardEvent) {
26597 * this.counter++;
26598 * }
26599 * resetCounter() {
26600 * this.counter = 0;
26601 * }
26602 * }
26603 * ```
26604 *
26605 * @Annotation
26606 * @publicApi
26607 */
26608const HostListener = makePropDecorator('HostListener', ɵ9);
26609const SWITCH_COMPILE_COMPONENT__POST_R3__ = compileComponent;
26610const SWITCH_COMPILE_DIRECTIVE__POST_R3__ = compileDirective;
26611const SWITCH_COMPILE_PIPE__POST_R3__ = compilePipe;
26612const SWITCH_COMPILE_COMPONENT__PRE_R3__ = noop;
26613const SWITCH_COMPILE_DIRECTIVE__PRE_R3__ = noop;
26614const SWITCH_COMPILE_PIPE__PRE_R3__ = noop;
26615const SWITCH_COMPILE_COMPONENT = SWITCH_COMPILE_COMPONENT__PRE_R3__;
26616const SWITCH_COMPILE_DIRECTIVE = SWITCH_COMPILE_DIRECTIVE__PRE_R3__;
26617const SWITCH_COMPILE_PIPE = SWITCH_COMPILE_PIPE__PRE_R3__;
26618
26619/**
26620 * @license
26621 * Copyright Google LLC All Rights Reserved.
26622 *
26623 * Use of this source code is governed by an MIT-style license that can be
26624 * found in the LICENSE file at https://angular.io/license
26625 */
26626const ɵ0$f = (ngModule) => ngModule, ɵ1$4 =
26627/**
26628 * Decorator that marks the following class as an NgModule, and supplies
26629 * configuration metadata for it.
26630 *
26631 * * The `declarations` and `entryComponents` options configure the compiler
26632 * with information about what belongs to the NgModule.
26633 * * The `providers` options configures the NgModule's injector to provide
26634 * dependencies the NgModule members.
26635 * * The `imports` and `exports` options bring in members from other modules, and make
26636 * this module's members available to others.
26637 */
26638(type, meta) => SWITCH_COMPILE_NGMODULE(type, meta);
26639/**
26640 * @Annotation
26641 * @publicApi
26642 */
26643const NgModule = makeDecorator('NgModule', ɵ0$f, undefined, undefined, ɵ1$4);
26644function preR3NgModuleCompile(moduleType, metadata) {
26645 let imports = (metadata && metadata.imports) || [];
26646 if (metadata && metadata.exports) {
26647 imports = [...imports, metadata.exports];
26648 }
26649 moduleType.ɵinj = ɵɵdefineInjector({
26650 factory: convertInjectableProviderToFactory(moduleType, { useClass: moduleType }),
26651 providers: metadata && metadata.providers,
26652 imports: imports,
26653 });
26654}
26655const SWITCH_COMPILE_NGMODULE__POST_R3__ = compileNgModule;
26656const SWITCH_COMPILE_NGMODULE__PRE_R3__ = preR3NgModuleCompile;
26657const SWITCH_COMPILE_NGMODULE = SWITCH_COMPILE_NGMODULE__PRE_R3__;
26658
26659/**
26660 * @license
26661 * Copyright Google LLC All Rights Reserved.
26662 *
26663 * Use of this source code is governed by an MIT-style license that can be
26664 * found in the LICENSE file at https://angular.io/license
26665 */
26666
26667/**
26668 * @license
26669 * Copyright Google LLC All Rights Reserved.
26670 *
26671 * Use of this source code is governed by an MIT-style license that can be
26672 * found in the LICENSE file at https://angular.io/license
26673 */
26674
26675/**
26676 * @license
26677 * Copyright Google LLC All Rights Reserved.
26678 *
26679 * Use of this source code is governed by an MIT-style license that can be
26680 * found in the LICENSE file at https://angular.io/license
26681 */
26682/**
26683 * A [DI token](guide/glossary#di-token "DI token definition") that you can use to provide
26684 * one or more initialization functions.
26685 *
26686 * The provided functions are injected at application startup and executed during
26687 * app initialization. If any of these functions returns a Promise, initialization
26688 * does not complete until the Promise is resolved.
26689 *
26690 * You can, for example, create a factory function that loads language data
26691 * or an external configuration, and provide that function to the `APP_INITIALIZER` token.
26692 * The function is executed during the application bootstrap process,
26693 * and the needed data is available on startup.
26694 *
26695 * @see `ApplicationInitStatus`
26696 *
26697 * @publicApi
26698 */
26699const APP_INITIALIZER = new InjectionToken('Application Initializer');
26700/**
26701 * A class that reflects the state of running {@link APP_INITIALIZER} functions.
26702 *
26703 * @publicApi
26704 */
26705class ApplicationInitStatus {
26706 constructor(appInits) {
26707 this.appInits = appInits;
26708 this.initialized = false;
26709 this.done = false;
26710 this.donePromise = new Promise((res, rej) => {
26711 this.resolve = res;
26712 this.reject = rej;
26713 });
26714 }
26715 /** @internal */
26716 runInitializers() {
26717 if (this.initialized) {
26718 return;
26719 }
26720 const asyncInitPromises = [];
26721 const complete = () => {
26722 this.done = true;
26723 this.resolve();
26724 };
26725 if (this.appInits) {
26726 for (let i = 0; i < this.appInits.length; i++) {
26727 const initResult = this.appInits[i]();
26728 if (isPromise(initResult)) {
26729 asyncInitPromises.push(initResult);
26730 }
26731 }
26732 }
26733 Promise.all(asyncInitPromises)
26734 .then(() => {
26735 complete();
26736 })
26737 .catch(e => {
26738 this.reject(e);
26739 });
26740 if (asyncInitPromises.length === 0) {
26741 complete();
26742 }
26743 this.initialized = true;
26744 }
26745}
26746ApplicationInitStatus.decorators = [
26747 { type: Injectable }
26748];
26749ApplicationInitStatus.ctorParameters = () => [
26750 { type: Array, decorators: [{ type: Inject, args: [APP_INITIALIZER,] }, { type: Optional }] }
26751];
26752
26753/**
26754 * @license
26755 * Copyright Google LLC All Rights Reserved.
26756 *
26757 * Use of this source code is governed by an MIT-style license that can be
26758 * found in the LICENSE file at https://angular.io/license
26759 */
26760/**
26761 * A [DI token](guide/glossary#di-token "DI token definition") representing a unique string ID, used
26762 * primarily for prefixing application attributes and CSS styles when
26763 * {@link ViewEncapsulation#Emulated ViewEncapsulation.Emulated} is being used.
26764 *
26765 * BY default, the value is randomly generated and assigned to the application by Angular.
26766 * To provide a custom ID value, use a DI provider <!-- TODO: provider --> to configure
26767 * the root {@link Injector} that uses this token.
26768 *
26769 * @publicApi
26770 */
26771const APP_ID = new InjectionToken('AppId');
26772function _appIdRandomProviderFactory() {
26773 return `${_randomChar()}${_randomChar()}${_randomChar()}`;
26774}
26775/**
26776 * Providers that generate a random `APP_ID_TOKEN`.
26777 * @publicApi
26778 */
26779const APP_ID_RANDOM_PROVIDER = {
26780 provide: APP_ID,
26781 useFactory: _appIdRandomProviderFactory,
26782 deps: [],
26783};
26784function _randomChar() {
26785 return String.fromCharCode(97 + Math.floor(Math.random() * 25));
26786}
26787/**
26788 * A function that is executed when a platform is initialized.
26789 * @publicApi
26790 */
26791const PLATFORM_INITIALIZER = new InjectionToken('Platform Initializer');
26792/**
26793 * A token that indicates an opaque platform ID.
26794 * @publicApi
26795 */
26796const PLATFORM_ID = new InjectionToken('Platform ID');
26797/**
26798 * A [DI token](guide/glossary#di-token "DI token definition") that provides a set of callbacks to
26799 * be called for every component that is bootstrapped.
26800 *
26801 * Each callback must take a `ComponentRef` instance and return nothing.
26802 *
26803 * `(componentRef: ComponentRef) => void`
26804 *
26805 * @publicApi
26806 */
26807const APP_BOOTSTRAP_LISTENER = new InjectionToken('appBootstrapListener');
26808/**
26809 * A [DI token](guide/glossary#di-token "DI token definition") that indicates the root directory of
26810 * the application
26811 * @publicApi
26812 */
26813const PACKAGE_ROOT_URL = new InjectionToken('Application Packages Root URL');
26814
26815/**
26816 * @license
26817 * Copyright Google LLC All Rights Reserved.
26818 *
26819 * Use of this source code is governed by an MIT-style license that can be
26820 * found in the LICENSE file at https://angular.io/license
26821 */
26822class Console {
26823 log(message) {
26824 // tslint:disable-next-line:no-console
26825 console.log(message);
26826 }
26827 // Note: for reporting errors use `DOM.logError()` as it is platform specific
26828 warn(message) {
26829 // tslint:disable-next-line:no-console
26830 console.warn(message);
26831 }
26832}
26833Console.decorators = [
26834 { type: Injectable }
26835];
26836
26837/**
26838 * @license
26839 * Copyright Google LLC All Rights Reserved.
26840 *
26841 * Use of this source code is governed by an MIT-style license that can be
26842 * found in the LICENSE file at https://angular.io/license
26843 */
26844/**
26845 * Provide this token to set the locale of your application.
26846 * It is used for i18n extraction, by i18n pipes (DatePipe, I18nPluralPipe, CurrencyPipe,
26847 * DecimalPipe and PercentPipe) and by ICU expressions.
26848 *
26849 * See the [i18n guide](guide/i18n#setting-up-locale) for more information.
26850 *
26851 * @usageNotes
26852 * ### Example
26853 *
26854 * ```typescript
26855 * import { LOCALE_ID } from '@angular/core';
26856 * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
26857 * import { AppModule } from './app/app.module';
26858 *
26859 * platformBrowserDynamic().bootstrapModule(AppModule, {
26860 * providers: [{provide: LOCALE_ID, useValue: 'en-US' }]
26861 * });
26862 * ```
26863 *
26864 * @publicApi
26865 */
26866const LOCALE_ID$1 = new InjectionToken('LocaleId');
26867/**
26868 * Provide this token to set the default currency code your application uses for
26869 * CurrencyPipe when there is no currency code passed into it. This is only used by
26870 * CurrencyPipe and has no relation to locale currency. Defaults to USD if not configured.
26871 *
26872 * See the [i18n guide](guide/i18n#setting-up-locale) for more information.
26873 *
26874 * <div class="alert is-helpful">
26875 *
26876 * **Deprecation notice:**
26877 *
26878 * The default currency code is currently always `USD` but this is deprecated from v9.
26879 *
26880 * **In v10 the default currency code will be taken from the current locale.**
26881 *
26882 * If you need the previous behavior then set it by creating a `DEFAULT_CURRENCY_CODE` provider in
26883 * your application `NgModule`:
26884 *
26885 * ```ts
26886 * {provide: DEFAULT_CURRENCY_CODE, useValue: 'USD'}
26887 * ```
26888 *
26889 * </div>
26890 *
26891 * @usageNotes
26892 * ### Example
26893 *
26894 * ```typescript
26895 * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
26896 * import { AppModule } from './app/app.module';
26897 *
26898 * platformBrowserDynamic().bootstrapModule(AppModule, {
26899 * providers: [{provide: DEFAULT_CURRENCY_CODE, useValue: 'EUR' }]
26900 * });
26901 * ```
26902 *
26903 * @publicApi
26904 */
26905const DEFAULT_CURRENCY_CODE = new InjectionToken('DefaultCurrencyCode');
26906/**
26907 * Use this token at bootstrap to provide the content of your translation file (`xtb`,
26908 * `xlf` or `xlf2`) when you want to translate your application in another language.
26909 *
26910 * See the [i18n guide](guide/i18n#merge) for more information.
26911 *
26912 * @usageNotes
26913 * ### Example
26914 *
26915 * ```typescript
26916 * import { TRANSLATIONS } from '@angular/core';
26917 * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
26918 * import { AppModule } from './app/app.module';
26919 *
26920 * // content of your translation file
26921 * const translations = '....';
26922 *
26923 * platformBrowserDynamic().bootstrapModule(AppModule, {
26924 * providers: [{provide: TRANSLATIONS, useValue: translations }]
26925 * });
26926 * ```
26927 *
26928 * @publicApi
26929 */
26930const TRANSLATIONS = new InjectionToken('Translations');
26931/**
26932 * Provide this token at bootstrap to set the format of your {@link TRANSLATIONS}: `xtb`,
26933 * `xlf` or `xlf2`.
26934 *
26935 * See the [i18n guide](guide/i18n#merge) for more information.
26936 *
26937 * @usageNotes
26938 * ### Example
26939 *
26940 * ```typescript
26941 * import { TRANSLATIONS_FORMAT } from '@angular/core';
26942 * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
26943 * import { AppModule } from './app/app.module';
26944 *
26945 * platformBrowserDynamic().bootstrapModule(AppModule, {
26946 * providers: [{provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }]
26947 * });
26948 * ```
26949 *
26950 * @publicApi
26951 */
26952const TRANSLATIONS_FORMAT = new InjectionToken('TranslationsFormat');
26953/**
26954 * Use this enum at bootstrap as an option of `bootstrapModule` to define the strategy
26955 * that the compiler should use in case of missing translations:
26956 * - Error: throw if you have missing translations.
26957 * - Warning (default): show a warning in the console and/or shell.
26958 * - Ignore: do nothing.
26959 *
26960 * See the [i18n guide](guide/i18n#missing-translation) for more information.
26961 *
26962 * @usageNotes
26963 * ### Example
26964 * ```typescript
26965 * import { MissingTranslationStrategy } from '@angular/core';
26966 * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
26967 * import { AppModule } from './app/app.module';
26968 *
26969 * platformBrowserDynamic().bootstrapModule(AppModule, {
26970 * missingTranslation: MissingTranslationStrategy.Error
26971 * });
26972 * ```
26973 *
26974 * @publicApi
26975 */
26976var MissingTranslationStrategy;
26977(function (MissingTranslationStrategy) {
26978 MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error";
26979 MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning";
26980 MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore";
26981})(MissingTranslationStrategy || (MissingTranslationStrategy = {}));
26982
26983/**
26984 * @license
26985 * Copyright Google LLC All Rights Reserved.
26986 *
26987 * Use of this source code is governed by an MIT-style license that can be
26988 * found in the LICENSE file at https://angular.io/license
26989 */
26990const SWITCH_IVY_ENABLED__POST_R3__ = true;
26991const SWITCH_IVY_ENABLED__PRE_R3__ = false;
26992const ivyEnabled = SWITCH_IVY_ENABLED__PRE_R3__;
26993
26994/**
26995 * @license
26996 * Copyright Google LLC All Rights Reserved.
26997 *
26998 * Use of this source code is governed by an MIT-style license that can be
26999 * found in the LICENSE file at https://angular.io/license
27000 */
27001/**
27002 * Combination of NgModuleFactory and ComponentFactorys.
27003 *
27004 * @publicApi
27005 */
27006class ModuleWithComponentFactories {
27007 constructor(ngModuleFactory, componentFactories) {
27008 this.ngModuleFactory = ngModuleFactory;
27009 this.componentFactories = componentFactories;
27010 }
27011}
27012function _throwError() {
27013 throw new Error(`Runtime compiler is not loaded`);
27014}
27015const Compiler_compileModuleSync__PRE_R3__ = _throwError;
27016const Compiler_compileModuleSync__POST_R3__ = function (moduleType) {
27017 return new NgModuleFactory$1(moduleType);
27018};
27019const Compiler_compileModuleSync = Compiler_compileModuleSync__PRE_R3__;
27020const Compiler_compileModuleAsync__PRE_R3__ = _throwError;
27021const Compiler_compileModuleAsync__POST_R3__ = function (moduleType) {
27022 return Promise.resolve(Compiler_compileModuleSync__POST_R3__(moduleType));
27023};
27024const Compiler_compileModuleAsync = Compiler_compileModuleAsync__PRE_R3__;
27025const Compiler_compileModuleAndAllComponentsSync__PRE_R3__ = _throwError;
27026const Compiler_compileModuleAndAllComponentsSync__POST_R3__ = function (moduleType) {
27027 const ngModuleFactory = Compiler_compileModuleSync__POST_R3__(moduleType);
27028 const moduleDef = getNgModuleDef(moduleType);
27029 const componentFactories = maybeUnwrapFn(moduleDef.declarations)
27030 .reduce((factories, declaration) => {
27031 const componentDef = getComponentDef(declaration);
27032 componentDef && factories.push(new ComponentFactory$1(componentDef));
27033 return factories;
27034 }, []);
27035 return new ModuleWithComponentFactories(ngModuleFactory, componentFactories);
27036};
27037const Compiler_compileModuleAndAllComponentsSync = Compiler_compileModuleAndAllComponentsSync__PRE_R3__;
27038const Compiler_compileModuleAndAllComponentsAsync__PRE_R3__ = _throwError;
27039const Compiler_compileModuleAndAllComponentsAsync__POST_R3__ = function (moduleType) {
27040 return Promise.resolve(Compiler_compileModuleAndAllComponentsSync__POST_R3__(moduleType));
27041};
27042const Compiler_compileModuleAndAllComponentsAsync = Compiler_compileModuleAndAllComponentsAsync__PRE_R3__;
27043/**
27044 * Low-level service for running the angular compiler during runtime
27045 * to create {@link ComponentFactory}s, which
27046 * can later be used to create and render a Component instance.
27047 *
27048 * Each `@NgModule` provides an own `Compiler` to its injector,
27049 * that will use the directives/pipes of the ng module for compilation
27050 * of components.
27051 *
27052 * @publicApi
27053 */
27054class Compiler {
27055 constructor() {
27056 /**
27057 * Compiles the given NgModule and all of its components. All templates of the components listed
27058 * in `entryComponents` have to be inlined.
27059 */
27060 this.compileModuleSync = Compiler_compileModuleSync;
27061 /**
27062 * Compiles the given NgModule and all of its components
27063 */
27064 this.compileModuleAsync = Compiler_compileModuleAsync;
27065 /**
27066 * Same as {@link #compileModuleSync} but also creates ComponentFactories for all components.
27067 */
27068 this.compileModuleAndAllComponentsSync = Compiler_compileModuleAndAllComponentsSync;
27069 /**
27070 * Same as {@link #compileModuleAsync} but also creates ComponentFactories for all components.
27071 */
27072 this.compileModuleAndAllComponentsAsync = Compiler_compileModuleAndAllComponentsAsync;
27073 }
27074 /**
27075 * Clears all caches.
27076 */
27077 clearCache() { }
27078 /**
27079 * Clears the cache for the given component/ngModule.
27080 */
27081 clearCacheFor(type) { }
27082 /**
27083 * Returns the id for a given NgModule, if one is defined and known to the compiler.
27084 */
27085 getModuleId(moduleType) {
27086 return undefined;
27087 }
27088}
27089Compiler.decorators = [
27090 { type: Injectable }
27091];
27092/**
27093 * Token to provide CompilerOptions in the platform injector.
27094 *
27095 * @publicApi
27096 */
27097const COMPILER_OPTIONS = new InjectionToken('compilerOptions');
27098/**
27099 * A factory for creating a Compiler
27100 *
27101 * @publicApi
27102 */
27103class CompilerFactory {
27104}
27105
27106/**
27107 * @license
27108 * Copyright Google LLC All Rights Reserved.
27109 *
27110 * Use of this source code is governed by an MIT-style license that can be
27111 * found in the LICENSE file at https://angular.io/license
27112 */
27113const promise = (() => Promise.resolve(0))();
27114function scheduleMicroTask(fn) {
27115 if (typeof Zone === 'undefined') {
27116 // use promise to schedule microTask instead of use Zone
27117 promise.then(() => {
27118 fn && fn.apply(null, null);
27119 });
27120 }
27121 else {
27122 Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
27123 }
27124}
27125
27126/**
27127 * @license
27128 * Copyright Google LLC All Rights Reserved.
27129 *
27130 * Use of this source code is governed by an MIT-style license that can be
27131 * found in the LICENSE file at https://angular.io/license
27132 */
27133function getNativeRequestAnimationFrame() {
27134 let nativeRequestAnimationFrame = _global['requestAnimationFrame'];
27135 let nativeCancelAnimationFrame = _global['cancelAnimationFrame'];
27136 if (typeof Zone !== 'undefined' && nativeRequestAnimationFrame && nativeCancelAnimationFrame) {
27137 // use unpatched version of requestAnimationFrame(native delegate) if possible
27138 // to avoid another Change detection
27139 const unpatchedRequestAnimationFrame = nativeRequestAnimationFrame[Zone.__symbol__('OriginalDelegate')];
27140 if (unpatchedRequestAnimationFrame) {
27141 nativeRequestAnimationFrame = unpatchedRequestAnimationFrame;
27142 }
27143 const unpatchedCancelAnimationFrame = nativeCancelAnimationFrame[Zone.__symbol__('OriginalDelegate')];
27144 if (unpatchedCancelAnimationFrame) {
27145 nativeCancelAnimationFrame = unpatchedCancelAnimationFrame;
27146 }
27147 }
27148 return { nativeRequestAnimationFrame, nativeCancelAnimationFrame };
27149}
27150
27151/**
27152 * @license
27153 * Copyright Google LLC All Rights Reserved.
27154 *
27155 * Use of this source code is governed by an MIT-style license that can be
27156 * found in the LICENSE file at https://angular.io/license
27157 */
27158/**
27159 * An injectable service for executing work inside or outside of the Angular zone.
27160 *
27161 * The most common use of this service is to optimize performance when starting a work consisting of
27162 * one or more asynchronous tasks that don't require UI updates or error handling to be handled by
27163 * Angular. Such tasks can be kicked off via {@link #runOutsideAngular} and if needed, these tasks
27164 * can reenter the Angular zone via {@link #run}.
27165 *
27166 * <!-- TODO: add/fix links to:
27167 * - docs explaining zones and the use of zones in Angular and change-detection
27168 * - link to runOutsideAngular/run (throughout this file!)
27169 * -->
27170 *
27171 * @usageNotes
27172 * ### Example
27173 *
27174 * ```
27175 * import {Component, NgZone} from '@angular/core';
27176 * import {NgIf} from '@angular/common';
27177 *
27178 * @Component({
27179 * selector: 'ng-zone-demo',
27180 * template: `
27181 * <h2>Demo: NgZone</h2>
27182 *
27183 * <p>Progress: {{progress}}%</p>
27184 * <p *ngIf="progress >= 100">Done processing {{label}} of Angular zone!</p>
27185 *
27186 * <button (click)="processWithinAngularZone()">Process within Angular zone</button>
27187 * <button (click)="processOutsideOfAngularZone()">Process outside of Angular zone</button>
27188 * `,
27189 * })
27190 * export class NgZoneDemo {
27191 * progress: number = 0;
27192 * label: string;
27193 *
27194 * constructor(private _ngZone: NgZone) {}
27195 *
27196 * // Loop inside the Angular zone
27197 * // so the UI DOES refresh after each setTimeout cycle
27198 * processWithinAngularZone() {
27199 * this.label = 'inside';
27200 * this.progress = 0;
27201 * this._increaseProgress(() => console.log('Inside Done!'));
27202 * }
27203 *
27204 * // Loop outside of the Angular zone
27205 * // so the UI DOES NOT refresh after each setTimeout cycle
27206 * processOutsideOfAngularZone() {
27207 * this.label = 'outside';
27208 * this.progress = 0;
27209 * this._ngZone.runOutsideAngular(() => {
27210 * this._increaseProgress(() => {
27211 * // reenter the Angular zone and display done
27212 * this._ngZone.run(() => { console.log('Outside Done!'); });
27213 * });
27214 * });
27215 * }
27216 *
27217 * _increaseProgress(doneCallback: () => void) {
27218 * this.progress += 1;
27219 * console.log(`Current progress: ${this.progress}%`);
27220 *
27221 * if (this.progress < 100) {
27222 * window.setTimeout(() => this._increaseProgress(doneCallback), 10);
27223 * } else {
27224 * doneCallback();
27225 * }
27226 * }
27227 * }
27228 * ```
27229 *
27230 * @publicApi
27231 */
27232class NgZone {
27233 constructor({ enableLongStackTrace = false, shouldCoalesceEventChangeDetection = false }) {
27234 this.hasPendingMacrotasks = false;
27235 this.hasPendingMicrotasks = false;
27236 /**
27237 * Whether there are no outstanding microtasks or macrotasks.
27238 */
27239 this.isStable = true;
27240 /**
27241 * Notifies when code enters Angular Zone. This gets fired first on VM Turn.
27242 */
27243 this.onUnstable = new EventEmitter(false);
27244 /**
27245 * Notifies when there is no more microtasks enqueued in the current VM Turn.
27246 * This is a hint for Angular to do change detection, which may enqueue more microtasks.
27247 * For this reason this event can fire multiple times per VM Turn.
27248 */
27249 this.onMicrotaskEmpty = new EventEmitter(false);
27250 /**
27251 * Notifies when the last `onMicrotaskEmpty` has run and there are no more microtasks, which
27252 * implies we are about to relinquish VM turn.
27253 * This event gets called just once.
27254 */
27255 this.onStable = new EventEmitter(false);
27256 /**
27257 * Notifies that an error has been delivered.
27258 */
27259 this.onError = new EventEmitter(false);
27260 if (typeof Zone == 'undefined') {
27261 throw new Error(`In this configuration Angular requires Zone.js`);
27262 }
27263 Zone.assertZonePatched();
27264 const self = this;
27265 self._nesting = 0;
27266 self._outer = self._inner = Zone.current;
27267 if (Zone['wtfZoneSpec']) {
27268 self._inner = self._inner.fork(Zone['wtfZoneSpec']);
27269 }
27270 if (Zone['TaskTrackingZoneSpec']) {
27271 self._inner = self._inner.fork(new Zone['TaskTrackingZoneSpec']);
27272 }
27273 if (enableLongStackTrace && Zone['longStackTraceZoneSpec']) {
27274 self._inner = self._inner.fork(Zone['longStackTraceZoneSpec']);
27275 }
27276 self.shouldCoalesceEventChangeDetection = shouldCoalesceEventChangeDetection;
27277 self.lastRequestAnimationFrameId = -1;
27278 self.nativeRequestAnimationFrame = getNativeRequestAnimationFrame().nativeRequestAnimationFrame;
27279 forkInnerZoneWithAngularBehavior(self);
27280 }
27281 static isInAngularZone() {
27282 return Zone.current.get('isAngularZone') === true;
27283 }
27284 static assertInAngularZone() {
27285 if (!NgZone.isInAngularZone()) {
27286 throw new Error('Expected to be in Angular Zone, but it is not!');
27287 }
27288 }
27289 static assertNotInAngularZone() {
27290 if (NgZone.isInAngularZone()) {
27291 throw new Error('Expected to not be in Angular Zone, but it is!');
27292 }
27293 }
27294 /**
27295 * Executes the `fn` function synchronously within the Angular zone and returns value returned by
27296 * the function.
27297 *
27298 * Running functions via `run` allows you to reenter Angular zone from a task that was executed
27299 * outside of the Angular zone (typically started via {@link #runOutsideAngular}).
27300 *
27301 * Any future tasks or microtasks scheduled from within this function will continue executing from
27302 * within the Angular zone.
27303 *
27304 * If a synchronous error happens it will be rethrown and not reported via `onError`.
27305 */
27306 run(fn, applyThis, applyArgs) {
27307 return this._inner.run(fn, applyThis, applyArgs);
27308 }
27309 /**
27310 * Executes the `fn` function synchronously within the Angular zone as a task and returns value
27311 * returned by the function.
27312 *
27313 * Running functions via `run` allows you to reenter Angular zone from a task that was executed
27314 * outside of the Angular zone (typically started via {@link #runOutsideAngular}).
27315 *
27316 * Any future tasks or microtasks scheduled from within this function will continue executing from
27317 * within the Angular zone.
27318 *
27319 * If a synchronous error happens it will be rethrown and not reported via `onError`.
27320 */
27321 runTask(fn, applyThis, applyArgs, name) {
27322 const zone = this._inner;
27323 const task = zone.scheduleEventTask('NgZoneEvent: ' + name, fn, EMPTY_PAYLOAD, noop$1, noop$1);
27324 try {
27325 return zone.runTask(task, applyThis, applyArgs);
27326 }
27327 finally {
27328 zone.cancelTask(task);
27329 }
27330 }
27331 /**
27332 * Same as `run`, except that synchronous errors are caught and forwarded via `onError` and not
27333 * rethrown.
27334 */
27335 runGuarded(fn, applyThis, applyArgs) {
27336 return this._inner.runGuarded(fn, applyThis, applyArgs);
27337 }
27338 /**
27339 * Executes the `fn` function synchronously in Angular's parent zone and returns value returned by
27340 * the function.
27341 *
27342 * Running functions via {@link #runOutsideAngular} allows you to escape Angular's zone and do
27343 * work that
27344 * doesn't trigger Angular change-detection or is subject to Angular's error handling.
27345 *
27346 * Any future tasks or microtasks scheduled from within this function will continue executing from
27347 * outside of the Angular zone.
27348 *
27349 * Use {@link #run} to reenter the Angular zone and do work that updates the application model.
27350 */
27351 runOutsideAngular(fn) {
27352 return this._outer.run(fn);
27353 }
27354}
27355function noop$1() { }
27356const EMPTY_PAYLOAD = {};
27357function checkStable(zone) {
27358 if (zone._nesting == 0 && !zone.hasPendingMicrotasks && !zone.isStable) {
27359 try {
27360 zone._nesting++;
27361 zone.onMicrotaskEmpty.emit(null);
27362 }
27363 finally {
27364 zone._nesting--;
27365 if (!zone.hasPendingMicrotasks) {
27366 try {
27367 zone.runOutsideAngular(() => zone.onStable.emit(null));
27368 }
27369 finally {
27370 zone.isStable = true;
27371 }
27372 }
27373 }
27374 }
27375}
27376function delayChangeDetectionForEvents(zone) {
27377 if (zone.lastRequestAnimationFrameId !== -1) {
27378 return;
27379 }
27380 zone.lastRequestAnimationFrameId = zone.nativeRequestAnimationFrame.call(_global, () => {
27381 // This is a work around for https://github.com/angular/angular/issues/36839.
27382 // The core issue is that when event coalescing is enabled it is possible for microtasks
27383 // to get flushed too early (As is the case with `Promise.then`) between the
27384 // coalescing eventTasks.
27385 //
27386 // To workaround this we schedule a "fake" eventTask before we process the
27387 // coalescing eventTasks. The benefit of this is that the "fake" container eventTask
27388 // will prevent the microtasks queue from getting drained in between the coalescing
27389 // eventTask execution.
27390 if (!zone.fakeTopEventTask) {
27391 zone.fakeTopEventTask = Zone.root.scheduleEventTask('fakeTopEventTask', () => {
27392 zone.lastRequestAnimationFrameId = -1;
27393 updateMicroTaskStatus(zone);
27394 checkStable(zone);
27395 }, undefined, () => { }, () => { });
27396 }
27397 zone.fakeTopEventTask.invoke();
27398 });
27399 updateMicroTaskStatus(zone);
27400}
27401function forkInnerZoneWithAngularBehavior(zone) {
27402 const delayChangeDetectionForEventsDelegate = () => {
27403 delayChangeDetectionForEvents(zone);
27404 };
27405 const maybeDelayChangeDetection = !!zone.shouldCoalesceEventChangeDetection &&
27406 zone.nativeRequestAnimationFrame && delayChangeDetectionForEventsDelegate;
27407 zone._inner = zone._inner.fork({
27408 name: 'angular',
27409 properties: { 'isAngularZone': true, 'maybeDelayChangeDetection': maybeDelayChangeDetection },
27410 onInvokeTask: (delegate, current, target, task, applyThis, applyArgs) => {
27411 try {
27412 onEnter(zone);
27413 return delegate.invokeTask(target, task, applyThis, applyArgs);
27414 }
27415 finally {
27416 if (maybeDelayChangeDetection && task.type === 'eventTask') {
27417 maybeDelayChangeDetection();
27418 }
27419 onLeave(zone);
27420 }
27421 },
27422 onInvoke: (delegate, current, target, callback, applyThis, applyArgs, source) => {
27423 try {
27424 onEnter(zone);
27425 return delegate.invoke(target, callback, applyThis, applyArgs, source);
27426 }
27427 finally {
27428 onLeave(zone);
27429 }
27430 },
27431 onHasTask: (delegate, current, target, hasTaskState) => {
27432 delegate.hasTask(target, hasTaskState);
27433 if (current === target) {
27434 // We are only interested in hasTask events which originate from our zone
27435 // (A child hasTask event is not interesting to us)
27436 if (hasTaskState.change == 'microTask') {
27437 zone._hasPendingMicrotasks = hasTaskState.microTask;
27438 updateMicroTaskStatus(zone);
27439 checkStable(zone);
27440 }
27441 else if (hasTaskState.change == 'macroTask') {
27442 zone.hasPendingMacrotasks = hasTaskState.macroTask;
27443 }
27444 }
27445 },
27446 onHandleError: (delegate, current, target, error) => {
27447 delegate.handleError(target, error);
27448 zone.runOutsideAngular(() => zone.onError.emit(error));
27449 return false;
27450 }
27451 });
27452}
27453function updateMicroTaskStatus(zone) {
27454 if (zone._hasPendingMicrotasks ||
27455 (zone.shouldCoalesceEventChangeDetection && zone.lastRequestAnimationFrameId !== -1)) {
27456 zone.hasPendingMicrotasks = true;
27457 }
27458 else {
27459 zone.hasPendingMicrotasks = false;
27460 }
27461}
27462function onEnter(zone) {
27463 zone._nesting++;
27464 if (zone.isStable) {
27465 zone.isStable = false;
27466 zone.onUnstable.emit(null);
27467 }
27468}
27469function onLeave(zone) {
27470 zone._nesting--;
27471 checkStable(zone);
27472}
27473/**
27474 * Provides a noop implementation of `NgZone` which does nothing. This zone requires explicit calls
27475 * to framework to perform rendering.
27476 */
27477class NoopNgZone {
27478 constructor() {
27479 this.hasPendingMicrotasks = false;
27480 this.hasPendingMacrotasks = false;
27481 this.isStable = true;
27482 this.onUnstable = new EventEmitter();
27483 this.onMicrotaskEmpty = new EventEmitter();
27484 this.onStable = new EventEmitter();
27485 this.onError = new EventEmitter();
27486 }
27487 run(fn, applyThis, applyArgs) {
27488 return fn.apply(applyThis, applyArgs);
27489 }
27490 runGuarded(fn, applyThis, applyArgs) {
27491 return fn.apply(applyThis, applyArgs);
27492 }
27493 runOutsideAngular(fn) {
27494 return fn();
27495 }
27496 runTask(fn, applyThis, applyArgs, name) {
27497 return fn.apply(applyThis, applyArgs);
27498 }
27499}
27500
27501/**
27502 * @license
27503 * Copyright Google LLC All Rights Reserved.
27504 *
27505 * Use of this source code is governed by an MIT-style license that can be
27506 * found in the LICENSE file at https://angular.io/license
27507 */
27508/**
27509 * The Testability service provides testing hooks that can be accessed from
27510 * the browser and by services such as Protractor. Each bootstrapped Angular
27511 * application on the page will have an instance of Testability.
27512 * @publicApi
27513 */
27514class Testability {
27515 constructor(_ngZone) {
27516 this._ngZone = _ngZone;
27517 this._pendingCount = 0;
27518 this._isZoneStable = true;
27519 /**
27520 * Whether any work was done since the last 'whenStable' callback. This is
27521 * useful to detect if this could have potentially destabilized another
27522 * component while it is stabilizing.
27523 * @internal
27524 */
27525 this._didWork = false;
27526 this._callbacks = [];
27527 this.taskTrackingZone = null;
27528 this._watchAngularEvents();
27529 _ngZone.run(() => {
27530 this.taskTrackingZone =
27531 typeof Zone == 'undefined' ? null : Zone.current.get('TaskTrackingZone');
27532 });
27533 }
27534 _watchAngularEvents() {
27535 this._ngZone.onUnstable.subscribe({
27536 next: () => {
27537 this._didWork = true;
27538 this._isZoneStable = false;
27539 }
27540 });
27541 this._ngZone.runOutsideAngular(() => {
27542 this._ngZone.onStable.subscribe({
27543 next: () => {
27544 NgZone.assertNotInAngularZone();
27545 scheduleMicroTask(() => {
27546 this._isZoneStable = true;
27547 this._runCallbacksIfReady();
27548 });
27549 }
27550 });
27551 });
27552 }
27553 /**
27554 * Increases the number of pending request
27555 * @deprecated pending requests are now tracked with zones.
27556 */
27557 increasePendingRequestCount() {
27558 this._pendingCount += 1;
27559 this._didWork = true;
27560 return this._pendingCount;
27561 }
27562 /**
27563 * Decreases the number of pending request
27564 * @deprecated pending requests are now tracked with zones
27565 */
27566 decreasePendingRequestCount() {
27567 this._pendingCount -= 1;
27568 if (this._pendingCount < 0) {
27569 throw new Error('pending async requests below zero');
27570 }
27571 this._runCallbacksIfReady();
27572 return this._pendingCount;
27573 }
27574 /**
27575 * Whether an associated application is stable
27576 */
27577 isStable() {
27578 return this._isZoneStable && this._pendingCount === 0 && !this._ngZone.hasPendingMacrotasks;
27579 }
27580 _runCallbacksIfReady() {
27581 if (this.isStable()) {
27582 // Schedules the call backs in a new frame so that it is always async.
27583 scheduleMicroTask(() => {
27584 while (this._callbacks.length !== 0) {
27585 let cb = this._callbacks.pop();
27586 clearTimeout(cb.timeoutId);
27587 cb.doneCb(this._didWork);
27588 }
27589 this._didWork = false;
27590 });
27591 }
27592 else {
27593 // Still not stable, send updates.
27594 let pending = this.getPendingTasks();
27595 this._callbacks = this._callbacks.filter((cb) => {
27596 if (cb.updateCb && cb.updateCb(pending)) {
27597 clearTimeout(cb.timeoutId);
27598 return false;
27599 }
27600 return true;
27601 });
27602 this._didWork = true;
27603 }
27604 }
27605 getPendingTasks() {
27606 if (!this.taskTrackingZone) {
27607 return [];
27608 }
27609 // Copy the tasks data so that we don't leak tasks.
27610 return this.taskTrackingZone.macroTasks.map((t) => {
27611 return {
27612 source: t.source,
27613 // From TaskTrackingZone:
27614 // https://github.com/angular/zone.js/blob/master/lib/zone-spec/task-tracking.ts#L40
27615 creationLocation: t.creationLocation,
27616 data: t.data
27617 };
27618 });
27619 }
27620 addCallback(cb, timeout, updateCb) {
27621 let timeoutId = -1;
27622 if (timeout && timeout > 0) {
27623 timeoutId = setTimeout(() => {
27624 this._callbacks = this._callbacks.filter((cb) => cb.timeoutId !== timeoutId);
27625 cb(this._didWork, this.getPendingTasks());
27626 }, timeout);
27627 }
27628 this._callbacks.push({ doneCb: cb, timeoutId: timeoutId, updateCb: updateCb });
27629 }
27630 /**
27631 * Wait for the application to be stable with a timeout. If the timeout is reached before that
27632 * happens, the callback receives a list of the macro tasks that were pending, otherwise null.
27633 *
27634 * @param doneCb The callback to invoke when Angular is stable or the timeout expires
27635 * whichever comes first.
27636 * @param timeout Optional. The maximum time to wait for Angular to become stable. If not
27637 * specified, whenStable() will wait forever.
27638 * @param updateCb Optional. If specified, this callback will be invoked whenever the set of
27639 * pending macrotasks changes. If this callback returns true doneCb will not be invoked
27640 * and no further updates will be issued.
27641 */
27642 whenStable(doneCb, timeout, updateCb) {
27643 if (updateCb && !this.taskTrackingZone) {
27644 throw new Error('Task tracking zone is required when passing an update callback to ' +
27645 'whenStable(). Is "zone.js/dist/task-tracking.js" loaded?');
27646 }
27647 // These arguments are 'Function' above to keep the public API simple.
27648 this.addCallback(doneCb, timeout, updateCb);
27649 this._runCallbacksIfReady();
27650 }
27651 /**
27652 * Get the number of pending requests
27653 * @deprecated pending requests are now tracked with zones
27654 */
27655 getPendingRequestCount() {
27656 return this._pendingCount;
27657 }
27658 /**
27659 * Find providers by name
27660 * @param using The root element to search from
27661 * @param provider The name of binding variable
27662 * @param exactMatch Whether using exactMatch
27663 */
27664 findProviders(using, provider, exactMatch) {
27665 // TODO(juliemr): implement.
27666 return [];
27667 }
27668}
27669Testability.decorators = [
27670 { type: Injectable }
27671];
27672Testability.ctorParameters = () => [
27673 { type: NgZone }
27674];
27675/**
27676 * A global registry of {@link Testability} instances for specific elements.
27677 * @publicApi
27678 */
27679class TestabilityRegistry {
27680 constructor() {
27681 /** @internal */
27682 this._applications = new Map();
27683 _testabilityGetter.addToWindow(this);
27684 }
27685 /**
27686 * Registers an application with a testability hook so that it can be tracked
27687 * @param token token of application, root element
27688 * @param testability Testability hook
27689 */
27690 registerApplication(token, testability) {
27691 this._applications.set(token, testability);
27692 }
27693 /**
27694 * Unregisters an application.
27695 * @param token token of application, root element
27696 */
27697 unregisterApplication(token) {
27698 this._applications.delete(token);
27699 }
27700 /**
27701 * Unregisters all applications
27702 */
27703 unregisterAllApplications() {
27704 this._applications.clear();
27705 }
27706 /**
27707 * Get a testability hook associated with the application
27708 * @param elem root element
27709 */
27710 getTestability(elem) {
27711 return this._applications.get(elem) || null;
27712 }
27713 /**
27714 * Get all registered testabilities
27715 */
27716 getAllTestabilities() {
27717 return Array.from(this._applications.values());
27718 }
27719 /**
27720 * Get all registered applications(root elements)
27721 */
27722 getAllRootElements() {
27723 return Array.from(this._applications.keys());
27724 }
27725 /**
27726 * Find testability of a node in the Tree
27727 * @param elem node
27728 * @param findInAncestors whether finding testability in ancestors if testability was not found in
27729 * current node
27730 */
27731 findTestabilityInTree(elem, findInAncestors = true) {
27732 return _testabilityGetter.findTestabilityInTree(this, elem, findInAncestors);
27733 }
27734}
27735TestabilityRegistry.decorators = [
27736 { type: Injectable }
27737];
27738TestabilityRegistry.ctorParameters = () => [];
27739class _NoopGetTestability {
27740 addToWindow(registry) { }
27741 findTestabilityInTree(registry, elem, findInAncestors) {
27742 return null;
27743 }
27744}
27745/**
27746 * Set the {@link GetTestability} implementation used by the Angular testing framework.
27747 * @publicApi
27748 */
27749function setTestabilityGetter(getter) {
27750 _testabilityGetter = getter;
27751}
27752let _testabilityGetter = new _NoopGetTestability();
27753
27754/**
27755 * @license
27756 * Copyright Google LLC All Rights Reserved.
27757 *
27758 * Use of this source code is governed by an MIT-style license that can be
27759 * found in the LICENSE file at https://angular.io/license
27760 */
27761let _platform;
27762let compileNgModuleFactory = compileNgModuleFactory__PRE_R3__;
27763function compileNgModuleFactory__PRE_R3__(injector, options, moduleType) {
27764 const compilerFactory = injector.get(CompilerFactory);
27765 const compiler = compilerFactory.createCompiler([options]);
27766 return compiler.compileModuleAsync(moduleType);
27767}
27768function compileNgModuleFactory__POST_R3__(injector, options, moduleType) {
27769 ngDevMode && assertNgModuleType(moduleType);
27770 const moduleFactory = new NgModuleFactory$1(moduleType);
27771 // All of the logic below is irrelevant for AOT-compiled code.
27772 if (typeof ngJitMode !== 'undefined' && !ngJitMode) {
27773 return Promise.resolve(moduleFactory);
27774 }
27775 const compilerOptions = injector.get(COMPILER_OPTIONS, []).concat(options);
27776 // Configure the compiler to use the provided options. This call may fail when multiple modules
27777 // are bootstrapped with incompatible options, as a component can only be compiled according to
27778 // a single set of options.
27779 setJitOptions({
27780 defaultEncapsulation: _lastDefined(compilerOptions.map(opts => opts.defaultEncapsulation)),
27781 preserveWhitespaces: _lastDefined(compilerOptions.map(opts => opts.preserveWhitespaces)),
27782 });
27783 if (isComponentResourceResolutionQueueEmpty()) {
27784 return Promise.resolve(moduleFactory);
27785 }
27786 const compilerProviders = _mergeArrays(compilerOptions.map(o => o.providers));
27787 // In case there are no compiler providers, we just return the module factory as
27788 // there won't be any resource loader. This can happen with Ivy, because AOT compiled
27789 // modules can be still passed through "bootstrapModule". In that case we shouldn't
27790 // unnecessarily require the JIT compiler.
27791 if (compilerProviders.length === 0) {
27792 return Promise.resolve(moduleFactory);
27793 }
27794 const compiler = getCompilerFacade();
27795 const compilerInjector = Injector.create({ providers: compilerProviders });
27796 const resourceLoader = compilerInjector.get(compiler.ResourceLoader);
27797 // The resource loader can also return a string while the "resolveComponentResources"
27798 // always expects a promise. Therefore we need to wrap the returned value in a promise.
27799 return resolveComponentResources(url => Promise.resolve(resourceLoader.get(url)))
27800 .then(() => moduleFactory);
27801}
27802// the `window.ng` global utilities are only available in non-VE versions of
27803// Angular. The function switch below will make sure that the code is not
27804// included into Angular when PRE mode is active.
27805function publishDefaultGlobalUtils__PRE_R3__() { }
27806function publishDefaultGlobalUtils__POST_R3__() {
27807 ngDevMode && publishDefaultGlobalUtils();
27808}
27809let publishDefaultGlobalUtils$1 = publishDefaultGlobalUtils__PRE_R3__;
27810let isBoundToModule = isBoundToModule__PRE_R3__;
27811function isBoundToModule__PRE_R3__(cf) {
27812 return cf instanceof ComponentFactoryBoundToModule;
27813}
27814function isBoundToModule__POST_R3__(cf) {
27815 return cf.isBoundToModule;
27816}
27817const ALLOW_MULTIPLE_PLATFORMS = new InjectionToken('AllowMultipleToken');
27818/**
27819 * A token for third-party components that can register themselves with NgProbe.
27820 *
27821 * @publicApi
27822 */
27823class NgProbeToken {
27824 constructor(name, token) {
27825 this.name = name;
27826 this.token = token;
27827 }
27828}
27829/**
27830 * Creates a platform.
27831 * Platforms must be created on launch using this function.
27832 *
27833 * @publicApi
27834 */
27835function createPlatform(injector) {
27836 if (_platform && !_platform.destroyed &&
27837 !_platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
27838 throw new Error('There can be only one platform. Destroy the previous one to create a new one.');
27839 }
27840 publishDefaultGlobalUtils$1();
27841 _platform = injector.get(PlatformRef);
27842 const inits = injector.get(PLATFORM_INITIALIZER, null);
27843 if (inits)
27844 inits.forEach((init) => init());
27845 return _platform;
27846}
27847/**
27848 * Creates a factory for a platform. Can be used to provide or override `Providers` specific to
27849 * your applciation's runtime needs, such as `PLATFORM_INITIALIZER` and `PLATFORM_ID`.
27850 * @param parentPlatformFactory Another platform factory to modify. Allows you to compose factories
27851 * to build up configurations that might be required by different libraries or parts of the
27852 * application.
27853 * @param name Identifies the new platform factory.
27854 * @param providers A set of dependency providers for platforms created with the new factory.
27855 *
27856 * @publicApi
27857 */
27858function createPlatformFactory(parentPlatformFactory, name, providers = []) {
27859 const desc = `Platform: ${name}`;
27860 const marker = new InjectionToken(desc);
27861 return (extraProviders = []) => {
27862 let platform = getPlatform();
27863 if (!platform || platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
27864 if (parentPlatformFactory) {
27865 parentPlatformFactory(providers.concat(extraProviders).concat({ provide: marker, useValue: true }));
27866 }
27867 else {
27868 const injectedProviders = providers.concat(extraProviders).concat({ provide: marker, useValue: true }, {
27869 provide: INJECTOR_SCOPE,
27870 useValue: 'platform'
27871 });
27872 createPlatform(Injector.create({ providers: injectedProviders, name: desc }));
27873 }
27874 }
27875 return assertPlatform(marker);
27876 };
27877}
27878/**
27879 * Checks that there is currently a platform that contains the given token as a provider.
27880 *
27881 * @publicApi
27882 */
27883function assertPlatform(requiredToken) {
27884 const platform = getPlatform();
27885 if (!platform) {
27886 throw new Error('No platform exists!');
27887 }
27888 if (!platform.injector.get(requiredToken, null)) {
27889 throw new Error('A platform with a different configuration has been created. Please destroy it first.');
27890 }
27891 return platform;
27892}
27893/**
27894 * Destroys the current Angular platform and all Angular applications on the page.
27895 * Destroys all modules and listeners registered with the platform.
27896 *
27897 * @publicApi
27898 */
27899function destroyPlatform() {
27900 if (_platform && !_platform.destroyed) {
27901 _platform.destroy();
27902 }
27903}
27904/**
27905 * Returns the current platform.
27906 *
27907 * @publicApi
27908 */
27909function getPlatform() {
27910 return _platform && !_platform.destroyed ? _platform : null;
27911}
27912/**
27913 * The Angular platform is the entry point for Angular on a web page.
27914 * Each page has exactly one platform. Services (such as reflection) which are common
27915 * to every Angular application running on the page are bound in its scope.
27916 * A page's platform is initialized implicitly when a platform is created using a platform
27917 * factory such as `PlatformBrowser`, or explicitly by calling the `createPlatform()` function.
27918 *
27919 * @publicApi
27920 */
27921class PlatformRef {
27922 /** @internal */
27923 constructor(_injector) {
27924 this._injector = _injector;
27925 this._modules = [];
27926 this._destroyListeners = [];
27927 this._destroyed = false;
27928 }
27929 /**
27930 * Creates an instance of an `@NgModule` for the given platform for offline compilation.
27931 *
27932 * @usageNotes
27933 *
27934 * The following example creates the NgModule for a browser platform.
27935 *
27936 * ```typescript
27937 * my_module.ts:
27938 *
27939 * @NgModule({
27940 * imports: [BrowserModule]
27941 * })
27942 * class MyModule {}
27943 *
27944 * main.ts:
27945 * import {MyModuleNgFactory} from './my_module.ngfactory';
27946 * import {platformBrowser} from '@angular/platform-browser';
27947 *
27948 * let moduleRef = platformBrowser().bootstrapModuleFactory(MyModuleNgFactory);
27949 * ```
27950 */
27951 bootstrapModuleFactory(moduleFactory, options) {
27952 // Note: We need to create the NgZone _before_ we instantiate the module,
27953 // as instantiating the module creates some providers eagerly.
27954 // So we create a mini parent injector that just contains the new NgZone and
27955 // pass that as parent to the NgModuleFactory.
27956 const ngZoneOption = options ? options.ngZone : undefined;
27957 const ngZoneEventCoalescing = (options && options.ngZoneEventCoalescing) || false;
27958 const ngZone = getNgZone(ngZoneOption, ngZoneEventCoalescing);
27959 const providers = [{ provide: NgZone, useValue: ngZone }];
27960 // Attention: Don't use ApplicationRef.run here,
27961 // as we want to be sure that all possible constructor calls are inside `ngZone.run`!
27962 return ngZone.run(() => {
27963 const ngZoneInjector = Injector.create({ providers: providers, parent: this.injector, name: moduleFactory.moduleType.name });
27964 const moduleRef = moduleFactory.create(ngZoneInjector);
27965 const exceptionHandler = moduleRef.injector.get(ErrorHandler, null);
27966 if (!exceptionHandler) {
27967 throw new Error('No ErrorHandler. Is platform module (BrowserModule) included?');
27968 }
27969 moduleRef.onDestroy(() => remove(this._modules, moduleRef));
27970 ngZone.runOutsideAngular(() => ngZone.onError.subscribe({
27971 next: (error) => {
27972 exceptionHandler.handleError(error);
27973 }
27974 }));
27975 return _callAndReportToErrorHandler(exceptionHandler, ngZone, () => {
27976 const initStatus = moduleRef.injector.get(ApplicationInitStatus);
27977 initStatus.runInitializers();
27978 return initStatus.donePromise.then(() => {
27979 if (ivyEnabled) {
27980 // If the `LOCALE_ID` provider is defined at bootstrap then we set the value for ivy
27981 const localeId = moduleRef.injector.get(LOCALE_ID$1, DEFAULT_LOCALE_ID);
27982 setLocaleId(localeId || DEFAULT_LOCALE_ID);
27983 }
27984 this._moduleDoBootstrap(moduleRef);
27985 return moduleRef;
27986 });
27987 });
27988 });
27989 }
27990 /**
27991 * Creates an instance of an `@NgModule` for a given platform using the given runtime compiler.
27992 *
27993 * @usageNotes
27994 * ### Simple Example
27995 *
27996 * ```typescript
27997 * @NgModule({
27998 * imports: [BrowserModule]
27999 * })
28000 * class MyModule {}
28001 *
28002 * let moduleRef = platformBrowser().bootstrapModule(MyModule);
28003 * ```
28004 *
28005 */
28006 bootstrapModule(moduleType, compilerOptions = []) {
28007 const options = optionsReducer({}, compilerOptions);
28008 return compileNgModuleFactory(this.injector, options, moduleType)
28009 .then(moduleFactory => this.bootstrapModuleFactory(moduleFactory, options));
28010 }
28011 _moduleDoBootstrap(moduleRef) {
28012 const appRef = moduleRef.injector.get(ApplicationRef);
28013 if (moduleRef._bootstrapComponents.length > 0) {
28014 moduleRef._bootstrapComponents.forEach(f => appRef.bootstrap(f));
28015 }
28016 else if (moduleRef.instance.ngDoBootstrap) {
28017 moduleRef.instance.ngDoBootstrap(appRef);
28018 }
28019 else {
28020 throw new Error(`The module ${stringify(moduleRef.instance
28021 .constructor)} was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. ` +
28022 `Please define one of these.`);
28023 }
28024 this._modules.push(moduleRef);
28025 }
28026 /**
28027 * Registers a listener to be called when the platform is destroyed.
28028 */
28029 onDestroy(callback) {
28030 this._destroyListeners.push(callback);
28031 }
28032 /**
28033 * Retrieves the platform {@link Injector}, which is the parent injector for
28034 * every Angular application on the page and provides singleton providers.
28035 */
28036 get injector() {
28037 return this._injector;
28038 }
28039 /**
28040 * Destroys the current Angular platform and all Angular applications on the page.
28041 * Destroys all modules and listeners registered with the platform.
28042 */
28043 destroy() {
28044 if (this._destroyed) {
28045 throw new Error('The platform has already been destroyed!');
28046 }
28047 this._modules.slice().forEach(module => module.destroy());
28048 this._destroyListeners.forEach(listener => listener());
28049 this._destroyed = true;
28050 }
28051 get destroyed() {
28052 return this._destroyed;
28053 }
28054}
28055PlatformRef.decorators = [
28056 { type: Injectable }
28057];
28058PlatformRef.ctorParameters = () => [
28059 { type: Injector }
28060];
28061function getNgZone(ngZoneOption, ngZoneEventCoalescing) {
28062 let ngZone;
28063 if (ngZoneOption === 'noop') {
28064 ngZone = new NoopNgZone();
28065 }
28066 else {
28067 ngZone = (ngZoneOption === 'zone.js' ? undefined : ngZoneOption) || new NgZone({
28068 enableLongStackTrace: isDevMode(),
28069 shouldCoalesceEventChangeDetection: ngZoneEventCoalescing
28070 });
28071 }
28072 return ngZone;
28073}
28074function _callAndReportToErrorHandler(errorHandler, ngZone, callback) {
28075 try {
28076 const result = callback();
28077 if (isPromise(result)) {
28078 return result.catch((e) => {
28079 ngZone.runOutsideAngular(() => errorHandler.handleError(e));
28080 // rethrow as the exception handler might not do it
28081 throw e;
28082 });
28083 }
28084 return result;
28085 }
28086 catch (e) {
28087 ngZone.runOutsideAngular(() => errorHandler.handleError(e));
28088 // rethrow as the exception handler might not do it
28089 throw e;
28090 }
28091}
28092function optionsReducer(dst, objs) {
28093 if (Array.isArray(objs)) {
28094 dst = objs.reduce(optionsReducer, dst);
28095 }
28096 else {
28097 dst = Object.assign(Object.assign({}, dst), objs);
28098 }
28099 return dst;
28100}
28101/**
28102 * A reference to an Angular application running on a page.
28103 *
28104 * @usageNotes
28105 *
28106 * {@a is-stable-examples}
28107 * ### isStable examples and caveats
28108 *
28109 * Note two important points about `isStable`, demonstrated in the examples below:
28110 * - the application will never be stable if you start any kind
28111 * of recurrent asynchronous task when the application starts
28112 * (for example for a polling process, started with a `setInterval`, a `setTimeout`
28113 * or using RxJS operators like `interval`);
28114 * - the `isStable` Observable runs outside of the Angular zone.
28115 *
28116 * Let's imagine that you start a recurrent task
28117 * (here incrementing a counter, using RxJS `interval`),
28118 * and at the same time subscribe to `isStable`.
28119 *
28120 * ```
28121 * constructor(appRef: ApplicationRef) {
28122 * appRef.isStable.pipe(
28123 * filter(stable => stable)
28124 * ).subscribe(() => console.log('App is stable now');
28125 * interval(1000).subscribe(counter => console.log(counter));
28126 * }
28127 * ```
28128 * In this example, `isStable` will never emit `true`,
28129 * and the trace "App is stable now" will never get logged.
28130 *
28131 * If you want to execute something when the app is stable,
28132 * you have to wait for the application to be stable
28133 * before starting your polling process.
28134 *
28135 * ```
28136 * constructor(appRef: ApplicationRef) {
28137 * appRef.isStable.pipe(
28138 * first(stable => stable),
28139 * tap(stable => console.log('App is stable now')),
28140 * switchMap(() => interval(1000))
28141 * ).subscribe(counter => console.log(counter));
28142 * }
28143 * ```
28144 * In this example, the trace "App is stable now" will be logged
28145 * and then the counter starts incrementing every second.
28146 *
28147 * Note also that this Observable runs outside of the Angular zone,
28148 * which means that the code in the subscription
28149 * to this Observable will not trigger the change detection.
28150 *
28151 * Let's imagine that instead of logging the counter value,
28152 * you update a field of your component
28153 * and display it in its template.
28154 *
28155 * ```
28156 * constructor(appRef: ApplicationRef) {
28157 * appRef.isStable.pipe(
28158 * first(stable => stable),
28159 * switchMap(() => interval(1000))
28160 * ).subscribe(counter => this.value = counter);
28161 * }
28162 * ```
28163 * As the `isStable` Observable runs outside the zone,
28164 * the `value` field will be updated properly,
28165 * but the template will not be refreshed!
28166 *
28167 * You'll have to manually trigger the change detection to update the template.
28168 *
28169 * ```
28170 * constructor(appRef: ApplicationRef, cd: ChangeDetectorRef) {
28171 * appRef.isStable.pipe(
28172 * first(stable => stable),
28173 * switchMap(() => interval(1000))
28174 * ).subscribe(counter => {
28175 * this.value = counter;
28176 * cd.detectChanges();
28177 * });
28178 * }
28179 * ```
28180 *
28181 * Or make the subscription callback run inside the zone.
28182 *
28183 * ```
28184 * constructor(appRef: ApplicationRef, zone: NgZone) {
28185 * appRef.isStable.pipe(
28186 * first(stable => stable),
28187 * switchMap(() => interval(1000))
28188 * ).subscribe(counter => zone.run(() => this.value = counter));
28189 * }
28190 * ```
28191 *
28192 * @publicApi
28193 */
28194class ApplicationRef {
28195 /** @internal */
28196 constructor(_zone, _console, _injector, _exceptionHandler, _componentFactoryResolver, _initStatus) {
28197 this._zone = _zone;
28198 this._console = _console;
28199 this._injector = _injector;
28200 this._exceptionHandler = _exceptionHandler;
28201 this._componentFactoryResolver = _componentFactoryResolver;
28202 this._initStatus = _initStatus;
28203 /** @internal */
28204 this._bootstrapListeners = [];
28205 this._views = [];
28206 this._runningTick = false;
28207 this._enforceNoNewChanges = false;
28208 this._stable = true;
28209 /**
28210 * Get a list of component types registered to this application.
28211 * This list is populated even before the component is created.
28212 */
28213 this.componentTypes = [];
28214 /**
28215 * Get a list of components registered to this application.
28216 */
28217 this.components = [];
28218 this._enforceNoNewChanges = isDevMode();
28219 this._zone.onMicrotaskEmpty.subscribe({
28220 next: () => {
28221 this._zone.run(() => {
28222 this.tick();
28223 });
28224 }
28225 });
28226 const isCurrentlyStable = new Observable((observer) => {
28227 this._stable = this._zone.isStable && !this._zone.hasPendingMacrotasks &&
28228 !this._zone.hasPendingMicrotasks;
28229 this._zone.runOutsideAngular(() => {
28230 observer.next(this._stable);
28231 observer.complete();
28232 });
28233 });
28234 const isStable = new Observable((observer) => {
28235 // Create the subscription to onStable outside the Angular Zone so that
28236 // the callback is run outside the Angular Zone.
28237 let stableSub;
28238 this._zone.runOutsideAngular(() => {
28239 stableSub = this._zone.onStable.subscribe(() => {
28240 NgZone.assertNotInAngularZone();
28241 // Check whether there are no pending macro/micro tasks in the next tick
28242 // to allow for NgZone to update the state.
28243 scheduleMicroTask(() => {
28244 if (!this._stable && !this._zone.hasPendingMacrotasks &&
28245 !this._zone.hasPendingMicrotasks) {
28246 this._stable = true;
28247 observer.next(true);
28248 }
28249 });
28250 });
28251 });
28252 const unstableSub = this._zone.onUnstable.subscribe(() => {
28253 NgZone.assertInAngularZone();
28254 if (this._stable) {
28255 this._stable = false;
28256 this._zone.runOutsideAngular(() => {
28257 observer.next(false);
28258 });
28259 }
28260 });
28261 return () => {
28262 stableSub.unsubscribe();
28263 unstableSub.unsubscribe();
28264 };
28265 });
28266 this.isStable =
28267 merge$1(isCurrentlyStable, isStable.pipe(share()));
28268 }
28269 /**
28270 * Bootstrap a new component at the root level of the application.
28271 *
28272 * @usageNotes
28273 * ### Bootstrap process
28274 *
28275 * When bootstrapping a new root component into an application, Angular mounts the
28276 * specified application component onto DOM elements identified by the componentType's
28277 * selector and kicks off automatic change detection to finish initializing the component.
28278 *
28279 * Optionally, a component can be mounted onto a DOM element that does not match the
28280 * componentType's selector.
28281 *
28282 * ### Example
28283 * {@example core/ts/platform/platform.ts region='longform'}
28284 */
28285 bootstrap(componentOrFactory, rootSelectorOrNode) {
28286 if (!this._initStatus.done) {
28287 throw new Error('Cannot bootstrap as there are still asynchronous initializers running. Bootstrap components in the `ngDoBootstrap` method of the root module.');
28288 }
28289 let componentFactory;
28290 if (componentOrFactory instanceof ComponentFactory) {
28291 componentFactory = componentOrFactory;
28292 }
28293 else {
28294 componentFactory =
28295 this._componentFactoryResolver.resolveComponentFactory(componentOrFactory);
28296 }
28297 this.componentTypes.push(componentFactory.componentType);
28298 // Create a factory associated with the current module if it's not bound to some other
28299 const ngModule = isBoundToModule(componentFactory) ? undefined : this._injector.get(NgModuleRef);
28300 const selectorOrNode = rootSelectorOrNode || componentFactory.selector;
28301 const compRef = componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule);
28302 compRef.onDestroy(() => {
28303 this._unloadComponent(compRef);
28304 });
28305 const testability = compRef.injector.get(Testability, null);
28306 if (testability) {
28307 compRef.injector.get(TestabilityRegistry)
28308 .registerApplication(compRef.location.nativeElement, testability);
28309 }
28310 this._loadComponent(compRef);
28311 if (isDevMode()) {
28312 this._console.log(`Angular is running in development mode. Call enableProdMode() to enable production mode.`);
28313 }
28314 return compRef;
28315 }
28316 /**
28317 * Invoke this method to explicitly process change detection and its side-effects.
28318 *
28319 * In development mode, `tick()` also performs a second change detection cycle to ensure that no
28320 * further changes are detected. If additional changes are picked up during this second cycle,
28321 * bindings in the app have side-effects that cannot be resolved in a single change detection
28322 * pass.
28323 * In this case, Angular throws an error, since an Angular application can only have one change
28324 * detection pass during which all change detection must complete.
28325 */
28326 tick() {
28327 if (this._runningTick) {
28328 throw new Error('ApplicationRef.tick is called recursively');
28329 }
28330 try {
28331 this._runningTick = true;
28332 for (let view of this._views) {
28333 view.detectChanges();
28334 }
28335 if (this._enforceNoNewChanges) {
28336 for (let view of this._views) {
28337 view.checkNoChanges();
28338 }
28339 }
28340 }
28341 catch (e) {
28342 // Attention: Don't rethrow as it could cancel subscriptions to Observables!
28343 this._zone.runOutsideAngular(() => this._exceptionHandler.handleError(e));
28344 }
28345 finally {
28346 this._runningTick = false;
28347 }
28348 }
28349 /**
28350 * Attaches a view so that it will be dirty checked.
28351 * The view will be automatically detached when it is destroyed.
28352 * This will throw if the view is already attached to a ViewContainer.
28353 */
28354 attachView(viewRef) {
28355 const view = viewRef;
28356 this._views.push(view);
28357 view.attachToAppRef(this);
28358 }
28359 /**
28360 * Detaches a view from dirty checking again.
28361 */
28362 detachView(viewRef) {
28363 const view = viewRef;
28364 remove(this._views, view);
28365 view.detachFromAppRef();
28366 }
28367 _loadComponent(componentRef) {
28368 this.attachView(componentRef.hostView);
28369 this.tick();
28370 this.components.push(componentRef);
28371 // Get the listeners lazily to prevent DI cycles.
28372 const listeners = this._injector.get(APP_BOOTSTRAP_LISTENER, []).concat(this._bootstrapListeners);
28373 listeners.forEach((listener) => listener(componentRef));
28374 }
28375 _unloadComponent(componentRef) {
28376 this.detachView(componentRef.hostView);
28377 remove(this.components, componentRef);
28378 }
28379 /** @internal */
28380 ngOnDestroy() {
28381 // TODO(alxhub): Dispose of the NgZone.
28382 this._views.slice().forEach((view) => view.destroy());
28383 }
28384 /**
28385 * Returns the number of attached views.
28386 */
28387 get viewCount() {
28388 return this._views.length;
28389 }
28390}
28391ApplicationRef.decorators = [
28392 { type: Injectable }
28393];
28394ApplicationRef.ctorParameters = () => [
28395 { type: NgZone },
28396 { type: Console },
28397 { type: Injector },
28398 { type: ErrorHandler },
28399 { type: ComponentFactoryResolver },
28400 { type: ApplicationInitStatus }
28401];
28402function remove(list, el) {
28403 const index = list.indexOf(el);
28404 if (index > -1) {
28405 list.splice(index, 1);
28406 }
28407}
28408function _lastDefined(args) {
28409 for (let i = args.length - 1; i >= 0; i--) {
28410 if (args[i] !== undefined) {
28411 return args[i];
28412 }
28413 }
28414 return undefined;
28415}
28416function _mergeArrays(parts) {
28417 const result = [];
28418 parts.forEach((part) => part && result.push(...part));
28419 return result;
28420}
28421
28422/**
28423 * @license
28424 * Copyright Google LLC All Rights Reserved.
28425 *
28426 * Use of this source code is governed by an MIT-style license that can be
28427 * found in the LICENSE file at https://angular.io/license
28428 */
28429
28430/**
28431 * @license
28432 * Copyright Google LLC All Rights Reserved.
28433 *
28434 * Use of this source code is governed by an MIT-style license that can be
28435 * found in the LICENSE file at https://angular.io/license
28436 */
28437
28438/**
28439 * @license
28440 * Copyright Google LLC All Rights Reserved.
28441 *
28442 * Use of this source code is governed by an MIT-style license that can be
28443 * found in the LICENSE file at https://angular.io/license
28444 */
28445/**
28446 * Used to load ng module factories.
28447 *
28448 * @publicApi
28449 * @deprecated the `string` form of `loadChildren` is deprecated, and `NgModuleFactoryLoader` is
28450 * part of its implementation. See `LoadChildren` for more details.
28451 */
28452class NgModuleFactoryLoader {
28453}
28454function getModuleFactory__PRE_R3__(id) {
28455 const factory = getRegisteredNgModuleType(id);
28456 if (!factory)
28457 throw noModuleError(id);
28458 return factory;
28459}
28460function getModuleFactory__POST_R3__(id) {
28461 const type = getRegisteredNgModuleType(id);
28462 if (!type)
28463 throw noModuleError(id);
28464 return new NgModuleFactory$1(type);
28465}
28466/**
28467 * Returns the NgModuleFactory with the given id, if it exists and has been loaded.
28468 * Factories for modules that do not specify an `id` cannot be retrieved. Throws if the module
28469 * cannot be found.
28470 * @publicApi
28471 */
28472const getModuleFactory = getModuleFactory__PRE_R3__;
28473function noModuleError(id) {
28474 return new Error(`No module with ID ${id} loaded`);
28475}
28476
28477/**
28478 * @license
28479 * Copyright Google LLC All Rights Reserved.
28480 *
28481 * Use of this source code is governed by an MIT-style license that can be
28482 * found in the LICENSE file at https://angular.io/license
28483 */
28484const _SEPARATOR = '#';
28485const FACTORY_CLASS_SUFFIX = 'NgFactory';
28486/**
28487 * Configuration for SystemJsNgModuleLoader.
28488 * token.
28489 *
28490 * @publicApi
28491 * @deprecated the `string` form of `loadChildren` is deprecated, and `SystemJsNgModuleLoaderConfig`
28492 * is part of its implementation. See `LoadChildren` for more details.
28493 */
28494class SystemJsNgModuleLoaderConfig {
28495}
28496const DEFAULT_CONFIG = {
28497 factoryPathPrefix: '',
28498 factoryPathSuffix: '.ngfactory',
28499};
28500/**
28501 * NgModuleFactoryLoader that uses SystemJS to load NgModuleFactory
28502 * @publicApi
28503 * @deprecated the `string` form of `loadChildren` is deprecated, and `SystemJsNgModuleLoader` is
28504 * part of its implementation. See `LoadChildren` for more details.
28505 */
28506class SystemJsNgModuleLoader {
28507 constructor(_compiler, config) {
28508 this._compiler = _compiler;
28509 this._config = config || DEFAULT_CONFIG;
28510 }
28511 load(path) {
28512 const legacyOfflineMode = !ivyEnabled && this._compiler instanceof Compiler;
28513 return legacyOfflineMode ? this.loadFactory(path) : this.loadAndCompile(path);
28514 }
28515 loadAndCompile(path) {
28516 let [module, exportName] = path.split(_SEPARATOR);
28517 if (exportName === undefined) {
28518 exportName = 'default';
28519 }
28520 return System.import(module)
28521 .then((module) => module[exportName])
28522 .then((type) => checkNotEmpty(type, module, exportName))
28523 .then((type) => this._compiler.compileModuleAsync(type));
28524 }
28525 loadFactory(path) {
28526 let [module, exportName] = path.split(_SEPARATOR);
28527 let factoryClassSuffix = FACTORY_CLASS_SUFFIX;
28528 if (exportName === undefined) {
28529 exportName = 'default';
28530 factoryClassSuffix = '';
28531 }
28532 return System.import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix)
28533 .then((module) => module[exportName + factoryClassSuffix])
28534 .then((factory) => checkNotEmpty(factory, module, exportName));
28535 }
28536}
28537SystemJsNgModuleLoader.decorators = [
28538 { type: Injectable }
28539];
28540SystemJsNgModuleLoader.ctorParameters = () => [
28541 { type: Compiler },
28542 { type: SystemJsNgModuleLoaderConfig, decorators: [{ type: Optional }] }
28543];
28544function checkNotEmpty(value, modulePath, exportName) {
28545 if (!value) {
28546 throw new Error(`Cannot find '${exportName}' in '${modulePath}'`);
28547 }
28548 return value;
28549}
28550
28551/**
28552 * @license
28553 * Copyright Google LLC All Rights Reserved.
28554 *
28555 * Use of this source code is governed by an MIT-style license that can be
28556 * found in the LICENSE file at https://angular.io/license
28557 */
28558/**
28559 * Represents an Angular [view](guide/glossary#view "Definition").
28560 *
28561 * @see {@link ChangeDetectorRef#usage-notes Change detection usage}
28562 *
28563 * @publicApi
28564 */
28565class ViewRef$1 extends ChangeDetectorRef {
28566}
28567/**
28568 * Represents an Angular [view](guide/glossary#view) in a view container.
28569 * An [embedded view](guide/glossary#view-tree) can be referenced from a component
28570 * other than the hosting component whose template defines it, or it can be defined
28571 * independently by a `TemplateRef`.
28572 *
28573 * Properties of elements in a view can change, but the structure (number and order) of elements in
28574 * a view cannot. Change the structure of elements by inserting, moving, or
28575 * removing nested views in a view container.
28576 *
28577 * @see `ViewContainerRef`
28578 *
28579 * @usageNotes
28580 *
28581 * The following template breaks down into two separate `TemplateRef` instances,
28582 * an outer one and an inner one.
28583 *
28584 * ```
28585 * Count: {{items.length}}
28586 * <ul>
28587 * <li *ngFor="let item of items">{{item}}</li>
28588 * </ul>
28589 * ```
28590 *
28591 * This is the outer `TemplateRef`:
28592 *
28593 * ```
28594 * Count: {{items.length}}
28595 * <ul>
28596 * <ng-template ngFor let-item [ngForOf]="items"></ng-template>
28597 * </ul>
28598 * ```
28599 *
28600 * This is the inner `TemplateRef`:
28601 *
28602 * ```
28603 * <li>{{item}}</li>
28604 * ```
28605 *
28606 * The outer and inner `TemplateRef` instances are assembled into views as follows:
28607 *
28608 * ```
28609 * <!-- ViewRef: outer-0 -->
28610 * Count: 2
28611 * <ul>
28612 * <ng-template view-container-ref></ng-template>
28613 * <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 -->
28614 * <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 -->
28615 * </ul>
28616 * <!-- /ViewRef: outer-0 -->
28617 * ```
28618 * @publicApi
28619 */
28620class EmbeddedViewRef extends ViewRef$1 {
28621}
28622
28623/**
28624 * @license
28625 * Copyright Google LLC All Rights Reserved.
28626 *
28627 * Use of this source code is governed by an MIT-style license that can be
28628 * found in the LICENSE file at https://angular.io/license
28629 */
28630
28631/**
28632 * @license
28633 * Copyright Google LLC All Rights Reserved.
28634 *
28635 * Use of this source code is governed by an MIT-style license that can be
28636 * found in the LICENSE file at https://angular.io/license
28637 */
28638/**
28639 * @publicApi
28640 */
28641class DebugEventListener {
28642 constructor(name, callback) {
28643 this.name = name;
28644 this.callback = callback;
28645 }
28646}
28647class DebugNode__PRE_R3__ {
28648 constructor(nativeNode, parent, _debugContext) {
28649 this.listeners = [];
28650 this.parent = null;
28651 this._debugContext = _debugContext;
28652 this.nativeNode = nativeNode;
28653 if (parent && parent instanceof DebugElement__PRE_R3__) {
28654 parent.addChild(this);
28655 }
28656 }
28657 get injector() {
28658 return this._debugContext.injector;
28659 }
28660 get componentInstance() {
28661 return this._debugContext.component;
28662 }
28663 get context() {
28664 return this._debugContext.context;
28665 }
28666 get references() {
28667 return this._debugContext.references;
28668 }
28669 get providerTokens() {
28670 return this._debugContext.providerTokens;
28671 }
28672}
28673class DebugElement__PRE_R3__ extends DebugNode__PRE_R3__ {
28674 constructor(nativeNode, parent, _debugContext) {
28675 super(nativeNode, parent, _debugContext);
28676 this.properties = {};
28677 this.attributes = {};
28678 this.classes = {};
28679 this.styles = {};
28680 this.childNodes = [];
28681 this.nativeElement = nativeNode;
28682 }
28683 addChild(child) {
28684 if (child) {
28685 this.childNodes.push(child);
28686 child.parent = this;
28687 }
28688 }
28689 removeChild(child) {
28690 const childIndex = this.childNodes.indexOf(child);
28691 if (childIndex !== -1) {
28692 child.parent = null;
28693 this.childNodes.splice(childIndex, 1);
28694 }
28695 }
28696 insertChildrenAfter(child, newChildren) {
28697 const siblingIndex = this.childNodes.indexOf(child);
28698 if (siblingIndex !== -1) {
28699 this.childNodes.splice(siblingIndex + 1, 0, ...newChildren);
28700 newChildren.forEach(c => {
28701 if (c.parent) {
28702 c.parent.removeChild(c);
28703 }
28704 child.parent = this;
28705 });
28706 }
28707 }
28708 insertBefore(refChild, newChild) {
28709 const refIndex = this.childNodes.indexOf(refChild);
28710 if (refIndex === -1) {
28711 this.addChild(newChild);
28712 }
28713 else {
28714 if (newChild.parent) {
28715 newChild.parent.removeChild(newChild);
28716 }
28717 newChild.parent = this;
28718 this.childNodes.splice(refIndex, 0, newChild);
28719 }
28720 }
28721 query(predicate) {
28722 const results = this.queryAll(predicate);
28723 return results[0] || null;
28724 }
28725 queryAll(predicate) {
28726 const matches = [];
28727 _queryElementChildren(this, predicate, matches);
28728 return matches;
28729 }
28730 queryAllNodes(predicate) {
28731 const matches = [];
28732 _queryNodeChildren(this, predicate, matches);
28733 return matches;
28734 }
28735 get children() {
28736 return this.childNodes //
28737 .filter((node) => node instanceof DebugElement__PRE_R3__);
28738 }
28739 triggerEventHandler(eventName, eventObj) {
28740 this.listeners.forEach((listener) => {
28741 if (listener.name == eventName) {
28742 listener.callback(eventObj);
28743 }
28744 });
28745 }
28746}
28747/**
28748 * @publicApi
28749 */
28750function asNativeElements(debugEls) {
28751 return debugEls.map((el) => el.nativeElement);
28752}
28753function _queryElementChildren(element, predicate, matches) {
28754 element.childNodes.forEach(node => {
28755 if (node instanceof DebugElement__PRE_R3__) {
28756 if (predicate(node)) {
28757 matches.push(node);
28758 }
28759 _queryElementChildren(node, predicate, matches);
28760 }
28761 });
28762}
28763function _queryNodeChildren(parentNode, predicate, matches) {
28764 if (parentNode instanceof DebugElement__PRE_R3__) {
28765 parentNode.childNodes.forEach(node => {
28766 if (predicate(node)) {
28767 matches.push(node);
28768 }
28769 if (node instanceof DebugElement__PRE_R3__) {
28770 _queryNodeChildren(node, predicate, matches);
28771 }
28772 });
28773 }
28774}
28775class DebugNode__POST_R3__ {
28776 constructor(nativeNode) {
28777 this.nativeNode = nativeNode;
28778 }
28779 get parent() {
28780 const parent = this.nativeNode.parentNode;
28781 return parent ? new DebugElement__POST_R3__(parent) : null;
28782 }
28783 get injector() {
28784 return getInjector(this.nativeNode);
28785 }
28786 get componentInstance() {
28787 const nativeElement = this.nativeNode;
28788 return nativeElement &&
28789 (getComponent(nativeElement) || getOwningComponent(nativeElement));
28790 }
28791 get context() {
28792 return getComponent(this.nativeNode) || getContext(this.nativeNode);
28793 }
28794 get listeners() {
28795 return getListeners(this.nativeNode).filter(listener => listener.type === 'dom');
28796 }
28797 get references() {
28798 return getLocalRefs(this.nativeNode);
28799 }
28800 get providerTokens() {
28801 return getInjectionTokens(this.nativeNode);
28802 }
28803}
28804class DebugElement__POST_R3__ extends DebugNode__POST_R3__ {
28805 constructor(nativeNode) {
28806 ngDevMode && assertDomNode(nativeNode);
28807 super(nativeNode);
28808 }
28809 get nativeElement() {
28810 return this.nativeNode.nodeType == Node.ELEMENT_NODE ? this.nativeNode : null;
28811 }
28812 get name() {
28813 try {
28814 const context = loadLContext(this.nativeNode);
28815 const lView = context.lView;
28816 const tData = lView[TVIEW].data;
28817 const tNode = tData[context.nodeIndex];
28818 return tNode.tagName;
28819 }
28820 catch (e) {
28821 return this.nativeNode.nodeName;
28822 }
28823 }
28824 /**
28825 * Gets a map of property names to property values for an element.
28826 *
28827 * This map includes:
28828 * - Regular property bindings (e.g. `[id]="id"`)
28829 * - Host property bindings (e.g. `host: { '[id]': "id" }`)
28830 * - Interpolated property bindings (e.g. `id="{{ value }}")
28831 *
28832 * It does not include:
28833 * - input property bindings (e.g. `[myCustomInput]="value"`)
28834 * - attribute bindings (e.g. `[attr.role]="menu"`)
28835 */
28836 get properties() {
28837 const context = loadLContext(this.nativeNode, false);
28838 if (context == null) {
28839 return {};
28840 }
28841 const lView = context.lView;
28842 const tData = lView[TVIEW].data;
28843 const tNode = tData[context.nodeIndex];
28844 const properties = {};
28845 // Collect properties from the DOM.
28846 copyDomProperties(this.nativeElement, properties);
28847 // Collect properties from the bindings. This is needed for animation renderer which has
28848 // synthetic properties which don't get reflected into the DOM.
28849 collectPropertyBindings(properties, tNode, lView, tData);
28850 return properties;
28851 }
28852 get attributes() {
28853 const attributes = {};
28854 const element = this.nativeElement;
28855 if (!element) {
28856 return attributes;
28857 }
28858 const context = loadLContext(element, false);
28859 if (context == null) {
28860 return {};
28861 }
28862 const lView = context.lView;
28863 const tNodeAttrs = lView[TVIEW].data[context.nodeIndex].attrs;
28864 const lowercaseTNodeAttrs = [];
28865 // For debug nodes we take the element's attribute directly from the DOM since it allows us
28866 // to account for ones that weren't set via bindings (e.g. ViewEngine keeps track of the ones
28867 // that are set through `Renderer2`). The problem is that the browser will lowercase all names,
28868 // however since we have the attributes already on the TNode, we can preserve the case by going
28869 // through them once, adding them to the `attributes` map and putting their lower-cased name
28870 // into an array. Afterwards when we're going through the native DOM attributes, we can check
28871 // whether we haven't run into an attribute already through the TNode.
28872 if (tNodeAttrs) {
28873 let i = 0;
28874 while (i < tNodeAttrs.length) {
28875 const attrName = tNodeAttrs[i];
28876 // Stop as soon as we hit a marker. We only care about the regular attributes. Everything
28877 // else will be handled below when we read the final attributes off the DOM.
28878 if (typeof attrName !== 'string')
28879 break;
28880 const attrValue = tNodeAttrs[i + 1];
28881 attributes[attrName] = attrValue;
28882 lowercaseTNodeAttrs.push(attrName.toLowerCase());
28883 i += 2;
28884 }
28885 }
28886 const eAttrs = element.attributes;
28887 for (let i = 0; i < eAttrs.length; i++) {
28888 const attr = eAttrs[i];
28889 const lowercaseName = attr.name.toLowerCase();
28890 // Make sure that we don't assign the same attribute both in its
28891 // case-sensitive form and the lower-cased one from the browser.
28892 if (lowercaseTNodeAttrs.indexOf(lowercaseName) === -1) {
28893 // Save the lowercase name to align the behavior between browsers.
28894 // IE preserves the case, while all other browser convert it to lower case.
28895 attributes[lowercaseName] = attr.value;
28896 }
28897 }
28898 return attributes;
28899 }
28900 get styles() {
28901 if (this.nativeElement && this.nativeElement.style) {
28902 return this.nativeElement.style;
28903 }
28904 return {};
28905 }
28906 get classes() {
28907 const result = {};
28908 const element = this.nativeElement;
28909 // SVG elements return an `SVGAnimatedString` instead of a plain string for the `className`.
28910 const className = element.className;
28911 const classes = className && typeof className !== 'string' ? className.baseVal.split(' ') :
28912 className.split(' ');
28913 classes.forEach((value) => result[value] = true);
28914 return result;
28915 }
28916 get childNodes() {
28917 const childNodes = this.nativeNode.childNodes;
28918 const children = [];
28919 for (let i = 0; i < childNodes.length; i++) {
28920 const element = childNodes[i];
28921 children.push(getDebugNode__POST_R3__(element));
28922 }
28923 return children;
28924 }
28925 get children() {
28926 const nativeElement = this.nativeElement;
28927 if (!nativeElement)
28928 return [];
28929 const childNodes = nativeElement.children;
28930 const children = [];
28931 for (let i = 0; i < childNodes.length; i++) {
28932 const element = childNodes[i];
28933 children.push(getDebugNode__POST_R3__(element));
28934 }
28935 return children;
28936 }
28937 query(predicate) {
28938 const results = this.queryAll(predicate);
28939 return results[0] || null;
28940 }
28941 queryAll(predicate) {
28942 const matches = [];
28943 _queryAllR3(this, predicate, matches, true);
28944 return matches;
28945 }
28946 queryAllNodes(predicate) {
28947 const matches = [];
28948 _queryAllR3(this, predicate, matches, false);
28949 return matches;
28950 }
28951 triggerEventHandler(eventName, eventObj) {
28952 const node = this.nativeNode;
28953 const invokedListeners = [];
28954 this.listeners.forEach(listener => {
28955 if (listener.name === eventName) {
28956 const callback = listener.callback;
28957 callback.call(node, eventObj);
28958 invokedListeners.push(callback);
28959 }
28960 });
28961 // We need to check whether `eventListeners` exists, because it's something
28962 // that Zone.js only adds to `EventTarget` in browser environments.
28963 if (typeof node.eventListeners === 'function') {
28964 // Note that in Ivy we wrap event listeners with a call to `event.preventDefault` in some
28965 // cases. We use '__ngUnwrap__' as a special token that gives us access to the actual event
28966 // listener.
28967 node.eventListeners(eventName).forEach((listener) => {
28968 // In order to ensure that we can detect the special __ngUnwrap__ token described above, we
28969 // use `toString` on the listener and see if it contains the token. We use this approach to
28970 // ensure that it still worked with compiled code since it cannot remove or rename string
28971 // literals. We also considered using a special function name (i.e. if(listener.name ===
28972 // special)) but that was more cumbersome and we were also concerned the compiled code could
28973 // strip the name, turning the condition in to ("" === "") and always returning true.
28974 if (listener.toString().indexOf('__ngUnwrap__') !== -1) {
28975 const unwrappedListener = listener('__ngUnwrap__');
28976 return invokedListeners.indexOf(unwrappedListener) === -1 &&
28977 unwrappedListener.call(node, eventObj);
28978 }
28979 });
28980 }
28981 }
28982}
28983function copyDomProperties(element, properties) {
28984 if (element) {
28985 // Skip own properties (as those are patched)
28986 let obj = Object.getPrototypeOf(element);
28987 const NodePrototype = Node.prototype;
28988 while (obj !== null && obj !== NodePrototype) {
28989 const descriptors = Object.getOwnPropertyDescriptors(obj);
28990 for (let key in descriptors) {
28991 if (!key.startsWith('__') && !key.startsWith('on')) {
28992 // don't include properties starting with `__` and `on`.
28993 // `__` are patched values which should not be included.
28994 // `on` are listeners which also should not be included.
28995 const value = element[key];
28996 if (isPrimitiveValue(value)) {
28997 properties[key] = value;
28998 }
28999 }
29000 }
29001 obj = Object.getPrototypeOf(obj);
29002 }
29003 }
29004}
29005function isPrimitiveValue(value) {
29006 return typeof value === 'string' || typeof value === 'boolean' || typeof value === 'number' ||
29007 value === null;
29008}
29009function _queryAllR3(parentElement, predicate, matches, elementsOnly) {
29010 const context = loadLContext(parentElement.nativeNode, false);
29011 if (context !== null) {
29012 const parentTNode = context.lView[TVIEW].data[context.nodeIndex];
29013 _queryNodeChildrenR3(parentTNode, context.lView, predicate, matches, elementsOnly, parentElement.nativeNode);
29014 }
29015 else {
29016 // If the context is null, then `parentElement` was either created with Renderer2 or native DOM
29017 // APIs.
29018 _queryNativeNodeDescendants(parentElement.nativeNode, predicate, matches, elementsOnly);
29019 }
29020}
29021/**
29022 * Recursively match the current TNode against the predicate, and goes on with the next ones.
29023 *
29024 * @param tNode the current TNode
29025 * @param lView the LView of this TNode
29026 * @param predicate the predicate to match
29027 * @param matches the list of positive matches
29028 * @param elementsOnly whether only elements should be searched
29029 * @param rootNativeNode the root native node on which predicate should not be matched
29030 */
29031function _queryNodeChildrenR3(tNode, lView, predicate, matches, elementsOnly, rootNativeNode) {
29032 const nativeNode = getNativeByTNodeOrNull(tNode, lView);
29033 // For each type of TNode, specific logic is executed.
29034 if (tNode.type === 3 /* Element */ || tNode.type === 4 /* ElementContainer */) {
29035 // Case 1: the TNode is an element
29036 // The native node has to be checked.
29037 _addQueryMatchR3(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
29038 if (isComponentHost(tNode)) {
29039 // If the element is the host of a component, then all nodes in its view have to be processed.
29040 // Note: the component's content (tNode.child) will be processed from the insertion points.
29041 const componentView = getComponentLViewByIndex(tNode.index, lView);
29042 if (componentView && componentView[TVIEW].firstChild) {
29043 _queryNodeChildrenR3(componentView[TVIEW].firstChild, componentView, predicate, matches, elementsOnly, rootNativeNode);
29044 }
29045 }
29046 else {
29047 if (tNode.child) {
29048 // Otherwise, its children have to be processed.
29049 _queryNodeChildrenR3(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
29050 }
29051 // We also have to query the DOM directly in order to catch elements inserted through
29052 // Renderer2. Note that this is __not__ optimal, because we're walking similar trees multiple
29053 // times. ViewEngine could do it more efficiently, because all the insertions go through
29054 // Renderer2, however that's not the case in Ivy. This approach is being used because:
29055 // 1. Matching the ViewEngine behavior would mean potentially introducing a depedency
29056 // from `Renderer2` to Ivy which could bring Ivy code into ViewEngine.
29057 // 2. We would have to make `Renderer3` "know" about debug nodes.
29058 // 3. It allows us to capture nodes that were inserted directly via the DOM.
29059 nativeNode && _queryNativeNodeDescendants(nativeNode, predicate, matches, elementsOnly);
29060 }
29061 // In all cases, if a dynamic container exists for this node, each view inside it has to be
29062 // processed.
29063 const nodeOrContainer = lView[tNode.index];
29064 if (isLContainer(nodeOrContainer)) {
29065 _queryNodeChildrenInContainerR3(nodeOrContainer, predicate, matches, elementsOnly, rootNativeNode);
29066 }
29067 }
29068 else if (tNode.type === 0 /* Container */) {
29069 // Case 2: the TNode is a container
29070 // The native node has to be checked.
29071 const lContainer = lView[tNode.index];
29072 _addQueryMatchR3(lContainer[NATIVE], predicate, matches, elementsOnly, rootNativeNode);
29073 // Each view inside the container has to be processed.
29074 _queryNodeChildrenInContainerR3(lContainer, predicate, matches, elementsOnly, rootNativeNode);
29075 }
29076 else if (tNode.type === 1 /* Projection */) {
29077 // Case 3: the TNode is a projection insertion point (i.e. a <ng-content>).
29078 // The nodes projected at this location all need to be processed.
29079 const componentView = lView[DECLARATION_COMPONENT_VIEW];
29080 const componentHost = componentView[T_HOST];
29081 const head = componentHost.projection[tNode.projection];
29082 if (Array.isArray(head)) {
29083 for (let nativeNode of head) {
29084 _addQueryMatchR3(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
29085 }
29086 }
29087 else if (head) {
29088 const nextLView = componentView[PARENT];
29089 const nextTNode = nextLView[TVIEW].data[head.index];
29090 _queryNodeChildrenR3(nextTNode, nextLView, predicate, matches, elementsOnly, rootNativeNode);
29091 }
29092 }
29093 else if (tNode.child) {
29094 // Case 4: the TNode is a view.
29095 _queryNodeChildrenR3(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
29096 }
29097 // We don't want to go to the next sibling of the root node.
29098 if (rootNativeNode !== nativeNode) {
29099 // To determine the next node to be processed, we need to use the next or the projectionNext
29100 // link, depending on whether the current node has been projected.
29101 const nextTNode = (tNode.flags & 4 /* isProjected */) ? tNode.projectionNext : tNode.next;
29102 if (nextTNode) {
29103 _queryNodeChildrenR3(nextTNode, lView, predicate, matches, elementsOnly, rootNativeNode);
29104 }
29105 }
29106}
29107/**
29108 * Process all TNodes in a given container.
29109 *
29110 * @param lContainer the container to be processed
29111 * @param predicate the predicate to match
29112 * @param matches the list of positive matches
29113 * @param elementsOnly whether only elements should be searched
29114 * @param rootNativeNode the root native node on which predicate should not be matched
29115 */
29116function _queryNodeChildrenInContainerR3(lContainer, predicate, matches, elementsOnly, rootNativeNode) {
29117 for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
29118 const childView = lContainer[i];
29119 _queryNodeChildrenR3(childView[TVIEW].node, childView, predicate, matches, elementsOnly, rootNativeNode);
29120 }
29121}
29122/**
29123 * Match the current native node against the predicate.
29124 *
29125 * @param nativeNode the current native node
29126 * @param predicate the predicate to match
29127 * @param matches the list of positive matches
29128 * @param elementsOnly whether only elements should be searched
29129 * @param rootNativeNode the root native node on which predicate should not be matched
29130 */
29131function _addQueryMatchR3(nativeNode, predicate, matches, elementsOnly, rootNativeNode) {
29132 if (rootNativeNode !== nativeNode) {
29133 const debugNode = getDebugNode$1(nativeNode);
29134 if (!debugNode) {
29135 return;
29136 }
29137 // Type of the "predicate and "matches" array are set based on the value of
29138 // the "elementsOnly" parameter. TypeScript is not able to properly infer these
29139 // types with generics, so we manually cast the parameters accordingly.
29140 if (elementsOnly && debugNode instanceof DebugElement__POST_R3__ && predicate(debugNode) &&
29141 matches.indexOf(debugNode) === -1) {
29142 matches.push(debugNode);
29143 }
29144 else if (!elementsOnly && predicate(debugNode) &&
29145 matches.indexOf(debugNode) === -1) {
29146 matches.push(debugNode);
29147 }
29148 }
29149}
29150/**
29151 * Match all the descendants of a DOM node against a predicate.
29152 *
29153 * @param nativeNode the current native node
29154 * @param predicate the predicate to match
29155 * @param matches the list of positive matches
29156 * @param elementsOnly whether only elements should be searched
29157 */
29158function _queryNativeNodeDescendants(parentNode, predicate, matches, elementsOnly) {
29159 const nodes = parentNode.childNodes;
29160 const length = nodes.length;
29161 for (let i = 0; i < length; i++) {
29162 const node = nodes[i];
29163 const debugNode = getDebugNode$1(node);
29164 if (debugNode) {
29165 if (elementsOnly && debugNode instanceof DebugElement__POST_R3__ && predicate(debugNode) &&
29166 matches.indexOf(debugNode) === -1) {
29167 matches.push(debugNode);
29168 }
29169 else if (!elementsOnly && predicate(debugNode) &&
29170 matches.indexOf(debugNode) === -1) {
29171 matches.push(debugNode);
29172 }
29173 _queryNativeNodeDescendants(node, predicate, matches, elementsOnly);
29174 }
29175 }
29176}
29177/**
29178 * Iterates through the property bindings for a given node and generates
29179 * a map of property names to values. This map only contains property bindings
29180 * defined in templates, not in host bindings.
29181 */
29182function collectPropertyBindings(properties, tNode, lView, tData) {
29183 let bindingIndexes = tNode.propertyBindings;
29184 if (bindingIndexes !== null) {
29185 for (let i = 0; i < bindingIndexes.length; i++) {
29186 const bindingIndex = bindingIndexes[i];
29187 const propMetadata = tData[bindingIndex];
29188 const metadataParts = propMetadata.split(INTERPOLATION_DELIMITER);
29189 const propertyName = metadataParts[0];
29190 if (metadataParts.length > 1) {
29191 let value = metadataParts[1];
29192 for (let j = 1; j < metadataParts.length - 1; j++) {
29193 value += renderStringify(lView[bindingIndex + j - 1]) + metadataParts[j + 1];
29194 }
29195 properties[propertyName] = value;
29196 }
29197 else {
29198 properties[propertyName] = lView[bindingIndex];
29199 }
29200 }
29201 }
29202}
29203// Need to keep the nodes in a global Map so that multiple angular apps are supported.
29204const _nativeNodeToDebugNode = new Map();
29205function getDebugNode__PRE_R3__(nativeNode) {
29206 return _nativeNodeToDebugNode.get(nativeNode) || null;
29207}
29208const NG_DEBUG_PROPERTY = '__ng_debug__';
29209function getDebugNode__POST_R3__(nativeNode) {
29210 if (nativeNode instanceof Node) {
29211 if (!(nativeNode.hasOwnProperty(NG_DEBUG_PROPERTY))) {
29212 nativeNode[NG_DEBUG_PROPERTY] = nativeNode.nodeType == Node.ELEMENT_NODE ?
29213 new DebugElement__POST_R3__(nativeNode) :
29214 new DebugNode__POST_R3__(nativeNode);
29215 }
29216 return nativeNode[NG_DEBUG_PROPERTY];
29217 }
29218 return null;
29219}
29220/**
29221 * @publicApi
29222 */
29223const getDebugNode$1 = getDebugNode__PRE_R3__;
29224function getDebugNodeR2__PRE_R3__(nativeNode) {
29225 return getDebugNode__PRE_R3__(nativeNode);
29226}
29227function getDebugNodeR2__POST_R3__(_nativeNode) {
29228 return null;
29229}
29230const getDebugNodeR2 = getDebugNodeR2__PRE_R3__;
29231function getAllDebugNodes() {
29232 return Array.from(_nativeNodeToDebugNode.values());
29233}
29234function indexDebugNode(node) {
29235 _nativeNodeToDebugNode.set(node.nativeNode, node);
29236}
29237function removeDebugNodeFromIndex(node) {
29238 _nativeNodeToDebugNode.delete(node.nativeNode);
29239}
29240/**
29241 * @publicApi
29242 */
29243const DebugNode = DebugNode__PRE_R3__;
29244/**
29245 * @publicApi
29246 */
29247const DebugElement = DebugElement__PRE_R3__;
29248
29249/**
29250 * @license
29251 * Copyright Google LLC All Rights Reserved.
29252 *
29253 * Use of this source code is governed by an MIT-style license that can be
29254 * found in the LICENSE file at https://angular.io/license
29255 */
29256
29257/**
29258 * @license
29259 * Copyright Google LLC All Rights Reserved.
29260 *
29261 * Use of this source code is governed by an MIT-style license that can be
29262 * found in the LICENSE file at https://angular.io/license
29263 */
29264const _CORE_PLATFORM_PROVIDERS = [
29265 // Set a default platform name for platforms that don't set it explicitly.
29266 { provide: PLATFORM_ID, useValue: 'unknown' },
29267 { provide: PlatformRef, deps: [Injector] },
29268 { provide: TestabilityRegistry, deps: [] },
29269 { provide: Console, deps: [] },
29270];
29271/**
29272 * This platform has to be included in any other platform
29273 *
29274 * @publicApi
29275 */
29276const platformCore = createPlatformFactory(null, 'core', _CORE_PLATFORM_PROVIDERS);
29277
29278/**
29279 * @license
29280 * Copyright Google LLC All Rights Reserved.
29281 *
29282 * Use of this source code is governed by an MIT-style license that can be
29283 * found in the LICENSE file at https://angular.io/license
29284 */
29285function _iterableDiffersFactory() {
29286 return defaultIterableDiffers;
29287}
29288function _keyValueDiffersFactory() {
29289 return defaultKeyValueDiffers;
29290}
29291function _localeFactory(locale) {
29292 locale = locale || getGlobalLocale();
29293 if (ivyEnabled) {
29294 setLocaleId(locale);
29295 }
29296 return locale;
29297}
29298/**
29299 * Work out the locale from the potential global properties.
29300 *
29301 * * Closure Compiler: use `goog.LOCALE`.
29302 * * Ivy enabled: use `$localize.locale`
29303 */
29304function getGlobalLocale() {
29305 if (typeof ngI18nClosureMode !== 'undefined' && ngI18nClosureMode &&
29306 typeof goog !== 'undefined' && goog.LOCALE !== 'en') {
29307 // * The default `goog.LOCALE` value is `en`, while Angular used `en-US`.
29308 // * In order to preserve backwards compatibility, we use Angular default value over
29309 // Closure Compiler's one.
29310 return goog.LOCALE;
29311 }
29312 else {
29313 // KEEP `typeof $localize !== 'undefined' && $localize.locale` IN SYNC WITH THE LOCALIZE
29314 // COMPILE-TIME INLINER.
29315 //
29316 // * During compile time inlining of translations the expression will be replaced
29317 // with a string literal that is the current locale. Other forms of this expression are not
29318 // guaranteed to be replaced.
29319 //
29320 // * During runtime translation evaluation, the developer is required to set `$localize.locale`
29321 // if required, or just to provide their own `LOCALE_ID` provider.
29322 return (ivyEnabled && typeof $localize !== 'undefined' && $localize.locale) ||
29323 DEFAULT_LOCALE_ID;
29324 }
29325}
29326const ɵ0$g = USD_CURRENCY_CODE;
29327/**
29328 * A built-in [dependency injection token](guide/glossary#di-token)
29329 * that is used to configure the root injector for bootstrapping.
29330 */
29331const APPLICATION_MODULE_PROVIDERS = [
29332 {
29333 provide: ApplicationRef,
29334 useClass: ApplicationRef,
29335 deps: [NgZone, Console, Injector, ErrorHandler, ComponentFactoryResolver, ApplicationInitStatus]
29336 },
29337 { provide: SCHEDULER, deps: [NgZone], useFactory: zoneSchedulerFactory },
29338 {
29339 provide: ApplicationInitStatus,
29340 useClass: ApplicationInitStatus,
29341 deps: [[new Optional(), APP_INITIALIZER]]
29342 },
29343 { provide: Compiler, useClass: Compiler, deps: [] },
29344 APP_ID_RANDOM_PROVIDER,
29345 { provide: IterableDiffers, useFactory: _iterableDiffersFactory, deps: [] },
29346 { provide: KeyValueDiffers, useFactory: _keyValueDiffersFactory, deps: [] },
29347 {
29348 provide: LOCALE_ID$1,
29349 useFactory: _localeFactory,
29350 deps: [[new Inject(LOCALE_ID$1), new Optional(), new SkipSelf()]]
29351 },
29352 { provide: DEFAULT_CURRENCY_CODE, useValue: ɵ0$g },
29353];
29354/**
29355 * Schedule work at next available slot.
29356 *
29357 * In Ivy this is just `requestAnimationFrame`. For compatibility reasons when bootstrapped
29358 * using `platformRef.bootstrap` we need to use `NgZone.onStable` as the scheduling mechanism.
29359 * This overrides the scheduling mechanism in Ivy to `NgZone.onStable`.
29360 *
29361 * @param ngZone NgZone to use for scheduling.
29362 */
29363function zoneSchedulerFactory(ngZone) {
29364 let queue = [];
29365 ngZone.onStable.subscribe(() => {
29366 while (queue.length) {
29367 queue.pop()();
29368 }
29369 });
29370 return function (fn) {
29371 queue.push(fn);
29372 };
29373}
29374/**
29375 * Configures the root injector for an app with
29376 * providers of `@angular/core` dependencies that `ApplicationRef` needs
29377 * to bootstrap components.
29378 *
29379 * Re-exported by `BrowserModule`, which is included automatically in the root
29380 * `AppModule` when you create a new app with the CLI `new` command.
29381 *
29382 * @publicApi
29383 */
29384class ApplicationModule {
29385 // Inject ApplicationRef to make it eager...
29386 constructor(appRef) { }
29387}
29388ApplicationModule.decorators = [
29389 { type: NgModule, args: [{ providers: APPLICATION_MODULE_PROVIDERS },] }
29390];
29391ApplicationModule.ctorParameters = () => [
29392 { type: ApplicationRef }
29393];
29394
29395/**
29396 * @license
29397 * Copyright Google LLC All Rights Reserved.
29398 *
29399 * Use of this source code is governed by an MIT-style license that can be
29400 * found in the LICENSE file at https://angular.io/license
29401 */
29402function anchorDef(flags, matchedQueriesDsl, ngContentIndex, childCount, handleEvent, templateFactory) {
29403 flags |= 1 /* TypeElement */;
29404 const { matchedQueries, references, matchedQueryIds } = splitMatchedQueriesDsl(matchedQueriesDsl);
29405 const template = templateFactory ? resolveDefinition(templateFactory) : null;
29406 return {
29407 // will bet set by the view definition
29408 nodeIndex: -1,
29409 parent: null,
29410 renderParent: null,
29411 bindingIndex: -1,
29412 outputIndex: -1,
29413 // regular values
29414 flags,
29415 checkIndex: -1,
29416 childFlags: 0,
29417 directChildFlags: 0,
29418 childMatchedQueries: 0,
29419 matchedQueries,
29420 matchedQueryIds,
29421 references,
29422 ngContentIndex,
29423 childCount,
29424 bindings: [],
29425 bindingFlags: 0,
29426 outputs: [],
29427 element: {
29428 ns: null,
29429 name: null,
29430 attrs: null,
29431 template,
29432 componentProvider: null,
29433 componentView: null,
29434 componentRendererType: null,
29435 publicProviders: null,
29436 allProviders: null,
29437 handleEvent: handleEvent || NOOP
29438 },
29439 provider: null,
29440 text: null,
29441 query: null,
29442 ngContent: null
29443 };
29444}
29445function elementDef(checkIndex, flags, matchedQueriesDsl, ngContentIndex, childCount, namespaceAndName, fixedAttrs = [], bindings, outputs, handleEvent, componentView, componentRendererType) {
29446 if (!handleEvent) {
29447 handleEvent = NOOP;
29448 }
29449 const { matchedQueries, references, matchedQueryIds } = splitMatchedQueriesDsl(matchedQueriesDsl);
29450 let ns = null;
29451 let name = null;
29452 if (namespaceAndName) {
29453 [ns, name] = splitNamespace(namespaceAndName);
29454 }
29455 bindings = bindings || [];
29456 const bindingDefs = [];
29457 for (let i = 0; i < bindings.length; i++) {
29458 const [bindingFlags, namespaceAndName, suffixOrSecurityContext] = bindings[i];
29459 const [ns, name] = splitNamespace(namespaceAndName);
29460 let securityContext = undefined;
29461 let suffix = undefined;
29462 switch (bindingFlags & 15 /* Types */) {
29463 case 4 /* TypeElementStyle */:
29464 suffix = suffixOrSecurityContext;
29465 break;
29466 case 1 /* TypeElementAttribute */:
29467 case 8 /* TypeProperty */:
29468 securityContext = suffixOrSecurityContext;
29469 break;
29470 }
29471 bindingDefs[i] =
29472 { flags: bindingFlags, ns, name, nonMinifiedName: name, securityContext, suffix };
29473 }
29474 outputs = outputs || [];
29475 const outputDefs = [];
29476 for (let i = 0; i < outputs.length; i++) {
29477 const [target, eventName] = outputs[i];
29478 outputDefs[i] =
29479 { type: 0 /* ElementOutput */, target: target, eventName, propName: null };
29480 }
29481 fixedAttrs = fixedAttrs || [];
29482 const attrs = fixedAttrs.map(([namespaceAndName, value]) => {
29483 const [ns, name] = splitNamespace(namespaceAndName);
29484 return [ns, name, value];
29485 });
29486 componentRendererType = resolveRendererType2(componentRendererType);
29487 if (componentView) {
29488 flags |= 33554432 /* ComponentView */;
29489 }
29490 flags |= 1 /* TypeElement */;
29491 return {
29492 // will bet set by the view definition
29493 nodeIndex: -1,
29494 parent: null,
29495 renderParent: null,
29496 bindingIndex: -1,
29497 outputIndex: -1,
29498 // regular values
29499 checkIndex,
29500 flags,
29501 childFlags: 0,
29502 directChildFlags: 0,
29503 childMatchedQueries: 0,
29504 matchedQueries,
29505 matchedQueryIds,
29506 references,
29507 ngContentIndex,
29508 childCount,
29509 bindings: bindingDefs,
29510 bindingFlags: calcBindingFlags(bindingDefs),
29511 outputs: outputDefs,
29512 element: {
29513 ns,
29514 name,
29515 attrs,
29516 template: null,
29517 // will bet set by the view definition
29518 componentProvider: null,
29519 componentView: componentView || null,
29520 componentRendererType: componentRendererType,
29521 publicProviders: null,
29522 allProviders: null,
29523 handleEvent: handleEvent || NOOP,
29524 },
29525 provider: null,
29526 text: null,
29527 query: null,
29528 ngContent: null
29529 };
29530}
29531function createElement(view, renderHost, def) {
29532 const elDef = def.element;
29533 const rootSelectorOrNode = view.root.selectorOrNode;
29534 const renderer = view.renderer;
29535 let el;
29536 if (view.parent || !rootSelectorOrNode) {
29537 if (elDef.name) {
29538 el = renderer.createElement(elDef.name, elDef.ns);
29539 }
29540 else {
29541 el = renderer.createComment('');
29542 }
29543 const parentEl = getParentRenderElement(view, renderHost, def);
29544 if (parentEl) {
29545 renderer.appendChild(parentEl, el);
29546 }
29547 }
29548 else {
29549 // when using native Shadow DOM, do not clear the root element contents to allow slot projection
29550 const preserveContent = (!!elDef.componentRendererType &&
29551 elDef.componentRendererType.encapsulation === ViewEncapsulation$1.ShadowDom);
29552 el = renderer.selectRootElement(rootSelectorOrNode, preserveContent);
29553 }
29554 if (elDef.attrs) {
29555 for (let i = 0; i < elDef.attrs.length; i++) {
29556 const [ns, name, value] = elDef.attrs[i];
29557 renderer.setAttribute(el, name, value, ns);
29558 }
29559 }
29560 return el;
29561}
29562function listenToElementOutputs(view, compView, def, el) {
29563 for (let i = 0; i < def.outputs.length; i++) {
29564 const output = def.outputs[i];
29565 const handleEventClosure = renderEventHandlerClosure(view, def.nodeIndex, elementEventFullName(output.target, output.eventName));
29566 let listenTarget = output.target;
29567 let listenerView = view;
29568 if (output.target === 'component') {
29569 listenTarget = null;
29570 listenerView = compView;
29571 }
29572 const disposable = listenerView.renderer.listen(listenTarget || el, output.eventName, handleEventClosure);
29573 view.disposables[def.outputIndex + i] = disposable;
29574 }
29575}
29576function renderEventHandlerClosure(view, index, eventName) {
29577 return (event) => dispatchEvent(view, index, eventName, event);
29578}
29579function checkAndUpdateElementInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
29580 const bindLen = def.bindings.length;
29581 let changed = false;
29582 if (bindLen > 0 && checkAndUpdateElementValue(view, def, 0, v0))
29583 changed = true;
29584 if (bindLen > 1 && checkAndUpdateElementValue(view, def, 1, v1))
29585 changed = true;
29586 if (bindLen > 2 && checkAndUpdateElementValue(view, def, 2, v2))
29587 changed = true;
29588 if (bindLen > 3 && checkAndUpdateElementValue(view, def, 3, v3))
29589 changed = true;
29590 if (bindLen > 4 && checkAndUpdateElementValue(view, def, 4, v4))
29591 changed = true;
29592 if (bindLen > 5 && checkAndUpdateElementValue(view, def, 5, v5))
29593 changed = true;
29594 if (bindLen > 6 && checkAndUpdateElementValue(view, def, 6, v6))
29595 changed = true;
29596 if (bindLen > 7 && checkAndUpdateElementValue(view, def, 7, v7))
29597 changed = true;
29598 if (bindLen > 8 && checkAndUpdateElementValue(view, def, 8, v8))
29599 changed = true;
29600 if (bindLen > 9 && checkAndUpdateElementValue(view, def, 9, v9))
29601 changed = true;
29602 return changed;
29603}
29604function checkAndUpdateElementDynamic(view, def, values) {
29605 let changed = false;
29606 for (let i = 0; i < values.length; i++) {
29607 if (checkAndUpdateElementValue(view, def, i, values[i]))
29608 changed = true;
29609 }
29610 return changed;
29611}
29612function checkAndUpdateElementValue(view, def, bindingIdx, value) {
29613 if (!checkAndUpdateBinding(view, def, bindingIdx, value)) {
29614 return false;
29615 }
29616 const binding = def.bindings[bindingIdx];
29617 const elData = asElementData(view, def.nodeIndex);
29618 const renderNode = elData.renderElement;
29619 const name = binding.name;
29620 switch (binding.flags & 15 /* Types */) {
29621 case 1 /* TypeElementAttribute */:
29622 setElementAttribute(view, binding, renderNode, binding.ns, name, value);
29623 break;
29624 case 2 /* TypeElementClass */:
29625 setElementClass(view, renderNode, name, value);
29626 break;
29627 case 4 /* TypeElementStyle */:
29628 setElementStyle(view, binding, renderNode, name, value);
29629 break;
29630 case 8 /* TypeProperty */:
29631 const bindView = (def.flags & 33554432 /* ComponentView */ &&
29632 binding.flags & 32 /* SyntheticHostProperty */) ?
29633 elData.componentView :
29634 view;
29635 setElementProperty(bindView, binding, renderNode, name, value);
29636 break;
29637 }
29638 return true;
29639}
29640function setElementAttribute(view, binding, renderNode, ns, name, value) {
29641 const securityContext = binding.securityContext;
29642 let renderValue = securityContext ? view.root.sanitizer.sanitize(securityContext, value) : value;
29643 renderValue = renderValue != null ? renderValue.toString() : null;
29644 const renderer = view.renderer;
29645 if (value != null) {
29646 renderer.setAttribute(renderNode, name, renderValue, ns);
29647 }
29648 else {
29649 renderer.removeAttribute(renderNode, name, ns);
29650 }
29651}
29652function setElementClass(view, renderNode, name, value) {
29653 const renderer = view.renderer;
29654 if (value) {
29655 renderer.addClass(renderNode, name);
29656 }
29657 else {
29658 renderer.removeClass(renderNode, name);
29659 }
29660}
29661function setElementStyle(view, binding, renderNode, name, value) {
29662 let renderValue = view.root.sanitizer.sanitize(SecurityContext.STYLE, value);
29663 if (renderValue != null) {
29664 renderValue = renderValue.toString();
29665 const unit = binding.suffix;
29666 if (unit != null) {
29667 renderValue = renderValue + unit;
29668 }
29669 }
29670 else {
29671 renderValue = null;
29672 }
29673 const renderer = view.renderer;
29674 if (renderValue != null) {
29675 renderer.setStyle(renderNode, name, renderValue);
29676 }
29677 else {
29678 renderer.removeStyle(renderNode, name);
29679 }
29680}
29681function setElementProperty(view, binding, renderNode, name, value) {
29682 const securityContext = binding.securityContext;
29683 let renderValue = securityContext ? view.root.sanitizer.sanitize(securityContext, value) : value;
29684 view.renderer.setProperty(renderNode, name, renderValue);
29685}
29686
29687/**
29688 * @license
29689 * Copyright Google LLC All Rights Reserved.
29690 *
29691 * Use of this source code is governed by an MIT-style license that can be
29692 * found in the LICENSE file at https://angular.io/license
29693 */
29694function queryDef(flags, id, bindings) {
29695 let bindingDefs = [];
29696 for (let propName in bindings) {
29697 const bindingType = bindings[propName];
29698 bindingDefs.push({ propName, bindingType });
29699 }
29700 return {
29701 // will bet set by the view definition
29702 nodeIndex: -1,
29703 parent: null,
29704 renderParent: null,
29705 bindingIndex: -1,
29706 outputIndex: -1,
29707 // regular values
29708 // TODO(vicb): check
29709 checkIndex: -1,
29710 flags,
29711 childFlags: 0,
29712 directChildFlags: 0,
29713 childMatchedQueries: 0,
29714 ngContentIndex: -1,
29715 matchedQueries: {},
29716 matchedQueryIds: 0,
29717 references: {},
29718 childCount: 0,
29719 bindings: [],
29720 bindingFlags: 0,
29721 outputs: [],
29722 element: null,
29723 provider: null,
29724 text: null,
29725 query: { id, filterId: filterQueryId(id), bindings: bindingDefs },
29726 ngContent: null
29727 };
29728}
29729function createQuery() {
29730 return new QueryList();
29731}
29732function dirtyParentQueries(view) {
29733 const queryIds = view.def.nodeMatchedQueries;
29734 while (view.parent && isEmbeddedView(view)) {
29735 let tplDef = view.parentNodeDef;
29736 view = view.parent;
29737 // content queries
29738 const end = tplDef.nodeIndex + tplDef.childCount;
29739 for (let i = 0; i <= end; i++) {
29740 const nodeDef = view.def.nodes[i];
29741 if ((nodeDef.flags & 67108864 /* TypeContentQuery */) &&
29742 (nodeDef.flags & 536870912 /* DynamicQuery */) &&
29743 (nodeDef.query.filterId & queryIds) === nodeDef.query.filterId) {
29744 asQueryList(view, i).setDirty();
29745 }
29746 if ((nodeDef.flags & 1 /* TypeElement */ && i + nodeDef.childCount < tplDef.nodeIndex) ||
29747 !(nodeDef.childFlags & 67108864 /* TypeContentQuery */) ||
29748 !(nodeDef.childFlags & 536870912 /* DynamicQuery */)) {
29749 // skip elements that don't contain the template element or no query.
29750 i += nodeDef.childCount;
29751 }
29752 }
29753 }
29754 // view queries
29755 if (view.def.nodeFlags & 134217728 /* TypeViewQuery */) {
29756 for (let i = 0; i < view.def.nodes.length; i++) {
29757 const nodeDef = view.def.nodes[i];
29758 if ((nodeDef.flags & 134217728 /* TypeViewQuery */) && (nodeDef.flags & 536870912 /* DynamicQuery */)) {
29759 asQueryList(view, i).setDirty();
29760 }
29761 // only visit the root nodes
29762 i += nodeDef.childCount;
29763 }
29764 }
29765}
29766function checkAndUpdateQuery(view, nodeDef) {
29767 const queryList = asQueryList(view, nodeDef.nodeIndex);
29768 if (!queryList.dirty) {
29769 return;
29770 }
29771 let directiveInstance;
29772 let newValues = undefined;
29773 if (nodeDef.flags & 67108864 /* TypeContentQuery */) {
29774 const elementDef = nodeDef.parent.parent;
29775 newValues = calcQueryValues(view, elementDef.nodeIndex, elementDef.nodeIndex + elementDef.childCount, nodeDef.query, []);
29776 directiveInstance = asProviderData(view, nodeDef.parent.nodeIndex).instance;
29777 }
29778 else if (nodeDef.flags & 134217728 /* TypeViewQuery */) {
29779 newValues = calcQueryValues(view, 0, view.def.nodes.length - 1, nodeDef.query, []);
29780 directiveInstance = view.component;
29781 }
29782 queryList.reset(newValues);
29783 const bindings = nodeDef.query.bindings;
29784 let notify = false;
29785 for (let i = 0; i < bindings.length; i++) {
29786 const binding = bindings[i];
29787 let boundValue;
29788 switch (binding.bindingType) {
29789 case 0 /* First */:
29790 boundValue = queryList.first;
29791 break;
29792 case 1 /* All */:
29793 boundValue = queryList;
29794 notify = true;
29795 break;
29796 }
29797 directiveInstance[binding.propName] = boundValue;
29798 }
29799 if (notify) {
29800 queryList.notifyOnChanges();
29801 }
29802}
29803function calcQueryValues(view, startIndex, endIndex, queryDef, values) {
29804 for (let i = startIndex; i <= endIndex; i++) {
29805 const nodeDef = view.def.nodes[i];
29806 const valueType = nodeDef.matchedQueries[queryDef.id];
29807 if (valueType != null) {
29808 values.push(getQueryValue(view, nodeDef, valueType));
29809 }
29810 if (nodeDef.flags & 1 /* TypeElement */ && nodeDef.element.template &&
29811 (nodeDef.element.template.nodeMatchedQueries & queryDef.filterId) ===
29812 queryDef.filterId) {
29813 const elementData = asElementData(view, i);
29814 // check embedded views that were attached at the place of their template,
29815 // but process child nodes first if some match the query (see issue #16568)
29816 if ((nodeDef.childMatchedQueries & queryDef.filterId) === queryDef.filterId) {
29817 calcQueryValues(view, i + 1, i + nodeDef.childCount, queryDef, values);
29818 i += nodeDef.childCount;
29819 }
29820 if (nodeDef.flags & 16777216 /* EmbeddedViews */) {
29821 const embeddedViews = elementData.viewContainer._embeddedViews;
29822 for (let k = 0; k < embeddedViews.length; k++) {
29823 const embeddedView = embeddedViews[k];
29824 const dvc = declaredViewContainer(embeddedView);
29825 if (dvc && dvc === elementData) {
29826 calcQueryValues(embeddedView, 0, embeddedView.def.nodes.length - 1, queryDef, values);
29827 }
29828 }
29829 }
29830 const projectedViews = elementData.template._projectedViews;
29831 if (projectedViews) {
29832 for (let k = 0; k < projectedViews.length; k++) {
29833 const projectedView = projectedViews[k];
29834 calcQueryValues(projectedView, 0, projectedView.def.nodes.length - 1, queryDef, values);
29835 }
29836 }
29837 }
29838 if ((nodeDef.childMatchedQueries & queryDef.filterId) !== queryDef.filterId) {
29839 // if no child matches the query, skip the children.
29840 i += nodeDef.childCount;
29841 }
29842 }
29843 return values;
29844}
29845function getQueryValue(view, nodeDef, queryValueType) {
29846 if (queryValueType != null) {
29847 // a match
29848 switch (queryValueType) {
29849 case 1 /* RenderElement */:
29850 return asElementData(view, nodeDef.nodeIndex).renderElement;
29851 case 0 /* ElementRef */:
29852 return new ElementRef(asElementData(view, nodeDef.nodeIndex).renderElement);
29853 case 2 /* TemplateRef */:
29854 return asElementData(view, nodeDef.nodeIndex).template;
29855 case 3 /* ViewContainerRef */:
29856 return asElementData(view, nodeDef.nodeIndex).viewContainer;
29857 case 4 /* Provider */:
29858 return asProviderData(view, nodeDef.nodeIndex).instance;
29859 }
29860 }
29861}
29862
29863/**
29864 * @license
29865 * Copyright Google LLC All Rights Reserved.
29866 *
29867 * Use of this source code is governed by an MIT-style license that can be
29868 * found in the LICENSE file at https://angular.io/license
29869 */
29870function ngContentDef(ngContentIndex, index) {
29871 return {
29872 // will bet set by the view definition
29873 nodeIndex: -1,
29874 parent: null,
29875 renderParent: null,
29876 bindingIndex: -1,
29877 outputIndex: -1,
29878 // regular values
29879 checkIndex: -1,
29880 flags: 8 /* TypeNgContent */,
29881 childFlags: 0,
29882 directChildFlags: 0,
29883 childMatchedQueries: 0,
29884 matchedQueries: {},
29885 matchedQueryIds: 0,
29886 references: {},
29887 ngContentIndex,
29888 childCount: 0,
29889 bindings: [],
29890 bindingFlags: 0,
29891 outputs: [],
29892 element: null,
29893 provider: null,
29894 text: null,
29895 query: null,
29896 ngContent: { index }
29897 };
29898}
29899function appendNgContent(view, renderHost, def) {
29900 const parentEl = getParentRenderElement(view, renderHost, def);
29901 if (!parentEl) {
29902 // Nothing to do if there is no parent element.
29903 return;
29904 }
29905 const ngContentIndex = def.ngContent.index;
29906 visitProjectedRenderNodes(view, ngContentIndex, 1 /* AppendChild */, parentEl, null, undefined);
29907}
29908
29909/**
29910 * @license
29911 * Copyright Google LLC All Rights Reserved.
29912 *
29913 * Use of this source code is governed by an MIT-style license that can be
29914 * found in the LICENSE file at https://angular.io/license
29915 */
29916function purePipeDef(checkIndex, argCount) {
29917 // argCount + 1 to include the pipe as first arg
29918 return _pureExpressionDef(128 /* TypePurePipe */, checkIndex, newArray(argCount + 1));
29919}
29920function pureArrayDef(checkIndex, argCount) {
29921 return _pureExpressionDef(32 /* TypePureArray */, checkIndex, newArray(argCount));
29922}
29923function pureObjectDef(checkIndex, propToIndex) {
29924 const keys = Object.keys(propToIndex);
29925 const nbKeys = keys.length;
29926 const propertyNames = [];
29927 for (let i = 0; i < nbKeys; i++) {
29928 const key = keys[i];
29929 const index = propToIndex[key];
29930 propertyNames.push(key);
29931 }
29932 return _pureExpressionDef(64 /* TypePureObject */, checkIndex, propertyNames);
29933}
29934function _pureExpressionDef(flags, checkIndex, propertyNames) {
29935 const bindings = [];
29936 for (let i = 0; i < propertyNames.length; i++) {
29937 const prop = propertyNames[i];
29938 bindings.push({
29939 flags: 8 /* TypeProperty */,
29940 name: prop,
29941 ns: null,
29942 nonMinifiedName: prop,
29943 securityContext: null,
29944 suffix: null
29945 });
29946 }
29947 return {
29948 // will bet set by the view definition
29949 nodeIndex: -1,
29950 parent: null,
29951 renderParent: null,
29952 bindingIndex: -1,
29953 outputIndex: -1,
29954 // regular values
29955 checkIndex,
29956 flags,
29957 childFlags: 0,
29958 directChildFlags: 0,
29959 childMatchedQueries: 0,
29960 matchedQueries: {},
29961 matchedQueryIds: 0,
29962 references: {},
29963 ngContentIndex: -1,
29964 childCount: 0,
29965 bindings,
29966 bindingFlags: calcBindingFlags(bindings),
29967 outputs: [],
29968 element: null,
29969 provider: null,
29970 text: null,
29971 query: null,
29972 ngContent: null
29973 };
29974}
29975function createPureExpression(view, def) {
29976 return { value: undefined };
29977}
29978function checkAndUpdatePureExpressionInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
29979 const bindings = def.bindings;
29980 let changed = false;
29981 const bindLen = bindings.length;
29982 if (bindLen > 0 && checkAndUpdateBinding(view, def, 0, v0))
29983 changed = true;
29984 if (bindLen > 1 && checkAndUpdateBinding(view, def, 1, v1))
29985 changed = true;
29986 if (bindLen > 2 && checkAndUpdateBinding(view, def, 2, v2))
29987 changed = true;
29988 if (bindLen > 3 && checkAndUpdateBinding(view, def, 3, v3))
29989 changed = true;
29990 if (bindLen > 4 && checkAndUpdateBinding(view, def, 4, v4))
29991 changed = true;
29992 if (bindLen > 5 && checkAndUpdateBinding(view, def, 5, v5))
29993 changed = true;
29994 if (bindLen > 6 && checkAndUpdateBinding(view, def, 6, v6))
29995 changed = true;
29996 if (bindLen > 7 && checkAndUpdateBinding(view, def, 7, v7))
29997 changed = true;
29998 if (bindLen > 8 && checkAndUpdateBinding(view, def, 8, v8))
29999 changed = true;
30000 if (bindLen > 9 && checkAndUpdateBinding(view, def, 9, v9))
30001 changed = true;
30002 if (changed) {
30003 const data = asPureExpressionData(view, def.nodeIndex);
30004 let value;
30005 switch (def.flags & 201347067 /* Types */) {
30006 case 32 /* TypePureArray */:
30007 value = [];
30008 if (bindLen > 0)
30009 value.push(v0);
30010 if (bindLen > 1)
30011 value.push(v1);
30012 if (bindLen > 2)
30013 value.push(v2);
30014 if (bindLen > 3)
30015 value.push(v3);
30016 if (bindLen > 4)
30017 value.push(v4);
30018 if (bindLen > 5)
30019 value.push(v5);
30020 if (bindLen > 6)
30021 value.push(v6);
30022 if (bindLen > 7)
30023 value.push(v7);
30024 if (bindLen > 8)
30025 value.push(v8);
30026 if (bindLen > 9)
30027 value.push(v9);
30028 break;
30029 case 64 /* TypePureObject */:
30030 value = {};
30031 if (bindLen > 0)
30032 value[bindings[0].name] = v0;
30033 if (bindLen > 1)
30034 value[bindings[1].name] = v1;
30035 if (bindLen > 2)
30036 value[bindings[2].name] = v2;
30037 if (bindLen > 3)
30038 value[bindings[3].name] = v3;
30039 if (bindLen > 4)
30040 value[bindings[4].name] = v4;
30041 if (bindLen > 5)
30042 value[bindings[5].name] = v5;
30043 if (bindLen > 6)
30044 value[bindings[6].name] = v6;
30045 if (bindLen > 7)
30046 value[bindings[7].name] = v7;
30047 if (bindLen > 8)
30048 value[bindings[8].name] = v8;
30049 if (bindLen > 9)
30050 value[bindings[9].name] = v9;
30051 break;
30052 case 128 /* TypePurePipe */:
30053 const pipe = v0;
30054 switch (bindLen) {
30055 case 1:
30056 value = pipe.transform(v0);
30057 break;
30058 case 2:
30059 value = pipe.transform(v1);
30060 break;
30061 case 3:
30062 value = pipe.transform(v1, v2);
30063 break;
30064 case 4:
30065 value = pipe.transform(v1, v2, v3);
30066 break;
30067 case 5:
30068 value = pipe.transform(v1, v2, v3, v4);
30069 break;
30070 case 6:
30071 value = pipe.transform(v1, v2, v3, v4, v5);
30072 break;
30073 case 7:
30074 value = pipe.transform(v1, v2, v3, v4, v5, v6);
30075 break;
30076 case 8:
30077 value = pipe.transform(v1, v2, v3, v4, v5, v6, v7);
30078 break;
30079 case 9:
30080 value = pipe.transform(v1, v2, v3, v4, v5, v6, v7, v8);
30081 break;
30082 case 10:
30083 value = pipe.transform(v1, v2, v3, v4, v5, v6, v7, v8, v9);
30084 break;
30085 }
30086 break;
30087 }
30088 data.value = value;
30089 }
30090 return changed;
30091}
30092function checkAndUpdatePureExpressionDynamic(view, def, values) {
30093 const bindings = def.bindings;
30094 let changed = false;
30095 for (let i = 0; i < values.length; i++) {
30096 // Note: We need to loop over all values, so that
30097 // the old values are updates as well!
30098 if (checkAndUpdateBinding(view, def, i, values[i])) {
30099 changed = true;
30100 }
30101 }
30102 if (changed) {
30103 const data = asPureExpressionData(view, def.nodeIndex);
30104 let value;
30105 switch (def.flags & 201347067 /* Types */) {
30106 case 32 /* TypePureArray */:
30107 value = values;
30108 break;
30109 case 64 /* TypePureObject */:
30110 value = {};
30111 for (let i = 0; i < values.length; i++) {
30112 value[bindings[i].name] = values[i];
30113 }
30114 break;
30115 case 128 /* TypePurePipe */:
30116 const pipe = values[0];
30117 const params = values.slice(1);
30118 value = pipe.transform(...params);
30119 break;
30120 }
30121 data.value = value;
30122 }
30123 return changed;
30124}
30125
30126/**
30127 * @license
30128 * Copyright Google LLC All Rights Reserved.
30129 *
30130 * Use of this source code is governed by an MIT-style license that can be
30131 * found in the LICENSE file at https://angular.io/license
30132 */
30133function textDef(checkIndex, ngContentIndex, staticText) {
30134 const bindings = [];
30135 for (let i = 1; i < staticText.length; i++) {
30136 bindings[i - 1] = {
30137 flags: 8 /* TypeProperty */,
30138 name: null,
30139 ns: null,
30140 nonMinifiedName: null,
30141 securityContext: null,
30142 suffix: staticText[i],
30143 };
30144 }
30145 return {
30146 // will bet set by the view definition
30147 nodeIndex: -1,
30148 parent: null,
30149 renderParent: null,
30150 bindingIndex: -1,
30151 outputIndex: -1,
30152 // regular values
30153 checkIndex,
30154 flags: 2 /* TypeText */,
30155 childFlags: 0,
30156 directChildFlags: 0,
30157 childMatchedQueries: 0,
30158 matchedQueries: {},
30159 matchedQueryIds: 0,
30160 references: {},
30161 ngContentIndex,
30162 childCount: 0,
30163 bindings,
30164 bindingFlags: 8 /* TypeProperty */,
30165 outputs: [],
30166 element: null,
30167 provider: null,
30168 text: { prefix: staticText[0] },
30169 query: null,
30170 ngContent: null,
30171 };
30172}
30173function createText(view, renderHost, def) {
30174 let renderNode;
30175 const renderer = view.renderer;
30176 renderNode = renderer.createText(def.text.prefix);
30177 const parentEl = getParentRenderElement(view, renderHost, def);
30178 if (parentEl) {
30179 renderer.appendChild(parentEl, renderNode);
30180 }
30181 return { renderText: renderNode };
30182}
30183function checkAndUpdateTextInline(view, def, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
30184 let changed = false;
30185 const bindings = def.bindings;
30186 const bindLen = bindings.length;
30187 if (bindLen > 0 && checkAndUpdateBinding(view, def, 0, v0))
30188 changed = true;
30189 if (bindLen > 1 && checkAndUpdateBinding(view, def, 1, v1))
30190 changed = true;
30191 if (bindLen > 2 && checkAndUpdateBinding(view, def, 2, v2))
30192 changed = true;
30193 if (bindLen > 3 && checkAndUpdateBinding(view, def, 3, v3))
30194 changed = true;
30195 if (bindLen > 4 && checkAndUpdateBinding(view, def, 4, v4))
30196 changed = true;
30197 if (bindLen > 5 && checkAndUpdateBinding(view, def, 5, v5))
30198 changed = true;
30199 if (bindLen > 6 && checkAndUpdateBinding(view, def, 6, v6))
30200 changed = true;
30201 if (bindLen > 7 && checkAndUpdateBinding(view, def, 7, v7))
30202 changed = true;
30203 if (bindLen > 8 && checkAndUpdateBinding(view, def, 8, v8))
30204 changed = true;
30205 if (bindLen > 9 && checkAndUpdateBinding(view, def, 9, v9))
30206 changed = true;
30207 if (changed) {
30208 let value = def.text.prefix;
30209 if (bindLen > 0)
30210 value += _addInterpolationPart(v0, bindings[0]);
30211 if (bindLen > 1)
30212 value += _addInterpolationPart(v1, bindings[1]);
30213 if (bindLen > 2)
30214 value += _addInterpolationPart(v2, bindings[2]);
30215 if (bindLen > 3)
30216 value += _addInterpolationPart(v3, bindings[3]);
30217 if (bindLen > 4)
30218 value += _addInterpolationPart(v4, bindings[4]);
30219 if (bindLen > 5)
30220 value += _addInterpolationPart(v5, bindings[5]);
30221 if (bindLen > 6)
30222 value += _addInterpolationPart(v6, bindings[6]);
30223 if (bindLen > 7)
30224 value += _addInterpolationPart(v7, bindings[7]);
30225 if (bindLen > 8)
30226 value += _addInterpolationPart(v8, bindings[8]);
30227 if (bindLen > 9)
30228 value += _addInterpolationPart(v9, bindings[9]);
30229 const renderNode = asTextData(view, def.nodeIndex).renderText;
30230 view.renderer.setValue(renderNode, value);
30231 }
30232 return changed;
30233}
30234function checkAndUpdateTextDynamic(view, def, values) {
30235 const bindings = def.bindings;
30236 let changed = false;
30237 for (let i = 0; i < values.length; i++) {
30238 // Note: We need to loop over all values, so that
30239 // the old values are updates as well!
30240 if (checkAndUpdateBinding(view, def, i, values[i])) {
30241 changed = true;
30242 }
30243 }
30244 if (changed) {
30245 let value = '';
30246 for (let i = 0; i < values.length; i++) {
30247 value = value + _addInterpolationPart(values[i], bindings[i]);
30248 }
30249 value = def.text.prefix + value;
30250 const renderNode = asTextData(view, def.nodeIndex).renderText;
30251 view.renderer.setValue(renderNode, value);
30252 }
30253 return changed;
30254}
30255function _addInterpolationPart(value, binding) {
30256 const valueStr = value != null ? value.toString() : '';
30257 return valueStr + binding.suffix;
30258}
30259
30260/**
30261 * @license
30262 * Copyright Google LLC All Rights Reserved.
30263 *
30264 * Use of this source code is governed by an MIT-style license that can be
30265 * found in the LICENSE file at https://angular.io/license
30266 */
30267function viewDef(flags, nodes, updateDirectives, updateRenderer) {
30268 // clone nodes and set auto calculated values
30269 let viewBindingCount = 0;
30270 let viewDisposableCount = 0;
30271 let viewNodeFlags = 0;
30272 let viewRootNodeFlags = 0;
30273 let viewMatchedQueries = 0;
30274 let currentParent = null;
30275 let currentRenderParent = null;
30276 let currentElementHasPublicProviders = false;
30277 let currentElementHasPrivateProviders = false;
30278 let lastRenderRootNode = null;
30279 for (let i = 0; i < nodes.length; i++) {
30280 const node = nodes[i];
30281 node.nodeIndex = i;
30282 node.parent = currentParent;
30283 node.bindingIndex = viewBindingCount;
30284 node.outputIndex = viewDisposableCount;
30285 node.renderParent = currentRenderParent;
30286 viewNodeFlags |= node.flags;
30287 viewMatchedQueries |= node.matchedQueryIds;
30288 if (node.element) {
30289 const elDef = node.element;
30290 elDef.publicProviders =
30291 currentParent ? currentParent.element.publicProviders : Object.create(null);
30292 elDef.allProviders = elDef.publicProviders;
30293 // Note: We assume that all providers of an element are before any child element!
30294 currentElementHasPublicProviders = false;
30295 currentElementHasPrivateProviders = false;
30296 if (node.element.template) {
30297 viewMatchedQueries |= node.element.template.nodeMatchedQueries;
30298 }
30299 }
30300 validateNode(currentParent, node, nodes.length);
30301 viewBindingCount += node.bindings.length;
30302 viewDisposableCount += node.outputs.length;
30303 if (!currentRenderParent && (node.flags & 3 /* CatRenderNode */)) {
30304 lastRenderRootNode = node;
30305 }
30306 if (node.flags & 20224 /* CatProvider */) {
30307 if (!currentElementHasPublicProviders) {
30308 currentElementHasPublicProviders = true;
30309 // Use prototypical inheritance to not get O(n^2) complexity...
30310 currentParent.element.publicProviders =
30311 Object.create(currentParent.element.publicProviders);
30312 currentParent.element.allProviders = currentParent.element.publicProviders;
30313 }
30314 const isPrivateService = (node.flags & 8192 /* PrivateProvider */) !== 0;
30315 const isComponent = (node.flags & 32768 /* Component */) !== 0;
30316 if (!isPrivateService || isComponent) {
30317 currentParent.element.publicProviders[tokenKey(node.provider.token)] = node;
30318 }
30319 else {
30320 if (!currentElementHasPrivateProviders) {
30321 currentElementHasPrivateProviders = true;
30322 // Use prototypical inheritance to not get O(n^2) complexity...
30323 currentParent.element.allProviders =
30324 Object.create(currentParent.element.publicProviders);
30325 }
30326 currentParent.element.allProviders[tokenKey(node.provider.token)] = node;
30327 }
30328 if (isComponent) {
30329 currentParent.element.componentProvider = node;
30330 }
30331 }
30332 if (currentParent) {
30333 currentParent.childFlags |= node.flags;
30334 currentParent.directChildFlags |= node.flags;
30335 currentParent.childMatchedQueries |= node.matchedQueryIds;
30336 if (node.element && node.element.template) {
30337 currentParent.childMatchedQueries |= node.element.template.nodeMatchedQueries;
30338 }
30339 }
30340 else {
30341 viewRootNodeFlags |= node.flags;
30342 }
30343 if (node.childCount > 0) {
30344 currentParent = node;
30345 if (!isNgContainer(node)) {
30346 currentRenderParent = node;
30347 }
30348 }
30349 else {
30350 // When the current node has no children, check if it is the last children of its parent.
30351 // When it is, propagate the flags up.
30352 // The loop is required because an element could be the last transitive children of several
30353 // elements. We loop to either the root or the highest opened element (= with remaining
30354 // children)
30355 while (currentParent && i === currentParent.nodeIndex + currentParent.childCount) {
30356 const newParent = currentParent.parent;
30357 if (newParent) {
30358 newParent.childFlags |= currentParent.childFlags;
30359 newParent.childMatchedQueries |= currentParent.childMatchedQueries;
30360 }
30361 currentParent = newParent;
30362 // We also need to update the render parent & account for ng-container
30363 if (currentParent && isNgContainer(currentParent)) {
30364 currentRenderParent = currentParent.renderParent;
30365 }
30366 else {
30367 currentRenderParent = currentParent;
30368 }
30369 }
30370 }
30371 }
30372 const handleEvent = (view, nodeIndex, eventName, event) => nodes[nodeIndex].element.handleEvent(view, eventName, event);
30373 return {
30374 // Will be filled later...
30375 factory: null,
30376 nodeFlags: viewNodeFlags,
30377 rootNodeFlags: viewRootNodeFlags,
30378 nodeMatchedQueries: viewMatchedQueries,
30379 flags,
30380 nodes: nodes,
30381 updateDirectives: updateDirectives || NOOP,
30382 updateRenderer: updateRenderer || NOOP,
30383 handleEvent,
30384 bindingCount: viewBindingCount,
30385 outputCount: viewDisposableCount,
30386 lastRenderRootNode
30387 };
30388}
30389function isNgContainer(node) {
30390 return (node.flags & 1 /* TypeElement */) !== 0 && node.element.name === null;
30391}
30392function validateNode(parent, node, nodeCount) {
30393 const template = node.element && node.element.template;
30394 if (template) {
30395 if (!template.lastRenderRootNode) {
30396 throw new Error(`Illegal State: Embedded templates without nodes are not allowed!`);
30397 }
30398 if (template.lastRenderRootNode &&
30399 template.lastRenderRootNode.flags & 16777216 /* EmbeddedViews */) {
30400 throw new Error(`Illegal State: Last root node of a template can't have embedded views, at index ${node.nodeIndex}!`);
30401 }
30402 }
30403 if (node.flags & 20224 /* CatProvider */) {
30404 const parentFlags = parent ? parent.flags : 0;
30405 if ((parentFlags & 1 /* TypeElement */) === 0) {
30406 throw new Error(`Illegal State: StaticProvider/Directive nodes need to be children of elements or anchors, at index ${node.nodeIndex}!`);
30407 }
30408 }
30409 if (node.query) {
30410 if (node.flags & 67108864 /* TypeContentQuery */ &&
30411 (!parent || (parent.flags & 16384 /* TypeDirective */) === 0)) {
30412 throw new Error(`Illegal State: Content Query nodes need to be children of directives, at index ${node.nodeIndex}!`);
30413 }
30414 if (node.flags & 134217728 /* TypeViewQuery */ && parent) {
30415 throw new Error(`Illegal State: View Query nodes have to be top level nodes, at index ${node.nodeIndex}!`);
30416 }
30417 }
30418 if (node.childCount) {
30419 const parentEnd = parent ? parent.nodeIndex + parent.childCount : nodeCount - 1;
30420 if (node.nodeIndex <= parentEnd && node.nodeIndex + node.childCount > parentEnd) {
30421 throw new Error(`Illegal State: childCount of node leads outside of parent, at index ${node.nodeIndex}!`);
30422 }
30423 }
30424}
30425function createEmbeddedView(parent, anchorDef, viewDef, context) {
30426 // embedded views are seen as siblings to the anchor, so we need
30427 // to get the parent of the anchor and use it as parentIndex.
30428 const view = createView(parent.root, parent.renderer, parent, anchorDef, viewDef);
30429 initView(view, parent.component, context);
30430 createViewNodes(view);
30431 return view;
30432}
30433function createRootView(root, def, context) {
30434 const view = createView(root, root.renderer, null, null, def);
30435 initView(view, context, context);
30436 createViewNodes(view);
30437 return view;
30438}
30439function createComponentView(parentView, nodeDef, viewDef, hostElement) {
30440 const rendererType = nodeDef.element.componentRendererType;
30441 let compRenderer;
30442 if (!rendererType) {
30443 compRenderer = parentView.root.renderer;
30444 }
30445 else {
30446 compRenderer = parentView.root.rendererFactory.createRenderer(hostElement, rendererType);
30447 }
30448 return createView(parentView.root, compRenderer, parentView, nodeDef.element.componentProvider, viewDef);
30449}
30450function createView(root, renderer, parent, parentNodeDef, def) {
30451 const nodes = new Array(def.nodes.length);
30452 const disposables = def.outputCount ? new Array(def.outputCount) : null;
30453 const view = {
30454 def,
30455 parent,
30456 viewContainerParent: null,
30457 parentNodeDef,
30458 context: null,
30459 component: null,
30460 nodes,
30461 state: 13 /* CatInit */,
30462 root,
30463 renderer,
30464 oldValues: new Array(def.bindingCount),
30465 disposables,
30466 initIndex: -1
30467 };
30468 return view;
30469}
30470function initView(view, component, context) {
30471 view.component = component;
30472 view.context = context;
30473}
30474function createViewNodes(view) {
30475 let renderHost;
30476 if (isComponentView(view)) {
30477 const hostDef = view.parentNodeDef;
30478 renderHost = asElementData(view.parent, hostDef.parent.nodeIndex).renderElement;
30479 }
30480 const def = view.def;
30481 const nodes = view.nodes;
30482 for (let i = 0; i < def.nodes.length; i++) {
30483 const nodeDef = def.nodes[i];
30484 Services.setCurrentNode(view, i);
30485 let nodeData;
30486 switch (nodeDef.flags & 201347067 /* Types */) {
30487 case 1 /* TypeElement */:
30488 const el = createElement(view, renderHost, nodeDef);
30489 let componentView = undefined;
30490 if (nodeDef.flags & 33554432 /* ComponentView */) {
30491 const compViewDef = resolveDefinition(nodeDef.element.componentView);
30492 componentView = Services.createComponentView(view, nodeDef, compViewDef, el);
30493 }
30494 listenToElementOutputs(view, componentView, nodeDef, el);
30495 nodeData = {
30496 renderElement: el,
30497 componentView,
30498 viewContainer: null,
30499 template: nodeDef.element.template ? createTemplateData(view, nodeDef) : undefined
30500 };
30501 if (nodeDef.flags & 16777216 /* EmbeddedViews */) {
30502 nodeData.viewContainer = createViewContainerData(view, nodeDef, nodeData);
30503 }
30504 break;
30505 case 2 /* TypeText */:
30506 nodeData = createText(view, renderHost, nodeDef);
30507 break;
30508 case 512 /* TypeClassProvider */:
30509 case 1024 /* TypeFactoryProvider */:
30510 case 2048 /* TypeUseExistingProvider */:
30511 case 256 /* TypeValueProvider */: {
30512 nodeData = nodes[i];
30513 if (!nodeData && !(nodeDef.flags & 4096 /* LazyProvider */)) {
30514 const instance = createProviderInstance(view, nodeDef);
30515 nodeData = { instance };
30516 }
30517 break;
30518 }
30519 case 16 /* TypePipe */: {
30520 const instance = createPipeInstance(view, nodeDef);
30521 nodeData = { instance };
30522 break;
30523 }
30524 case 16384 /* TypeDirective */: {
30525 nodeData = nodes[i];
30526 if (!nodeData) {
30527 const instance = createDirectiveInstance(view, nodeDef);
30528 nodeData = { instance };
30529 }
30530 if (nodeDef.flags & 32768 /* Component */) {
30531 const compView = asElementData(view, nodeDef.parent.nodeIndex).componentView;
30532 initView(compView, nodeData.instance, nodeData.instance);
30533 }
30534 break;
30535 }
30536 case 32 /* TypePureArray */:
30537 case 64 /* TypePureObject */:
30538 case 128 /* TypePurePipe */:
30539 nodeData = createPureExpression(view, nodeDef);
30540 break;
30541 case 67108864 /* TypeContentQuery */:
30542 case 134217728 /* TypeViewQuery */:
30543 nodeData = createQuery();
30544 break;
30545 case 8 /* TypeNgContent */:
30546 appendNgContent(view, renderHost, nodeDef);
30547 // no runtime data needed for NgContent...
30548 nodeData = undefined;
30549 break;
30550 }
30551 nodes[i] = nodeData;
30552 }
30553 // Create the ViewData.nodes of component views after we created everything else,
30554 // so that e.g. ng-content works
30555 execComponentViewsAction(view, ViewAction.CreateViewNodes);
30556 // fill static content and view queries
30557 execQueriesAction(view, 67108864 /* TypeContentQuery */ | 134217728 /* TypeViewQuery */, 268435456 /* StaticQuery */, 0 /* CheckAndUpdate */);
30558}
30559function checkNoChangesView(view) {
30560 markProjectedViewsForCheck(view);
30561 Services.updateDirectives(view, 1 /* CheckNoChanges */);
30562 execEmbeddedViewsAction(view, ViewAction.CheckNoChanges);
30563 Services.updateRenderer(view, 1 /* CheckNoChanges */);
30564 execComponentViewsAction(view, ViewAction.CheckNoChanges);
30565 // Note: We don't check queries for changes as we didn't do this in v2.x.
30566 // TODO(tbosch): investigate if we can enable the check again in v5.x with a nicer error message.
30567 view.state &= ~(64 /* CheckProjectedViews */ | 32 /* CheckProjectedView */);
30568}
30569function checkAndUpdateView(view) {
30570 if (view.state & 1 /* BeforeFirstCheck */) {
30571 view.state &= ~1 /* BeforeFirstCheck */;
30572 view.state |= 2 /* FirstCheck */;
30573 }
30574 else {
30575 view.state &= ~2 /* FirstCheck */;
30576 }
30577 shiftInitState(view, 0 /* InitState_BeforeInit */, 256 /* InitState_CallingOnInit */);
30578 markProjectedViewsForCheck(view);
30579 Services.updateDirectives(view, 0 /* CheckAndUpdate */);
30580 execEmbeddedViewsAction(view, ViewAction.CheckAndUpdate);
30581 execQueriesAction(view, 67108864 /* TypeContentQuery */, 536870912 /* DynamicQuery */, 0 /* CheckAndUpdate */);
30582 let callInit = shiftInitState(view, 256 /* InitState_CallingOnInit */, 512 /* InitState_CallingAfterContentInit */);
30583 callLifecycleHooksChildrenFirst(view, 2097152 /* AfterContentChecked */ | (callInit ? 1048576 /* AfterContentInit */ : 0));
30584 Services.updateRenderer(view, 0 /* CheckAndUpdate */);
30585 execComponentViewsAction(view, ViewAction.CheckAndUpdate);
30586 execQueriesAction(view, 134217728 /* TypeViewQuery */, 536870912 /* DynamicQuery */, 0 /* CheckAndUpdate */);
30587 callInit = shiftInitState(view, 512 /* InitState_CallingAfterContentInit */, 768 /* InitState_CallingAfterViewInit */);
30588 callLifecycleHooksChildrenFirst(view, 8388608 /* AfterViewChecked */ | (callInit ? 4194304 /* AfterViewInit */ : 0));
30589 if (view.def.flags & 2 /* OnPush */) {
30590 view.state &= ~8 /* ChecksEnabled */;
30591 }
30592 view.state &= ~(64 /* CheckProjectedViews */ | 32 /* CheckProjectedView */);
30593 shiftInitState(view, 768 /* InitState_CallingAfterViewInit */, 1024 /* InitState_AfterInit */);
30594}
30595function checkAndUpdateNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
30596 if (argStyle === 0 /* Inline */) {
30597 return checkAndUpdateNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
30598 }
30599 else {
30600 return checkAndUpdateNodeDynamic(view, nodeDef, v0);
30601 }
30602}
30603function markProjectedViewsForCheck(view) {
30604 const def = view.def;
30605 if (!(def.nodeFlags & 4 /* ProjectedTemplate */)) {
30606 return;
30607 }
30608 for (let i = 0; i < def.nodes.length; i++) {
30609 const nodeDef = def.nodes[i];
30610 if (nodeDef.flags & 4 /* ProjectedTemplate */) {
30611 const projectedViews = asElementData(view, i).template._projectedViews;
30612 if (projectedViews) {
30613 for (let i = 0; i < projectedViews.length; i++) {
30614 const projectedView = projectedViews[i];
30615 projectedView.state |= 32 /* CheckProjectedView */;
30616 markParentViewsForCheckProjectedViews(projectedView, view);
30617 }
30618 }
30619 }
30620 else if ((nodeDef.childFlags & 4 /* ProjectedTemplate */) === 0) {
30621 // a parent with leafs
30622 // no child is a component,
30623 // then skip the children
30624 i += nodeDef.childCount;
30625 }
30626 }
30627}
30628function checkAndUpdateNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
30629 switch (nodeDef.flags & 201347067 /* Types */) {
30630 case 1 /* TypeElement */:
30631 return checkAndUpdateElementInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
30632 case 2 /* TypeText */:
30633 return checkAndUpdateTextInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
30634 case 16384 /* TypeDirective */:
30635 return checkAndUpdateDirectiveInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
30636 case 32 /* TypePureArray */:
30637 case 64 /* TypePureObject */:
30638 case 128 /* TypePurePipe */:
30639 return checkAndUpdatePureExpressionInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
30640 default:
30641 throw 'unreachable';
30642 }
30643}
30644function checkAndUpdateNodeDynamic(view, nodeDef, values) {
30645 switch (nodeDef.flags & 201347067 /* Types */) {
30646 case 1 /* TypeElement */:
30647 return checkAndUpdateElementDynamic(view, nodeDef, values);
30648 case 2 /* TypeText */:
30649 return checkAndUpdateTextDynamic(view, nodeDef, values);
30650 case 16384 /* TypeDirective */:
30651 return checkAndUpdateDirectiveDynamic(view, nodeDef, values);
30652 case 32 /* TypePureArray */:
30653 case 64 /* TypePureObject */:
30654 case 128 /* TypePurePipe */:
30655 return checkAndUpdatePureExpressionDynamic(view, nodeDef, values);
30656 default:
30657 throw 'unreachable';
30658 }
30659}
30660function checkNoChangesNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
30661 if (argStyle === 0 /* Inline */) {
30662 checkNoChangesNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
30663 }
30664 else {
30665 checkNoChangesNodeDynamic(view, nodeDef, v0);
30666 }
30667 // Returning false is ok here as we would have thrown in case of a change.
30668 return false;
30669}
30670function checkNoChangesNodeInline(view, nodeDef, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
30671 const bindLen = nodeDef.bindings.length;
30672 if (bindLen > 0)
30673 checkBindingNoChanges(view, nodeDef, 0, v0);
30674 if (bindLen > 1)
30675 checkBindingNoChanges(view, nodeDef, 1, v1);
30676 if (bindLen > 2)
30677 checkBindingNoChanges(view, nodeDef, 2, v2);
30678 if (bindLen > 3)
30679 checkBindingNoChanges(view, nodeDef, 3, v3);
30680 if (bindLen > 4)
30681 checkBindingNoChanges(view, nodeDef, 4, v4);
30682 if (bindLen > 5)
30683 checkBindingNoChanges(view, nodeDef, 5, v5);
30684 if (bindLen > 6)
30685 checkBindingNoChanges(view, nodeDef, 6, v6);
30686 if (bindLen > 7)
30687 checkBindingNoChanges(view, nodeDef, 7, v7);
30688 if (bindLen > 8)
30689 checkBindingNoChanges(view, nodeDef, 8, v8);
30690 if (bindLen > 9)
30691 checkBindingNoChanges(view, nodeDef, 9, v9);
30692}
30693function checkNoChangesNodeDynamic(view, nodeDef, values) {
30694 for (let i = 0; i < values.length; i++) {
30695 checkBindingNoChanges(view, nodeDef, i, values[i]);
30696 }
30697}
30698/**
30699 * Workaround https://github.com/angular/tsickle/issues/497
30700 * @suppress {misplacedTypeAnnotation}
30701 */
30702function checkNoChangesQuery(view, nodeDef) {
30703 const queryList = asQueryList(view, nodeDef.nodeIndex);
30704 if (queryList.dirty) {
30705 throw expressionChangedAfterItHasBeenCheckedError(Services.createDebugContext(view, nodeDef.nodeIndex), `Query ${nodeDef.query.id} not dirty`, `Query ${nodeDef.query.id} dirty`, (view.state & 1 /* BeforeFirstCheck */) !== 0);
30706 }
30707}
30708function destroyView(view) {
30709 if (view.state & 128 /* Destroyed */) {
30710 return;
30711 }
30712 execEmbeddedViewsAction(view, ViewAction.Destroy);
30713 execComponentViewsAction(view, ViewAction.Destroy);
30714 callLifecycleHooksChildrenFirst(view, 131072 /* OnDestroy */);
30715 if (view.disposables) {
30716 for (let i = 0; i < view.disposables.length; i++) {
30717 view.disposables[i]();
30718 }
30719 }
30720 detachProjectedView(view);
30721 if (view.renderer.destroyNode) {
30722 destroyViewNodes(view);
30723 }
30724 if (isComponentView(view)) {
30725 view.renderer.destroy();
30726 }
30727 view.state |= 128 /* Destroyed */;
30728}
30729function destroyViewNodes(view) {
30730 const len = view.def.nodes.length;
30731 for (let i = 0; i < len; i++) {
30732 const def = view.def.nodes[i];
30733 if (def.flags & 1 /* TypeElement */) {
30734 view.renderer.destroyNode(asElementData(view, i).renderElement);
30735 }
30736 else if (def.flags & 2 /* TypeText */) {
30737 view.renderer.destroyNode(asTextData(view, i).renderText);
30738 }
30739 else if (def.flags & 67108864 /* TypeContentQuery */ || def.flags & 134217728 /* TypeViewQuery */) {
30740 asQueryList(view, i).destroy();
30741 }
30742 }
30743}
30744var ViewAction;
30745(function (ViewAction) {
30746 ViewAction[ViewAction["CreateViewNodes"] = 0] = "CreateViewNodes";
30747 ViewAction[ViewAction["CheckNoChanges"] = 1] = "CheckNoChanges";
30748 ViewAction[ViewAction["CheckNoChangesProjectedViews"] = 2] = "CheckNoChangesProjectedViews";
30749 ViewAction[ViewAction["CheckAndUpdate"] = 3] = "CheckAndUpdate";
30750 ViewAction[ViewAction["CheckAndUpdateProjectedViews"] = 4] = "CheckAndUpdateProjectedViews";
30751 ViewAction[ViewAction["Destroy"] = 5] = "Destroy";
30752})(ViewAction || (ViewAction = {}));
30753function execComponentViewsAction(view, action) {
30754 const def = view.def;
30755 if (!(def.nodeFlags & 33554432 /* ComponentView */)) {
30756 return;
30757 }
30758 for (let i = 0; i < def.nodes.length; i++) {
30759 const nodeDef = def.nodes[i];
30760 if (nodeDef.flags & 33554432 /* ComponentView */) {
30761 // a leaf
30762 callViewAction(asElementData(view, i).componentView, action);
30763 }
30764 else if ((nodeDef.childFlags & 33554432 /* ComponentView */) === 0) {
30765 // a parent with leafs
30766 // no child is a component,
30767 // then skip the children
30768 i += nodeDef.childCount;
30769 }
30770 }
30771}
30772function execEmbeddedViewsAction(view, action) {
30773 const def = view.def;
30774 if (!(def.nodeFlags & 16777216 /* EmbeddedViews */)) {
30775 return;
30776 }
30777 for (let i = 0; i < def.nodes.length; i++) {
30778 const nodeDef = def.nodes[i];
30779 if (nodeDef.flags & 16777216 /* EmbeddedViews */) {
30780 // a leaf
30781 const embeddedViews = asElementData(view, i).viewContainer._embeddedViews;
30782 for (let k = 0; k < embeddedViews.length; k++) {
30783 callViewAction(embeddedViews[k], action);
30784 }
30785 }
30786 else if ((nodeDef.childFlags & 16777216 /* EmbeddedViews */) === 0) {
30787 // a parent with leafs
30788 // no child is a component,
30789 // then skip the children
30790 i += nodeDef.childCount;
30791 }
30792 }
30793}
30794function callViewAction(view, action) {
30795 const viewState = view.state;
30796 switch (action) {
30797 case ViewAction.CheckNoChanges:
30798 if ((viewState & 128 /* Destroyed */) === 0) {
30799 if ((viewState & 12 /* CatDetectChanges */) === 12 /* CatDetectChanges */) {
30800 checkNoChangesView(view);
30801 }
30802 else if (viewState & 64 /* CheckProjectedViews */) {
30803 execProjectedViewsAction(view, ViewAction.CheckNoChangesProjectedViews);
30804 }
30805 }
30806 break;
30807 case ViewAction.CheckNoChangesProjectedViews:
30808 if ((viewState & 128 /* Destroyed */) === 0) {
30809 if (viewState & 32 /* CheckProjectedView */) {
30810 checkNoChangesView(view);
30811 }
30812 else if (viewState & 64 /* CheckProjectedViews */) {
30813 execProjectedViewsAction(view, action);
30814 }
30815 }
30816 break;
30817 case ViewAction.CheckAndUpdate:
30818 if ((viewState & 128 /* Destroyed */) === 0) {
30819 if ((viewState & 12 /* CatDetectChanges */) === 12 /* CatDetectChanges */) {
30820 checkAndUpdateView(view);
30821 }
30822 else if (viewState & 64 /* CheckProjectedViews */) {
30823 execProjectedViewsAction(view, ViewAction.CheckAndUpdateProjectedViews);
30824 }
30825 }
30826 break;
30827 case ViewAction.CheckAndUpdateProjectedViews:
30828 if ((viewState & 128 /* Destroyed */) === 0) {
30829 if (viewState & 32 /* CheckProjectedView */) {
30830 checkAndUpdateView(view);
30831 }
30832 else if (viewState & 64 /* CheckProjectedViews */) {
30833 execProjectedViewsAction(view, action);
30834 }
30835 }
30836 break;
30837 case ViewAction.Destroy:
30838 // Note: destroyView recurses over all views,
30839 // so we don't need to special case projected views here.
30840 destroyView(view);
30841 break;
30842 case ViewAction.CreateViewNodes:
30843 createViewNodes(view);
30844 break;
30845 }
30846}
30847function execProjectedViewsAction(view, action) {
30848 execEmbeddedViewsAction(view, action);
30849 execComponentViewsAction(view, action);
30850}
30851function execQueriesAction(view, queryFlags, staticDynamicQueryFlag, checkType) {
30852 if (!(view.def.nodeFlags & queryFlags) || !(view.def.nodeFlags & staticDynamicQueryFlag)) {
30853 return;
30854 }
30855 const nodeCount = view.def.nodes.length;
30856 for (let i = 0; i < nodeCount; i++) {
30857 const nodeDef = view.def.nodes[i];
30858 if ((nodeDef.flags & queryFlags) && (nodeDef.flags & staticDynamicQueryFlag)) {
30859 Services.setCurrentNode(view, nodeDef.nodeIndex);
30860 switch (checkType) {
30861 case 0 /* CheckAndUpdate */:
30862 checkAndUpdateQuery(view, nodeDef);
30863 break;
30864 case 1 /* CheckNoChanges */:
30865 checkNoChangesQuery(view, nodeDef);
30866 break;
30867 }
30868 }
30869 if (!(nodeDef.childFlags & queryFlags) || !(nodeDef.childFlags & staticDynamicQueryFlag)) {
30870 // no child has a matching query
30871 // then skip the children
30872 i += nodeDef.childCount;
30873 }
30874 }
30875}
30876
30877/**
30878 * @license
30879 * Copyright Google LLC All Rights Reserved.
30880 *
30881 * Use of this source code is governed by an MIT-style license that can be
30882 * found in the LICENSE file at https://angular.io/license
30883 */
30884let initialized = false;
30885function initServicesIfNeeded() {
30886 if (initialized) {
30887 return;
30888 }
30889 initialized = true;
30890 const services = isDevMode() ? createDebugServices() : createProdServices();
30891 Services.setCurrentNode = services.setCurrentNode;
30892 Services.createRootView = services.createRootView;
30893 Services.createEmbeddedView = services.createEmbeddedView;
30894 Services.createComponentView = services.createComponentView;
30895 Services.createNgModuleRef = services.createNgModuleRef;
30896 Services.overrideProvider = services.overrideProvider;
30897 Services.overrideComponentView = services.overrideComponentView;
30898 Services.clearOverrides = services.clearOverrides;
30899 Services.checkAndUpdateView = services.checkAndUpdateView;
30900 Services.checkNoChangesView = services.checkNoChangesView;
30901 Services.destroyView = services.destroyView;
30902 Services.resolveDep = resolveDep;
30903 Services.createDebugContext = services.createDebugContext;
30904 Services.handleEvent = services.handleEvent;
30905 Services.updateDirectives = services.updateDirectives;
30906 Services.updateRenderer = services.updateRenderer;
30907 Services.dirtyParentQueries = dirtyParentQueries;
30908}
30909function createProdServices() {
30910 return {
30911 setCurrentNode: () => { },
30912 createRootView: createProdRootView,
30913 createEmbeddedView: createEmbeddedView,
30914 createComponentView: createComponentView,
30915 createNgModuleRef: createNgModuleRef,
30916 overrideProvider: NOOP,
30917 overrideComponentView: NOOP,
30918 clearOverrides: NOOP,
30919 checkAndUpdateView: checkAndUpdateView,
30920 checkNoChangesView: checkNoChangesView,
30921 destroyView: destroyView,
30922 createDebugContext: (view, nodeIndex) => new DebugContext_(view, nodeIndex),
30923 handleEvent: (view, nodeIndex, eventName, event) => view.def.handleEvent(view, nodeIndex, eventName, event),
30924 updateDirectives: (view, checkType) => view.def.updateDirectives(checkType === 0 /* CheckAndUpdate */ ? prodCheckAndUpdateNode : prodCheckNoChangesNode, view),
30925 updateRenderer: (view, checkType) => view.def.updateRenderer(checkType === 0 /* CheckAndUpdate */ ? prodCheckAndUpdateNode : prodCheckNoChangesNode, view),
30926 };
30927}
30928function createDebugServices() {
30929 return {
30930 setCurrentNode: debugSetCurrentNode,
30931 createRootView: debugCreateRootView,
30932 createEmbeddedView: debugCreateEmbeddedView,
30933 createComponentView: debugCreateComponentView,
30934 createNgModuleRef: debugCreateNgModuleRef,
30935 overrideProvider: debugOverrideProvider,
30936 overrideComponentView: debugOverrideComponentView,
30937 clearOverrides: debugClearOverrides,
30938 checkAndUpdateView: debugCheckAndUpdateView,
30939 checkNoChangesView: debugCheckNoChangesView,
30940 destroyView: debugDestroyView,
30941 createDebugContext: (view, nodeIndex) => new DebugContext_(view, nodeIndex),
30942 handleEvent: debugHandleEvent,
30943 updateDirectives: debugUpdateDirectives,
30944 updateRenderer: debugUpdateRenderer,
30945 };
30946}
30947function createProdRootView(elInjector, projectableNodes, rootSelectorOrNode, def, ngModule, context) {
30948 const rendererFactory = ngModule.injector.get(RendererFactory2);
30949 return createRootView(createRootData(elInjector, ngModule, rendererFactory, projectableNodes, rootSelectorOrNode), def, context);
30950}
30951function debugCreateRootView(elInjector, projectableNodes, rootSelectorOrNode, def, ngModule, context) {
30952 const rendererFactory = ngModule.injector.get(RendererFactory2);
30953 const root = createRootData(elInjector, ngModule, new DebugRendererFactory2(rendererFactory), projectableNodes, rootSelectorOrNode);
30954 const defWithOverride = applyProviderOverridesToView(def);
30955 return callWithDebugContext(DebugAction.create, createRootView, null, [root, defWithOverride, context]);
30956}
30957function createRootData(elInjector, ngModule, rendererFactory, projectableNodes, rootSelectorOrNode) {
30958 const sanitizer = ngModule.injector.get(Sanitizer);
30959 const errorHandler = ngModule.injector.get(ErrorHandler);
30960 const renderer = rendererFactory.createRenderer(null, null);
30961 return {
30962 ngModule,
30963 injector: elInjector,
30964 projectableNodes,
30965 selectorOrNode: rootSelectorOrNode,
30966 sanitizer,
30967 rendererFactory,
30968 renderer,
30969 errorHandler
30970 };
30971}
30972function debugCreateEmbeddedView(parentView, anchorDef, viewDef, context) {
30973 const defWithOverride = applyProviderOverridesToView(viewDef);
30974 return callWithDebugContext(DebugAction.create, createEmbeddedView, null, [parentView, anchorDef, defWithOverride, context]);
30975}
30976function debugCreateComponentView(parentView, nodeDef, viewDef, hostElement) {
30977 const overrideComponentView = viewDefOverrides.get(nodeDef.element.componentProvider.provider.token);
30978 if (overrideComponentView) {
30979 viewDef = overrideComponentView;
30980 }
30981 else {
30982 viewDef = applyProviderOverridesToView(viewDef);
30983 }
30984 return callWithDebugContext(DebugAction.create, createComponentView, null, [parentView, nodeDef, viewDef, hostElement]);
30985}
30986function debugCreateNgModuleRef(moduleType, parentInjector, bootstrapComponents, def) {
30987 const defWithOverride = applyProviderOverridesToNgModule(def);
30988 return createNgModuleRef(moduleType, parentInjector, bootstrapComponents, defWithOverride);
30989}
30990const providerOverrides = new Map();
30991const providerOverridesWithScope = new Map();
30992const viewDefOverrides = new Map();
30993function debugOverrideProvider(override) {
30994 providerOverrides.set(override.token, override);
30995 let injectableDef;
30996 if (typeof override.token === 'function' && (injectableDef = getInjectableDef(override.token)) &&
30997 typeof injectableDef.providedIn === 'function') {
30998 providerOverridesWithScope.set(override.token, override);
30999 }
31000}
31001function debugOverrideComponentView(comp, compFactory) {
31002 const hostViewDef = resolveDefinition(getComponentViewDefinitionFactory(compFactory));
31003 const compViewDef = resolveDefinition(hostViewDef.nodes[0].element.componentView);
31004 viewDefOverrides.set(comp, compViewDef);
31005}
31006function debugClearOverrides() {
31007 providerOverrides.clear();
31008 providerOverridesWithScope.clear();
31009 viewDefOverrides.clear();
31010}
31011// Notes about the algorithm:
31012// 1) Locate the providers of an element and check if one of them was overwritten
31013// 2) Change the providers of that element
31014//
31015// We only create new datastructures if we need to, to keep perf impact
31016// reasonable.
31017function applyProviderOverridesToView(def) {
31018 if (providerOverrides.size === 0) {
31019 return def;
31020 }
31021 const elementIndicesWithOverwrittenProviders = findElementIndicesWithOverwrittenProviders(def);
31022 if (elementIndicesWithOverwrittenProviders.length === 0) {
31023 return def;
31024 }
31025 // clone the whole view definition,
31026 // as it maintains references between the nodes that are hard to update.
31027 def = def.factory(() => NOOP);
31028 for (let i = 0; i < elementIndicesWithOverwrittenProviders.length; i++) {
31029 applyProviderOverridesToElement(def, elementIndicesWithOverwrittenProviders[i]);
31030 }
31031 return def;
31032 function findElementIndicesWithOverwrittenProviders(def) {
31033 const elIndicesWithOverwrittenProviders = [];
31034 let lastElementDef = null;
31035 for (let i = 0; i < def.nodes.length; i++) {
31036 const nodeDef = def.nodes[i];
31037 if (nodeDef.flags & 1 /* TypeElement */) {
31038 lastElementDef = nodeDef;
31039 }
31040 if (lastElementDef && nodeDef.flags & 3840 /* CatProviderNoDirective */ &&
31041 providerOverrides.has(nodeDef.provider.token)) {
31042 elIndicesWithOverwrittenProviders.push(lastElementDef.nodeIndex);
31043 lastElementDef = null;
31044 }
31045 }
31046 return elIndicesWithOverwrittenProviders;
31047 }
31048 function applyProviderOverridesToElement(viewDef, elIndex) {
31049 for (let i = elIndex + 1; i < viewDef.nodes.length; i++) {
31050 const nodeDef = viewDef.nodes[i];
31051 if (nodeDef.flags & 1 /* TypeElement */) {
31052 // stop at the next element
31053 return;
31054 }
31055 if (nodeDef.flags & 3840 /* CatProviderNoDirective */) {
31056 const provider = nodeDef.provider;
31057 const override = providerOverrides.get(provider.token);
31058 if (override) {
31059 nodeDef.flags = (nodeDef.flags & ~3840 /* CatProviderNoDirective */) | override.flags;
31060 provider.deps = splitDepsDsl(override.deps);
31061 provider.value = override.value;
31062 }
31063 }
31064 }
31065 }
31066}
31067// Notes about the algorithm:
31068// We only create new datastructures if we need to, to keep perf impact
31069// reasonable.
31070function applyProviderOverridesToNgModule(def) {
31071 const { hasOverrides, hasDeprecatedOverrides } = calcHasOverrides(def);
31072 if (!hasOverrides) {
31073 return def;
31074 }
31075 // clone the whole view definition,
31076 // as it maintains references between the nodes that are hard to update.
31077 def = def.factory(() => NOOP);
31078 applyProviderOverrides(def);
31079 return def;
31080 function calcHasOverrides(def) {
31081 let hasOverrides = false;
31082 let hasDeprecatedOverrides = false;
31083 if (providerOverrides.size === 0) {
31084 return { hasOverrides, hasDeprecatedOverrides };
31085 }
31086 def.providers.forEach(node => {
31087 const override = providerOverrides.get(node.token);
31088 if ((node.flags & 3840 /* CatProviderNoDirective */) && override) {
31089 hasOverrides = true;
31090 hasDeprecatedOverrides = hasDeprecatedOverrides || override.deprecatedBehavior;
31091 }
31092 });
31093 def.modules.forEach(module => {
31094 providerOverridesWithScope.forEach((override, token) => {
31095 if (getInjectableDef(token).providedIn === module) {
31096 hasOverrides = true;
31097 hasDeprecatedOverrides = hasDeprecatedOverrides || override.deprecatedBehavior;
31098 }
31099 });
31100 });
31101 return { hasOverrides, hasDeprecatedOverrides };
31102 }
31103 function applyProviderOverrides(def) {
31104 for (let i = 0; i < def.providers.length; i++) {
31105 const provider = def.providers[i];
31106 if (hasDeprecatedOverrides) {
31107 // We had a bug where me made
31108 // all providers lazy. Keep this logic behind a flag
31109 // for migrating existing users.
31110 provider.flags |= 4096 /* LazyProvider */;
31111 }
31112 const override = providerOverrides.get(provider.token);
31113 if (override) {
31114 provider.flags = (provider.flags & ~3840 /* CatProviderNoDirective */) | override.flags;
31115 provider.deps = splitDepsDsl(override.deps);
31116 provider.value = override.value;
31117 }
31118 }
31119 if (providerOverridesWithScope.size > 0) {
31120 let moduleSet = new Set(def.modules);
31121 providerOverridesWithScope.forEach((override, token) => {
31122 if (moduleSet.has(getInjectableDef(token).providedIn)) {
31123 let provider = {
31124 token: token,
31125 flags: override.flags | (hasDeprecatedOverrides ? 4096 /* LazyProvider */ : 0 /* None */),
31126 deps: splitDepsDsl(override.deps),
31127 value: override.value,
31128 index: def.providers.length,
31129 };
31130 def.providers.push(provider);
31131 def.providersByKey[tokenKey(token)] = provider;
31132 }
31133 });
31134 }
31135 }
31136}
31137function prodCheckAndUpdateNode(view, checkIndex, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
31138 const nodeDef = view.def.nodes[checkIndex];
31139 checkAndUpdateNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
31140 return (nodeDef.flags & 224 /* CatPureExpression */) ?
31141 asPureExpressionData(view, checkIndex).value :
31142 undefined;
31143}
31144function prodCheckNoChangesNode(view, checkIndex, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
31145 const nodeDef = view.def.nodes[checkIndex];
31146 checkNoChangesNode(view, nodeDef, argStyle, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
31147 return (nodeDef.flags & 224 /* CatPureExpression */) ?
31148 asPureExpressionData(view, checkIndex).value :
31149 undefined;
31150}
31151function debugCheckAndUpdateView(view) {
31152 return callWithDebugContext(DebugAction.detectChanges, checkAndUpdateView, null, [view]);
31153}
31154function debugCheckNoChangesView(view) {
31155 return callWithDebugContext(DebugAction.checkNoChanges, checkNoChangesView, null, [view]);
31156}
31157function debugDestroyView(view) {
31158 return callWithDebugContext(DebugAction.destroy, destroyView, null, [view]);
31159}
31160var DebugAction;
31161(function (DebugAction) {
31162 DebugAction[DebugAction["create"] = 0] = "create";
31163 DebugAction[DebugAction["detectChanges"] = 1] = "detectChanges";
31164 DebugAction[DebugAction["checkNoChanges"] = 2] = "checkNoChanges";
31165 DebugAction[DebugAction["destroy"] = 3] = "destroy";
31166 DebugAction[DebugAction["handleEvent"] = 4] = "handleEvent";
31167})(DebugAction || (DebugAction = {}));
31168let _currentAction;
31169let _currentView;
31170let _currentNodeIndex;
31171function debugSetCurrentNode(view, nodeIndex) {
31172 _currentView = view;
31173 _currentNodeIndex = nodeIndex;
31174}
31175function debugHandleEvent(view, nodeIndex, eventName, event) {
31176 debugSetCurrentNode(view, nodeIndex);
31177 return callWithDebugContext(DebugAction.handleEvent, view.def.handleEvent, null, [view, nodeIndex, eventName, event]);
31178}
31179function debugUpdateDirectives(view, checkType) {
31180 if (view.state & 128 /* Destroyed */) {
31181 throw viewDestroyedError(DebugAction[_currentAction]);
31182 }
31183 debugSetCurrentNode(view, nextDirectiveWithBinding(view, 0));
31184 return view.def.updateDirectives(debugCheckDirectivesFn, view);
31185 function debugCheckDirectivesFn(view, nodeIndex, argStyle, ...values) {
31186 const nodeDef = view.def.nodes[nodeIndex];
31187 if (checkType === 0 /* CheckAndUpdate */) {
31188 debugCheckAndUpdateNode(view, nodeDef, argStyle, values);
31189 }
31190 else {
31191 debugCheckNoChangesNode(view, nodeDef, argStyle, values);
31192 }
31193 if (nodeDef.flags & 16384 /* TypeDirective */) {
31194 debugSetCurrentNode(view, nextDirectiveWithBinding(view, nodeIndex));
31195 }
31196 return (nodeDef.flags & 224 /* CatPureExpression */) ?
31197 asPureExpressionData(view, nodeDef.nodeIndex).value :
31198 undefined;
31199 }
31200}
31201function debugUpdateRenderer(view, checkType) {
31202 if (view.state & 128 /* Destroyed */) {
31203 throw viewDestroyedError(DebugAction[_currentAction]);
31204 }
31205 debugSetCurrentNode(view, nextRenderNodeWithBinding(view, 0));
31206 return view.def.updateRenderer(debugCheckRenderNodeFn, view);
31207 function debugCheckRenderNodeFn(view, nodeIndex, argStyle, ...values) {
31208 const nodeDef = view.def.nodes[nodeIndex];
31209 if (checkType === 0 /* CheckAndUpdate */) {
31210 debugCheckAndUpdateNode(view, nodeDef, argStyle, values);
31211 }
31212 else {
31213 debugCheckNoChangesNode(view, nodeDef, argStyle, values);
31214 }
31215 if (nodeDef.flags & 3 /* CatRenderNode */) {
31216 debugSetCurrentNode(view, nextRenderNodeWithBinding(view, nodeIndex));
31217 }
31218 return (nodeDef.flags & 224 /* CatPureExpression */) ?
31219 asPureExpressionData(view, nodeDef.nodeIndex).value :
31220 undefined;
31221 }
31222}
31223function debugCheckAndUpdateNode(view, nodeDef, argStyle, givenValues) {
31224 const changed = checkAndUpdateNode(view, nodeDef, argStyle, ...givenValues);
31225 if (changed) {
31226 const values = argStyle === 1 /* Dynamic */ ? givenValues[0] : givenValues;
31227 if (nodeDef.flags & 16384 /* TypeDirective */) {
31228 const bindingValues = {};
31229 for (let i = 0; i < nodeDef.bindings.length; i++) {
31230 const binding = nodeDef.bindings[i];
31231 const value = values[i];
31232 if (binding.flags & 8 /* TypeProperty */) {
31233 bindingValues[normalizeDebugBindingName(binding.nonMinifiedName)] =
31234 normalizeDebugBindingValue(value);
31235 }
31236 }
31237 const elDef = nodeDef.parent;
31238 const el = asElementData(view, elDef.nodeIndex).renderElement;
31239 if (!elDef.element.name) {
31240 // a comment.
31241 view.renderer.setValue(el, `bindings=${JSON.stringify(bindingValues, null, 2)}`);
31242 }
31243 else {
31244 // a regular element.
31245 for (let attr in bindingValues) {
31246 const value = bindingValues[attr];
31247 if (value != null) {
31248 view.renderer.setAttribute(el, attr, value);
31249 }
31250 else {
31251 view.renderer.removeAttribute(el, attr);
31252 }
31253 }
31254 }
31255 }
31256 }
31257}
31258function debugCheckNoChangesNode(view, nodeDef, argStyle, values) {
31259 checkNoChangesNode(view, nodeDef, argStyle, ...values);
31260}
31261function nextDirectiveWithBinding(view, nodeIndex) {
31262 for (let i = nodeIndex; i < view.def.nodes.length; i++) {
31263 const nodeDef = view.def.nodes[i];
31264 if (nodeDef.flags & 16384 /* TypeDirective */ && nodeDef.bindings && nodeDef.bindings.length) {
31265 return i;
31266 }
31267 }
31268 return null;
31269}
31270function nextRenderNodeWithBinding(view, nodeIndex) {
31271 for (let i = nodeIndex; i < view.def.nodes.length; i++) {
31272 const nodeDef = view.def.nodes[i];
31273 if ((nodeDef.flags & 3 /* CatRenderNode */) && nodeDef.bindings && nodeDef.bindings.length) {
31274 return i;
31275 }
31276 }
31277 return null;
31278}
31279class DebugContext_ {
31280 constructor(view, nodeIndex) {
31281 this.view = view;
31282 this.nodeIndex = nodeIndex;
31283 if (nodeIndex == null) {
31284 this.nodeIndex = nodeIndex = 0;
31285 }
31286 this.nodeDef = view.def.nodes[nodeIndex];
31287 let elDef = this.nodeDef;
31288 let elView = view;
31289 while (elDef && (elDef.flags & 1 /* TypeElement */) === 0) {
31290 elDef = elDef.parent;
31291 }
31292 if (!elDef) {
31293 while (!elDef && elView) {
31294 elDef = viewParentEl(elView);
31295 elView = elView.parent;
31296 }
31297 }
31298 this.elDef = elDef;
31299 this.elView = elView;
31300 }
31301 get elOrCompView() {
31302 // Has to be done lazily as we use the DebugContext also during creation of elements...
31303 return asElementData(this.elView, this.elDef.nodeIndex).componentView || this.view;
31304 }
31305 get injector() {
31306 return createInjector$1(this.elView, this.elDef);
31307 }
31308 get component() {
31309 return this.elOrCompView.component;
31310 }
31311 get context() {
31312 return this.elOrCompView.context;
31313 }
31314 get providerTokens() {
31315 const tokens = [];
31316 if (this.elDef) {
31317 for (let i = this.elDef.nodeIndex + 1; i <= this.elDef.nodeIndex + this.elDef.childCount; i++) {
31318 const childDef = this.elView.def.nodes[i];
31319 if (childDef.flags & 20224 /* CatProvider */) {
31320 tokens.push(childDef.provider.token);
31321 }
31322 i += childDef.childCount;
31323 }
31324 }
31325 return tokens;
31326 }
31327 get references() {
31328 const references = {};
31329 if (this.elDef) {
31330 collectReferences(this.elView, this.elDef, references);
31331 for (let i = this.elDef.nodeIndex + 1; i <= this.elDef.nodeIndex + this.elDef.childCount; i++) {
31332 const childDef = this.elView.def.nodes[i];
31333 if (childDef.flags & 20224 /* CatProvider */) {
31334 collectReferences(this.elView, childDef, references);
31335 }
31336 i += childDef.childCount;
31337 }
31338 }
31339 return references;
31340 }
31341 get componentRenderElement() {
31342 const elData = findHostElement(this.elOrCompView);
31343 return elData ? elData.renderElement : undefined;
31344 }
31345 get renderNode() {
31346 return this.nodeDef.flags & 2 /* TypeText */ ? renderNode(this.view, this.nodeDef) :
31347 renderNode(this.elView, this.elDef);
31348 }
31349 logError(console, ...values) {
31350 let logViewDef;
31351 let logNodeIndex;
31352 if (this.nodeDef.flags & 2 /* TypeText */) {
31353 logViewDef = this.view.def;
31354 logNodeIndex = this.nodeDef.nodeIndex;
31355 }
31356 else {
31357 logViewDef = this.elView.def;
31358 logNodeIndex = this.elDef.nodeIndex;
31359 }
31360 // Note: we only generate a log function for text and element nodes
31361 // to make the generated code as small as possible.
31362 const renderNodeIndex = getRenderNodeIndex(logViewDef, logNodeIndex);
31363 let currRenderNodeIndex = -1;
31364 let nodeLogger = () => {
31365 currRenderNodeIndex++;
31366 if (currRenderNodeIndex === renderNodeIndex) {
31367 return console.error.bind(console, ...values);
31368 }
31369 else {
31370 return NOOP;
31371 }
31372 };
31373 logViewDef.factory(nodeLogger);
31374 if (currRenderNodeIndex < renderNodeIndex) {
31375 console.error('Illegal state: the ViewDefinitionFactory did not call the logger!');
31376 console.error(...values);
31377 }
31378 }
31379}
31380function getRenderNodeIndex(viewDef, nodeIndex) {
31381 let renderNodeIndex = -1;
31382 for (let i = 0; i <= nodeIndex; i++) {
31383 const nodeDef = viewDef.nodes[i];
31384 if (nodeDef.flags & 3 /* CatRenderNode */) {
31385 renderNodeIndex++;
31386 }
31387 }
31388 return renderNodeIndex;
31389}
31390function findHostElement(view) {
31391 while (view && !isComponentView(view)) {
31392 view = view.parent;
31393 }
31394 if (view.parent) {
31395 return asElementData(view.parent, viewParentEl(view).nodeIndex);
31396 }
31397 return null;
31398}
31399function collectReferences(view, nodeDef, references) {
31400 for (let refName in nodeDef.references) {
31401 references[refName] = getQueryValue(view, nodeDef, nodeDef.references[refName]);
31402 }
31403}
31404function callWithDebugContext(action, fn, self, args) {
31405 const oldAction = _currentAction;
31406 const oldView = _currentView;
31407 const oldNodeIndex = _currentNodeIndex;
31408 try {
31409 _currentAction = action;
31410 const result = fn.apply(self, args);
31411 _currentView = oldView;
31412 _currentNodeIndex = oldNodeIndex;
31413 _currentAction = oldAction;
31414 return result;
31415 }
31416 catch (e) {
31417 if (isViewDebugError(e) || !_currentView) {
31418 throw e;
31419 }
31420 throw viewWrappedDebugError(e, getCurrentDebugContext());
31421 }
31422}
31423function getCurrentDebugContext() {
31424 return _currentView ? new DebugContext_(_currentView, _currentNodeIndex) : null;
31425}
31426class DebugRendererFactory2 {
31427 constructor(delegate) {
31428 this.delegate = delegate;
31429 }
31430 createRenderer(element, renderData) {
31431 return new DebugRenderer2(this.delegate.createRenderer(element, renderData));
31432 }
31433 begin() {
31434 if (this.delegate.begin) {
31435 this.delegate.begin();
31436 }
31437 }
31438 end() {
31439 if (this.delegate.end) {
31440 this.delegate.end();
31441 }
31442 }
31443 whenRenderingDone() {
31444 if (this.delegate.whenRenderingDone) {
31445 return this.delegate.whenRenderingDone();
31446 }
31447 return Promise.resolve(null);
31448 }
31449}
31450class DebugRenderer2 {
31451 constructor(delegate) {
31452 this.delegate = delegate;
31453 /**
31454 * Factory function used to create a `DebugContext` when a node is created.
31455 *
31456 * The `DebugContext` allows to retrieve information about the nodes that are useful in tests.
31457 *
31458 * The factory is configurable so that the `DebugRenderer2` could instantiate either a View Engine
31459 * or a Render context.
31460 */
31461 this.debugContextFactory = getCurrentDebugContext;
31462 this.data = this.delegate.data;
31463 }
31464 createDebugContext(nativeElement) {
31465 return this.debugContextFactory(nativeElement);
31466 }
31467 destroyNode(node) {
31468 const debugNode = getDebugNode$1(node);
31469 removeDebugNodeFromIndex(debugNode);
31470 if (debugNode instanceof DebugNode__PRE_R3__) {
31471 debugNode.listeners.length = 0;
31472 }
31473 if (this.delegate.destroyNode) {
31474 this.delegate.destroyNode(node);
31475 }
31476 }
31477 destroy() {
31478 this.delegate.destroy();
31479 }
31480 createElement(name, namespace) {
31481 const el = this.delegate.createElement(name, namespace);
31482 const debugCtx = this.createDebugContext(el);
31483 if (debugCtx) {
31484 const debugEl = new DebugElement__PRE_R3__(el, null, debugCtx);
31485 debugEl.name = name;
31486 indexDebugNode(debugEl);
31487 }
31488 return el;
31489 }
31490 createComment(value) {
31491 const comment = this.delegate.createComment(value);
31492 const debugCtx = this.createDebugContext(comment);
31493 if (debugCtx) {
31494 indexDebugNode(new DebugNode__PRE_R3__(comment, null, debugCtx));
31495 }
31496 return comment;
31497 }
31498 createText(value) {
31499 const text = this.delegate.createText(value);
31500 const debugCtx = this.createDebugContext(text);
31501 if (debugCtx) {
31502 indexDebugNode(new DebugNode__PRE_R3__(text, null, debugCtx));
31503 }
31504 return text;
31505 }
31506 appendChild(parent, newChild) {
31507 const debugEl = getDebugNode$1(parent);
31508 const debugChildEl = getDebugNode$1(newChild);
31509 if (debugEl && debugChildEl && debugEl instanceof DebugElement__PRE_R3__) {
31510 debugEl.addChild(debugChildEl);
31511 }
31512 this.delegate.appendChild(parent, newChild);
31513 }
31514 insertBefore(parent, newChild, refChild) {
31515 const debugEl = getDebugNode$1(parent);
31516 const debugChildEl = getDebugNode$1(newChild);
31517 const debugRefEl = getDebugNode$1(refChild);
31518 if (debugEl && debugChildEl && debugEl instanceof DebugElement__PRE_R3__) {
31519 debugEl.insertBefore(debugRefEl, debugChildEl);
31520 }
31521 this.delegate.insertBefore(parent, newChild, refChild);
31522 }
31523 removeChild(parent, oldChild) {
31524 const debugEl = getDebugNode$1(parent);
31525 const debugChildEl = getDebugNode$1(oldChild);
31526 if (debugEl && debugChildEl && debugEl instanceof DebugElement__PRE_R3__) {
31527 debugEl.removeChild(debugChildEl);
31528 }
31529 this.delegate.removeChild(parent, oldChild);
31530 }
31531 selectRootElement(selectorOrNode, preserveContent) {
31532 const el = this.delegate.selectRootElement(selectorOrNode, preserveContent);
31533 const debugCtx = getCurrentDebugContext();
31534 if (debugCtx) {
31535 indexDebugNode(new DebugElement__PRE_R3__(el, null, debugCtx));
31536 }
31537 return el;
31538 }
31539 setAttribute(el, name, value, namespace) {
31540 const debugEl = getDebugNode$1(el);
31541 if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
31542 const fullName = namespace ? namespace + ':' + name : name;
31543 debugEl.attributes[fullName] = value;
31544 }
31545 this.delegate.setAttribute(el, name, value, namespace);
31546 }
31547 removeAttribute(el, name, namespace) {
31548 const debugEl = getDebugNode$1(el);
31549 if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
31550 const fullName = namespace ? namespace + ':' + name : name;
31551 debugEl.attributes[fullName] = null;
31552 }
31553 this.delegate.removeAttribute(el, name, namespace);
31554 }
31555 addClass(el, name) {
31556 const debugEl = getDebugNode$1(el);
31557 if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
31558 debugEl.classes[name] = true;
31559 }
31560 this.delegate.addClass(el, name);
31561 }
31562 removeClass(el, name) {
31563 const debugEl = getDebugNode$1(el);
31564 if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
31565 debugEl.classes[name] = false;
31566 }
31567 this.delegate.removeClass(el, name);
31568 }
31569 setStyle(el, style, value, flags) {
31570 const debugEl = getDebugNode$1(el);
31571 if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
31572 debugEl.styles[style] = value;
31573 }
31574 this.delegate.setStyle(el, style, value, flags);
31575 }
31576 removeStyle(el, style, flags) {
31577 const debugEl = getDebugNode$1(el);
31578 if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
31579 debugEl.styles[style] = null;
31580 }
31581 this.delegate.removeStyle(el, style, flags);
31582 }
31583 setProperty(el, name, value) {
31584 const debugEl = getDebugNode$1(el);
31585 if (debugEl && debugEl instanceof DebugElement__PRE_R3__) {
31586 debugEl.properties[name] = value;
31587 }
31588 this.delegate.setProperty(el, name, value);
31589 }
31590 listen(target, eventName, callback) {
31591 if (typeof target !== 'string') {
31592 const debugEl = getDebugNode$1(target);
31593 if (debugEl) {
31594 debugEl.listeners.push(new DebugEventListener(eventName, callback));
31595 }
31596 }
31597 return this.delegate.listen(target, eventName, callback);
31598 }
31599 parentNode(node) {
31600 return this.delegate.parentNode(node);
31601 }
31602 nextSibling(node) {
31603 return this.delegate.nextSibling(node);
31604 }
31605 setValue(node, value) {
31606 return this.delegate.setValue(node, value);
31607 }
31608}
31609
31610/**
31611 * @license
31612 * Copyright Google LLC All Rights Reserved.
31613 *
31614 * Use of this source code is governed by an MIT-style license that can be
31615 * found in the LICENSE file at https://angular.io/license
31616 */
31617function overrideProvider(override) {
31618 initServicesIfNeeded();
31619 return Services.overrideProvider(override);
31620}
31621function overrideComponentView(comp, componentFactory) {
31622 initServicesIfNeeded();
31623 return Services.overrideComponentView(comp, componentFactory);
31624}
31625function clearOverrides() {
31626 initServicesIfNeeded();
31627 return Services.clearOverrides();
31628}
31629// Attention: this function is called as top level function.
31630// Putting any logic in here will destroy closure tree shaking!
31631function createNgModuleFactory(ngModuleType, bootstrapComponents, defFactory) {
31632 return new NgModuleFactory_(ngModuleType, bootstrapComponents, defFactory);
31633}
31634function cloneNgModuleDefinition(def) {
31635 const providers = Array.from(def.providers);
31636 const modules = Array.from(def.modules);
31637 const providersByKey = {};
31638 for (const key in def.providersByKey) {
31639 providersByKey[key] = def.providersByKey[key];
31640 }
31641 return {
31642 factory: def.factory,
31643 scope: def.scope,
31644 providers,
31645 modules,
31646 providersByKey,
31647 };
31648}
31649class NgModuleFactory_ extends NgModuleFactory {
31650 constructor(moduleType, _bootstrapComponents, _ngModuleDefFactory) {
31651 // Attention: this ctor is called as top level function.
31652 // Putting any logic in here will destroy closure tree shaking!
31653 super();
31654 this.moduleType = moduleType;
31655 this._bootstrapComponents = _bootstrapComponents;
31656 this._ngModuleDefFactory = _ngModuleDefFactory;
31657 }
31658 create(parentInjector) {
31659 initServicesIfNeeded();
31660 // Clone the NgModuleDefinition so that any tree shakeable provider definition
31661 // added to this instance of the NgModuleRef doesn't affect the cached copy.
31662 // See https://github.com/angular/angular/issues/25018.
31663 const def = cloneNgModuleDefinition(resolveDefinition(this._ngModuleDefFactory));
31664 return Services.createNgModuleRef(this.moduleType, parentInjector || Injector.NULL, this._bootstrapComponents, def);
31665 }
31666}
31667
31668/**
31669 * @license
31670 * Copyright Google LLC All Rights Reserved.
31671 *
31672 * Use of this source code is governed by an MIT-style license that can be
31673 * found in the LICENSE file at https://angular.io/license
31674 */
31675
31676/**
31677 * @license
31678 * Copyright Google LLC All Rights Reserved.
31679 *
31680 * Use of this source code is governed by an MIT-style license that can be
31681 * found in the LICENSE file at https://angular.io/license
31682 */
31683
31684/**
31685 * @license
31686 * Copyright Google LLC All Rights Reserved.
31687 *
31688 * Use of this source code is governed by an MIT-style license that can be
31689 * found in the LICENSE file at https://angular.io/license
31690 */
31691// clang-format on
31692
31693/**
31694 * @license
31695 * Copyright Google LLC All Rights Reserved.
31696 *
31697 * Use of this source code is governed by an MIT-style license that can be
31698 * found in the LICENSE file at https://angular.io/license
31699 */
31700
31701/**
31702 * @license
31703 * Copyright Google LLC All Rights Reserved.
31704 *
31705 * Use of this source code is governed by an MIT-style license that can be
31706 * found in the LICENSE file at https://angular.io/license
31707 */
31708if (ngDevMode) {
31709 // This helper is to give a reasonable error message to people upgrading to v9 that have not yet
31710 // installed `@angular/localize` in their app.
31711 // tslint:disable-next-line: no-toplevel-property-access
31712 _global.$localize = _global.$localize || function () {
31713 throw new Error('It looks like your application or one of its dependencies is using i18n.\n' +
31714 'Angular 9 introduced a global `$localize()` function that needs to be loaded.\n' +
31715 'Please run `ng add @angular/localize` from the Angular CLI.\n' +
31716 '(For non-CLI projects, add `import \'@angular/localize/init\';` to your `polyfills.ts` file.\n' +
31717 'For server-side rendering applications add the import to your `main.server.ts` file.)');
31718 };
31719}
31720
31721/**
31722 * @license
31723 * Copyright Google LLC All Rights Reserved.
31724 *
31725 * Use of this source code is governed by an MIT-style license that can be
31726 * found in the LICENSE file at https://angular.io/license
31727 */
31728// This file only reexports content of the `src` folder. Keep it that way.
31729
31730/**
31731 * @license
31732 * Copyright Google LLC All Rights Reserved.
31733 *
31734 * Use of this source code is governed by an MIT-style license that can be
31735 * found in the LICENSE file at https://angular.io/license
31736 */
31737
31738/**
31739 * Generated bundle index. Do not edit.
31740 */
31741
31742export { ANALYZE_FOR_ENTRY_COMPONENTS, APP_BOOTSTRAP_LISTENER, APP_ID, APP_INITIALIZER, ApplicationInitStatus, ApplicationModule, ApplicationRef, Attribute, COMPILER_OPTIONS, CUSTOM_ELEMENTS_SCHEMA, ChangeDetectionStrategy, ChangeDetectorRef, Compiler, CompilerFactory, Component, ComponentFactory, ComponentFactoryResolver, ComponentRef, ContentChild, ContentChildren, DEFAULT_CURRENCY_CODE, DebugElement, DebugEventListener, DebugNode, DefaultIterableDiffer, Directive, ElementRef, EmbeddedViewRef, ErrorHandler, EventEmitter, Host, HostBinding, HostListener, INJECTOR, Inject, InjectFlags, Injectable, InjectionToken, Injector, Input, IterableDiffers, KeyValueDiffers, LOCALE_ID$1 as LOCALE_ID, MissingTranslationStrategy, ModuleWithComponentFactories, NO_ERRORS_SCHEMA, NgModule, NgModuleFactory, NgModuleFactoryLoader, NgModuleRef, NgProbeToken, NgZone, Optional, Output, PACKAGE_ROOT_URL, PLATFORM_ID, PLATFORM_INITIALIZER, Pipe, PlatformRef, Query, QueryList, ReflectiveInjector, ReflectiveKey, Renderer2, RendererFactory2, RendererStyleFlags2, ResolvedReflectiveFactory, Sanitizer, SecurityContext, Self, SimpleChange, SkipSelf, SystemJsNgModuleLoader, SystemJsNgModuleLoaderConfig, TRANSLATIONS, TRANSLATIONS_FORMAT, TemplateRef, Testability, TestabilityRegistry, Type, VERSION, Version, ViewChild, ViewChildren, ViewContainerRef, ViewEncapsulation$1 as ViewEncapsulation, ViewRef$1 as ViewRef, WrappedValue, asNativeElements, assertPlatform, createPlatform, createPlatformFactory, defineInjectable, destroyPlatform, enableProdMode, forwardRef, getDebugNode$1 as getDebugNode, getModuleFactory, getPlatform, inject, isDevMode, platformCore, resolveForwardRef, setTestabilityGetter, ɵ0, ɵ1, ALLOW_MULTIPLE_PLATFORMS as ɵALLOW_MULTIPLE_PLATFORMS, APP_ID_RANDOM_PROVIDER as ɵAPP_ID_RANDOM_PROVIDER, ChangeDetectorStatus as ɵChangeDetectorStatus, CodegenComponentFactoryResolver as ɵCodegenComponentFactoryResolver, Compiler_compileModuleAndAllComponentsAsync__POST_R3__ as ɵCompiler_compileModuleAndAllComponentsAsync__POST_R3__, Compiler_compileModuleAndAllComponentsSync__POST_R3__ as ɵCompiler_compileModuleAndAllComponentsSync__POST_R3__, Compiler_compileModuleAsync__POST_R3__ as ɵCompiler_compileModuleAsync__POST_R3__, Compiler_compileModuleSync__POST_R3__ as ɵCompiler_compileModuleSync__POST_R3__, ComponentFactory as ɵComponentFactory, Console as ɵConsole, DEFAULT_LOCALE_ID as ɵDEFAULT_LOCALE_ID, EMPTY_ARRAY$4 as ɵEMPTY_ARRAY, EMPTY_MAP as ɵEMPTY_MAP, INJECTOR_IMPL__POST_R3__ as ɵINJECTOR_IMPL__POST_R3__, INJECTOR_SCOPE as ɵINJECTOR_SCOPE, LifecycleHooksFeature as ɵLifecycleHooksFeature, LocaleDataIndex as ɵLocaleDataIndex, NG_COMP_DEF as ɵNG_COMP_DEF, NG_DIR_DEF as ɵNG_DIR_DEF, NG_ELEMENT_ID as ɵNG_ELEMENT_ID, NG_INJ_DEF as ɵNG_INJ_DEF, NG_MOD_DEF as ɵNG_MOD_DEF, NG_PIPE_DEF as ɵNG_PIPE_DEF, NG_PROV_DEF as ɵNG_PROV_DEF, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR as ɵNOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR, NO_CHANGE as ɵNO_CHANGE, NgModuleFactory$1 as ɵNgModuleFactory, NoopNgZone as ɵNoopNgZone, ReflectionCapabilities as ɵReflectionCapabilities, ComponentFactory$1 as ɵRender3ComponentFactory, ComponentRef$1 as ɵRender3ComponentRef, NgModuleRef$1 as ɵRender3NgModuleRef, SWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__ as ɵSWITCH_CHANGE_DETECTOR_REF_FACTORY__POST_R3__, SWITCH_COMPILE_COMPONENT__POST_R3__ as ɵSWITCH_COMPILE_COMPONENT__POST_R3__, SWITCH_COMPILE_DIRECTIVE__POST_R3__ as ɵSWITCH_COMPILE_DIRECTIVE__POST_R3__, SWITCH_COMPILE_INJECTABLE__POST_R3__ as ɵSWITCH_COMPILE_INJECTABLE__POST_R3__, SWITCH_COMPILE_NGMODULE__POST_R3__ as ɵSWITCH_COMPILE_NGMODULE__POST_R3__, SWITCH_COMPILE_PIPE__POST_R3__ as ɵSWITCH_COMPILE_PIPE__POST_R3__, SWITCH_ELEMENT_REF_FACTORY__POST_R3__ as ɵSWITCH_ELEMENT_REF_FACTORY__POST_R3__, SWITCH_IVY_ENABLED__POST_R3__ as ɵSWITCH_IVY_ENABLED__POST_R3__, SWITCH_RENDERER2_FACTORY__POST_R3__ as ɵSWITCH_RENDERER2_FACTORY__POST_R3__, SWITCH_TEMPLATE_REF_FACTORY__POST_R3__ as ɵSWITCH_TEMPLATE_REF_FACTORY__POST_R3__, SWITCH_VIEW_CONTAINER_REF_FACTORY__POST_R3__ as ɵSWITCH_VIEW_CONTAINER_REF_FACTORY__POST_R3__, _sanitizeHtml as ɵ_sanitizeHtml, _sanitizeUrl as ɵ_sanitizeUrl, allowSanitizationBypassAndThrow as ɵallowSanitizationBypassAndThrow, anchorDef as ɵand, isForwardRef as ɵangular_packages_core_core_a, injectInjectorOnly as ɵangular_packages_core_core_b, instructionState as ɵangular_packages_core_core_ba, getLView as ɵangular_packages_core_core_bb, getPreviousOrParentTNode as ɵangular_packages_core_core_bc, getBindingRoot as ɵangular_packages_core_core_bd, nextContextImpl as ɵangular_packages_core_core_be, pureFunction1Internal as ɵangular_packages_core_core_bg, pureFunction2Internal as ɵangular_packages_core_core_bh, pureFunction3Internal as ɵangular_packages_core_core_bi, pureFunction4Internal as ɵangular_packages_core_core_bj, pureFunctionVInternal as ɵangular_packages_core_core_bk, getUrlSanitizer as ɵangular_packages_core_core_bl, makeParamDecorator as ɵangular_packages_core_core_bm, makePropDecorator as ɵangular_packages_core_core_bn, getClosureSafeProperty as ɵangular_packages_core_core_bo, getRootContext as ɵangular_packages_core_core_bq, i18nPostprocess as ɵangular_packages_core_core_br, NullInjector as ɵangular_packages_core_core_c, ReflectiveInjector_ as ɵangular_packages_core_core_d, ReflectiveDependency as ɵangular_packages_core_core_e, resolveReflectiveProviders as ɵangular_packages_core_core_f, _appIdRandomProviderFactory as ɵangular_packages_core_core_g, createElementRef as ɵangular_packages_core_core_h, createTemplateRef as ɵangular_packages_core_core_i, getModuleFactory__PRE_R3__ as ɵangular_packages_core_core_j, DebugNode__PRE_R3__ as ɵangular_packages_core_core_k, DebugElement__PRE_R3__ as ɵangular_packages_core_core_l, getDebugNodeR2__PRE_R3__ as ɵangular_packages_core_core_m, DefaultIterableDifferFactory as ɵangular_packages_core_core_n, DefaultKeyValueDifferFactory as ɵangular_packages_core_core_o, _iterableDiffersFactory as ɵangular_packages_core_core_p, _keyValueDiffersFactory as ɵangular_packages_core_core_q, _localeFactory as ɵangular_packages_core_core_r, APPLICATION_MODULE_PROVIDERS as ɵangular_packages_core_core_s, zoneSchedulerFactory as ɵangular_packages_core_core_t, USD_CURRENCY_CODE as ɵangular_packages_core_core_u, _def as ɵangular_packages_core_core_v, DebugContext as ɵangular_packages_core_core_w, NgOnChangesFeatureImpl as ɵangular_packages_core_core_x, SCHEDULER as ɵangular_packages_core_core_y, injectAttributeImpl as ɵangular_packages_core_core_z, bypassSanitizationTrustHtml as ɵbypassSanitizationTrustHtml, bypassSanitizationTrustResourceUrl as ɵbypassSanitizationTrustResourceUrl, bypassSanitizationTrustScript as ɵbypassSanitizationTrustScript, bypassSanitizationTrustStyle as ɵbypassSanitizationTrustStyle, bypassSanitizationTrustUrl as ɵbypassSanitizationTrustUrl, createComponentFactory as ɵccf, clearOverrides as ɵclearOverrides, clearResolutionOfComponentResourcesQueue as ɵclearResolutionOfComponentResourcesQueue, createNgModuleFactory as ɵcmf, compileComponent as ɵcompileComponent, compileDirective as ɵcompileDirective, compileNgModule as ɵcompileNgModule, compileNgModuleDefs as ɵcompileNgModuleDefs, compileNgModuleFactory__POST_R3__ as ɵcompileNgModuleFactory__POST_R3__, compilePipe as ɵcompilePipe, createInjector as ɵcreateInjector, createRendererType2 as ɵcrt, defaultIterableDiffers as ɵdefaultIterableDiffers, defaultKeyValueDiffers as ɵdefaultKeyValueDiffers, detectChanges as ɵdetectChanges, devModeEqual as ɵdevModeEqual, directiveDef as ɵdid, elementDef as ɵeld, findLocaleData as ɵfindLocaleData, flushModuleScopingQueueAsMuchAsPossible as ɵflushModuleScopingQueueAsMuchAsPossible, getComponentViewDefinitionFactory as ɵgetComponentViewDefinitionFactory, getDebugNodeR2 as ɵgetDebugNodeR2, getDebugNode__POST_R3__ as ɵgetDebugNode__POST_R3__, getDirectives as ɵgetDirectives, getHostElement as ɵgetHostElement, getInjectableDef as ɵgetInjectableDef, getLContext as ɵgetLContext, getLocaleCurrencyCode as ɵgetLocaleCurrencyCode, getLocalePluralCase as ɵgetLocalePluralCase, getModuleFactory__POST_R3__ as ɵgetModuleFactory__POST_R3__, getSanitizationBypassType as ɵgetSanitizationBypassType, _global as ɵglobal, initServicesIfNeeded as ɵinitServicesIfNeeded, inlineInterpolate as ɵinlineInterpolate, interpolate as ɵinterpolate, isBoundToModule__POST_R3__ as ɵisBoundToModule__POST_R3__, isDefaultChangeDetectionStrategy as ɵisDefaultChangeDetectionStrategy, isListLikeIterable as ɵisListLikeIterable, isObservable as ɵisObservable, isPromise as ɵisPromise, ivyEnabled as ɵivyEnabled, makeDecorator as ɵmakeDecorator, markDirty as ɵmarkDirty, moduleDef as ɵmod, moduleProvideDef as ɵmpd, ngContentDef as ɵncd, noSideEffects as ɵnoSideEffects, nodeValue as ɵnov, overrideComponentView as ɵoverrideComponentView, overrideProvider as ɵoverrideProvider, pureArrayDef as ɵpad, patchComponentDefWithScope as ɵpatchComponentDefWithScope, pipeDef as ɵpid, pureObjectDef as ɵpod, purePipeDef as ɵppd, providerDef as ɵprd, publishDefaultGlobalUtils as ɵpublishDefaultGlobalUtils, publishGlobalUtil as ɵpublishGlobalUtil, queryDef as ɵqud, registerLocaleData as ɵregisterLocaleData, registerModuleFactory as ɵregisterModuleFactory, registerNgModuleType as ɵregisterNgModuleType, renderComponent$1 as ɵrenderComponent, resetCompiledComponents as ɵresetCompiledComponents, resetJitOptions as ɵresetJitOptions, resolveComponentResources as ɵresolveComponentResources, setClassMetadata as ɵsetClassMetadata, setCurrentInjector as ɵsetCurrentInjector, setDocument as ɵsetDocument, setLocaleId as ɵsetLocaleId, store as ɵstore, stringify as ɵstringify, textDef as ɵted, transitiveScopesFor as ɵtransitiveScopesFor, unregisterAllLocaleData as ɵunregisterLocaleData, unwrapValue as ɵunv, unwrapSafeValue as ɵunwrapSafeValue, viewDef as ɵvid, whenRendered as ɵwhenRendered, ɵɵCopyDefinitionFeature, ɵɵInheritDefinitionFeature, ɵɵNgOnChangesFeature, ɵɵProvidersFeature, ɵɵadvance, ɵɵattribute, ɵɵattributeInterpolate1, ɵɵattributeInterpolate2, ɵɵattributeInterpolate3, ɵɵattributeInterpolate4, ɵɵattributeInterpolate5, ɵɵattributeInterpolate6, ɵɵattributeInterpolate7, ɵɵattributeInterpolate8, ɵɵattributeInterpolateV, ɵɵclassMap, ɵɵclassMapInterpolate1, ɵɵclassMapInterpolate2, ɵɵclassMapInterpolate3, ɵɵclassMapInterpolate4, ɵɵclassMapInterpolate5, ɵɵclassMapInterpolate6, ɵɵclassMapInterpolate7, ɵɵclassMapInterpolate8, ɵɵclassMapInterpolateV, ɵɵclassProp, ɵɵcontentQuery, ɵɵdefineComponent, ɵɵdefineDirective, ɵɵdefineInjectable, ɵɵdefineInjector, ɵɵdefineNgModule, ɵɵdefinePipe, ɵɵdirectiveInject, ɵɵdisableBindings, ɵɵelement, ɵɵelementContainer, ɵɵelementContainerEnd, ɵɵelementContainerStart, ɵɵelementEnd, ɵɵelementStart, ɵɵenableBindings, ɵɵgetCurrentView, ɵɵgetFactoryOf, ɵɵgetInheritedFactory, ɵɵhostProperty, ɵɵi18n, ɵɵi18nApply, ɵɵi18nAttributes, ɵɵi18nEnd, ɵɵi18nExp, ɵɵi18nPostprocess, ɵɵi18nStart, ɵɵinject, ɵɵinjectAttribute, ɵɵinjectPipeChangeDetectorRef, ɵɵinvalidFactory, ɵɵinvalidFactoryDep, ɵɵlistener, ɵɵloadQuery, ɵɵnamespaceHTML, ɵɵnamespaceMathML, ɵɵnamespaceSVG, ɵɵnextContext, ɵɵpipe, ɵɵpipeBind1, ɵɵpipeBind2, ɵɵpipeBind3, ɵɵpipeBind4, ɵɵpipeBindV, ɵɵprojection, ɵɵprojectionDef, ɵɵproperty, ɵɵpropertyInterpolate, ɵɵpropertyInterpolate1, ɵɵpropertyInterpolate2, ɵɵpropertyInterpolate3, ɵɵpropertyInterpolate4, ɵɵpropertyInterpolate5, ɵɵpropertyInterpolate6, ɵɵpropertyInterpolate7, ɵɵpropertyInterpolate8, ɵɵpropertyInterpolateV, ɵɵpureFunction0, ɵɵpureFunction1, ɵɵpureFunction2, ɵɵpureFunction3, ɵɵpureFunction4, ɵɵpureFunction5, ɵɵpureFunction6, ɵɵpureFunction7, ɵɵpureFunction8, ɵɵpureFunctionV, ɵɵqueryRefresh, ɵɵreference, ɵɵresolveBody, ɵɵresolveDocument, ɵɵresolveWindow, ɵɵrestoreView, ɵɵsanitizeHtml, ɵɵsanitizeResourceUrl, ɵɵsanitizeScript, ɵɵsanitizeStyle, ɵɵsanitizeUrl, ɵɵsanitizeUrlOrResourceUrl, ɵɵselect, ɵɵsetComponentScope, ɵɵsetNgModuleScope, ɵɵstaticContentQuery, ɵɵstaticViewQuery, ɵɵstyleMap, ɵɵstyleMapInterpolate1, ɵɵstyleMapInterpolate2, ɵɵstyleMapInterpolate3, ɵɵstyleMapInterpolate4, ɵɵstyleMapInterpolate5, ɵɵstyleMapInterpolate6, ɵɵstyleMapInterpolate7, ɵɵstyleMapInterpolate8, ɵɵstyleMapInterpolateV, ɵɵstyleProp, ɵɵstylePropInterpolate1, ɵɵstylePropInterpolate2, ɵɵstylePropInterpolate3, ɵɵstylePropInterpolate4, ɵɵstylePropInterpolate5, ɵɵstylePropInterpolate6, ɵɵstylePropInterpolate7, ɵɵstylePropInterpolate8, ɵɵstylePropInterpolateV, ɵɵsyntheticHostListener, ɵɵsyntheticHostProperty, ɵɵtemplate, ɵɵtemplateRefExtractor, ɵɵtext, ɵɵtextInterpolate, ɵɵtextInterpolate1, ɵɵtextInterpolate2, ɵɵtextInterpolate3, ɵɵtextInterpolate4, ɵɵtextInterpolate5, ɵɵtextInterpolate6, ɵɵtextInterpolate7, ɵɵtextInterpolate8, ɵɵtextInterpolateV, ɵɵviewQuery };
31743//# sourceMappingURL=core.js.map